@glw907/cairn-cms 0.11.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/components/ComponentForm.svelte +33 -10
  2. package/dist/components/ComponentForm.svelte.d.ts.map +1 -1
  3. package/dist/components/IconPicker.svelte +53 -7
  4. package/dist/components/IconPicker.svelte.d.ts +7 -3
  5. package/dist/components/IconPicker.svelte.d.ts.map +1 -1
  6. package/dist/content/adapter.d.ts +4 -0
  7. package/dist/content/adapter.d.ts.map +1 -0
  8. package/dist/content/adapter.js +4 -0
  9. package/dist/content/concepts.js +2 -2
  10. package/dist/content/schema.d.ts +75 -0
  11. package/dist/content/schema.d.ts.map +1 -0
  12. package/dist/content/schema.js +72 -0
  13. package/dist/content/types.d.ts +30 -7
  14. package/dist/content/types.d.ts.map +1 -1
  15. package/dist/content/validate.d.ts +5 -3
  16. package/dist/content/validate.d.ts.map +1 -1
  17. package/dist/content/validate.js +14 -7
  18. package/dist/delivery/content-index.d.ts +8 -0
  19. package/dist/delivery/content-index.d.ts.map +1 -1
  20. package/dist/delivery/content-index.js +17 -8
  21. package/dist/delivery/index.d.ts +5 -1
  22. package/dist/delivery/index.d.ts.map +1 -1
  23. package/dist/delivery/index.js +2 -0
  24. package/dist/delivery/seo-fields.d.ts +22 -0
  25. package/dist/delivery/seo-fields.d.ts.map +1 -0
  26. package/dist/delivery/seo-fields.js +32 -0
  27. package/dist/delivery/site-index.d.ts +2 -2
  28. package/dist/delivery/site-index.d.ts.map +1 -1
  29. package/dist/delivery/site-index.js +16 -18
  30. package/dist/delivery/site-indexes.d.ts +26 -0
  31. package/dist/delivery/site-indexes.d.ts.map +1 -0
  32. package/dist/delivery/site-indexes.js +22 -0
  33. package/dist/index.d.ts +9 -3
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +5 -2
  36. package/dist/render/component-grammar.d.ts +7 -0
  37. package/dist/render/component-grammar.d.ts.map +1 -1
  38. package/dist/render/component-grammar.js +27 -8
  39. package/dist/render/component-validate.js +3 -3
  40. package/dist/render/glyph.d.ts +4 -1
  41. package/dist/render/glyph.d.ts.map +1 -1
  42. package/dist/render/glyph.js +6 -2
  43. package/dist/render/registry.d.ts +23 -5
  44. package/dist/render/registry.d.ts.map +1 -1
  45. package/dist/render/registry.js +6 -0
  46. package/dist/render/rehype-dispatch.d.ts +1 -5
  47. package/dist/render/rehype-dispatch.d.ts.map +1 -1
  48. package/dist/render/rehype-dispatch.js +71 -19
  49. package/dist/render/remark-directives.d.ts +1 -1
  50. package/dist/render/remark-directives.d.ts.map +1 -1
  51. package/dist/render/remark-directives.js +37 -0
  52. package/dist/sveltekit/public-routes.d.ts +3 -0
  53. package/dist/sveltekit/public-routes.d.ts.map +1 -1
  54. package/dist/sveltekit/public-routes.js +9 -2
  55. package/package.json +1 -1
  56. package/src/lib/components/ComponentForm.svelte +33 -10
  57. package/src/lib/components/IconPicker.svelte +53 -7
  58. package/src/lib/content/adapter.ts +10 -0
  59. package/src/lib/content/concepts.ts +2 -2
  60. package/src/lib/content/schema.ts +133 -0
  61. package/src/lib/content/types.ts +30 -7
  62. package/src/lib/content/validate.ts +10 -7
  63. package/src/lib/delivery/content-index.ts +25 -8
  64. package/src/lib/delivery/index.ts +5 -1
  65. package/src/lib/delivery/seo-fields.ts +43 -0
  66. package/src/lib/delivery/site-index.ts +15 -16
  67. package/src/lib/delivery/site-indexes.ts +52 -0
  68. package/src/lib/index.ts +8 -2
  69. package/src/lib/render/component-grammar.ts +34 -10
  70. package/src/lib/render/component-validate.ts +3 -3
  71. package/src/lib/render/glyph.ts +6 -2
  72. package/src/lib/render/registry.ts +27 -5
  73. package/src/lib/render/rehype-dispatch.ts +67 -20
  74. package/src/lib/render/remark-directives.ts +39 -1
  75. package/src/lib/sveltekit/public-routes.ts +12 -2
@@ -1,4 +1,5 @@
1
1
  import { h } from 'hastscript';
2
+ import { dataAttrProp } from './registry.js';
2
3
  export function isElement(node) {
3
4
  return !!node && node.type === 'element';
4
5
  }
@@ -14,24 +15,6 @@ export function iconSpan(glyphEl, role) {
14
15
  const className = role === 'secondary' ? ['ec-icon', 'ec-icon-secondary'] : ['ec-icon'];
15
16
  return h('span', { className }, [glyphEl]);
16
17
  }
17
- // Pull the section's <h2> out, retag it .card-title, and build the .ec-head row
18
- // (optional icon + heading). Returns the head plus the remaining body children.
19
- // `makeIcon` (site-supplied) turns the stamped data-icon into an element; omit it
20
- // for a head with no icon.
21
- export function splitHead(node, makeIcon) {
22
- const children = node.children;
23
- const i = children.findIndex((c) => isElement(c) && c.tagName === 'h2');
24
- const h2 = children[i];
25
- h2.properties = { ...h2.properties, className: ['card-title'] };
26
- const rest = children.filter((_, j) => j !== i);
27
- const icon = strProp(node, 'dataIcon');
28
- const role = strProp(node, 'dataRole');
29
- const headKids = [];
30
- if (makeIcon && icon)
31
- headKids.push(makeIcon(icon, role));
32
- headKids.push(h2);
33
- return { head: h('div', { className: ['ec-head'] }, headKids), rest };
34
- }
35
18
  /** Section wrapper: `<section class=…><div class="card-body">…</div></section>`. */
36
19
  export function cardShell(classes, body) {
37
20
  return h('section', { className: classes }, [h('div', { className: ['card-body'] }, body)]);
@@ -58,11 +41,80 @@ function transformChildren(children, registry) {
58
41
  return c;
59
42
  });
60
43
  }
44
+ // Read a stamped attribute back into its typed value. Booleans arrive as the strings
45
+ // 'true'/'false'; everything else is the literal string the author wrote.
46
+ function readAttributes(node, def) {
47
+ const out = {};
48
+ for (const field of def.attributes ?? []) {
49
+ const value = strProp(node, dataAttrProp(field.key));
50
+ if (value == null)
51
+ continue;
52
+ out[field.key] = field.type === 'boolean' ? value === 'true' : value;
53
+ }
54
+ return out;
55
+ }
56
+ // The title label paragraph carries data-slot="title"; build() wants its inline children, not
57
+ // the marked paragraph. Return the paragraph's children.
58
+ function stripSlotMarker(child) {
59
+ return isElement(child) ? child.children : [child];
60
+ }
61
+ // Split a component's stamped children into named slots and the default body. A child marked
62
+ // data-slot="title"/<name> routes to that slot; an unmarked child is body. A repeatable slot
63
+ // wraps a <ul>, so its items are that list's <li> children, one child-list per item.
64
+ function partitionSlots(node) {
65
+ const named = new Map();
66
+ const body = [];
67
+ for (const child of node.children) {
68
+ const slotName = isElement(child) ? strProp(child, 'dataSlot') : undefined;
69
+ if (slotName === 'title')
70
+ named.set('title', stripSlotMarker(child));
71
+ else if (slotName)
72
+ named.set(slotName, [child]);
73
+ else
74
+ body.push(child);
75
+ }
76
+ return {
77
+ slot(name) {
78
+ if (name === 'body')
79
+ return body;
80
+ const wrap = named.get(name);
81
+ if (!wrap)
82
+ return [];
83
+ // For title we stored the label's own children, so return them as-is. For a markdown or
84
+ // inline named slot the wrapper <div> holds the rendered children; unwrap it.
85
+ if (name === 'title')
86
+ return wrap;
87
+ const div = wrap[0];
88
+ return isElement(div) ? div.children : wrap;
89
+ },
90
+ items(name) {
91
+ const wrap = named.get(name);
92
+ const div = wrap?.[0];
93
+ if (!div || !isElement(div))
94
+ return [];
95
+ const ul = div.children.find((c) => isElement(c) && c.tagName === 'ul');
96
+ if (!ul || !isElement(ul))
97
+ return [];
98
+ return ul.children
99
+ .filter((li) => isElement(li) && li.tagName === 'li')
100
+ .map((li) => li.children);
101
+ },
102
+ };
103
+ }
61
104
  function transformNode(node, registry) {
62
105
  node.children = transformChildren(node.children, registry);
63
106
  const name = strProp(node, 'dataPrimitive');
64
107
  const def = name ? registry.get(name) : undefined;
65
- return def ? def.build(node) : node;
108
+ if (!def)
109
+ return node;
110
+ const parts = partitionSlots(node);
111
+ const ctx = {
112
+ attributes: readAttributes(node, def),
113
+ slot: parts.slot,
114
+ items: parts.items,
115
+ node,
116
+ };
117
+ return def.build(ctx);
66
118
  }
67
119
  /** Rehype transformer: dispatch each stamped element through its registry `build`
68
120
  * fn. When `stagger` is on, each top-level primitive gets a `data-rise` attribute
@@ -1,4 +1,4 @@
1
1
  import type { Root } from 'mdast';
2
- import type { ComponentRegistry } from './registry.js';
2
+ import { type ComponentRegistry } from './registry.js';
3
3
  export declare function remarkDirectiveStamp(registry: ComponentRegistry): (tree: Root) => void;
4
4
  //# sourceMappingURL=remark-directives.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"remark-directives.d.ts","sourceRoot":"","sources":["../../src/lib/render/remark-directives.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA8B,IAAI,EAAQ,MAAM,OAAO,CAAC;AAGpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAmCvD,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,IAEtD,MAAM,IAAI,UA8BnB"}
1
+ {"version":3,"file":"remark-directives.d.ts","sourceRoot":"","sources":["../../src/lib/render/remark-directives.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA8B,IAAI,EAAQ,MAAM,OAAO,CAAC;AAGpE,OAAO,EAAgB,KAAK,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAkDrE,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,IAEtD,MAAM,IAAI,UAqDnB"}
@@ -1,4 +1,19 @@
1
1
  import { visit } from 'unist-util-visit';
2
+ import { dataAttrProp } from './registry.js';
3
+ // mdast-util-directive carries the `[label]` as a paragraph whose `data.directiveLabel` is set.
4
+ function isDirectiveLabel(node) {
5
+ return Boolean(node.data?.directiveLabel);
6
+ }
7
+ // Stamp data-slot on a child so the rehype dispatch partitioner can route it. For a nested
8
+ // container directive we also set hName so it renders as a <div> wrapper rather than being
9
+ // dropped as an unknown directive.
10
+ function markSlot(node, name) {
11
+ const n = node;
12
+ const data = n.data ?? (n.data = {});
13
+ if (n.type === 'containerDirective')
14
+ data.hName = 'div';
15
+ data.hProperties = { ...(data.hProperties ?? {}), dataSlot: name };
16
+ }
2
17
  // Reconstruct a directive's authored attribute block (`{#id .class key="value"}`).
3
18
  // Accidental prose directives carry none, so this is almost always empty.
4
19
  function serializeAttributes(attributes) {
@@ -42,6 +57,7 @@ export function remarkDirectiveStamp(registry) {
42
57
  visit(tree, 'containerDirective', (node) => {
43
58
  if (!known.has(node.name))
44
59
  return;
60
+ const def = registry.get(node.name);
45
61
  const attrs = node.attributes ?? {};
46
62
  const role = attrs.role || undefined;
47
63
  let icon = attrs.icon || undefined;
@@ -52,9 +68,30 @@ export function remarkDirectiveStamp(registry) {
52
68
  properties.dataIcon = icon;
53
69
  if (role)
54
70
  properties.dataRole = role;
71
+ // Carry every declared attribute to hast so the dispatch partitioner can build the
72
+ // component context. data-attr-<key> survives to the element; build() consumes it and
73
+ // returns a fresh element, so the marker never reaches the published DOM.
74
+ for (const field of def?.attributes ?? []) {
75
+ const raw = attrs[field.key];
76
+ if (raw != null)
77
+ properties[dataAttrProp(field.key)] = raw;
78
+ }
55
79
  const data = node.data ?? (node.data = {});
56
80
  data.hName = 'div';
57
81
  data.hProperties = properties;
82
+ // Mark the title label paragraph and the nested slot directives so they survive to hast
83
+ // and the partitioner can find them. A slot named in the component schema (other than the
84
+ // default body) is a nested container directive; the title is the directive [label].
85
+ const slotNames = new Set((def?.slots ?? []).map((s) => s.name));
86
+ for (const child of node.children) {
87
+ if (isDirectiveLabel(child) && slotNames.has('title')) {
88
+ markSlot(child, 'title');
89
+ }
90
+ else if (child.type === 'containerDirective' &&
91
+ slotNames.has(child.name)) {
92
+ markSlot(child, child.name);
93
+ }
94
+ }
58
95
  });
59
96
  visit(tree, ['textDirective', 'leafDirective'], (node, index, parent) => {
60
97
  if (!parent || index == null)
@@ -17,6 +17,9 @@ export interface PublicRoutesDeps {
17
17
  rss?: string;
18
18
  json?: string;
19
19
  };
20
+ /** A site-wide default OG image, used when an entry declares none. Resolved to absolute like the
21
+ * canonical URL, so a relative path such as "/og/default.png" works. */
22
+ defaultImage?: string;
20
23
  }
21
24
  /** The archive and tag list data: summaries the template renders. */
22
25
  export interface ListData {
@@ -1 +1 @@
1
- {"version":3,"file":"public-routes.d.ts","sourceRoot":"","sources":["../../src/lib/sveltekit/public-routes.ts"],"names":[],"m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M,WAAW,OAAQ,SAAQ,QAAQ;IACvC,GAAG,EAAE,MAAM,CAAC;CACb;AAED,oDAAoD;AACpD,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CACxC;AAED,oFAAoF;AACpF,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,YAAY,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,EAAE,OAAO,CAAC;IACb,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,KAAK,CAAC,EAAE,cAAc,CAAC;CACxB;AAED,2DAA2D;AAC3D,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,gBAAgB;uBAWvB;QAAE,GAAG,EAAE,GAAG,CAAA;KAAE,KAAG,OAAO,CAAC,SAAS,CAAC;6BA0BjC,MAAM,KAAG,QAAQ;8BAKhB,MAAM,KAAG,YAAY;yBAK1B,MAAM,SAAS;QAAE,MAAM,EAAE;YAAE,GAAG,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,KAAG,OAAO;mBAO5D;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE;EAKvC"}
@@ -5,9 +5,10 @@
5
5
  // from globs, so it stays in the prerender graph and out of the runtime Worker.
6
6
  import { error } from '@sveltejs/kit';
7
7
  import { buildSeoMeta } from '../delivery/seo.js';
8
+ import { readSeoFields, resolveImageUrl } from '../delivery/seo-fields.js';
8
9
  /** Build the public loaders for a site's unified index. */
9
10
  export function createPublicRoutes(deps) {
10
- const { site, render, origin, siteName, description, feeds } = deps;
11
+ const { site, render, origin, siteName, description, feeds, defaultImage } = deps;
11
12
  /** Resolve one concept's index by id, or a 404 (the route names an unconfigured concept). */
12
13
  function indexOf(conceptId) {
13
14
  const index = site.concept(conceptId);
@@ -22,15 +23,21 @@ export function createPublicRoutes(deps) {
22
23
  throw error(404, `Not found: ${event.url.pathname}`);
23
24
  const { newer, older } = site.adjacent(entry);
24
25
  const canonicalUrl = origin + entry.permalink;
26
+ const fields = readSeoFields(entry.frontmatter);
27
+ const rawImage = fields.image ?? defaultImage;
28
+ const image = rawImage ? resolveImageUrl(rawImage, origin) : undefined;
25
29
  // A dated entry is an article; an undated one (a page) is a website.
26
30
  const seo = buildSeoMeta({
27
31
  title: entry.title,
28
- description: entry.frontmatter.description || entry.excerpt || description,
32
+ description: fields.description || entry.excerpt || description,
29
33
  canonicalUrl,
30
34
  siteName,
31
35
  type: entry.date ? 'article' : 'website',
32
36
  ...(entry.date ? { published: entry.date } : {}),
33
37
  ...(entry.updated ? { modified: entry.updated } : {}),
38
+ ...(image ? { image } : {}),
39
+ ...(fields.robots ? { robots: fields.robots } : {}),
40
+ ...(fields.author ? { author: fields.author } : {}),
34
41
  feeds,
35
42
  });
36
43
  return { entry, html: await render(entry.body, { stagger: true }), canonicalUrl, seo, newer, older };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glw907/cairn-cms",
3
- "version": "0.11.0",
3
+ "version": "0.14.0",
4
4
  "description": "Embedded, magic-link, GitHub-committing CMS for SvelteKit/Cloudflare sites.",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -38,6 +38,32 @@ markdown. Back returns to the picker. This is not a nested HTML form; Insert cal
38
38
  return Array.isArray(v) ? v : [];
39
39
  }
40
40
 
41
+ // Stable per-item ids run parallel to each repeatable slot's value array, so the {#each} keys by
42
+ // identity instead of index. A mid-list removal then drops the right DOM node and the focused
43
+ // item follows the data. Ids come from a monotonic module-local counter, never Math.random or
44
+ // Date.now. The value arrays in values.slots stay the canonical string lists serializeComponent
45
+ // reads, so the emitted markdown is unchanged. emptyValues seeds every repeatable slot to [], so
46
+ // the id lists start empty and stay in lockstep with the values through addItem/removeItem.
47
+ let nextId = 0;
48
+ const itemIds = $state<Record<string, number[]>>(
49
+ untrack(() => Object.fromEntries((def.slots ?? []).filter((s) => s.kind === 'repeatable').map((s) => [s.name, []]))),
50
+ );
51
+
52
+ // emptyValues and the itemIds seed both cover every repeatable slot, so this read always hits.
53
+ function slotIds(name: string): number[] {
54
+ return itemIds[name] ?? [];
55
+ }
56
+
57
+ function addItem(name: string): void {
58
+ slotItems(name).push('');
59
+ slotIds(name).push(nextId++);
60
+ }
61
+
62
+ function removeItem(name: string, index: number): void {
63
+ slotItems(name).splice(index, 1);
64
+ slotIds(name).splice(index, 1);
65
+ }
66
+
41
67
  // Typed accessors over the unions so explicit value targets stay sound.
42
68
  function asString(key: string): string {
43
69
  const v = values.attributes[key];
@@ -79,7 +105,6 @@ markdown. Back returns to the picker. This is not a nested HTML form; Insert cal
79
105
  <input
80
106
  class="checkbox checkbox-sm"
81
107
  type="checkbox"
82
- aria-label={field.label}
83
108
  aria-invalid={Boolean(errors[field.key])}
84
109
  aria-describedby={errors[field.key] ? `err-${field.key}` : undefined}
85
110
  checked={asBool(field.key)}
@@ -92,7 +117,6 @@ markdown. Back returns to the picker. This is not a nested HTML form; Insert cal
92
117
  <span class="text-sm font-medium">{field.label}</span>
93
118
  <select
94
119
  class="select"
95
- aria-label={field.label}
96
120
  aria-invalid={Boolean(errors[field.key])}
97
121
  aria-describedby={errors[field.key] ? `err-${field.key}` : undefined}
98
122
  value={asString(field.key)}
@@ -107,6 +131,7 @@ markdown. Back returns to the picker. This is not a nested HTML form; Insert cal
107
131
  <span class="text-sm font-medium">{field.label}</span>
108
132
  <IconPicker
109
133
  {icons}
134
+ label={field.label}
110
135
  value={asString(field.key)}
111
136
  required={field.required ?? false}
112
137
  onChange={(name) => (values.attributes[field.key] = name)}
@@ -117,7 +142,6 @@ markdown. Back returns to the picker. This is not a nested HTML form; Insert cal
117
142
  <span class="text-sm font-medium">{field.label}</span>
118
143
  <input
119
144
  class="input"
120
- aria-label={field.label}
121
145
  aria-invalid={Boolean(errors[field.key])}
122
146
  aria-describedby={errors[field.key] ? `err-${field.key}` : undefined}
123
147
  value={asString(field.key)}
@@ -134,7 +158,6 @@ markdown. Back returns to the picker. This is not a nested HTML form; Insert cal
134
158
  <span class="text-sm font-medium">{slot.label}</span>
135
159
  <textarea
136
160
  class="textarea"
137
- aria-label={slot.label}
138
161
  aria-invalid={Boolean(errors[slot.name])}
139
162
  aria-describedby={errors[slot.name] ? `err-${slot.name}` : undefined}
140
163
  rows={3}
@@ -147,7 +170,6 @@ markdown. Back returns to the picker. This is not a nested HTML form; Insert cal
147
170
  <span class="text-sm font-medium">{slot.label}</span>
148
171
  <input
149
172
  class="input"
150
- aria-label={slot.label}
151
173
  aria-invalid={Boolean(errors[slot.name])}
152
174
  aria-describedby={errors[slot.name] ? `err-${slot.name}` : undefined}
153
175
  value={slotString(slot.name)}
@@ -160,16 +182,17 @@ markdown. Back returns to the picker. This is not a nested HTML form; Insert cal
160
182
 
161
183
  {#each repeatableSlots as slot (slot.name)}
162
184
  {@const items = slotItems(slot.name)}
185
+ {@const ids = slotIds(slot.name)}
163
186
  <fieldset class="rounded-box border border-base-300 flex flex-col gap-2 p-2">
164
187
  <legend class="text-sm font-medium">{slot.label}</legend>
165
- <!-- Index key is deliberate: items are bare strings with no stable id, so the value bindings and splice/push are index-based by design. -->
166
- {#each items as _, i (i)}
188
+ <!-- Keyed by the parallel stable id so a mid-list removal drops the right node and focus follows the data; the value still binds to the canonical items[i] string the serializer reads. -->
189
+ {#each ids as id, i (id)}
167
190
  <div class="flex items-center gap-2">
168
- <input class="input input-sm flex-1" aria-label={`${slot.label} item`} bind:value={items[i]} />
169
- <button type="button" class="btn btn-ghost btn-sm" aria-label={`Remove item ${i + 1}`} onclick={() => items.splice(i, 1)}>✕</button>
191
+ <input class="input input-sm flex-1" aria-label={`${slot.label} ${i + 1}`} bind:value={items[i]} />
192
+ <button type="button" class="btn btn-ghost btn-sm" aria-label={`Remove item ${i + 1}`} onclick={() => removeItem(slot.name, i)}>✕</button>
170
193
  </div>
171
194
  {/each}
172
- <button type="button" class="btn btn-sm self-start" onclick={() => items.push('')}>Add item</button>
195
+ <button type="button" class="btn btn-sm self-start" onclick={() => addItem(slot.name)}>Add item</button>
173
196
  {#if errors[slot.name]}<span id={`err-${slot.name}`} role="alert" class="text-error text-xs">{errors[slot.name]}</span>{/if}
174
197
  </fieldset>
175
198
  {/each}
@@ -1,10 +1,13 @@
1
1
  <!--
2
2
  @component
3
- A visual icon choice over the site's IconSet. Each glyph is a toggle button; the selected one carries
4
- aria-pressed. When the field is optional, a None button clears the value. The glyph renders inline from
5
- the IconSet path data, matching the renderer's 256-unit viewBox.
3
+ A visual icon choice over the site's IconSet. The choices form a radiogroup; each glyph is a radio
4
+ button carrying aria-checked, and the selected one carries btn-primary for the visible state. When the
5
+ field is optional, a None radio clears the value. A roving tabindex keeps a single tab stop and arrow
6
+ keys move the selection, the standard radiogroup keyboard model. The glyph renders inline from the
7
+ IconSet path data, matching the renderer's 256-unit viewBox.
6
8
  -->
7
9
  <script lang="ts">
10
+ import { tick } from 'svelte';
8
11
  import type { IconSet } from '../render/glyph.js';
9
12
 
10
13
  interface Props {
@@ -16,20 +19,60 @@ the IconSet path data, matching the renderer's 256-unit viewBox.
16
19
  required: boolean;
17
20
  /** Called with the new glyph name (or '' for none). */
18
21
  onChange: (name: string) => void;
22
+ /** The group's accessible name, threaded from the field label. Defaults to Icon. */
23
+ label?: string;
19
24
  }
20
25
 
21
- let { icons, value, required, onChange }: Props = $props();
26
+ let { icons, value, required, onChange, label = 'Icon' }: Props = $props();
27
+
28
+ // The radiogroup container, used to move focus with the selection per the ARIA radiogroup pattern.
29
+ let group: HTMLDivElement;
22
30
 
23
31
  const names = $derived(Object.keys(icons));
32
+ // The selectable keys in DOM order: the optional None choice ('') first, then each glyph name.
33
+ // Arrow-key navigation walks this list, and the roving tabindex marks the selected key (or the
34
+ // first key when nothing is selected) as the single tab stop.
35
+ const choices = $derived(required ? names : ['', ...names]);
36
+ const tabStop = $derived(choices.includes(value) ? value : choices[0]);
37
+
38
+ function move(delta: number): void {
39
+ // Navigate relative to the focused element (the current tab stop), not the bound value. In a
40
+ // required group with no value, tabStop is the first radio while value is '', so a value-based
41
+ // origin would skip the first step.
42
+ const from = Math.max(0, choices.indexOf(tabStop));
43
+ const next = (from + delta + choices.length) % choices.length;
44
+ onChange(choices[next]);
45
+ // The roving tabindex updates reactively, so wait for the DOM then move focus onto the new tab
46
+ // stop. The keydown handler runs only when focus is already inside the group, so this never
47
+ // steals focus on mount.
48
+ void tick().then(() => {
49
+ const target = group?.querySelector<HTMLElement>('[tabindex="0"]');
50
+ target?.focus();
51
+ });
52
+ }
53
+
54
+ function onKeydown(e: KeyboardEvent): void {
55
+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
56
+ e.preventDefault();
57
+ move(1);
58
+ } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
59
+ e.preventDefault();
60
+ move(-1);
61
+ }
62
+ }
24
63
  </script>
25
64
 
26
- <div class="flex flex-wrap gap-2" role="group" aria-label="Icon">
65
+ <div class="flex flex-wrap gap-2" role="radiogroup" aria-label={label} bind:this={group}>
27
66
  {#if !required}
28
67
  <button
29
68
  type="button"
30
69
  class="btn btn-sm"
31
70
  class:btn-primary={value === ''}
32
- aria-pressed={value === ''}
71
+ role="radio"
72
+ aria-checked={value === ''}
73
+ aria-label="None"
74
+ tabindex={tabStop === '' ? 0 : -1}
75
+ onkeydown={onKeydown}
33
76
  onclick={() => onChange('')}
34
77
  >None</button>
35
78
  {/if}
@@ -38,8 +81,11 @@ the IconSet path data, matching the renderer's 256-unit viewBox.
38
81
  type="button"
39
82
  class="btn btn-sm gap-1"
40
83
  class:btn-primary={value === name}
41
- aria-pressed={value === name}
84
+ role="radio"
85
+ aria-checked={value === name}
42
86
  aria-label={name}
87
+ tabindex={tabStop === name ? 0 : -1}
88
+ onkeydown={onKeydown}
43
89
  onclick={() => onChange(name)}
44
90
  >
45
91
  <svg class="ec-glyph" viewBox="0 0 256 256" fill="currentColor" aria-hidden="true" width="16" height="16">
@@ -0,0 +1,10 @@
1
+ // cairn-cms: the adapter-authoring helper. A plain `const adapter: CairnAdapter = {...}` annotation
2
+ // widens each concept's schema type away and breaks typed reads. defineAdapter captures the adapter
3
+ // through a `const` type parameter, so each concept's concrete ConceptSchema<F> survives for the
4
+ // full-auto typed reads in createSiteIndexes, while still checking the adapter against the contract.
5
+ import type { CairnAdapter } from './types.js';
6
+
7
+ /** Declare a site's adapter while preserving each concept's concrete schema type for typed reads. */
8
+ export function defineAdapter<const A extends CairnAdapter>(adapter: A): A {
9
+ return adapter;
10
+ }
@@ -51,8 +51,8 @@ export function normalizeConcepts(
51
51
  routing: routing[id] ?? DEFAULT_ROUTING,
52
52
  permalink: policy.permalink ?? defaultPermalink(id),
53
53
  datePrefix: policy.datePrefix ?? 'day',
54
- fields: config.fields,
55
- validate: config.validate,
54
+ fields: config.schema.fields,
55
+ validate: config.schema.validate,
56
56
  });
57
57
  }
58
58
  return descriptors;
@@ -0,0 +1,133 @@
1
+ // cairn-cms: the concept schema primitive (schema-source-of-truth design). One field
2
+ // declaration yields a plain-data field projection for the editor form, a generated validator,
3
+ // and an inferred frontmatter type. Plan 1 builds the additive primitive; the adapter-contract
4
+ // cutover and the typed reads are Plan 2.
5
+ import type { FrontmatterField, ValidationResult } from './types.js';
6
+ import { validateFields } from './validate.js';
7
+
8
+ /** The validate input the cairn adapter takes: the raw frontmatter and the body. */
9
+ export interface StandardInput {
10
+ frontmatter: Record<string, unknown>;
11
+ body: string;
12
+ }
13
+
14
+ /** A minimal local copy of the Standard Schema v1 interface (https://standardschema.dev), so the
15
+ * schema is a drop-in where the ecosystem accepts a validator, with no runtime dependency. */
16
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
17
+ readonly '~standard': {
18
+ readonly version: 1;
19
+ readonly vendor: string;
20
+ readonly validate: (value: unknown) => StandardResult<Output>;
21
+ readonly types?: { readonly input: Input; readonly output: Output };
22
+ };
23
+ }
24
+ type StandardResult<Output> =
25
+ | { readonly value: Output; readonly issues?: undefined }
26
+ | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray<PropertyKey> }> };
27
+
28
+ /** Map one field descriptor to the TS type of its normalized value. text, textarea, and date
29
+ * normalize to a string; a closed-vocabulary `tags` field to the option-union array. */
30
+ type FieldValue<K extends FrontmatterField> = K extends { type: 'boolean' }
31
+ ? boolean
32
+ : K extends { type: 'tags'; options: readonly (infer O extends string)[] }
33
+ ? O[]
34
+ : K extends { type: 'tags' | 'freetags' }
35
+ ? string[]
36
+ : string;
37
+
38
+ /** Flatten an intersection into a single readable object type. */
39
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
40
+
41
+ /** The normalized frontmatter type inferred from a field tuple. A field declared
42
+ * `required: true` is a required key; every other field is optional. */
43
+ export type InferFields<F extends readonly FrontmatterField[]> = Prettify<
44
+ { [K in F[number] as K extends { required: true } ? K['name'] : never]: FieldValue<K> } & {
45
+ [K in F[number] as K extends { required: true } ? never : K['name']]?: FieldValue<K>;
46
+ }
47
+ >;
48
+
49
+ /** A concept's schema: the plain-data field projection, the generated validator, and the
50
+ * Standard Schema conformance property. */
51
+ export interface ConceptSchema<F extends readonly FrontmatterField[] = readonly FrontmatterField[]> {
52
+ /** The declared fields as plain serializable data, for the editor form. */
53
+ readonly fields: FrontmatterField[];
54
+ /** Validate raw frontmatter, returning field-keyed errors or the normalized data. */
55
+ validate(frontmatter: Record<string, unknown>, body: string): ValidationResult;
56
+ /** Standard Schema v1 conformance, for ecosystem interop. A thin adapter over `validate`. */
57
+ readonly '~standard': StandardSchemaV1<StandardInput, InferFields<F>>['~standard'];
58
+ }
59
+
60
+ /** Extract the inferred frontmatter type from a `ConceptSchema`. */
61
+ export type Infer<S> = S extends ConceptSchema<infer F> ? InferFields<F> : never;
62
+
63
+ // Enforce the declarative per-field rules on an already-coerced value. Rules run only on a
64
+ // present, non-empty string value, so an absent optional field is never flagged. The first
65
+ // failing rule per field wins, so the author sees one clear message at a time.
66
+ function applyRules(field: FrontmatterField, value: unknown, errors: Record<string, string>, patterns: Map<string, RegExp>): void {
67
+ if (typeof value !== 'string' || value === '') return;
68
+ if (field.type === 'text' || field.type === 'textarea') {
69
+ if (field.min != null && value.length < field.min) errors[field.name] = `${field.label} must be at least ${field.min} characters`;
70
+ else if (field.max != null && value.length > field.max) errors[field.name] = `${field.label} must be at most ${field.max} characters`;
71
+ else if (field.length != null && value.length !== field.length) errors[field.name] = `${field.label} must be exactly ${field.length} characters`;
72
+ else if (field.pattern != null) {
73
+ const re = patterns.get(field.name);
74
+ if (re && !re.test(value)) errors[field.name] = `${field.label} is not in the expected format`;
75
+ }
76
+ } else if (field.type === 'date') {
77
+ if (field.min != null && value < field.min) errors[field.name] = `${field.label} must be on or after ${field.min}`;
78
+ else if (field.max != null && value > field.max) errors[field.name] = `${field.label} must be on or before ${field.max}`;
79
+ }
80
+ }
81
+
82
+ /** Options for `defineFields`. `refine` runs after the per-field rules pass, for cross-field and
83
+ * body-dependent checks. It is validation-only: it returns field-keyed errors to merge, or
84
+ * nothing, and never transforms the data. */
85
+ export interface DefineFieldsOptions<F extends readonly FrontmatterField[]> {
86
+ refine?: (data: InferFields<F>, body: string) => Record<string, string> | undefined;
87
+ }
88
+
89
+ // Compile each declared text/textarea pattern once, so a malformed pattern fails loudly at
90
+ // declaration (a site config error) instead of throwing from inside validate() on every save.
91
+ function compilePatterns(fields: FrontmatterField[]): Map<string, RegExp> {
92
+ const compiled = new Map<string, RegExp>();
93
+ for (const field of fields) {
94
+ if ((field.type === 'text' || field.type === 'textarea') && field.pattern != null) {
95
+ try {
96
+ compiled.set(field.name, new RegExp(field.pattern));
97
+ } catch (cause) {
98
+ throw new Error(`cairn: field "${field.name}" has an invalid pattern: ${field.pattern}`, { cause });
99
+ }
100
+ }
101
+ }
102
+ return compiled;
103
+ }
104
+
105
+ /** Declare a concept's fields once. Returns the schema's faces derived from that one declaration. */
106
+ export function defineFields<const F extends readonly FrontmatterField[]>(
107
+ fields: F,
108
+ options: DefineFieldsOptions<F> = {},
109
+ ): ConceptSchema<F> {
110
+ const list = [...fields] as FrontmatterField[];
111
+ const patterns = compilePatterns(list);
112
+ const validate = (frontmatter: Record<string, unknown>, body: string): ValidationResult => {
113
+ const base = validateFields(list, frontmatter);
114
+ if (!base.ok) return base;
115
+ const errors: Record<string, string> = {};
116
+ for (const field of list) applyRules(field, base.data[field.name], errors, patterns);
117
+ if (Object.keys(errors).length > 0) return { ok: false, errors };
118
+ const refined = options.refine?.(base.data as InferFields<F>, body);
119
+ return refined && Object.keys(refined).length > 0 ? { ok: false, errors: refined } : base;
120
+ };
121
+ const standard: StandardSchemaV1<StandardInput, InferFields<F>>['~standard'] = {
122
+ version: 1,
123
+ vendor: 'cairn',
124
+ validate: (value) => {
125
+ const { frontmatter = {}, body = '' } = (value ?? {}) as Partial<StandardInput>;
126
+ const result = validate(frontmatter ?? {}, body ?? '');
127
+ return result.ok
128
+ ? { value: result.data as InferFields<F> }
129
+ : { issues: Object.entries(result.errors).map(([field, message]) => ({ message, path: [field] })) };
130
+ },
131
+ };
132
+ return { fields: list, validate, '~standard': standard };
133
+ }