@conloca/astro-cms 0.2.2 → 0.2.3

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.
@@ -1,3 +1,4 @@
1
+ import { findContentWrapper } from '@conloca/cms-spa/content-wrapper';
1
2
  import type { Connect } from 'vite';
2
3
 
3
4
  /**
@@ -7,63 +8,10 @@ import type { Connect } from 'vite';
7
8
  * contenteditable inside a clone of whatever element the host wraps
8
9
  * its page content in. This endpoint fetches the live HTML the dev
9
10
  * server serves at `?url=<route>`, locates the relevant wrappers
10
- * (prose content + code-block chrome), and returns them as JSON.
11
- *
12
- * Returned shape:
13
- *
14
- * {
15
- * content: { tagName, className } | null,
16
- * codeBlock: { tagName, className }[] | null,
17
- * }
18
- *
19
- * - `content` is the wrapper for prose (h1-h6, p, lists, etc.). The
20
- * editor wraps its contenteditable in a clone so the host's prose
21
- * CSS reaches via the cascade.
22
- * - `codeBlock` is the ORDERED chain of classed wrappers around the
23
- * host's `<pre>`, outermost first. For Starlight's expressive-code:
24
- * `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.
25
- * The editor's CodeMirror frame renders each link as a nested
26
- * element (outer→inner) so the host's code-block CSS reaches via
27
- * the cascade including descendant selectors (`.expressive-code
28
- * .frame .header`, etc.) — not just single-class targets.
29
- *
30
- * Discovery priorities (content):
31
- *
32
- * 1. `[data-conloca-content-root]` — explicit opt-in.
33
- * 2. The smallest classed wrapper inside `<main>` containing the
34
- * majority of prose tags.
35
- * 3. `<main>` itself.
36
- * 4. `null`.
37
- *
38
- * Discovery (codeBlock): walk up from a `<pre>` inside `<main>` and
39
- * collect classed ancestors between the content wrapper and `<pre>`,
40
- * preserving their nesting order. Returns null when no `<pre>` exists,
41
- * or when there are no classed wrappers between the prose wrapper and
42
- * the `<pre>`.
11
+ * (prose content + code-block chrome) with `findContentWrapper`, and
12
+ * returns them as JSON. An editor page without this endpoint runs the
13
+ * same function on the page its style probe loads.
43
14
  */
44
- export interface ContentWrapperInfo {
45
- /** Lower-case HTML tag name as it appeared in source, eg `'article'`. */
46
- tagName: string;
47
- /** Space-separated class list from the source element. Preserved
48
- * verbatim so Astro-scoped hashes (`astro-e3flfouy`) survive — host
49
- * scoped CSS only matches when those hashes are present on the
50
- * element. */
51
- className: string;
52
- }
53
-
54
- export interface DiscoveredWrappers {
55
- /** The element wrapping the page's prose content (h1-h6, p, etc.).
56
- * For Starlight: `.sl-markdown-content`. For Tailwind Typography:
57
- * `.prose`. Null when no prose wrapper exists on the page. */
58
- content: ContentWrapperInfo | null;
59
- /** Ordered chain of classed wrappers between the content wrapper
60
- * and the `<pre>`, outermost first. For Starlight:
61
- * `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.
62
- * Null when the page has no code blocks or no classed wrappers
63
- * between the prose wrapper and the `<pre>`. */
64
- codeBlock: ContentWrapperInfo[] | null;
65
- }
66
-
67
15
  export function createContentWrapperEndpoint(): Connect.NextHandleFunction {
68
16
  return async (req, res, _next) => {
69
17
  try {
@@ -96,232 +44,3 @@ export function createContentWrapperEndpoint(): Connect.NextHandleFunction {
96
44
  }
97
45
  };
98
46
  }
99
-
100
- /** Tags whose presence signals "this element holds prose content."
101
- * We walk up from the first such element we find inside `<main>` to
102
- * locate the wrapper. Headings + paragraphs cover every prose-styling
103
- * convention we've seen — every CSS framework scopes typography
104
- * through descendant selectors on `h1`–`h6` and `p`. */
105
- const PROSE_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p']);
106
-
107
- /** Tag that anchors code-block wrapper discovery. The host's code-
108
- * block library (Starlight's expressive-code, Tailwind's `pre`
109
- * styling, etc.) always renders a `<pre>` containing the code,
110
- * often wrapped in additional classed elements. */
111
- const CODE_BLOCK_ANCHOR = 'pre';
112
-
113
- /** HTML5 void elements — never push onto the open-tag stack since they
114
- * have no closing tag. */
115
- const VOID_TAGS = new Set([
116
- 'area',
117
- 'base',
118
- 'br',
119
- 'col',
120
- 'embed',
121
- 'hr',
122
- 'img',
123
- 'input',
124
- 'link',
125
- 'meta',
126
- 'source',
127
- 'track',
128
- 'wbr',
129
- ]);
130
-
131
- interface OpenTag {
132
- tag: string;
133
- className: string;
134
- attrs: Record<string, string>;
135
- }
136
-
137
- /**
138
- * Locate the host's content + code-block wrappers in raw HTML. Single-
139
- * pass regex walk with a stack so we can recover ancestor chains for
140
- * both prose tags and `<pre>` tags without a full DOM parser dep.
141
- *
142
- * Exported for unit testing.
143
- */
144
- export function findContentWrapper(html: string): DiscoveredWrappers {
145
- // Strip comments and scripts so opening-tag-shaped strings inside
146
- // them don't pollute the walk.
147
- const cleaned = html
148
- .replace(/<!--[\s\S]*?-->/g, '')
149
- .replace(/<script[\s\S]*?<\/script>/gi, '')
150
- .replace(/<style[\s\S]*?<\/style>/gi, '');
151
-
152
- const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^>]*)?)\s*(\/?)>/g;
153
- const stack: OpenTag[] = [];
154
-
155
- let explicit: ContentWrapperInfo | null = null;
156
- let mainEl: OpenTag | null = null;
157
- const proseAncestorChains: OpenTag[][] = [];
158
- const preAncestorChains: OpenTag[][] = [];
159
-
160
- for (const match of cleaned.matchAll(tagRe)) {
161
- const isClose = match[1] === '/';
162
- const tagName = match[2].toLowerCase();
163
- const attrBlob = match[3] ?? '';
164
- const explicitlySelfClosing = match[4] === '/';
165
-
166
- if (isClose) {
167
- for (let i = stack.length - 1; i >= 0; i--) {
168
- if (stack[i].tag === tagName) {
169
- stack.length = i;
170
- break;
171
- }
172
- }
173
- continue;
174
- }
175
-
176
- const attrs = parseAttributes(attrBlob);
177
- const className = attrs.class ?? '';
178
- const el: OpenTag = { tag: tagName, className, attrs };
179
-
180
- // Priority 1 (content only): explicit opt-in. Capture and keep
181
- // walking — we still need to discover the code-block wrapper.
182
- if (!explicit && 'data-conloca-content-root' in attrs) {
183
- explicit = { tagName, className };
184
- }
185
-
186
- if (!mainEl && tagName === 'main') {
187
- mainEl = el;
188
- }
189
-
190
- if (mainEl && PROSE_TAGS.has(tagName)) {
191
- const mainIdx = stack.indexOf(mainEl);
192
- if (mainIdx >= 0) {
193
- proseAncestorChains.push(stack.slice(mainIdx + 1));
194
- }
195
- }
196
-
197
- if (mainEl && tagName === CODE_BLOCK_ANCHOR) {
198
- const mainIdx = stack.indexOf(mainEl);
199
- if (mainIdx >= 0) {
200
- preAncestorChains.push(stack.slice(mainIdx + 1));
201
- }
202
- }
203
-
204
- const isVoid = VOID_TAGS.has(tagName);
205
- if (!isVoid && !explicitlySelfClosing) {
206
- stack.push(el);
207
- }
208
- }
209
-
210
- const content = resolveContentWrapper(explicit, mainEl, proseAncestorChains);
211
- const codeBlock = resolveCodeBlockWrapper(content, preAncestorChains);
212
-
213
- return { content, codeBlock };
214
- }
215
-
216
- /**
217
- * Pick the content wrapper from the walk's collected data.
218
- *
219
- * Priority: explicit opt-in > majority-prose-wrapper-inside-main >
220
- * `<main>` fallback > null.
221
- */
222
- function resolveContentWrapper(
223
- explicit: ContentWrapperInfo | null,
224
- mainEl: OpenTag | null,
225
- proseAncestorChains: OpenTag[][],
226
- ): ContentWrapperInfo | null {
227
- if (explicit) return explicit;
228
- if (!mainEl) return null;
229
-
230
- if (proseAncestorChains.length === 0) {
231
- return { tagName: 'main', className: mainEl.className };
232
- }
233
-
234
- // Tally classed-ancestor occurrences across all prose chains.
235
- const scores = new Map<OpenTag, number>();
236
- for (const chain of proseAncestorChains) {
237
- for (const ancestor of chain) {
238
- if (!ancestor.className) continue;
239
- scores.set(ancestor, (scores.get(ancestor) ?? 0) + 1);
240
- }
241
- }
242
-
243
- // Majority threshold rules out partial-coverage classed ancestors
244
- // (single Cards holding one of many prose blocks).
245
- const threshold = proseAncestorChains.length / 2;
246
- const candidates = [...scores.entries()].filter(([, count]) => count > threshold);
247
-
248
- if (candidates.length === 0) {
249
- return { tagName: 'main', className: mainEl.className };
250
- }
251
-
252
- // Tie-break by depth: the candidate that appears deepest in any
253
- // chain is the most specific (closest to the prose tags).
254
- const maxChainIndex = (el: OpenTag) => Math.max(...proseAncestorChains.map((c) => c.indexOf(el)));
255
- candidates.sort((a, b) => {
256
- if (b[1] !== a[1]) return b[1] - a[1];
257
- return maxChainIndex(b[0]) - maxChainIndex(a[0]);
258
- });
259
-
260
- const winner = candidates[0][0];
261
- return { tagName: winner.tag, className: winner.className };
262
- }
263
-
264
- /**
265
- * Derive the code-block wrapper chain from a representative `<pre>`'s
266
- * ancestor chain. We strip everything at or above the content wrapper
267
- * (its styles are already handled by the content-wrapper mirror) and
268
- * return the remaining classed elements in nesting order, outermost
269
- * first.
270
- *
271
- * Returning a chain (instead of one collapsed element) preserves the
272
- * shape host CSS expects:
273
- *
274
- * - Single-class selectors (`.frame { ... }`) hit on whichever link
275
- * carries that class.
276
- * - Descendant selectors (`.expressive-code .frame { ... }`,
277
- * `.frame .header > .title`) hit because the editor's renderer
278
- * materialises the chain as nested elements with the host's
279
- * expected tag names.
280
- *
281
- * The editor's code-block frame component (`code-block-frame.tsx` in
282
- * `@conloca/mdx`) treats the LAST link as the "frame" element (where
283
- * figcaption/pre/copy children render) and wraps it with the earlier
284
- * links from inside out. This matches the host's authoring shape for
285
- * libraries like ExpressiveCode (`.expressive-code > figure.frame >
286
- * figcaption + pre + .copy`).
287
- */
288
- function resolveCodeBlockWrapper(
289
- content: ContentWrapperInfo | null,
290
- preAncestorChains: OpenTag[][],
291
- ): ContentWrapperInfo[] | null {
292
- if (preAncestorChains.length === 0) return null;
293
-
294
- // Pick the first <pre>'s chain as representative. Code blocks on a
295
- // single page are uniformly wrapped, so chains are interchangeable.
296
- const chain = preAncestorChains[0];
297
-
298
- // Strip everything at-or-above the content wrapper; the rest is
299
- // code-block-specific chrome that this endpoint is responsible for.
300
- const contentIdx = content
301
- ? chain.findIndex((el) => el.tag === content.tagName && el.className === content.className)
302
- : -1;
303
- const codeBlockChain = chain.slice(contentIdx + 1);
304
-
305
- const classedAncestors = codeBlockChain.filter((el) => el.className);
306
- if (classedAncestors.length === 0) return null;
307
-
308
- return classedAncestors.map((el) => ({ tagName: el.tag, className: el.className }));
309
- }
310
-
311
- /**
312
- * Parse the attribute blob inside an opening tag. Handles `name="v"`,
313
- * `name='v'`, `name=v`, and boolean (no-value) attributes. Doesn't
314
- * handle entity decoding (`&amp;` → `&`) since the values we read
315
- * (tag name, class list, the marker attribute) don't carry entities
316
- * in practice.
317
- */
318
- function parseAttributes(s: string): Record<string, string> {
319
- const out: Record<string, string> = {};
320
- const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
321
- for (const match of s.matchAll(re)) {
322
- const name = match[1];
323
- const value = match[2] ?? match[3] ?? match[4] ?? '';
324
- out[name] = value;
325
- }
326
- return out;
327
- }