-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathaccordion.ts
1580 lines (1564 loc) · 64.9 KB
/
accordion.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Component, EventHandler, Property, Event, EmitType, AnimationModel, KeyboardEvents, rippleEffect, animationMode } from '@syncfusion/ej2-base';
import { KeyboardEventArgs, BaseEventArgs, Effect, getUniqueID, compile as templateCompiler } from '@syncfusion/ej2-base';
import { isVisible, closest, attributes, detach, select, addClass, removeClass, append } from '@syncfusion/ej2-base';
import { INotifyPropertyChanged, NotifyPropertyChanges, ChildProperty, Collection, Animation } from '@syncfusion/ej2-base';
import { setStyleAttribute as setStyle, Complex } from '@syncfusion/ej2-base';
import { isNullOrUndefined as isNOU, formatUnit, selectAll, SanitizeHtmlHelper, isRippleEnabled } from '@syncfusion/ej2-base';
import { AccordionModel, AccordionItemModel, AccordionAnimationSettingsModel, AccordionActionSettingsModel } from './accordion-model';
/**
* Specifies the option to expand single or multiple panel at a time.
* ```props
* Single :- Only one Accordion item can be expanded at a time.
* Multiple :- Multiple Accordion items can be expanded simultaneously.
* ```
*/
export type ExpandMode = 'Single' | 'Multiple';
type HTEle = HTMLElement;
type Str = string;
const CLS_ACRDN_ROOT: Str = 'e-acrdn-root';
const CLS_ROOT: Str = 'e-accordion';
const CLS_ITEM: Str = 'e-acrdn-item';
const CLS_ITEMFOCUS: Str = 'e-item-focus';
const CLS_ITEMHIDE: Str = 'e-hide';
const CLS_HEADER: Str = 'e-acrdn-header';
const CLS_HEADERICN: Str = 'e-acrdn-header-icon';
const CLS_HEADERCTN: Str = 'e-acrdn-header-content';
const CLS_CONTENT: Str = 'e-acrdn-panel';
const CLS_CTENT: Str = 'e-acrdn-content';
const CLS_TOOGLEICN: Str = 'e-toggle-icon';
const CLS_COLLAPSEICN: Str = 'e-tgl-collapse-icon e-icons';
const CLS_EXPANDICN: Str = 'e-expand-icon';
const CLS_RTL: Str = 'e-rtl';
const CLS_CTNHIDE: Str = 'e-content-hide';
const CLS_SLCT: Str = 'e-select';
const CLS_SLCTED: Str = 'e-selected';
const CLS_ACTIVE: Str = 'e-active';
const CLS_ANIMATE: Str = 'e-animate';
const CLS_DISABLE: Str = 'e-overlay';
const CLS_TOGANIMATE: Str = 'e-toggle-animation';
const CLS_NEST: Str = 'e-nested';
const CLS_EXPANDSTATE: Str = 'e-expand-state';
const CLS_CONTAINER: Str = 'e-accordion-container';
interface AcrdnTemplateRef {
elementRef: AcrdnElementRef
}
interface AcrdnElementRef {
nativeElement: AcrdnElementComment
}
interface AcrdnElementComment {
childNodes?: NodeList
firstChild?: HTMLElement
lastChild?: HTMLElement
nextElementSibling?: HTMLElement
parentElement?: HTMLElement
propName?: HTMLElement
data?: string
}
/** An interface that holds options to control the accordion click action. */
export interface AccordionClickArgs extends BaseEventArgs {
/** Defines the current Accordion Item Object. */
item?: AccordionItemModel
/**
* Defines the current Event arguments.
*/
originalEvent?: Event
/**
* Defines whether to cancel the Accordion click action.
* When set to `true`, the default click behavior will be prevented,
* preventing any action associated with the Accordion item click (such as expanding or collapsing the item).
* When set to `false` or omitted, the default click behavior will proceed as normal.
*/
cancel?: boolean;
}
/** An interface that holds options to control the expanding item action. */
export interface ExpandEventArgs extends BaseEventArgs {
/** Defines the current Accordion Item Object. */
item?: AccordionItemModel
/** Defines the current Accordion Item Element. */
element?: HTMLElement
/** Defines the expand/collapse state. */
isExpanded?: boolean
/** Defines the prevent action. */
cancel?: boolean
/** Defines the Accordion Item Index */
index?: number
/** Defines the Accordion Item Content */
content?: HTMLElement
}
/** An interface that holds options to control the expanded item action. */
export interface ExpandedEventArgs extends BaseEventArgs {
/** Defines the current Accordion Item Object. */
item?: AccordionItemModel
/** Defines the current Accordion Item Element. */
element?: HTMLElement
/** Defines the expand/collapse state. */
isExpanded?: boolean
/** Defines the Accordion Item Index */
index?: number
/** Defines the Accordion Item Content */
content?: HTMLElement
}
/**
* Objects used for configuring the Accordion expanding item action properties.
*/
export class AccordionActionSettings extends ChildProperty<AccordionActionSettings> {
/**
* Specifies the type of animation.
*
* @default 'SlideDown'
* @aspType string
*/
@Property('SlideDown')
public effect: 'None' | Effect;
/**
* Specifies the duration to animate.
*
* @default 400
*/
@Property(400)
public duration: number;
/**
* Specifies the animation timing function.
*
* @default 'linear'
*/
@Property('linear')
public easing: string;
}
/**
* Objects used for configuring the Accordion animation properties.
*/
export class AccordionAnimationSettings extends ChildProperty<AccordionAnimationSettings> {
/**
* Specifies the animation to appear while collapsing the Accordion item.
*
* @default { effect: 'SlideDown', duration: 400, easing: 'linear' }
*/
@Complex<AccordionActionSettingsModel>({ effect: 'SlideUp', duration: 400, easing: 'linear' }, AccordionActionSettings)
public collapse: AccordionActionSettingsModel;
/**
* Specifies the animation to appear while expanding the Accordion item.
*
* @default { effect: 'SlideDown', duration: 400, easing: 'linear' }
*/
@Complex<AccordionActionSettingsModel>({ effect: 'SlideDown', duration: 400, easing: 'linear' }, AccordionActionSettings)
public expand: AccordionActionSettingsModel;
}
/**
* An item object that is used to configure Accordion items.
*/
export class AccordionItem extends ChildProperty<AccordionItem> {
/**
* Sets the text content to be displayed for the Accordion item.
* You can set the content of the Accordion item using `content` property.
* It also supports to include the title as `HTML element`, `string`, or `query selector`.
* ```typescript
* let accordionObj: Accordion = new Accordion( {
* items: [
* { header: 'Accordion Header', content: 'Accordion Content' },
* { header: '<div>Accordion Header</div>', content: '<div>Accordion Content</div>' },
* { header: '#headerContent', content: '#panelContent' }]
* });
* accordionObj.appendTo('#accordion');
* ```
*
* @default null
*/
@Property(null)
public content: string;
/**
* Sets the header text to be displayed for the Accordion item.
* You can set the title of the Accordion item using `header` property.
* It also supports to include the title as `HTML element`, `string`, or `query selector`.
* ```typescript
* let accordionObj: Accordion = new Accordion( {
* items: [
* { header: 'Accordion Header', content: 'Accordion Content' },
* { header: '<div>Accordion Header</div>', content: '<div>Accordion Content</div>' },
* { header: '#headerContent', content: '#panelContent' }]
* });
* accordionObj.appendTo('#accordion');
* ```
*
* @default null
*/
@Property(null)
public header: string;
/**
* Defines single/multiple classes (separated by a space) are to be used for Accordion item customization.
*
* @default null
*/
@Property(null)
public cssClass: string;
/**
* Defines an icon with the given custom CSS class that is to be rendered before the header text.
* Add the css classes to the `iconCss` property and write the css styles to the defined class to set images/icons.
* Adding icon is applicable only to the header.
* ```typescript
* let accordionObj: Accordion = new Accordion( {
* items: [
* { header: 'Accordion Header', iconCss: 'e-app-icon' }]
* });
* accordionObj.appendTo('#accordion');
* ```
* ```css
* .e-app-icon::before {
* content: "\e710";
* }
* ```
*
* @default null
*/
@Property(null)
public iconCss: string;
/**
* Sets the expand (true) or collapse (false) state of the Accordion item. By default, all the items are in a collapsed state.
*
* @default false
*/
@Property(false)
public expanded: boolean;
/**
* Sets false to hide an accordion item.
*
* @default true
*/
@Property(true)
public visible: boolean;
/**
* Sets true to disable an accordion item.
*
* @default false
*/
@Property(false)
public disabled: boolean;
/**
* Sets unique ID to accordion item.
*
* @default null
*/
@Property()
public id: string;
}
/**
* The Accordion is a vertically collapsible content panel that displays one or more panels at a time within the available space.
* ```html
* <div id='accordion'/>
* <script>
* var accordionObj = new Accordion();
* accordionObj.appendTo('#accordion');
* </script>
* ```
*/
@NotifyPropertyChanges
export class Accordion extends Component<HTMLElement> implements INotifyPropertyChanged {
private lastActiveItemId: string;
private trgtEle: HTEle;
private ctrlTem: HTEle;
private keyModule: KeyboardEvents;
private initExpand: number[];
private isNested: boolean;
private isDestroy: boolean;
private templateEle: string[];
private headerTemplateFn: Function;
private itemTemplateFn: Function;
private removeRippleEffect: () => void;
/**
* Contains the keyboard configuration of the Accordion.
*/
private keyConfigs: { [key: string]: Str } = {
moveUp: 'uparrow',
moveDown: 'downarrow',
enter: 'enter',
space: 'space',
home: 'home',
end: 'end'
};
/**
* An array of item that is used to specify Accordion items.
* ```typescript
* let accordionObj: Accordion = new Accordion( {
* items: [
* { header: 'Accordion Header', content: 'Accordion Content' }]
* });
* accordionObj.appendTo('#accordion');
* ```
*
* @default []
*/
@Collection<AccordionItemModel>([], AccordionItem)
public items: AccordionItemModel[];
/**
* Specifies the datasource for the accordion items.
*
* @isdatamanager false
* @default []
*/
@Property([])
public dataSource: Object[];
/**
* Specifies the template option for accordion items.
*
* @default null
* @angularType string | object
* @reactType string | function | JSX.Element
* @vueType string | function
* @aspType string
*/
@Property()
public itemTemplate: string | Function;
/**
* Specifies the header title template option for accordion items.
*
* @default null
* @angularType string | object
* @reactType string | function | JSX.Element
* @vueType string | function
* @aspType string
*/
@Property()
public headerTemplate: string | Function;
/**
* Specifies the width of the Accordion in pixels/number/percentage. Number value is considered as pixels.
*
* @default '100%'
*/
@Property('100%')
public width: string | number;
/**
* Specifies the height of the Accordion in pixels/number/percentage. Number value is considered as pixels.
*
* @default 'auto'
*/
@Property('auto')
public height: string | number;
/**
* Specifies the expanded items at initial load.
*
* @default []
*/
@Property([])
public expandedIndices: number[];
/**
* Specifies the options to expand single or multiple panel at a time.
* The possible values are:
* * `Single`: Sets to expand only one Accordion item at a time.
* * `Multiple`: Sets to expand more than one Accordion item at a time.
*
* @default 'Multiple'
*/
@Property('Multiple')
public expandMode: ExpandMode;
/**
* Specifies whether to enable the rendering of untrusted HTML values in the Accordion component.
* When this property is enabled, the component will sanitize any suspected untrusted strings and scripts before rendering them.
*
* @default true
*/
@Property(true)
public enableHtmlSanitizer: boolean;
/**
* Specifies the animation configuration settings for expanding and collapsing the panel.
*
* @default { expand: { effect: 'SlideDown', duration: 400, easing: 'linear' },
* collapse: { effect: 'SlideUp', duration: 400, easing: 'linear' }}
*/
@Complex<AccordionAnimationSettingsModel>({}, AccordionAnimationSettings)
public animation: AccordionAnimationSettingsModel;
/**
* The event will be fired while clicking anywhere within the Accordion.
*
* @event clicked
*/
@Event()
public clicked: EmitType<AccordionClickArgs>;
/**
* The event will be fired before the item gets collapsed/expanded.
*
* @event expanding
*/
@Event()
public expanding: EmitType<ExpandEventArgs>;
/**
* The event will be fired after the item gets collapsed/expanded.
*
* @event expanded
*/
@Event()
public expanded: EmitType<ExpandedEventArgs>;
/**
* The event will be fired once the control rendering is completed.
*
* @event created
*/
@Event()
public created: EmitType<Event>;
/**
* The event will be fired when the control gets destroyed.
*
* @event destroyed
*/
@Event()
public destroyed: EmitType<Event>;
/**
* Initializes a new instance of the Accordion class.
*
* @param {AccordionModel} options - Specifies Accordion model properties as options.
* @param {string | HTMLElement} element - Specifies the element that is rendered as an Accordion.
*/
public constructor(options?: AccordionModel, element?: string | HTMLElement) {
super(options, <HTEle | Str>element);
}
/**
* Removes the control from the DOM and also removes all its related events.
*
* @returns {void}
*/
public destroy(): void {
if (this.isReact || this.isAngular || this.isVue) {
this.clearTemplate();
}
const ele: HTEle = this.element;
super.destroy();
this.unWireEvents();
this.isDestroy = true;
this.restoreContent(null);
[].slice.call(ele.children).forEach((el: HTEle) => {
ele.removeChild(el);
});
if (this.trgtEle) {
this.trgtEle = null;
while (this.ctrlTem.firstElementChild) {
ele.appendChild(this.ctrlTem.firstElementChild);
}
this.ctrlTem = null;
}
ele.classList.remove(CLS_ACRDN_ROOT);
ele.removeAttribute('style');
this.element.removeAttribute('data-ripple');
if (!this.isNested && isRippleEnabled) {
this.removeRippleEffect();
}
}
protected preRender(): void {
const nested: Element = closest(this.element, '.' + CLS_CONTENT);
this.isNested = false;
this.templateEle = [];
if (!this.isDestroy) {
this.isDestroy = false;
}
if (nested && nested.firstElementChild && nested.firstElementChild.firstElementChild) {
if (nested.firstElementChild.firstElementChild.classList.contains(CLS_ROOT)) {
nested.classList.add(CLS_NEST);
this.isNested = true;
}
} else {
this.element.classList.add(CLS_ACRDN_ROOT);
}
if (this.enableRtl) {
this.add(this.element, CLS_RTL);
}
}
private add(ele: HTEle, val: Str): void {
ele.classList.add(val);
}
private remove(ele: HTEle, val: Str): void {
ele.classList.remove(val);
}
/**
* To initialize the control rendering
*
* @private
* @returns {void}
*/
protected render(): void {
this.initializeHeaderTemplate();
this.initializeItemTemplate();
this.initialize();
this.renderControl();
this.wireEvents();
this.renderComplete();
}
private initialize(): void {
const width: Str = formatUnit(this.width);
const height: Str = formatUnit(this.height);
setStyle(this.element, { 'width': width, 'height': height });
if (isNOU(this.initExpand)) {
this.initExpand = [];
}
if (!isNOU(this.expandedIndices) && this.expandedIndices.length > 0) {
this.initExpand = this.expandedIndices;
}
}
private renderControl(): void {
this.trgtEle = (this.element.children.length > 0) ? <HTEle>select('div', this.element) : null;
this.renderItems();
this.initItemExpand();
}
private wireFocusEvents(): void {
const acrdItem: HTEle[] = [].slice.call(this.element.querySelectorAll('.' + CLS_ITEM));
for (const item of acrdItem) {
const headerEle: Element = item.querySelector('.' + CLS_HEADER);
if (item.childElementCount > 0 && headerEle) {
EventHandler.clearEvents(headerEle);
EventHandler.add(headerEle, 'focus', this.focusIn, this);
EventHandler.add(headerEle, 'blur', this.focusOut, this);
}
}
}
private unWireEvents(): void {
EventHandler.remove(this.element, 'click', this.clickHandler);
if (!isNOU(this.keyModule)) {
this.keyModule.destroy();
}
}
private wireEvents(): void {
EventHandler.add(this.element, 'click', this.clickHandler, this);
if (!this.isNested && !this.isDestroy) {
this.removeRippleEffect = rippleEffect(this.element, { selector: '.' + CLS_HEADER });
}
if (!this.isNested) {
this.keyModule = new KeyboardEvents(
this.element,
{
keyAction: this.keyActionHandler.bind(this),
keyConfigs: this.keyConfigs,
eventName: 'keydown'
});
}
}
private templateParser(template: string | Function): (template: string | Function) => NodeList | undefined {
if (template) {
try {
if (typeof template !== 'function' && document.querySelectorAll(template).length) {
return templateCompiler(document.querySelector(template).innerHTML.trim());
} else {
return templateCompiler(template);
}
} catch (error) {
return templateCompiler(template);
}
}
return undefined;
}
private initializeHeaderTemplate(): void {
if (this.headerTemplate) {
this.headerTemplateFn = this.templateParser(this.headerTemplate);
}
}
private initializeItemTemplate(): void {
if (this.itemTemplate) {
this.itemTemplateFn = this.templateParser(this.itemTemplate);
}
}
private getHeaderTemplate(): Function {
return this.headerTemplateFn;
}
private getItemTemplate(): Function {
return this.itemTemplateFn;
}
private focusIn(e: FocusEvent): void {
(<HTEle>e.target).parentElement.classList.add(CLS_ITEMFOCUS);
}
private focusOut(e: FocusEvent): void {
(<HTEle>e.target).parentElement.classList.remove(CLS_ITEMFOCUS);
}
private ctrlTemplate(): void {
this.ctrlTem = <HTEle>this.element.cloneNode(true);
let innerEles: HTMLCollection;
const rootEle: HTMLElement = <HTMLElement>select('.' + CLS_CONTAINER, this.element);
if (rootEle) {
innerEles = rootEle.children as HTMLCollection;
} else {
innerEles = this.element.children as HTMLCollection;
}
const items: AccordionItemModel[] = [];
[].slice.call(innerEles).forEach((el: HTEle) => {
items.push({
header: (el.childElementCount > 0 && el.children[0]) ? (el.children[0]) as any : '',
content: (el.childElementCount > 1 && el.children[1]) ? (el.children[1]) as any : ''
});
el.parentNode.removeChild(el);
});
if (rootEle) {
this.element.removeChild(rootEle);
}
this.setProperties({ items: items }, true);
}
private toggleIconGenerate(): HTEle {
const tglIcon: HTEle = this.createElement('div', { className: CLS_TOOGLEICN });
const hdrColIcon: HTEle = this.createElement('span', { className: CLS_COLLAPSEICN });
tglIcon.appendChild(hdrColIcon);
return tglIcon;
}
private initItemExpand(): void {
const len: number = this.initExpand.length;
if (len === 0) {
return;
}
if (this.expandMode === 'Single') {
this.expandItem(true, this.initExpand[len - 1]);
} else {
for (let i: number = 0; i < len; i++) {
this.expandItem(true, this.initExpand[parseInt(i.toString(), 10)]);
}
}
if (this.isReact) {
this.renderReactTemplates();
}
}
private renderItems(): void {
const ele: HTEle = this.element;
let innerItem: HTEle;
let innerDataSourceItem: HTEle;
if (!isNOU(this.trgtEle)) {
this.ctrlTemplate();
}
if (!isNOU(this.dataSource) && this.dataSource.length > 0) {
this.dataSource.forEach((item: object, index: number) => {
innerDataSourceItem = this.renderInnerItem(item, index);
ele.appendChild(innerDataSourceItem);
if (innerDataSourceItem.childElementCount > 0) {
EventHandler.add(innerDataSourceItem.querySelector('.' + CLS_HEADER), 'focus', this.focusIn, this);
EventHandler.add(innerDataSourceItem.querySelector('.' + CLS_HEADER), 'blur', this.focusOut, this);
}
});
} else {
const items: AccordionItem[] = <AccordionItem[]>this.items;
if (ele && items.length > 0) {
items.forEach((item: AccordionItem, index: number) => {
innerItem = this.renderInnerItem(item, index);
ele.appendChild(innerItem);
if (innerItem.childElementCount > 0) {
EventHandler.add(innerItem.querySelector('.' + CLS_HEADER), 'focus', this.focusIn, this);
EventHandler.add(innerItem.querySelector('.' + CLS_HEADER), 'blur', this.focusOut, this);
}
});
}
}
if (this.isReact) {
this.renderReactTemplates();
}
}
private clickHandler(e: Event): void {
const trgt: HTEle = <HTEle>e.target;
const items: Object[] = this.getItems();
const eventArgs: AccordionClickArgs = {};
let tglIcon: HTEle;
const acrdEle: HTEle = <HTEle>closest(trgt, '.' + CLS_ROOT);
if (acrdEle !== this.element) {
return;
}
trgt.classList.add('e-target');
const acrdnItem: HTEle = <HTEle>closest(trgt, '.' + CLS_ITEM);
let acrdnHdr: HTEle = <HTEle>closest(trgt, '.' + CLS_HEADER);
let acrdnCtn: HTEle = <HTEle>closest(trgt, '.' + CLS_CONTENT);
if (acrdnItem && (isNOU(acrdnHdr) || isNOU(acrdnCtn))) {
acrdnHdr = <HTEle>acrdnItem.children[0];
acrdnCtn = <HTEle>acrdnItem.children[1];
}
if (acrdnHdr) {
tglIcon = <HTEle>select('.' + CLS_TOOGLEICN, acrdnHdr);
}
let acrdnCtnItem: HTEle;
if (acrdnHdr) {
acrdnCtnItem = <HTEle>closest(acrdnHdr, '.' + CLS_ITEM);
} else if (acrdnCtn) {
acrdnCtnItem = <HTEle>closest(acrdnCtn, '.' + CLS_ITEM);
}
const index: number = this.getIndexByItem(acrdnItem);
if (acrdnCtnItem) {
eventArgs.item = items[this.getIndexByItem(acrdnCtnItem)];
}
eventArgs.originalEvent = e;
const ctnCheck: boolean = !isNOU(tglIcon) && acrdnItem.childElementCount <= 1;
if (ctnCheck && (isNOU(acrdnCtn) || !isNOU(select('.' + CLS_HEADER + ' .' + CLS_TOOGLEICN, acrdnCtnItem)))) {
acrdnItem.appendChild(this.contentRendering(index));
this.ariaAttrUpdate(acrdnItem);
this.afterContentRender(trgt, eventArgs, acrdnItem, acrdnHdr, acrdnCtn, acrdnCtnItem);
} else {
this.afterContentRender(trgt, eventArgs, acrdnItem, acrdnHdr, acrdnCtn, acrdnCtnItem);
}
if (this.isReact) {
this.renderReactTemplates();
}
}
private afterContentRender(
trgt: HTEle, eventArgs: AccordionClickArgs, acrdnItem: HTEle, acrdnHdr: HTEle, acrdnCtn: HTEle, acrdnCtnItem: HTEle): void {
const acrdActive: HTEle[] = [];
this.trigger('clicked', eventArgs, (eventArgs: AccordionClickArgs) => {
if (eventArgs.cancel) {
return;
}
let cntclkCheck: boolean = (acrdnCtn && !isNOU(select('.e-target', acrdnCtn)));
const inlineAcrdnSel: string = '.' + CLS_CONTENT + ' .' + CLS_ROOT;
const inlineEleAcrdn: boolean = acrdnCtn && !isNOU(select('.' + CLS_ROOT, acrdnCtn)) && isNOU(closest(trgt, inlineAcrdnSel));
const nestContCheck: boolean = acrdnCtn && isNOU(select('.' + CLS_ROOT, acrdnCtn)) || !(closest(trgt, '.' + CLS_ROOT) === this.element);
cntclkCheck = cntclkCheck && (inlineEleAcrdn || nestContCheck);
trgt.classList.remove('e-target');
if (trgt.classList.contains(CLS_CONTENT) || trgt.classList.contains(CLS_CTENT) || cntclkCheck) {
return;
}
const acrdcontainer: HTMLElement = <HTMLElement>this.element.querySelector('.' + CLS_CONTAINER);
const acrdnchild: HTMLCollection = (acrdcontainer) ? acrdcontainer.children : this.element.children;
[].slice.call(acrdnchild).forEach((el: HTEle) => {
if (el.classList.contains(CLS_ACTIVE)) {
acrdActive.push(el);
}
});
const acrdAniEle: HTEle[] = [].slice.call(this.element.querySelectorAll('.' + CLS_ITEM + ' [' + CLS_ANIMATE + ']'));
if (acrdAniEle.length > 0) {
for (const el of acrdAniEle) {
acrdActive.push(el.parentElement);
}
}
const sameContentCheck: boolean = acrdActive.indexOf(acrdnCtnItem) !== -1 && acrdnCtn.getAttribute('e-animate') === 'true';
let sameHeader: boolean = false;
if (!isNOU(acrdnItem) && !isNOU(acrdnHdr)) {
const acrdnCtn: HTEle = <HTEle>select('.' + CLS_CONTENT, acrdnItem);
const acrdnRoot: HTEle = <HTEle>closest(acrdnItem, '.' + CLS_ACRDN_ROOT);
const expandState: HTEle = <HTEle>acrdnRoot.querySelector('.' + CLS_EXPANDSTATE);
if (isNOU(acrdnCtn)) {
return;
}
sameHeader = (expandState === acrdnItem);
if (isVisible(acrdnCtn) && (!sameContentCheck || acrdnCtnItem.classList.contains(CLS_SLCTED))) {
this.collapse(acrdnCtn);
} else {
if ((acrdActive.length > 0) && this.expandMode === 'Single' && !sameContentCheck) {
acrdActive.forEach((el: HTEle) => {
this.collapse(<HTEle>select('.' + CLS_CONTENT, el));
el.classList.remove(CLS_EXPANDSTATE);
});
}
this.expand(acrdnCtn);
}
if (!isNOU(expandState) && !sameHeader) {
expandState.classList.remove(CLS_EXPANDSTATE);
}
}
});
}
private eleMoveFocus(action: Str, root: HTEle, trgt: HTEle): void {
let clst: HTEle;
let clstItem: HTEle = <HTEle>closest(trgt, '.' + CLS_ITEM);
if (trgt === root) {
clst = <HTEle>((action === 'moveUp' ? trgt.lastElementChild : trgt).querySelector('.' + CLS_HEADER));
} else if (trgt.classList.contains(CLS_HEADER)) {
clstItem = <HTEle>(action === 'moveUp' ? clstItem.previousElementSibling : clstItem.nextElementSibling);
if (clstItem) {
clst = <HTEle>select('.' + CLS_HEADER, clstItem);
}
}
if (clst) {
clst.focus();
}
}
private keyActionHandler(e: KeyboardEventArgs): void {
const trgt: HTEle = <HTEle>e.target;
const header: HTEle = <HTEle>closest(e.target as HTEle, CLS_HEADER);
if (isNOU(header) && !trgt.classList.contains(CLS_ROOT) && !trgt.classList.contains(CLS_HEADER)) {
return;
}
let clst: HTEle;
const root: HTEle = this.element;
let content: HTEle;
switch (e.action) {
case 'moveUp':
this.eleMoveFocus(e.action, root, trgt);
break;
case 'moveDown':
this.eleMoveFocus(e.action, root, trgt);
break;
case 'space':
case 'enter':
content = trgt.nextElementSibling as HTEle;
if (!isNOU(content) && content.classList.contains(CLS_CONTENT)) {
if (content.getAttribute('e-animate') !== 'true') {
trgt.click();
}
} else {
trgt.click();
}
e.preventDefault();
break;
case 'home':
case 'end':
clst = e.action === 'home' ? <HTEle>root.firstElementChild.children[0] : <HTEle>root.lastElementChild.children[0];
clst.focus();
e.preventDefault();
break;
}
}
private headerEleGenerate(): HTEle {
const header: HTEle = this.createElement('div', { className: CLS_HEADER, id: getUniqueID('acrdn_header') });
const ariaAttr: { [key: string]: Str } = {
'tabindex': '0', 'role': 'button', 'aria-disabled': 'false', 'aria-expanded': 'false'
};
attributes(header, ariaAttr);
return header;
}
private renderInnerItem(item: AccordionItemModel, index: number): HTEle {
const innerEle: HTEle = this.createElement('div', {
className: CLS_ITEM, id: item.id || getUniqueID('acrdn_item')
});
if (this.headerTemplate) {
const ctnEle: HTEle = this.headerEleGenerate();
const hdrEle: HTEle = this.createElement('div', { className: CLS_HEADERCTN });
ctnEle.appendChild(hdrEle);
append(this.getHeaderTemplate()(item, this, 'headerTemplate', this.element.id + '_headerTemplate', false), hdrEle);
innerEle.appendChild(ctnEle);
ctnEle.appendChild(this.toggleIconGenerate());
this.add(innerEle, CLS_SLCT);
return innerEle;
}
if (item.header && this.angularnativeCondiCheck(item, 'header')) {
let header: string = item.header;
if (this.enableHtmlSanitizer && typeof (item.header) === 'string') {
header = SanitizeHtmlHelper.sanitize(item.header);
}
const ctnEle: HTEle = this.headerEleGenerate();
const hdrEle: HTEle = this.createElement('div', { className: CLS_HEADERCTN });
ctnEle.appendChild(hdrEle);
ctnEle.appendChild(this.fetchElement(hdrEle, header, index));
innerEle.appendChild(ctnEle);
}
let hdr: HTEle = <HTEle>select('.' + CLS_HEADER, innerEle);
if (item.expanded && !isNOU(index) && (!this.enablePersistence)) {
if (this.initExpand.indexOf(index) === -1) {
this.initExpand.push(index);
}
}
if (item.cssClass) {
addClass([innerEle], item.cssClass.split(' '));
}
if (item.disabled) {
addClass([innerEle], CLS_DISABLE);
}
if (item.visible === false) {
addClass([innerEle], CLS_ITEMHIDE);
}
if (item.iconCss) {
const hdrIcnEle: HTEle = this.createElement('div', { className: CLS_HEADERICN });
const icon: HTEle = this.createElement('span', { className: item.iconCss + ' e-icons' });
hdrIcnEle.appendChild(icon);
if (isNOU(hdr)) {
hdr = this.headerEleGenerate();
hdr.appendChild(hdrIcnEle);
innerEle.appendChild(hdr);
} else {
hdr.insertBefore(hdrIcnEle, hdr.childNodes[0]);
}
}
if (item.content && this.angularnativeCondiCheck(item, 'content')) {
const hdrIcon: HTEle = this.toggleIconGenerate();
if (isNOU(hdr)) {
hdr = this.headerEleGenerate();
innerEle.appendChild(hdr);
}
hdr.appendChild(hdrIcon);
this.add(innerEle, CLS_SLCT);
}
return innerEle;
}
private angularnativeCondiCheck(item: AccordionItemModel, prop: string): boolean {
const property: string = prop === 'content' ? item.content : item.header;
const content: AcrdnTemplateRef = (property as Object) as AcrdnTemplateRef;
if (this.isAngular && !isNOU(content.elementRef)) {
const data: string = content.elementRef.nativeElement.data;
if (isNOU(data) || data === '' || (data.indexOf('bindings=') === -1)) {
return true;
}
const parseddata: { [key: string]: string } = JSON.parse(content.elementRef.nativeElement.data.replace('bindings=', ''));
if (!isNOU(parseddata) && parseddata['ng-reflect-ng-if'] === 'false') {
return false;
} else {
return true;
}
} else {
return true;
}
}
private fetchElement(ele: HTEle, value: Str, index: number): HTEle {
let templateFn: Function;
let temString: Str;
try {
if (document.querySelectorAll(value).length && value !== 'Button') {
const eleVal: HTEle = <HTEle>document.querySelector(value);
temString = eleVal.outerHTML.trim();
ele.appendChild(eleVal);
eleVal.style.display = '';
} else {
templateFn = templateCompiler(value);
}
} catch (e) {
if (typeof (value) === 'string') {
ele.innerHTML = this.enableHtmlSanitizer ? SanitizeHtmlHelper.sanitize(value) : value;
} else if ((value as any) instanceof (HTMLElement)) {
ele.appendChild(value as HTMLElement);
if (this.trgtEle) {
(<HTMLElement>ele.firstElementChild).style.display = '';
}
} else {
templateFn = templateCompiler(value);
}
}
let tempArray: HTEle[];
if (!isNOU(templateFn)) {
if (this.isReact) {
this.renderReactTemplates();
}
let templateProps: string;
let templateName: string;
if (ele.classList.contains(CLS_HEADERCTN)) {
templateProps = this.element.id + index + '_header';
templateName = 'header';
} else if (ele.classList.contains(CLS_CTENT)) {
templateProps = this.element.id + index + '_content';
templateName = 'content';
}
tempArray = templateFn({}, this, templateName, templateProps, this.isStringTemplate);
}
if (!isNOU(tempArray) && tempArray.length > 0 && !(isNOU(tempArray[0].tagName) && tempArray.length === 1)) {
[].slice.call(tempArray).forEach((el: HTEle): void => {
if (!isNOU(el.tagName)) {
el.style.display = '';
}
ele.appendChild(el);
});
} else if (ele.childElementCount === 0) {
ele.innerHTML = this.enableHtmlSanitizer ? SanitizeHtmlHelper.sanitize(value) : value;
}
if (!isNOU(temString)) {
if (this.templateEle.indexOf(value) === -1) {
this.templateEle.push(value);
}
}
return ele;
}
private ariaAttrUpdate(itemEle: HTEle): void {
const header: Element = select('.' + CLS_HEADER, itemEle);
const content: Element = select('.' + CLS_CONTENT, itemEle);
header.setAttribute('aria-controls', content.id);
content.setAttribute('aria-labelledby', header.id);
content.setAttribute('role', 'region');
}
private contentRendering(index: number): HTEle {
const itemcnt: HTEle = this.createElement('div', { className: CLS_CONTENT + ' ' + CLS_CTNHIDE, id: getUniqueID('acrdn_panel') });
attributes(itemcnt, { 'aria-hidden': 'true' });
const ctn: HTEle = this.createElement('div', { className: CLS_CTENT });
if (!isNOU(this.dataSource) && this.dataSource.length > 0) {
if (this.isReact) {
this.renderReactTemplates();
}
append(this.getItemTemplate()(this.dataSource[parseInt(index.toString(), 10)], this, 'itemTemplate', this.element.id + '_itemTemplate', false), ctn);
itemcnt.appendChild(ctn);
} else {
let content: string = this.items[parseInt(index.toString(), 10)].content;
if (this.enableHtmlSanitizer && typeof (content) === 'string') {
content = SanitizeHtmlHelper.sanitize(content);
}
itemcnt.appendChild(this.fetchElement(ctn, content, index));
}
return itemcnt;
}
private expand(trgt: HTEle): void {
const items: Object[] = this.getItems();
const trgtItemEle: HTEle = <HTEle>closest(trgt, '.' + CLS_ITEM);
if (isNOU(trgt) || (isVisible(trgt) && trgt.getAttribute('e-animate') !== 'true') || trgtItemEle.classList.contains(CLS_DISABLE)) {
return;
}
const acrdnRoot: HTEle = <HTEle>closest(trgtItemEle, '.' + CLS_ACRDN_ROOT);
const expandState: HTEle = <HTEle>acrdnRoot.querySelector('.' + CLS_EXPANDSTATE);
const animation: AnimationModel = {
name: <Effect>this.animation.expand.effect,
duration: this.animation.expand.duration,
timingFunction: this.animation.expand.easing
};
const icon: HTEle = <HTEle>select('.' + CLS_TOOGLEICN, trgtItemEle).firstElementChild;
const eventArgs: ExpandEventArgs = {
element: trgtItemEle,
item: items[this.getIndexByItem(trgtItemEle)],
index: this.getIndexByItem(trgtItemEle),