|
| 1 | +/* eslint-disable @typescript-eslint/no-unsafe-argument */ |
| 2 | +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ |
| 3 | +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ |
| 4 | +/* eslint-disable @typescript-eslint/no-unsafe-call */ |
| 5 | + |
| 6 | +// plugins/remark-add-platform-metadata.js |
| 7 | +import { visit } from 'unist-util-visit'; |
| 8 | + |
| 9 | +const platformClasses = { |
| 10 | + '[A]': 'platform-indicator-android', |
| 11 | + '[I]': 'platform-indicator-ios', |
| 12 | + '[W]': 'platform-indicator-web', |
| 13 | +}; |
| 14 | + |
| 15 | +const processHeaderMarkers = () => { |
| 16 | + return (ast) => { |
| 17 | + visit(ast, 'heading', (node) => { |
| 18 | + let textContent = ''; |
| 19 | + let markers = []; |
| 20 | + |
| 21 | + visit(node, 'text', (textNode) => { |
| 22 | + // Split header into text and platform markers |
| 23 | + const headerParts = textNode.value |
| 24 | + .split(/(\[A\]|\[I\]|\[W\])/g) |
| 25 | + .filter((headerPart) => headerPart !== ''); |
| 26 | + |
| 27 | + // Assume that the first part is always the text content, and the rest are markers |
| 28 | + textContent = headerParts.shift().trimEnd(); |
| 29 | + |
| 30 | + // Sort markers to ensure consistent order |
| 31 | + markers = headerParts.sort(); |
| 32 | + }); |
| 33 | + |
| 34 | + if (markers.length === 0) { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + const newChildren = [{ type: 'text', value: textContent }]; |
| 39 | + |
| 40 | + markers.forEach((marker) => { |
| 41 | + newChildren.push({ |
| 42 | + type: 'mdxJsxTextElement', |
| 43 | + name: 'span', |
| 44 | + attributes: [ |
| 45 | + { |
| 46 | + type: 'mdxJsxAttribute', |
| 47 | + name: 'className', |
| 48 | + value: platformClasses[marker], |
| 49 | + }, |
| 50 | + ], |
| 51 | + children: [], |
| 52 | + data: { isPlatformIndicator: true }, |
| 53 | + }); |
| 54 | + }); |
| 55 | + |
| 56 | + node.children = newChildren; |
| 57 | + }); |
| 58 | + }; |
| 59 | +}; |
| 60 | + |
| 61 | +const removeHeaderJSX = () => { |
| 62 | + return (ast) => { |
| 63 | + const classes = Object.values(platformClasses); |
| 64 | + |
| 65 | + visit(ast, 'heading', (node) => { |
| 66 | + node.children = node.children.filter((child) => { |
| 67 | + if (child.type === 'mdxJsxTextElement') { |
| 68 | + const classAttr = child.attributes?.find( |
| 69 | + (a) => a.name === 'className' |
| 70 | + ); |
| 71 | + |
| 72 | + return !(classAttr && classes.includes(classAttr.value)); |
| 73 | + } |
| 74 | + |
| 75 | + return true; |
| 76 | + }); |
| 77 | + }); |
| 78 | + }; |
| 79 | +}; |
| 80 | + |
| 81 | +export { processHeaderMarkers, removeHeaderJSX }; |
0 commit comments