|
| 1 | +import parseAttrs from 'md-attr-parser' |
| 2 | +import type { Node, Parent, Root } from 'mdast' |
| 3 | +import { visit } from 'unist-util-visit' |
| 4 | + |
| 5 | +export interface Attrs extends Node { |
| 6 | + type: 'attrs' |
| 7 | + value?: string | null |
| 8 | +} |
| 9 | + |
| 10 | +declare module 'mdast' { |
| 11 | + interface PhrasingContentMap { |
| 12 | + attrs: Attrs |
| 13 | + } |
| 14 | + |
| 15 | + interface RootContentMap { |
| 16 | + attrs: Attrs |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +export function attributesTransformer(root: Root): void { |
| 21 | + visit(root, 'paragraph', (node, _, parent) => { |
| 22 | + if ( |
| 23 | + 'children' in node && |
| 24 | + node.children.length === 1 && |
| 25 | + node.children[0].type === 'attrs' |
| 26 | + ) { |
| 27 | + const children = parent!.children |
| 28 | + const index = children.indexOf(node) |
| 29 | + children[index] = node.children[0] |
| 30 | + } |
| 31 | + }) |
| 32 | + |
| 33 | + visit( |
| 34 | + root, |
| 35 | + (node, _, parent) => |
| 36 | + node.type === 'paragraph' && parent?.type === 'listItem', |
| 37 | + (node, _, parent) => { |
| 38 | + const { children } = node as Parent |
| 39 | + |
| 40 | + const ids = Object.entries(children) |
| 41 | + .filter(([, child]) => child.type === 'attrs') |
| 42 | + .map(([id, node]) => [Number.parseInt(id, 10), node] as [number, Attrs]) |
| 43 | + |
| 44 | + if (ids.length === 0) { |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + for (const [index, attrNode] of ids) { |
| 49 | + const sibling = children[index - 1] |
| 50 | + if (sibling.type === 'text') { |
| 51 | + const data = parent!.data |
| 52 | + parent!.data = { |
| 53 | + ...data, |
| 54 | + hProperties: { |
| 55 | + ...data?.hProperties, |
| 56 | + ...parseAttrs(attrNode.value).prop, |
| 57 | + }, |
| 58 | + } |
| 59 | + children.splice(index, 1) |
| 60 | + } |
| 61 | + } |
| 62 | + }, |
| 63 | + ) |
| 64 | + |
| 65 | + visit(root, 'attrs', (node, index, parent) => { |
| 66 | + if (index == null || parent == null || parent.children.length <= 1) { |
| 67 | + return |
| 68 | + } |
| 69 | + |
| 70 | + const { children } = parent |
| 71 | + |
| 72 | + const sibling = children.at(index - 1) |
| 73 | + if (!sibling || sibling.type === 'text') { |
| 74 | + parent.data = { |
| 75 | + ...parent.data, |
| 76 | + hProperties: { |
| 77 | + ...parent.data?.hProperties, |
| 78 | + ...parseAttrs(node.value).prop, |
| 79 | + }, |
| 80 | + } |
| 81 | + } else { |
| 82 | + sibling.data = { |
| 83 | + ...sibling.data, |
| 84 | + hProperties: { |
| 85 | + ...sibling.data?.hProperties, |
| 86 | + ...parseAttrs(node.value).prop, |
| 87 | + }, |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + children.splice(index, 1) |
| 92 | + }) |
| 93 | +} |
0 commit comments