|
| 1 | +import { visit } from "unist-util-visit"; |
| 2 | +import type { Root, Element, ElementContent } from "hast"; |
| 3 | + |
| 4 | +/** |
| 5 | + * Rehype plugin that makes nested list items individually collapsible. |
| 6 | + * For each <li> that contains a nested <ul>, wraps the content in |
| 7 | + * <details><summary> to enable collapse/expand functionality. |
| 8 | + */ |
| 9 | +export default function rehypeWrapFirstList() { |
| 10 | + return (tree: Root) => { |
| 11 | + visit(tree, "element", (node) => { |
| 12 | + // Only process <li> elements |
| 13 | + if (node.tagName !== "li") { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + // Check if this <li> has a nested <ul> child |
| 18 | + const nestedUlIndex = node.children.findIndex( |
| 19 | + (child): child is Element => |
| 20 | + child.type === "element" && child.tagName === "ul", |
| 21 | + ); |
| 22 | + |
| 23 | + // If no nested <ul>, nothing to do |
| 24 | + if (nestedUlIndex === -1) { |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + // Split children into summary content (before ul) and nested ul |
| 29 | + const summaryContent = node.children.slice(0, nestedUlIndex); |
| 30 | + const nestedUl = node.children[nestedUlIndex] as Element; |
| 31 | + |
| 32 | + // Only wrap if there's content to put in the summary |
| 33 | + if (summaryContent.length === 0) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + // Create the summary element with the content before the nested ul |
| 38 | + const summary: Element = { |
| 39 | + type: "element", |
| 40 | + tagName: "summary", |
| 41 | + properties: {}, |
| 42 | + children: summaryContent as ElementContent[], |
| 43 | + }; |
| 44 | + |
| 45 | + // Create the details element |
| 46 | + const details: Element = { |
| 47 | + type: "element", |
| 48 | + tagName: "details", |
| 49 | + properties: { open: true }, // Open by default |
| 50 | + children: [summary, nestedUl], |
| 51 | + }; |
| 52 | + |
| 53 | + // Replace the <li>'s children with just the details element |
| 54 | + node.children = [details]; |
| 55 | + }); |
| 56 | + }; |
| 57 | +} |
0 commit comments