|
| 1 | +(function () { |
| 2 | + const menuCollapse = function (hook, vm) { |
| 3 | + // Hook to execute after the page is fully loaded https://github.com/docsifyjs/docsify/blob/develop/docs/write-a-plugin.md |
| 4 | + hook.doneEach(() => { |
| 5 | + // Select all parent items |
| 6 | + const parentItems = document.querySelectorAll('.sidebar-nav > ul > li'); |
| 7 | + |
| 8 | + parentItems.forEach(item => { |
| 9 | + /** |
| 10 | + * Skip items that already have link or not rendered |
| 11 | + * Check on empty string required because an original docsify menu does not provide hooks after load |
| 12 | + */ |
| 13 | + const textNode = item.firstChild; |
| 14 | + if (textNode.nodeType !== Node.TEXT_NODE || textNode.textContent.trim() === "") return; |
| 15 | + |
| 16 | + // Create link for text item |
| 17 | + const link = document.createElement('a'); |
| 18 | + link.href = '#'; |
| 19 | + link.textContent = textNode.textContent; |
| 20 | + textNode.parentNode.replaceChild(link, textNode); |
| 21 | + |
| 22 | + // Check if the parent item has a sublist |
| 23 | + const sublist = item.querySelector('ul'); |
| 24 | + if (!sublist) return; |
| 25 | + |
| 26 | + // Check if any nested items in the sublist have the 'active' class |
| 27 | + const hasActiveItems = sublist.querySelector('.active'); |
| 28 | + |
| 29 | + /** |
| 30 | + * Set data-submenu-state attribute to items without active nested items, otherwise set it to 'active' |
| 31 | + * That is need to highlight menu item on a page load when subitem is active |
| 32 | + */ |
| 33 | + if (hasActiveItems) { |
| 34 | + item.setAttribute('data-submenu-state', 'opened'); |
| 35 | + } else { |
| 36 | + item.setAttribute('data-submenu-state', 'collapsed'); |
| 37 | + } |
| 38 | + |
| 39 | + // Add click event listener to link to toggle submenu state |
| 40 | + link.addEventListener('click', (e) => { |
| 41 | + e.preventDefault(); |
| 42 | + const submenuState = item.getAttribute('data-submenu-state'); |
| 43 | + item.setAttribute('data-submenu-state', submenuState === 'collapsed' ? 'opened' : 'collapsed'); |
| 44 | + }); |
| 45 | + }); |
| 46 | + }); |
| 47 | + }; |
| 48 | + |
| 49 | + // Add the plugin to the Docsify plugin array |
| 50 | + $docsify = $docsify || {}; |
| 51 | + $docsify.plugins = [$docsify.plugins || [], menuCollapse]; |
| 52 | +})(); |
0 commit comments