]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/app.component.ts
Add title to left menu toggle
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { concat } from 'rxjs'
3 import { filter, first, map, pairwise } from 'rxjs/operators'
4 import { DOCUMENT, PlatformLocation, ViewportScroller } from '@angular/common'
5 import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
6 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
7 import { Event, GuardsCheckStart, NavigationEnd, Router, Scroll } from '@angular/router'
8 import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core'
9 import { HooksService } from '@app/core/plugins/hooks.service'
10 import { PluginService } from '@app/core/plugins/plugin.service'
11 import { CustomModalComponent } from '@app/modal/custom-modal.component'
12 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
13 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
14 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
15 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
16 import { getShortLocale, is18nPath } from '@shared/core-utils/i18n'
17 import { BroadcastMessageLevel, ServerConfig, UserRole } from '@shared/models'
18 import { MenuService } from './core/menu/menu.service'
19 import { POP_STATE_MODAL_DISMISS } from './helpers'
20 import { InstanceService } from './shared/shared-instance'
21
22 @Component({
23 selector: 'my-app',
24 templateUrl: './app.component.html',
25 styleUrls: [ './app.component.scss' ]
26 })
27 export class AppComponent implements OnInit, AfterViewInit {
28 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
29
30 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
31 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
32 @ViewChild('customModal') customModal: CustomModalComponent
33
34 customCSS: SafeHtml
35 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
36
37 private serverConfig: ServerConfig
38
39 constructor (
40 @Inject(DOCUMENT) private document: Document,
41 @Inject(LOCALE_ID) private localeId: string,
42 private viewportScroller: ViewportScroller,
43 private router: Router,
44 private authService: AuthService,
45 private serverService: ServerService,
46 private pluginService: PluginService,
47 private instanceService: InstanceService,
48 private domSanitizer: DomSanitizer,
49 private redirectService: RedirectService,
50 private screenService: ScreenService,
51 private hotkeysService: HotkeysService,
52 private themeService: ThemeService,
53 private hooks: HooksService,
54 private location: PlatformLocation,
55 private modalService: NgbModal,
56 private markdownService: MarkdownService,
57 private ngbConfig: NgbConfig,
58 public menu: MenuService
59 ) {
60 this.ngbConfig.animation = false
61 }
62
63 get instanceName () {
64 return this.serverConfig.instance.name
65 }
66
67 get defaultRoute () {
68 return RedirectService.DEFAULT_ROUTE
69 }
70
71 ngOnInit () {
72 document.getElementById('incompatible-browser').className += ' browser-ok'
73
74 this.serverConfig = this.serverService.getTmpConfig()
75 this.serverService.getConfig()
76 .subscribe(config => this.serverConfig = config)
77
78 this.loadPlugins()
79 this.themeService.initialize()
80
81 this.authService.loadClientCredentials()
82
83 if (this.isUserLoggedIn()) {
84 // The service will automatically redirect to the login page if the token is not valid anymore
85 this.authService.refreshUserInformation()
86 }
87
88 this.initRouteEvents()
89 this.injectJS()
90 this.injectCSS()
91 this.injectBroadcastMessage()
92
93 this.initHotkeys()
94
95 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
96
97 this.openModalsIfNeeded()
98
99 this.document.documentElement.lang = getShortLocale(this.localeId)
100 }
101
102 ngAfterViewInit () {
103 this.pluginService.initializeCustomModal(this.customModal)
104 }
105
106 getToggleTitle () {
107 if (this.menu.isDisplayed()) return $localize`Close the left menu`
108
109 return $localize`Open the left menu`
110 }
111
112 isUserLoggedIn () {
113 return this.authService.isLoggedIn()
114 }
115
116 hideBroadcastMessage () {
117 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
118
119 this.broadcastMessage = null
120 this.screenService.isBroadcastMessageDisplayed = false
121 }
122
123 private initRouteEvents () {
124 let resetScroll = true
125 const eventsObs = this.router.events
126
127 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
128
129 scrollEvent.subscribe(e => {
130 // scrollToAnchor first to preserve anchor position when using history navigation
131 if (e.anchor) {
132 setTimeout(() => {
133 this.viewportScroller.scrollToAnchor(e.anchor)
134 })
135
136 return
137 }
138
139 if (e.position) {
140 return this.viewportScroller.scrollToPosition(e.position)
141 }
142
143 if (resetScroll) {
144 return this.viewportScroller.scrollToPosition([ 0, 0 ])
145 }
146 })
147
148 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
149
150 // When we add the a-state parameter, we don't want to alter the scroll
151 navigationEndEvent.pipe(pairwise())
152 .subscribe(([ e1, e2 ]) => {
153 try {
154 resetScroll = false
155
156 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
157 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
158
159 if (previousUrl.pathname !== nextUrl.pathname) {
160 resetScroll = true
161 return
162 }
163
164 const nextSearchParams = nextUrl.searchParams
165 nextSearchParams.delete('a-state')
166
167 const previousSearchParams = previousUrl.searchParams
168
169 nextSearchParams.sort()
170 previousSearchParams.sort()
171
172 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
173 resetScroll = true
174 }
175 } catch (e) {
176 console.error('Cannot parse URL to check next scroll.', e)
177 resetScroll = true
178 }
179 })
180
181 navigationEndEvent.pipe(
182 map(() => window.location.pathname),
183 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
184 ).subscribe(() => this.redirectService.redirectToHomepage(true))
185
186 navigationEndEvent.subscribe(e => {
187 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
188 })
189
190 eventsObs.pipe(
191 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
192 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
193 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
194 }
195
196 private injectBroadcastMessage () {
197 concat(
198 this.serverService.getConfig().pipe(first()),
199 this.serverService.configReloaded
200 ).subscribe(async config => {
201 this.broadcastMessage = null
202 this.screenService.isBroadcastMessageDisplayed = false
203
204 const messageConfig = config.broadcastMessage
205
206 if (messageConfig.enabled) {
207 // Already dismissed this message?
208 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
209 return
210 }
211
212 const classes: { [id in BroadcastMessageLevel]: string } = {
213 info: 'alert-info',
214 warning: 'alert-warning',
215 error: 'alert-danger'
216 }
217
218 this.broadcastMessage = {
219 message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
220 dismissable: messageConfig.dismissable,
221 class: classes[messageConfig.level]
222 }
223
224 this.screenService.isBroadcastMessageDisplayed = true
225 }
226 })
227 }
228
229 private injectJS () {
230 // Inject JS
231 this.serverService.getConfig()
232 .subscribe(config => {
233 if (config.instance.customizations.javascript) {
234 try {
235 // tslint:disable:no-eval
236 eval(config.instance.customizations.javascript)
237 } catch (err) {
238 console.error('Cannot eval custom JavaScript.', err)
239 }
240 }
241 })
242 }
243
244 private injectCSS () {
245 // Inject CSS if modified (admin config settings)
246 concat(
247 this.serverService.getConfig().pipe(first()),
248 this.serverService.configReloaded
249 ).subscribe(config => {
250 const headStyle = document.querySelector('style.custom-css-style')
251 if (headStyle) headStyle.parentNode.removeChild(headStyle)
252
253 // We test customCSS if the admin removed the css
254 if (this.customCSS || config.instance.customizations.css) {
255 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
256 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
257 }
258 })
259 }
260
261 private async loadPlugins () {
262 this.pluginService.initializePlugins()
263
264 this.hooks.runAction('action:application.init', 'common')
265 }
266
267 private async openModalsIfNeeded () {
268 this.authService.userInformationLoaded
269 .pipe(
270 map(() => this.authService.getUser()),
271 filter(user => user.role === UserRole.ADMINISTRATOR)
272 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
273 }
274
275 private async _openAdminModalsIfNeeded (user: User) {
276 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
277
278 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
279
280 this.instanceService.getAbout()
281 .subscribe(about => {
282 if (
283 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
284 !about.instance.terms ||
285 !about.instance.administrator ||
286 !about.instance.maintenanceLifetime
287 ) {
288 this.instanceConfigWarningModal.show(about)
289 }
290 })
291 }
292
293 private initHotkeys () {
294 this.hotkeysService.add([
295 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
296 document.getElementById('search-video').focus()
297 return false
298 }, undefined, $localize`Focus the search bar`),
299
300 new Hotkey('b', (event: KeyboardEvent): boolean => {
301 this.menu.toggleMenu()
302 return false
303 }, undefined, $localize`Toggle the left menu`),
304
305 new Hotkey('g o', (event: KeyboardEvent): boolean => {
306 this.router.navigate([ '/videos/overview' ])
307 return false
308 }, undefined, $localize`Go to the discover videos page`),
309
310 new Hotkey('g t', (event: KeyboardEvent): boolean => {
311 this.router.navigate([ '/videos/trending' ])
312 return false
313 }, undefined, $localize`Go to the trending videos page`),
314
315 new Hotkey('g r', (event: KeyboardEvent): boolean => {
316 this.router.navigate([ '/videos/recently-added' ])
317 return false
318 }, undefined, $localize`Go to the recently added videos page`),
319
320 new Hotkey('g l', (event: KeyboardEvent): boolean => {
321 this.router.navigate([ '/videos/local' ])
322 return false
323 }, undefined, $localize`Go to the local videos page`),
324
325 new Hotkey('g u', (event: KeyboardEvent): boolean => {
326 this.router.navigate([ '/videos/upload' ])
327 return false
328 }, undefined, $localize`Go to the videos upload page`)
329 ])
330 }
331 }