-
Notifications
You must be signed in to change notification settings - Fork 76
/
tab-nav.tsx
669 lines (567 loc) · 20 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
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
import {
Component,
Element,
Event,
EventEmitter,
h,
Host,
Listen,
Prop,
readTask,
State,
VNode,
Watch,
} from "@stencil/core";
import {
calciteSize24,
calciteSize32,
calciteSize44,
} from "@esri/calcite-design-tokens/dist/es6/core";
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 { connectLocalized, disconnectLocalized, LocalizedComponent } from "../../utils/locale";
import {
connectMessages,
disconnectMessages,
setUpMessages,
T9nComponent,
updateMessages,
} from "../../utils/t9n";
import { CSS_UTILITY } from "../../utils/resources";
import { CSS, ICON } from "./resources";
import { TabNavMessages } from "./assets/tab-nav/t9n";
/**
* @slot - A slot for adding `calcite-tab-title`s.
*/
@Component({
tag: "calcite-tab-nav",
styleUrl: "tab-nav.scss",
shadow: true,
assetsDirs: ["assets"],
})
export class TabNav implements LocalizedComponent, T9nComponent {
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/**
* Specifies the name when saving selected `calcite-tab` data to `localStorage`.
*/
@Prop({ reflect: true }) storageId: string;
/**
* Specifies text to update multiple components to keep in sync if one changes.
*/
@Prop({ reflect: true }) syncId: string;
/**
* Specifies the component's selected `calcite-tab-title`.
*
* @readonly
*/
@Prop({ mutable: true }) selectedTitle: HTMLCalciteTabTitleElement = null;
@Watch("selectedTitle")
selectedTitleChanged(): void {
this.calciteInternalTabChange.emit({
tab: this.selectedTabId,
});
}
/**
* Specifies the size of the component inherited from the parent `calcite-tabs`, defaults to `m`.
*
* @internal
*/
@Prop() scale: Scale = "m";
/**
* @internal
*/
@Prop({ reflect: true, mutable: true }) layout: TabLayout = "inline";
/**
* 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
*/
@Prop() position: TabPosition = "bottom";
/**
* @internal
*/
@Prop({ reflect: true, mutable: true }) bordered = false;
/**
* Made into a prop for testing purposes only.
*
* @internal
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated by t9n module
@Prop({ mutable: true }) messages: TabNavMessages;
/**
* Use this property to override individual strings used by the component.
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated by t9n module
@Prop({ mutable: true }) messageOverrides: Partial<TabNavMessages>;
@Watch("messageOverrides")
onMessagesChange(): void {
/* wired up by t9n util */
}
//--------------------------------------------------------------------------
//
// Lifecycle
//
//--------------------------------------------------------------------------
connectedCallback(): void {
this.parentTabsEl = this.el.closest("calcite-tabs");
this.resizeObserver?.observe(this.el);
connectLocalized(this);
connectMessages(this);
}
async componentWillLoad(): 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;
}
await setUpMessages(this);
}
componentDidLoad(): void {
this.scrollTabTitleIntoView(this.selectedTitle, "instant");
}
componentWillRender(): void {
const { parentTabsEl } = this;
this.layout = parentTabsEl?.layout;
this.bordered = parentTabsEl?.bordered;
this.effectiveDir = getElementDir(this.el);
}
componentDidRender(): void {
// 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,
});
});
}
}
disconnectedCallback(): void {
this.resizeObserver?.disconnect();
disconnectLocalized(this);
disconnectMessages(this);
}
//--------------------------------------------------------------------------
//
// Render Methods
//
//--------------------------------------------------------------------------
render(): VNode {
return (
<Host role="tablist">
<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>
</Host>
);
}
//--------------------------------------------------------------------------
//
// Event Listeners
//
//--------------------------------------------------------------------------
@Listen("calciteInternalTabsFocusPrevious")
focusPreviousTabHandler(event: CustomEvent): void {
this.handleTabFocus(event, event.target as HTMLCalciteTabTitleElement, "previous");
}
@Listen("calciteInternalTabsFocusNext")
focusNextTabHandler(event: CustomEvent): void {
this.handleTabFocus(event, event.target as HTMLCalciteTabTitleElement, "next");
}
@Listen("calciteInternalTabsFocusFirst")
focusFirstTabHandler(event: CustomEvent): void {
this.handleTabFocus(event, event.target as HTMLCalciteTabTitleElement, "first");
}
@Listen("calciteInternalTabsFocusLast")
focusLastTabHandler(event: CustomEvent): void {
this.handleTabFocus(event, event.target as HTMLCalciteTabTitleElement, "last");
}
@Listen("calciteInternalTabsActivate")
internalActivateTabHandler(event: CustomEvent<TabChangeEventDetail>): void {
const activatedTabTitle = event.target as HTMLCalciteTabTitleElement;
this.selectedTabId = event.detail.tab
? event.detail.tab
: this.getIndexOfTabTitle(activatedTabTitle);
event.stopPropagation();
this.selectedTitle = activatedTabTitle;
this.scrollTabTitleIntoView(activatedTabTitle);
}
private scrollTabTitleIntoView(
activatedTabTitle: HTMLCalciteTabTitleElement,
behavior: ScrollBehavior = "smooth",
): void {
if (!activatedTabTitle) {
return;
}
readTask(() => {
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 });
}
});
}
@Listen("calciteTabsActivate")
activateTabHandler(event: CustomEvent<void>): void {
this.calciteTabChange.emit();
event.stopPropagation();
}
@Listen("calciteInternalTabsClose")
internalCloseTabHandler(event: CustomEvent<TabCloseEventDetail>): void {
const closedTabTitleEl = event.target as HTMLCalciteTabTitleElement;
this.handleTabTitleClose(closedTabTitleEl);
event.stopPropagation();
}
/**
* Check for active tabs on register and update selected
*
* @param event
*/
@Listen("calciteInternalTabTitleRegister")
async updateTabTitles(event: CustomEvent<TabID>): Promise<void> {
if ((event.target as HTMLCalciteTabTitleElement).selected) {
this.selectedTabId = event.detail;
this.selectedTitle = await this.getTabTitleById(this.selectedTabId);
}
}
@Listen("calciteInternalTabChange", { target: "body" })
globalInternalTabChangeHandler(event: CustomEvent<TabChangeEventDetail>): void {
if (
this.syncId &&
event.target !== this.el &&
(event.target as HTMLCalciteTabNavElement).syncId === this.syncId &&
this.selectedTabId !== event.detail.tab
) {
this.selectedTabId = event.detail.tab;
}
event.stopPropagation();
}
//--------------------------------------------------------------------------
//
// Events
//
//--------------------------------------------------------------------------
/**
* Emits when the selected `calcite-tab` changes.
*/
@Event({ cancelable: false }) calciteTabChange: EventEmitter<void>;
/**
* @internal
*/
@Event() calciteInternalTabNavSlotChange: EventEmitter<Element[]>;
/**
* @internal
*/
@Event({ cancelable: false }) calciteInternalTabChange: EventEmitter<TabChangeEventDetail>;
//--------------------------------------------------------------------------
//
// Private State/Props
//
//--------------------------------------------------------------------------
@Element() el: HTMLCalciteTabNavElement;
@State() defaultMessages: TabNavMessages;
@State() effectiveLocale = "";
@Watch("effectiveLocale")
effectiveLocaleChange(): void {
updateMessages(this, this.effectiveLocale);
}
@State() private hasOverflowingStartTabTitle = false;
@State() private hasOverflowingEndTabTitle = false;
@State() private selectedTabId: TabID;
@Watch("selectedTabId")
async selectedTabIdChanged(): Promise<void> {
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 effectiveDir: Direction = "ltr";
private lastScrollWheelAxis: "x" | "y" = "x";
private parentTabsEl: HTMLCalciteTabsElement;
private tabTitleContainerEl: HTMLDivElement;
private intersectionObserver: IntersectionObserver;
private resizeObserver = createObserver("resize", () => {
this.updateScrollingState();
});
private get scrollerButtonWidth(): number {
const { scale } = this;
return parseInt(scale === "s" ? calciteSize24 : scale === "m" ? calciteSize32 : calciteSize44);
}
//--------------------------------------------------------------------------
//
// Private Methods
//
//--------------------------------------------------------------------------
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) => {
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 => {
readTask(() => {
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: HTMLCalciteTabTitleElement = 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");
handleTabFocus = (
event: CustomEvent,
el: HTMLCalciteTabTitleElement,
destination: FocusElementInGroupDestination,
): void => {
const focused = focusElementInGroup<HTMLCalciteTabTitleElement>(
this.enabledTabTitles,
el,
destination,
);
this.scrollTabTitleIntoView(focused, "instant");
event.stopPropagation();
};
getIndexOfTabTitle(el: HTMLCalciteTabTitleElement, 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();
};
async getTabTitleById(id: TabID): Promise<HTMLCalciteTabTitleElement | null> {
return Promise.all(this.tabTitles.map((el) => el.getTabIdentifier())).then((ids) => {
return this.tabTitles[ids.indexOf(id)];
});
}
get tabTitles(): HTMLCalciteTabTitleElement[] {
return filterDirectChildren<HTMLCalciteTabTitleElement>(this.el, "calcite-tab-title");
}
get enabledTabTitles(): HTMLCalciteTabTitleElement[] {
return filterDirectChildren<HTMLCalciteTabTitleElement>(
this.el,
"calcite-tab-title:not([disabled])",
).filter((tabTitle) => !tabTitle.closed);
}
private handleTabTitleClose(closedTabTitleEl: HTMLCalciteTabTitleElement): 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();
});
}
private renderScrollButton = (overflowDirection: "start" | "end"): VNode => {
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"}
aria-label={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>
);
};
}