| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
export function rehypeSections({split = 'h2'} = {}) { |
| 8 |
return function (tree) { |
| 9 |
wrap(tree, split); |
| 10 |
}; |
| 11 |
} |
| 12 |
|
| 13 |
function wrap(node, tag) { |
| 14 |
if (!node.children) return; |
| 15 |
for (const child of node.children) wrap(child, tag); |
| 16 |
|
| 17 |
if (!node.children.some(c => c.type === 'element' && c.tagName === tag)) return; |
| 18 |
|
| 19 |
const out = []; |
| 20 |
let section = null; |
| 21 |
|
| 22 |
for (const child of node.children) { |
| 23 |
if (child.type === 'element' && child.tagName === tag) { |
| 24 |
if (section) out.push(section); |
| 25 |
section = { |
| 26 |
type: 'element', |
| 27 |
tagName: 'section', |
| 28 |
properties: {}, |
| 29 |
children: [child], |
| 30 |
}; |
| 31 |
} else if (section) { |
| 32 |
section.children.push(child); |
| 33 |
} else { |
| 34 |
out.push(child); |
| 35 |
} |
| 36 |
} |
| 37 |
if (section) out.push(section); |
| 38 |
|
| 39 |
node.children = out; |
| 40 |
} |