@threadlabs/looma 0.43.0 → 0.43.1
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.
- package/components/ui-card/ui-card.html +6 -6
- package/components/ui-editor-mention-menu/ui-editor-mention-menu.js +3 -0
- package/components/ui-editor-slash-menu/ui-editor-slash-menu.js +4 -0
- package/components/ui-editor-table-overlay/ui-editor-table-overlay.html +1 -0
- package/dist/index.js +1 -1
- package/docs/README.md +2 -2
- package/docs/card.html +2 -6
- package/docs/card.js +7 -37
- package/docs/catalog.json +214 -10
- package/docs/catalog.mjs +1 -1
- package/docs/customizer-render.mjs +7 -6
- package/docs/customizer.js +2 -7
- package/docs/documentation.css +3 -7
- package/docs/examples/ui-button/examples/08-loading.behavior.js +1 -1
- package/docs/examples/ui-checkbox/examples/02-checked-indeterminate-and-disabled.behavior.js +1 -1
- package/docs/examples/ui-editor-mention-menu/examples/00-preview.behavior.js +1 -0
- package/docs/examples/ui-editor-slash-menu/examples/00-preview.behavior.js +81 -0
- package/docs/examples/ui-editor-table-overlay/examples/00-preview.behavior.js +24 -0
- package/docs/examples/ui-search-shell/examples/00-preview.behavior.js +14 -0
- package/docs/examples/ui-search-shell/examples/02-label-dismissible-status-and-footer.behavior.js +7 -7
- package/docs/examples/ui-toast/examples/01-authored.behavior.js +2 -2
- package/docs/index.d.ts +1 -1
- package/docs/local-server.mjs +2 -5
- package/docs/pastoral.svg +54 -0
- package/docs/portrait.svg +15 -0
- package/docs/render.mjs +33 -3
- package/docs/site.mjs +22 -54
- package/package.json +1 -1
- package/styles/ui-card.css +6 -6
- package/vanilla/UiEditorTableOverlay.js +50 -36
- package/vue/UiCard.vue +6 -6
- package/vue/UiEditorTableOverlay.d.ts +11 -1
- package/vue/UiEditorTableOverlay.vue +98 -63
- package/vue/chunks/UiCard.js +1 -1
- package/vue/chunks/UiEditorTableOverlay.js +41 -13
- package/vue/components.css +54 -53
- package/docs/preview.js +0 -22
package/docs/customizer.js
CHANGED
|
@@ -157,7 +157,6 @@ export function connect(host) {
|
|
|
157
157
|
const report = root.querySelector('[data-palette-adjustments]');
|
|
158
158
|
report.textContent = adjustments.length ? 'Paired ranges are derived for readability. Your base colors stay editable; resolved values are shown below.' : 'Both ranges preserve your base colors with readable text and essential outlines.';
|
|
159
159
|
root.querySelector('[data-palette-adjustment-details]').textContent = adjustments.length ? adjustments.map(item => `${item.mode} ${fields.get(item.id).label.toLowerCase()} ${item.requested} → ${item.resolved}`).join('; ') + '. Base colors remain editable.' : 'Both ranges preserve your base colors with readable text and essential outlines.';
|
|
160
|
-
for (const card of root.querySelectorAll('[data-example-card]')) card.dispatchEvent(new CustomEvent('looma-theme-preview', { detail: { css } }));
|
|
161
160
|
const cssControl = root.querySelector('[data-css]');
|
|
162
161
|
if (cssControl.getClientRects().length) updateControl(cssControl, css);
|
|
163
162
|
for (const action of ['undo','redo']) componentRegistry.update(root.querySelector(`[data-action="${action}"]`), { disabled: !theme?.[action === 'undo' ? 'canUndo' : 'canRedo'] });
|
|
@@ -320,7 +319,7 @@ export function connect(host) {
|
|
|
320
319
|
const option = [...root.querySelectorAll('[data-add-example] option')].find(option => option.value === selectedExample);
|
|
321
320
|
if (!option) break;
|
|
322
321
|
const selected = JSON.parse(option.dataset.example);
|
|
323
|
-
const card = Object.fromEntries(['id','title','description','exampleTitle','
|
|
322
|
+
const card = Object.fromEntries(['id','title','description','exampleTitle','resizable','category','tag','nativeRoot','href','packageName'].map(key => [key, selected[key]]));
|
|
324
323
|
removedExamples.delete(card.id);
|
|
325
324
|
if (!host.state.cards.some(item => item.id === card.id)) host.state.cards = [card, ...host.state.cards];
|
|
326
325
|
updateControl(root.querySelector('[data-example-query]'), ''); previewQuery = '';
|
|
@@ -412,9 +411,6 @@ export function connect(host) {
|
|
|
412
411
|
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'z' || event.target.closest?.('input,textarea,select,[contenteditable="true"]')) return;
|
|
413
412
|
event.preventDefault(); flush(); theme?.[event.shiftKey ? 'redo' : 'undo'](); show(theme?.recipe ?? recipe, false);
|
|
414
413
|
};
|
|
415
|
-
const ready = event => {
|
|
416
|
-
if (event.data?.type === 'looma-preview-ready' && [...root.querySelectorAll('iframe')].some(frame => frame.contentWindow === event.source)) paint();
|
|
417
|
-
};
|
|
418
414
|
const remove = event => {
|
|
419
415
|
const example = catalogExamples.find(card => card.id === event.detail.id);
|
|
420
416
|
const chosen = host.state.cards.some(card => card.id === event.detail.id);
|
|
@@ -468,7 +464,6 @@ export function connect(host) {
|
|
|
468
464
|
root.addEventListener('blur', blur, true);
|
|
469
465
|
root.addEventListener('change', change);
|
|
470
466
|
root.addEventListener('click', click);
|
|
471
|
-
view.addEventListener('message', ready);
|
|
472
467
|
view.addEventListener('popstate', renderView);
|
|
473
468
|
view.addEventListener('hashchange', renderView);
|
|
474
469
|
view.addEventListener('beforeunload', flush);
|
|
@@ -486,5 +481,5 @@ export function connect(host) {
|
|
|
486
481
|
root.querySelector('[data-action="save"]').hidden = false;
|
|
487
482
|
}).catch(error => { if (alive && error.name !== 'AbortError') say(error.message, true); });
|
|
488
483
|
}
|
|
489
|
-
return () => { previewObserver.disconnect(); if (layoutFrame) view.cancelAnimationFrame(layoutFrame); view.removeEventListener('resize', schedulePreviewLayout); motionPreference.removeEventListener('change', motionPreferenceChanged); root.removeEventListener('toggle', updateSizes, true); motionAnimation?.cancel(); flush(); root.removeEventListener('cancel', cancel); root.removeEventListener('keydown', keyboard); alive = false; abort.abort(); root.removeEventListener('looma-example-remove', remove); root.removeEventListener('input', input); root.removeEventListener('value-change', choose); root.removeEventListener('value-change', selectExample); root.removeEventListener('value-change', selectFont); root.removeEventListener('blur', blur, true); root.removeEventListener('change', change); root.removeEventListener('click', click); view.removeEventListener('beforeunload', flush); view.removeEventListener('
|
|
484
|
+
return () => { previewObserver.disconnect(); if (layoutFrame) view.cancelAnimationFrame(layoutFrame); view.removeEventListener('resize', schedulePreviewLayout); motionPreference.removeEventListener('change', motionPreferenceChanged); root.removeEventListener('toggle', updateSizes, true); motionAnimation?.cancel(); flush(); root.removeEventListener('cancel', cancel); root.removeEventListener('keydown', keyboard); alive = false; abort.abort(); root.removeEventListener('looma-example-remove', remove); root.removeEventListener('input', input); root.removeEventListener('value-change', choose); root.removeEventListener('value-change', selectExample); root.removeEventListener('value-change', selectFont); root.removeEventListener('blur', blur, true); root.removeEventListener('change', change); root.removeEventListener('click', click); view.removeEventListener('beforeunload', flush); view.removeEventListener('popstate', renderView); view.removeEventListener('hashchange', renderView); view.removeEventListener(themeEvent, synchronize); };
|
|
490
485
|
}
|
package/docs/documentation.css
CHANGED
|
@@ -1,18 +1,14 @@
|
|
|
1
1
|
:root { --markupress-header-notice-display: none; }
|
|
2
2
|
:root[data-looma-documentation-theme] { --markupress-header-notice-display: inline-flex; }
|
|
3
|
-
/* Documentation presentation owns
|
|
4
|
-
[data-example-card] iframe { display: block; max-inline-size: 100%; border: 0; background: transparent; }
|
|
3
|
+
/* Documentation presentation owns its native example stage. Controls use Looma. */
|
|
5
4
|
[data-example-card] pre { overflow: auto; }
|
|
6
5
|
/* The customizer is an application page; use Markupress's public width token instead of patching its layout. */
|
|
7
6
|
:root:has([data-looma-customizer]), :root:has([data-component~="looma-catalog"]) { --markupress-content-width: 110rem; }
|
|
8
|
-
|
|
9
|
-
[data-preview] { display: grid; place-items: center; gap: var(--ui-space-4); min-block-size: 13rem; padding: 1.35rem; box-sizing: border-box; }
|
|
7
|
+
[data-preview] { display: grid; place-items: center; gap: var(--ui-space-4); min-inline-size: 0; min-block-size: 13rem; padding: var(--ui-space-4); box-sizing: border-box; color: var(--ui-text); font-family: var(--ui-font-sans); font-size: var(--ui-font-size); line-height: var(--ui-line-height); background: linear-gradient(90deg, rgb(43 37 56 / .035) 1px, transparent 1px), linear-gradient(rgb(43 37 56 / .035) 1px, transparent 1px), color-mix(in srgb, var(--ui-accent) 5%, var(--ui-surface)); background-size: 22px 22px; }
|
|
10
8
|
[data-preview-layout] { justify-items: stretch; }
|
|
11
|
-
body:has([data-preview]) { margin: 0; background: linear-gradient(90deg, rgb(43 37 56 / .035) 1px, transparent 1px), linear-gradient(rgb(43 37 56 / .035) 1px, transparent 1px), color-mix(in srgb, var(--ui-accent) 5%, var(--ui-surface)); background-size: 22px 22px; }
|
|
12
9
|
|
|
13
10
|
/* These headings are authored page content projected through the example card's heading slot. */
|
|
14
11
|
.looma-reference-examples { padding-block-start: var(--ui-space-5); }
|
|
15
12
|
.looma-example-heading h3 { margin: 0; font-size: var(--ui-font-size-lg); line-height: var(--ui-line-height-tight); }
|
|
16
13
|
.looma-example-heading p { margin: var(--ui-space-2) 0 0; font-size: var(--ui-font-size-sm); color: var(--ui-text-secondary); }
|
|
17
|
-
|
|
18
|
-
html[data-preview-reference] [data-preview] { min-block-size: 11rem; }
|
|
14
|
+
[data-example-card][reference] [data-preview] { min-block-size: 11rem; background: var(--ui-surface); }
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { componentRegistry } from "@nextwebwg/html-next/runtime";
|
|
2
2
|
/** Simulates a save so the example shows the transition into and out of loading. */
|
|
3
3
|
export default function saveChanges(root) {
|
|
4
|
-
const button = root.querySelector("
|
|
4
|
+
const button = root.querySelector('[data-example-id="docs-save-changes"]');
|
|
5
5
|
if (!button)
|
|
6
6
|
return () => { };
|
|
7
7
|
let timer;
|
package/docs/examples/ui-checkbox/examples/02-checked-indeterminate-and-disabled.behavior.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { componentRegistry } from "@nextwebwg/html-next/runtime";
|
|
2
2
|
/** Keeps the summary checkbox in step with three independently checked items. */
|
|
3
3
|
export default function connectSelection(root) {
|
|
4
|
-
const all = root.querySelector("
|
|
4
|
+
const all = root.querySelector('[data-example-id="docs-checkbox-all"]');
|
|
5
5
|
const items = Array.from(root.querySelectorAll(".docs-checkbox-item"));
|
|
6
6
|
if (!all || !items.length)
|
|
7
7
|
return () => { };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { openPicker as default } from "../../ui-editor-slash-menu/examples/00-preview.behavior.js";
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { componentRegistry } from "@nextwebwg/html-next/runtime";
|
|
2
|
+
/** The host owns keyboard selection and dismissal for editor suggestion surfaces. */
|
|
3
|
+
export function openPicker(root) {
|
|
4
|
+
const trigger = root.querySelector("[data-demo-trigger]");
|
|
5
|
+
const surface = root.querySelector("[data-demo-surface]");
|
|
6
|
+
if (!trigger || !surface)
|
|
7
|
+
return () => { };
|
|
8
|
+
let open = false, selectedIndex = 0, frame = 0;
|
|
9
|
+
const options = () => [...surface.querySelectorAll('[role="option"]')].filter(option => !option.hidden && option.getAttribute("aria-disabled") !== "true");
|
|
10
|
+
const select = (index) => {
|
|
11
|
+
const rows = options();
|
|
12
|
+
selectedIndex = rows.length ? (index + rows.length) % rows.length : 0;
|
|
13
|
+
componentRegistry.update(surface, { selectedIndex });
|
|
14
|
+
const active = rows[selectedIndex];
|
|
15
|
+
if (active?.id)
|
|
16
|
+
surface.setAttribute("aria-activedescendant", active.id);
|
|
17
|
+
};
|
|
18
|
+
const close = () => {
|
|
19
|
+
open = false;
|
|
20
|
+
cancelAnimationFrame(frame);
|
|
21
|
+
componentRegistry.update(surface, { open: false });
|
|
22
|
+
trigger.setAttribute("aria-expanded", "false");
|
|
23
|
+
};
|
|
24
|
+
const commit = () => { close(); trigger.focus(); };
|
|
25
|
+
const toggle = () => {
|
|
26
|
+
if (open) {
|
|
27
|
+
close();
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
open = true;
|
|
31
|
+
selectedIndex = 0;
|
|
32
|
+
componentRegistry.update(surface, { open: true, selectedIndex, anchorRect: trigger.getBoundingClientRect().toJSON() });
|
|
33
|
+
trigger.setAttribute("aria-expanded", "true");
|
|
34
|
+
frame = requestAnimationFrame(() => { select(0); surface.focus(); });
|
|
35
|
+
};
|
|
36
|
+
const keyboard = (event) => {
|
|
37
|
+
if (!open) {
|
|
38
|
+
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
39
|
+
event.preventDefault();
|
|
40
|
+
toggle();
|
|
41
|
+
}
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (event.key === "Escape") {
|
|
45
|
+
event.preventDefault();
|
|
46
|
+
commit();
|
|
47
|
+
}
|
|
48
|
+
else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
49
|
+
event.preventDefault();
|
|
50
|
+
select(selectedIndex + (event.key === "ArrowDown" ? 1 : -1));
|
|
51
|
+
}
|
|
52
|
+
else if (event.key === "Enter") {
|
|
53
|
+
event.preventDefault();
|
|
54
|
+
options()[selectedIndex]?.click();
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const highlight = (event) => select(event.detail.index);
|
|
58
|
+
const reposition = () => { if (open)
|
|
59
|
+
componentRegistry.update(surface, { anchorRect: trigger.getBoundingClientRect().toJSON() }); };
|
|
60
|
+
const view = root.ownerDocument.defaultView;
|
|
61
|
+
const outside = (event) => { if (open && !surface.contains(event.target) && !trigger.contains(event.target))
|
|
62
|
+
close(); };
|
|
63
|
+
trigger.addEventListener("click", toggle);
|
|
64
|
+
root.addEventListener("keydown", keyboard);
|
|
65
|
+
surface.addEventListener("select", commit);
|
|
66
|
+
surface.addEventListener("highlight", highlight);
|
|
67
|
+
view?.addEventListener("scroll", reposition, { capture: true, passive: true });
|
|
68
|
+
view?.addEventListener("resize", reposition);
|
|
69
|
+
root.ownerDocument.addEventListener("pointerdown", outside);
|
|
70
|
+
return () => {
|
|
71
|
+
cancelAnimationFrame(frame);
|
|
72
|
+
trigger.removeEventListener("click", toggle);
|
|
73
|
+
root.removeEventListener("keydown", keyboard);
|
|
74
|
+
surface.removeEventListener("select", commit);
|
|
75
|
+
surface.removeEventListener("highlight", highlight);
|
|
76
|
+
view?.removeEventListener("scroll", reposition, true);
|
|
77
|
+
view?.removeEventListener("resize", reposition);
|
|
78
|
+
root.ownerDocument.removeEventListener("pointerdown", outside);
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
export default openPicker;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { componentRegistry } from "@nextwebwg/html-next/runtime";
|
|
2
|
+
/** Keep the controls aligned with the real cells at every preview width. */
|
|
3
|
+
export default function setup(root) {
|
|
4
|
+
const surface = root.querySelector("[data-demo-table-controls]");
|
|
5
|
+
const table = surface?.querySelector("table");
|
|
6
|
+
if (!surface || !table)
|
|
7
|
+
return () => { };
|
|
8
|
+
const measure = () => {
|
|
9
|
+
const origin = surface.getBoundingClientRect();
|
|
10
|
+
const rows = [...table.rows], cells = [...(rows[0]?.cells ?? [])];
|
|
11
|
+
if (!rows.length || !cells.length)
|
|
12
|
+
return;
|
|
13
|
+
const cell = cells[0].getBoundingClientRect();
|
|
14
|
+
componentRegistry.update(surface, { geometry: {
|
|
15
|
+
rowBoundaries: [...rows.map(row => row.getBoundingClientRect().top - origin.top), rows.at(-1).getBoundingClientRect().bottom - origin.top],
|
|
16
|
+
columnBoundaries: [...cells.map(cell => cell.getBoundingClientRect().left - origin.left), cells.at(-1).getBoundingClientRect().right - origin.left],
|
|
17
|
+
activeCell: { left: cell.left - origin.left, top: cell.top - origin.top, width: cell.width, height: cell.height, rowIndex: 0, columnIndex: 0 },
|
|
18
|
+
} });
|
|
19
|
+
};
|
|
20
|
+
const observer = new ResizeObserver(measure);
|
|
21
|
+
observer.observe(table);
|
|
22
|
+
measure();
|
|
23
|
+
return () => observer.disconnect();
|
|
24
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { componentRegistry } from "@nextwebwg/html-next/runtime";
|
|
2
|
+
/** Opens this specimen from its own trigger and closes it after a choice. */
|
|
3
|
+
export default function setup(root) {
|
|
4
|
+
const trigger = root.querySelector("[data-demo-trigger]");
|
|
5
|
+
const surface = root.querySelector("[data-demo-surface]");
|
|
6
|
+
if (!trigger || !surface)
|
|
7
|
+
return () => { };
|
|
8
|
+
const open = () => componentRegistry.update(surface, { open: true });
|
|
9
|
+
const close = () => componentRegistry.update(surface, { open: false });
|
|
10
|
+
trigger.addEventListener("click", open);
|
|
11
|
+
surface.addEventListener("select", close);
|
|
12
|
+
surface.addEventListener("close", close);
|
|
13
|
+
return () => { trigger.removeEventListener("click", open); surface.removeEventListener("select", close); surface.removeEventListener("close", close); };
|
|
14
|
+
}
|
package/docs/examples/ui-search-shell/examples/02-label-dismissible-status-and-footer.behavior.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/** Filters the example's results as the query changes; a real application would query its index. */
|
|
2
2
|
export default function filterResults(root) {
|
|
3
3
|
const update = () => {
|
|
4
|
-
const input = root.querySelector("
|
|
5
|
-
const status = root.querySelector("
|
|
6
|
-
const empty = root.querySelector("
|
|
4
|
+
const input = root.querySelector('[data-example-id="docs-search-input"]');
|
|
5
|
+
const status = root.querySelector('[data-example-id="docs-search-status"]');
|
|
6
|
+
const empty = root.querySelector('[data-example-id="docs-search-empty"]');
|
|
7
7
|
const results = [
|
|
8
|
-
root.querySelector("
|
|
9
|
-
root.querySelector("
|
|
10
|
-
root.querySelector("
|
|
8
|
+
root.querySelector('[data-example-id="docs-result-design-tokens"]'),
|
|
9
|
+
root.querySelector('[data-example-id="docs-result-token-overrides"]'),
|
|
10
|
+
root.querySelector('[data-example-id="docs-result-button-variants"]')
|
|
11
11
|
].filter((result) => result !== null);
|
|
12
12
|
if (!input || !status || !empty || results.length === 0)
|
|
13
13
|
return;
|
|
@@ -22,7 +22,7 @@ export default function filterResults(root) {
|
|
|
22
22
|
empty.hidden = visible !== 0;
|
|
23
23
|
};
|
|
24
24
|
const onInput = (event) => {
|
|
25
|
-
if (event.target?.
|
|
25
|
+
if (event.target?.dataset.exampleId === "docs-search-input")
|
|
26
26
|
update();
|
|
27
27
|
};
|
|
28
28
|
root.addEventListener("input", onInput);
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/** Shows a hidden authored toast when the example's button is pressed; the toast hides itself when dismissed. */
|
|
2
2
|
export function showToastOnClick(buttonId, toastId) {
|
|
3
3
|
return (root) => {
|
|
4
|
-
const button = root.querySelector(
|
|
5
|
-
const toast = root.querySelector(
|
|
4
|
+
const button = root.querySelector(`[data-example-id="${buttonId}"]`);
|
|
5
|
+
const toast = root.querySelector(`[data-example-id="${toastId}"]`);
|
|
6
6
|
if (!button || !toast)
|
|
7
7
|
return () => { };
|
|
8
8
|
const show = () => {
|
package/docs/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export interface DocumentationGroup { id: string; label: string }
|
|
|
2
2
|
export interface ExampleCode { language: string; code: string }
|
|
3
3
|
export interface DocumentationExample {
|
|
4
4
|
id: string; name: string; title: string; description: string; markup: string;
|
|
5
|
-
resizable: boolean; frameworks: Record<string, ExampleCode>; behavior?: string; bindings?: string;
|
|
5
|
+
resizable: boolean; stretch?: boolean; frameworks: Record<string, ExampleCode>; behavior?: string; bindings?: string;
|
|
6
6
|
}
|
|
7
7
|
export interface DocumentationComponent {
|
|
8
8
|
id: string; package: string; tag: string; title: string; description: string; group: string;
|
package/docs/local-server.mjs
CHANGED
|
@@ -14,7 +14,7 @@ async function body(request) {
|
|
|
14
14
|
catch { throw rejected('Expected a JSON theme recipe and revision.', 400); }
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
/**
|
|
17
|
+
/** Serve trusted project documentation with a constrained, same-origin theme writer. */
|
|
18
18
|
export async function serveLocalDocumentation({ upstream, store, base = '/', port = 0, onSaved = async () => {} }) {
|
|
19
19
|
const target = new URL(upstream);
|
|
20
20
|
if (target.protocol !== 'http:' || target.hostname !== '127.0.0.1') throw new Error('The documentation upstream must be a loopback MarkupKit server.');
|
|
@@ -52,10 +52,7 @@ export async function serveLocalDocumentation({ upstream, store, base = '/', por
|
|
|
52
52
|
delete headers['x-looma-capability'];
|
|
53
53
|
const proxy = proxyRequest(target.origin + request.url, { method: request.method, headers }, remote => {
|
|
54
54
|
const responseHeaders = { ...remote.headers };
|
|
55
|
-
|
|
56
|
-
const existing = responseHeaders['content-security-policy'];
|
|
57
|
-
responseHeaders['content-security-policy'] = [...(existing ? [existing].flat() : []), 'sandbox allow-scripts'];
|
|
58
|
-
}
|
|
55
|
+
|
|
59
56
|
response.writeHead(remote.statusCode, responseHeaders); remote.pipe(response);
|
|
60
57
|
});
|
|
61
58
|
proxy.on('error', () => { if (!response.headersSent) json(response, 502, { error: 'The documentation renderer is unavailable.' }); else response.destroy(); });
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 400" role="img" aria-labelledby="title description">
|
|
2
|
+
<title id="title">A quiet afternoon in the countryside</title>
|
|
3
|
+
<desc id="description">Soft green hills surround a red-roofed farmhouse, a winding stream, and sheep grazing beneath a broad oak tree.</desc>
|
|
4
|
+
<rect width="640" height="400" fill="#e9efdf"/>
|
|
5
|
+
<circle cx="486" cy="85" r="36" fill="#edcd79"/>
|
|
6
|
+
<g fill="#faf8ed">
|
|
7
|
+
<path d="M65 89c0-12 10-21 22-20 4-20 35-24 46-6 16-4 30 8 29 23 14-2 25 7 25 18H65Z"/>
|
|
8
|
+
<path d="M300 58c2-11 17-16 26-9 10-15 33-10 36 7 13-3 25 6 25 17h-87Z"/>
|
|
9
|
+
</g>
|
|
10
|
+
<path d="M0 183c76-55 128-46 196-8 67 37 112-68 199-45 85 22 134 67 245 22v248H0Z" fill="#a9c2ad"/>
|
|
11
|
+
<path d="M0 227c108-62 189-36 285-8 111 33 182-60 355-18v199H0Z" fill="#89aa79"/>
|
|
12
|
+
<path d="M0 287c89-20 165-64 267-45 110 21 219 79 373 18v140H0Z" fill="#6b925e"/>
|
|
13
|
+
<path d="M0 349c128-72 240-22 363-4 116 17 190-36 277-31v86H0Z" fill="#52784f"/>
|
|
14
|
+
<path d="M362 211c-43 31 63 45 28 72-35 26-113 35-99 64 9 20 54 32 84 53h92c-40-44-127-52-124-72 3-19 79-31 84-57 6-30-94-38-55-60Z" fill="#c7deda"/>
|
|
15
|
+
<path d="M368 213c-28 26 57 44 31 65" fill="none" stroke="#e5eee0" stroke-width="4" stroke-linecap="round"/>
|
|
16
|
+
<path d="M168 214c-21 37-74 45-90 75-17 33 26 56 21 111h40c-1-57-48-77-38-105 10-27 72-45 80-81Z" fill="#d9c38b"/>
|
|
17
|
+
<g>
|
|
18
|
+
<rect x="121" y="173" width="88" height="53" fill="#f6ead0"/>
|
|
19
|
+
<path d="m109 177 56-39 56 39Z" fill="#a55d48"/>
|
|
20
|
+
<path d="m118 177 47-32 47 32Z" fill="#bd7458"/>
|
|
21
|
+
<rect x="181" y="191" width="15" height="35" rx="1" fill="#637961"/>
|
|
22
|
+
<rect x="135" y="189" width="20" height="19" rx="1" fill="#75999a"/>
|
|
23
|
+
<path d="M145 189v19m-10-9h20" stroke="#f6ead0" stroke-width="3"/>
|
|
24
|
+
<path d="M194 155v-17h9v23" fill="#a55d48"/>
|
|
25
|
+
<rect x="238" y="192" width="47" height="35" fill="#b67456"/>
|
|
26
|
+
<path d="m231 194 30-26 31 26Z" fill="#805947"/>
|
|
27
|
+
<rect x="253" y="207" width="16" height="20" fill="#765940"/>
|
|
28
|
+
</g>
|
|
29
|
+
<g fill="none" stroke="#f0dfb7" stroke-width="4" stroke-linecap="round">
|
|
30
|
+
<path d="m27 253 76-18m-65 3v27m25-34v27m25-34v27"/>
|
|
31
|
+
<path d="m222 248 74 11m-63-24v27m26-22v27m26-23v27"/>
|
|
32
|
+
</g>
|
|
33
|
+
<g>
|
|
34
|
+
<path d="m535 220-8 112h24l-6-112Z" fill="#6d6246"/>
|
|
35
|
+
<path d="m539 263-23-28m24 14 23-24" fill="none" stroke="#6d6246" stroke-width="8" stroke-linecap="round"/>
|
|
36
|
+
<path d="M482 232c-26-5-33-36-14-54-10-23 9-45 33-42 9-28 48-31 64-8 26-13 55 6 52 32 28 10 29 45 6 59 0 23-35 34-51 19-24 21-63 16-67-5Z" fill="#3c684d"/>
|
|
37
|
+
<path d="M484 174c4-21 29-30 44-18 9-24 45-22 53 3 22-5 38 13 34 31-43-17-86 6-131-16Z" fill="#527d55"/>
|
|
38
|
+
</g>
|
|
39
|
+
<g stroke="#465b48" stroke-width="3" stroke-linecap="round">
|
|
40
|
+
<path d="M385 323v9m17-10v9m47 13v8m16-10v9"/>
|
|
41
|
+
</g>
|
|
42
|
+
<g fill="#f4edda">
|
|
43
|
+
<ellipse cx="392" cy="317" rx="16" ry="10"/>
|
|
44
|
+
<ellipse cx="455" cy="338" rx="14" ry="9"/>
|
|
45
|
+
</g>
|
|
46
|
+
<g fill="#465b48">
|
|
47
|
+
<ellipse cx="406" cy="318" rx="5" ry="7"/>
|
|
48
|
+
<ellipse cx="468" cy="338" rx="4" ry="6"/>
|
|
49
|
+
</g>
|
|
50
|
+
<g fill="#e4ca80">
|
|
51
|
+
<circle cx="41" cy="370" r="3"/><circle cx="56" cy="351" r="3"/><circle cx="186" cy="346" r="3"/>
|
|
52
|
+
<circle cx="202" cy="364" r="3"/><circle cx="569" cy="363" r="3"/><circle cx="590" cy="346" r="3"/>
|
|
53
|
+
</g>
|
|
54
|
+
</svg>
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" role="img" aria-labelledby="title description">
|
|
2
|
+
<title id="title">Illustrated portrait of Maya Chen</title>
|
|
3
|
+
<desc id="description">A warm, abstract profile portrait on a violet background.</desc>
|
|
4
|
+
<defs>
|
|
5
|
+
<linearGradient id="background" x1="0" y1="0" x2="1" y2="1">
|
|
6
|
+
<stop offset="0" stop-color="#8078ed"/>
|
|
7
|
+
<stop offset="1" stop-color="#40389e"/>
|
|
8
|
+
</linearGradient>
|
|
9
|
+
</defs>
|
|
10
|
+
<rect width="96" height="96" rx="24" fill="url(#background)"/>
|
|
11
|
+
<circle cx="48" cy="38" r="18" fill="#f5c9a7"/>
|
|
12
|
+
<path d="M29 38c0-17 10-25 21-25 13 0 22 10 21 26-5-8-13-13-24-13-7 0-13 4-18 12Z" fill="#292238"/>
|
|
13
|
+
<path d="M18 96c2-23 13-35 30-35s28 12 30 35H18Z" fill="#f6f3ff"/>
|
|
14
|
+
<path d="M39 43c3 3 15 3 18 0" fill="none" stroke="#a45b50" stroke-width="2" stroke-linecap="round"/>
|
|
15
|
+
</svg>
|
package/docs/render.mjs
CHANGED
|
@@ -3,13 +3,43 @@ import { escapeHtml as escape } from './catalog.mjs';
|
|
|
3
3
|
import { createLoomaMarkdownIt } from '@threadlabs/looma/markdown/markdown-it';
|
|
4
4
|
|
|
5
5
|
const descriptions = createLoomaMarkdownIt().set({ html: false });
|
|
6
|
+
export const cardDescription = description => (descriptions.parseInline(description ?? '', {})[0]?.children ?? []).map(token => token.content).join('').split(/(?<=[.!?])\s/)[0];
|
|
6
7
|
|
|
7
8
|
const literal = value => escape(value).replaceAll('{', '\\{');
|
|
8
9
|
const code = value => `<code>${literal(value ?? '—')}</code>`;
|
|
9
10
|
const table = (head, rows) => `<table><thead><tr>${head.map(h => `<th>${literal(h)}</th>`).join('')}</tr></thead><tbody>${rows.map(row => `<tr>${row.map(value => `<td>${value}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
|
|
10
11
|
export const exampleKey = id => createHash('sha256').update(id).digest('hex').slice(0, 20);
|
|
11
12
|
export const componentPath = component => `/${component.group === 'editor' ? 'editor' : 'components'}/${component.navigationParent ?? component.tag}/` + (component.navigationParent ? `#${component.tag}-api` : '');
|
|
12
|
-
export const
|
|
13
|
+
export const previewTag = example => `looma-preview-${exampleKey(example.id)}`;
|
|
14
|
+
export const previewMarkup = (example, namespace, base = '/', layout = false) => `<div slot="preview"><div data-preview="${escape(example.id)}"${layout || example.stretch ? ' data-preview-layout' : ''}>${scopedExampleMarkup(example, base, namespace)}</div></div>`;
|
|
15
|
+
export function exampleResources(examples, catalog) {
|
|
16
|
+
const resources = new Map([...catalog.resources ?? [], ...catalog.components].map(resource => [resource.tag, resource.resource]));
|
|
17
|
+
const tags = [...new Set(examples.flatMap(example => [...example.markup.matchAll(/<([a-z][\w]*-[\w-]+)\b/g)].map(match => match[1])))];
|
|
18
|
+
return tags.filter(tag => resources.has(tag)).map(tag => `<link rel="component" href="${escape(resources.get(tag))}">`).join('\n');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Keep authored ID relationships local when several examples share one document. */
|
|
22
|
+
export function scopedExampleMarkup(example, base = '/', namespace) {
|
|
23
|
+
const ids = new Set([...example.markup.matchAll(/\sid=["']([^"']+)["']/g)].map(match => match[1]));
|
|
24
|
+
const destinations = [...new Set([...example.markup.matchAll(/\bhref=["']#([^"']+)["']/g)].map(match => match[1]))].filter(id => !ids.has(id));
|
|
25
|
+
const markup = example.markup.replaceAll('src="/_looma/', `src="${base}_looma/`) + destinations.map(id => `<span id="${escape(id)}" hidden></span>`).join('');
|
|
26
|
+
return markup.replace(/<([a-z][\w:-]*)\b((?:[^>"']|"[^"]*"|'[^']*')*)>/gi, (tag, name, attributes) => {
|
|
27
|
+
if (name === 'img') attributes = attributes.replace(/\ssrc="([^"]*\/_looma\/[^"]*)"/, (_, url) => ` from:src="${escape(JSON.stringify(url))}"`);
|
|
28
|
+
const scoped = attributes.replace(/\s(id|for|commandfor|popovertarget|aria-labelledby|aria-describedby|aria-controls|aria-owns|aria-activedescendant|list|form|headers|href|name)\s*=\s*(["'])(.*?)\2/gi, (attribute, key, quote, value) => {
|
|
29
|
+
if (key === 'name' && !['ui-radio', 'ui-radio-group'].includes(name) && !(name === 'input' && /\btype=["']radio["']/.test(attributes))) return attribute;
|
|
30
|
+
if (!value || key === 'href' && !value.startsWith('#')) return attribute;
|
|
31
|
+
if (namespace) {
|
|
32
|
+
const scopedValue = (key === 'href' ? '#' : '') + value.replace(/^#/, '').split(/\s+/).map(id => `${namespace}-${id}`).join(' ');
|
|
33
|
+
return `${key === 'id' && !/\bdata-example-id=/.test(attributes) ? ` data-example-id="${escape(value)}"` : ''} ${key}="${escape(scopedValue)}"`;
|
|
34
|
+
}
|
|
35
|
+
const values = value.replace(/^#/, '').split(/\s+/);
|
|
36
|
+
const binding = values.map(id => `concat($namespace, '-', ${JSON.stringify(id)})`).join(', " ", ');
|
|
37
|
+
const source = key === 'href' ? `concat('#', ${binding})` : values.length > 1 ? `concat(${binding})` : `concat($namespace, '-', ${JSON.stringify(value)})`;
|
|
38
|
+
return `${key === 'id' && !/\bdata-example-id=/.test(attributes) ? ` data-example-id="${escape(value)}"` : ''} from:${key}="${escape(source)}"`;
|
|
39
|
+
});
|
|
40
|
+
return `<${name}${scoped}>`;
|
|
41
|
+
});
|
|
42
|
+
}
|
|
13
43
|
|
|
14
44
|
export function apiBody(api, prefix = '') {
|
|
15
45
|
const attributes = api.attributes ?? [];
|
|
@@ -71,7 +101,7 @@ export function exampleCodes(example, component, components) {
|
|
|
71
101
|
|
|
72
102
|
/** The same card invocation is embedded in reference pages and rendered by the customizer. */
|
|
73
103
|
export function cardMarkup(example, base = '/', component = {}, { reference = false, code: exampleCode = '' } = {}) {
|
|
74
|
-
return `<looma-example-card identity="${escape(example.id)}"${reference ? ' reference' : ''} title="${escape(component.title ?? example.title)}" description="${escape(reference ? example.description : component.description ?? example.description)}" example-title="${escape(example.title)}" category="${escape(component.group ?? 'forms')}" tag="${escape(component.tag ?? '')}" package-name="${escape(component.package ?? '')}" native-root="${escape(component.root ? `<${component.root}>` : '')}" href="${component.tag ? base + componentPath(component).slice(1) : ''}"
|
|
104
|
+
return `<looma-example-card identity="${escape(example.id)}"${reference ? ' reference' : ''} title="${escape(component.title ?? example.title)}" description="${escape(reference ? example.description : cardDescription(component.description ?? example.description))}" example-title="${escape(example.title)}" category="${escape(component.group ?? 'forms')}" tag="${escape(component.tag ?? '')}" package-name="${escape(component.package ?? '')}" native-root="${escape(component.root ? `<${component.root}>` : '')}" href="${component.tag ? base + componentPath(component).slice(1) : ''}"${example.resizable ? ' resizable' : ''}>${previewMarkup(example, `${reference ? 'reference' : 'catalog'}-${exampleKey(example.id)}`, base, component.group === 'layout')}${reference ? `<div slot="heading" class="looma-example-heading"><h3 id="example-${exampleKey(example.id)}">${escape(example.title)}</h3><p>${escape(example.description)}</p></div>` : ''}${exampleCode}</looma-example-card>`;
|
|
75
105
|
}
|
|
76
106
|
|
|
77
107
|
export function referencePage(component, catalog, cardResource, base) {
|
|
@@ -89,5 +119,5 @@ export function referencePage(component, catalog, cardResource, base) {
|
|
|
89
119
|
return `<ui-tabs slot="code" label="Example syntax" group="syntax" style="--ui-tabs-panel-padding: 0px">${tabs}</ui-tabs>`;
|
|
90
120
|
};
|
|
91
121
|
const body = `<div class="looma-reference-examples"><ui-stack gap="xl">${examples.map(example => `<ui-card as="section" variant="subtle" padding="lg">${cardMarkup(example, base, catalog.components.find(c => c.examples.some(e => e.id === example.id)) ?? component, { reference: true, code: codes(example) })}</ui-card>`).join('')}</ui-stack></div>`;
|
|
92
|
-
return `---\ntitle: ${JSON.stringify(component.title)}\ndescription: ${JSON.stringify(component.description || `${component.title} component reference.`)}\nid: ${JSON.stringify(component.id)}\n---\n\n# ${escape(component.title)}\n\n<div class="component-description"><p>${descriptions.renderInline(component.description).replaceAll('{', '\\{').replaceAll('\n', ' ')}</p></div>\n\n<link rel="component" href="${cardResource}">\n<link rel="component" href="${cardResource.replace(/card\.html$/, 'reference.html')}">\n<link rel="component" href="@threadlabs/looma/components/ui-card/ui-card.html">\n<link rel="component" href="@threadlabs/looma/components/ui-tabs/ui-tabs.html">\n<link rel="component" href="@threadlabs/looma/components/ui-disclosure/ui-disclosure.html">\n<link rel="component" href="@threadlabs/looma/components/ui-stack/ui-stack.html">\n\n<looma-reference>\n\n<div class="looma-reference-tabs"><ui-tabs label="Component reference" style="--ui-tabs-panel-padding: 0px; --ui-tabs-tab-min-block-size: var(--ui-control-size-lg)"><section aria-label="Examples">${body}</section><section aria-label="API"><h2 id="api">API</h2>\n${apiBody(component)}\n${parts.map(part => `<h2 id="${part.tag}-api">${literal(part.title)} API</h2><p>${literal(part.description)}</p>${apiBody(part, part.tag + '-')}`).join('\n')}</section></ui-tabs></div>\n\n</looma-reference>\n`;
|
|
122
|
+
return `---\ntitle: ${JSON.stringify(component.title)}\ndescription: ${JSON.stringify(component.description || `${component.title} component reference.`)}\nid: ${JSON.stringify(component.id)}\n---\n\n# ${escape(component.title)}\n\n<div class="component-description"><p>${descriptions.renderInline(component.description).replaceAll('{', '\\{').replaceAll('\n', ' ')}</p></div>\n\n<link rel="component" href="${cardResource}">\n${exampleResources(examples, catalog)}\n<link rel="component" href="${cardResource.replace(/card\.html$/, 'reference.html')}">\n<link rel="component" href="@threadlabs/looma/components/ui-card/ui-card.html">\n<link rel="component" href="@threadlabs/looma/components/ui-tabs/ui-tabs.html">\n<link rel="component" href="@threadlabs/looma/components/ui-disclosure/ui-disclosure.html">\n<link rel="component" href="@threadlabs/looma/components/ui-stack/ui-stack.html">\n\n<looma-reference>\n\n<div class="looma-reference-tabs"><ui-tabs label="Component reference" style="--ui-tabs-panel-padding: 0px; --ui-tabs-tab-min-block-size: var(--ui-control-size-lg)"><section aria-label="Examples">${body}</section><section aria-label="API"><h2 id="api">API</h2>\n${apiBody(component)}\n${parts.map(part => `<h2 id="${part.tag}-api">${literal(part.title)} API</h2><p>${literal(part.description)}</p>${apiBody(part, part.tag + '-')}`).join('\n')}</section></ui-tabs></div>\n\n</looma-reference>\n`;
|
|
93
123
|
}
|
package/docs/site.mjs
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { cp, mkdir, readFile, readdir, realpath, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import {
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
6
|
import { discoverComponents, escapeHtml, mergeCatalogs, readCatalog, readJson } from './catalog.mjs';
|
|
7
|
-
import { cardMarkup, componentPath, exampleKey,
|
|
7
|
+
import { cardMarkup, componentPath, exampleKey, previewTag, scopedExampleMarkup, exampleResources, referencePage } from './render.mjs';
|
|
8
8
|
import { defaultRecipe, themeCSS } from './theme.mjs';
|
|
9
9
|
import { customizerResource } from './customizer-render.mjs';
|
|
10
10
|
import { catalogResource } from './catalog-view.mjs';
|
|
11
11
|
import { cacheDirectory, rejectSymlink, withBuildLock } from './workspace.mjs';
|
|
12
|
+
import { googleFontURL } from './fonts.mjs';
|
|
12
13
|
|
|
13
14
|
const own = name => fileURLToPath(new URL(name, import.meta.url));
|
|
14
15
|
/** Resolve import-only optional tooling peers in the consumer's ESM package scope. */
|
|
@@ -84,7 +85,6 @@ export async function prepareDocumentation({ root, config = {}, catalog }) {
|
|
|
84
85
|
await cp(own('card.js'), path.join(generated, 'card.js'));
|
|
85
86
|
await writeFile(path.join(generated, 'catalog-view.html'), catalogResource(combined.groups));
|
|
86
87
|
await cp(own('catalog-view.js'), path.join(generated, 'catalog-view.js'));
|
|
87
|
-
await cp(own('preview.js'), path.join(generated, 'preview.js'));
|
|
88
88
|
for (const file of ['reference.html', 'reference.js']) await cp(own(file), path.join(generated, file));
|
|
89
89
|
for (const file of ['customizer.js', 'theme.mjs', 'theme-session.mjs', 'value-editors.mjs', 'palette.mjs', 'fonts.mjs']) await cp(own(file), path.join(generated, file));
|
|
90
90
|
const write = async (file, source) => { await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, source); };
|
|
@@ -106,16 +106,10 @@ export async function prepareDocumentation({ root, config = {}, catalog }) {
|
|
|
106
106
|
const file = path.join(previews, key + '.html');
|
|
107
107
|
const tags = [...new Set([...example.markup.matchAll(/<([a-z][\w]*-[\w-]+)\b/g)].map(match => match[1]))];
|
|
108
108
|
const links = tags.filter(tag => resourceByTag.has(tag)).map(tag => `<link rel="component" href="${escapeHtml(resourceByTag.get(tag).resource)}">`).join('\n');
|
|
109
|
-
// Navigation specimens name destinations supplied by their host application. Give those
|
|
110
|
-
// fragments local stand-ins inside the isolated stage; keep real documentation links checked.
|
|
111
|
-
const declaredIds = new Set([...example.markup.matchAll(/\sid=["']([^"']+)["']/g)].map(match => match[1]));
|
|
112
|
-
const destinations = [...new Set([...example.markup.matchAll(/\bhref=["']#([^"']+)["']/g)].map(match => match[1]))].filter(id => !declaredIds.has(id));
|
|
113
|
-
const anchors = destinations.map(id => `<span id="${escapeHtml(id)}" hidden></span>`).join('');
|
|
114
109
|
const setup = path.join(previews, key + '.js');
|
|
115
|
-
|
|
116
|
-
await write(
|
|
117
|
-
|
|
118
|
-
examples.push({ ...example, file, component: component.id, path: base + previewPath(example).slice(1) });
|
|
110
|
+
if (example.behavior) await write(setup, `import setupExample from ${JSON.stringify(example.behavior)};\nexport function connect(host) { return setupExample(host.element); }\n`);
|
|
111
|
+
await write(file, `${links}\n<template component="${previewTag(example)}"${example.behavior ? ` module="./${key}.js"` : ''}><defs><prop name="namespace" type="string" default="${key}">A unique namespace for this example's IDs and control relationships.</prop></defs><div><div data-preview="${escapeHtml(example.id)}"${component.group === 'layout' ? ' data-preview-layout' : ''}>${scopedExampleMarkup(example, base)}</div></div></template>\n`);
|
|
112
|
+
examples.push({ ...example, file, component: component.id, path: base + componentPath(component).slice(1) });
|
|
119
113
|
}
|
|
120
114
|
}
|
|
121
115
|
const gallery = combined.groups.map(group => {
|
|
@@ -123,7 +117,7 @@ export async function prepareDocumentation({ root, config = {}, catalog }) {
|
|
|
123
117
|
// A standalone opening tag makes this a Markdown HTML block, keeping native card wrappers inside Grid.
|
|
124
118
|
return components.length ? `<section data-catalog-group="${escapeHtml(group.id)}">\n\n## ${escapeHtml(group.label)}\n\n<ui-grid columns="3" min="sm">\n${components.map(component => `<div data-category="${escapeHtml(component.group)}" data-catalog-search="${escapeHtml(`${component.tag} ${component.title} ${component.description}`)}">${cardMarkup(component.examples[0], base, component)}</div>`).join('\n')}\n</ui-grid>\n\n</section>` : '';
|
|
125
119
|
}).join('\n\n');
|
|
126
|
-
await write(path.join(content, 'components/index.md'), `---\ntitle: Components\n---\n\n# Components\n\nExplore the live examples that also power your theme customizer.\n\n<link rel="component" href="${relativeHref(path.join(content, 'components/index.md'), card)}">\n<link rel="component" href="@threadlabs/looma/components/ui-grid/ui-grid.html">\n<link rel="component" href="${relativeHref(path.join(content, 'components/index.md'), path.join(generated, 'catalog-view.html'))}">\n\n<looma-catalog>\n\n${gallery}\n\n</looma-catalog>\n`);
|
|
120
|
+
await write(path.join(content, 'components/index.md'), `---\ntitle: Components\n---\n\n# Components\n\nExplore the live examples that also power your theme customizer.\n\n<link rel="component" href="${relativeHref(path.join(content, 'components/index.md'), card)}">\n${exampleResources(combined.components.filter(component => !component.navigationParent).map(component => component.examples[0]), combined)}\n<link rel="component" href="@threadlabs/looma/components/ui-grid/ui-grid.html">\n<link rel="component" href="${relativeHref(path.join(content, 'components/index.md'), path.join(generated, 'catalog-view.html'))}">\n\n<looma-catalog>\n\n${gallery}\n\n</looma-catalog>\n`);
|
|
127
121
|
await write(path.join(content, 'index.md'), `---\ntitle: ${JSON.stringify(config.title ?? 'Your design system')}\n---\n\n# ${config.title ?? 'Your design system'}\n\nWeave your design system from Looma and your own HTML Next components.\n\n[Explore components](/components/) · [Customize your theme](/customize/)\n`);
|
|
128
122
|
if (combined.components.some(component => component.group === 'editor')) await write(path.join(content, 'editor.md'), `---\ntitle: Editor\nsidebar: false\n---\n\n# Editor\n\nWriting tools and editor components, separate from the general component reference.\n\n${combined.components.filter(component => component.group === 'editor' && !component.navigationParent).map(component => `- [${component.title}](${componentPath(component)})`).join('\n')}\n`);
|
|
129
123
|
await write(path.join(content, 'design-system.md'), await readFile(own('README.md'), 'utf8'));
|
|
@@ -141,6 +135,9 @@ export async function prepareDocumentation({ root, config = {}, catalog }) {
|
|
|
141
135
|
await mkdir(path.dirname(target), { recursive: true }); await cp(source, target);
|
|
142
136
|
}
|
|
143
137
|
}
|
|
138
|
+
await write(path.join(generated, 'example-behaviors.js'), examples.filter(example => example.behavior).map((example, index) => `import setup${index} from ${JSON.stringify(example.behavior)};`).join('\n') + `\nexport const exampleBehaviors = {${examples.filter(example => example.behavior).map((example, index) => `${JSON.stringify(example.id)}: setup${index}`).join(',')}};\n`);
|
|
139
|
+
const choice = exampleResources(examples, combined) + `\n<template component="looma-preview-choice"><defs><prop name="identity" type="string" default="">The authored example to render.</prop><prop name="namespace" type="string" default="selected">Unique ID namespace within this page.</prop></defs><div>${examples.map(example => `<div $if="${escapeHtml(`$identity = ${JSON.stringify(example.id)}`)}" data-preview="${escapeHtml(example.id)}"${example.stretch || combined.components.find(component => component.id === example.component)?.group === 'layout' ? ' data-preview-layout' : ''}>${scopedExampleMarkup(example, base)}</div>`).join('')}</div></template>`;
|
|
140
|
+
await write(path.join(generated, 'preview-choice.html'), choice);
|
|
144
141
|
const customizer = path.join(generated, 'customizer.html');
|
|
145
142
|
await write(customizer, customizerResource({ catalog: combined, config, base }, config.recipe));
|
|
146
143
|
const customizerPage = path.join(content, 'customize.md');
|
|
@@ -169,9 +166,8 @@ async function themeBootstrap(site) {
|
|
|
169
166
|
export function documentationPlugin(site) {
|
|
170
167
|
return {
|
|
171
168
|
name: 'looma-design-system',
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
config: () => ({ pages: [{ dir: path.relative(site.root, site.previews), prefix: '/_looma/preview/', layout: false }], css: [own('documentation.css')] }),
|
|
169
|
+
generate: async () => ({ '/_looma/pastoral.svg': await readFile(own('pastoral.svg'), 'utf8'), '/_looma/portrait.svg': await readFile(own('portrait.svg'), 'utf8'), '/_looma/theme-system.css': await readFile(fileURLToPath(import.meta.resolve('@threadlabs/looma/theme-system.css')), 'utf8') }),
|
|
170
|
+
config: () => ({ css: [own('documentation.css')] }),
|
|
175
171
|
};
|
|
176
172
|
}
|
|
177
173
|
|
|
@@ -180,15 +176,21 @@ export async function documentationOptions(site) {
|
|
|
180
176
|
const styles = ['tokens.css', 'theme-light.css', 'theme-dark.css', 'theme-system.css'].map(file => fileURLToPath(import.meta.resolve(`@threadlabs/looma/${file}`)));
|
|
181
177
|
const options = siteOptions({ root: site.root, contentDir: path.relative(site.root, site.content), title: site.config.title ?? 'Your design system', headerNotice: 'Custom theme', base: site.base, outDir: site.config.outDir ?? 'site', ...(site.config.origin ? { origin: site.config.origin } : {}), ...(site.config.logo ? { logo: site.config.logo } : {}), ...(site.config.nav ? { nav: site.config.nav } : {}) }, { plugins: [documentationPlugin(site)], css: styles, redirects: site.redirects });
|
|
182
178
|
const savedTheme = path.join(site.generated, 'saved-theme.css');
|
|
183
|
-
|
|
179
|
+
const recipe = site.config.recipe ?? defaultRecipe();
|
|
180
|
+
const overrides = await Promise.all((site.config.overrides ?? []).map(file => readFile(path.resolve(site.root, file), 'utf8')));
|
|
181
|
+
const localFonts = new Set(overrides.flatMap(css => [...css.matchAll(/@font-face\s*\{[^}]*font-family:\s*['"]([^'"]+)['"]/g)].map(match => match[1])));
|
|
182
|
+
const remoteFonts = Object.fromEntries(Object.entries(recipe.fonts ?? {}).filter(([, family]) => !localFonts.has(family)));
|
|
183
|
+
const imported = googleFontURL(recipe.fonts), remaining = googleFontURL(remoteFonts);
|
|
184
|
+
// A supplied face already serves the same family; avoid another render-blocking stylesheet.
|
|
185
|
+
const savedCSS = (site.config.themeCSSContents ?? themeCSS(recipe)).replace(`@import url("${imported}");`, remaining ? `@import url("${remaining}");` : '');
|
|
186
|
+
await writeFile(savedTheme, savedCSS);
|
|
184
187
|
const themeStyles = [savedTheme, ...await portableThemeStyles(site)];
|
|
185
188
|
return { ...options, plugins: [...options.plugins, { name: 'looma-saved-theme', config: () => ({ css: themeStyles }) },
|
|
186
189
|
// Markupress supplies its head script in its own config hook; compose after it.
|
|
187
190
|
{ name: 'looma-browser-theme', config: async current => ({ headScript: [current.headScript, await themeBootstrap(site)].filter(Boolean).join('\n;\n') }) }] };
|
|
188
191
|
}
|
|
189
192
|
|
|
190
|
-
/**
|
|
191
|
-
* Bundle those font files into theme CSS for both the local server and static output. */
|
|
193
|
+
/** Bundle project theme styles once, shared by the page and every inline example. */
|
|
192
194
|
async function portableThemeStyles(site) {
|
|
193
195
|
const overrides = site.config.overrides ?? [];
|
|
194
196
|
if (!overrides.length) return [];
|
|
@@ -197,7 +199,6 @@ async function portableThemeStyles(site) {
|
|
|
197
199
|
await writeFile(entry, overrides.map(file => `@import ${JSON.stringify(path.resolve(site.root, file))};`).join('\n'));
|
|
198
200
|
const bundled = await build({ root: site.root, base: './', configFile: false, logLevel: 'silent',
|
|
199
201
|
build: { write: false, minify: false, cssMinify: false,
|
|
200
|
-
assetsInlineLimit: file => /\.(woff2?|ttf|otf)$/i.test(file),
|
|
201
202
|
rollupOptions: { input: entry, output: { assetFileNames: 'theme-assets/[name]-[hash][extname]' } } } });
|
|
202
203
|
const styles = [];
|
|
203
204
|
for (const output of (Array.isArray(bundled) ? bundled[0] : bundled).output) {
|
|
@@ -210,7 +211,7 @@ async function portableThemeStyles(site) {
|
|
|
210
211
|
return styles;
|
|
211
212
|
}
|
|
212
213
|
|
|
213
|
-
/** Build
|
|
214
|
+
/** Build references and examples together through MarkupKit. */
|
|
214
215
|
export async function buildDocumentation({ root = process.cwd(), config = {}, catalog } = {}) {
|
|
215
216
|
return withBuildLock(root, async () => {
|
|
216
217
|
const site = await prepareDocumentation({ root, config, catalog });
|
|
@@ -219,36 +220,3 @@ export async function buildDocumentation({ root = process.cwd(), config = {}, ca
|
|
|
219
220
|
return { ...built, site };
|
|
220
221
|
});
|
|
221
222
|
}
|
|
222
|
-
|
|
223
|
-
async function isolatePreviewScripts(site, { outDir }) {
|
|
224
|
-
const { build } = await tool('vite', site.root);
|
|
225
|
-
// Preview entries and outputs are independent. Keep compiler memory bounded
|
|
226
|
-
// and retain the build lock until every in-flight bundle has settled.
|
|
227
|
-
const remaining = [...site.examples];
|
|
228
|
-
const results = await Promise.allSettled(Array.from({ length: Math.min(2, remaining.length) }, async () => {
|
|
229
|
-
try {
|
|
230
|
-
for (let example; (example = remaining.pop());) {
|
|
231
|
-
const htmlFile = path.join(outDir, '_looma/preview', exampleKey(example.id), 'index.html');
|
|
232
|
-
let html = await readFile(htmlFile, 'utf8');
|
|
233
|
-
const scripts = [...html.matchAll(/<script\b[^>]*type="module"[^>]*src="([^"]+)"[^>]*><\/script>/g)];
|
|
234
|
-
if (!scripts.length) throw new Error(`No browser module found for isolated preview ${example.id}.`);
|
|
235
|
-
for (const [tag, url] of scripts) {
|
|
236
|
-
const input = path.join(outDir, url.slice(site.base.length));
|
|
237
|
-
const bundle = await build({ configFile: false, logLevel: 'silent', build: { write: false, minify: true, lib: { entry: input, name: 'LoomaPreview', formats: ['iife'] }, rollupOptions: { output: { codeSplitting: false } } } });
|
|
238
|
-
const code = (Array.isArray(bundle) ? bundle[0] : bundle).output.find(output => output.type === 'chunk').code;
|
|
239
|
-
// A sandbox has an opaque origin: Safari cannot authorize this runtime via 'self'.
|
|
240
|
-
// Hash the exact inline bytes and run after the preview DOM, preserving isolation.
|
|
241
|
-
const script = code.replace(/<\/script/gi, '<\\/script');
|
|
242
|
-
const hash = createHash('sha256').update(script).digest('base64');
|
|
243
|
-
if (!/<meta\b[^>]*http-equiv="Content-Security-Policy"[^>]*content="[^"]*\bscript-src\b/.test(html)) throw new Error(`Missing script policy for isolated preview ${example.id}.`);
|
|
244
|
-
html = html.replace(/(<meta\b[^>]*http-equiv="Content-Security-Policy"[^>]*content="[^"]*\bscript-src)\b/, `$1 'sha256-${hash}'`);
|
|
245
|
-
html = html.replace(tag, '').replace('</body>', () => `<script>${script}</script></body>`);
|
|
246
|
-
}
|
|
247
|
-
html = html.replace(/<link\b[^>]*rel="modulepreload"[^>]*>/g, '');
|
|
248
|
-
await writeFile(htmlFile, html);
|
|
249
|
-
}
|
|
250
|
-
} catch (error) { remaining.length = 0; throw error; }
|
|
251
|
-
}));
|
|
252
|
-
const failed = results.find(result => result.status === 'rejected');
|
|
253
|
-
if (failed) throw failed.reason;
|
|
254
|
-
}
|