]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/app.component.ts
Use ::ng-deep instead of /deep/
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
1 import { Component, OnInit } from '@angular/core'
2 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
3 import { Event, GuardsCheckStart, NavigationEnd, Router, Scroll } from '@angular/router'
4 import { AuthService, RedirectService, ServerService, ThemeService } from '@app/core'
5 import { is18nPath } from '../../../shared/models/i18n'
6 import { ScreenService } from '@app/shared/misc/screen.service'
7 import { debounceTime, filter, map, pairwise, skip } from 'rxjs/operators'
8 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
9 import { I18n } from '@ngx-translate/i18n-polyfill'
10 import { fromEvent } from 'rxjs'
11 import { ViewportScroller } from '@angular/common'
12 import { PluginService } from '@app/core/plugins/plugin.service'
13 import { HooksService } from '@app/core/plugins/hooks.service'
14
15 @Component({
16 selector: 'my-app',
17 templateUrl: './app.component.html',
18 styleUrls: [ './app.component.scss' ]
19 })
20 export class AppComponent implements OnInit {
21 isMenuDisplayed = true
22 isMenuChangedByUser = false
23
24 customCSS: SafeHtml
25
26 constructor (
27 private i18n: I18n,
28 private viewportScroller: ViewportScroller,
29 private router: Router,
30 private authService: AuthService,
31 private serverService: ServerService,
32 private pluginService: PluginService,
33 private domSanitizer: DomSanitizer,
34 private redirectService: RedirectService,
35 private screenService: ScreenService,
36 private hotkeysService: HotkeysService,
37 private themeService: ThemeService,
38 private hooks: HooksService
39 ) { }
40
41 get serverVersion () {
42 return this.serverService.getConfig().serverVersion
43 }
44
45 get serverCommit () {
46 const commit = this.serverService.getConfig().serverCommit || ''
47 return (commit !== '') ? '...' + commit : commit
48 }
49
50 get instanceName () {
51 return this.serverService.getConfig().instance.name
52 }
53
54 get defaultRoute () {
55 return RedirectService.DEFAULT_ROUTE
56 }
57
58 ngOnInit () {
59 document.getElementById('incompatible-browser').className += ' browser-ok'
60
61 this.authService.loadClientCredentials()
62
63 if (this.isUserLoggedIn()) {
64 // The service will automatically redirect to the login page if the token is not valid anymore
65 this.authService.refreshUserInformation()
66 }
67
68 // Load custom data from server
69 this.serverService.loadConfig()
70 this.serverService.loadVideoCategories()
71 this.serverService.loadVideoLanguages()
72 this.serverService.loadVideoLicences()
73 this.serverService.loadVideoPrivacies()
74 this.serverService.loadVideoPlaylistPrivacies()
75
76 this.loadPlugins()
77 this.themeService.initialize()
78
79 // Do not display menu on small screens
80 if (this.screenService.isInSmallView()) {
81 this.isMenuDisplayed = false
82 }
83
84 this.initRouteEvents()
85 this.injectJS()
86 this.injectCSS()
87
88 this.initHotkeys()
89
90 fromEvent(window, 'resize')
91 .pipe(debounceTime(200))
92 .subscribe(() => this.onResize())
93 }
94
95 isUserLoggedIn () {
96 return this.authService.isLoggedIn()
97 }
98
99 toggleMenu () {
100 this.isMenuDisplayed = !this.isMenuDisplayed
101 this.isMenuChangedByUser = true
102 }
103
104 onResize () {
105 this.isMenuDisplayed = window.innerWidth >= 800 && !this.isMenuChangedByUser
106 }
107
108 private initRouteEvents () {
109 let resetScroll = true
110 const eventsObs = this.router.events
111
112 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
113 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
114
115 scrollEvent.subscribe(e => {
116 if (e.position) {
117 return this.viewportScroller.scrollToPosition(e.position)
118 }
119
120 if (e.anchor) {
121 return this.viewportScroller.scrollToAnchor(e.anchor)
122 }
123
124 if (resetScroll) {
125 return this.viewportScroller.scrollToPosition([ 0, 0 ])
126 }
127 })
128
129 // When we add the a-state parameter, we don't want to alter the scroll
130 navigationEndEvent.pipe(pairwise())
131 .subscribe(([ e1, e2 ]) => {
132 try {
133 resetScroll = false
134
135 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
136 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
137
138 if (previousUrl.pathname !== nextUrl.pathname) {
139 resetScroll = true
140 return
141 }
142
143 const nextSearchParams = nextUrl.searchParams
144 nextSearchParams.delete('a-state')
145
146 const previousSearchParams = previousUrl.searchParams
147
148 nextSearchParams.sort()
149 previousSearchParams.sort()
150
151 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
152 resetScroll = true
153 }
154 } catch (e) {
155 console.error('Cannot parse URL to check next scroll.', e)
156 resetScroll = true
157 }
158 })
159
160 navigationEndEvent.pipe(
161 map(() => window.location.pathname),
162 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
163 ).subscribe(() => this.redirectService.redirectToHomepage(true))
164
165 eventsObs.pipe(
166 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
167 filter(() => this.screenService.isInSmallView())
168 ).subscribe(() => this.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
169 }
170
171 private injectJS () {
172 // Inject JS
173 this.serverService.configLoaded
174 .subscribe(() => {
175 const config = this.serverService.getConfig()
176
177 if (config.instance.customizations.javascript) {
178 try {
179 // tslint:disable:no-eval
180 eval(config.instance.customizations.javascript)
181 } catch (err) {
182 console.error('Cannot eval custom JavaScript.', err)
183 }
184 }
185 })
186 }
187
188 private injectCSS () {
189 // Inject CSS if modified (admin config settings)
190 this.serverService.configLoaded
191 .pipe(skip(1)) // We only want to subscribe to reloads, because the CSS is already injected by the server
192 .subscribe(() => {
193 const headStyle = document.querySelector('style.custom-css-style')
194 if (headStyle) headStyle.parentNode.removeChild(headStyle)
195
196 const config = this.serverService.getConfig()
197
198 // We test customCSS if the admin removed the css
199 if (this.customCSS || config.instance.customizations.css) {
200 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
201 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
202 }
203 })
204 }
205
206 private async loadPlugins () {
207 this.pluginService.initializePlugins()
208
209 this.hooks.runAction('action:application.init', 'common')
210 }
211
212 private initHotkeys () {
213 this.hotkeysService.add([
214 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
215 document.getElementById('search-video').focus()
216 return false
217 }, undefined, this.i18n('Focus the search bar')),
218 new Hotkey('b', (event: KeyboardEvent): boolean => {
219 this.toggleMenu()
220 return false
221 }, undefined, this.i18n('Toggle the left menu')),
222 new Hotkey('g o', (event: KeyboardEvent): boolean => {
223 this.router.navigate([ '/videos/overview' ])
224 return false
225 }, undefined, this.i18n('Go to the videos overview page')),
226 new Hotkey('g t', (event: KeyboardEvent): boolean => {
227 this.router.navigate([ '/videos/trending' ])
228 return false
229 }, undefined, this.i18n('Go to the trending videos page')),
230 new Hotkey('g r', (event: KeyboardEvent): boolean => {
231 this.router.navigate([ '/videos/recently-added' ])
232 return false
233 }, undefined, this.i18n('Go to the recently added videos page')),
234 new Hotkey('g l', (event: KeyboardEvent): boolean => {
235 this.router.navigate([ '/videos/local' ])
236 return false
237 }, undefined, this.i18n('Go to the local videos page')),
238 new Hotkey('g u', (event: KeyboardEvent): boolean => {
239 this.router.navigate([ '/videos/upload' ])
240 return false
241 }, undefined, this.i18n('Go to the videos upload page'))
242 ])
243 }
244 }