1 import { Injectable } from '@angular/core'
2 import { AuthService } from '@app/core/auth'
3 import { ServerService } from '@app/core/server'
4 import { environment } from '../../../environments/environment'
5 import { PluginService } from '@app/core/plugins/plugin.service'
6 import { ServerConfigTheme } from '@shared/models'
9 export class ThemeService {
11 private oldThemeName: string
12 private themes: ServerConfigTheme[] = []
15 private auth: AuthService,
16 private pluginService: PluginService,
17 private server: ServerService
21 this.server.configLoaded
25 this.listenUserTheme()
29 private injectThemes () {
30 this.themes = this.server.getConfig().theme.registered
32 console.log('Injecting %d themes.', this.themes.length)
34 const head = document.getElementsByTagName('head')[0]
36 for (const theme of this.themes) {
38 for (const css of theme.css) {
39 const link = document.createElement('link')
41 const href = environment.apiUrl + `/themes/${theme.name}/${theme.version}/css/${css}`
42 link.setAttribute('href', href)
43 link.setAttribute('rel', 'alternate stylesheet')
44 link.setAttribute('type', 'text/css')
45 link.setAttribute('title', theme.name)
46 link.setAttribute('disabled', '')
48 head.appendChild(link)
53 private getCurrentTheme () {
54 if (this.auth.isLoggedIn()) {
55 const theme = this.auth.getUser().theme
56 if (theme !== 'instance-default') return theme
59 return this.server.getConfig().theme.default
62 private loadTheme (name: string) {
63 const links = document.getElementsByTagName('link')
64 for (let i = 0; i < links.length; i++) {
65 const link = links[ i ]
66 if (link.getAttribute('rel').indexOf('style') !== -1 && link.getAttribute('title')) {
67 link.disabled = link.getAttribute('title') !== name
72 private updateCurrentTheme () {
73 if (this.oldThemeName) {
74 const oldTheme = this.getTheme(this.oldThemeName)
76 console.log('Removing scripts of old theme %s.', this.oldThemeName)
77 this.pluginService.removePlugin(oldTheme)
81 const currentTheme = this.getCurrentTheme()
83 console.log('Enabling %s theme.', currentTheme)
85 this.loadTheme(currentTheme)
87 const theme = this.getTheme(currentTheme)
89 console.log('Adding scripts of theme %s.', currentTheme)
90 this.pluginService.addPlugin(theme, true)
92 this.pluginService.reloadLoadedScopes()
95 this.oldThemeName = currentTheme
98 private listenUserTheme () {
99 if (!this.auth.isLoggedIn()) {
100 this.updateCurrentTheme()
103 this.auth.userInformationLoaded
104 .subscribe(() => this.updateCurrentTheme())
107 private getTheme (name: string) {
108 return this.themes.find(t => t.name === name)