Skip to content

Commit 4a5fed8

Browse files
committed
feat: Add .c-active if current URL contains link target.
fix: Exclude node if the node is a comment node
1 parent ed3fdef commit 4a5fed8

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

js/src/sidebar.js

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const EVENT_KEY = `.${DATA_KEY}`
3131
const DATA_API_KEY = '.data-api'
3232

3333
const Default = {
34+
activeLinksExact: true,
3435
breakpoints: {
3536
xs: 'c-sidebar-show',
3637
sm: 'c-sidebar-sm-show',
@@ -43,6 +44,7 @@ const Default = {
4344
}
4445

4546
const DefaultType = {
47+
activeLinksExact: 'boolean',
4648
breakpoints: 'object',
4749
dropdownAccordion: '(string|boolean)'
4850
}
@@ -349,6 +351,10 @@ class Sidebar {
349351
continue // text node
350352
}
351353

354+
if (element.nodeType === 8) {
355+
continue // comment node
356+
}
357+
352358
if (!filter || filter(element)) {
353359
siblings.push(element)
354360
}
@@ -373,7 +379,7 @@ class Sidebar {
373379

374380
// TODO: find better solution
375381
if (Default.dropdownAccordion === true) {
376-
this._getAllSiblings(toggler.parentElement).forEach(element => {
382+
this._getAllSiblings(toggler.parentElement, element => Boolean(element.classList.contains(CLASS_NAME_NAV_DROPDOWN))).forEach(element => {
377383
if (element !== toggler.parentNode) {
378384
if (element.classList.contains(CLASS_NAME_NAV_DROPDOWN)) {
379385
element.classList.remove(CLASS_NAME_SHOW)
@@ -453,7 +459,21 @@ class Sidebar {
453459
currentUrl = currentUrl.slice(0, -1)
454460
}
455461

456-
if (element.href === currentUrl) {
462+
const dataAttributes = element.closest(SELECTOR_NAVIGATION_CONTAINER).dataset
463+
464+
if (typeof dataAttributes.activeLinksExact !== 'undefined') {
465+
Default.activeLinksExact = JSON.parse(dataAttributes.activeLinksExact)
466+
}
467+
468+
if (Default.activeLinksExact && element.href === currentUrl) {
469+
element.classList.add(CLASS_NAME_ACTIVE)
470+
// eslint-disable-next-line unicorn/prefer-spread
471+
Array.from(this._getParents(element, SELECTOR_NAV_DROPDOWN)).forEach(element => {
472+
element.classList.add(CLASS_NAME_SHOW)
473+
})
474+
}
475+
476+
if (!Default.activeLinksExact && element.href.startsWith(currentUrl)) {
457477
element.classList.add(CLASS_NAME_ACTIVE)
458478
// eslint-disable-next-line unicorn/prefer-spread
459479
Array.from(this._getParents(element, SELECTOR_NAV_DROPDOWN)).forEach(element => {

0 commit comments

Comments
 (0)