]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/menu/top-menu-dropdown.component.ts
Merge branch 'release/2.1.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / menu / top-menu-dropdown.component.ts
1 import { Component, Input, OnDestroy, OnInit } from '@angular/core'
2 import { filter, take } from 'rxjs/operators'
3 import { NavigationEnd, Router } from '@angular/router'
4 import { Subscription } from 'rxjs'
5 import { NgbDropdown } from '@ng-bootstrap/ng-bootstrap'
6 import { GlobalIconName } from '@app/shared/images/global-icon.component'
7 import { ScreenService } from '@app/shared/misc/screen.service'
8
9 export type TopMenuDropdownParam = {
10 label: string
11 routerLink?: string
12
13 children?: {
14 label: string
15 routerLink: string
16
17 iconName?: GlobalIconName
18 }[]
19 }
20
21 @Component({
22 selector: 'my-top-menu-dropdown',
23 templateUrl: './top-menu-dropdown.component.html',
24 styleUrls: [ './top-menu-dropdown.component.scss' ]
25 })
26 export class TopMenuDropdownComponent implements OnInit, OnDestroy {
27 @Input() menuEntries: TopMenuDropdownParam[] = []
28
29 suffixLabels: { [ parentLabel: string ]: string }
30 hasIcons = false
31 container: undefined | 'body' = undefined
32
33 private openedOnHover = false
34 private routeSub: Subscription
35
36 constructor (
37 private router: Router,
38 private screen: ScreenService
39 ) {}
40
41 ngOnInit () {
42 this.updateChildLabels(window.location.pathname)
43
44 this.routeSub = this.router.events
45 .pipe(filter(event => event instanceof NavigationEnd))
46 .subscribe(() => this.updateChildLabels(window.location.pathname))
47
48 this.hasIcons = this.menuEntries.some(
49 e => e.children && e.children.some(c => !!c.iconName)
50 )
51
52 // We have to set body for the container to avoid scroll overflow on mobile view
53 if (this.screen.isInMobileView()) {
54 this.container = 'body'
55 }
56 }
57
58 ngOnDestroy () {
59 if (this.routeSub) this.routeSub.unsubscribe()
60 }
61
62 openDropdownOnHover (dropdown: NgbDropdown) {
63 this.openedOnHover = true
64 dropdown.open()
65
66 // Menu was closed
67 dropdown.openChange
68 .pipe(take(1))
69 .subscribe(() => this.openedOnHover = false)
70 }
71
72 dropdownAnchorClicked (dropdown: NgbDropdown) {
73 if (this.openedOnHover) {
74 this.openedOnHover = false
75 return
76 }
77
78 return dropdown.toggle()
79 }
80
81 closeDropdownIfHovered (dropdown: NgbDropdown) {
82 if (this.openedOnHover === false) return
83
84 dropdown.close()
85 this.openedOnHover = false
86 }
87
88 private updateChildLabels (path: string) {
89 this.suffixLabels = {}
90
91 for (const entry of this.menuEntries) {
92 if (!entry.children) continue
93
94 for (const child of entry.children) {
95 if (path.startsWith(child.routerLink)) {
96 this.suffixLabels[entry.label] = child.label
97 }
98 }
99 }
100 }
101 }