1 import { Component, forwardRef, Input } from '@angular/core'
2 import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
3 import { Notifier } from '@app/core'
4 import { prepareIcu } from '@app/helpers'
5 import { SelectOptionsItem } from '../../../../types/select-options-item.model'
6 import { ItemSelectCheckboxValue } from './select-checkbox.component'
9 selector: 'my-select-checkbox-all',
10 styleUrls: [ './select-shared.component.scss' ],
14 [(ngModel)]="selectedItems"
15 (ngModelChange)="onModelChange()"
16 [availableItems]="availableItems"
17 [selectableGroup]="true" [selectableGroupAsModel]="true"
18 [placeholder]="placeholder"
21 </my-select-checkbox>`,
25 provide: NG_VALUE_ACCESSOR,
26 useExisting: forwardRef(() => SelectCheckboxAllComponent),
31 export class SelectCheckboxAllComponent implements ControlValueAccessor {
32 @Input() availableItems: SelectOptionsItem[] = []
33 @Input() allGroupLabel: string
35 @Input() placeholder: string
36 @Input() maxItems: number
38 selectedItems: ItemSelectCheckboxValue[]
41 private notifier: Notifier
46 propagateChange = (_: any) => { /* empty */ }
48 writeValue (items: string[]) {
49 this.selectedItems = items
50 ? items.map(l => ({ id: l }))
51 : [ { group: this.allGroupLabel } ]
54 registerOnChange (fn: (_: any) => void) {
55 this.propagateChange = fn
58 registerOnTouched () {
63 if (!this.isMaxConstraintValid()) return
65 this.propagateChange(this.buildOutputItems())
69 // Automatically use "All languages" if the user did not select any language
70 if (Array.isArray(this.selectedItems) && this.selectedItems.length === 0) {
71 this.selectedItems = [ { group: this.allGroupLabel } ]
75 private isMaxConstraintValid () {
76 if (!this.maxItems) return true
78 const outputItems = this.buildOutputItems()
79 if (!outputItems) return true
81 if (outputItems.length >= this.maxItems) {
83 prepareIcu($localize`You can't select more than {maxItems, plural, =1 {1 item} other {{maxItems} items}}`)(
84 { maxItems: this.maxItems },
85 $localize`You can't select more than ${this.maxItems} items`
95 private buildOutputItems () {
96 if (!Array.isArray(this.selectedItems)) return undefined
99 if (this.selectedItems.length === 0 || this.selectedItems.length === this.availableItems.length) {
103 if (this.selectedItems.length === 1) {
104 const item = this.selectedItems[0]
106 const itemGroup = typeof item === 'string' || typeof item === 'number'
110 if (itemGroup === this.allGroupLabel) return null
113 return this.selectedItems.map(l => {
114 if (typeof l === 'string' || typeof l === 'number') return l
116 if (l.group) return l.group