This repository has been archived by the owner on Sep 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
switch.ts
301 lines (262 loc) · 8.89 KB
/
switch.ts
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/**
* @license
* Copyright 2019 Dynatrace LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FocusMonitor, FocusOrigin } from '@angular/cdk/a11y';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import {
AfterViewInit,
Attribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Directive,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Output,
Provider,
Renderer2,
ViewChild,
ViewEncapsulation,
forwardRef,
} from '@angular/core';
import {
CheckboxRequiredValidator,
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
} from '@angular/forms';
import {
CanDisable,
HasTabIndex,
mixinDisabled,
mixinTabIndex,
} from '@dynatrace/barista-components/core';
// Increasing integer for generating unique ids for switch components.
let nextUniqueId = 0;
/**
* Provider Expression that allows dt-switch to register as a ControlValueAccessor.
* This allows it to support [(ngModel)].
*/
export const DT_SWITCH_CONTROL_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
// tslint:disable-next-line: no-use-before-declare no-forward-ref
useExisting: forwardRef(() => DtSwitch),
multi: true,
};
/** Change event object emitted by DtSwitch */
export interface DtSwitchChange<T> {
source: DtSwitch<T>;
checked: boolean;
}
// Boilerplate for applying mixins to DtSwitch.
export class DtSwitchBase {}
export const _DtSwitchMixinBase = mixinTabIndex(mixinDisabled(DtSwitchBase));
@Component({
selector: 'dt-switch',
templateUrl: 'switch.html',
styleUrls: ['switch.scss'],
exportAs: 'dtSwitch',
inputs: ['disabled', 'tabIndex'],
host: {
class: 'dt-switch',
'[id]': 'id',
'[class.dt-switch-checked]': 'checked',
'[class.dt-switch-disabled]': 'disabled',
'(focus)': '_inputElement.nativeElement.focus()',
},
providers: [DT_SWITCH_CONTROL_VALUE_ACCESSOR],
preserveWhitespaces: false,
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.Emulated,
})
export class DtSwitch<T> extends _DtSwitchMixinBase
implements
CanDisable,
HasTabIndex,
OnDestroy,
AfterViewInit,
ControlValueAccessor {
/** Whether or not the switch is checked. */
@Input()
get checked(): boolean {
return this._checked;
}
set checked(value: boolean) {
const coercedValue = coerceBooleanProperty(value);
if (coercedValue !== this._checked) {
this._checked = coercedValue;
this._changeDetectorRef.markForCheck();
}
}
/** Unique id of the element. */
@Input()
get id(): string {
return this._id;
}
set id(value: string) {
this._id = value || this._uid;
}
/** Whether the switch is required. */
@Input()
get required(): boolean {
return this._required;
}
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
}
/**
* Whether the switch is disabled. This fully overrides the implementation provided by
* mixinDisabled, but the mixin is still required because mixinTabIndex requires it.
*/
@Input()
get disabled(): boolean {
return this._disabled;
}
set disabled(value: boolean) {
if (value !== this.disabled) {
this._disabled = coerceBooleanProperty(value);
this._changeDetectorRef.markForCheck();
}
}
/** Name value will be applied to the input element if present */
@Input() name: string | null = null;
/** The value attribute of the native input element */
@Input() value: T;
/** The 'aria-labelledby' attribute takes precedence as the element's text alternative. */
// tslint:disable-next-line:no-input-rename
@Input('aria-label') ariaLabel = '';
/** The 'aria-describedby' attribute is read after the element's label and field type. */
// tslint:disable-next-line:no-input-rename
@Input('aria-labelledby') ariaLabelledby: string | null = null;
/** Event emitted when the switch's `checked` value changes. */
// Disabling no-output-native rule because we want to keep a similar API to the checkbox
// tslint:disable-next-line: no-output-native
@Output() readonly change = new EventEmitter<DtSwitchChange<T>>();
/** @internal The native switch input element */
@ViewChild('input', { static: true }) _inputElement: ElementRef;
/** Returns the unique id for the visual hidden input. */
get inputId(): string {
return `${this.id}-input`;
}
/** @internal Implemented as part of the ControlValueAccessor */
_onTouched: () => void = () => {};
private _checked = false;
private _uid = `dt-switch-${nextUniqueId++}`;
private _id: string;
private _required: boolean;
private _disabled = false;
private _controlValueAccessorChangeFn: (value: boolean) => void = () => {};
constructor(
private _renderer: Renderer2,
private _changeDetectorRef: ChangeDetectorRef,
private _elementRef: ElementRef,
private _focusMonitor: FocusMonitor,
@Attribute('tabindex') tabIndex: string,
) {
super();
// Force setter to be called in case id was not specified.
this.id = this.id;
this.tabIndex = parseInt(tabIndex, 10) || 0;
}
ngAfterViewInit(): void {
this._focusMonitor
.monitor(this._inputElement.nativeElement, false)
.subscribe(focusOrigin => {
this._onInputFocusChange(focusOrigin);
});
}
ngOnDestroy(): void {
this._focusMonitor.stopMonitoring(this._inputElement.nativeElement);
}
/** Toggles the checked state of the switch */
toggle(): void {
this.checked = !this.checked;
}
/** @internal Handles clicking the hidden input element */
_handleInputClick(event: Event): void {
// We have to stop propagation for click events on the visual hidden input element.
// Otherwise this will lead to multiple click events.
event.stopPropagation();
}
/** @internal Handles the input change event */
_handleInputChange(event: Event): void {
// We always have to stop propagation on the change event.
// Otherwise the change event, from the input element, will bubble up and
// emit its event object to the `change` output.
event.stopPropagation();
this.checked = this._inputElement.nativeElement.checked;
// Emit our custom change event only if the underlying input emitted one. This ensures that
// there is no change event, when the checked state changes programmatically.
this._emitChangeEvent();
}
/** @internal Transforms the checked state to a string so it can be set as aria-checked. */
_getAriaChecked(): 'true' | 'false' {
return this.checked ? 'true' : 'false';
}
/** Implemented as a part of ControlValueAccessor. */
writeValue(value: boolean): void {
this.checked = !!value;
}
/** Implemented as a part of ControlValueAccessor. */
registerOnChange(fn: (value: boolean) => void): void {
this._controlValueAccessorChangeFn = fn;
}
/** Implemented as a part of ControlValueAccessor. */
registerOnTouched(fn: () => void = () => {}): void {
this._onTouched = fn;
}
/** Implemented as a part of ControlValueAccessor. */
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this._changeDetectorRef.markForCheck();
}
/** Focuses the slide-toggle. */
focus(): void {
this._focusMonitor.focusVia(this._inputElement.nativeElement, 'keyboard');
}
private _onInputFocusChange(focusOrigin: FocusOrigin): void {
const element = this._elementRef.nativeElement;
if (focusOrigin === 'keyboard') {
this._renderer.addClass(element, 'dt-switch-focused');
} else if (!focusOrigin) {
this._renderer.removeClass(element, 'dt-switch-focused');
this._onTouched();
}
}
private _emitChangeEvent(): void {
this._controlValueAccessorChangeFn(this.checked);
this.change.emit({ source: this, checked: this.checked });
}
}
export const DT_SWITCH_REQUIRED_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
// tslint:disable-next-line: no-use-before-declare no-forward-ref
useExisting: forwardRef(() => DtSwitchRequiredValidator),
multi: true,
};
/**
* Validator for checkbox's required attribute in template-driven checkbox.
* TODO @alexfrasst: Remove once CheckboxRequiredValidator supports custom checkbox
*/
@Directive({
selector: `dt-switch[required][formControlName],
dt-switch[required][formControl], dt-switch[required][ngModel]`,
exportAs: 'dtSwitchRequiredValidator',
providers: [DT_SWITCH_REQUIRED_VALIDATOR],
host: { '[attr.required]': 'required ? "" : null' },
})
export class DtSwitchRequiredValidator extends CheckboxRequiredValidator {}