/
checkbox.ts
398 lines (336 loc) · 12.5 KB
/
checkbox.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import {
ChangeDetectorRef,
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Input,
Output,
Renderer,
ViewEncapsulation,
forwardRef,
NgModule,
ModuleWithProviders,
ViewChild,
} from '@angular/core';
import {CommonModule} from '@angular/common';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/forms';
import {coerceBooleanProperty} from '../core/coersion/boolean-property';
import {MdRippleModule, DefaultStyleCompatibilityModeModule} from '../core';
import {ViewportRuler} from '../core/overlay/position/viewport-ruler';
/**
* Monotonically increasing integer used to auto-generate unique ids for checkbox components.
*/
let nextId = 0;
/**
* Provider Expression that allows md-checkbox to register as a ControlValueAccessor. This allows it
* to support [(ngModel)].
*/
export const MD_CHECKBOX_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MdCheckbox),
multi: true
};
/**
* Represents the different states that require custom transitions between them.
*/
export enum TransitionCheckState {
/** The initial state of the component before any user interaction. */
Init,
/** The state representing the component when it's becoming checked. */
Checked,
/** The state representing the component when it's becoming unchecked. */
Unchecked,
/** The state representing the component when it's becoming indeterminate. */
Indeterminate
}
// A simple change event emitted by the MdCheckbox component.
export class MdCheckboxChange {
source: MdCheckbox;
checked: boolean;
}
/**
* A material design checkbox component. Supports all of the functionality of an HTML5 checkbox,
* and exposes a similar API. An MdCheckbox can be either checked, unchecked, indeterminate, or
* disabled. Note that all additional accessibility attributes are taken care of by the component,
* so there is no need to provide them yourself. However, if you want to omit a label and still
* have the checkbox be accessible, you may supply an [aria-label] input.
* See: https://www.google.com/design/spec/components/selection-controls.html
*/
@Component({
moduleId: module.id,
selector: 'md-checkbox, mat-checkbox',
templateUrl: 'checkbox.html',
styleUrls: ['checkbox.css'],
host: {
'[class.md-checkbox-indeterminate]': 'indeterminate',
'[class.md-checkbox-checked]': 'checked',
'[class.md-checkbox-disabled]': 'disabled',
'[class.md-checkbox-align-end]': 'align == "end"',
'[class.md-checkbox-focused]': 'hasFocus',
},
providers: [MD_CHECKBOX_CONTROL_VALUE_ACCESSOR],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MdCheckbox implements ControlValueAccessor {
/**
* Attached to the aria-label attribute of the host element. In most cases, arial-labelledby will
* take precedence so this may be omitted.
*/
@Input('aria-label') ariaLabel: string = '';
/**
* Users can specify the `aria-labelledby` attribute which will be forwarded to the input element
*/
@Input('aria-labelledby') ariaLabelledby: string = null;
/** A unique id for the checkbox. If one is not supplied, it is auto-generated. */
@Input() id: string = `md-checkbox-${++nextId}`;
/** Whether the ripple effect on click should be disabled. */
private _disableRipple: boolean;
@Input()
get disableRipple(): boolean { return this._disableRipple; }
set disableRipple(value) { this._disableRipple = coerceBooleanProperty(value); }
/** ID to be applied to the `input` element */
get inputId(): string {
return `input-${this.id}`;
}
private _required: boolean;
/** Whether the checkbox is required or not. */
@Input()
get required(): boolean { return this._required; }
set required(value) { this._required = coerceBooleanProperty(value); }
/** Whether or not the checkbox should come before or after the label. */
@Input() align: 'start' | 'end' = 'start';
private _disabled: boolean = false;
/**
* Whether the checkbox is disabled. When the checkbox is disabled it cannot be interacted with.
* The correct ARIA attributes are applied to denote this to assistive technology.
*/
@Input()
get disabled(): boolean { return this._disabled; }
set disabled(value) { this._disabled = coerceBooleanProperty(value); }
/**
* The tabindex attribute for the checkbox. Note that when the checkbox is disabled, the attribute
* on the host element will be removed. It will be placed back when the checkbox is re-enabled.
*/
@Input() tabindex: number = 0;
/** Name value will be applied to the input element if present */
@Input() name: string = null;
/** Event emitted when the checkbox's `checked` value changes. */
@Output() change: EventEmitter<MdCheckboxChange> = new EventEmitter<MdCheckboxChange>();
/** The native `<input type=checkbox> element */
@ViewChild('input') _inputElement: ElementRef;
/** Called when the checkbox is blurred. Needed to properly implement ControlValueAccessor. */
onTouched: () => any = () => {};
private _currentAnimationClass: string = '';
private _currentCheckState: TransitionCheckState = TransitionCheckState.Init;
private _checked: boolean = false;
private _indeterminate: boolean = false;
private _color: string;
private _controlValueAccessorChangeFn: (value: any) => void = (value) => {};
hasFocus: boolean = false;
constructor(private _renderer: Renderer,
private _elementRef: ElementRef,
private _changeDetectorRef: ChangeDetectorRef) {
this.color = 'accent';
}
/**
* Whether the checkbox is checked. Note that setting `checked` will immediately set
* `indeterminate` to false.
*/
@Input() get checked() {
return this._checked;
}
set checked(checked: boolean) {
if (checked != this.checked) {
this._indeterminate = false;
this._checked = checked;
this._transitionCheckState(
this._checked ? TransitionCheckState.Checked : TransitionCheckState.Unchecked);
this._changeDetectorRef.markForCheck();
}
}
/**
* Whether the checkbox is indeterminate. This is also known as "mixed" mode and can be used to
* represent a checkbox with three states, e.g. a checkbox that represents a nested list of
* checkable items. Note that whenever `checked` is set, indeterminate is immediately set to
* false. This differs from the web platform in that indeterminate state on native
* checkboxes is only remove when the user manually checks the checkbox (rather than setting the
* `checked` property programmatically). However, we feel that this behavior is more accommodating
* to the way consumers would envision using this component.
*/
@Input() get indeterminate() {
return this._indeterminate;
}
set indeterminate(indeterminate: boolean) {
this._indeterminate = indeterminate;
if (this._indeterminate) {
this._transitionCheckState(TransitionCheckState.Indeterminate);
} else {
this._transitionCheckState(
this.checked ? TransitionCheckState.Checked : TransitionCheckState.Unchecked);
}
}
/** Sets the color of the checkbox */
@Input()
get color(): string {
return this._color;
}
set color(value: string) {
this._updateColor(value);
}
_updateColor(newColor: string) {
this._setElementColor(this._color, false);
this._setElementColor(newColor, true);
this._color = newColor;
}
_setElementColor(color: string, isAdd: boolean) {
if (color != null && color != '') {
this._renderer.setElementClass(this._elementRef.nativeElement, `md-${color}`, isAdd);
}
}
_isRippleDisabled() {
return this.disableRipple || this.disabled;
}
/**
* Implemented as part of ControlValueAccessor.
* TODO: internal
*/
writeValue(value: any) {
this.checked = !!value;
}
/**
* Implemented as part of ControlValueAccessor.
* TODO: internal
*/
registerOnChange(fn: (value: any) => void) {
this._controlValueAccessorChangeFn = fn;
}
/**
* Implemented as part of ControlValueAccessor.
* TODO: internal
*/
registerOnTouched(fn: any) {
this.onTouched = fn;
}
/**
* Implemented as a part of ControlValueAccessor.
*/
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
}
private _transitionCheckState(newState: TransitionCheckState) {
let oldState = this._currentCheckState;
let renderer = this._renderer;
let elementRef = this._elementRef;
if (oldState === newState) {
return;
}
if (this._currentAnimationClass.length > 0) {
renderer.setElementClass(elementRef.nativeElement, this._currentAnimationClass, false);
}
this._currentAnimationClass = this._getAnimationClassForCheckStateTransition(
oldState, newState);
this._currentCheckState = newState;
if (this._currentAnimationClass.length > 0) {
renderer.setElementClass(elementRef.nativeElement, this._currentAnimationClass, true);
}
}
private _emitChangeEvent() {
let event = new MdCheckboxChange();
event.source = this;
event.checked = this.checked;
this._controlValueAccessorChangeFn(this.checked);
this.change.emit(event);
}
/** Informs the component when the input has focus so that we can style accordingly */
_onInputFocus() {
this.hasFocus = true;
}
/** Informs the component when we lose focus in order to style accordingly */
_onInputBlur() {
this.hasFocus = false;
this.onTouched();
}
/**
* Toggles the `checked` value between true and false
*/
toggle() {
this.checked = !this.checked;
}
/**
* Event handler for checkbox input element.
* Toggles checked state if element is not disabled.
* @param event
*/
_onInteractionEvent(event: Event) {
// 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();
if (!this.disabled) {
this.toggle();
// Emit our custom change event if the native input emitted one.
// It is important to only emit it, if the native input triggered one, because
// we don't want to trigger a change event, when the `checked` variable changes for example.
this._emitChangeEvent();
}
}
focus() {
this._renderer.invokeElementMethod(this._inputElement.nativeElement, 'focus');
this._onInputFocus();
}
_onInputClick(event: Event) {
// We have to stop propagation for click events on the visual hidden input element.
// By default, when a user clicks on a label element, a generated click event will be
// dispatched on the associated input element. Since we are using a label element as our
// root container, the click event on the `checkbox` will be executed twice.
// The real click event will bubble up, and the generated click event also tries to bubble up.
// This will lead to multiple click events.
// Preventing bubbling for the second event will solve that issue.
event.stopPropagation();
}
private _getAnimationClassForCheckStateTransition(
oldState: TransitionCheckState, newState: TransitionCheckState): string {
var animSuffix: string;
switch (oldState) {
case TransitionCheckState.Init:
// Handle edge case where user interacts with checkbox that does not have [(ngModel)] or
// [checked] bound to it.
if (newState === TransitionCheckState.Checked) {
animSuffix = 'unchecked-checked';
} else {
return '';
}
break;
case TransitionCheckState.Unchecked:
animSuffix = newState === TransitionCheckState.Checked ?
'unchecked-checked' : 'unchecked-indeterminate';
break;
case TransitionCheckState.Checked:
animSuffix = newState === TransitionCheckState.Unchecked ?
'checked-unchecked' : 'checked-indeterminate';
break;
case TransitionCheckState.Indeterminate:
animSuffix = newState === TransitionCheckState.Checked ?
'indeterminate-checked' : 'indeterminate-unchecked';
}
return `md-checkbox-anim-${animSuffix}`;
}
getHostElement() {
return this._elementRef.nativeElement;
}
}
@NgModule({
imports: [CommonModule, MdRippleModule, DefaultStyleCompatibilityModeModule],
exports: [MdCheckbox, DefaultStyleCompatibilityModeModule],
declarations: [MdCheckbox],
})
export class MdCheckboxModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: MdCheckboxModule,
providers: [ViewportRuler]
};
}
}