@threadlabs/looma 0.43.0 → 0.43.2

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.
Files changed (41) hide show
  1. package/components/ui-card/ui-card.html +6 -6
  2. package/components/ui-editor-mention-menu/ui-editor-mention-menu.js +3 -0
  3. package/components/ui-editor-slash-menu/ui-editor-slash-menu.js +4 -0
  4. package/components/ui-editor-table-overlay/ui-editor-table-overlay.html +1 -0
  5. package/components/ui-site-header/ui-site-header.html +1 -1
  6. package/dist/index.js +1 -1
  7. package/docs/README.md +2 -2
  8. package/docs/card.html +2 -6
  9. package/docs/card.js +7 -37
  10. package/docs/catalog.json +217 -13
  11. package/docs/catalog.mjs +1 -1
  12. package/docs/customizer-render.mjs +7 -6
  13. package/docs/customizer.js +2 -7
  14. package/docs/documentation.css +3 -7
  15. package/docs/examples/ui-button/examples/08-loading.behavior.js +1 -1
  16. package/docs/examples/ui-checkbox/examples/02-checked-indeterminate-and-disabled.behavior.js +1 -1
  17. package/docs/examples/ui-editor-mention-menu/examples/00-preview.behavior.js +1 -0
  18. package/docs/examples/ui-editor-slash-menu/examples/00-preview.behavior.js +81 -0
  19. package/docs/examples/ui-editor-table-overlay/examples/00-preview.behavior.js +24 -0
  20. package/docs/examples/ui-search-shell/examples/00-preview.behavior.js +14 -0
  21. package/docs/examples/ui-search-shell/examples/02-label-dismissible-status-and-footer.behavior.js +7 -7
  22. package/docs/examples/ui-toast/examples/01-authored.behavior.js +2 -2
  23. package/docs/index.d.ts +1 -1
  24. package/docs/local-server.mjs +2 -5
  25. package/docs/pastoral.svg +54 -0
  26. package/docs/portrait.svg +15 -0
  27. package/docs/render.mjs +33 -3
  28. package/docs/site.mjs +22 -54
  29. package/package.json +1 -1
  30. package/styles/ui-card.css +6 -6
  31. package/styles/ui-site-header.css +1 -1
  32. package/vanilla/UiEditorTableOverlay.js +50 -36
  33. package/vue/UiCard.vue +6 -6
  34. package/vue/UiEditorTableOverlay.d.ts +11 -1
  35. package/vue/UiEditorTableOverlay.vue +98 -63
  36. package/vue/UiSiteHeader.vue +1 -1
  37. package/vue/chunks/UiCard.js +1 -1
  38. package/vue/chunks/UiEditorTableOverlay.js +41 -13
  39. package/vue/chunks/UiSiteHeader.js +1 -1
  40. package/vue/components.css +55 -54
  41. package/docs/preview.js +0 -22
@@ -1,19 +1,20 @@
1
1
  import { googleFonts, systemFont } from './fonts.mjs';
2
2
  import { escapeHtml as escape } from './catalog.mjs';
3
- import { componentPath, previewPath } from './render.mjs';
3
+ import { componentPath, previewMarkup, exampleKey, exampleResources, cardDescription } from './render.mjs';
4
4
  import { valueEditor } from './value-editors.mjs';
5
5
  import { defaultRecipe, themeFields, startingPoints, startingPointLabels, startingPointFor, deriveTheme, applyRefinement, themeCSS, validateRecipe, themePalettes, materialPresets, refinementState } from './theme.mjs';
6
6
 
7
7
  export function customizerResource(site, input = defaultRecipe()) {
8
8
  const recipe = validateRecipe(input);
9
- const cardFields = ['id', 'title', 'description', 'exampleTitle', 'src', 'resizable', 'category', 'tag', 'nativeRoot', 'href', 'packageName'];
10
- const examples = site.catalog.components.flatMap(component => component.examples.map(example => ({ id: example.id, title: component.title, description: component.description, exampleTitle: example.title, src: site.base + previewPath(example).slice(1), resizable: Boolean(example.resizable), category: component.group, tag: component.tag, packageName: component.package, nativeRoot: component.root ? `<${component.root}>` : '', href: site.base + componentPath(component).slice(1) })));
9
+ const cardFields = ['id', 'title', 'description', 'exampleTitle', 'resizable', 'category', 'tag', 'nativeRoot', 'href', 'packageName'];
10
+ const examples = site.catalog.components.flatMap(component => component.examples.map(example => ({ id: example.id, title: component.title, description: cardDescription(component.description), exampleTitle: example.title, resizable: Boolean(example.resizable), category: component.group, tag: component.tag, packageName: component.package, nativeRoot: component.root ? `<${component.root}>` : '', href: site.base + componentPath(component).slice(1) })));
11
11
  const toCard = example => Object.fromEntries(cardFields.map(key => [key, example[key]]));
12
12
  const initial = ['ui-button', 'ui-input', 'ui-color-picker', 'ui-checkbox', 'ui-card', 'ui-switch', 'ui-text', 'ui-dialog', 'ui-popover'].map(tag => examples.find(example => example.tag === tag && (tag !== 'ui-button' || example.id.endsWith('/02-variant')) && (tag !== 'ui-text' || example.id.endsWith('/02-variants')) && (tag !== 'ui-card' || example.id.endsWith('/04-expressive-surface'))) ?? examples.find(example => example.tag === tag)).filter(Boolean).map(toCard);
13
13
  if (!initial.length && examples.length) initial.push(toCard(examples[0]));
14
+ let specimen = 0;
14
15
  const documentationCard = (tag, suffix, previewOnly = false) => {
15
16
  const example = examples.find(item => item.tag === tag && (!suffix || item.id.endsWith(suffix))) ?? examples.find(item => item.tag === tag);
16
- return example ? `<looma-example-card ${previewOnly ? 'preview-only' : ''} ${cardFields.filter(key => key !== 'id').map(key => `${key.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase())}="${escape(String(example[key]))}"`).join(' ')} identity="${escape(example.id)}" loading="lazy"></looma-example-card>` : '';
17
+ return example ? `<looma-example-card ${previewOnly ? 'preview-only' : ''} ${cardFields.filter(key => key !== 'id').map(key => `${key.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase())}="${escape(String(example[key]))}"`).join(' ')} identity="${escape(example.id)}">${previewMarkup(site.catalog.components.flatMap(component => component.examples).find(item => item.id === example.id), `customizer-${specimen++}-${exampleKey(example.id)}`, site.base, example.category === 'layout')}</looma-example-card>` : '';
17
18
  };
18
19
  const renderField = field => {
19
20
  const value = recipe.values[field.id];
@@ -79,7 +80,7 @@ export function customizerResource(site, input = defaultRecipe()) {
79
80
  const paletteView = refinement('palette', `<ui-cluster>${renderPreset('palette', 'refinement')}<ui-button data-action="restore-palette">Reset palette</ui-button></ui-cluster><div class="refinement-layout"><div class="palette-preview"><ui-stack>${paletteDetails}</ui-stack></div><ui-stack><ui-text variant="heading" as="h3">Base colors</ui-text><ui-text variant="caption">Primary is the main voice. Add supporting accents where they help; status colors keep their own meanings.</ui-text>${fieldsFor(['action','canvas','surface','text'])}<ui-disclosure summary="Supporting accents"><ui-stack>${fieldsFor(['secondary-action','tertiary-action'])}</ui-stack></ui-disclosure><ui-disclosure summary="Neutrals & shared borders" data-advanced="neutrals"><ui-stack>${fieldsFor(['neutral-source','neutral-strength','neutral-border-contrast'])}<ui-text variant="caption">Neutral solid and outline buttons and form fields use this same border. Raising the minimum changes the whole family.</ui-text></ui-stack></ui-disclosure><ui-disclosure summary="Status colors" data-advanced="status"><ui-stack>${statusControls}${fieldsFor(['status-chroma'])}<ui-text variant="caption">Keep semantic hues, harmonize them with your brand, or use an accent family. Looma derives readable fills and text; labels and icons keep states identifiable when colors are shared. Supporting accents follow primary until enabled.</ui-text></ui-stack></ui-disclosure><ui-disclosure summary="Accent assignments" data-advanced="assignments"><ui-stack>${fieldsFor(['selection-accent','focus-accent','link-accent'])}</ui-stack></ui-disclosure><ui-disclosure summary="Adjust color character"><ui-stack>${fieldsFor(['warmth','color-intensity'])}</ui-stack></ui-disclosure><ui-disclosure summary="Color relationships">${paletteRelationships}</ui-disclosure></ui-stack></div>`);
80
81
  const options = site.catalog.groups.map(group => `<optgroup label="${escape(group.label)}">${examples.filter(example => example.category === group.id).map(example => `<option value="${escape(example.id)}" data-description="${escape(example.category + ' · ' + example.tag)}" data-example="${escape(JSON.stringify(example))}" data-search="${escape(`${example.title} ${example.tag} ${example.description} ${example.exampleTitle}`.toLocaleLowerCase())}">${escape(example.title)} · ${escape(example.exampleTitle)}</option>`).join('')}</optgroup>`).join('');
81
82
  const links = ['ui-action-bar','ui-stack','ui-grid','ui-cluster','ui-form-field','ui-input','ui-select','ui-color-picker','ui-button','ui-disclosure','ui-textarea','ui-number-input','ui-slider','ui-curve-editor','ui-card','ui-text','ui-light-editor','ui-combobox','ui-checkbox','ui-badge','ui-icon','ui-callout','ui-popover','ui-dialog','ui-list','ui-list-item'].map(tag => `<link rel="component" href="@threadlabs/looma/components/${tag}/${tag}.html">`).join('\n');
82
- return `${links}\n<link rel="component" href="./card.html">\n<template component="looma-customizer" module="./customizer.js"><defs>
83
+ return `${links}\n${exampleResources(site.catalog.components.flatMap(component => component.examples), site.catalog)}\n<link rel="component" href="./card.html">\n<link rel="component" href="./preview-choice.html">\n<template component="looma-customizer" module="./customizer.js"><defs>
83
84
  <state name="previews" type="list" value="${escape(JSON.stringify(initial))}"><prop type="object">${cardFields.map(name => `<prop name="${name}" required type="${name === 'resizable' ? 'boolean' : 'string'}"></prop>`).join('')}</prop></state>
84
85
  <state name="cards" type="list" value="${escape(JSON.stringify(initial))}"><prop type="object">${cardFields.map(name => `<prop name="${name}" required type="${name === 'resizable' ? 'boolean' : 'string'}"></prop>`).join('')}</prop></state>
85
86
  </defs>
@@ -102,7 +103,7 @@ export function customizerResource(site, input = defaultRecipe()) {
102
103
  <section data-theme-sampler><ui-stack gap="xs"><ui-text variant="heading" as="h2">Theme sampler</ui-text>${documentationCard('ui-cluster', '/99-theme-sampler', true)}</ui-stack></section>
103
104
  <noscript>Enable JavaScript to edit the theme. The component reference and example previews remain available.</noscript>
104
105
  </div>${refinement('components', ` <section class="examples"><ui-stack><ui-form-field><label slot="label" for="example-query">Search components</label><ui-input id="example-query" type="search" data-example-query placeholder="Name, tag or purpose"></ui-input></ui-form-field><ui-text variant="caption" role="status" aria-live="polite" data-example-count></ui-text><ui-disclosure summary="Add an example"><ui-stack><ui-combobox id="example-choice" data-add-example label="Choose a component example" placeholder="Search buttons, fields, dialogs…" disclosure clearable>${options}</ui-combobox><ui-button data-action="add" disabled>Add to preview</ui-button></ui-stack></ui-disclosure>
105
- <ui-grid columns="2" min="sm"><section $each="card of $previews" $key="$card.id"><looma-example-card ${cardFields.filter(name => name !== 'id').map(name => `from:${name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase())}="$card.${name}"`).join(' ')} from:identity="$card.id" loading="eager" removable></looma-example-card></section></ui-grid>
106
+ <ui-grid columns="2" min="sm"><section $each="card of $previews" $key="$card.id"><looma-example-card ${cardFields.filter(name => name !== 'id').map(name => `from:${name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase())}="$card.${name}"`).join(' ')} from:identity="$card.id" removable><looma-preview-choice slot="preview" from:identity="$card.id" from:namespace="concat('selected-', $card.id)"></looma-preview-choice></looma-example-card></section></ui-grid>
106
107
  <ui-button data-action="more-examples">Show more components</ui-button></ui-stack></section>
107
108
  `)}</ui-stack></div>
108
109
  <style>
@@ -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','src','resizable','category','tag','nativeRoot','href','packageName'].map(key => [key, selected[key]]));
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('message', ready); view.removeEventListener('popstate', renderView); view.removeEventListener('hashchange', renderView); view.removeEventListener(themeEvent, synchronize); };
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
  }
@@ -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 only its native preview frame and code overflow. Controls use Looma. */
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
- body:has([data-preview]) { background: var(--ui-surface); color: var(--ui-text); font-family: var(--ui-font-sans); font-size: var(--ui-font-size); line-height: var(--ui-line-height); }
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
- html[data-preview-reference], html[data-preview-reference] body { background: var(--ui-surface); }
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("#docs-save-changes");
4
+ const button = root.querySelector('[data-example-id="docs-save-changes"]');
5
5
  if (!button)
6
6
  return () => { };
7
7
  let timer;
@@ -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("#docs-checkbox-all");
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
+ }
@@ -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("#docs-search-input");
5
- const status = root.querySelector("#docs-search-status");
6
- const empty = root.querySelector("#docs-search-empty");
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("#docs-result-design-tokens"),
9
- root.querySelector("#docs-result-token-overrides"),
10
- root.querySelector("#docs-result-button-variants")
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?.id === "docs-search-input")
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(`#${buttonId}`);
5
- const toast = root.querySelector(`#${toastId}`);
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;
@@ -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
- /** Local capabilities stay in the parent editor; opaque example frames receive only theme CSS. */
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
- if (url.pathname.startsWith(api + 'preview/')) {
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 previewPath = example => `/_looma/preview/${exampleKey(example.id)}/`;
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) : ''}" src="${base}${previewPath(example).slice(1)}"${example.resizable ? ' resizable' : ''}>${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>`;
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', '&#10;')}</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', '&#10;')}</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
  }