-
Notifications
You must be signed in to change notification settings - Fork 191
/
Tabs.ts
473 lines (424 loc) · 14.8 KB
/
Tabs.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
/*
Copyright 2020 Adobe. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import {
css,
CSSResult,
CSSResultArray,
html,
PropertyValues,
SizedMixin,
TemplateResult,
} from '@spectrum-web-components/base';
import {
property,
query,
} from '@spectrum-web-components/base/src/decorators.js';
import {
classMap,
ifDefined,
} from '@spectrum-web-components/base/src/directives.js';
import { IntersectionController } from '@lit-labs/observers/intersection-controller.js';
import { ResizeController } from '@lit-labs/observers/resize-controller.js';
import { Tab } from './Tab.js';
import { Focusable } from '@spectrum-web-components/shared';
import { RovingTabindexController } from '@spectrum-web-components/reactive-controllers/src/RovingTabindex.js';
import tabStyles from './tabs.css.js';
import tabSizes from './tabs-sizes.css.js';
import { TabPanel } from './TabPanel.js';
// Encapsulated for use both here and in TopNav
export const ScaledIndicator = {
baseSize: 100 as const,
noSelectionStyle: 'transform: translateX(0px) scaleX(0) scaleY(0)',
transformX(left: number, width: number): string {
const scale = width / this.baseSize;
return `transform: translateX(${left}px) scaleX(${scale});`;
},
transformY(top: number, height: number): string {
const scale = height / this.baseSize;
return `transform: translateY(${top}px) scaleY(${scale});`;
},
baseStyles(): CSSResult {
return css`
:host([direction='vertical-right']) #selection-indicator,
:host([direction='vertical']) #selection-indicator {
height: ${this.baseSize}px;
}
:host([dir][direction='horizontal']) #selection-indicator {
width: ${this.baseSize}px;
}
`;
},
};
/**
* @element sp-tabs
*
* @slot - Tab elements to manage as a group
* @slot tab-panel - Tab Panel elements related to the listed Tab elements
* @csspart tablist - Container element for the slotted sp-tab elements
*
* @fires change - The selected Tab child has changed.
*/
export class Tabs extends SizedMixin(Focusable) {
public static override get styles(): CSSResultArray {
return [tabSizes, tabStyles, ScaledIndicator.baseStyles()];
}
/**
* Whether to activate a tab on keyboard focus or not.
*
* By default a tab is activated via a "click" interaction. This is specifically intended for when
* tab content cannot be displayed instantly, e.g. not all of the DOM content is available, etc.
* To learn more about "Deciding When to Make Selection Automatically Follow Focus", visit:
* https://w3c.github.io/aria-practices/#kbd_selection_follows_focus
*/
@property({ type: Boolean })
public auto = false;
/**
* The tab items are displayed closer together.
*/
@property({ type: Boolean, reflect: true })
public compact = false;
@property({ reflect: true })
public override dir!: 'ltr' | 'rtl';
@property({ reflect: true })
public direction: 'vertical' | 'vertical-right' | 'horizontal' =
'horizontal';
@property({ type: Boolean, reflect: true })
public emphasized = false;
@property()
public label = '';
@property({ type: Boolean })
public enableTabsScroll = false;
/**
* The tab list is displayed without a border.
*/
@property({ type: Boolean, reflect: true })
public quiet = false;
@property({ attribute: false })
public selectionIndicatorStyle = ScaledIndicator.noSelectionStyle;
@property({ attribute: false })
public shouldAnimate = false;
@query('slot')
private slotEl!: HTMLSlotElement;
@query('#list')
private tabList!: HTMLDivElement;
@property({ reflect: true })
selected = '';
private set tabs(tabs: Tab[]) {
if (tabs === this.tabs) return;
this._tabs.forEach((tab) => {
this.resizeController.unobserve(tab);
});
tabs.forEach((tab) => {
this.resizeController.observe(tab);
});
this._tabs = tabs;
this.rovingTabindexController.clearElementCache();
}
private get tabs(): Tab[] {
return this._tabs;
}
private _tabs: Tab[] = [];
constructor() {
super();
new IntersectionController(this, {
config: {
root: null,
rootMargin: '0px',
threshold: [0, 1],
},
callback: () => {
this.updateSelectionIndicator();
},
});
}
protected resizeController = new ResizeController(this, {
callback: () => {
this.updateSelectionIndicator();
},
});
rovingTabindexController = new RovingTabindexController<Tab>(this, {
focusInIndex: (elements) => {
let focusInIndex = 0;
const firstFocusableElement = elements.find((el, index) => {
const focusInElement = this.selected
? !el.disabled && el.value === this.selected
: !el.disabled;
focusInIndex = index;
return focusInElement;
});
return firstFocusableElement ? focusInIndex : -1;
},
direction: () => 'both',
elementEnterAction: (el) => {
if (!this.auto) return;
this.shouldAnimate = true;
this.selectTarget(el);
},
elements: () => this.tabs,
isFocusableElement: (el) => !el.disabled,
listenerScope: () => this.tabList,
});
/**
* @private
*/
public override get focusElement(): Tab | this {
return this.rovingTabindexController.focusInElement || this;
}
public scrollTabs(
delta: number,
behavior: ScrollBehavior = 'smooth'
): void {
this.tabList?.scrollBy({
left: delta,
top: 0,
behavior,
});
}
public get scrollState(): Record<string, boolean> {
if (this.tabList) {
const { scrollLeft, clientWidth, scrollWidth } = this.tabList;
const canScrollLeft = Math.abs(scrollLeft) > 0;
const canScrollRight =
Math.ceil(Math.abs(scrollLeft)) < scrollWidth - clientWidth;
return {
canScrollLeft:
this.dir === 'ltr' ? canScrollLeft : canScrollRight,
canScrollRight:
this.dir === 'ltr' ? canScrollRight : canScrollLeft,
};
}
return {};
}
protected override manageAutoFocus(): void {
const tabs = [...this.children] as Tab[];
const tabUpdateCompletes = tabs.map((tab) => {
if (typeof tab.updateComplete !== 'undefined') {
return tab.updateComplete;
}
return Promise.resolve(true);
});
Promise.all(tabUpdateCompletes).then(() => super.manageAutoFocus());
}
protected managePanels({
target,
}: Event & { target: HTMLSlotElement }): void {
const panels = target.assignedElements() as TabPanel[];
panels.map((panel) => {
const { value, id } = panel;
const tab = this.querySelector(`[role="tab"][value="${value}"]`);
if (tab) {
tab.setAttribute('aria-controls', id);
panel.setAttribute('aria-labelledby', tab.id);
}
panel.selected = value === this.selected;
});
}
protected override render(): TemplateResult {
return html`
<div
class=${classMap({ scroll: this.enableTabsScroll })}
aria-label=${ifDefined(this.label ? this.label : undefined)}
@click=${this.onClick}
@keydown=${this.onKeyDown}
@scroll=${this.onTabsScroll}
id="list"
role="tablist"
part="tablist"
>
<slot @slotchange=${this.onSlotChange}></slot>
<div
id="selection-indicator"
class=${ifDefined(
this.shouldAnimate ? undefined : 'first-position'
)}
style=${this.selectionIndicatorStyle}
role="presentation"
></div>
</div>
<slot name="tab-panel" @slotchange=${this.managePanels}></slot>
`;
}
protected override willUpdate(changes: PropertyValues): void {
if (!this.hasUpdated) {
const selectedChild = this.querySelector(
':scope > [selected]'
) as Tab;
if (selectedChild) {
this.selectTarget(selectedChild);
}
}
super.willUpdate(changes);
if (changes.has('selected')) {
if (this.tabs.length) {
this.updateCheckedState();
}
if (changes.get('selected')) {
const previous = this.querySelector(
`[role="tabpanel"][value="${changes.get('selected')}"]`
) as TabPanel;
if (previous) previous.selected = false;
}
const next = this.querySelector(
`[role="tabpanel"][value="${this.selected}"]`
) as TabPanel;
if (next) next.selected = true;
}
if (changes.has('direction')) {
if (this.direction === 'horizontal') {
this.removeAttribute('aria-orientation');
} else {
this.setAttribute('aria-orientation', 'vertical');
}
}
if (changes.has('dir')) {
this.updateSelectionIndicator();
}
if (changes.has('disabled')) {
if (this.disabled) {
this.setAttribute('aria-disabled', 'true');
} else {
this.removeAttribute('aria-disabled');
}
}
if (
!this.shouldAnimate &&
typeof changes.get('shouldAnimate') !== 'undefined'
) {
this.shouldAnimate = true;
}
}
private onTabsScroll = (): void => {
this.dispatchEvent(
new Event('sp-tabs-scroll', {
bubbles: true,
composed: true,
})
);
};
private onClick = (event: Event): void => {
if (this.disabled) {
return;
}
const target = event
.composedPath()
.find((el) => (el as Tab).parentElement === this) as Tab;
if (!target || target.disabled) {
return;
}
this.shouldAnimate = true;
this.selectTarget(target);
};
private onKeyDown = (event: KeyboardEvent): void => {
if (event.code === 'Enter' || event.code === 'Space') {
event.preventDefault();
const target = event.target as HTMLElement;
if (target) {
this.selectTarget(target);
}
}
};
private selectTarget(target: HTMLElement): void {
const value = target.getAttribute('value');
if (value) {
const selected = this.selected;
this.selected = value;
const applyDefault = this.dispatchEvent(
new Event('change', {
cancelable: true,
})
);
if (!applyDefault) {
this.selected = selected;
}
}
}
private onSlotChange(): void {
this.tabs = this.slotEl
.assignedElements()
.filter((el) => el.getAttribute('role') === 'tab') as Tab[];
this.updateCheckedState();
}
private updateCheckedState = (): void => {
this.tabs.forEach((element) => {
element.removeAttribute('selected');
});
if (this.selected) {
const currentChecked = this.tabs.find(
(el) => el.value === this.selected
);
if (currentChecked) {
currentChecked.selected = true;
} else {
this.selected = '';
}
} else {
const firstTab = this.tabs[0];
if (firstTab) {
firstTab.setAttribute('tabindex', '0');
}
}
this.updateSelectionIndicator();
};
private updateSelectionIndicator = async (): Promise<void> => {
const selectedElement = this.tabs.find((el) => el.selected);
if (!selectedElement) {
this.selectionIndicatorStyle = ScaledIndicator.noSelectionStyle;
return;
}
await Promise.all([
selectedElement.updateComplete,
document.fonts ? document.fonts.ready : Promise.resolve(),
]);
const { width, height } = selectedElement.getBoundingClientRect();
this.selectionIndicatorStyle =
this.direction === 'horizontal'
? ScaledIndicator.transformX(selectedElement.offsetLeft, width)
: ScaledIndicator.transformY(selectedElement.offsetTop, height);
};
public override connectedCallback(): void {
super.connectedCallback();
window.addEventListener('resize', this.updateSelectionIndicator);
if ('fonts' in document) {
(
document as unknown as {
fonts: {
addEventListener: (
name: string,
callback: () => void
) => void;
};
}
).fonts.addEventListener(
'loadingdone',
this.updateSelectionIndicator
);
}
}
public override disconnectedCallback(): void {
window.removeEventListener('resize', this.updateSelectionIndicator);
if ('fonts' in document) {
(
document as unknown as {
fonts: {
removeEventListener: (
name: string,
callback: () => void
) => void;
};
}
).fonts.removeEventListener(
'loadingdone',
this.updateSelectionIndicator
);
}
super.disconnectedCallback();
}
}