| 12 | * Class to be used to power selecting one or more options from a list. |
| 13 | */ |
| 14 | export class SelectionModel<T> { |
| 15 | /** Currently-selected values. */ |
| 16 | private _selection = new Set<T>(); |
| 17 | |
| 18 | /** Keeps track of the deselected options that haven't been emitted by the change event. */ |
| 19 | private _deselectedToEmit: T[] = []; |
| 20 | |
| 21 | /** Keeps track of the selected options that haven't been emitted by the change event. */ |
| 22 | private _selectedToEmit: T[] = []; |
| 23 | |
| 24 | /** Cache for the array value of the selected items. */ |
| 25 | private _selected: T[] | null = null; |
| 26 | |
| 27 | /** Selected values. */ |
| 28 | get selected(): T[] { |
| 29 | if (!this._selected) { |
| 30 | this._selected = Array.from(this._selection.values()); |
| 31 | } |
| 32 | |
| 33 | return this._selected; |
| 34 | } |
| 35 | |
| 36 | /** Event emitted when the value has changed. */ |
| 37 | readonly changed = new Subject<SelectionChange<T>>(); |
| 38 | |
| 39 | /** |
| 40 | * Exposes selection/deselection methods that work on array of values and don't expect a spread. |
| 41 | * This is useful in the cases where you may have a large collection of items that can't be |
| 42 | * easily spread into the existing methods without hitting browser limits. |
| 43 | */ |
| 44 | readonly bulk: Readonly<{ |
| 45 | select: (values: T[]) => boolean; |
| 46 | deselect: (values: T[]) => boolean; |
| 47 | setSelection: (values: T[]) => boolean; |
| 48 | }> = { |
| 49 | select: values => this._select(values), |
| 50 | deselect: values => this._deselect(values), |
| 51 | setSelection: values => this._setSelection(values), |
| 52 | }; |
| 53 | |
| 54 | constructor( |
| 55 | private _multiple = false, |
| 56 | initiallySelectedValues?: T[], |
| 57 | private _emitChanges = true, |
| 58 | public compareWith?: (o1: T, o2: T) => boolean, |
| 59 | ) { |
| 60 | if (initiallySelectedValues && initiallySelectedValues.length) { |
| 61 | if (_multiple) { |
| 62 | initiallySelectedValues.forEach(value => this._markSelected(value)); |
| 63 | } else { |
| 64 | this._markSelected(initiallySelectedValues[0]); |
| 65 | } |
| 66 | |
| 67 | // Clear the array in order to avoid firing the change event for preselected values. |
| 68 | this._selectedToEmit.length = 0; |
| 69 | } |
| 70 | } |
| 71 |
nothing calls this directly
no test coverage detected
searching dependent graphs…