@backmatter/core 0.0.53 → 0.0.55

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.53",
3
+ "version": "0.0.55",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/src/block.ts CHANGED
@@ -135,7 +135,7 @@ function humanize(name: string): string {
135
135
  }
136
136
 
137
137
  /**
138
- * Stand-in props for a block without examples: a label for text, the first
138
+ * Stand-in props for a block without examples: a label for text and markdown, the first
139
139
  * option, the minimum, false. Richer fields stay unset.
140
140
  */
141
141
  export function placeholderBlockProps(
@@ -144,6 +144,7 @@ export function placeholderBlockProps(
144
144
  const props: Record<string, unknown> = {};
145
145
  for (const [name, field] of Object.entries(fields)) {
146
146
  if (field.kind === "text") props[name] = field.options?.[0] ?? humanize(name);
147
+ else if (field.kind === "markdown") props[name] = humanize(name);
147
148
  else if (field.kind === "number") props[name] = field.min ?? 0;
148
149
  else if (field.kind === "boolean") props[name] = false;
149
150
  }
package/src/fields.ts CHANGED
@@ -3,6 +3,7 @@ import { MEDIA_KINDS, isMediaKind, type MediaKind } from "./media-url";
3
3
 
4
4
  export type FieldKind =
5
5
  | "text"
6
+ | "markdown"
6
7
  | "image"
7
8
  | "media"
8
9
  | "relation"
@@ -13,6 +14,24 @@ export type FieldKind =
13
14
  | "object"
14
15
  | "array";
15
16
 
17
+ /** Formatting a markdown field may allow, in the order Studio's toolbar shows it. */
18
+ export const MARKDOWN_FORMATS = ["bold", "italic", "link", "heading", "list"] as const;
19
+ export type MarkdownFormat = (typeof MARKDOWN_FORMATS)[number];
20
+
21
+ /** What a markdown field allows when it lists nothing. */
22
+ export const DEFAULT_MARKDOWN_ALLOW: readonly MarkdownFormat[] = ["bold", "italic", "link"];
23
+
24
+ function isMarkdownFormat(value: unknown): value is MarkdownFormat {
25
+ return MARKDOWN_FORMATS.includes(value as MarkdownFormat);
26
+ }
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;
31
+ if (!value.every(isMarkdownFormat)) return null;
32
+ return MARKDOWN_FORMATS.filter((format) => value.includes(format));
33
+ }
34
+
16
35
  /** Equality filter on scalar frontmatter keys for a file-backed relation target. */
17
36
  export type RelationWhere = Record<string, string | number | boolean>;
18
37
 
@@ -54,6 +73,8 @@ export type FieldDef<
54
73
  accept?: readonly MediaKind[];
55
74
  /** For blocks fields: how Studio's "Add block" picker lays out the blocks. */
56
75
  picker?: BlockPickerView;
76
+ /** For markdown fields: the formatting the stored markdown may use. */
77
+ allow?: readonly MarkdownFormat[];
57
78
  /** Guidance for editors and the AI: what goes here, length, tone. Never rendered. */
58
79
  description?: string;
59
80
  };
@@ -87,6 +108,7 @@ export type FieldSnapshot = {
87
108
  multiple?: true;
88
109
  accept?: MediaKind[];
89
110
  picker?: BlockPickerView;
111
+ allow?: MarkdownFormat[];
90
112
  description?: string;
91
113
  };
92
114
 
@@ -494,6 +516,17 @@ const constructors = {
494
516
  ...(opts?.input ? { input: opts.input } : {}),
495
517
  }) as TextFieldDef<R, O>;
496
518
  },
519
+ markdown: <const R extends boolean = false>(
520
+ opts?: Opts<R> & { allow?: readonly MarkdownFormat[] },
521
+ ): FieldDef<"markdown", R> => {
522
+ const allow = opts?.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(opts.allow);
523
+ if (!allow) {
524
+ throw new Error(
525
+ 'field.markdown allow must list "bold", "italic", "link", "heading" and/or "list"',
526
+ );
527
+ }
528
+ return { ...base("markdown", { required: opts?.required, input: opts?.input }), allow };
529
+ },
497
530
  image: <const R extends boolean = false>(opts?: Opts<R>) => base("image", opts),
498
531
  media: <const R extends boolean = false, const M extends boolean = false>(
499
532
  opts?: Opts<R> & { multiple?: M; accept?: readonly MediaKind[] },
@@ -527,6 +560,7 @@ const constructors = {
527
560
 
528
561
  export const field = {
529
562
  text: described(constructors.text, 0),
563
+ markdown: described(constructors.markdown, 0),
530
564
  image: described(constructors.image, 0),
531
565
  media: described(constructors.media, 0),
532
566
  number: described(constructors.number, 0),
@@ -555,6 +589,7 @@ export function serializeField(def: FieldDef): FieldSnapshot {
555
589
  ...(def.multiple ? { multiple: true as const } : {}),
556
590
  ...(def.accept ? { accept: [...def.accept] } : {}),
557
591
  ...(def.picker ? { picker: def.picker } : {}),
592
+ ...(def.allow ? { allow: [...def.allow] } : {}),
558
593
  ...(def.description?.trim() ? { description: def.description.trim() } : {}),
559
594
  };
560
595
  if (def.fields) {
@@ -575,6 +610,7 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
575
610
  const kind = value.kind;
576
611
  const allowed: FieldKind[] = [
577
612
  "text",
613
+ "markdown",
578
614
  "image",
579
615
  "media",
580
616
  "relation",
@@ -644,6 +680,11 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
644
680
  snap.where = where;
645
681
  }
646
682
  if (isPickerView(value.picker)) snap.picker = value.picker;
683
+ if (snap.kind === "markdown") {
684
+ const allow = value.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(value.allow);
685
+ if (!allow) throw new Error("invalid field.allow");
686
+ snap.allow = allow;
687
+ }
647
688
  if (typeof value.description === "string" && value.description.trim()) {
648
689
  snap.description = value.description.trim();
649
690
  }
package/src/index.ts CHANGED
@@ -7,8 +7,22 @@ export type {
7
7
  FieldKind,
8
8
  FieldSnapshot,
9
9
  BlockPickerView,
10
+ MarkdownFormat,
10
11
  } from "./fields";
11
- export { field, serializeField, parseFieldSnapshot } from "./fields";
12
+ export {
13
+ field,
14
+ serializeField,
15
+ parseFieldSnapshot,
16
+ MARKDOWN_FORMATS,
17
+ DEFAULT_MARKDOWN_ALLOW,
18
+ } from "./fields";
19
+ export type {
20
+ MarkdownBlock,
21
+ MarkdownInline,
22
+ MarkdownOutside,
23
+ ParsedMarkdownField,
24
+ } from "./markdown-field";
25
+ export { parseMarkdownField } from "./markdown-field";
12
26
  export {
13
27
  MAX_MEDIA_BYTES,
14
28
  MAX_MEDIA_TEXT,
@@ -0,0 +1,248 @@
1
+ // packages/core/src/inline-edit.ts
2
+ //
3
+ // Inline editing on the preview page. The page knows only the DOM; whoever
4
+ // holds the document (the dashboard editor, or the site bar) knows the schema.
5
+ // The holder tells the page which block texts are editable, and applies the
6
+ // edit the page sends back. No framework imports.
7
+ import type { MarkdownFormat } from "./fields";
8
+ import { parseMarkdownField, type MarkdownInline } from "./markdown-field";
9
+
10
+ /** Where an inline edit lands in the document. */
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. */
13
+ | { kind: "field"; blockId: string; field: string }
14
+ /**
15
+ * The inline content of one MDX paragraph or heading, by character offset.
16
+ * `hash` is `bodyRangeHash` of the source in that range when the page rendered it.
17
+ */
18
+ | { kind: "body"; start: number; end: number; hash: string };
19
+
20
+ export type InlineEdit = {
21
+ target: InlineEditTarget;
22
+ /** The stored text the page showed when editing began. */
23
+ from: string;
24
+ /** What the person typed. For a body range, the markdown the page wrote from it. */
25
+ to: string;
26
+ /**
27
+ * Store `to` as it is, line breaks included. Only a holder sets this, for an
28
+ * undo that puts back the source an edit replaced; a page never sends it.
29
+ */
30
+ exact?: true;
31
+ };
32
+
33
+ /** Text props a page may edit inline: block id → field → stored text. */
34
+ export type InlineEditableFields = Record<string, Record<string, string>>;
35
+
36
+ /** Text field names of each block type. */
37
+ export type InlineTextFields = Record<string, readonly string[]>;
38
+
39
+ /** Markdown field names of each block type, with the formatting each allows. */
40
+ export type InlineMarkdownFields = Record<string, Record<string, readonly MarkdownFormat[]>>;
41
+
42
+ /** Markdown props a page may edit inline: block id → field → the formatting it allows. */
43
+ export type InlineEditableMarkdown = Record<string, Record<string, MarkdownFormat[]>>;
44
+
45
+ export type InlineEditDoc = { frontmatter: Record<string, unknown>; body: string };
46
+
47
+ export type InlineEditResult =
48
+ | { ok: true; doc: InlineEditDoc }
49
+ | { ok: false; reason: "stale" | "not_editable" | "empty" };
50
+
51
+ type BlockLike = { id?: unknown; type?: unknown; props?: unknown };
52
+
53
+ function asBlocks(value: unknown): BlockLike[] {
54
+ return Array.isArray(value) ? (value.filter((b) => b && typeof b === "object") as BlockLike[]) : [];
55
+ }
56
+
57
+ /** The id the page marks a block with: its id, or its index (as `renderPage` does). */
58
+ function blockKey(block: BlockLike, index: number): string {
59
+ return typeof block.id === "string" && block.id ? block.id : String(index);
60
+ }
61
+
62
+ function propsOf(block: BlockLike): Record<string, unknown> {
63
+ return block.props && typeof block.props === "object" && !Array.isArray(block.props)
64
+ ? (block.props as Record<string, unknown>)
65
+ : {};
66
+ }
67
+
68
+ function flatten(nodes: MarkdownInline[]): string {
69
+ return nodes
70
+ .map((node) => (node.type === "text" ? node.value : node.type === "break" ? "\n" : flatten(node.children)))
71
+ .join("");
72
+ }
73
+
74
+ /**
75
+ * 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.
78
+ */
79
+ export function inlineMarkdownText(source: string, allow: readonly MarkdownFormat[]): string | null {
80
+ const { blocks } = parseMarkdownField(source, allow);
81
+ const only = blocks[0];
82
+ if (blocks.length !== 1 || only?.type !== "paragraph") return null;
83
+ return flatten(only.children);
84
+ }
85
+
86
+ function editableMarkdown(
87
+ blocks: unknown,
88
+ markdownFields: InlineMarkdownFields,
89
+ each: (key: string, name: string, value: string, allow: readonly MarkdownFormat[]) => void,
90
+ ) {
91
+ asBlocks(blocks).forEach((block, index) => {
92
+ if (typeof block.type !== "string") return;
93
+ 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);
98
+ }
99
+ });
100
+ }
101
+
102
+ export function inlineEditableFields(
103
+ blocks: unknown,
104
+ textFields: InlineTextFields,
105
+ markdownFields: InlineMarkdownFields = {},
106
+ ): InlineEditableFields {
107
+ const out: InlineEditableFields = {};
108
+ asBlocks(blocks).forEach((block, index) => {
109
+ if (typeof block.type !== "string") return;
110
+ const names = textFields[block.type] ?? [];
111
+ const props = propsOf(block);
112
+ 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;
116
+ }
117
+ if (Object.keys(fields).length > 0) out[blockKey(block, index)] = fields;
118
+ });
119
+ editableMarkdown(blocks, markdownFields, (key, name, value) => {
120
+ out[key] = { ...out[key], [name]: value };
121
+ });
122
+ return out;
123
+ }
124
+
125
+ /** Which offered fields hold markdown, and the formatting each allows. */
126
+ export function inlineEditableMarkdown(blocks: unknown, markdownFields: InlineMarkdownFields): InlineEditableMarkdown {
127
+ const out: InlineEditableMarkdown = {};
128
+ editableMarkdown(blocks, markdownFields, (key, name, _value, allow) => {
129
+ out[key] = { ...out[key], [name]: [...allow] };
130
+ });
131
+ return out;
132
+ }
133
+
134
+ function squash(text: string): string {
135
+ return text.replace(/\s+/g, " ").trim();
136
+ }
137
+
138
+ /** The one field whose stored text the page rendered unchanged, or null. */
139
+ export function matchInlineField(fields: Record<string, string>, rendered: string): string | null {
140
+ const wanted = squash(rendered);
141
+ if (!wanted) return null;
142
+ const hits = Object.keys(fields).filter((name) => squash(fields[name]!) === wanted);
143
+ return hits.length === 1 ? hits[0]! : null;
144
+ }
145
+
146
+ /** Short FNV-1a hash of a body range's source, so a holder can tell the page saw the same text. */
147
+ export function bodyRangeHash(text: string): string {
148
+ let hash = 0x811c9dc5;
149
+ for (let i = 0; i < text.length; i += 1) {
150
+ hash ^= text.charCodeAt(i);
151
+ hash = Math.imul(hash, 0x01000193) >>> 0;
152
+ }
153
+ return hash.toString(36);
154
+ }
155
+
156
+ /** Escape what would turn typed text into inline MDX markup. */
157
+ export function escapeInlineText(text: string): string {
158
+ return text.replace(/[\\`*_~[<{]/g, (ch) => `\\${ch}`);
159
+ }
160
+
161
+ /** Escape a marker at the start of a line that would turn it into another block. */
162
+ export function escapeBlockStart(markdown: string): string {
163
+ return markdown.replace(/^(\s*)([#>+|-])/, "$1\\$2").replace(/^(\s*\d+)([.)])/, "$1\\$2");
164
+ }
165
+
166
+ /** Escape typed text so it stays one plain paragraph of MDX. */
167
+ export function escapeInlineMarkdown(text: string): string {
168
+ return escapeBlockStart(escapeInlineText(text));
169
+ }
170
+
171
+ function oneLine(text: string): string {
172
+ return text.replace(/\s*\n\s*/g, " ");
173
+ }
174
+
175
+ /** Markdown for one paragraph: single line breaks stay, blank lines go. */
176
+ function oneParagraph(text: string): string {
177
+ return text
178
+ .split("\n")
179
+ .map((line) => line.trim())
180
+ .filter(Boolean)
181
+ .join("\n");
182
+ }
183
+
184
+ export function applyInlineEdit(
185
+ doc: InlineEditDoc,
186
+ edit: InlineEdit,
187
+ options: { blocksField: string; textFields: InlineTextFields; markdownFields?: InlineMarkdownFields },
188
+ ): InlineEditResult {
189
+ const { target } = edit;
190
+ if (target.kind === "body") {
191
+ if (bodyRangeHash(doc.body.slice(target.start, target.end)) !== target.hash) {
192
+ return { ok: false, reason: "stale" };
193
+ }
194
+ const markdown = edit.exact ? edit.to : oneLine(edit.to).trim();
195
+ if (!markdown.trim()) return { ok: false, reason: "empty" };
196
+ const body = doc.body.slice(0, target.start) + markdown + doc.body.slice(target.end);
197
+ return { ok: true, doc: { frontmatter: doc.frontmatter, body } };
198
+ }
199
+
200
+ const blocks = asBlocks(doc.frontmatter[options.blocksField]);
201
+ const index = blocks.findIndex((block, i) => blockKey(block, i) === target.blockId);
202
+ const block = blocks[index];
203
+ 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)) {
206
+ return { ok: false, reason: "not_editable" };
207
+ }
208
+ const props = propsOf(block);
209
+ if (props[target.field] !== edit.from) return { ok: false, reason: "stale" };
210
+ const next = [...(doc.frontmatter[options.blocksField] as unknown[])];
211
+ const rawIndex = (doc.frontmatter[options.blocksField] as unknown[]).indexOf(block);
212
+ const value = edit.exact ? edit.to : markdown ? oneParagraph(edit.to) : oneLine(edit.to);
213
+ next[rawIndex] = { ...block, props: { ...props, [target.field]: value } };
214
+ return {
215
+ ok: true,
216
+ doc: { frontmatter: { ...doc.frontmatter, [options.blocksField]: next }, body: doc.body },
217
+ };
218
+ }
219
+
220
+ /**
221
+ * The edit that takes `doc` back after `edit` is applied to it, or null when
222
+ * `edit` would not apply. Inverting the inverse gives the edit again (a redo).
223
+ */
224
+ export function invertInlineEdit(
225
+ doc: InlineEditDoc,
226
+ edit: InlineEdit,
227
+ options: { blocksField: string; textFields: InlineTextFields; markdownFields?: InlineMarkdownFields },
228
+ ): InlineEdit | null {
229
+ const applied = applyInlineEdit(doc, edit, options);
230
+ if (!applied.ok) return null;
231
+ const { target } = edit;
232
+ if (target.kind === "body") {
233
+ const before = doc.body.slice(target.start, target.end);
234
+ const written = applied.doc.body.slice(target.start, applied.doc.body.length - (doc.body.length - target.end));
235
+ return {
236
+ target: { kind: "body", start: target.start, end: target.start + written.length, hash: bodyRangeHash(written) },
237
+ from: written,
238
+ to: before,
239
+ exact: true,
240
+ };
241
+ }
242
+ const written = asBlocks(applied.doc.frontmatter[options.blocksField]).find(
243
+ (block, i) => blockKey(block, i) === target.blockId,
244
+ );
245
+ const now = written ? propsOf(written)[target.field] : undefined;
246
+ if (typeof now !== "string") return null;
247
+ return { target, from: now, to: edit.from, exact: true };
248
+ }
@@ -0,0 +1,305 @@
1
+ // packages/core/src/markdown-field.ts
2
+ // The markdown a markdown field stores, read into a small tree a host renders.
3
+ // It is a subset on purpose: the block owns the layout around it (ADR 0007).
4
+ import type { MarkdownFormat } from "./fields";
5
+
6
+ export type MarkdownInline =
7
+ | { type: "text"; value: string }
8
+ | { type: "break" }
9
+ | { type: "strong"; children: MarkdownInline[] }
10
+ | { type: "emphasis"; children: MarkdownInline[] }
11
+ | { type: "link"; href: string; children: MarkdownInline[] };
12
+
13
+ export type MarkdownBlock =
14
+ | { type: "paragraph"; children: MarkdownInline[] }
15
+ | { type: "heading"; level: 3 | 4; children: MarkdownInline[] }
16
+ | { type: "list"; ordered: boolean; items: MarkdownInline[][] };
17
+
18
+ /** Markdown the value uses that renders as text: not allowed by the field, or never allowed. */
19
+ export type MarkdownOutside = MarkdownFormat | "image" | "html" | "code";
20
+
21
+ export type ParsedMarkdownField = {
22
+ blocks: MarkdownBlock[];
23
+ /** Each kind once, in the order it first appears. Studio warns about these. */
24
+ outside: MarkdownOutside[];
25
+ };
26
+
27
+ const HEADING = /^(#{1,6})\s+(.*)$/;
28
+ const BULLET = /^[-*+]\s+(.*)$/;
29
+ const NUMBERED = /^\d{1,9}[.)]\s+(.*)$/;
30
+ const HTML_TAG = /^<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?\/?>/;
31
+ const ESCAPABLE = /[!-/:-@[-`{-~]/;
32
+ const WORD = /[\p{L}\p{N}]/u;
33
+ const SCHEME = /^([a-z][a-z0-9+.-]*):/i;
34
+ const SAFE_SCHEMES = new Set(["http", "https", "mailto", "tel"]);
35
+
36
+ type Context = {
37
+ allow: ReadonlySet<MarkdownFormat>;
38
+ outside: MarkdownOutside[];
39
+ };
40
+
41
+ function report(ctx: Context, kind: MarkdownOutside): void {
42
+ if (!ctx.outside.includes(kind)) ctx.outside.push(kind);
43
+ }
44
+
45
+ /**
46
+ * Read a markdown field's value. A single newline is a line break, a blank line
47
+ * starts a paragraph. Formatting outside `allow`, and images, HTML and code
48
+ * always, stay as the text that was written and are listed in `outside`.
49
+ */
50
+ export function parseMarkdownField(
51
+ source: string,
52
+ allow: readonly MarkdownFormat[],
53
+ ): ParsedMarkdownField {
54
+ const ctx: Context = { allow: new Set(allow), outside: [] };
55
+ const blocks: MarkdownBlock[] = [];
56
+ let paragraph: string[] = [];
57
+ let list: { ordered: boolean; items: string[] } | null = null;
58
+
59
+ const flushParagraph = () => {
60
+ if (paragraph.length === 0) return;
61
+ const children: MarkdownInline[] = [];
62
+ paragraph.forEach((line, index) => {
63
+ if (index > 0) children.push({ type: "break" });
64
+ appendAll(children, parseInline(line, ctx));
65
+ });
66
+ blocks.push({ type: "paragraph", children });
67
+ paragraph = [];
68
+ };
69
+ const flushList = () => {
70
+ if (!list) return;
71
+ const { ordered, items } = list;
72
+ blocks.push({ type: "list", ordered, items: items.map((item) => parseInline(item, ctx)) });
73
+ list = null;
74
+ };
75
+
76
+ for (const raw of source.replace(/\r\n?/g, "\n").split("\n")) {
77
+ const line = raw.trim();
78
+ if (line === "") {
79
+ flushParagraph();
80
+ flushList();
81
+ continue;
82
+ }
83
+
84
+ const heading = HEADING.exec(line);
85
+ if (heading) {
86
+ const level = heading[1]!.length;
87
+ if (ctx.allow.has("heading") && (level === 3 || level === 4)) {
88
+ flushParagraph();
89
+ flushList();
90
+ blocks.push({ type: "heading", level, children: parseInline(heading[2]!.trim(), ctx) });
91
+ continue;
92
+ }
93
+ report(ctx, "heading");
94
+ }
95
+
96
+ const bullet = BULLET.exec(line);
97
+ const numbered = bullet ? null : NUMBERED.exec(line);
98
+ const item = bullet ?? numbered;
99
+ if (item) {
100
+ if (ctx.allow.has("list")) {
101
+ const ordered = numbered !== null;
102
+ flushParagraph();
103
+ if (list && list.ordered !== ordered) flushList();
104
+ list ??= { ordered, items: [] };
105
+ list.items.push(item[1]!.trim());
106
+ continue;
107
+ }
108
+ report(ctx, "list");
109
+ }
110
+
111
+ flushList();
112
+ paragraph.push(line);
113
+ }
114
+ flushParagraph();
115
+ flushList();
116
+ return { blocks, outside: ctx.outside };
117
+ }
118
+
119
+ function appendText(out: MarkdownInline[], value: string): void {
120
+ if (value === "") return;
121
+ const last = out[out.length - 1];
122
+ if (last?.type === "text") last.value += value;
123
+ else out.push({ type: "text", value });
124
+ }
125
+
126
+ function appendAll(out: MarkdownInline[], nodes: MarkdownInline[]): void {
127
+ for (const node of nodes) {
128
+ if (node.type === "text") appendText(out, node.value);
129
+ else out.push(node);
130
+ }
131
+ }
132
+
133
+ function isEscaped(src: string, index: number): boolean {
134
+ let slashes = 0;
135
+ for (let i = index - 1; i >= 0 && src[i] === "\\"; i--) slashes++;
136
+ return slashes % 2 === 1;
137
+ }
138
+
139
+ function isSpace(char: string | undefined): boolean {
140
+ return char === undefined || /\s/.test(char);
141
+ }
142
+
143
+ function isWord(char: string | undefined): boolean {
144
+ return char !== undefined && WORD.test(char);
145
+ }
146
+
147
+ function runLength(src: string, index: number, char: string): number {
148
+ let n = 0;
149
+ while (src[index + n] === char) n++;
150
+ return n;
151
+ }
152
+
153
+ /** Where `delim` (one or two of `*` or `_`) can open at `index`. */
154
+ function canOpen(src: string, index: number, delim: string): boolean {
155
+ const after = src[index + delim.length];
156
+ if (isSpace(after)) return false;
157
+ if (delim[0] === "_" && isWord(src[index - 1])) return false;
158
+ return true;
159
+ }
160
+
161
+ /** Index of the delimiter that closes one opened before `from`, or -1. */
162
+ function findClose(src: string, from: number, delim: string): number {
163
+ const char = delim[0]!;
164
+ let j = from;
165
+ while (j < src.length) {
166
+ if (src[j] !== char || isEscaped(src, j)) {
167
+ j++;
168
+ continue;
169
+ }
170
+ const run = runLength(src, j, char);
171
+ const closesHere =
172
+ !isSpace(src[j - 1]) && (char !== "_" || !isWord(src[j + run]));
173
+ if (closesHere) {
174
+ // "***" ends both an emphasis and a strong: a single closes on its first
175
+ // star, a double on its last two.
176
+ if (delim.length === 1 && run !== 2) return j;
177
+ if (delim.length === 2 && run >= 2) return j + run - 2;
178
+ }
179
+ j += run;
180
+ }
181
+ return -1;
182
+ }
183
+
184
+ type LinkMatch = { text: string; href: string; end: number };
185
+
186
+ /** A `[text](href)` starting at `index`, where `src[index]` is `[`. */
187
+ function matchLink(src: string, index: number): LinkMatch | null {
188
+ let depth = 0;
189
+ let close = -1;
190
+ for (let j = index; j < src.length; j++) {
191
+ if (isEscaped(src, j)) continue;
192
+ if (src[j] === "[") depth++;
193
+ else if (src[j] === "]" && --depth === 0) {
194
+ close = j;
195
+ break;
196
+ }
197
+ }
198
+ if (close < 0 || src[close + 1] !== "(") return null;
199
+ let parens = 0;
200
+ for (let j = close + 1; j < src.length; j++) {
201
+ const char = src[j]!;
202
+ if (/\s/.test(char)) return null;
203
+ if (char === "(") parens++;
204
+ else if (char === ")" && --parens === 0) {
205
+ const href = src.slice(close + 2, j);
206
+ if (href === "") return null;
207
+ return { text: src.slice(index + 1, close), href, end: j + 1 };
208
+ }
209
+ }
210
+ return null;
211
+ }
212
+
213
+ function isSafeHref(href: string): boolean {
214
+ const scheme = SCHEME.exec(href);
215
+ return !scheme || SAFE_SCHEMES.has(scheme[1]!.toLowerCase());
216
+ }
217
+
218
+ function parseInline(src: string, ctx: Context): MarkdownInline[] {
219
+ const out: MarkdownInline[] = [];
220
+ let i = 0;
221
+ while (i < src.length) {
222
+ const char = src[i]!;
223
+
224
+ if (char === "\\" && i + 1 < src.length && ESCAPABLE.test(src[i + 1]!)) {
225
+ appendText(out, src[i + 1]!);
226
+ i += 2;
227
+ continue;
228
+ }
229
+
230
+ if (char === "`") {
231
+ const close = src.indexOf("`", i + 1);
232
+ if (close > i + 1) {
233
+ report(ctx, "code");
234
+ appendText(out, src.slice(i, close + 1));
235
+ i = close + 1;
236
+ continue;
237
+ }
238
+ }
239
+
240
+ if (char === "!" && src[i + 1] === "[") {
241
+ const image = matchLink(src, i + 1);
242
+ if (image) {
243
+ report(ctx, "image");
244
+ appendText(out, src.slice(i, image.end));
245
+ i = image.end;
246
+ continue;
247
+ }
248
+ }
249
+
250
+ if (char === "<") {
251
+ const tag = HTML_TAG.exec(src.slice(i));
252
+ if (tag) {
253
+ report(ctx, "html");
254
+ appendText(out, tag[0]);
255
+ i += tag[0].length;
256
+ continue;
257
+ }
258
+ }
259
+
260
+ if (char === "[") {
261
+ const link = matchLink(src, i);
262
+ if (link) {
263
+ const children = parseInline(link.text, ctx);
264
+ if (ctx.allow.has("link") && isSafeHref(link.href)) {
265
+ out.push({ type: "link", href: link.href, children });
266
+ } else {
267
+ report(ctx, "link");
268
+ appendText(out, "[");
269
+ appendAll(out, children);
270
+ appendText(out, `](${link.href})`);
271
+ }
272
+ i = link.end;
273
+ continue;
274
+ }
275
+ }
276
+
277
+ if (char === "*" || char === "_") {
278
+ const delim = src[i + 1] === char ? char + char : char;
279
+ if (canOpen(src, i, delim)) {
280
+ const close = findClose(src, i + delim.length, delim);
281
+ if (close > i + delim.length) {
282
+ const format: MarkdownFormat = delim.length === 2 ? "bold" : "italic";
283
+ const children = parseInline(src.slice(i + delim.length, close), ctx);
284
+ if (ctx.allow.has(format)) {
285
+ out.push({ type: format === "bold" ? "strong" : "emphasis", children });
286
+ } else {
287
+ report(ctx, format);
288
+ appendText(out, delim);
289
+ appendAll(out, children);
290
+ appendText(out, delim);
291
+ }
292
+ i = close + delim.length;
293
+ continue;
294
+ }
295
+ }
296
+ appendText(out, delim);
297
+ i += delim.length;
298
+ continue;
299
+ }
300
+
301
+ appendText(out, char);
302
+ i++;
303
+ }
304
+ return out;
305
+ }
@@ -4,6 +4,8 @@
4
4
  // they are different windows; an in-memory pair when they share one (on-site
5
5
  // overlay). No framework imports.
6
6
 
7
+ import { MARKDOWN_FORMATS, type MarkdownFormat } from "./fields";
8
+ import type { InlineEdit, InlineEditableFields, InlineEditableMarkdown, InlineEditTarget } from "./inline-edit";
7
9
  import { parsePreviewHotkey, type PreviewHotkeyMessage } from "./preview-hotkeys";
8
10
 
9
11
  export const PREVIEW_CHANNEL_VERSION = 1 as const;
@@ -79,6 +81,23 @@ export type PreviewHighlightMessage = Envelope & {
79
81
  blockId: string | null;
80
82
  };
81
83
 
84
+ /** Holder → page: the block texts the page may edit inline. Also says the holder applies edits. */
85
+ export type PreviewEditableMessage = Envelope & {
86
+ type: "backmatter:editable";
87
+ fields: InlineEditableFields;
88
+ /** Which offered fields hold markdown, and the formatting each allows. */
89
+ markdown?: InlineEditableMarkdown;
90
+ };
91
+
92
+ /** Either way: inline edit mode is on or off. The holder sets it; the page reports changes. */
93
+ export type PreviewEditModeMessage = Envelope & { type: "backmatter:edit-mode"; on: boolean };
94
+
95
+ /** Page → holder: undo the last inline edit, or redo the last undone one. */
96
+ export type PreviewEditHistoryMessage = Envelope & { type: "backmatter:edit-history"; step: "undo" | "redo" };
97
+
98
+ /** Page → holder: the person finished editing one text on the page. */
99
+ export type PreviewEditMessage = Envelope & { type: "backmatter:edit" } & InlineEdit;
100
+
82
101
  export type PreviewChannelMessage =
83
102
  | PreviewHelloMessage
84
103
  | PreviewDocMessage
@@ -88,6 +107,10 @@ export type PreviewChannelMessage =
88
107
  | PreviewPointMessage
89
108
  | PreviewGrabMessage
90
109
  | PreviewHighlightMessage
110
+ | PreviewEditableMessage
111
+ | PreviewEditMessage
112
+ | PreviewEditModeMessage
113
+ | PreviewEditHistoryMessage
91
114
  | PreviewHotkeyMessage;
92
115
 
93
116
  export type PreviewTransport = {
@@ -160,6 +183,55 @@ function readGrabPlace(data: Record<string, unknown>): Pick<
160
183
  };
161
184
  }
162
185
 
186
+ const EDIT_TEXT_MAX = 20_000;
187
+
188
+ function readEditableFields(value: unknown): InlineEditableFields | null {
189
+ if (!isRecord(value) || Array.isArray(value)) return null;
190
+ const out: InlineEditableFields = {};
191
+ for (const [blockId, fields] of Object.entries(value)) {
192
+ if (!blockId || !isRecord(fields) || Array.isArray(fields)) continue;
193
+ const texts: Record<string, string> = {};
194
+ for (const [name, text] of Object.entries(fields)) {
195
+ if (GRAB_FIELD.test(name) && typeof text === "string" && text.length <= EDIT_TEXT_MAX) texts[name] = text;
196
+ }
197
+ out[blockId] = texts;
198
+ }
199
+ return out;
200
+ }
201
+
202
+ function readEditableMarkdown(value: unknown): InlineEditableMarkdown | undefined {
203
+ if (!isRecord(value) || Array.isArray(value)) return undefined;
204
+ const out: InlineEditableMarkdown = {};
205
+ for (const [blockId, fields] of Object.entries(value)) {
206
+ if (!blockId || !isRecord(fields) || Array.isArray(fields)) continue;
207
+ const allowed: Record<string, MarkdownFormat[]> = {};
208
+ for (const [name, allow] of Object.entries(fields)) {
209
+ if (!GRAB_FIELD.test(name) || !Array.isArray(allow)) continue;
210
+ if (!allow.every((format) => MARKDOWN_FORMATS.includes(format as MarkdownFormat))) continue;
211
+ allowed[name] = allow as MarkdownFormat[];
212
+ }
213
+ out[blockId] = allowed;
214
+ }
215
+ return out;
216
+ }
217
+
218
+ function readEditTarget(value: unknown): InlineEditTarget | null {
219
+ if (!isRecord(value)) return null;
220
+ if (value.kind === "field") {
221
+ if (typeof value.blockId !== "string" || !value.blockId || value.blockId.length > 80) return null;
222
+ if (typeof value.field !== "string" || !GRAB_FIELD.test(value.field)) return null;
223
+ return { kind: "field", blockId: value.blockId, field: value.field };
224
+ }
225
+ if (value.kind === "body") {
226
+ const { start, end } = value;
227
+ if (typeof start !== "number" || !Number.isInteger(start) || start < 0) return null;
228
+ if (typeof end !== "number" || !Number.isInteger(end) || end <= start) return null;
229
+ if (typeof value.hash !== "string" || !/^[0-9a-z]{1,8}$/.test(value.hash)) return null;
230
+ return { kind: "body", start, end, hash: value.hash };
231
+ }
232
+ return null;
233
+ }
234
+
163
235
  /** Parse a channel payload. Legacy hotkey messages (no `v`) still parse. */
164
236
  export function parsePreviewMessage(data: unknown): PreviewChannelMessage | null {
165
237
  const hotkey = parsePreviewHotkey(data);
@@ -238,6 +310,27 @@ export function parsePreviewMessage(data: unknown): PreviewChannelMessage | null
238
310
  }
239
311
  return { type: "backmatter:highlight", ...envelope, blockId: data.blockId };
240
312
  }
313
+ case "backmatter:editable": {
314
+ const fields = readEditableFields(data.fields);
315
+ if (!fields) return null;
316
+ const markdown = readEditableMarkdown(data.markdown);
317
+ return { type: "backmatter:editable", ...envelope, fields, ...(markdown ? { markdown } : {}) };
318
+ }
319
+ case "backmatter:edit-mode": {
320
+ if (typeof data.on !== "boolean") return null;
321
+ return { type: "backmatter:edit-mode", ...envelope, on: data.on };
322
+ }
323
+ case "backmatter:edit-history": {
324
+ if (data.step !== "undo" && data.step !== "redo") return null;
325
+ return { type: "backmatter:edit-history", ...envelope, step: data.step };
326
+ }
327
+ case "backmatter:edit": {
328
+ const target = readEditTarget(data.target);
329
+ if (!target) return null;
330
+ if (typeof data.from !== "string" || typeof data.to !== "string") return null;
331
+ if (data.from.length > EDIT_TEXT_MAX || data.to.length > EDIT_TEXT_MAX) return null;
332
+ return { type: "backmatter:edit", ...envelope, target, from: data.from, to: data.to };
333
+ }
241
334
  default:
242
335
  return null;
243
336
  }
@@ -4,6 +4,7 @@
4
4
  // through a renderer. SSE is the source until an editor attaches, and after
5
5
  // that only a tombstone (`raw: ""`) from SSE still wins.
6
6
 
7
+ import type { InlineEdit, InlineEditableFields, InlineEditableMarkdown } from "./inline-edit";
7
8
  import {
8
9
  normalizePointerQuote,
9
10
  samePreviewRef,
@@ -39,6 +40,10 @@ export type PreviewPageHandlers = {
39
40
  onNavigate?: (path: string) => void;
40
41
  onPoint?: (on: boolean) => void;
41
42
  onHighlight?: (blockId: string | null) => void;
43
+ /** The holder offers these block texts for inline editing. */
44
+ onEditable?: (fields: InlineEditableFields, markdown: InlineEditableMarkdown) => void;
45
+ /** The holder turned inline edit mode on or off. */
46
+ onEditMode?: (on: boolean) => void;
42
47
  };
43
48
 
44
49
  type Job = {
@@ -53,6 +58,12 @@ export type PreviewPageSession = {
53
58
  editorAttached(): boolean;
54
59
  grab(grab: Omit<PreviewGrabMessage, "type" | "v" | "ref">): void;
55
60
  point(on: boolean): void;
61
+ /** Send an inline edit to whoever holds the document. */
62
+ edit(edit: InlineEdit): void;
63
+ /** Tell the holder that edit mode changed on the page. */
64
+ editMode(on: boolean): void;
65
+ /** Ask the holder to undo its last inline edit, or redo the last undone one. */
66
+ editHistory(step: "undo" | "redo"): void;
56
67
  };
57
68
 
58
69
  /**
@@ -166,6 +177,12 @@ export function createPreviewPage(options: {
166
177
  case "backmatter:highlight":
167
178
  handlers.onHighlight?.(message.blockId);
168
179
  break;
180
+ case "backmatter:editable":
181
+ handlers.onEditable?.(message.fields, message.markdown ?? {});
182
+ break;
183
+ case "backmatter:edit-mode":
184
+ handlers.onEditMode?.(message.on);
185
+ break;
169
186
  default:
170
187
  break;
171
188
  }
@@ -210,6 +227,15 @@ export function createPreviewPage(options: {
210
227
  point(on) {
211
228
  send({ type: "backmatter:point", v: 1, ref: options.ref, on });
212
229
  },
230
+ edit(edit) {
231
+ send({ type: "backmatter:edit", v: 1, ref: options.ref, ...edit });
232
+ },
233
+ editMode(on) {
234
+ send({ type: "backmatter:edit-mode", v: 1, ref: options.ref, on });
235
+ },
236
+ editHistory(step) {
237
+ send({ type: "backmatter:edit-history", v: 1, ref: options.ref, step });
238
+ },
213
239
  close() {
214
240
  if (closed) return;
215
241
  closed = true;
@@ -241,6 +267,10 @@ export type PreviewEditorSession = {
241
267
  removed(): void;
242
268
  point(on: boolean): void;
243
269
  highlight(blockId: string | null): void;
270
+ /** Offer these block texts for inline editing. Send again whenever the document changes. */
271
+ editable(fields: InlineEditableFields, markdown?: InlineEditableMarkdown): void;
272
+ /** Turn inline edit mode on or off in the page. */
273
+ editMode(on: boolean): void;
244
274
  close(): void;
245
275
  };
246
276
 
@@ -255,6 +285,9 @@ export function createPreviewEditor(options: {
255
285
  onGrab?: (grab: PreviewGrabMessage) => void;
256
286
  onPoint?: (on: boolean) => void;
257
287
  onStatus?: (status: { seq: number; state: "rendered" | "error"; message?: string }) => void;
288
+ onEdit?: (edit: InlineEdit) => void;
289
+ onEditMode?: (on: boolean) => void;
290
+ onEditHistory?: (step: "undo" | "redo") => void;
258
291
  schedule?: PreviewSchedule;
259
292
  }): PreviewEditorSession {
260
293
  const schedule = options.schedule ?? animationFrameSchedule();
@@ -297,6 +330,11 @@ export function createPreviewEditor(options: {
297
330
  }
298
331
  if (message.type === "backmatter:grab") options.onGrab?.(message);
299
332
  if (message.type === "backmatter:point") options.onPoint?.(message.on);
333
+ if (message.type === "backmatter:edit-mode") options.onEditMode?.(message.on);
334
+ if (message.type === "backmatter:edit-history") options.onEditHistory?.(message.step);
335
+ if (message.type === "backmatter:edit") {
336
+ options.onEdit?.({ target: message.target, from: message.from, to: message.to });
337
+ }
300
338
  });
301
339
 
302
340
  return {
@@ -322,6 +360,20 @@ export function createPreviewEditor(options: {
322
360
  if (closed) return;
323
361
  options.transport.send({ type: "backmatter:highlight", v: 1, ref: currentRef(), blockId });
324
362
  },
363
+ editMode(on) {
364
+ if (closed) return;
365
+ options.transport.send({ type: "backmatter:edit-mode", v: 1, ref: currentRef(), on });
366
+ },
367
+ editable(fields, markdown) {
368
+ if (closed) return;
369
+ options.transport.send({
370
+ type: "backmatter:editable",
371
+ v: 1,
372
+ ref: currentRef(),
373
+ fields,
374
+ ...(markdown && Object.keys(markdown).length > 0 ? { markdown } : {}),
375
+ });
376
+ },
325
377
  close() {
326
378
  if (closed) return;
327
379
  closed = true;
package/src/preview.ts CHANGED
@@ -309,6 +309,9 @@ export type {
309
309
  PreviewChannelMessage,
310
310
  PreviewChannelRef,
311
311
  PreviewDocMessage,
312
+ PreviewEditableMessage,
313
+ PreviewEditMessage,
314
+ PreviewEditModeMessage,
312
315
  PreviewGrabMessage,
313
316
  PreviewHelloMessage,
314
317
  PreviewHighlightMessage,
@@ -329,6 +332,28 @@ export type {
329
332
  PointerRoute,
330
333
  RoutedGrab,
331
334
  } from "./preview-pointer";
335
+ export {
336
+ applyInlineEdit,
337
+ bodyRangeHash,
338
+ escapeBlockStart,
339
+ escapeInlineMarkdown,
340
+ escapeInlineText,
341
+ inlineEditableFields,
342
+ inlineEditableMarkdown,
343
+ inlineMarkdownText,
344
+ invertInlineEdit,
345
+ matchInlineField,
346
+ } from "./inline-edit";
347
+ export type {
348
+ InlineEdit,
349
+ InlineEditableFields,
350
+ InlineEditableMarkdown,
351
+ InlineEditDoc,
352
+ InlineEditResult,
353
+ InlineEditTarget,
354
+ InlineMarkdownFields,
355
+ InlineTextFields,
356
+ } from "./inline-edit";
332
357
  export { createPreviewEditor, createPreviewPage } from "./preview-client";
333
358
  export type {
334
359
  PreviewEditorSession,
package/src/zod.ts CHANGED
@@ -24,6 +24,7 @@ export function expectedTypeFor(
24
24
  case "object":
25
25
  return "object";
26
26
  case "text":
27
+ case "markdown":
27
28
  case "image":
28
29
  case "media":
29
30
  case "relation":
@@ -57,6 +58,7 @@ export function exampleValueFor(kind: FieldKind): unknown {
57
58
  case "link":
58
59
  return "/page";
59
60
  case "text":
61
+ case "markdown":
60
62
  return "";
61
63
  default: {
62
64
  const _exhaustive: never = kind;