@scania/tegel
Version:
Tegel Design System
334 lines (333 loc) • 14 kB
JavaScript
import { h, Host, } from "@stencil/core";
const GRID_LG_BREAKPOINT = 992;
/**
* @slot overlay - Used of injection of tds-side-menu-overlay
* @slot close-button - Used for injection of tds-side-menu-close-button that is show when in mobile view
* @slot <default> - <b>Unnamed slot.</b> For primary content of the side menu - like buttons.
* Used for nesting main content of Side Menu, e.g. <code><tds-side-menu-item></code> and <code><tds-side-menu-dropdown></code> components
* @slot end - Used for items that are presented at the bottom of the Side Menu, e.g. profile settings
* @slot sticky-end - Used for tds-side-menu-collapse-button component
* */
export class TdsSideMenu {
constructor() {
this.handleMatchesLgBreakpointChange = (e) => {
const isBelowLg = !e.matches;
if (isBelowLg) {
this.collapsed = false;
}
else {
this.collapsed = this.initialCollapsedState;
this.open = false;
}
};
this.open = false;
this.persistent = false;
this.collapsed = false;
this.isUpperSlotEmpty = false;
this.isCollapsed = false;
this.initialCollapsedState = false;
this.activeElementIndex = 0;
}
handleKeyDown(event) {
if (event.key === 'Escape' && this.open) {
this.open = false;
}
}
connectedCallback() {
this.matchesLgBreakpointMq = window.matchMedia(`(min-width: ${GRID_LG_BREAKPOINT}px)`);
this.matchesLgBreakpointMq.addEventListener('change', this.handleMatchesLgBreakpointChange);
this.isCollapsed = this.collapsed;
this.initialCollapsedState = this.collapsed;
}
componentDidLoad() {
const upperSlot = this.host.shadowRoot.querySelector('slot:not([name])');
const upperSlotElements = upperSlot.assignedElements();
const hasUpperSlotElements = (upperSlotElements === null || upperSlotElements === void 0 ? void 0 : upperSlotElements.length) > 0;
if (!hasUpperSlotElements) {
this.isUpperSlotEmpty = true;
}
if (window.innerWidth < GRID_LG_BREAKPOINT) {
this.collapsed = false;
}
}
disconnectedCallback() {
this.matchesLgBreakpointMq.removeEventListener('change', this.handleMatchesLgBreakpointChange);
}
onCollapsedChange(newVal) {
/** Emits the internal collapse event when the prop has changed. */
this.internalTdsSideMenuPropChange.emit({
changed: ['collapsed'],
collapsed: newVal,
});
this.isCollapsed = newVal;
}
onOpenChange(newVal) {
if (newVal) {
// When menu opens, focus the first interactive element
setTimeout(() => {
const focusableElements = this.getFocusableElements();
if (focusableElements.length > 0) {
this.activeElementIndex = 0;
focusableElements[0].focus();
}
}, 100);
}
else {
// When menu closes, focus the hamburger button
const hamburgerComponent = document.querySelector('tds-header-hamburger');
if (hamburgerComponent && hamburgerComponent.shadowRoot) {
const hamburgerButton = hamburgerComponent.shadowRoot.querySelector('button');
if (hamburgerButton) {
hamburgerButton.focus();
}
}
}
}
getFocusableElements() {
var _a;
const focusableSelectors = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
const focusableInShadowRoot = Array.from(this.host.shadowRoot.querySelectorAll(focusableSelectors));
const focusableInSlots = Array.from(this.host.querySelectorAll(focusableSelectors));
const closeBtn = (_a = this.host
.querySelector('[slot="close-button"]')) === null || _a === void 0 ? void 0 : _a.shadowRoot.querySelector('button');
let focusableElements = [...focusableInShadowRoot, ...focusableInSlots];
if (closeBtn)
focusableElements.push(closeBtn);
/** Focusable elements */
return focusableElements;
}
handleFocusTrap(event) {
// Only trap focus if the menu is open
if (!this.open)
return;
// We care only about the Tab key
if (event.key !== 'Tab')
return;
const focusableElements = this.getFocusableElements();
// If there are no focusable elements
if (focusableElements.length === 0)
return;
// Prevent default tab behavior
event.preventDefault();
// Going backwards (Shift + Tab) on the first element => move to last
if (event.shiftKey) {
this.activeElementIndex -= 1;
if (this.activeElementIndex < 0) {
this.activeElementIndex = focusableElements.length - 1;
}
}
// Going forwards (Tab) on the last element => move to first
else {
this.activeElementIndex += 1;
if (this.activeElementIndex >= focusableElements.length) {
this.activeElementIndex = 0;
}
}
// Focus the next element
const nextElement = focusableElements[this.activeElementIndex];
nextElement.focus();
}
collapsedSideMenuEventHandler(event) {
this.collapsed = event.detail.collapsed;
}
render() {
return (h(Host, { key: '62d159fdff0e4dd3d2a93e0c5542b8e672e3f287', class: {
'menu-opened': this.open,
'menu-persistent': this.persistent,
'menu-collapsed': this.collapsed,
}, "aria-expanded": !this.collapsed ? 'true' : 'false' }, h("div", { key: '17134ffc1c3ca6658f4ff87c203ca3b6ba991b83', class: {
'wrapper': true,
'state-upper-slot-empty': this.isUpperSlotEmpty,
'state-open': this.open,
'state-closed': !this.open,
} }, h("slot", { key: '8ed1f309c2188e6de12b874198c36a4698d7a69f', name: "overlay" }), h("aside", { key: '45702b7ff79693b31565550fc1985bfd64e45f92', class: `menu` }, h("div", { key: 'e799983a07a07ad0f4cac8e962e1748d08107b6b', role: "navigation" }, h("slot", { key: '4550b56dae039b94005dd58c8c5cb9818c3ab48a', name: "close-button" }), h("div", { key: 'ad2457482eb6dc9b08428f36078d53143f7b5168', class: "tds-side-menu-wrapper" }, h("ul", { key: '541323ca57ed67565c848a984bd3ac210ce6f135', class: `tds-side-menu-list tds-side-menu-list-upper` }, h("li", { key: '6248720390640a1166e1158caa0f50164fe1dfad' }, h("slot", { key: 'b3d24d582d4781fef041a2c099681fd538d01910' }))), h("ul", { key: '0a5f76474b4b3851d790ab8f698dbea9fd0fda05', class: `tds-side-menu-list tds-side-menu-list-end` }, h("li", { key: '576cf3e91cac7c1a21e6b35105475f1f443c2f45' }, h("slot", { key: '71f9c2d1c061401ef26daf68c7801b5665a25d03', name: "end" })))), h("slot", { key: '41805c2bb7c66f74f47edd2393a9a3452132c769', name: "sticky-end" }))))));
}
static get is() { return "tds-side-menu"; }
static get encapsulation() { return "shadow"; }
static get originalStyleUrls() {
return {
"$": ["side-menu.scss"]
};
}
static get styleUrls() {
return {
"$": ["side-menu.css"]
};
}
static get properties() {
return {
"open": {
"type": "boolean",
"mutable": true,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "Applicable only for mobile. If the Side Menu is open or not."
},
"attribute": "open",
"reflect": false,
"defaultValue": "false"
},
"persistent": {
"type": "boolean",
"mutable": false,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "Applicable only for desktop. If the Side Menu should always be shown."
},
"attribute": "persistent",
"reflect": false,
"defaultValue": "false"
},
"collapsed": {
"type": "boolean",
"mutable": true,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "If the Side Menu is collapsed. Only a persistent desktop menu can be collapsed.\nNOTE: Only use this if you have prevented the automatic collapsing with preventDefault on the tdsCollapse event."
},
"attribute": "collapsed",
"reflect": false,
"defaultValue": "false"
}
};
}
static get states() {
return {
"isUpperSlotEmpty": {},
"isCollapsed": {},
"initialCollapsedState": {},
"activeElementIndex": {}
};
}
static get events() {
return [{
"method": "tdsCollapse",
"name": "tdsCollapse",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": "Event that is emitted when the Side Menu is collapsed."
},
"complexType": {
"original": "CollapseEvent",
"resolved": "{ collapsed: boolean; }",
"references": {
"CollapseEvent": {
"location": "local",
"path": "/home/runner/work/tegel/tegel/packages/core/src/components/side-menu/side-menu.tsx",
"id": "src/components/side-menu/side-menu.tsx::CollapseEvent"
}
}
}
}, {
"method": "internalTdsCollapse",
"name": "internalTdsCollapse",
"bubbles": true,
"cancelable": false,
"composed": true,
"docs": {
"tags": [{
"name": "internal",
"text": "Broadcasts collapsed state to child components."
}],
"text": ""
},
"complexType": {
"original": "CollapseEvent",
"resolved": "{ collapsed: boolean; }",
"references": {
"CollapseEvent": {
"location": "local",
"path": "/home/runner/work/tegel/tegel/packages/core/src/components/side-menu/side-menu.tsx",
"id": "src/components/side-menu/side-menu.tsx::CollapseEvent"
}
}
}
}, {
"method": "internalTdsSideMenuPropChange",
"name": "internalTdsSideMenuPropChange",
"bubbles": true,
"cancelable": false,
"composed": true,
"docs": {
"tags": [{
"name": "internal",
"text": "Broadcasts collapsed state to child components."
}],
"text": ""
},
"complexType": {
"original": "InternalTdsSideMenuPropChange",
"resolved": "{ changed: \"collapsed\"[]; } & Partial<Props>",
"references": {
"InternalTdsSideMenuPropChange": {
"location": "local",
"path": "/home/runner/work/tegel/tegel/packages/core/src/components/side-menu/side-menu.tsx",
"id": "src/components/side-menu/side-menu.tsx::InternalTdsSideMenuPropChange"
}
}
}
}];
}
static get elementRef() { return "host"; }
static get watchers() {
return [{
"propName": "collapsed",
"methodName": "onCollapsedChange"
}, {
"propName": "open",
"methodName": "onOpenChange"
}];
}
static get listeners() {
return [{
"name": "keydown",
"method": "handleKeyDown",
"target": "window",
"capture": false,
"passive": false
}, {
"name": "keydown",
"method": "handleFocusTrap",
"target": "window",
"capture": true,
"passive": false
}, {
"name": "internalTdsCollapse",
"method": "collapsedSideMenuEventHandler",
"target": "body",
"capture": false,
"passive": false
}];
}
}