forked from carbon-design-system/carbon-for-ibm-dotcom
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathleft-nav.ts
More file actions
423 lines (380 loc) · 13.1 KB
/
left-nav.ts
File metadata and controls
423 lines (380 loc) · 13.1 KB
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
/**
* @license
*
* Copyright IBM Corp. 2020, 2024
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import findLast from 'lodash-es/findLast.js';
import { html } from 'lit';
import { property, query } from 'lit/decorators.js';
import { selectorTabbable } from '../../internal/vendor/@carbon/web-components/globals/settings.js';
import HostListener from '../../internal/vendor/@carbon/web-components/globals/decorators/host-listener.js';
import CDSSideNav, {
SIDE_NAV_USAGE_MODE,
} from '../../internal/vendor/@carbon/web-components/components/ui-shell/side-nav.js';
import settings from '../../internal/vendor/@carbon/ibmdotcom-utilities/utilities/settings/settings';
import focuswrap from '../../internal/vendor/@carbon/ibmdotcom-utilities/utilities/focuswrap/focuswrap';
import { find, forEach } from '../../globals/internal/collection-helpers';
import Handle from '../../globals/internal/handle';
import StableSelectorMixin from '../../globals/mixins/stable-selector';
import C4DLeftNavOverlay from './left-nav-overlay';
import styles from './masthead.scss';
import C4DLeftNavMenuSection from './left-nav-menu-section';
import { carbonElement as customElement } from '../../internal/vendor/@carbon/web-components/globals/decorators/carbon-element.js';
const { prefix, stablePrefix: c4dPrefix } = settings;
// eslint-disable-next-line no-bitwise
const PRECEDING =
Node.DOCUMENT_POSITION_PRECEDING | Node.DOCUMENT_POSITION_CONTAINS;
// eslint-disable-next-line no-bitwise
const FOLLOWING =
Node.DOCUMENT_POSITION_FOLLOWING | Node.DOCUMENT_POSITION_CONTAINED_BY;
/**
* Masthead left nav.
*
* @element c4d-left-nav
*/
@customElement(`${c4dPrefix}-left-nav`)
class C4DLeftNav extends StableSelectorMixin(CDSSideNav) {
/**
* The handle for focus wrapping.
*/
private _hFocusWrap: Handle | null = null;
/**
* Node to track focus going outside of modal content.
*/
@query('#start-sentinel')
private _startSentinelNode!: HTMLAnchorElement;
/**
* Node to track focus going outside of modal content.
*/
@query('#end-sentinel')
private _endSentinelNode!: HTMLAnchorElement;
@property({ type: Boolean })
private _importedSideNav = false;
/**
* Handles `${prefix}-header-menu-button-toggle` event on the document.
*/
@HostListener('parentRoot:eventButtonToggle')
// @ts-ignore: The decorator refers to this method but TS thinks this method is not referred to
protected _handleButtonToggle = async (event: CustomEvent) => {
if (!this._importedSideNav) {
await Promise.all([
import('./left-nav-name'),
import('./left-nav-menu'),
import('./left-nav-menu-section'),
import('./left-nav-menu-item'),
import('./left-nav-menu-category-heading'),
import('./left-nav-overlay'),
]);
this._importedSideNav = true;
}
this.expanded = event.detail.active;
};
/**
* Handles `cds-request-focus-wrap` event on the document dispatched from focuswrap.
*
* @param event The event.
*/
@HostListener('document:cds-request-focus-wrap')
// @ts-ignore: The decorator refers to this method but TS thinks this method is not referred to
private _handleRequestMenuButtonFocusWrap = (event: CustomEvent) => {
const { selectorButtonToggle } = this.constructor as typeof C4DLeftNav;
/**
* If focus leaves this element, send focus to the menu toggle.
* Else if focus leaves the menu toggle, bring it back to this element.
*/
if (event.target === this) {
const toggle = (this.getRootNode() as Document).querySelector(
selectorButtonToggle
);
if (toggle) {
(toggle as HTMLElement).focus();
}
} else if (
(event.composedPath()[1] as HTMLElement).tagName ===
selectorButtonToggle.toUpperCase()
) {
const { comparisonResult } = event.detail;
const {
selectorExpandedMenuSection,
selectorTabbable: selectorTabbableForLeftnav,
} = this.constructor as typeof C4DLeftNav;
const expandedMenuSection = this.querySelector(
selectorExpandedMenuSection
);
// focus on first tabbable element when expanding left-nav
if (comparisonResult === -1) {
const tabbable = find(
this.querySelectorAll(selectorTabbableForLeftnav),
(elem) => Boolean((elem as HTMLElement).offsetParent)
);
if (tabbable) {
(tabbable as HTMLElement).focus();
}
}
// wrap focus to last tabbable element focusing out of first tabbable element
// eslint-disable-next-line no-bitwise
else if (comparisonResult & PRECEDING) {
const tabbable = findLast(
expandedMenuSection?.querySelectorAll(selectorTabbableForLeftnav),
(elem) => Boolean((elem as HTMLElement).offsetParent)
);
if (tabbable) {
(tabbable as HTMLElement).focus();
}
}
// wrap focus to first tabbable element focusing out of last tabbable element
// eslint-disable-next-line no-bitwise
else if (comparisonResult & FOLLOWING) {
const allTabbable = [
...Array.from(
expandedMenuSection?.shadowRoot?.querySelectorAll(
selectorTabbableForLeftnav
) || []
),
...Array.from(
expandedMenuSection?.querySelectorAll(selectorTabbableForLeftnav) ||
[]
),
];
if (allTabbable.length) {
(allTabbable[0] as HTMLElement).focus();
}
}
}
};
private _handleClickOut(event: MouseEvent) {
const { selectorButtonToggle } = this.constructor as typeof C4DLeftNav;
const toggleButton: HTMLElement | null = (
this.getRootNode() as Document
).querySelector(selectorButtonToggle);
// TODO: check why `target` returns `c4d-masthead-container` (parent) in Lit v2
if (
this.expanded &&
(event.composedPath()[0] as HTMLElement).tagName ===
'C4D-LEFT-NAV-OVERLAY'
) {
this.expanded = false;
toggleButton?.focus();
}
}
@HostListener('keydown')
// @ts-ignore: The decorator refers to this method but TS thinks this method is not referred to
private _handleKeydown(event: KeyboardEvent) {
const { selectorButtonToggle } = this.constructor as typeof C4DLeftNav;
const toggleButton: HTMLElement | null = (
this.getRootNode() as Document
).querySelector(selectorButtonToggle);
if (event.key === 'Escape') {
this.expanded = false;
toggleButton?.focus();
}
}
@HostListener('parentRoot:eventToggle')
protected _handleContentStateChangeDocument = (event: CustomEvent) => {
const { selectorMenuSections } = this.constructor as typeof C4DLeftNav;
const { panelId }: { panelId: string } = event.detail;
const menuSections: C4DLeftNavMenuSection[] = Array.from(
this.querySelectorAll(selectorMenuSections)
);
const expandedSection = menuSections
.filter((section) => section.matches('[expanded]'))
.shift();
const requestedSection = menuSections
.filter((section) => section.matches(`[section-id="${panelId}"]`))
.shift();
if (
expandedSection !== undefined &&
requestedSection !== undefined &&
expandedSection !== requestedSection
) {
const id = panelId.split(', ');
requestedSection.expanded = true;
requestedSection.ariaHidden = 'false';
requestedSection.transition = false;
expandedSection.expanded = false;
expandedSection.ariaHidden = 'true';
/**
* if next menu section expanded is a level 2 menu section and current expanded
* menu section is a level 1 menu section, add transition attribute for proper animation
*/
if (
id[0] !== '-1' &&
id[1] !== '-1' &&
!requestedSection.matches('[section-id*=" -1"]')
) {
expandedSection.transition = true;
}
}
};
/**
* Usage mode of the side nav.
*/
@property({ reflect: true, attribute: 'usage-mode' })
usageMode = SIDE_NAV_USAGE_MODE.HEADER_NAV;
connectedCallback() {
super.connectedCallback();
document.addEventListener('click', this._handleClickOut.bind(this));
}
async updated(changedProperties) {
super.updated(changedProperties);
const { usageMode } = this;
if (
changedProperties.has('usageMode') &&
usageMode !== SIDE_NAV_USAGE_MODE.HEADER_NAV
) {
// eslint-disable-next-line no-console
console.warn(
'c4d-left-nav supports only `header-nav` for its `usage-mode` attribute or `usageMode` property. The value is ignored:',
usageMode
);
}
if (changedProperties.has('expanded')) {
const doc = this.getRootNode() as Document;
forEach(
doc.querySelectorAll(
(this.constructor as typeof C4DLeftNav).selectorOverlay
),
(item) => {
(item as C4DLeftNavOverlay).active = this.expanded;
}
);
const {
expanded,
_startSentinelNode: startSentinelNode,
_endSentinelNode: endSentinelNode,
} = this;
const masthead: HTMLElement | null | undefined = doc
?.querySelector(
`${c4dPrefix}-masthead-container,
${c4dPrefix}-masthead-composite`
)
?.querySelector(`${c4dPrefix}-masthead`);
if (expanded && masthead) {
this._hFocusWrap = focuswrap(this.shadowRoot!, [
startSentinelNode,
endSentinelNode,
]);
if (doc.body?.style) {
doc.body.style.overflow = `hidden`;
}
// TODO: remove this logic once masthead can account for banners.
// set masthead position to `fixed` when left-nav is open for cloud-mastead
if (masthead) {
masthead!.style.position = 'fixed';
}
} else {
const { selectorMenuSections, selectorFirstMenuSection } = this
.constructor as typeof C4DLeftNav;
// TODO: remove this logic once masthead can account for banners.
// remove set position from mastead when left-nav is closed for cloud-mastead
if (masthead) {
document.body.style.overflow = 'auto';
masthead.style.position = '';
}
this.querySelectorAll(selectorMenuSections).forEach(
(c4dLeftNavMenuSection) => {
(c4dLeftNavMenuSection as C4DLeftNavMenuSection).expanded = false;
(c4dLeftNavMenuSection as C4DLeftNavMenuSection).transition = false;
}
);
// reset to first menu section
this.querySelectorAll(selectorFirstMenuSection).forEach(
(c4dLeftNavMenuSection) => {
(c4dLeftNavMenuSection as C4DLeftNavMenuSection).expanded = true;
}
);
if (this._hFocusWrap) {
this._hFocusWrap = this._hFocusWrap.release();
}
}
}
}
private _renderSentinel = (side: string) => {
return html`
<button
id="${side}-sentinel"
type="button"
class="${prefix}--visually-hidden"></button>
`;
};
render() {
const { _renderSentinel: renderSentinel } = this;
return html`
<div class="${prefix}--side-nav__wrapper">
${renderSentinel('start')}
<div class="${prefix}--side-nav__platform-name">
<slot name="platform-id"></slot>
</div>
<div class="${prefix}--side-nav__menu-sections">
<slot></slot>
</div>
${renderSentinel('end')}
</div>
`;
}
/**
* A selector that will return the toggle buttons.
*/
static get selectorButtonToggle() {
return `${c4dPrefix}-masthead-menu-button`;
}
/**
* A selector that will return side nav focusable items.
*/
static get selectorNavItems() {
return [
`${c4dPrefix}-left-nav-menu`,
`${c4dPrefix}-left-nav-menu-item`,
`${c4dPrefix}-left-nav-name`,
].join(', ');
}
/**
* A selector that will return menu sections.
*/
static get selectorMenuSections() {
return `${c4dPrefix}-left-nav-menu-section`;
}
/**
* A selector that will return expanded menu section.
*/
static get selectorExpandedMenuSection() {
return `${c4dPrefix}-left-nav-menu-section[expanded]`;
}
/**
* A selector that will return first main visible menu section.
*/
static get selectorFirstMenuSection() {
return `${c4dPrefix}-left-nav-menu-section[section-id='-1, -1']`;
}
/**
* A selector selecting tabbable nodes.
*/
static get selectorTabbable() {
return [
selectorTabbable,
`${c4dPrefix}-left-nav-menu`,
`${c4dPrefix}-left-nav-menu-item`,
`${c4dPrefix}-left-nav-name`,
].join(', ');
}
/**
* A selector that will return the overlays.
*/
static get selectorOverlay() {
return `${c4dPrefix}-left-nav-overlay`;
}
static get stableSelector() {
return `${c4dPrefix}--masthead__l0-sidenav`;
}
/**
* The name of the custom event fired after this side nav menu is toggled upon a user gesture.
*/
static get eventToggle() {
return `${c4dPrefix}-left-nav-menu-toggled`;
}
static styles = styles; // `styles` here is a `CSSResult` generated by custom WebPack loader
}
export default C4DLeftNav;