1 import { Injectable } from '@angular/core'
2 import { UserLocalStorageKeys } from '@root-helpers/users'
3 import { HTMLServerConfig, ServerConfigTheme } from '@shared/models'
4 import { environment } from '../../../environments/environment'
5 import { AuthService } from '../auth'
6 import { PluginService } from '../plugins/plugin.service'
7 import { ServerService } from '../server'
8 import { UserService } from '../users/user.service'
9 import { LocalStorageService } from '../wrappers/storage.service'
12 export class ThemeService {
14 private oldThemeName: string
15 private themes: ServerConfigTheme[] = []
17 private themeFromLocalStorage: ServerConfigTheme
18 private themeDOMLinksFromLocalStorage: HTMLLinkElement[] = []
20 private serverConfig: HTMLServerConfig
23 private auth: AuthService,
24 private userService: UserService,
25 private pluginService: PluginService,
26 private server: ServerService,
27 private localStorageService: LocalStorageService
31 // Try to load from local storage first, so we don't have to wait network requests
32 this.loadAndSetFromLocalStorage()
34 this.serverConfig = this.server.getHTMLConfig()
35 const themes = this.serverConfig.theme.registered
37 this.removeThemeFromLocalStorageIfNeeded(themes)
38 this.injectThemes(themes)
40 this.listenUserTheme()
43 private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) {
46 console.log('Injecting %d themes.', this.themes.length)
48 const head = this.getHeadElement()
50 for (const theme of this.themes) {
51 // Already added this theme?
52 if (fromLocalStorage === false && this.themeFromLocalStorage && this.themeFromLocalStorage.name === theme.name) continue
54 for (const css of theme.css) {
55 const link = document.createElement('link')
57 const href = environment.apiUrl + `/themes/${theme.name}/${theme.version}/css/${css}`
58 link.setAttribute('href', href)
59 link.setAttribute('rel', 'alternate stylesheet')
60 link.setAttribute('type', 'text/css')
61 link.setAttribute('title', theme.name)
62 link.setAttribute('disabled', '')
64 if (fromLocalStorage === true) this.themeDOMLinksFromLocalStorage.push(link)
66 head.appendChild(link)
71 private getCurrentTheme () {
72 if (this.themeFromLocalStorage) return this.themeFromLocalStorage.name
74 const theme = this.auth.isLoggedIn()
75 ? this.auth.getUser().theme
76 : this.userService.getAnonymousUser().theme
78 if (theme !== 'instance-default') return theme
80 const instanceTheme = this.serverConfig.theme.default
81 if (instanceTheme !== 'default') return instanceTheme
83 // Default to dark theme if available and wanted by the user
85 this.themes.find(t => t.name === 'dark') &&
86 window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
94 private loadTheme (name: string) {
95 const links = document.getElementsByTagName('link')
96 for (let i = 0; i < links.length; i++) {
98 if (link.getAttribute('rel').includes('style') && link.getAttribute('title')) {
99 link.disabled = link.getAttribute('title') !== name
104 private updateCurrentTheme () {
105 if (this.oldThemeName) this.removeThemePlugins(this.oldThemeName)
107 const currentTheme = this.getCurrentTheme()
109 console.log('Enabling %s theme.', currentTheme)
111 this.loadTheme(currentTheme)
113 const theme = this.getTheme(currentTheme)
115 console.log('Adding scripts of theme %s.', currentTheme)
117 this.pluginService.addPlugin(theme, true)
119 this.pluginService.reloadLoadedScopes()
121 this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false)
123 this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
126 this.oldThemeName = currentTheme
129 private listenUserTheme () {
130 // We don't need them anymore
131 this.themeFromLocalStorage = undefined
132 this.themeDOMLinksFromLocalStorage = []
134 if (!this.auth.isLoggedIn()) {
135 this.updateCurrentTheme()
137 this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
138 () => this.updateCurrentTheme()
142 this.auth.userInformationLoaded
143 .subscribe(() => this.updateCurrentTheme())
146 private loadAndSetFromLocalStorage () {
147 const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
148 if (!lastActiveThemeString) return
151 const lastActiveTheme = JSON.parse(lastActiveThemeString)
152 this.themeFromLocalStorage = lastActiveTheme
154 this.injectThemes([ lastActiveTheme ], true)
155 this.updateCurrentTheme()
157 console.error('Cannot parse last active theme.', err)
162 private removeThemePlugins (themeName: string) {
163 const oldTheme = this.getTheme(themeName)
165 console.log('Removing scripts of old theme %s.', themeName)
166 this.pluginService.removePlugin(oldTheme)
170 private removeThemeFromLocalStorageIfNeeded (themes: ServerConfigTheme[]) {
171 if (!this.themeFromLocalStorage) return
173 const loadedTheme = themes.find(t => t.name === this.themeFromLocalStorage.name)
174 if (!loadedTheme || loadedTheme.version !== this.themeFromLocalStorage.version) {
175 // Need to remove this theme: we loaded an old version or a theme that does not exist anymore
176 this.removeThemePlugins(this.themeFromLocalStorage.name)
177 this.oldThemeName = undefined
179 const head = this.getHeadElement()
180 for (const htmlLinkElement of this.themeDOMLinksFromLocalStorage) {
181 head.removeChild(htmlLinkElement)
184 this.themeFromLocalStorage = undefined
185 this.themeDOMLinksFromLocalStorage = []
189 private getHeadElement () {
190 return document.getElementsByTagName('head')[0]
193 private getTheme (name: string) {
194 return this.themes.find(t => t.name === name)