forked from syncfusion/ej2-javascript-ui-controls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathradio-button.ts
588 lines (546 loc) · 20.5 KB
/
radio-button.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import { Component, INotifyPropertyChanged, rippleEffect, NotifyPropertyChanges, Property, closest, setValue } from '@syncfusion/ej2-base';
import { addClass, getInstance, getUniqueID, isRippleEnabled, removeClass, attributes, isNullOrUndefined } from '@syncfusion/ej2-base';
import { BaseEventArgs, detach, EmitType, Event, EventHandler, SanitizeHtmlHelper } from '@syncfusion/ej2-base';
import { wrapperInitialize, rippleMouseHandler } from './../common/common';
import { RadioButtonModel } from './radio-button-model';
/**
* Defines the label position of Radio Button.
* ```props
* After :- When the label is positioned After, it appears to the right of the Radio Button.
* Before :- When the label is positioned Before, it appears to the left of the Radio Button.
* ```
*/
export type RadioLabelPosition = 'After' | 'Before';
const LABEL: string = 'e-label';
const RIPPLE: string = 'e-ripple-container';
const RTL: string = 'e-rtl';
const WRAPPER: string = 'e-radio-wrapper';
const ATTRIBUTES: string[] = ['title', 'class', 'style', 'disabled', 'readonly', 'name', 'value', 'id'];
/**
* The RadioButton is a graphical user interface element that allows you to select one option from the choices.
* It contains checked and unchecked states.
* ```html
* <input type="radio" id="radio"/>
* <script>
* var radioObj = new RadioButton({ label: "Default" });
* radioObj.appendTo("#radio");
* </script>
* ```
*/
@NotifyPropertyChanges
export class RadioButton extends Component<HTMLInputElement> implements INotifyPropertyChanged {
private tagName: string;
private isFocused: boolean = false;
private formElement: HTMLFormElement;
private initialCheckedValue: boolean;
private angularValue: string;
private wrapper: Element;
private type: string = 'radio';
/**
* Event trigger when the RadioButton state has been changed by user interaction.
*
* @event change
*/
@Event()
public change: EmitType<ChangeArgs>;
/**
* Triggers once the component rendering is completed.
*
* @event created
*/
@Event()
public created: EmitType<Event>;
/**
* Specifies a value that indicates whether the RadioButton is `checked` or not.
* When set to `true`, the RadioButton will be in `checked` state.
*
* @default false
*/
@Property(false)
public checked: boolean;
/**
* Defines class/multiple classes separated by a space in the RadioButton element.
* You can add custom styles to the RadioButton by using this property.
*
* @default ''
*/
@Property('')
public cssClass: string;
/**
* Specifies a value that indicates whether the RadioButton is `disabled` or not.
* When set to `true`, the RadioButton will be in `disabled` state.
*
* @default false
*/
@Property(false)
public disabled: boolean;
/**
* Defines the caption for the RadioButton, that describes the purpose of the RadioButton.
*
* @default ''
*/
@Property('')
public label: string;
/**
* Positions label `before`/`after` the RadioButton.
* The possible values are:
* * Before: The label is positioned to left of the RadioButton.
* * After: The label is positioned to right of the RadioButton.
*
* @default 'After'
*/
@Property('After')
public labelPosition: RadioLabelPosition;
/**
* Defines `name` attribute for the RadioButton.
* It is used to reference form data (RadioButton value) after a form is submitted.
*
* @default ''
*/
@Property('')
public name: string;
/**
* Defines `value` attribute for the RadioButton.
* It is a form data passed to the server when submitting the form.
*
* @default ''
*/
@Property('')
public value: string;
/**
* Specifies whether to enable the rendering of untrusted HTML values in the Radio Button component.
* If 'enableHtmlSanitizer' set to true, the component will sanitize any suspected untrusted strings and scripts before rendering them.
*
* @default true
*/
@Property(true)
public enableHtmlSanitizer: boolean;
/**
* You can add the additional html attributes such as disabled, value etc., to the element.
* If you configured both property and equivalent html attribute then the component considers the property value.
*
* @default {}
*/
@Property({})
public htmlAttributes: { [key: string]: string; };
/**
* Constructor for creating the widget
*
* @private
* @param {RadioButtonModel} options - Specifies Radio button model
* @param {string | HTMLInputElement} element - Specifies target element
*/
constructor(options?: RadioButtonModel, element?: string | HTMLInputElement) {
super(options, <string | HTMLInputElement>element);
}
private changeHandler(event: Event): void {
this.checked = true;
this.dataBind();
let value: string | boolean = this.element.getAttribute('value') as string;
value = this.isVue && value ? this.element.value : this.value;
const type: string = typeof this.value;
if (this.isVue && type === 'boolean') {
value = value === 'true' ? true : false;
}
this.trigger('change', <ChangeArgs>{ value: value, event: event });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((this as any).isAngular) {
event.stopPropagation();
}
}
private updateChange(): void {
let input: HTMLInputElement; let instance: RadioButton;
const radioGrp: NodeListOf<Element> = this.getRadioGroup();
for (let i: number = 0; i < radioGrp.length; i++) {
input = radioGrp[i as number] as HTMLInputElement;
if (input !== this.element) {
instance = getInstance(input, RadioButton) as RadioButton;
instance.checked = false;
if (this.tagName === 'EJS-RADIOBUTTON') { instance.angularValue = this.value; }
}
}
}
/**
* Destroys the widget.
*
* @returns {void}
*/
public destroy(): void {
const radioWrap: Element = this.wrapper;
super.destroy();
if (radioWrap) {
if (!this.disabled) {
this.unWireEvents();
}
if (this.tagName === 'INPUT') {
if (radioWrap.parentNode) {
radioWrap.parentNode.insertBefore(this.element, radioWrap);
}
detach(radioWrap);
this.element.checked = false;
['name', 'value', 'disabled'].forEach((key: string) => {
this.element.removeAttribute(key);
});
} else {
['role', 'aria-checked', 'class'].forEach((key: string) => {
radioWrap.removeAttribute(key);
});
radioWrap.innerHTML = '';
this.element = this.wrapper as HTMLInputElement;
if (this.refreshing) {
['e-control', 'e-radio', 'e-lib'].forEach((key: string) => {
this.element.classList.add(key);
});
setValue('ej2_instances', [this], this.element);
}
}
}
}
private focusHandler(): void {
this.isFocused = true;
}
private focusOutHandler(): void {
const label: Element = this.getLabel() as Element;
if (label) {
label.classList.remove('e-focus');
}
}
protected getModuleName(): string {
return 'radio';
}
/**
* To get the value of selected radio button in a group.
*
* @method getSelectedValue
* @returns {string} - Selected Value
*/
public getSelectedValue(): string {
let input: HTMLInputElement; const radioGrp: NodeListOf<Element> = this.getRadioGroup();
for (let i: number = 0, len: number = radioGrp.length; i < len; i++) {
input = radioGrp[i as number] as HTMLInputElement;
if (input.checked ) { return input.value; }
}
return '';
}
private getRadioGroup(): NodeListOf<Element> {
return document.querySelectorAll('input.e-radio[name="' + this.element.getAttribute('name') + '"]');
}
/**
* Gets the properties to be maintained in the persistence state.
*
* @private
* @returns {string} - Persist Data
*/
public getPersistData(): string {
return this.addOnPersist(['checked']);
}
private getWrapper(): Element | null {
if (this.element.parentElement) {
return this.element.parentElement;
} else {
return null;
}
}
private getLabel(): Element | null {
if (this.element.nextElementSibling) {
return this.element.nextElementSibling;
} else {
return null;
}
}
private initialize(): void {
if (isNullOrUndefined(this.initialCheckedValue)) {
this.initialCheckedValue = this.checked;
}
this.initWrapper();
this.updateHtmlAttribute();
if (this.name) {
this.element.setAttribute('name', this.name);
}
let value: string | boolean = this.element.getAttribute('value') as string;
const type: string = typeof this.value;
if (this.isVue && type === 'boolean') {
value = value === 'true' ? true : false;
}
if (this.isVue ? this.value && type !== 'boolean' && !value : this.value) {
this.element.setAttribute('value', this.value);
}
if (this.checked) {
this.element.checked = true;
}
if (this.disabled) {
this.setDisabled();
}
}
private initWrapper(): void {
let rippleSpan: Element;
let wrapper: Element = this.element.parentElement as Element;
if (!wrapper.classList.contains(WRAPPER)) {
wrapper = this.createElement('div', { className: WRAPPER });
if (this.element.parentNode) {
this.element.parentNode.insertBefore(wrapper as Node, this.element);
}
}
const label: HTMLElement = this.createElement('label', { attrs: { for: this.element.id } });
wrapper.appendChild(this.element);
wrapper.appendChild(label);
if (isRippleEnabled) {
rippleSpan = this.createElement('span', { className: (RIPPLE) });
label.appendChild(rippleSpan);
rippleEffect(rippleSpan as HTMLElement, {
duration: 400,
isCenterRipple: true
});
}
wrapper.classList.add('e-wrapper');
if (this.enableRtl) {
label.classList.add(RTL);
}
if (this.cssClass) {
addClass([wrapper], this.cssClass.replace(/\s+/g, ' ').trim().split(' '));
}
if (this.label) {
this.setText(this.label);
}
}
private keyUpHandler(): void {
if (this.isFocused) {
(this.getLabel() as Element).classList.add('e-focus');
}
}
private labelMouseDownHandler(e: MouseEvent): void {
const rippleSpan: Element = (this.getLabel() as Element).getElementsByClassName(RIPPLE)[0];
rippleMouseHandler(e, rippleSpan);
}
private labelMouseLeaveHandler(e: MouseEvent): void {
const rippleSpan: Element = (this.getLabel() as Element).getElementsByClassName(RIPPLE)[0];
if (rippleSpan) {
const rippleElem: NodeListOf<Element> = rippleSpan.querySelectorAll('.e-ripple-element');
for (let i: number = rippleElem.length - 1; i > 0; i--) {
rippleSpan.removeChild(rippleSpan.childNodes[i as number]);
}
rippleMouseHandler(e, rippleSpan);
}
}
private labelMouseUpHandler(e: MouseEvent): void {
const rippleSpan: Element = (this.getLabel() as Element).getElementsByClassName(RIPPLE)[0];
if (rippleSpan) {
const rippleElem: NodeListOf<Element> = rippleSpan.querySelectorAll('.e-ripple-element');
for (let i: number = rippleElem.length - 1; i > 0; i--) {
rippleSpan.removeChild(rippleSpan.childNodes[i as number]);
}
rippleMouseHandler(e, rippleSpan);
}
}
private formResetHandler(): void {
this.checked = this.initialCheckedValue;
if (this.initialCheckedValue) {
attributes(this.element, { 'checked' : 'true'});
}
}
/**
* Called internally if any of the property value changes.
*
* @private
* @param {RadioButtonModel} newProp - Specifies New Properties
* @param {RadioButtonModel} oldProp - Specifies Old Properties
* @returns {void}
*/
public onPropertyChanged(newProp: RadioButtonModel, oldProp: RadioButtonModel): void {
const wrap: Element = this.getWrapper() as Element;
const label: Element = this.getLabel() as Element;
for (const prop of Object.keys(newProp)) {
switch (prop) {
case 'checked':
if (newProp.checked) {
this.updateChange();
}
this.element.checked = newProp.checked as boolean;
break;
case 'disabled':
if (newProp.disabled) {
this.setDisabled();
this.unWireEvents();
} else {
this.element.disabled = false;
this.wireEvents();
}
break;
case 'cssClass':
if (oldProp.cssClass) {
removeClass([wrap], oldProp.cssClass.split(' '));
}
if (newProp.cssClass) {
addClass([wrap], newProp.cssClass.replace(/\s+/g, ' ').trim().split(' '));
}
break;
case 'enableRtl':
if (newProp.enableRtl) {
label.classList.add(RTL);
} else {
label.classList.remove(RTL);
}
break;
case 'label':
this.setText(newProp.label as string);
break;
case 'labelPosition':
if (newProp.labelPosition === 'Before') {
label.classList.add('e-right');
} else {
label.classList.remove('e-right');
}
break;
case 'name':
this.element.setAttribute('name', newProp.name as string);
break;
case 'value':
// eslint-disable-next-line no-case-declarations
const type: string | undefined = typeof this.htmlAttributes.value;
if (!isNullOrUndefined(this.htmlAttributes) && (this.htmlAttributes.value || type === 'boolean' && !this.htmlAttributes.value)) { break; }
this.element.setAttribute('value', newProp.value as string);
break;
case 'htmlAttributes':
this.updateHtmlAttribute();
break;
}
}
}
/**
* Initialize checked Property, Angular and React and Unique ID support.
*
* @private
* @returns {void}
*/
protected preRender(): void {
let element: HTMLInputElement = this.element;
this.formElement = <HTMLFormElement>closest(this.element, 'form');
this.tagName = this.element.tagName;
element = wrapperInitialize(this.createElement, 'EJS-RADIOBUTTON', 'radio', element, WRAPPER, 'radio');
this.element = element;
if (this.element.getAttribute('type') !== 'radio') {
this.element.setAttribute('type', 'radio');
}
if (!this.element.id) {
this.element.id = getUniqueID('e-' + this.getModuleName());
}
if (this.tagName === 'EJS-RADIOBUTTON') {
const formControlName: string = this.element.getAttribute('formcontrolname') as string;
if (formControlName) {
this.setProperties({ 'name': formControlName }, true); this.element.setAttribute('name', formControlName);
}
}
}
/**
* Initialize the control rendering
*
* @private
* @returns {void}
*/
protected render(): void {
this.initialize();
if (!this.disabled) {
this.wireEvents();
}
this.renderComplete();
this.wrapper = this.getWrapper() as Element;
}
private setDisabled(): void {
this.element.disabled = true;
}
private setText(text: string): void {
const label: Element = this.getLabel() as Element;
let textLabel: Element = label.getElementsByClassName(LABEL)[0];
if (textLabel) {
textLabel.textContent = text;
} else {
text = (this.enableHtmlSanitizer) ? SanitizeHtmlHelper.sanitize(text) : text;
textLabel = this.createElement('span', { className: LABEL, innerHTML: text });
label.appendChild(textLabel);
}
if (this.labelPosition === 'Before') {
(this.getLabel() as Element).classList.add('e-right');
} else {
(this.getLabel() as Element).classList.remove('e-right');
}
}
private updateHtmlAttribute(): void {
if (!isNullOrUndefined(this.htmlAttributes)) {
for (const key of Object.keys(this.htmlAttributes)) {
const wrapper: Element = this.element.parentElement as Element;
if (ATTRIBUTES.indexOf(key) > -1) {
if (key === 'class') {
addClass([wrapper], this.htmlAttributes[`${key}`].replace(/\s+/g, ' ').trim().split(' '));
} else if (key === 'title' || key === 'style') {
wrapper.setAttribute(key, this.htmlAttributes[`${key}`]);
} else {
this.element.setAttribute(key, this.htmlAttributes[`${key}`]);
}
} else {
wrapper.setAttribute(key, this.htmlAttributes[`${key}`]);
}
}
}
}
protected unWireEvents(): void {
const label: Element = this.wrapper;
EventHandler.remove(this.element, 'change', this.changeHandler);
EventHandler.remove(this.element, 'focus', this.focusHandler);
EventHandler.remove(this.element, 'focusout', this.focusOutHandler);
EventHandler.remove(this.element, 'keyup', this.keyUpHandler);
const rippleLabel: Element = label.getElementsByTagName('label')[0];
if (rippleLabel) {
EventHandler.remove(rippleLabel, 'mousedown', this.labelMouseDownHandler);
EventHandler.remove(rippleLabel, 'mouseup', this.labelMouseUpHandler);
EventHandler.remove(rippleLabel, 'mouseleave', this.labelMouseLeaveHandler);
}
if (this.formElement) {
EventHandler.remove(this.formElement, 'reset', this.formResetHandler);
}
}
protected wireEvents(): void {
const label: Element = this.getLabel() as Element;
EventHandler.add(this.element, 'change', this.changeHandler, this);
EventHandler.add(this.element, 'keyup', this.keyUpHandler, this);
EventHandler.add(this.element, 'focus', this.focusHandler, this);
EventHandler.add(this.element, 'focusout', this.focusOutHandler, this);
const rippleLabel: Element = label.getElementsByClassName(LABEL)[0];
if (rippleLabel) {
EventHandler.add(rippleLabel, 'mousedown', this.labelMouseDownHandler, this);
EventHandler.add(rippleLabel, 'mouseup', this.labelMouseUpHandler, this);
EventHandler.add(rippleLabel, 'mouseleave', this.labelMouseLeaveHandler, this);
}
if (this.formElement) {
EventHandler.add(this.formElement, 'reset', this.formResetHandler, this);
}
}
/**
* Click the RadioButton element
* its native method
*
* @public
* @returns {void}
*/
public click(): void {
this.element.click();
}
/**
* Sets the focus to RadioButton
* its native method
*
* @public
* @returns {void}
*/
public focusIn(): void {
this.element.focus();
}
}
/**
* Interface for Radio Button change event arguments.
*/
export interface ChangeArgs extends BaseEventArgs {
/** Returns the value of the RadioButton. */
value?: string;
/** Returns the event parameters of the RadioButton. */
event?: Event;
}