1 import { Injectable } from '@angular/core'
2 import { capitalizeFirstLetter } from '@root-helpers/string'
3 import { UserLocalStorageKeys } from '@root-helpers/users'
4 import { HTMLServerConfig, 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: HTMLServerConfig
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.getHTMLConfig()
36 const themes = this.serverConfig.theme.registered
38 this.removeThemeFromLocalStorageIfNeeded(themes)
39 this.injectThemes(themes)
41 this.listenUserTheme()
44 getDefaultThemeLabel () {
45 if (this.hasDarkTheme()) {
46 return $localize`Light/Orange or Dark`
49 return $localize`Light/Orange`
52 getAvailableThemeLabels () {
53 return this.serverConfig.theme.registered
54 .map(t => capitalizeFirstLetter(t.name))
57 private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) {
60 console.log('Injecting %d themes.', this.themes.length)
62 const head = this.getHeadElement()
64 for (const theme of this.themes) {
65 // Already added this theme?
66 if (fromLocalStorage === false && this.themeFromLocalStorage && this.themeFromLocalStorage.name === theme.name) continue
68 for (const css of theme.css) {
69 const link = document.createElement('link')
71 const href = environment.apiUrl + `/themes/${theme.name}/${theme.version}/css/${css}`
72 link.setAttribute('href', href)
73 link.setAttribute('rel', 'alternate stylesheet')
74 link.setAttribute('type', 'text/css')
75 link.setAttribute('title', theme.name)
76 link.setAttribute('disabled', '')
78 if (fromLocalStorage === true) this.themeDOMLinksFromLocalStorage.push(link)
80 head.appendChild(link)
85 private getCurrentTheme () {
86 if (this.themeFromLocalStorage) return this.themeFromLocalStorage.name
88 const theme = this.auth.isLoggedIn()
89 ? this.auth.getUser().theme
90 : this.userService.getAnonymousUser().theme
92 if (theme !== 'instance-default') return theme
94 const instanceTheme = this.serverConfig.theme.default
95 if (instanceTheme !== 'default') return instanceTheme
97 // Default to dark theme if available and wanted by the user
98 if (this.hasDarkTheme() && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
105 private loadTheme (name: string) {
106 const links = document.getElementsByTagName('link')
107 for (let i = 0; i < links.length; i++) {
108 const link = links[i]
109 if (link.getAttribute('rel').includes('style') && link.getAttribute('title')) {
110 link.disabled = link.getAttribute('title') !== name
115 private updateCurrentTheme () {
116 if (this.oldThemeName) this.removeThemePlugins(this.oldThemeName)
118 const currentTheme = this.getCurrentTheme()
120 console.log('Enabling %s theme.', currentTheme)
122 this.loadTheme(currentTheme)
124 const theme = this.getTheme(currentTheme)
126 console.log('Adding scripts of theme %s.', currentTheme)
128 this.pluginService.addPlugin(theme, true)
130 this.pluginService.reloadLoadedScopes()
132 this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false)
134 this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
137 this.oldThemeName = currentTheme
140 private listenUserTheme () {
141 // We don't need them anymore
142 this.themeFromLocalStorage = undefined
143 this.themeDOMLinksFromLocalStorage = []
145 if (!this.auth.isLoggedIn()) {
146 this.updateCurrentTheme()
148 this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
149 () => this.updateCurrentTheme()
153 this.auth.userInformationLoaded
154 .subscribe(() => this.updateCurrentTheme())
157 private loadAndSetFromLocalStorage () {
158 const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
159 if (!lastActiveThemeString) return
162 const lastActiveTheme = JSON.parse(lastActiveThemeString)
163 this.themeFromLocalStorage = lastActiveTheme
165 this.injectThemes([ lastActiveTheme ], true)
166 this.updateCurrentTheme()
168 console.error('Cannot parse last active theme.', err)
173 private removeThemePlugins (themeName: string) {
174 const oldTheme = this.getTheme(themeName)
176 console.log('Removing scripts of old theme %s.', themeName)
177 this.pluginService.removePlugin(oldTheme)
181 private removeThemeFromLocalStorageIfNeeded (themes: ServerConfigTheme[]) {
182 if (!this.themeFromLocalStorage) return
184 const loadedTheme = themes.find(t => t.name === this.themeFromLocalStorage.name)
185 if (!loadedTheme || loadedTheme.version !== this.themeFromLocalStorage.version) {
186 // Need to remove this theme: we loaded an old version or a theme that does not exist anymore
187 this.removeThemePlugins(this.themeFromLocalStorage.name)
188 this.oldThemeName = undefined
190 const head = this.getHeadElement()
191 for (const htmlLinkElement of this.themeDOMLinksFromLocalStorage) {
192 head.removeChild(htmlLinkElement)
195 this.themeFromLocalStorage = undefined
196 this.themeDOMLinksFromLocalStorage = []
200 private getHeadElement () {
201 return document.getElementsByTagName('head')[0]
204 private getTheme (name: string) {
205 return this.themes.find(t => t.name === name)
208 private hasDarkTheme () {
209 return this.serverConfig.theme.registered.some(t => t.name === 'dark')