]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/theme/theme.service.ts
Merge branch 'release/4.2.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / app / core / theme / theme.service.ts
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'
11
12 @Injectable()
13 export class ThemeService {
14
15 private oldThemeName: string
16 private themes: ServerConfigTheme[] = []
17
18 private themeFromLocalStorage: ServerConfigTheme
19 private themeDOMLinksFromLocalStorage: HTMLLinkElement[] = []
20
21 private serverConfig: HTMLServerConfig
22
23 constructor (
24 private auth: AuthService,
25 private userService: UserService,
26 private pluginService: PluginService,
27 private server: ServerService,
28 private localStorageService: LocalStorageService
29 ) {}
30
31 initialize () {
32 // Try to load from local storage first, so we don't have to wait network requests
33 this.loadAndSetFromLocalStorage()
34
35 this.serverConfig = this.server.getHTMLConfig()
36 const themes = this.serverConfig.theme.registered
37
38 this.removeThemeFromLocalStorageIfNeeded(themes)
39 this.injectThemes(themes)
40
41 this.listenUserTheme()
42 }
43
44 getDefaultThemeLabel () {
45 if (this.hasDarkTheme()) {
46 return $localize`Light/Orange or Dark`
47 }
48
49 return $localize`Light/Orange`
50 }
51
52 getAvailableThemeLabels () {
53 return this.serverConfig.theme.registered
54 .map(t => capitalizeFirstLetter(t.name))
55 }
56
57 private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) {
58 this.themes = themes
59
60 console.log('Injecting %d themes.', this.themes.length)
61
62 const head = this.getHeadElement()
63
64 for (const theme of this.themes) {
65 // Already added this theme?
66 if (fromLocalStorage === false && this.themeFromLocalStorage && this.themeFromLocalStorage.name === theme.name) continue
67
68 for (const css of theme.css) {
69 const link = document.createElement('link')
70
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', '')
77
78 if (fromLocalStorage === true) this.themeDOMLinksFromLocalStorage.push(link)
79
80 head.appendChild(link)
81 }
82 }
83 }
84
85 private getCurrentTheme () {
86 if (this.themeFromLocalStorage) return this.themeFromLocalStorage.name
87
88 const theme = this.auth.isLoggedIn()
89 ? this.auth.getUser().theme
90 : this.userService.getAnonymousUser().theme
91
92 if (theme !== 'instance-default') return theme
93
94 const instanceTheme = this.serverConfig.theme.default
95 if (instanceTheme !== 'default') return instanceTheme
96
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) {
99 return 'dark'
100 }
101
102 return instanceTheme
103 }
104
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
111 }
112 }
113 }
114
115 private updateCurrentTheme () {
116 if (this.oldThemeName) this.removeThemePlugins(this.oldThemeName)
117
118 const currentTheme = this.getCurrentTheme()
119
120 console.log('Enabling %s theme.', currentTheme)
121
122 this.loadTheme(currentTheme)
123
124 const theme = this.getTheme(currentTheme)
125 if (theme) {
126 console.log('Adding scripts of theme %s.', currentTheme)
127
128 this.pluginService.addPlugin(theme, true)
129
130 this.pluginService.reloadLoadedScopes()
131
132 this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false)
133 } else {
134 this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
135 }
136
137 this.oldThemeName = currentTheme
138 }
139
140 private listenUserTheme () {
141 // We don't need them anymore
142 this.themeFromLocalStorage = undefined
143 this.themeDOMLinksFromLocalStorage = []
144
145 if (!this.auth.isLoggedIn()) {
146 this.updateCurrentTheme()
147
148 this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
149 () => this.updateCurrentTheme()
150 )
151 }
152
153 this.auth.userInformationLoaded
154 .subscribe(() => this.updateCurrentTheme())
155 }
156
157 private loadAndSetFromLocalStorage () {
158 const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
159 if (!lastActiveThemeString) return
160
161 try {
162 const lastActiveTheme = JSON.parse(lastActiveThemeString)
163 this.themeFromLocalStorage = lastActiveTheme
164
165 this.injectThemes([ lastActiveTheme ], true)
166 this.updateCurrentTheme()
167 } catch (err) {
168 console.error('Cannot parse last active theme.', err)
169 return
170 }
171 }
172
173 private removeThemePlugins (themeName: string) {
174 const oldTheme = this.getTheme(themeName)
175 if (oldTheme) {
176 console.log('Removing scripts of old theme %s.', themeName)
177 this.pluginService.removePlugin(oldTheme)
178 }
179 }
180
181 private removeThemeFromLocalStorageIfNeeded (themes: ServerConfigTheme[]) {
182 if (!this.themeFromLocalStorage) return
183
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
189
190 const head = this.getHeadElement()
191 for (const htmlLinkElement of this.themeDOMLinksFromLocalStorage) {
192 head.removeChild(htmlLinkElement)
193 }
194
195 this.themeFromLocalStorage = undefined
196 this.themeDOMLinksFromLocalStorage = []
197 }
198 }
199
200 private getHeadElement () {
201 return document.getElementsByTagName('head')[0]
202 }
203
204 private getTheme (name: string) {
205 return this.themes.find(t => t.name === name)
206 }
207
208 private hasDarkTheme () {
209 return this.serverConfig.theme.registered.some(t => t.name === 'dark')
210 }
211 }