|
1 | 1 | (function () { |
2 | 2 | const menuCollapse = function (hook, vm) { |
3 | | - |
| 3 | + // Hook to execute after the page is fully loaded https://github.com/docsifyjs/docsify/blob/develop/docs/write-a-plugin.md |
4 | 4 | hook.doneEach(() => { |
5 | | - |
6 | 5 | const parentItems = document.querySelectorAll('.sidebar-nav > ul > li'); |
7 | 6 |
|
8 | 7 | parentItems.forEach(item => { |
| 8 | + /** |
| 9 | + * Skip items that already have link or not rendered |
| 10 | + * Check on empty string required because an original docsify menu does not provide hooks after load |
| 11 | + */ |
| 12 | + if (item.firstChild.nodeType !== Node.TEXT_NODE || item.firstChild.textContent.trim() === "") return; |
| 13 | + |
| 14 | + // Check if the parent item has a sublist |
9 | 15 | const sublist = item.querySelector('ul'); |
10 | 16 |
|
11 | 17 | if (sublist) { |
| 18 | + // Check if any nested items in the sublist have the 'active' class |
12 | 19 | const nestedItems = sublist.querySelectorAll('li'); |
13 | 20 | const hasActiveItems = Array.from(nestedItems).some(nestedItem => nestedItem.classList.contains('active')); |
14 | 21 |
|
15 | | - if (item.firstChild.nodeType !== Node.TEXT_NODE || item.firstChild.textContent.trim() === "") { |
16 | | - return |
17 | | - } |
18 | | - |
| 22 | + /** |
| 23 | + * Add the 'collapse' class to items without active nested items, otherwise add 'active' |
| 24 | + * That is need to highlight menu item on a page load when subitem is active |
| 25 | + */ |
19 | 26 | if (!hasActiveItems) { |
20 | 27 | item.classList.add('collapse'); |
21 | 28 | } else { |
22 | 29 | item.classList.add('active'); |
23 | 30 | item.classList.remove('collapse'); |
24 | 31 | } |
25 | 32 |
|
| 33 | + // Add class to sublist |
26 | 34 | sublist.classList.add('app-sub-sidebar'); |
27 | 35 |
|
| 36 | + // Wrap text item in a link to follow default menu behavior and classes |
28 | 37 | const textNode = item.firstChild; |
29 | 38 | const link = document.createElement('a'); |
30 | 39 | link.href = '#/'; |
31 | 40 | link.textContent = textNode.textContent; |
32 | 41 | textNode.parentNode.replaceChild(link, textNode); |
33 | 42 |
|
34 | | - |
| 43 | + // Add click event listener to link to prevent default behavior |
35 | 44 | link.addEventListener('click', (e) => { |
36 | 45 | e.preventDefault(); |
| 46 | + // Close all other collapsed items when a link is clicked |
37 | 47 | parentItems.forEach(otherItem => { |
38 | 48 | if (otherItem !== item) { |
39 | 49 | otherItem.classList.remove('collapse'); |
|
45 | 55 | }); |
46 | 56 | }; |
47 | 57 |
|
48 | | - // Add plugin to docsify's plugin array |
| 58 | + // Add the plugin to the Docsify plugin array |
49 | 59 | $docsify = $docsify || {}; |
50 | 60 | $docsify.plugins = [].concat(menuCollapse, $docsify.plugins || []); |
51 | 61 | })(); |
0 commit comments