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