|
| 1 | +const visit = require('unist-util-visit'); |
| 2 | +const { select } = require('unist-util-select'); |
| 3 | +const { |
| 4 | + isMdxBlockElement, |
| 5 | + isPlainText, |
| 6 | + hasClassName, |
| 7 | + removeAttribute, |
| 8 | + removeChild, |
| 9 | + setAttribute, |
| 10 | +} = require('./utils/mdxast'); |
| 11 | +const toString = require('mdast-util-to-string'); |
| 12 | +const toJSXExpression = require('./utils/to-jsx-expression'); |
| 13 | + |
| 14 | +const isExampleBox = (node) => |
| 15 | + isMdxBlockElement('dl', node) && hasClassName('example-box', node); |
| 16 | + |
| 17 | +const exampleBoxes = () => (tree, file) => { |
| 18 | + visit( |
| 19 | + tree, |
| 20 | + (node) => isExampleBox(node) && node.children.length === 1, |
| 21 | + (dl) => { |
| 22 | + const child = dl.children[0]; |
| 23 | + const [title, children] = child.children; |
| 24 | + |
| 25 | + if (child.children.length > 2) { |
| 26 | + file.message( |
| 27 | + 'Simple collapser example has more than 2 child nodes. Please revisit this implementation to handle the additional nodes', |
| 28 | + child.position.start, |
| 29 | + 'example-boxes' |
| 30 | + ); |
| 31 | + } |
| 32 | + |
| 33 | + setAttribute( |
| 34 | + 'title', |
| 35 | + isPlainText(title) ? toString(title) : toJSXExpression(title, file), |
| 36 | + child |
| 37 | + ); |
| 38 | + |
| 39 | + dl.name = 'CollapserGroup'; |
| 40 | + child.name = 'Collapser'; |
| 41 | + child.children = [children]; |
| 42 | + removeAttribute('className', dl); |
| 43 | + } |
| 44 | + ); |
| 45 | + |
| 46 | + visit(tree, isExampleBox, (dl) => { |
| 47 | + dl.name = 'CollapserGroup'; |
| 48 | + removeAttribute('className', dl); |
| 49 | + |
| 50 | + visit( |
| 51 | + dl, |
| 52 | + (node, _idx, parent) => parent === dl && isMdxBlockElement('dt', node), |
| 53 | + (dt, idx) => { |
| 54 | + const dd = dl.children[idx + 1]; |
| 55 | + |
| 56 | + setAttribute( |
| 57 | + 'title', |
| 58 | + isPlainText(dt) ? toString(dt) : toJSXExpression(dt, file), |
| 59 | + dt |
| 60 | + ); |
| 61 | + |
| 62 | + dt.name = 'Collapser'; |
| 63 | + dt.children = dd.children; |
| 64 | + } |
| 65 | + ); |
| 66 | + |
| 67 | + visit( |
| 68 | + dl, |
| 69 | + (node, _idx, parent) => parent === dl && isMdxBlockElement('dd', node), |
| 70 | + (dd) => { |
| 71 | + removeChild(dd, dl); |
| 72 | + } |
| 73 | + ); |
| 74 | + }); |
| 75 | +}; |
| 76 | + |
| 77 | +module.exports = exampleBoxes; |
0 commit comments