-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathtab-nav.tsx
623 lines (511 loc) · 19.3 KB
/
tab-nav.tsx
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
// @ts-strict-ignore
import {
calciteSize24,
calciteSize32,
calciteSize44,
} from "@esri/calcite-design-tokens/dist/es6/core";
import { PropertyValues } from "lit";
import { LitElement, property, createEvent, h, state, JsxNode } from "@arcgis/lumina";
import {
Direction,
filterDirectChildren,
focusElementInGroup,
FocusElementInGroupDestination,
getElementDir,
slotChangeGetAssignedElements,
} from "../../utils/dom";
import { createObserver } from "../../utils/observers";
import { Scale } from "../interfaces";
import { TabChangeEventDetail, TabCloseEventDetail } from "../tab/interfaces";
import { TabID, TabLayout, TabPosition } from "../tabs/interfaces";
import { CSS_UTILITY } from "../../utils/resources";
import { useT9n } from "../../controllers/useT9n";
import type { TabTitle } from "../tab-title/tab-title";
import type { Tabs } from "../tabs/tabs";
import { CSS, ICON } from "./resources";
import T9nStrings from "./assets/t9n/messages.en.json";
import { styles } from "./tab-nav.scss";
declare global {
interface DeclareElements {
"calcite-tab-nav": TabNav;
}
}
/** @slot - A slot for adding `calcite-tab-title`s. */
export class TabNav extends LitElement {
// #region Static Members
static override styles = styles;
// #endregion
// #region Private Properties
private effectiveDir: Direction = "ltr";
get enabledTabTitles(): TabTitle["el"][] {
return filterDirectChildren<TabTitle["el"]>(
this.el,
"calcite-tab-title:not([disabled])",
).filter((tabTitle) => !tabTitle.closed);
}
private intersectionObserver: IntersectionObserver;
private lastScrollWheelAxis: "x" | "y" = "x";
private parentTabsEl: Tabs["el"];
private resizeObserver = createObserver("resize", () => {
this.updateScrollingState();
});
private get scrollerButtonWidth(): number {
const { scale } = this;
return parseInt(scale === "s" ? calciteSize24 : scale === "m" ? calciteSize32 : calciteSize44);
}
private tabTitleContainerEl: HTMLDivElement;
get tabTitles(): TabTitle["el"][] {
return filterDirectChildren<TabTitle["el"]>(this.el, "calcite-tab-title");
}
// #endregion
// #region State Properties
@state() private hasOverflowingEndTabTitle = false;
@state() private hasOverflowingStartTabTitle = false;
@state() selectedTabId: TabID;
// #endregion
// #region Public Properties
/** @private */
@property({ reflect: true }) bordered = false;
/** @private */
@property({ reflect: true }) layout: TabLayout = "inline";
/** Use this property to override individual strings used by the component. */
@property() messageOverrides?: typeof this.messages._overrides;
/**
* Made into a prop for testing purposes only.
*
* @private
*/
messages = useT9n<typeof T9nStrings>();
/**
* Specifies the position of `calcite-tab-nav` and `calcite-tab-title` components in relation to, and is inherited from the parent `calcite-tabs`, defaults to `top`.
*
* `@internal`
*/
@property() position: TabPosition = "bottom";
/**
* Specifies the size of the component inherited from the parent `calcite-tabs`, defaults to `m`.
*
* @private
*/
@property() scale: Scale = "m";
/**
* Specifies the component's selected `calcite-tab-title`.
*
* @readonly
*/
@property() selectedTitle: TabTitle["el"] = null;
/** Specifies the name when saving selected `calcite-tab` data to `localStorage`. */
@property({ reflect: true }) storageId: string;
/** Specifies text to update multiple components to keep in sync if one changes. */
@property({ reflect: true }) syncId: string;
// #endregion
// #region Events
/** @private */
calciteInternalTabChange = createEvent<TabChangeEventDetail>({ cancelable: false });
/** @private */
calciteInternalTabNavSlotChange = createEvent<Element[]>();
/** Emits when the selected `calcite-tab` changes. */
calciteTabChange = createEvent({ cancelable: false });
// #endregion
// #region Lifecycle
constructor() {
super();
this.listen("calciteInternalTabsFocusPrevious", this.focusPreviousTabHandler);
this.listen("calciteInternalTabsFocusNext", this.focusNextTabHandler);
this.listen("calciteInternalTabsFocusFirst", this.focusFirstTabHandler);
this.listen("calciteInternalTabsFocusLast", this.focusLastTabHandler);
this.listen("calciteInternalTabsActivate", this.internalActivateTabHandler);
this.listen("calciteTabsActivate", this.activateTabHandler);
this.listen("calciteInternalTabsClose", this.internalCloseTabHandler);
this.listen("calciteInternalTabTitleRegister", this.updateTabTitles);
this.listenOn<CustomEvent<TabChangeEventDetail>>(
document.body,
"calciteInternalTabChange",
this.globalInternalTabChangeHandler,
);
}
override connectedCallback(): void {
this.parentTabsEl = this.el.closest("calcite-tabs");
this.resizeObserver?.observe(this.el);
}
async load(): Promise<void> {
const storageKey = `calcite-tab-nav-${this.storageId}`;
if (localStorage && this.storageId && localStorage.getItem(storageKey)) {
const storedTab = JSON.parse(localStorage.getItem(storageKey));
this.selectedTabId = storedTab;
}
}
override willUpdate(changes: PropertyValues<this>): void {
/* TODO: [MIGRATION] First time Lit calls willUpdate(), changes will include not just properties provided by the user, but also any default values your component set.
To account for this semantics change, the checks for (this.hasUpdated || value != defaultValue) was added in this method
Please refactor your code to reduce the need for this check.
Docs: https://qawebgis.esri.com/arcgis-components/?path=/docs/lumina-transition-from-stencil--docs#watching-for-property-changes */
if (changes.has("selectedTitle") && (this.hasUpdated || this.selectedTitle !== null)) {
this.calciteInternalTabChange.emit({
tab: this.selectedTabId,
});
}
if (changes.has("selectedTabId")) {
this.selectedTabIdChanged();
}
const { parentTabsEl } = this;
this.layout = parentTabsEl?.layout;
this.bordered = parentTabsEl?.bordered;
this.effectiveDir = getElementDir(this.el);
}
loaded(): void {
this.scrollTabTitleIntoView(this.selectedTitle, "instant");
// if every tab title is active select the first tab.
if (
this.tabTitles.length &&
this.tabTitles.every((title) => !title.selected) &&
!this.selectedTabId
) {
this.tabTitles[0].getTabIdentifier().then((tab) => {
this.calciteInternalTabChange.emit({
tab,
});
});
}
}
override disconnectedCallback(): void {
this.resizeObserver?.disconnect();
}
// #endregion
// #region Private Methods
private focusPreviousTabHandler(event: CustomEvent): void {
this.handleTabFocus(event, event.target as TabTitle["el"], "previous");
}
private focusNextTabHandler(event: CustomEvent): void {
this.handleTabFocus(event, event.target as TabTitle["el"], "next");
}
private focusFirstTabHandler(event: CustomEvent): void {
this.handleTabFocus(event, event.target as TabTitle["el"], "first");
}
private focusLastTabHandler(event: CustomEvent): void {
this.handleTabFocus(event, event.target as TabTitle["el"], "last");
}
private internalActivateTabHandler(event: CustomEvent<TabChangeEventDetail>): void {
const activatedTabTitle = event.target as TabTitle["el"];
this.selectedTabId = event.detail.tab
? event.detail.tab
: this.getIndexOfTabTitle(activatedTabTitle);
event.stopPropagation();
this.selectedTitle = activatedTabTitle;
this.scrollTabTitleIntoView(activatedTabTitle);
}
private scrollTabTitleIntoView(
activatedTabTitle: TabTitle["el"],
behavior: ScrollBehavior = "smooth",
): void {
if (!activatedTabTitle) {
return;
}
requestAnimationFrame(() => {
const isLTR = this.effectiveDir === "ltr";
const tabTitleContainer = this.tabTitleContainerEl;
const containerBounds = tabTitleContainer.getBoundingClientRect();
const tabTitleBounds = activatedTabTitle.getBoundingClientRect();
const scrollPosition = tabTitleContainer.scrollLeft;
const overflowingStartTabTitle = isLTR
? this.hasOverflowingStartTabTitle
: this.hasOverflowingEndTabTitle;
const overflowingEndTabTitle = isLTR
? this.hasOverflowingEndTabTitle
: this.hasOverflowingStartTabTitle;
if (
tabTitleBounds.left <
containerBounds.left + (overflowingStartTabTitle ? this.scrollerButtonWidth : 0)
) {
const left =
scrollPosition + (tabTitleBounds.left - containerBounds.left) - this.scrollerButtonWidth;
tabTitleContainer.scrollTo({ left, behavior });
} else if (
tabTitleBounds.right >
containerBounds.right - (overflowingEndTabTitle ? this.scrollerButtonWidth : 0)
) {
const left =
scrollPosition +
(tabTitleBounds.right - containerBounds.right) +
this.scrollerButtonWidth;
tabTitleContainer.scrollTo({ left, behavior });
}
});
}
private activateTabHandler(event: CustomEvent<void>): void {
this.calciteTabChange.emit();
event.stopPropagation();
}
private internalCloseTabHandler(event: CustomEvent<TabCloseEventDetail>): void {
const closedTabTitleEl = event.target as TabTitle["el"];
this.handleTabTitleClose(closedTabTitleEl);
event.stopPropagation();
}
/**
* Check for active tabs on register and update selected
*
* @param event
*/
private async updateTabTitles(event: CustomEvent<TabID>): Promise<void> {
if ((event.target as TabTitle["el"]).selected) {
this.selectedTabId = event.detail;
this.selectedTitle = await this.getTabTitleById(this.selectedTabId);
}
}
private globalInternalTabChangeHandler(event: CustomEvent<TabChangeEventDetail>): void {
if (
this.syncId &&
event.target !== this.el &&
(event.target as TabNav["el"]).syncId === this.syncId &&
this.selectedTabId !== event.detail.tab
) {
this.selectedTabId = event.detail.tab;
}
event.stopPropagation();
}
private async selectedTabIdChanged(): Promise<void> {
await this.componentOnReady();
if (
localStorage &&
this.storageId &&
this.selectedTabId !== undefined &&
this.selectedTabId !== null
) {
localStorage.setItem(`calcite-tab-nav-${this.storageId}`, JSON.stringify(this.selectedTabId));
}
this.calciteInternalTabChange.emit({
tab: this.selectedTabId,
});
}
private onTabTitleWheel(event: WheelEvent): void {
event.preventDefault();
const { deltaX, deltaY } = event;
const x = Math.abs(deltaX);
const y = Math.abs(deltaY);
let scrollBy: number;
if (x === y) {
scrollBy = this.lastScrollWheelAxis === "x" ? deltaX : deltaY;
} else if (x > y) {
scrollBy = deltaX;
this.lastScrollWheelAxis = "x";
} else {
scrollBy = deltaY;
this.lastScrollWheelAxis = "y";
}
const scrollByX = (this.effectiveDir === "rtl" ? -1 : 1) * scrollBy;
(event.currentTarget as HTMLDivElement).scrollBy(scrollByX, 0);
}
private onSlotChange(event: Event): void {
this.intersectionObserver?.disconnect();
const slottedElements = slotChangeGetAssignedElements(event, "calcite-tab-title");
slottedElements.forEach((child) => {
this.intersectionObserver?.observe(child);
});
this.calciteInternalTabNavSlotChange.emit(slottedElements);
}
private storeTabTitleWrapperRef(el: HTMLDivElement) {
if (!el) {
return;
}
this.tabTitleContainerEl = el;
this.intersectionObserver = createObserver("intersection", () => this.updateScrollingState(), {
root: el,
threshold: [0, 0.5, 1],
});
}
private updateScrollingState(): void {
const tabTitleContainer = this.tabTitleContainerEl;
if (!tabTitleContainer) {
return;
}
let isOverflowStart: boolean;
let isOverflowEnd: boolean;
const scrollPosition = tabTitleContainer.scrollLeft;
const visibleWidth = tabTitleContainer.clientWidth;
const totalContentWidth = tabTitleContainer.scrollWidth;
if (this.effectiveDir === "ltr") {
isOverflowStart = scrollPosition > 0;
isOverflowEnd = scrollPosition + visibleWidth < totalContentWidth;
} else {
isOverflowStart = scrollPosition < 0;
isOverflowEnd = scrollPosition !== -(totalContentWidth - visibleWidth);
}
this.hasOverflowingStartTabTitle = isOverflowStart;
this.hasOverflowingEndTabTitle = isOverflowEnd;
}
private scrollToTabTitles(direction: "forward" | "backward"): void {
requestAnimationFrame(() => {
const tabTitleContainer = this.tabTitleContainerEl;
const containerBounds = tabTitleContainer.getBoundingClientRect();
const tabTitles = Array.from(this.el.querySelectorAll("calcite-tab-title"));
const { effectiveDir } = this;
if (direction === "forward") {
tabTitles.reverse();
}
let closestToEdge: TabTitle["el"] = null;
tabTitles.forEach((tabTitle) => {
const tabTitleBounds = tabTitle.getBoundingClientRect();
const containerEndX = containerBounds.x + containerBounds.width;
const tabTitleEndX = tabTitleBounds.x + tabTitleBounds.width;
if (
(direction === "forward" && effectiveDir === "ltr") ||
(direction === "backward" && effectiveDir === "rtl")
) {
const afterContainerEnd = tabTitleBounds.x > containerEndX;
if (afterContainerEnd) {
closestToEdge = tabTitle;
} else {
const crossingContainerEnd =
tabTitleEndX > containerEndX && tabTitleBounds.x > containerBounds.x;
if (crossingContainerEnd) {
closestToEdge = tabTitle;
}
}
} else {
const beforeContainerStart = tabTitleEndX < containerBounds.x;
if (beforeContainerStart) {
closestToEdge = tabTitle;
} else {
const crossingContainerStart =
tabTitleEndX < containerEndX && tabTitleBounds.x < containerBounds.x;
if (crossingContainerStart) {
closestToEdge = tabTitle;
}
}
}
});
if (closestToEdge) {
const { scrollerButtonWidth } = this;
const offsetAdjustment =
(direction === "forward" && effectiveDir === "ltr") ||
(direction === "backward" && effectiveDir === "rtl")
? -scrollerButtonWidth
: closestToEdge.offsetWidth - tabTitleContainer.clientWidth + scrollerButtonWidth;
const scrollTo = closestToEdge.offsetLeft + offsetAdjustment;
tabTitleContainer.scrollTo({
left: scrollTo,
behavior: "smooth",
});
}
});
}
private scrollToNextTabTitles(): void {
this.scrollToTabTitles("forward");
}
private scrollToPreviousTabTitles(): void {
this.scrollToTabTitles("backward");
}
private handleTabFocus(
event: CustomEvent,
el: TabTitle["el"],
destination: FocusElementInGroupDestination,
): void {
const focused = focusElementInGroup<TabTitle["el"]>(this.enabledTabTitles, el, destination);
this.scrollTabTitleIntoView(focused, "instant");
event.stopPropagation();
}
private getIndexOfTabTitle(el: TabTitle["el"], tabTitles = this.tabTitles): number {
// In most cases, since these indexes correlate with tab contents, we want to consider all tab titles.
// However, when doing relative index operations, it makes sense to pass in this.enabledTabTitles as the 2nd arg.
return tabTitles.indexOf(el);
}
private onTabTitleScroll(): void {
this.updateScrollingState();
}
private async getTabTitleById(id: TabID): Promise<TabTitle["el"] | null> {
return Promise.all(this.tabTitles.map((el) => el.getTabIdentifier())).then((ids) => {
return this.tabTitles[ids.indexOf(id)];
});
}
private handleTabTitleClose(closedTabTitleEl: TabTitle["el"]): void {
const { tabTitles } = this;
const selectionModified = closedTabTitleEl.selected;
const visibleTabTitlesIndices = tabTitles.reduce(
(tabTitleIndices: number[], tabTitle, index) =>
!tabTitle.closed ? [...tabTitleIndices, index] : tabTitleIndices,
[],
);
const totalVisibleTabTitles = visibleTabTitlesIndices.length;
if (totalVisibleTabTitles === 1 && tabTitles[visibleTabTitlesIndices[0]].closable) {
tabTitles[visibleTabTitlesIndices[0]].closable = false;
this.selectedTabId = visibleTabTitlesIndices[0];
if (selectionModified) {
tabTitles[visibleTabTitlesIndices[0]].activateTab();
}
} else if (totalVisibleTabTitles > 1) {
const closedTabTitleIndex = tabTitles.findIndex((el) => el === closedTabTitleEl);
const nextTabTitleIndex = visibleTabTitlesIndices.find(
(value) => value > closedTabTitleIndex,
);
if (this.selectedTabId === closedTabTitleIndex) {
this.selectedTabId = nextTabTitleIndex ? nextTabTitleIndex : totalVisibleTabTitles - 1;
tabTitles[this.selectedTabId].activateTab();
}
}
requestAnimationFrame(() => {
tabTitles[this.selectedTabId].focus();
});
}
// #endregion
// #region Rendering
override render(): JsxNode {
/* TODO: [MIGRATION] This used <Host> before. In Stencil, <Host> props overwrite user-provided props. If you don't wish to overwrite user-values, replace "=" here with "??=" */
this.el.role = "tablist";
return (
<div
class={{
[CSS.container]: true,
[CSS.containerHasStartTabTitleOverflow]: !!this.hasOverflowingStartTabTitle,
[CSS.containerHasEndTabTitleOverflow]: !!this.hasOverflowingEndTabTitle,
[`scale-${this.scale}`]: true,
[`position-${this.position}`]: true,
[CSS_UTILITY.rtl]: this.effectiveDir === "rtl",
}}
>
{this.renderScrollButton("start")}
<div
class={{
[CSS.tabTitleSlotWrapper]: true,
}}
onScroll={this.onTabTitleScroll}
onWheel={this.onTabTitleWheel}
ref={this.storeTabTitleWrapperRef}
>
<slot onSlotChange={this.onSlotChange} />
</div>
{this.renderScrollButton("end")}
</div>
);
}
private renderScrollButton(overflowDirection: "start" | "end"): JsxNode {
const { bordered, messages, hasOverflowingStartTabTitle, hasOverflowingEndTabTitle, scale } =
this;
const isEnd = overflowDirection === "end";
return (
<div
class={{
[CSS.scrollButtonContainer]: true,
[CSS.scrollBackwardContainerButton]: !isEnd,
[CSS.scrollForwardContainerButton]: isEnd,
}}
hidden={(isEnd && !hasOverflowingEndTabTitle) || (!isEnd && !hasOverflowingStartTabTitle)}
key={overflowDirection}
>
<calcite-button
appearance={bordered ? "outline-fill" : "transparent"}
ariaLabel={isEnd ? messages.nextTabTitles : messages.previousTabTitles}
class={{
[CSS.scrollButton]: true,
}}
iconFlipRtl="both"
iconStart={isEnd ? ICON.chevronRight : ICON.chevronLeft}
kind="neutral"
onClick={isEnd ? this.scrollToNextTabTitles : this.scrollToPreviousTabTitles}
scale={scale}
tabIndex={-1}
/>
</div>
);
}
// #endregion
}