@writedocs/generator 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ // Turns an HTML fragment into MDX that renders the same HTML - for ReadMe's
2
+ // <HTMLBlock> and its HTML landing page, which hold whole hand-written
3
+ // pages: <style> sheets, inline SVG, `class` and `style` attributes,
4
+ // comments. None of that is valid MDX as written, and MDX has no "raw
5
+ // HTML" escape hatch writedocs can use (`<Fragment set:html>` isn't
6
+ // resolved in a page), so the HTML is parsed (parse5, the HTML spec's own
7
+ // parser) and written back out as JSX:
8
+ //
9
+ // - `class` -> `className`, `for` -> `htmlFor`, a `style` string -> a style
10
+ // object; every other attribute keeps its HTML name (`fill-rule`,
11
+ // `viewBox`, `xlink:href`, `data-*`), which Astro renders unchanged.
12
+ // - Void elements are self-closed; comments, <meta>, <title> and <base> are
13
+ // dropped; <html>/<head>/<body> wrappers are unwrapped by the parser.
14
+ // - <style> and <script> keep their text exactly, as a template literal.
15
+ // MDX halves backslashes before the expression reaches the JavaScript
16
+ // parser (`"\\201C"` arrives as the invalid escape `"\201C"`), so every
17
+ // backslash, backtick and `$` is written as a \u escape instead.
18
+ // - Text: an element whose children include text is written on one line,
19
+ // so MDX keeps it inline instead of wrapping it in <p>. Its text is
20
+ // Markdown-escaped (MDX parses Markdown inside JSX: `*a*` would become
21
+ // <em>). Elements that hold only elements are written one per line,
22
+ // indented, with no blank lines - a blank line inside JSX would turn
23
+ // what follows into Markdown paragraphs.
24
+ // - <pre> and <textarea> keep their whitespace, as a string expression.
25
+ //
26
+ // `rewriteUrl(url, attribute)` lets the caller change href/src values -
27
+ // ReadMe links to local pages, images to their downloaded copies.
28
+
29
+ import { parseFragment } from 'parse5';
30
+
31
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
32
+ const DROPPED = new Set(['meta', 'title', 'base']);
33
+ const RAW_TEXT = new Set(['style', 'script']);
34
+ const PRESERVE_WS = new Set(['pre', 'textarea']);
35
+ const URL_ATTRS = new Set(['href', 'src', 'poster', 'action', 'xlink:href']);
36
+ const RENAMED = { class: 'className', for: 'htmlFor' };
37
+
38
+ /** A JavaScript string literal that survives MDX: every character MDX or
39
+ * a JS string could read specially is a \u escape. */
40
+ export function mdxJsString(value) {
41
+ return `"${String(value).replace(/[\\"\n\r\u2028\u2029`$<>{}]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`)}"`;
42
+ }
43
+
44
+ /** A template literal's body that survives MDX - see the comment above. */
45
+ function mdxTemplateBody(value) {
46
+ return String(value).replace(/[\\`$]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
47
+ }
48
+
49
+ /** Splits CSS declarations on `;`, but not inside parentheses or quotes
50
+ * (`background: url(data:image/png;base64,...)`). */
51
+ function splitDeclarations(css) {
52
+ const out = [];
53
+ let depth = 0;
54
+ let quote = null;
55
+ let start = 0;
56
+ for (let i = 0; i < css.length; i++) {
57
+ const c = css[i];
58
+ if (quote) {
59
+ if (c === '\\') i++;
60
+ else if (c === quote) quote = null;
61
+ } else if (c === '"' || c === "'") quote = c;
62
+ else if (c === '(') depth++;
63
+ else if (c === ')') depth = Math.max(0, depth - 1);
64
+ else if (c === ';' && depth === 0) {
65
+ out.push(css.slice(start, i));
66
+ start = i + 1;
67
+ }
68
+ }
69
+ out.push(css.slice(start));
70
+ return out.map((d) => d.trim()).filter(Boolean);
71
+ }
72
+
73
+ /** A style attribute's text as a JSX style object: `color: red; font-size: 2px`
74
+ * -> `{{ color: "red", fontSize: "2px" }}`. Custom properties keep their
75
+ * name, quoted. */
76
+ export function styleToJsx(css) {
77
+ const entries = [];
78
+ for (const decl of splitDeclarations(String(css).replace(/\/\*[\s\S]*?\*\//g, ''))) {
79
+ const colon = decl.indexOf(':');
80
+ if (colon < 1) continue;
81
+ const prop = decl.slice(0, colon).trim();
82
+ const value = decl.slice(colon + 1).trim();
83
+ if (!prop || !value) continue;
84
+ let key;
85
+ if (prop.startsWith('--')) key = mdxJsString(prop);
86
+ else {
87
+ const camel = prop.toLowerCase().replace(/^-ms-/, 'ms-').replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
88
+ key = /^[A-Za-z_$][\w$]*$/.test(camel) ? camel : mdxJsString(camel);
89
+ }
90
+ entries.push(`${key}: ${mdxJsString(value)}`);
91
+ }
92
+ return `{{ ${entries.join(', ')} }}`;
93
+ }
94
+
95
+ /** Escapes text so MDX shows it as written: Markdown punctuation gets a
96
+ * backslash, and `{`, `}`, `<`, `>` (which a backslash doesn't protect in
97
+ * MDX) become character references. */
98
+ export function escapeMdxText(text) {
99
+ return String(text)
100
+ .replace(/[\\`*_[\]#|~!]/g, (c) => `\\${c}`)
101
+ .replace(/&/g, '&amp;')
102
+ .replace(/[{}<>]/g, (c) => `&#${c.charCodeAt(0)};`);
103
+ }
104
+
105
+ function attrName(attr) {
106
+ const name = attr.prefix ? `${attr.prefix}:${attr.name}` : attr.name;
107
+ return RENAMED[name] ?? name;
108
+ }
109
+
110
+ function attrValue(value) {
111
+ return /^[^"\\{}<>\n\r&]*$/.test(value) ? `"${value}"` : `{${mdxJsString(value)}}`;
112
+ }
113
+
114
+ function attributes(node, rewriteUrl) {
115
+ const parts = [];
116
+ for (const attr of node.attrs ?? []) {
117
+ const original = attr.prefix ? `${attr.prefix}:${attr.name}` : attr.name;
118
+ // An attribute name JSX can't hold (`@click`, `x-on:foo.bar`) is dropped.
119
+ if (!/^[A-Za-z_][\w.:-]*$/.test(original) || /[.]/.test(original)) continue;
120
+ let value = attr.value;
121
+ if (original === 'style') {
122
+ const style = styleToJsx(value);
123
+ if (style !== '{{ }}') parts.push(`style=${style}`);
124
+ continue;
125
+ }
126
+ if (URL_ATTRS.has(original) && rewriteUrl) value = rewriteUrl(value, original) ?? value;
127
+ parts.push(`${attrName(attr)}=${attrValue(value)}`);
128
+ }
129
+ return parts.length ? ` ${parts.join(' ')}` : '';
130
+ }
131
+
132
+ const isText = (n) => n.nodeName === '#text';
133
+ const isElement = (n) => n.tagName !== undefined;
134
+ const textOf = (n) => (n.childNodes ?? []).map((c) => (isText(c) ? c.value : isElement(c) ? textOf(c) : '')).join('');
135
+
136
+ function children(node) {
137
+ // <template> keeps its children in .content.
138
+ return node.content ? node.content.childNodes : node.childNodes ?? [];
139
+ }
140
+
141
+ /** One element written on a single line - its text inline. */
142
+ function inline(node, rewriteUrl) {
143
+ if (isText(node)) return escapeMdxText(node.value.replace(/\s+/g, ' '));
144
+ if (!isElement(node) || DROPPED.has(node.tagName)) return '';
145
+ return element(node, rewriteUrl, null);
146
+ }
147
+
148
+ function element(node, rewriteUrl, indent) {
149
+ const tag = node.tagName;
150
+ const open = `<${tag}${attributes(node, rewriteUrl)}`;
151
+ if (VOID.has(tag)) return `${open} />`;
152
+ if (RAW_TEXT.has(tag)) {
153
+ const text = textOf(node);
154
+ return text.trim() ? `${open}>{\`${mdxTemplateBody(text)}\`}</${tag}>` : `${open}></${tag}>`;
155
+ }
156
+ if (PRESERVE_WS.has(tag)) {
157
+ const text = textOf(node);
158
+ return text ? `${open}>{${mdxJsString(text)}}</${tag}>` : `${open}></${tag}>`;
159
+ }
160
+ const kids = children(node).filter((c) => isElement(c) || isText(c));
161
+ const hasText = kids.some((c) => isText(c) && c.value.trim());
162
+ if (!kids.some((c) => isElement(c) || c.value.trim())) return `${open}></${tag}>`;
163
+ if (hasText || indent === null) {
164
+ // Inline: one line, whitespace between parts collapsed to one space.
165
+ const body = kids.map((c) => inline(c, rewriteUrl)).join('').replace(/^ +| +$/g, '');
166
+ return `${open}>${body}</${tag}>`;
167
+ }
168
+ const pad = `${indent} `;
169
+ const lines = kids.filter(isElement).filter((c) => !DROPPED.has(c.tagName)).map((c) => pad + element(c, rewriteUrl, pad));
170
+ return `${open}>\n${lines.join('\n')}\n${indent}</${tag}>`;
171
+ }
172
+
173
+ /**
174
+ * The MDX for an HTML fragment: one block, no blank lines inside it.
175
+ * Top-level text becomes a <p>-free inline run of its own; top-level
176
+ * elements are written one after another.
177
+ *
178
+ * @param {string} html
179
+ * @param {{ rewriteUrl?: (url: string, attribute: string) => string | undefined }} [options]
180
+ */
181
+ export function htmlToMdx(html, { rewriteUrl } = {}) {
182
+ const fragment = parseFragment(String(html ?? ''));
183
+ const out = [];
184
+ let run = [];
185
+ const flush = () => {
186
+ const text = run.join('').replace(/\s+/g, ' ').trim();
187
+ if (text) out.push(`<span>${text}</span>`);
188
+ run = [];
189
+ };
190
+ for (const node of fragment.childNodes) {
191
+ if (isText(node)) {
192
+ if (node.value.trim()) run.push(escapeMdxText(node.value));
193
+ continue;
194
+ }
195
+ if (!isElement(node) || DROPPED.has(node.tagName)) continue;
196
+ flush();
197
+ out.push(element(node, rewriteUrl, ''));
198
+ }
199
+ flush();
200
+ return out.join('\n');
201
+ }