@backmatter/core 0.0.55 → 0.0.57

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backmatter/core",
3
- "version": "0.0.55",
3
+ "version": "0.0.57",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/src/fields.ts CHANGED
@@ -25,13 +25,51 @@ function isMarkdownFormat(value: unknown): value is MarkdownFormat {
25
25
  return MARKDOWN_FORMATS.includes(value as MarkdownFormat);
26
26
  }
27
27
 
28
- /** Allowed formats in toolbar order, without repeats; null when empty or unknown. */
29
- function normalizeAllow(value: unknown): MarkdownFormat[] | null {
30
- if (!Array.isArray(value) || value.length === 0) return null;
28
+ /** Allowed formats in toolbar order, without repeats; null when unknown, or empty unless `empty`. */
29
+ function normalizeAllow(value: unknown, empty = false): MarkdownFormat[] | null {
30
+ if (!Array.isArray(value) || (value.length === 0 && !empty)) return null;
31
31
  if (!value.every(isMarkdownFormat)) return null;
32
32
  return MARKDOWN_FORMATS.filter((format) => value.includes(format));
33
33
  }
34
34
 
35
+ /** A named inline style a markdown field declares; the site styles it (ADR 0008). */
36
+ export type MarkdownMark = {
37
+ /** Studio's button text. */
38
+ label: string;
39
+ /** When to use it, for editors and the AI. */
40
+ description?: string;
41
+ };
42
+
43
+ export type MarkdownMarkInput = { label?: string; description?: string };
44
+
45
+ const MARK_NAME = /^[a-z][a-z0-9-]*$/;
46
+
47
+ function markLabel(name: string): string {
48
+ const words = name.replace(/-/g, " ");
49
+ return words.charAt(0).toUpperCase() + words.slice(1);
50
+ }
51
+
52
+ /** Marks with labels filled in; null when a name or value is invalid or there are none. */
53
+ function normalizeMarks(value: unknown, onBadName?: (name: string) => never): Record<string, MarkdownMark> | null {
54
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
55
+ const out: Record<string, MarkdownMark> = {};
56
+ for (const [name, raw] of Object.entries(value as Record<string, unknown>)) {
57
+ if (!MARK_NAME.test(name)) {
58
+ onBadName?.(name);
59
+ return null;
60
+ }
61
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
62
+ const { label, description } = raw as Record<string, unknown>;
63
+ if (label !== undefined && typeof label !== "string") return null;
64
+ if (description !== undefined && typeof description !== "string") return null;
65
+ out[name] = {
66
+ label: label?.trim() || markLabel(name),
67
+ ...(description?.trim() ? { description: description.trim() } : {}),
68
+ };
69
+ }
70
+ return Object.keys(out).length > 0 ? out : null;
71
+ }
72
+
35
73
  /** Equality filter on scalar frontmatter keys for a file-backed relation target. */
36
74
  export type RelationWhere = Record<string, string | number | boolean>;
37
75
 
@@ -75,6 +113,8 @@ export type FieldDef<
75
113
  picker?: BlockPickerView;
76
114
  /** For markdown fields: the formatting the stored markdown may use. */
77
115
  allow?: readonly MarkdownFormat[];
116
+ /** For markdown fields: the marks it declares, by name. */
117
+ marks?: Readonly<Record<string, MarkdownMark>>;
78
118
  /** Guidance for editors and the AI: what goes here, length, tone. Never rendered. */
79
119
  description?: string;
80
120
  };
@@ -109,6 +149,7 @@ export type FieldSnapshot = {
109
149
  accept?: MediaKind[];
110
150
  picker?: BlockPickerView;
111
151
  allow?: MarkdownFormat[];
152
+ marks?: Record<string, MarkdownMark>;
112
153
  description?: string;
113
154
  };
114
155
 
@@ -517,15 +558,30 @@ const constructors = {
517
558
  }) as TextFieldDef<R, O>;
518
559
  },
519
560
  markdown: <const R extends boolean = false>(
520
- opts?: Opts<R> & { allow?: readonly MarkdownFormat[] },
561
+ opts?: Opts<R> & {
562
+ allow?: readonly MarkdownFormat[];
563
+ /** Named inline styles the site defines, e.g. `{ muted: { label: "Muted" } }` (ADR 0008). */
564
+ marks?: Readonly<Record<string, MarkdownMarkInput>>;
565
+ },
521
566
  ): FieldDef<"markdown", R> => {
522
- const allow = opts?.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(opts.allow);
567
+ const marks =
568
+ opts?.marks === undefined
569
+ ? null
570
+ : normalizeMarks(opts.marks, (name) => {
571
+ throw new Error(`field.markdown mark "${name}" must be lowercase letters, digits and dashes`);
572
+ });
573
+ if (opts?.marks !== undefined && !marks) throw new Error("field.markdown marks must declare a mark");
574
+ const allow = opts?.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(opts.allow, marks !== null);
523
575
  if (!allow) {
524
576
  throw new Error(
525
577
  'field.markdown allow must list "bold", "italic", "link", "heading" and/or "list"',
526
578
  );
527
579
  }
528
- return { ...base("markdown", { required: opts?.required, input: opts?.input }), allow };
580
+ return {
581
+ ...base("markdown", { required: opts?.required, input: opts?.input }),
582
+ allow,
583
+ ...(marks ? { marks } : {}),
584
+ };
529
585
  },
530
586
  image: <const R extends boolean = false>(opts?: Opts<R>) => base("image", opts),
531
587
  media: <const R extends boolean = false, const M extends boolean = false>(
@@ -590,6 +646,7 @@ export function serializeField(def: FieldDef): FieldSnapshot {
590
646
  ...(def.accept ? { accept: [...def.accept] } : {}),
591
647
  ...(def.picker ? { picker: def.picker } : {}),
592
648
  ...(def.allow ? { allow: [...def.allow] } : {}),
649
+ ...(def.marks ? { marks: structuredClone(def.marks) as Record<string, MarkdownMark> } : {}),
593
650
  ...(def.description?.trim() ? { description: def.description.trim() } : {}),
594
651
  };
595
652
  if (def.fields) {
@@ -681,9 +738,13 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
681
738
  }
682
739
  if (isPickerView(value.picker)) snap.picker = value.picker;
683
740
  if (snap.kind === "markdown") {
684
- const allow = value.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(value.allow);
741
+ const marks = value.marks === undefined ? null : normalizeMarks(value.marks);
742
+ if (value.marks !== undefined && !marks) throw new Error("invalid field.marks");
743
+ const allow =
744
+ value.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(value.allow, marks !== null);
685
745
  if (!allow) throw new Error("invalid field.allow");
686
746
  snap.allow = allow;
747
+ if (marks) snap.marks = marks;
687
748
  }
688
749
  if (typeof value.description === "string" && value.description.trim()) {
689
750
  snap.description = value.description.trim();
package/src/index.ts CHANGED
@@ -8,6 +8,8 @@ export type {
8
8
  FieldSnapshot,
9
9
  BlockPickerView,
10
10
  MarkdownFormat,
11
+ MarkdownMark,
12
+ MarkdownMarkInput,
11
13
  } from "./fields";
12
14
  export {
13
15
  field,
@@ -9,7 +9,11 @@ import { parseMarkdownField, type MarkdownInline } from "./markdown-field";
9
9
 
10
10
  /** Where an inline edit lands in the document. */
11
11
  export type InlineEditTarget =
12
- /** One text prop of one page block. `blockId` is the block's id, or its index when it has none. */
12
+ /**
13
+ * One text of one page block. `blockId` is the block's id, or its index when it has none.
14
+ * `field` is a field path: a prop (`title`), or a field inside an object or an array item
15
+ * (`cta.label`, `items.2.quote`), where a number is the item's index in the stored array.
16
+ */
13
17
  | { kind: "field"; blockId: string; field: string }
14
18
  /**
15
19
  * The inline content of one MDX paragraph or heading, by character offset.
@@ -30,16 +34,19 @@ export type InlineEdit = {
30
34
  exact?: true;
31
35
  };
32
36
 
33
- /** Text props a page may edit inline: block id → field → stored text. */
37
+ /** Texts a page may edit inline: block id → field path → stored text. */
34
38
  export type InlineEditableFields = Record<string, Record<string, string>>;
35
39
 
36
- /** Text field names of each block type. */
40
+ /**
41
+ * Text fields of each block type, as path templates: `title`, `cta.label`, or
42
+ * `items.*.label`, where `*` stands for every item of the array.
43
+ */
37
44
  export type InlineTextFields = Record<string, readonly string[]>;
38
45
 
39
- /** Markdown field names of each block type, with the formatting each allows. */
46
+ /** Markdown fields of each block type, as path templates, with the formatting each allows. */
40
47
  export type InlineMarkdownFields = Record<string, Record<string, readonly MarkdownFormat[]>>;
41
48
 
42
- /** Markdown props a page may edit inline: block id → field → the formatting it allows. */
49
+ /** Markdown texts a page may edit inline: block id → field path → the formatting it allows. */
43
50
  export type InlineEditableMarkdown = Record<string, Record<string, MarkdownFormat[]>>;
44
51
 
45
52
  export type InlineEditDoc = { frontmatter: Record<string, unknown>; body: string };
@@ -65,18 +72,73 @@ function propsOf(block: BlockLike): Record<string, unknown> {
65
72
  : {};
66
73
  }
67
74
 
75
+ function isRecord(value: unknown): value is Record<string, unknown> {
76
+ return value !== null && typeof value === "object" && !Array.isArray(value);
77
+ }
78
+
79
+ const INDEX = /^(0|[1-9]\d*)$/;
80
+
81
+ /** Every path a template names in `props` that holds a value, with that value. */
82
+ function expand(template: string, props: Record<string, unknown>, each: (path: string, value: unknown) => void) {
83
+ const walk = (value: unknown, parts: string[], path: string) => {
84
+ if (parts.length === 0) return each(path, value);
85
+ const [head, ...rest] = parts as [string, ...string[]];
86
+ if (head === "*") {
87
+ if (Array.isArray(value)) value.forEach((item, i) => walk(item, rest, `${path}.${i}`));
88
+ return;
89
+ }
90
+ if (isRecord(value)) walk(value[head], rest, path ? `${path}.${head}` : head);
91
+ };
92
+ walk(props, template.split("."), "");
93
+ }
94
+
95
+ /** Whether a field path (`items.2.label`) is one the template (`items.*.label`) names. */
96
+ function fits(template: string, path: string): boolean {
97
+ const want = template.split(".");
98
+ const got = path.split(".");
99
+ return want.length === got.length && want.every((part, i) => (part === "*" ? INDEX.test(got[i]!) : part === got[i]));
100
+ }
101
+
102
+ /** The value at a field path, or undefined. */
103
+ function readPath(props: Record<string, unknown>, path: string): unknown {
104
+ let value: unknown = props;
105
+ for (const part of path.split(".")) {
106
+ if (Array.isArray(value) && INDEX.test(part)) value = value[Number(part)];
107
+ else if (isRecord(value) && !INDEX.test(part)) value = value[part];
108
+ else return undefined;
109
+ }
110
+ return value;
111
+ }
112
+
113
+ /** A copy of `node` with the value at `parts` set, copying only the objects and arrays on the way. */
114
+ function writePath(node: unknown, parts: readonly string[], value: string): unknown {
115
+ if (parts.length === 0) return value;
116
+ const [head, ...rest] = parts as [string, ...string[]];
117
+ if (Array.isArray(node)) {
118
+ const next = [...node];
119
+ next[Number(head)] = writePath(node[Number(head)], rest, value);
120
+ return next;
121
+ }
122
+ const record = isRecord(node) ? node : {};
123
+ return { ...record, [head]: writePath(record[head], rest, value) };
124
+ }
125
+
68
126
  function flatten(nodes: MarkdownInline[]): string {
69
127
  return nodes
70
128
  .map((node) => (node.type === "text" ? node.value : node.type === "break" ? "\n" : flatten(node.children)))
71
129
  .join("");
72
130
  }
73
131
 
132
+ /** Something that may be a mark (ADR 0008), which page editing would drop. */
133
+ const MARK_LIKE = /(^|[^:\\]):[a-z][a-z0-9-]*\[/;
134
+
74
135
  /**
75
136
  * The text a markdown value shows when it renders as one paragraph, line breaks
76
- * as `\n`. Null for anything else (headings, lists, several paragraphs): those
77
- * are edited in the form, not on the page.
137
+ * as `\n`. Null for anything else (headings, lists, several paragraphs, marks):
138
+ * those are edited in the form, not on the page.
78
139
  */
79
140
  export function inlineMarkdownText(source: string, allow: readonly MarkdownFormat[]): string | null {
141
+ if (MARK_LIKE.test(source)) return null;
80
142
  const { blocks } = parseMarkdownField(source, allow);
81
143
  const only = blocks[0];
82
144
  if (blocks.length !== 1 || only?.type !== "paragraph") return null;
@@ -91,10 +153,11 @@ function editableMarkdown(
91
153
  asBlocks(blocks).forEach((block, index) => {
92
154
  if (typeof block.type !== "string") return;
93
155
  const props = propsOf(block);
94
- for (const [name, allow] of Object.entries(markdownFields[block.type] ?? {})) {
95
- const value = props[name];
96
- if (typeof value !== "string" || !value.trim() || inlineMarkdownText(value, allow) === null) continue;
97
- each(blockKey(block, index), name, value, allow);
156
+ for (const [template, allow] of Object.entries(markdownFields[block.type] ?? {})) {
157
+ expand(template, props, (path, value) => {
158
+ if (typeof value !== "string" || !value.trim() || inlineMarkdownText(value, allow) === null) return;
159
+ each(blockKey(block, index), path, value, allow);
160
+ });
98
161
  }
99
162
  });
100
163
  }
@@ -110,9 +173,10 @@ export function inlineEditableFields(
110
173
  const names = textFields[block.type] ?? [];
111
174
  const props = propsOf(block);
112
175
  const fields: Record<string, string> = {};
113
- for (const name of names) {
114
- const value = props[name];
115
- if (typeof value === "string" && value.trim()) fields[name] = value;
176
+ for (const template of names) {
177
+ expand(template, props, (path, value) => {
178
+ if (typeof value === "string" && value.trim()) fields[path] = value;
179
+ });
116
180
  }
117
181
  if (Object.keys(fields).length > 0) out[blockKey(block, index)] = fields;
118
182
  });
@@ -201,16 +265,17 @@ export function applyInlineEdit(
201
265
  const index = blocks.findIndex((block, i) => blockKey(block, i) === target.blockId);
202
266
  const block = blocks[index];
203
267
  if (!block || typeof block.type !== "string") return { ok: false, reason: "stale" };
204
- const markdown = options.markdownFields?.[block.type]?.[target.field] !== undefined;
205
- if (!markdown && !(options.textFields[block.type] ?? []).includes(target.field)) {
268
+ const markdown = Object.keys(options.markdownFields?.[block.type] ?? {}).some((t) => fits(t, target.field));
269
+ if (!markdown && !(options.textFields[block.type] ?? []).some((t) => fits(t, target.field))) {
206
270
  return { ok: false, reason: "not_editable" };
207
271
  }
208
272
  const props = propsOf(block);
209
- if (props[target.field] !== edit.from) return { ok: false, reason: "stale" };
273
+ // An item reordered, removed, or edited in the form since the page rendered it is refused here.
274
+ if (readPath(props, target.field) !== edit.from) return { ok: false, reason: "stale" };
210
275
  const next = [...(doc.frontmatter[options.blocksField] as unknown[])];
211
276
  const rawIndex = (doc.frontmatter[options.blocksField] as unknown[]).indexOf(block);
212
277
  const value = edit.exact ? edit.to : markdown ? oneParagraph(edit.to) : oneLine(edit.to);
213
- next[rawIndex] = { ...block, props: { ...props, [target.field]: value } };
278
+ next[rawIndex] = { ...block, props: writePath(props, target.field.split("."), value) };
214
279
  return {
215
280
  ok: true,
216
281
  doc: { frontmatter: { ...doc.frontmatter, [options.blocksField]: next }, body: doc.body },
@@ -242,7 +307,7 @@ export function invertInlineEdit(
242
307
  const written = asBlocks(applied.doc.frontmatter[options.blocksField]).find(
243
308
  (block, i) => blockKey(block, i) === target.blockId,
244
309
  );
245
- const now = written ? propsOf(written)[target.field] : undefined;
310
+ const now = written ? readPath(propsOf(written), target.field) : undefined;
246
311
  if (typeof now !== "string") return null;
247
312
  return { target, from: now, to: edit.from, exact: true };
248
313
  }
@@ -1,6 +1,7 @@
1
1
  // packages/core/src/markdown-field.ts
2
2
  // The markdown a markdown field stores, read into a small tree a host renders.
3
3
  // It is a subset on purpose: the block owns the layout around it (ADR 0007).
4
+ // A mark the field declares is a text directive, `:name[text]` (ADR 0008).
4
5
  import type { MarkdownFormat } from "./fields";
5
6
 
6
7
  export type MarkdownInline =
@@ -8,7 +9,8 @@ export type MarkdownInline =
8
9
  | { type: "break" }
9
10
  | { type: "strong"; children: MarkdownInline[] }
10
11
  | { type: "emphasis"; children: MarkdownInline[] }
11
- | { type: "link"; href: string; children: MarkdownInline[] };
12
+ | { type: "link"; href: string; children: MarkdownInline[] }
13
+ | { type: "mark"; name: string; children: MarkdownInline[] };
12
14
 
13
15
  export type MarkdownBlock =
14
16
  | { type: "paragraph"; children: MarkdownInline[] }
@@ -16,7 +18,7 @@ export type MarkdownBlock =
16
18
  | { type: "list"; ordered: boolean; items: MarkdownInline[][] };
17
19
 
18
20
  /** Markdown the value uses that renders as text: not allowed by the field, or never allowed. */
19
- export type MarkdownOutside = MarkdownFormat | "image" | "html" | "code";
21
+ export type MarkdownOutside = MarkdownFormat | "mark" | "image" | "html" | "code";
20
22
 
21
23
  export type ParsedMarkdownField = {
22
24
  blocks: MarkdownBlock[];
@@ -32,9 +34,11 @@ const ESCAPABLE = /[!-/:-@[-`{-~]/;
32
34
  const WORD = /[\p{L}\p{N}]/u;
33
35
  const SCHEME = /^([a-z][a-z0-9+.-]*):/i;
34
36
  const SAFE_SCHEMES = new Set(["http", "https", "mailto", "tel"]);
37
+ const MARK_NAME = /^[a-z][a-z0-9-]*/;
35
38
 
36
39
  type Context = {
37
40
  allow: ReadonlySet<MarkdownFormat>;
41
+ marks: ReadonlySet<string>;
38
42
  outside: MarkdownOutside[];
39
43
  };
40
44
 
@@ -46,12 +50,14 @@ function report(ctx: Context, kind: MarkdownOutside): void {
46
50
  * Read a markdown field's value. A single newline is a line break, a blank line
47
51
  * starts a paragraph. Formatting outside `allow`, and images, HTML and code
48
52
  * always, stay as the text that was written and are listed in `outside`.
53
+ * `marks` are the mark names the field declares; any other `:name[text]` is text.
49
54
  */
50
55
  export function parseMarkdownField(
51
56
  source: string,
52
57
  allow: readonly MarkdownFormat[],
58
+ marks: readonly string[] = [],
53
59
  ): ParsedMarkdownField {
54
- const ctx: Context = { allow: new Set(allow), outside: [] };
60
+ const ctx: Context = { allow: new Set(allow), marks: new Set(marks), outside: [] };
55
61
  const blocks: MarkdownBlock[] = [];
56
62
  let paragraph: string[] = [];
57
63
  let list: { ordered: boolean; items: string[] } | null = null;
@@ -183,18 +189,34 @@ function findClose(src: string, from: number, delim: string): number {
183
189
 
184
190
  type LinkMatch = { text: string; href: string; end: number };
185
191
 
186
- /** A `[text](href)` starting at `index`, where `src[index]` is `[`. */
187
- function matchLink(src: string, index: number): LinkMatch | null {
192
+ /** Index of the `]` that closes the `[` at `index`, or -1. */
193
+ function closeBracket(src: string, index: number): number {
188
194
  let depth = 0;
189
- let close = -1;
190
195
  for (let j = index; j < src.length; j++) {
191
196
  if (isEscaped(src, j)) continue;
192
197
  if (src[j] === "[") depth++;
193
- else if (src[j] === "]" && --depth === 0) {
194
- close = j;
195
- break;
196
- }
198
+ else if (src[j] === "]" && --depth === 0) return j;
197
199
  }
200
+ return -1;
201
+ }
202
+
203
+ type MarkMatch = { name: string; text: string; end: number };
204
+
205
+ /** A `:name[text]` starting at `index`, where `src[index]` is `:`. Not after or before another `:`. */
206
+ function matchMark(src: string, index: number): MarkMatch | null {
207
+ if (src[index - 1] === ":" || src[index + 1] === ":") return null;
208
+ const name = MARK_NAME.exec(src.slice(index + 1))?.[0];
209
+ if (!name) return null;
210
+ const open = index + 1 + name.length;
211
+ if (src[open] !== "[") return null;
212
+ const close = closeBracket(src, open);
213
+ if (close < 0) return null;
214
+ return { name, text: src.slice(open + 1, close), end: close + 1 };
215
+ }
216
+
217
+ /** A `[text](href)` starting at `index`, where `src[index]` is `[`. */
218
+ function matchLink(src: string, index: number): LinkMatch | null {
219
+ const close = closeBracket(src, index);
198
220
  if (close < 0 || src[close + 1] !== "(") return null;
199
221
  let parens = 0;
200
222
  for (let j = close + 1; j < src.length; j++) {
@@ -257,6 +279,20 @@ function parseInline(src: string, ctx: Context): MarkdownInline[] {
257
279
  }
258
280
  }
259
281
 
282
+ if (char === ":") {
283
+ const mark = matchMark(src, i);
284
+ if (mark) {
285
+ if (ctx.marks.has(mark.name)) {
286
+ out.push({ type: "mark", name: mark.name, children: parseInline(mark.text, ctx) });
287
+ i = mark.end;
288
+ continue;
289
+ }
290
+ // Only a mark the field declares is one, but a name it lacks is a
291
+ // mistake worth a warning when the field declares any.
292
+ if (ctx.marks.size > 0) report(ctx, "mark");
293
+ }
294
+ }
295
+
260
296
  if (char === "[") {
261
297
  const link = matchLink(src, i);
262
298
  if (link) {
@@ -192,6 +192,8 @@ function walkFields(
192
192
  ): void {
193
193
  for (const [name, field] of Object.entries(fields)) {
194
194
  const path = fieldPath(owner, [...segments, name]);
195
+ // Inline editing addresses a field inside an object or array item by a dotted path.
196
+ if (name.includes(".")) problems.push(`${path}: a field name cannot contain "."`);
195
197
  checkObjectReference(schema, path, field, problems);
196
198
  checkRelationField(path, field, modelsByType, problems);
197
199
  checkLinkField(path, field, modelsByType, problems);