+ private themeFromLocalStorage: ServerConfigTheme
+ private themeDOMLinksFromLocalStorage: HTMLLinkElement[] = []
+
+ private serverConfig: ServerConfig
+
+ constructor (
+ private auth: AuthService,
+ private userService: UserService,
+ private pluginService: PluginService,
+ private server: ServerService,
+ private localStorageService: LocalStorageService
+ ) {}
+
+ initialize () {
+ // Try to load from local storage first, so we don't have to wait network requests
+ this.loadAndSetFromLocalStorage()
+
+ this.serverConfig = this.server.getTmpConfig()
+ this.server.getConfig()
+ .subscribe(config => {
+ this.serverConfig = config
+
+ const themes = this.serverConfig.theme.registered
+
+ this.removeThemeFromLocalStorageIfNeeded(themes)
+ this.injectThemes(themes)
+
+ this.listenUserTheme()
+ })
+ }
+
+ private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) {
+ this.themes = themes
+
+ console.log('Injecting %d themes.', this.themes.length)
+
+ const head = this.getHeadElement()
+
+ for (const theme of this.themes) {
+ // Already added this theme?
+ if (fromLocalStorage === false && this.themeFromLocalStorage && this.themeFromLocalStorage.name === theme.name) continue
+
+ for (const css of theme.css) {
+ const link = document.createElement('link')
+
+ const href = environment.apiUrl + `/themes/${theme.name}/${theme.version}/css/${css}`
+ link.setAttribute('href', href)
+ link.setAttribute('rel', 'alternate stylesheet')
+ link.setAttribute('type', 'text/css')
+ link.setAttribute('title', theme.name)
+ link.setAttribute('disabled', '')
+
+ if (fromLocalStorage === true) this.themeDOMLinksFromLocalStorage.push(link)
+
+ head.appendChild(link)
+ }
+ }
+ }
+
+ private getCurrentTheme () {
+ if (this.themeFromLocalStorage) return this.themeFromLocalStorage.name
+
+ const theme = this.auth.isLoggedIn()
+ ? this.auth.getUser().theme
+ : this.userService.getAnonymousUser().theme
+
+ if (theme !== 'instance-default') return theme
+
+ const instanceTheme = this.serverConfig.theme.default
+ if (instanceTheme !== 'default') return instanceTheme
+
+ // Default to dark theme if available and wanted by the user
+ if (
+ this.themes.find(t => t.name === 'dark') &&
+ window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
+ ) {
+ return 'dark'
+ }
+
+ return instanceTheme
+ }
+
+ private loadTheme (name: string) {
+ const links = document.getElementsByTagName('link')
+ for (let i = 0; i < links.length; i++) {
+ const link = links[ i ]
+ if (link.getAttribute('rel').indexOf('style') !== -1 && link.getAttribute('title')) {
+ link.disabled = link.getAttribute('title') !== name
+ }
+ }