]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-forms/select/select-checkbox.component.ts
Add video filters to common video pages
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-forms / select / select-checkbox.component.ts
1 import { Component, forwardRef, Input, OnInit } from '@angular/core'
2 import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
3 import { SelectOptionsItem } from '../../../../types/select-options-item.model'
4
5 export type ItemSelectCheckboxValue = { id?: string, group?: string } | string
6
7 @Component({
8 selector: 'my-select-checkbox',
9 styleUrls: [ './select-shared.component.scss', 'select-checkbox.component.scss' ],
10 templateUrl: './select-checkbox.component.html',
11 providers: [
12 {
13 provide: NG_VALUE_ACCESSOR,
14 useExisting: forwardRef(() => SelectCheckboxComponent),
15 multi: true
16 }
17 ]
18 })
19 export class SelectCheckboxComponent implements OnInit, ControlValueAccessor {
20 @Input() availableItems: SelectOptionsItem[] = []
21 @Input() selectedItems: ItemSelectCheckboxValue[] = []
22 @Input() selectableGroup: boolean
23 @Input() selectableGroupAsModel: boolean
24 @Input() placeholder: string
25
26 ngOnInit () {
27 if (!this.placeholder) this.placeholder = $localize`Add a new option`
28 }
29
30 propagateChange = (_: any) => { /* empty */ }
31
32 writeValue (items: ItemSelectCheckboxValue[]) {
33 if (Array.isArray(items)) {
34 this.selectedItems = items.map(i => {
35 if (typeof i === 'string' || typeof i === 'number') {
36 return i + ''
37 }
38
39 if (i.group) {
40 return { group: i.group }
41 }
42
43 return { id: i.id + '' }
44 })
45 } else {
46 this.selectedItems = items
47 }
48 }
49
50 registerOnChange (fn: (_: any) => void) {
51 this.propagateChange = fn
52 }
53
54 registerOnTouched () {
55 // Unused
56 }
57
58 onModelChange () {
59 this.propagateChange(this.selectedItems)
60 }
61
62 compareFn (item: SelectOptionsItem, selected: ItemSelectCheckboxValue) {
63 if (typeof selected === 'string' || typeof selected === 'number') {
64 return item.id === selected
65 }
66
67 if (this.selectableGroup && item.group && selected.group) {
68 return item.group === selected.group
69 }
70
71 if (selected.id && item.id) {
72 return item.id === selected.id
73 }
74
75 return false
76 }
77 }