|
1 | 1 | import { Root } from "mdast"
|
2 |
| -import { MdxJsxFlowElement } from "mdast-util-mdx-jsx" |
| 2 | +import { MdxJsxAttribute, MdxJsxFlowElement } from "mdast-util-mdx-jsx" |
3 | 3 | import { visit } from "unist-util-visit"
|
4 | 4 | import { isHikeElement, listToSection } from "./1.1.remark-list-to-section.js"
|
5 | 5 | import { sectionToAttribute } from "./1.2.remark-section-to-attribute.js"
|
6 | 6 | import { CodeHikeConfig } from "./config.js"
|
7 | 7 |
|
| 8 | +/** |
| 9 | + * Determines whether Markdown is enabled for the given MDX JSX element. |
| 10 | + * |
| 11 | + * This function checks for the presence of a `markdownEnabled` attribute: |
| 12 | + * - If no attribute is found, it returns `false`. |
| 13 | + * - If the attribute is present in shorthand form (e.g. `<SomeTag |
| 14 | + * markdownEnabled>`), it returns `true`. |
| 15 | + * - If the attribute is an MDX expression (e.g. `<SomeTag |
| 16 | + * markdownEnabled={true} />`), it checks if the raw expression text is |
| 17 | + * literally `"true"`. |
| 18 | + */ |
| 19 | +export function isMarkdownEnabled(node: MdxJsxFlowElement): boolean { |
| 20 | + // Look for the "markdownEnabled" attribute within the node’s attributes. |
| 21 | + const markdownEnabledAttr = node.attributes.find( |
| 22 | + (attr): attr is MdxJsxAttribute => |
| 23 | + attr.type === "mdxJsxAttribute" && attr.name === "markdownEnabled", |
| 24 | + ) |
| 25 | + |
| 26 | + if (!markdownEnabledAttr) return false |
| 27 | + |
| 28 | + // Shorthand (<Component markdownEnabled>) implies true. |
| 29 | + if (markdownEnabledAttr.value === null) return true |
| 30 | + |
| 31 | + // If the attribute value is an object, it indicates an MDX expression |
| 32 | + // (e.g. markdownEnabled={true}). The `.value` property on this object is the |
| 33 | + // raw string representation of the expression, so we check if it’s |
| 34 | + // literally "true". |
| 35 | + if ( |
| 36 | + typeof markdownEnabledAttr.value === "object" && |
| 37 | + markdownEnabledAttr.value.type === "mdxJsxAttributeValueExpression" |
| 38 | + ) { |
| 39 | + return markdownEnabledAttr.value.value.trim() === "true" |
| 40 | + } |
| 41 | + |
| 42 | + return false |
| 43 | +} |
| 44 | + |
8 | 45 | export async function transformAllHikes(root: Root, config: CodeHikeConfig) {
|
9 | 46 | let tree = wrapInHike(root)
|
10 | 47 |
|
@@ -42,8 +79,10 @@ async function transformRemarkHike(
|
42 | 79 | node: MdxJsxFlowElement,
|
43 | 80 | config: CodeHikeConfig,
|
44 | 81 | ) {
|
| 82 | + const markdownEnabled = isMarkdownEnabled(node) |
| 83 | + |
45 | 84 | const section = await listToSection(node, config)
|
46 |
| - const { children, attributes } = sectionToAttribute(section) |
| 85 | + const { children, attributes } = sectionToAttribute(section, markdownEnabled) |
47 | 86 |
|
48 | 87 | node.children = children
|
49 | 88 | node.attributes.push(...attributes)
|
|
0 commit comments