]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/theme/theme.service.ts
Use random port for mock servers in tests
[github/Chocobozzz/PeerTube.git] / client / src / app / core / theme / theme.service.ts
CommitLineData
67ed6552 1import { first } from 'rxjs/operators'
1a00c561 2import { Injectable } from '@angular/core'
a4ff3100
C
3import { UserLocalStorageKeys } from '@root-helpers/users'
4import { ServerConfig, ServerConfigTheme } from '@shared/models'
5import { environment } from '../../../environments/environment'
67ed6552
C
6import { AuthService } from '../auth'
7import { PluginService } from '../plugins/plugin.service'
8import { ServerService } from '../server'
67ed6552 9import { UserService } from '../users/user.service'
a4ff3100 10import { LocalStorageService } from '../wrappers/storage.service'
1a00c561
RK
11
12@Injectable()
13export class ThemeService {
ffb321be
C
14
15 private oldThemeName: string
16 private themes: ServerConfigTheme[] = []
17
a2ffd046
C
18 private themeFromLocalStorage: ServerConfigTheme
19 private themeDOMLinksFromLocalStorage: HTMLLinkElement[] = []
20
ba430d75
C
21 private serverConfig: ServerConfig
22
ffb321be
C
23 constructor (
24 private auth: AuthService,
d3217560 25 private userService: UserService,
ffb321be 26 private pluginService: PluginService,
d3217560
RK
27 private server: ServerService,
28 private localStorageService: LocalStorageService
ffb321be
C
29 ) {}
30
31 initialize () {
a2ffd046
C
32 // Try to load from local storage first, so we don't have to wait network requests
33 this.loadAndSetFromLocalStorage()
34
ba430d75
C
35 this.serverConfig = this.server.getTmpConfig()
36 this.server.getConfig()
37 .subscribe(config => {
38 this.serverConfig = config
39
40 const themes = this.serverConfig.theme.registered
a2ffd046
C
41
42 this.removeThemeFromLocalStorageIfNeeded(themes)
43 this.injectThemes(themes)
ffb321be
C
44
45 this.listenUserTheme()
46 })
47 }
48
a2ffd046
C
49 private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) {
50 this.themes = themes
ffb321be
C
51
52 console.log('Injecting %d themes.', this.themes.length)
53
a2ffd046 54 const head = this.getHeadElement()
ffb321be
C
55
56 for (const theme of this.themes) {
a2ffd046
C
57 // Already added this theme?
58 if (fromLocalStorage === false && this.themeFromLocalStorage && this.themeFromLocalStorage.name === theme.name) continue
ffb321be
C
59
60 for (const css of theme.css) {
61 const link = document.createElement('link')
62
63 const href = environment.apiUrl + `/themes/${theme.name}/${theme.version}/css/${css}`
64 link.setAttribute('href', href)
65 link.setAttribute('rel', 'alternate stylesheet')
66 link.setAttribute('type', 'text/css')
67 link.setAttribute('title', theme.name)
68 link.setAttribute('disabled', '')
69
a2ffd046
C
70 if (fromLocalStorage === true) this.themeDOMLinksFromLocalStorage.push(link)
71
ffb321be
C
72 head.appendChild(link)
73 }
74 }
75 }
76
77 private getCurrentTheme () {
a2ffd046
C
78 if (this.themeFromLocalStorage) return this.themeFromLocalStorage.name
79
d3217560
RK
80 const theme = this.auth.isLoggedIn()
81 ? this.auth.getUser().theme
82 : this.userService.getAnonymousUser().theme
ffb321be 83
d3217560 84 if (theme !== 'instance-default') return theme
5c48aa8c
C
85
86 const instanceTheme = this.serverConfig.theme.default
87 if (instanceTheme !== 'default') return instanceTheme
88
89 // Default to dark theme if available and wanted by the user
90 if (
91 this.themes.find(t => t.name === 'dark') &&
92 window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
93 ) {
94 return 'dark'
95 }
96
97 return instanceTheme
1a00c561
RK
98 }
99
ffb321be
C
100 private loadTheme (name: string) {
101 const links = document.getElementsByTagName('link')
102 for (let i = 0; i < links.length; i++) {
103 const link = links[ i ]
104 if (link.getAttribute('rel').indexOf('style') !== -1 && link.getAttribute('title')) {
105 link.disabled = link.getAttribute('title') !== name
106 }
107 }
108 }
109
110 private updateCurrentTheme () {
a2ffd046 111 if (this.oldThemeName) this.removeThemePlugins(this.oldThemeName)
ffb321be
C
112
113 const currentTheme = this.getCurrentTheme()
114
115 console.log('Enabling %s theme.', currentTheme)
116
117 this.loadTheme(currentTheme)
d00dc28d 118
ffb321be
C
119 const theme = this.getTheme(currentTheme)
120 if (theme) {
121 console.log('Adding scripts of theme %s.', currentTheme)
f0c5e8b6 122 this.pluginService.addPlugin(theme, true)
ffb321be
C
123
124 this.pluginService.reloadLoadedScopes()
a2ffd046 125
a4ff3100 126 this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false)
a2ffd046 127 } else {
a4ff3100 128 this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
e3f7f600 129 }
ffb321be
C
130
131 this.oldThemeName = currentTheme
132 }
133
134 private listenUserTheme () {
a2ffd046
C
135 // We don't need them anymore
136 this.themeFromLocalStorage = undefined
137 this.themeDOMLinksFromLocalStorage = []
138
d00dc28d
C
139 if (!this.auth.isLoggedIn()) {
140 this.updateCurrentTheme()
d3217560 141
a4ff3100 142 this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
d3217560
RK
143 () => this.updateCurrentTheme()
144 )
d00dc28d
C
145 }
146
ffb321be 147 this.auth.userInformationLoaded
7c93905d 148 .pipe(first())
ffb321be 149 .subscribe(() => this.updateCurrentTheme())
1a00c561
RK
150 }
151
a2ffd046 152 private loadAndSetFromLocalStorage () {
a4ff3100 153 const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
a2ffd046
C
154 if (!lastActiveThemeString) return
155
156 try {
157 const lastActiveTheme = JSON.parse(lastActiveThemeString)
158 this.themeFromLocalStorage = lastActiveTheme
159
160 this.injectThemes([ lastActiveTheme ], true)
161 this.updateCurrentTheme()
162 } catch (err) {
163 console.error('Cannot parse last active theme.', err)
164 return
165 }
166 }
167
168 private removeThemePlugins (themeName: string) {
169 const oldTheme = this.getTheme(themeName)
170 if (oldTheme) {
171 console.log('Removing scripts of old theme %s.', themeName)
172 this.pluginService.removePlugin(oldTheme)
173 }
174 }
175
176 private removeThemeFromLocalStorageIfNeeded (themes: ServerConfigTheme[]) {
177 if (!this.themeFromLocalStorage) return
178
179 const loadedTheme = themes.find(t => t.name === this.themeFromLocalStorage.name)
180 if (!loadedTheme || loadedTheme.version !== this.themeFromLocalStorage.version) {
181 // Need to remove this theme: we loaded an old version or a theme that does not exist anymore
182 this.removeThemePlugins(this.themeFromLocalStorage.name)
183 this.oldThemeName = undefined
184
185 const head = this.getHeadElement()
186 for (const htmlLinkElement of this.themeDOMLinksFromLocalStorage) {
187 head.removeChild(htmlLinkElement)
188 }
189
190 this.themeFromLocalStorage = undefined
191 this.themeDOMLinksFromLocalStorage = []
192 }
193 }
194
195 private getHeadElement () {
196 return document.getElementsByTagName('head')[0]
197 }
198
ffb321be
C
199 private getTheme (name: string) {
200 return this.themes.find(t => t.name === name)
1a00c561
RK
201 }
202}