FreeTube/src/renderer/components/top-nav/top-nav.js

351 lines
9.1 KiB
JavaScript
Raw Normal View History

2020-02-16 19:30:00 +01:00
import Vue from 'vue'
import { mapActions } from 'vuex'
2020-02-16 19:30:00 +01:00
import FtInput from '../ft-input/ft-input.vue'
import FtSearchFilters from '../ft-search-filters/ft-search-filters.vue'
import FtProfileSelector from '../ft-profile-selector/ft-profile-selector.vue'
import debounce from 'lodash.debounce'
import ytSuggest from 'youtube-suggest'
2020-02-16 19:30:00 +01:00
Store Revamp / Full database synchronization across windows (#1833) * History: Refactor history module * Profiles: Refactor profiles module * IPC: Move channel ids to their own file and make them constants * IPC: Replace single sync channel for one channel per sync type * Everywhere: Replace default profile id magic strings with constant ref * Profiles: Refactor `activeProfile` property from store This commit makes it so that `activeProfile`'s getter returns the entire profile, while the related update function only needs the profile id (instead of the previously used array index) to change the currently active profile. This change was made due to inconsistency regarding the active profile when creating new profiles. If a new profile coincidentally landed in the current active profile's array index after sorting, the app would mistakenly change to it without any action from the user apart from the profile's creation. Turning the profile id into the selector instead solves this issue. * Revert "Store: Implement history synchronization between windows" This reverts commit 99b61e617873412eb393d8f4dfccd8f8c172021f. This is necessary for an upcoming improved implementation of the history synchronization. * History: Remove unused mutation * Everywhere: Create abstract database handlers The project now utilizes abstract handlers to fetch, modify or otherwise manipulate data from the database. This facilitates 3 aspects of the app, in addition of making them future proof: - Switching database libraries is now trivial Since most of the app utilizes the abstract handlers, it's incredibly easily to change to a different DB library. Hypothetically, all that would need to be done is to simply replace the the file containing the base handlers, while the rest of the app would go unchanged. - Syncing logic between Electron and web is now properly separated There are now two distinct DB handling APIs: the Electron one and the web one. The app doesn't need to manually choose the API, because it's detected which platform is being utilized on import. - All Electron windows now share the same database instance This provides a single source of truth, improving consistency regarding data manipulation and windows synchronization. As a sidenote, syncing implementation has been left as is (web unimplemented; Electron only syncs settings, remaining datastore syncing will be implemented in the upcoming commits). * Electron/History: Implement history synchronization * Profiles: Implement suplementary profile creation logic * ft-profile-edit: Small fix on profile name missing display * Electron/Profiles: Implement profile synchronization * Electron/Playlists: Implement playlist synchronization
2021-12-15 19:42:24 +01:00
import { IpcChannels } from '../../../constants'
2020-02-16 19:30:00 +01:00
export default Vue.extend({
name: 'TopNav',
components: {
FtInput,
FtSearchFilters,
FtProfileSelector
2020-02-16 19:30:00 +01:00
},
data: () => {
return {
component: this,
showSearchContainer: true,
showFilters: false,
searchFilterValueChanged: false,
historyIndex: 1,
isForwardOrBack: false,
searchSuggestionsDataList: []
2020-02-16 19:30:00 +01:00
}
},
computed: {
hideSearchBar: function () {
return this.$store.getters.getHideSearchBar
},
2020-06-19 21:46:01 +02:00
enableSearchSuggestions: function () {
return this.$store.getters.getEnableSearchSuggestions
},
searchInput: function () {
return this.$refs.searchInput.$refs.input
},
2020-02-16 19:30:00 +01:00
searchSettings: function () {
return this.$store.getters.getSearchSettings
},
barColor: function () {
return this.$store.getters.getBarColor
},
currentInvidiousInstance: function () {
return this.$store.getters.getCurrentInvidiousInstance
},
backendFallback: function () {
return this.$store.getters.getBackendFallback
},
backendPreference: function () {
return this.$store.getters.getBackendPreference
},
expandSideBar: function () {
return this.$store.getters.getExpandSideBar
},
forwardText: function () {
return this.$t('Forward')
},
backwardText: function () {
return this.$t('Back')
},
newWindowText: function () {
return this.$t('Open New Window')
}
2020-02-16 19:30:00 +01:00
},
mounted: function () {
if (window.innerWidth <= 680) {
this.showSearchContainer = false
2020-04-14 04:59:25 +02:00
}
// Store is not up-to-date when the component mounts, so we use timeout.
setTimeout(() => {
if (this.expandSideBar) {
this.toggleSideNav()
}
}, 0)
window.addEventListener('resize', () => {
this.showSearchContainer = window.innerWidth > 680
})
this.debounceSearchResults = debounce(this.getSearchSuggestions, 200)
},
2020-02-16 19:30:00 +01:00
methods: {
goToSearch: async function (query, { event }) {
const doCreateNewWindow = event && event.shiftKey
if (window.innerWidth <= 680) {
this.$refs.searchContainer.blur()
this.showSearchContainer = false
2020-08-25 00:04:59 +02:00
} else {
this.searchInput.blur()
}
this.getYoutubeUrlInfo(query).then((result) => {
switch (result.urlType) {
case 'video': {
const { videoId, timestamp, playlistId } = result
const query = {}
if (timestamp) {
query.timestamp = timestamp
}
if (playlistId && playlistId.length > 0) {
query.playlistId = playlistId
}
this.openInternalPath({
path: `/watch/${videoId}`,
query,
doCreateNewWindow
})
break
}
case 'playlist': {
const { playlistId, query } = result
this.$router.push({
path: `/playlist/${playlistId}`,
query
})
break
}
2020-04-14 04:59:25 +02:00
case 'search': {
const { searchQuery, query } = result
this.openInternalPath({
path: `/search/${encodeURIComponent(searchQuery)}`,
query,
doCreateNewWindow,
searchQueryText: searchQuery
})
break
}
case 'hashtag': {
// TODO: Implement a hashtag related view
let message = 'Hashtags have not yet been implemented, try again later'
if (this.$t(message) && this.$t(message) !== '') {
message = this.$t(message)
}
this.showToast({
message: message
})
break
}
case 'channel': {
const { channelId, idType, subPath } = result
this.openInternalPath({
path: `/channel/${channelId}/${subPath}`,
query: { idType },
doCreateNewWindow
})
break
}
case 'invalid_url':
default: {
this.openInternalPath({
path: `/search/${encodeURIComponent(query)}`,
query: {
sortBy: this.searchSettings.sortBy,
time: this.searchSettings.time,
type: this.searchSettings.type,
duration: this.searchSettings.duration
},
doCreateNewWindow,
searchQueryText: query
})
}
}
})
// Close the filter panel
2020-04-14 04:59:25 +02:00
this.showFilters = false
2020-02-16 19:30:00 +01:00
},
focusSearch: function () {
if (!this.hideSearchBar) {
this.searchInput.focus()
}
},
getSearchSuggestionsDebounce: function (query) {
2020-06-19 21:46:01 +02:00
if (this.enableSearchSuggestions) {
this.debounceSearchResults(query)
}
},
getSearchSuggestions: function (query) {
switch (this.backendPreference) {
case 'local':
this.getSearchSuggestionsLocal(query)
break
case 'invidious':
this.getSearchSuggestionsInvidious(query)
break
}
},
getSearchSuggestionsLocal: function (query) {
if (query === '') {
this.searchSuggestionsDataList = []
return
}
ytSuggest(query).then((results) => {
this.searchSuggestionsDataList = results
})
},
getSearchSuggestionsInvidious: function (query) {
if (query === '') {
this.searchSuggestionsDataList = []
return
}
const searchPayload = {
resource: 'search/suggestions',
id: '',
params: {
q: query
}
}
this.invidiousAPICall(searchPayload).then((results) => {
this.searchSuggestionsDataList = results.suggestions
}).catch((err) => {
console.error(err)
if (this.backendFallback) {
console.error(
'Error gettings search suggestions. Falling back to Local API'
)
this.getSearchSuggestionsLocal(query)
}
})
},
toggleSearchContainer: function () {
this.showSearchContainer = !this.showSearchContainer
this.showFilters = false
},
handleSearchFilterValueChanged: function(filterValueChanged) {
this.searchFilterValueChanged = filterValueChanged
},
navigateHistory: function() {
if (!this.isForwardOrBack) {
this.historyIndex = window.history.length
this.$refs.historyArrowBack.classList.remove('fa-arrow-left')
this.$refs.historyArrowForward.classList.add('fa-arrow-right')
} else {
this.isForwardOrBack = false
}
},
2020-02-16 19:30:00 +01:00
historyBack: function () {
this.isForwardOrBack = true
2020-02-16 19:30:00 +01:00
window.history.back()
if (this.historyIndex > 1) {
this.historyIndex--
this.$refs.historyArrowForward.classList.remove('fa-arrow-right')
if (this.historyIndex === 1) {
this.$refs.historyArrowBack.classList.add('fa-arrow-left')
}
}
2020-02-16 19:30:00 +01:00
},
historyForward: function () {
this.isForwardOrBack = true
2020-02-16 19:30:00 +01:00
window.history.forward()
if (this.historyIndex < window.history.length) {
this.historyIndex++
this.$refs.historyArrowBack.classList.remove('fa-arrow-left')
if (this.historyIndex === window.history.length) {
this.$refs.historyArrowForward.classList.add('fa-arrow-right')
}
}
2020-02-16 19:30:00 +01:00
},
toggleSideNav: function () {
this.$store.commit('toggleSideNav')
2021-04-15 20:28:35 +02:00
},
openInternalPath: function({ path, doCreateNewWindow, query = {}, searchQueryText = null }) {
if (process.env.IS_ELECTRON && doCreateNewWindow) {
const { ipcRenderer } = require('electron')
// Combine current document path and new "hash" as new window startup URL
const newWindowStartupURL = [
window.location.href.split('#')[0],
`#${path}?${(new URLSearchParams(query)).toString()}`
].join('')
ipcRenderer.send(IpcChannels.CREATE_NEW_WINDOW, {
windowStartupUrl: newWindowStartupURL,
searchQueryText
})
} else {
// Web
this.$router.push({
path,
query
})
}
},
2021-04-15 20:28:35 +02:00
createNewWindow: function () {
if (process.env.IS_ELECTRON) {
const { ipcRenderer } = require('electron')
Store Revamp / Full database synchronization across windows (#1833) * History: Refactor history module * Profiles: Refactor profiles module * IPC: Move channel ids to their own file and make them constants * IPC: Replace single sync channel for one channel per sync type * Everywhere: Replace default profile id magic strings with constant ref * Profiles: Refactor `activeProfile` property from store This commit makes it so that `activeProfile`'s getter returns the entire profile, while the related update function only needs the profile id (instead of the previously used array index) to change the currently active profile. This change was made due to inconsistency regarding the active profile when creating new profiles. If a new profile coincidentally landed in the current active profile's array index after sorting, the app would mistakenly change to it without any action from the user apart from the profile's creation. Turning the profile id into the selector instead solves this issue. * Revert "Store: Implement history synchronization between windows" This reverts commit 99b61e617873412eb393d8f4dfccd8f8c172021f. This is necessary for an upcoming improved implementation of the history synchronization. * History: Remove unused mutation * Everywhere: Create abstract database handlers The project now utilizes abstract handlers to fetch, modify or otherwise manipulate data from the database. This facilitates 3 aspects of the app, in addition of making them future proof: - Switching database libraries is now trivial Since most of the app utilizes the abstract handlers, it's incredibly easily to change to a different DB library. Hypothetically, all that would need to be done is to simply replace the the file containing the base handlers, while the rest of the app would go unchanged. - Syncing logic between Electron and web is now properly separated There are now two distinct DB handling APIs: the Electron one and the web one. The app doesn't need to manually choose the API, because it's detected which platform is being utilized on import. - All Electron windows now share the same database instance This provides a single source of truth, improving consistency regarding data manipulation and windows synchronization. As a sidenote, syncing implementation has been left as is (web unimplemented; Electron only syncs settings, remaining datastore syncing will be implemented in the upcoming commits). * Electron/History: Implement history synchronization * Profiles: Implement suplementary profile creation logic * ft-profile-edit: Small fix on profile name missing display * Electron/Profiles: Implement profile synchronization * Electron/Playlists: Implement playlist synchronization
2021-12-15 19:42:24 +01:00
ipcRenderer.send(IpcChannels.CREATE_NEW_WINDOW)
} else {
// Web placeholder
}
},
navigate: function (route) {
this.$router.push('/' + route)
},
hideFilters: function () {
this.showFilters = false
},
updateSearchInputText: function(text) {
this.$refs.searchInput.updateInputData(text)
},
...mapActions([
'showToast',
'getYoutubeUrlInfo',
'invidiousAPICall'
])
}
2020-02-16 19:30:00 +01:00
})