|
| 1 | +/** |
| 2 | + * prettier-plugin-mdx-inline |
| 3 | + * |
| 4 | + * Prevents prettier from reformatting specific JSX elements in MDX files. |
| 5 | + * |
| 6 | + * Problem: Prettier's MDX formatter treats standalone JSX elements (like |
| 7 | + * `<code>`) as block-level and wraps their children |
| 8 | + * onto new lines when they exceed printWidth. MDX v2+ then interprets those |
| 9 | + * newlines as markdown paragraph boundaries, injecting <p> tags inside inline |
| 10 | + * elements — producing broken HTML like `<code><p>...</p></code>`. |
| 11 | + * |
| 12 | + * Solution: This plugin intercepts the parsed MDX AST and converts matching |
| 13 | + * JSX nodes to opaque HTML nodes that prettier outputs verbatim. It also |
| 14 | + * collapses any existing multi-line formatting back to a single line. |
| 15 | + * |
| 16 | + * Configuration (.prettierrc.mjs): |
| 17 | + * |
| 18 | + * export default { |
| 19 | + * plugins: ["./prettier-plugin-mdx-inline/index.mjs"], |
| 20 | + * overrides: [{ |
| 21 | + * files: "*.mdx", |
| 22 | + * options: { parser: "mdx-inline" }, |
| 23 | + * }], |
| 24 | + * }; |
| 25 | + * |
| 26 | + * You must specify which elements to protect via `mdxInlineElements`: |
| 27 | + * |
| 28 | + * overrides: [{ |
| 29 | + * files: "*.mdx", |
| 30 | + * options: { |
| 31 | + * parser: "mdx-inline", |
| 32 | + * mdxInlineElements: "code,GlossaryTooltip", |
| 33 | + * }, |
| 34 | + * }], |
| 35 | + */ |
| 36 | + |
| 37 | +/** |
| 38 | + * Extract the element name from the start of a JSX string. |
| 39 | + * e.g., "<code>" → "code", "<GlossaryTooltip term="x">" → "GlossaryTooltip" |
| 40 | + */ |
| 41 | +function getElementName(value) { |
| 42 | + const match = value.trim().match(/^<([a-zA-Z][a-zA-Z0-9]*)/); |
| 43 | + return match ? match[1] : null; |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Collapse a multi-line JSX element value onto a single line. |
| 48 | + * |
| 49 | + * Handles: |
| 50 | + * - {" "} spacer expressions inserted by prettier |
| 51 | + * - Newlines with surrounding whitespace from indentation |
| 52 | + * - Multiple consecutive spaces from collapsing |
| 53 | + * - Trailing content after the closing tag (e.g., in list items) |
| 54 | + * |
| 55 | + * Preserves: |
| 56 | + * - Attribute values (strings in the opening tag) |
| 57 | + * - Self-closing tags within content (e.g., <Type text="..." />) |
| 58 | + */ |
| 59 | +function collapseInlineJsx(value) { |
| 60 | + // Remove {" "} spacers — these are prettier artifacts for preserving spaces |
| 61 | + let result = value.replace(/\{" "\}/g, " "); |
| 62 | + |
| 63 | + const elementName = getElementName(result); |
| 64 | + if (!elementName) return result; |
| 65 | + |
| 66 | + // Find the end of the opening tag by tracking string context. |
| 67 | + // We need to skip over attribute values that may contain '>' characters. |
| 68 | + let inString = false; |
| 69 | + let stringChar = ""; |
| 70 | + let openTagEnd = -1; |
| 71 | + |
| 72 | + for (let i = 0; i < result.length; i++) { |
| 73 | + const ch = result[i]; |
| 74 | + if (inString) { |
| 75 | + if (ch === stringChar && result[i - 1] !== "\\") { |
| 76 | + inString = false; |
| 77 | + } |
| 78 | + } else if (ch === '"' || ch === "'") { |
| 79 | + inString = true; |
| 80 | + stringChar = ch; |
| 81 | + } else if (ch === ">") { |
| 82 | + openTagEnd = i; |
| 83 | + break; |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + if (openTagEnd === -1) return result; |
| 88 | + |
| 89 | + // Find the matching closing tag — it may not be at the very end of the |
| 90 | + // value if there is trailing content (e.g., in a list item where the |
| 91 | + // description text follows the </code> within the same JSX node). |
| 92 | + const closeTag = `</${elementName}>`; |
| 93 | + const closeTagIndex = result.indexOf(closeTag, openTagEnd); |
| 94 | + if (closeTagIndex === -1) return result; |
| 95 | + |
| 96 | + const openTag = result.substring(0, openTagEnd + 1); |
| 97 | + const content = result.substring(openTagEnd + 1, closeTagIndex); |
| 98 | + const trailing = result.substring(closeTagIndex + closeTag.length); |
| 99 | + |
| 100 | + // Collapse whitespace in the content between tags |
| 101 | + const collapsed = content |
| 102 | + .replace(/\n\s*/g, " ") // newlines + indentation → single space |
| 103 | + .replace(/\s{2,}/g, " ") // multiple spaces → single space |
| 104 | + .trim(); |
| 105 | + |
| 106 | + return openTag + collapsed + closeTag + trailing; |
| 107 | +} |
| 108 | + |
| 109 | +/** |
| 110 | + * Parse the configured element list from the options. |
| 111 | + */ |
| 112 | +function getInlineElements(options) { |
| 113 | + const configured = options.mdxInlineElements; |
| 114 | + if (!configured || typeof configured !== "string") { |
| 115 | + return []; |
| 116 | + } |
| 117 | + return configured |
| 118 | + .split(",") |
| 119 | + .map((s) => s.trim()) |
| 120 | + .filter(Boolean); |
| 121 | +} |
| 122 | + |
| 123 | +/** |
| 124 | + * Check if a JSX node value starts with one of the inline element names. |
| 125 | + */ |
| 126 | +function isInlineElement(value, elements) { |
| 127 | + const trimmed = value.trim(); |
| 128 | + for (const el of elements) { |
| 129 | + if (trimmed.startsWith(`<${el}>`) || trimmed.startsWith(`<${el} `)) { |
| 130 | + return true; |
| 131 | + } |
| 132 | + } |
| 133 | + return false; |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * Walk the AST and convert matching JSX nodes to HTML nodes. |
| 138 | + */ |
| 139 | +function transformAst(ast, elements) { |
| 140 | + function walk(node) { |
| 141 | + if (node.type === "jsx" && isInlineElement(node.value, elements)) { |
| 142 | + // Convert to HTML type so prettier outputs it verbatim |
| 143 | + node.type = "html"; |
| 144 | + // Collapse multi-line content back to a single line |
| 145 | + node.value = collapseInlineJsx(node.value); |
| 146 | + } |
| 147 | + if (node.children) { |
| 148 | + node.children.forEach(walk); |
| 149 | + } |
| 150 | + } |
| 151 | + walk(ast); |
| 152 | + return ast; |
| 153 | +} |
| 154 | + |
| 155 | +/** @type {import("prettier").Plugin} */ |
| 156 | +const plugin = { |
| 157 | + options: { |
| 158 | + mdxInlineElements: { |
| 159 | + type: "string", |
| 160 | + category: "MDX", |
| 161 | + default: "", |
| 162 | + description: |
| 163 | + "Comma-separated list of JSX element names that should not be reformatted.", |
| 164 | + }, |
| 165 | + }, |
| 166 | + |
| 167 | + parsers: { |
| 168 | + "mdx-inline": { |
| 169 | + async parse(text, options) { |
| 170 | + // Delegate to the built-in MDX parser via prettier's stable plugin export |
| 171 | + const { parsers } = await import("prettier/plugins/markdown"); |
| 172 | + const ast = await parsers.mdx.parse(text, options); |
| 173 | + |
| 174 | + // Transform matching JSX nodes to prevent reformatting |
| 175 | + const elements = getInlineElements(options); |
| 176 | + transformAst(ast, elements); |
| 177 | + |
| 178 | + return ast; |
| 179 | + }, |
| 180 | + // Use the built-in mdast printer — we only modify the AST |
| 181 | + astFormat: "mdast", |
| 182 | + locStart: (node) => node.position?.start?.offset ?? 0, |
| 183 | + locEnd: (node) => node.position?.end?.offset ?? 0, |
| 184 | + }, |
| 185 | + }, |
| 186 | +}; |
| 187 | + |
| 188 | +export default plugin; |
0 commit comments