+ private updateCurrentTheme () {
+ if (this.oldThemeName) this.removeThemePlugins(this.oldThemeName)
+
+ const currentTheme = this.getCurrentTheme()
+
+ console.log('Enabling %s theme.', currentTheme)
+
+ this.loadTheme(currentTheme)
+
+ const theme = this.getTheme(currentTheme)
+ if (theme) {
+ console.log('Adding scripts of theme %s.', currentTheme)
+ this.pluginService.addPlugin(theme, true)
+
+ this.pluginService.reloadLoadedScopes()
+
+ this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false)
+ } else {
+ this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
+ }
+
+ this.oldThemeName = currentTheme
+ }
+
+ private listenUserTheme () {
+ // We don't need them anymore
+ this.themeFromLocalStorage = undefined
+ this.themeDOMLinksFromLocalStorage = []
+
+ if (!this.auth.isLoggedIn()) {
+ this.updateCurrentTheme()
+
+ this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
+ () => this.updateCurrentTheme()
+ )
+ }
+
+ this.auth.userInformationLoaded
+ .pipe(first())
+ .subscribe(() => this.updateCurrentTheme())
+ }
+
+ private loadAndSetFromLocalStorage () {
+ const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
+ if (!lastActiveThemeString) return
+
+ try {
+ const lastActiveTheme = JSON.parse(lastActiveThemeString)
+ this.themeFromLocalStorage = lastActiveTheme
+
+ this.injectThemes([ lastActiveTheme ], true)
+ this.updateCurrentTheme()
+ } catch (err) {
+ console.error('Cannot parse last active theme.', err)
+ return
+ }
+ }
+
+ private removeThemePlugins (themeName: string) {
+ const oldTheme = this.getTheme(themeName)
+ if (oldTheme) {
+ console.log('Removing scripts of old theme %s.', themeName)
+ this.pluginService.removePlugin(oldTheme)
+ }
+ }
+
+ private removeThemeFromLocalStorageIfNeeded (themes: ServerConfigTheme[]) {
+ if (!this.themeFromLocalStorage) return
+
+ const loadedTheme = themes.find(t => t.name === this.themeFromLocalStorage.name)
+ if (!loadedTheme || loadedTheme.version !== this.themeFromLocalStorage.version) {
+ // Need to remove this theme: we loaded an old version or a theme that does not exist anymore
+ this.removeThemePlugins(this.themeFromLocalStorage.name)
+ this.oldThemeName = undefined
+
+ const head = this.getHeadElement()
+ for (const htmlLinkElement of this.themeDOMLinksFromLocalStorage) {
+ head.removeChild(htmlLinkElement)
+ }
+
+ this.themeFromLocalStorage = undefined
+ this.themeDOMLinksFromLocalStorage = []
+ }
+ }
+
+ private getHeadElement () {
+ return document.getElementsByTagName('head')[0]
+ }
+
+ private getTheme (name: string) {
+ return this.themes.find(t => t.name === name)