1 import { Injectable } from '@angular/core'
2 import { logger } from '@root-helpers/logger'
3 import { capitalizeFirstLetter } from '@root-helpers/string'
4 import { UserLocalStorageKeys } from '@root-helpers/users'
5 import { HTMLServerConfig, ServerConfigTheme } from '@shared/models'
6 import { environment } from '../../../environments/environment'
7 import { AuthService } from '../auth'
8 import { PluginService } from '../plugins/plugin.service'
9 import { ServerService } from '../server'
10 import { UserService } from '../users/user.service'
11 import { LocalStorageService } from '../wrappers/storage.service'
14 export class ThemeService {
16 private oldThemeName: string
17 private themes: ServerConfigTheme[] = []
19 private themeFromLocalStorage: ServerConfigTheme
20 private themeDOMLinksFromLocalStorage: HTMLLinkElement[] = []
22 private serverConfig: HTMLServerConfig
25 private auth: AuthService,
26 private userService: UserService,
27 private pluginService: PluginService,
28 private server: ServerService,
29 private localStorageService: LocalStorageService
33 // Try to load from local storage first, so we don't have to wait network requests
34 this.loadAndSetFromLocalStorage()
36 this.serverConfig = this.server.getHTMLConfig()
37 const themes = this.serverConfig.theme.registered
39 this.removeThemeFromLocalStorageIfNeeded(themes)
40 this.injectThemes(themes)
42 this.listenUserTheme()
45 getDefaultThemeLabel () {
46 if (this.hasDarkTheme()) {
47 return $localize`Light/Orange or Dark`
50 return $localize`Light/Orange`
53 buildAvailableThemes () {
54 return this.serverConfig.theme.registered
55 .map(t => ({ id: t.name, label: capitalizeFirstLetter(t.name) }))
58 private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) {
61 logger.info(`Injecting ${this.themes.length} themes.`)
63 const head = this.getHeadElement()
65 for (const theme of this.themes) {
66 // Already added this theme?
67 if (fromLocalStorage === false && this.themeFromLocalStorage && this.themeFromLocalStorage.name === theme.name) continue
69 for (const css of theme.css) {
70 const link = document.createElement('link')
72 const href = environment.apiUrl + `/themes/${theme.name}/${theme.version}/css/${css}`
73 link.setAttribute('href', href)
74 link.setAttribute('rel', 'alternate stylesheet')
75 link.setAttribute('type', 'text/css')
76 link.setAttribute('title', theme.name)
77 link.setAttribute('disabled', '')
79 if (fromLocalStorage === true) this.themeDOMLinksFromLocalStorage.push(link)
81 head.appendChild(link)
86 private getCurrentTheme () {
87 if (this.themeFromLocalStorage) return this.themeFromLocalStorage.name
89 const theme = this.auth.isLoggedIn()
90 ? this.auth.getUser().theme
91 : this.userService.getAnonymousUser().theme
93 if (theme !== 'instance-default') return theme
95 const instanceTheme = this.serverConfig.theme.default
96 if (instanceTheme !== 'default') return instanceTheme
98 // Default to dark theme if available and wanted by the user
99 if (this.hasDarkTheme() && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
106 private loadTheme (name: string) {
107 const links = document.getElementsByTagName('link')
108 for (let i = 0; i < links.length; i++) {
109 const link = links[i]
110 if (link.getAttribute('rel').includes('style') && link.getAttribute('title')) {
111 link.disabled = link.getAttribute('title') !== name
116 private updateCurrentTheme () {
117 if (this.oldThemeName) this.removeThemePlugins(this.oldThemeName)
119 const currentTheme = this.getCurrentTheme()
121 logger.info(`Enabling ${currentTheme} theme.`)
123 this.loadTheme(currentTheme)
125 const theme = this.getTheme(currentTheme)
127 logger.info(`Adding scripts of theme ${currentTheme}`)
129 this.pluginService.addPlugin(theme, true)
131 this.pluginService.reloadLoadedScopes()
133 this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false)
135 this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
138 this.oldThemeName = currentTheme
141 private listenUserTheme () {
142 // We don't need them anymore
143 this.themeFromLocalStorage = undefined
144 this.themeDOMLinksFromLocalStorage = []
146 if (!this.auth.isLoggedIn()) {
147 this.updateCurrentTheme()
149 this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
150 () => this.updateCurrentTheme()
154 this.auth.userInformationLoaded
155 .subscribe(() => this.updateCurrentTheme())
158 private loadAndSetFromLocalStorage () {
159 const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
160 if (!lastActiveThemeString) return
163 const lastActiveTheme = JSON.parse(lastActiveThemeString)
164 this.themeFromLocalStorage = lastActiveTheme
166 this.injectThemes([ lastActiveTheme ], true)
167 this.updateCurrentTheme()
169 logger.error('Cannot parse last active theme.', err)
174 private removeThemePlugins (themeName: string) {
175 const oldTheme = this.getTheme(themeName)
177 logger.info(`Removing scripts of old theme ${themeName}.`)
178 this.pluginService.removePlugin(oldTheme)
182 private removeThemeFromLocalStorageIfNeeded (themes: ServerConfigTheme[]) {
183 if (!this.themeFromLocalStorage) return
185 const loadedTheme = themes.find(t => t.name === this.themeFromLocalStorage.name)
186 if (!loadedTheme || loadedTheme.version !== this.themeFromLocalStorage.version) {
187 // Need to remove this theme: we loaded an old version or a theme that does not exist anymore
188 this.removeThemePlugins(this.themeFromLocalStorage.name)
189 this.oldThemeName = undefined
191 const head = this.getHeadElement()
192 for (const htmlLinkElement of this.themeDOMLinksFromLocalStorage) {
193 head.removeChild(htmlLinkElement)
196 this.themeFromLocalStorage = undefined
197 this.themeDOMLinksFromLocalStorage = []
201 private getHeadElement () {
202 return document.getElementsByTagName('head')[0]
205 private getTheme (name: string) {
206 return this.themes.find(t => t.name === name)
209 private hasDarkTheme () {
210 return this.serverConfig.theme.registered.some(t => t.name === 'dark')