aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/shared-forms/select/select-checkbox.component.ts
blob: c9a5003248d2f751570ba0d7d35ba5537826b65b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { Component, forwardRef, Input, OnInit } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
import { SelectOptionsItem } from '../../../../types/select-options-item.model'

export type ItemSelectCheckboxValue = { id?: string, group?: string } | string

@Component({
  selector: 'my-select-checkbox',
  styleUrls: [ './select-shared.component.scss', 'select-checkbox.component.scss' ],
  templateUrl: './select-checkbox.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SelectCheckboxComponent),
      multi: true
    }
  ]
})
export class SelectCheckboxComponent implements OnInit, ControlValueAccessor {
  @Input() availableItems: SelectOptionsItem[] = []
  @Input() selectedItems: ItemSelectCheckboxValue[] = []
  @Input() selectableGroup: boolean
  @Input() selectableGroupAsModel: boolean
  @Input() placeholder: string

  disabled = false

  ngOnInit () {
    if (!this.placeholder) this.placeholder = $localize`Add a new option`
  }

  propagateChange = (_: any) => { /* empty */ }

  writeValue (items: ItemSelectCheckboxValue[]) {
    if (Array.isArray(items)) {
      this.selectedItems = items.map(i => {
        if (typeof i === 'string' || typeof i === 'number') {
          return i + ''
        }

        if (i.group) {
          return { group: i.group }
        }

        return { id: i.id + '' }
      })
    } else {
      this.selectedItems = items
    }
  }

  registerOnChange (fn: (_: any) => void) {
    this.propagateChange = fn
  }

  registerOnTouched () {
    // Unused
  }

  onModelChange () {
    this.propagateChange(this.selectedItems)
  }

  setDisabledState (isDisabled: boolean) {
    this.disabled = isDisabled
  }

  compareFn (item: SelectOptionsItem, selected: ItemSelectCheckboxValue) {
    if (typeof selected === 'string' || typeof selected === 'number') {
      return item.id === selected
    }

    if (this.selectableGroup && item.group && selected.group) {
      return item.group === selected.group
    }

    if (selected.id && item.id) {
      return item.id === selected.id
    }

    return false
  }
}