/
accordion.ts
351 lines (307 loc) · 10.1 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
import {
AfterContentChecked,
Component,
ContentChildren,
Directive,
EventEmitter,
Host,
Input,
Optional,
Output,
QueryList,
TemplateRef,
ViewEncapsulation
} from '@angular/core';
import {isString} from '../util/util';
import {NgbAccordionConfig} from './accordion-config';
let nextId = 0;
/**
* The context for the [NgbPanelHeader](#/components/accordion/api#NgbPanelHeader) template
*
* @since 4.1.0
*/
export interface NgbPanelHeaderContext {
/**
* `True` if current panel is opened
*/
opened: boolean;
}
/**
* A directive that wraps an accordion panel header with any HTML markup and a toggling button
* marked with [`NgbPanelToggle`](#/components/accordion/api#NgbPanelToggle).
* See the [header customization demo](#/components/accordion/examples#header) for more details.
*
* You can also use [`NgbPanelTitle`](#/components/accordion/api#NgbPanelTitle) to customize only the panel title.
*
* @since 4.1.0
*/
@Directive({selector: 'ng-template[ngbPanelHeader]'})
export class NgbPanelHeader {
constructor(public templateRef: TemplateRef<any>) {}
}
/**
* A directive that wraps only the panel title with HTML markup inside.
*
* You can also use [`NgbPanelHeader`](#/components/accordion/api#NgbPanelHeader) to customize the full panel header.
*/
@Directive({selector: 'ng-template[ngbPanelTitle]'})
export class NgbPanelTitle {
constructor(public templateRef: TemplateRef<any>) {}
}
/**
* A directive that wraps the accordion panel content.
*/
@Directive({selector: 'ng-template[ngbPanelContent]'})
export class NgbPanelContent {
constructor(public templateRef: TemplateRef<any>) {}
}
/**
* A directive that wraps an individual accordion panel with title and collapsible content.
*/
@Directive({selector: 'ngb-panel'})
export class NgbPanel implements AfterContentChecked {
/**
* If `true`, the panel is disabled an can't be toggled.
*/
@Input() disabled = false;
/**
* An optional id for the panel that must be unique on the page.
*
* If not provided, it will be auto-generated in the `ngb-panel-xxx` format.
*/
@Input() id = `ngb-panel-${nextId++}`;
isOpen = false;
/**
* The panel title.
*
* You can alternatively use [`NgbPanelTitle`](#/components/accordion/api#NgbPanelTitle) to set panel title.
*/
@Input() title: string;
/**
* Type of the current panel.
*
* Bootstrap provides styles for the following types: `'success'`, `'info'`, `'warning'`, `'danger'`, `'primary'`,
* `'secondary'`, `'light'` and `'dark'`.
*/
@Input() type: string;
/**
* An optional class applied to the card that wraps the panel.
*/
@Input() cardClass: string;
titleTpl: NgbPanelTitle | null;
headerTpl: NgbPanelHeader | null;
contentTpl: NgbPanelContent | null;
@ContentChildren(NgbPanelTitle, {descendants: false}) titleTpls: QueryList<NgbPanelTitle>;
@ContentChildren(NgbPanelHeader, {descendants: false}) headerTpls: QueryList<NgbPanelHeader>;
@ContentChildren(NgbPanelContent, {descendants: false}) contentTpls: QueryList<NgbPanelContent>;
ngAfterContentChecked() {
// We are using @ContentChildren instead of @ContentChild as in the Angular version being used
// only @ContentChildren allows us to specify the {descendants: false} option.
// Without {descendants: false} we are hitting bugs described in:
// https://github.com/ng-bootstrap/ng-bootstrap/issues/2240
this.titleTpl = this.titleTpls.first;
this.headerTpl = this.headerTpls.first;
this.contentTpl = this.contentTpls.first;
}
}
/**
* An event emitted right before toggling an accordion panel.
*/
export interface NgbPanelChangeEvent {
/**
* The id of the accordion panel that is being toggled.
*/
panelId: string;
/**
* The next state of the panel.
*
* `true` if it will be opened, `false` if closed.
*/
nextState: boolean;
/**
* Calling this function will prevent panel toggling.
*/
preventDefault: () => void;
}
/**
* Accordion is a collection of collapsible panels (bootstrap cards).
*
* It can ensure only one panel is opened at a time and allows to customize panel
* headers.
*/
@Component({
selector: 'ngb-accordion',
exportAs: 'ngbAccordion',
encapsulation: ViewEncapsulation.None,
host: {'class': 'accordion', 'role': 'tablist', '[attr.aria-multiselectable]': '!closeOtherPanels'},
template: `
<ng-template #t ngbPanelHeader let-panel>
<button class="btn btn-link" [ngbPanelToggle]="panel">
{{panel.title}}<ng-template [ngTemplateOutlet]="panel.titleTpl?.templateRef"></ng-template>
</button>
</ng-template>
<ng-template ngFor let-panel [ngForOf]="panels">
<div [class]="'card ' + panel.cardClass || ''">
<div role="tab" id="{{panel.id}}-header" [class]="'card-header ' + (panel.type ? 'bg-'+panel.type: type ? 'bg-'+type : '')">
<ng-template [ngTemplateOutlet]="panel.headerTpl?.templateRef || t"
[ngTemplateOutletContext]="{$implicit: panel, opened: panel.isOpen}"></ng-template>
</div>
<div id="{{panel.id}}" role="tabpanel" [attr.aria-labelledby]="panel.id + '-header'"
class="collapse" [class.show]="panel.isOpen" *ngIf="!destroyOnHide || panel.isOpen">
<div class="card-body">
<ng-template [ngTemplateOutlet]="panel.contentTpl?.templateRef"></ng-template>
</div>
</div>
</div>
</ng-template>
`
})
export class NgbAccordion implements AfterContentChecked {
@ContentChildren(NgbPanel) panels: QueryList<NgbPanel>;
/**
* An array or comma separated strings of panel ids that should be opened **initially**.
*
* For subsequent changes use methods like `expand()`, `collapse()`, etc. and
* the `(panelChange)` event.
*/
@Input() activeIds: string | readonly string[] = [];
/**
* If `true`, only one panel could be opened at a time.
*
* Opening a new panel will close others.
*/
@Input('closeOthers') closeOtherPanels: boolean;
/**
* If `true`, panel content will be detached from DOM and not simply hidden when the panel is collapsed.
*/
@Input() destroyOnHide = true;
/**
* Type of panels.
*
* Bootstrap provides styles for the following types: `'success'`, `'info'`, `'warning'`, `'danger'`, `'primary'`,
* `'secondary'`, `'light'` and `'dark'`.
*/
@Input() type: string;
/**
* Event emitted right before the panel toggle happens.
*
* See [NgbPanelChangeEvent](#/components/accordion/api#NgbPanelChangeEvent) for payload details.
*/
@Output() panelChange = new EventEmitter<NgbPanelChangeEvent>();
constructor(config: NgbAccordionConfig) {
this.type = config.type;
this.closeOtherPanels = config.closeOthers;
}
/**
* Checks if a panel with a given id is expanded.
*/
isExpanded(panelId: string): boolean { return this.activeIds.indexOf(panelId) > -1; }
/**
* Expands a panel with a given id.
*
* Has no effect if the panel is already expanded or disabled.
*/
expand(panelId: string): void { this._changeOpenState(this._findPanelById(panelId), true); }
/**
* Expands all panels, if `[closeOthers]` is `false`.
*
* If `[closeOthers]` is `true`, it will expand the first panel, unless there is already a panel opened.
*/
expandAll(): void {
if (this.closeOtherPanels) {
if (this.activeIds.length === 0 && this.panels.length) {
this._changeOpenState(this.panels.first, true);
}
} else {
this.panels.forEach(panel => this._changeOpenState(panel, true));
}
}
/**
* Collapses a panel with the given id.
*
* Has no effect if the panel is already collapsed or disabled.
*/
collapse(panelId: string) { this._changeOpenState(this._findPanelById(panelId), false); }
/**
* Collapses all opened panels.
*/
collapseAll() {
this.panels.forEach((panel) => { this._changeOpenState(panel, false); });
}
/**
* Toggles a panel with the given id.
*
* Has no effect if the panel is disabled.
*/
toggle(panelId: string) {
const panel = this._findPanelById(panelId);
if (panel) {
this._changeOpenState(panel, !panel.isOpen);
}
}
ngAfterContentChecked() {
// active id updates
if (isString(this.activeIds)) {
this.activeIds = this.activeIds.split(/\s*,\s*/);
}
// update panels open states
this.panels.forEach(panel => panel.isOpen = !panel.disabled && this.activeIds.indexOf(panel.id) > -1);
// closeOthers updates
if (this.activeIds.length > 1 && this.closeOtherPanels) {
this._closeOthers(this.activeIds[0]);
this._updateActiveIds();
}
}
private _changeOpenState(panel: NgbPanel, nextState: boolean) {
if (panel && !panel.disabled && panel.isOpen !== nextState) {
let defaultPrevented = false;
this.panelChange.emit(
{panelId: panel.id, nextState: nextState, preventDefault: () => { defaultPrevented = true; }});
if (!defaultPrevented) {
panel.isOpen = nextState;
if (nextState && this.closeOtherPanels) {
this._closeOthers(panel.id);
}
this._updateActiveIds();
}
}
}
private _closeOthers(panelId: string) {
this.panels.forEach(panel => {
if (panel.id !== panelId) {
panel.isOpen = false;
}
});
}
private _findPanelById(panelId: string): NgbPanel | null { return this.panels.find(p => p.id === panelId); }
private _updateActiveIds() {
this.activeIds = this.panels.filter(panel => panel.isOpen && !panel.disabled).map(panel => panel.id);
}
}
/**
* A directive to put on a button that toggles panel opening and closing.
*
* To be used inside the [`NgbPanelHeader`](#/components/accordion/api#NgbPanelHeader)
*
* @since 4.1.0
*/
@Directive({
selector: 'button[ngbPanelToggle]',
host: {
'type': 'button',
'[disabled]': 'panel.disabled',
'[class.collapsed]': '!panel.isOpen',
'[attr.aria-expanded]': 'panel.isOpen',
'[attr.aria-controls]': 'panel.id',
'(click)': 'accordion.toggle(panel.id)'
}
})
export class NgbPanelToggle {
@Input()
set ngbPanelToggle(panel: NgbPanel) {
if (panel) {
this.panel = panel;
}
}
constructor(public accordion: NgbAccordion, @Optional() @Host() public panel: NgbPanel) {}
}