@esri/calcite-components
Version:
Web Components for Esri's Calcite Design System.
557 lines (556 loc) • 17.1 kB
JavaScript
/*!
* All material copyright ESRI, All Rights Reserved, unless otherwise specified.
* See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
* v1.5.0-next.4
*/
import { h, Host } from "@stencil/core";
import { filterDirectChildren, focusElementInGroup, getElementDir } from "../../utils/dom";
import { createObserver } from "../../utils/observers";
/**
* @slot - A slot for adding `calcite-tab-title`s.
*/
export class TabNav {
constructor() {
this.animationActiveDuration = 0.3;
this.resizeObserver = createObserver("resize", () => {
if (!this.activeIndicatorEl) {
return;
}
// remove active indicator transition duration during resize to prevent wobble
this.activeIndicatorEl.style.transitionDuration = "0s";
this.updateActiveWidth();
this.updateOffsetPosition();
});
//--------------------------------------------------------------------------
//
// Private Methods
//
//--------------------------------------------------------------------------
this.handleTabFocus = (event, el, destination) => {
focusElementInGroup(this.enabledTabTitles, el, destination);
event.stopPropagation();
};
this.handleContainerScroll = () => {
// remove active indicator transition duration while container is scrolling to prevent wobble
this.activeIndicatorEl.style.transitionDuration = "0s";
this.updateOffsetPosition();
};
this.storageId = undefined;
this.syncId = undefined;
this.selectedTitle = null;
this.scale = "m";
this.layout = "inline";
this.position = "bottom";
this.bordered = false;
this.indicatorOffset = undefined;
this.indicatorWidth = undefined;
this.selectedTabId = undefined;
}
async selectedTabIdChanged() {
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
});
this.selectedTitle = await this.getTabTitleById(this.selectedTabId);
}
selectedTitleChanged() {
this.updateOffsetPosition();
this.updateActiveWidth();
// reset the animation time on tab selection
this.activeIndicatorEl.style.transitionDuration = `${this.animationActiveDuration}s`;
}
//--------------------------------------------------------------------------
//
// Lifecycle
//
//--------------------------------------------------------------------------
connectedCallback() {
this.parentTabsEl = this.el.closest("calcite-tabs");
this.resizeObserver?.observe(this.el);
}
disconnectedCallback() {
this.resizeObserver?.disconnect();
}
componentWillLoad() {
const storageKey = `calcite-tab-nav-${this.storageId}`;
if (localStorage && this.storageId && localStorage.getItem(storageKey)) {
const storedTab = JSON.parse(localStorage.getItem(storageKey));
this.selectedTabId = storedTab;
}
}
componentWillRender() {
const { parentTabsEl } = this;
this.layout = parentTabsEl?.layout;
this.position = parentTabsEl?.position;
this.scale = parentTabsEl?.scale;
this.bordered = parentTabsEl?.bordered;
// fix issue with active tab-title not lining up with blue indicator
if (this.selectedTitle) {
this.updateOffsetPosition();
}
}
componentDidRender() {
// 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
});
});
}
}
render() {
const dir = getElementDir(this.el);
const width = `${this.indicatorWidth}px`;
const offset = `${this.indicatorOffset}px`;
const indicatorStyle = dir !== "rtl" ? { width, left: offset } : { width, right: offset };
return (h(Host, { role: "tablist" }, h("div", { class: "tab-nav", onScroll: this.handleContainerScroll,
// eslint-disable-next-line react/jsx-sort-props
ref: (el) => (this.tabNavEl = el) }, h("slot", null), h("div", { class: "tab-nav-active-indicator-container",
// eslint-disable-next-line react/jsx-sort-props
ref: (el) => (this.activeIndicatorContainerEl = el) }, h("div", { class: "tab-nav-active-indicator", style: indicatorStyle,
// eslint-disable-next-line react/jsx-sort-props
ref: (el) => (this.activeIndicatorEl = el) })))));
}
//--------------------------------------------------------------------------
//
// Event Listeners
//
//--------------------------------------------------------------------------
focusPreviousTabHandler(event) {
this.handleTabFocus(event, event.target, "previous");
}
focusNextTabHandler(event) {
this.handleTabFocus(event, event.target, "next");
}
focusFirstTabHandler(event) {
this.handleTabFocus(event, event.target, "first");
}
focusLastTabHandler(event) {
this.handleTabFocus(event, event.target, "last");
}
internalActivateTabHandler(event) {
this.selectedTabId = event.detail.tab
? event.detail.tab
: this.getIndexOfTabTitle(event.target);
event.stopPropagation();
}
activateTabHandler(event) {
this.calciteTabChange.emit();
event.stopPropagation();
}
internalCloseTabHandler(event) {
const closedTabTitleEl = event.target;
this.handleTabTitleClose(closedTabTitleEl);
event.stopPropagation();
}
/**
* Check for active tabs on register and update selected
*
* @param event
*/
updateTabTitles(event) {
if (event.target.selected) {
this.selectedTabId = event.detail;
}
}
globalInternalTabChangeHandler(event) {
if (this.syncId &&
event.target !== this.el &&
event.target.syncId === this.syncId &&
this.selectedTabId !== event.detail.tab) {
this.selectedTabId = event.detail.tab;
}
event.stopPropagation();
}
iconStartChangeHandler() {
this.updateActiveWidth();
}
updateOffsetPosition() {
const dir = getElementDir(this.el);
const navWidth = this.activeIndicatorContainerEl?.offsetWidth;
const tabLeft = this.selectedTitle?.offsetLeft;
const tabWidth = this.selectedTitle?.offsetWidth;
const offsetRight = navWidth - (tabLeft + tabWidth);
this.indicatorOffset =
dir !== "rtl" ? tabLeft - this.tabNavEl?.scrollLeft : offsetRight + this.tabNavEl?.scrollLeft;
}
updateActiveWidth() {
this.indicatorWidth = this.selectedTitle?.offsetWidth;
}
getIndexOfTabTitle(el, tabTitles = this.tabTitles) {
// 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);
}
async getTabTitleById(id) {
return Promise.all(this.tabTitles.map((el) => el.getTabIdentifier())).then((ids) => {
return this.tabTitles[ids.indexOf(id)];
});
}
get tabTitles() {
return filterDirectChildren(this.el, "calcite-tab-title");
}
get enabledTabTitles() {
return filterDirectChildren(this.el, "calcite-tab-title:not([disabled])").filter((tabTitle) => !tabTitle.closed);
}
handleTabTitleClose(closedTabTitleEl) {
const { tabTitles } = this;
const visibleTabTitlesIndices = tabTitles.reduce((tabTitleIndices, 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];
}
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;
}
}
requestAnimationFrame(() => {
this.updateOffsetPosition();
this.updateActiveWidth();
tabTitles[this.selectedTabId].focus();
});
}
static get is() { return "calcite-tab-nav"; }
static get encapsulation() { return "shadow"; }
static get originalStyleUrls() {
return {
"$": ["tab-nav.scss"]
};
}
static get styleUrls() {
return {
"$": ["tab-nav.css"]
};
}
static get properties() {
return {
"storageId": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "Specifies the name when saving selected `calcite-tab` data to `localStorage`."
},
"attribute": "storage-id",
"reflect": true
},
"syncId": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "Specifies text to update multiple components to keep in sync if one changes."
},
"attribute": "sync-id",
"reflect": true
},
"selectedTitle": {
"type": "unknown",
"mutable": true,
"complexType": {
"original": "HTMLCalciteTabTitleElement",
"resolved": "HTMLCalciteTabTitleElement",
"references": {
"HTMLCalciteTabTitleElement": {
"location": "global"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [{
"name": "readonly",
"text": undefined
}],
"text": "Specifies the component's selected tab-title."
},
"defaultValue": "null"
},
"scale": {
"type": "string",
"mutable": true,
"complexType": {
"original": "Scale",
"resolved": "\"l\" | \"m\" | \"s\"",
"references": {
"Scale": {
"location": "import",
"path": "../interfaces"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [{
"name": "internal",
"text": undefined
}],
"text": ""
},
"attribute": "scale",
"reflect": true,
"defaultValue": "\"m\""
},
"layout": {
"type": "string",
"mutable": true,
"complexType": {
"original": "TabLayout",
"resolved": "\"center\" | \"inline\"",
"references": {
"TabLayout": {
"location": "import",
"path": "../tabs/interfaces"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [{
"name": "internal",
"text": undefined
}],
"text": ""
},
"attribute": "layout",
"reflect": true,
"defaultValue": "\"inline\""
},
"position": {
"type": "string",
"mutable": true,
"complexType": {
"original": "TabPosition",
"resolved": "\"bottom\" | \"top\"",
"references": {
"TabPosition": {
"location": "import",
"path": "../tabs/interfaces"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [{
"name": "internal",
"text": undefined
}],
"text": ""
},
"attribute": "position",
"reflect": true,
"defaultValue": "\"bottom\""
},
"bordered": {
"type": "boolean",
"mutable": true,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [{
"name": "internal",
"text": undefined
}],
"text": ""
},
"attribute": "bordered",
"reflect": true,
"defaultValue": "false"
},
"indicatorOffset": {
"type": "number",
"mutable": true,
"complexType": {
"original": "number",
"resolved": "number",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [{
"name": "internal",
"text": undefined
}],
"text": ""
},
"attribute": "indicator-offset",
"reflect": false
},
"indicatorWidth": {
"type": "number",
"mutable": true,
"complexType": {
"original": "number",
"resolved": "number",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [{
"name": "internal",
"text": undefined
}],
"text": ""
},
"attribute": "indicator-width",
"reflect": false
}
};
}
static get states() {
return {
"selectedTabId": {}
};
}
static get events() {
return [{
"method": "calciteTabChange",
"name": "calciteTabChange",
"bubbles": true,
"cancelable": false,
"composed": true,
"docs": {
"tags": [],
"text": "Emits when the selected `calcite-tab` changes."
},
"complexType": {
"original": "void",
"resolved": "void",
"references": {}
}
}, {
"method": "calciteInternalTabChange",
"name": "calciteInternalTabChange",
"bubbles": true,
"cancelable": false,
"composed": true,
"docs": {
"tags": [{
"name": "internal",
"text": undefined
}],
"text": ""
},
"complexType": {
"original": "TabChangeEventDetail",
"resolved": "TabChangeEventDetail",
"references": {
"TabChangeEventDetail": {
"location": "import",
"path": "../tab/interfaces"
}
}
}
}];
}
static get elementRef() { return "el"; }
static get watchers() {
return [{
"propName": "selectedTabId",
"methodName": "selectedTabIdChanged"
}, {
"propName": "selectedTitle",
"methodName": "selectedTitleChanged"
}];
}
static get listeners() {
return [{
"name": "calciteInternalTabsFocusPrevious",
"method": "focusPreviousTabHandler",
"target": undefined,
"capture": false,
"passive": false
}, {
"name": "calciteInternalTabsFocusNext",
"method": "focusNextTabHandler",
"target": undefined,
"capture": false,
"passive": false
}, {
"name": "calciteInternalTabsFocusFirst",
"method": "focusFirstTabHandler",
"target": undefined,
"capture": false,
"passive": false
}, {
"name": "calciteInternalTabsFocusLast",
"method": "focusLastTabHandler",
"target": undefined,
"capture": false,
"passive": false
}, {
"name": "calciteInternalTabsActivate",
"method": "internalActivateTabHandler",
"target": undefined,
"capture": false,
"passive": false
}, {
"name": "calciteTabsActivate",
"method": "activateTabHandler",
"target": undefined,
"capture": false,
"passive": false
}, {
"name": "calciteInternalTabsClose",
"method": "internalCloseTabHandler",
"target": undefined,
"capture": false,
"passive": false
}, {
"name": "calciteInternalTabTitleRegister",
"method": "updateTabTitles",
"target": undefined,
"capture": false,
"passive": false
}, {
"name": "calciteInternalTabChange",
"method": "globalInternalTabChangeHandler",
"target": "body",
"capture": false,
"passive": false
}, {
"name": "calciteInternalTabIconChanged",
"method": "iconStartChangeHandler",
"target": undefined,
"capture": false,
"passive": false
}];
}
}