@backmatter/core 0.0.54 → 0.0.56

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.54",
3
+ "version": "0.0.56",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -0,0 +1,309 @@
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
+ /**
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
+ */
17
+ | { kind: "field"; blockId: string; field: string }
18
+ /**
19
+ * The inline content of one MDX paragraph or heading, by character offset.
20
+ * `hash` is `bodyRangeHash` of the source in that range when the page rendered it.
21
+ */
22
+ | { kind: "body"; start: number; end: number; hash: string };
23
+
24
+ export type InlineEdit = {
25
+ target: InlineEditTarget;
26
+ /** The stored text the page showed when editing began. */
27
+ from: string;
28
+ /** What the person typed. For a body range, the markdown the page wrote from it. */
29
+ to: string;
30
+ /**
31
+ * Store `to` as it is, line breaks included. Only a holder sets this, for an
32
+ * undo that puts back the source an edit replaced; a page never sends it.
33
+ */
34
+ exact?: true;
35
+ };
36
+
37
+ /** Texts a page may edit inline: block id → field path → stored text. */
38
+ export type InlineEditableFields = Record<string, Record<string, string>>;
39
+
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
+ */
44
+ export type InlineTextFields = Record<string, readonly string[]>;
45
+
46
+ /** Markdown fields of each block type, as path templates, with the formatting each allows. */
47
+ export type InlineMarkdownFields = Record<string, Record<string, readonly MarkdownFormat[]>>;
48
+
49
+ /** Markdown texts a page may edit inline: block id → field path → the formatting it allows. */
50
+ export type InlineEditableMarkdown = Record<string, Record<string, MarkdownFormat[]>>;
51
+
52
+ export type InlineEditDoc = { frontmatter: Record<string, unknown>; body: string };
53
+
54
+ export type InlineEditResult =
55
+ | { ok: true; doc: InlineEditDoc }
56
+ | { ok: false; reason: "stale" | "not_editable" | "empty" };
57
+
58
+ type BlockLike = { id?: unknown; type?: unknown; props?: unknown };
59
+
60
+ function asBlocks(value: unknown): BlockLike[] {
61
+ return Array.isArray(value) ? (value.filter((b) => b && typeof b === "object") as BlockLike[]) : [];
62
+ }
63
+
64
+ /** The id the page marks a block with: its id, or its index (as `renderPage` does). */
65
+ function blockKey(block: BlockLike, index: number): string {
66
+ return typeof block.id === "string" && block.id ? block.id : String(index);
67
+ }
68
+
69
+ function propsOf(block: BlockLike): Record<string, unknown> {
70
+ return block.props && typeof block.props === "object" && !Array.isArray(block.props)
71
+ ? (block.props as Record<string, unknown>)
72
+ : {};
73
+ }
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
+
126
+ function flatten(nodes: MarkdownInline[]): string {
127
+ return nodes
128
+ .map((node) => (node.type === "text" ? node.value : node.type === "break" ? "\n" : flatten(node.children)))
129
+ .join("");
130
+ }
131
+
132
+ /**
133
+ * The text a markdown value shows when it renders as one paragraph, line breaks
134
+ * as `\n`. Null for anything else (headings, lists, several paragraphs): those
135
+ * are edited in the form, not on the page.
136
+ */
137
+ export function inlineMarkdownText(source: string, allow: readonly MarkdownFormat[]): string | null {
138
+ const { blocks } = parseMarkdownField(source, allow);
139
+ const only = blocks[0];
140
+ if (blocks.length !== 1 || only?.type !== "paragraph") return null;
141
+ return flatten(only.children);
142
+ }
143
+
144
+ function editableMarkdown(
145
+ blocks: unknown,
146
+ markdownFields: InlineMarkdownFields,
147
+ each: (key: string, name: string, value: string, allow: readonly MarkdownFormat[]) => void,
148
+ ) {
149
+ asBlocks(blocks).forEach((block, index) => {
150
+ if (typeof block.type !== "string") return;
151
+ const props = propsOf(block);
152
+ for (const [template, allow] of Object.entries(markdownFields[block.type] ?? {})) {
153
+ expand(template, props, (path, value) => {
154
+ if (typeof value !== "string" || !value.trim() || inlineMarkdownText(value, allow) === null) return;
155
+ each(blockKey(block, index), path, value, allow);
156
+ });
157
+ }
158
+ });
159
+ }
160
+
161
+ export function inlineEditableFields(
162
+ blocks: unknown,
163
+ textFields: InlineTextFields,
164
+ markdownFields: InlineMarkdownFields = {},
165
+ ): InlineEditableFields {
166
+ const out: InlineEditableFields = {};
167
+ asBlocks(blocks).forEach((block, index) => {
168
+ if (typeof block.type !== "string") return;
169
+ const names = textFields[block.type] ?? [];
170
+ const props = propsOf(block);
171
+ const fields: Record<string, string> = {};
172
+ for (const template of names) {
173
+ expand(template, props, (path, value) => {
174
+ if (typeof value === "string" && value.trim()) fields[path] = value;
175
+ });
176
+ }
177
+ if (Object.keys(fields).length > 0) out[blockKey(block, index)] = fields;
178
+ });
179
+ editableMarkdown(blocks, markdownFields, (key, name, value) => {
180
+ out[key] = { ...out[key], [name]: value };
181
+ });
182
+ return out;
183
+ }
184
+
185
+ /** Which offered fields hold markdown, and the formatting each allows. */
186
+ export function inlineEditableMarkdown(blocks: unknown, markdownFields: InlineMarkdownFields): InlineEditableMarkdown {
187
+ const out: InlineEditableMarkdown = {};
188
+ editableMarkdown(blocks, markdownFields, (key, name, _value, allow) => {
189
+ out[key] = { ...out[key], [name]: [...allow] };
190
+ });
191
+ return out;
192
+ }
193
+
194
+ function squash(text: string): string {
195
+ return text.replace(/\s+/g, " ").trim();
196
+ }
197
+
198
+ /** The one field whose stored text the page rendered unchanged, or null. */
199
+ export function matchInlineField(fields: Record<string, string>, rendered: string): string | null {
200
+ const wanted = squash(rendered);
201
+ if (!wanted) return null;
202
+ const hits = Object.keys(fields).filter((name) => squash(fields[name]!) === wanted);
203
+ return hits.length === 1 ? hits[0]! : null;
204
+ }
205
+
206
+ /** Short FNV-1a hash of a body range's source, so a holder can tell the page saw the same text. */
207
+ export function bodyRangeHash(text: string): string {
208
+ let hash = 0x811c9dc5;
209
+ for (let i = 0; i < text.length; i += 1) {
210
+ hash ^= text.charCodeAt(i);
211
+ hash = Math.imul(hash, 0x01000193) >>> 0;
212
+ }
213
+ return hash.toString(36);
214
+ }
215
+
216
+ /** Escape what would turn typed text into inline MDX markup. */
217
+ export function escapeInlineText(text: string): string {
218
+ return text.replace(/[\\`*_~[<{]/g, (ch) => `\\${ch}`);
219
+ }
220
+
221
+ /** Escape a marker at the start of a line that would turn it into another block. */
222
+ export function escapeBlockStart(markdown: string): string {
223
+ return markdown.replace(/^(\s*)([#>+|-])/, "$1\\$2").replace(/^(\s*\d+)([.)])/, "$1\\$2");
224
+ }
225
+
226
+ /** Escape typed text so it stays one plain paragraph of MDX. */
227
+ export function escapeInlineMarkdown(text: string): string {
228
+ return escapeBlockStart(escapeInlineText(text));
229
+ }
230
+
231
+ function oneLine(text: string): string {
232
+ return text.replace(/\s*\n\s*/g, " ");
233
+ }
234
+
235
+ /** Markdown for one paragraph: single line breaks stay, blank lines go. */
236
+ function oneParagraph(text: string): string {
237
+ return text
238
+ .split("\n")
239
+ .map((line) => line.trim())
240
+ .filter(Boolean)
241
+ .join("\n");
242
+ }
243
+
244
+ export function applyInlineEdit(
245
+ doc: InlineEditDoc,
246
+ edit: InlineEdit,
247
+ options: { blocksField: string; textFields: InlineTextFields; markdownFields?: InlineMarkdownFields },
248
+ ): InlineEditResult {
249
+ const { target } = edit;
250
+ if (target.kind === "body") {
251
+ if (bodyRangeHash(doc.body.slice(target.start, target.end)) !== target.hash) {
252
+ return { ok: false, reason: "stale" };
253
+ }
254
+ const markdown = edit.exact ? edit.to : oneLine(edit.to).trim();
255
+ if (!markdown.trim()) return { ok: false, reason: "empty" };
256
+ const body = doc.body.slice(0, target.start) + markdown + doc.body.slice(target.end);
257
+ return { ok: true, doc: { frontmatter: doc.frontmatter, body } };
258
+ }
259
+
260
+ const blocks = asBlocks(doc.frontmatter[options.blocksField]);
261
+ const index = blocks.findIndex((block, i) => blockKey(block, i) === target.blockId);
262
+ const block = blocks[index];
263
+ if (!block || typeof block.type !== "string") return { ok: false, reason: "stale" };
264
+ const markdown = Object.keys(options.markdownFields?.[block.type] ?? {}).some((t) => fits(t, target.field));
265
+ if (!markdown && !(options.textFields[block.type] ?? []).some((t) => fits(t, target.field))) {
266
+ return { ok: false, reason: "not_editable" };
267
+ }
268
+ const props = propsOf(block);
269
+ // An item reordered, removed, or edited in the form since the page rendered it is refused here.
270
+ if (readPath(props, target.field) !== edit.from) return { ok: false, reason: "stale" };
271
+ const next = [...(doc.frontmatter[options.blocksField] as unknown[])];
272
+ const rawIndex = (doc.frontmatter[options.blocksField] as unknown[]).indexOf(block);
273
+ const value = edit.exact ? edit.to : markdown ? oneParagraph(edit.to) : oneLine(edit.to);
274
+ next[rawIndex] = { ...block, props: writePath(props, target.field.split("."), value) };
275
+ return {
276
+ ok: true,
277
+ doc: { frontmatter: { ...doc.frontmatter, [options.blocksField]: next }, body: doc.body },
278
+ };
279
+ }
280
+
281
+ /**
282
+ * The edit that takes `doc` back after `edit` is applied to it, or null when
283
+ * `edit` would not apply. Inverting the inverse gives the edit again (a redo).
284
+ */
285
+ export function invertInlineEdit(
286
+ doc: InlineEditDoc,
287
+ edit: InlineEdit,
288
+ options: { blocksField: string; textFields: InlineTextFields; markdownFields?: InlineMarkdownFields },
289
+ ): InlineEdit | null {
290
+ const applied = applyInlineEdit(doc, edit, options);
291
+ if (!applied.ok) return null;
292
+ const { target } = edit;
293
+ if (target.kind === "body") {
294
+ const before = doc.body.slice(target.start, target.end);
295
+ const written = applied.doc.body.slice(target.start, applied.doc.body.length - (doc.body.length - target.end));
296
+ return {
297
+ target: { kind: "body", start: target.start, end: target.start + written.length, hash: bodyRangeHash(written) },
298
+ from: written,
299
+ to: before,
300
+ exact: true,
301
+ };
302
+ }
303
+ const written = asBlocks(applied.doc.frontmatter[options.blocksField]).find(
304
+ (block, i) => blockKey(block, i) === target.blockId,
305
+ );
306
+ const now = written ? readPath(propsOf(written), target.field) : undefined;
307
+ if (typeof now !== "string") return null;
308
+ return { target, from: now, to: edit.from, exact: true };
309
+ }
@@ -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,
@@ -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);