1 import { first } from 'rxjs/operators'
2 import { Injectable } from '@angular/core'
3 import { UserLocalStorageKeys } from '@root-helpers/users'
4 import { ServerConfig, ServerConfigTheme } from '@shared/models'
5 import { environment } from '../../../environments/environment'
6 import { AuthService } from '../auth'
7 import { PluginService } from '../plugins/plugin.service'
8 import { ServerService } from '../server'
9 import { UserService } from '../users/user.service'
10 import { LocalStorageService } from '../wrappers/storage.service'
13 export class ThemeService {
15 private oldThemeName: string
16 private themes: ServerConfigTheme[] = []
18 private themeFromLocalStorage: ServerConfigTheme
19 private themeDOMLinksFromLocalStorage: HTMLLinkElement[] = []
21 private serverConfig: ServerConfig
24 private auth: AuthService,
25 private userService: UserService,
26 private pluginService: PluginService,
27 private server: ServerService,
28 private localStorageService: LocalStorageService
32 // Try to load from local storage first, so we don't have to wait network requests
33 this.loadAndSetFromLocalStorage()
35 this.serverConfig = this.server.getTmpConfig()
36 this.server.getConfig()
37 .subscribe(config => {
38 this.serverConfig = config
40 const themes = this.serverConfig.theme.registered
42 this.removeThemeFromLocalStorageIfNeeded(themes)
43 this.injectThemes(themes)
45 this.listenUserTheme()
49 private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) {
52 console.log('Injecting %d themes.', this.themes.length)
54 const head = this.getHeadElement()
56 for (const theme of this.themes) {
57 // Already added this theme?
58 if (fromLocalStorage === false && this.themeFromLocalStorage && this.themeFromLocalStorage.name === theme.name) continue
60 for (const css of theme.css) {
61 const link = document.createElement('link')
63 const href = environment.apiUrl + `/themes/${theme.name}/${theme.version}/css/${css}`
64 link.setAttribute('href', href)
65 link.setAttribute('rel', 'alternate stylesheet')
66 link.setAttribute('type', 'text/css')
67 link.setAttribute('title', theme.name)
68 link.setAttribute('disabled', '')
70 if (fromLocalStorage === true) this.themeDOMLinksFromLocalStorage.push(link)
72 head.appendChild(link)
77 private getCurrentTheme () {
78 if (this.themeFromLocalStorage) return this.themeFromLocalStorage.name
80 const theme = this.auth.isLoggedIn()
81 ? this.auth.getUser().theme
82 : this.userService.getAnonymousUser().theme
84 if (theme !== 'instance-default') return theme
86 const instanceTheme = this.serverConfig.theme.default
87 if (instanceTheme !== 'default') return instanceTheme
89 // Default to dark theme if available and wanted by the user
91 this.themes.find(t => t.name === 'dark') &&
92 window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
100 private loadTheme (name: string) {
101 const links = document.getElementsByTagName('link')
102 for (let i = 0; i < links.length; i++) {
103 const link = links[ i ]
104 if (link.getAttribute('rel').indexOf('style') !== -1 && link.getAttribute('title')) {
105 link.disabled = link.getAttribute('title') !== name
110 private updateCurrentTheme () {
111 if (this.oldThemeName) this.removeThemePlugins(this.oldThemeName)
113 const currentTheme = this.getCurrentTheme()
115 console.log('Enabling %s theme.', currentTheme)
117 this.loadTheme(currentTheme)
119 const theme = this.getTheme(currentTheme)
121 console.log('Adding scripts of theme %s.', currentTheme)
122 this.pluginService.addPlugin(theme, true)
124 this.pluginService.reloadLoadedScopes()
126 this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false)
128 this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
131 this.oldThemeName = currentTheme
134 private listenUserTheme () {
135 // We don't need them anymore
136 this.themeFromLocalStorage = undefined
137 this.themeDOMLinksFromLocalStorage = []
139 if (!this.auth.isLoggedIn()) {
140 this.updateCurrentTheme()
142 this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
143 () => this.updateCurrentTheme()
147 this.auth.userInformationLoaded
149 .subscribe(() => this.updateCurrentTheme())
152 private loadAndSetFromLocalStorage () {
153 const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
154 if (!lastActiveThemeString) return
157 const lastActiveTheme = JSON.parse(lastActiveThemeString)
158 this.themeFromLocalStorage = lastActiveTheme
160 this.injectThemes([ lastActiveTheme ], true)
161 this.updateCurrentTheme()
163 console.error('Cannot parse last active theme.', err)
168 private removeThemePlugins (themeName: string) {
169 const oldTheme = this.getTheme(themeName)
171 console.log('Removing scripts of old theme %s.', themeName)
172 this.pluginService.removePlugin(oldTheme)
176 private removeThemeFromLocalStorageIfNeeded (themes: ServerConfigTheme[]) {
177 if (!this.themeFromLocalStorage) return
179 const loadedTheme = themes.find(t => t.name === this.themeFromLocalStorage.name)
180 if (!loadedTheme || loadedTheme.version !== this.themeFromLocalStorage.version) {
181 // Need to remove this theme: we loaded an old version or a theme that does not exist anymore
182 this.removeThemePlugins(this.themeFromLocalStorage.name)
183 this.oldThemeName = undefined
185 const head = this.getHeadElement()
186 for (const htmlLinkElement of this.themeDOMLinksFromLocalStorage) {
187 head.removeChild(htmlLinkElement)
190 this.themeFromLocalStorage = undefined
191 this.themeDOMLinksFromLocalStorage = []
195 private getHeadElement () {
196 return document.getElementsByTagName('head')[0]
199 private getTheme (name: string) {
200 return this.themes.find(t => t.name === name)