@backmatter/next 0.0.67 → 0.0.69

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/next",
3
- "version": "0.0.67",
3
+ "version": "0.0.69",
4
4
  "description": "Experimental Next.js adapter for Backmatter. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -48,10 +48,10 @@
48
48
  "test": "bun test"
49
49
  },
50
50
  "dependencies": {
51
- "@backmatter/core": "^0.0.54",
51
+ "@backmatter/core": "^0.0.55",
52
52
  "@mdx-js/mdx": "^3.1.1",
53
53
  "remark-gfm": "^4.0.1",
54
- "@backmatter/studio": "^0.0.44"
54
+ "@backmatter/studio": "^0.0.46"
55
55
  },
56
56
  "peerDependencies": {
57
57
  "next": ">=16.3.0",
package/src/cms-proxy.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import { PREVIEW_SESSION_COOKIE, readPreviewSession } from "@backmatter/core";
5
5
  import type { BackmatterClient } from "@backmatter/core/node/create-backmatter";
6
6
 
7
- const DOC = "/workspaces/[^/]+/docs/[^/]+/[^/]+/[^/]+";
7
+ const DOC = "/workspaces/[^/]+/docs/[^/]+/[^/]+";
8
8
 
9
9
  const WS = "/workspaces/[^/]+";
10
10
 
package/src/layout-doc.ts CHANGED
@@ -18,6 +18,8 @@ export type LayoutDocOptions = {
18
18
  /** `sources/{type}.ts` loaders, usually the generated `sources`. Resolved by the caller. */
19
19
  sources?: Record<string, SourceDef>;
20
20
  render?: (doc: BackmatterDoc, body: ReactNode) => ReactNode;
21
+ /** Preview render: mark MDX text with its body range so the page can edit it inline. */
22
+ preview?: boolean;
21
23
  };
22
24
 
23
25
  export async function renderLayoutDoc(
@@ -29,7 +31,7 @@ export async function renderLayoutDoc(
29
31
  const isPage = Boolean(model && modelFormat(model) === "page");
30
32
  const rendered = isPage
31
33
  ? await renderPage(doc, options.blocks, options.fallbacks, data)
32
- : await renderDoc(doc, { components: options.components });
34
+ : await renderDoc(doc, { components: options.components, bodyRanges: options.preview });
33
35
  const layout = options.layouts?.[doc.type];
34
36
  const laidOut = layout ? layout(doc, rendered, data) : rendered;
35
37
  if (options.render) return options.render(doc, laidOut);
@@ -7,6 +7,7 @@ import {
7
7
  } from "react";
8
8
  import * as runtime from "react/jsx-runtime";
9
9
  import remarkGfm from "remark-gfm";
10
+ import { bodyRangeHash } from "@backmatter/core/preview";
10
11
 
11
12
  export type MdxComponents = Record<string, ComponentType<any>>;
12
13
 
@@ -29,16 +30,78 @@ function mdxComponentsWithFallback(source: string, components?: MdxComponents):
29
30
  return provided;
30
31
  }
31
32
 
33
+ type MdastNode = {
34
+ type: string;
35
+ value?: string;
36
+ spread?: boolean | null;
37
+ children?: MdastNode[];
38
+ position?: { start?: { offset?: number }; end?: { offset?: number } };
39
+ data?: { hProperties?: Record<string, unknown> } & Record<string, unknown>;
40
+ };
41
+
42
+ /** Attribute on a rendered element: `start:end:hash`, the body range of its inline source. */
43
+ export const BODY_RANGE_ATTRIBUTE = "data-backmatter-body";
44
+
45
+ /** Inline nodes the page can edit and write back as markdown. */
46
+ const EDITABLE_INLINE = new Set(["text", "strong", "emphasis", "delete", "inlineCode", "link", "break"]);
47
+
48
+ function editableInline(node: MdastNode): boolean {
49
+ if (!EDITABLE_INLINE.has(node.type)) return false;
50
+ return (node.children ?? []).every(editableInline);
51
+ }
52
+
53
+ /** The body range of a paragraph's or heading's inline content, when the page can edit all of it. */
54
+ function inlineRange(node: MdastNode, source: string): string | null {
55
+ if (node.type !== "paragraph" && node.type !== "heading") return null;
56
+ const kids = node.children ?? [];
57
+ if (kids.length === 0 || !kids.every(editableInline)) return null;
58
+ const start = kids[0]!.position?.start?.offset;
59
+ const end = kids[kids.length - 1]!.position?.end?.offset;
60
+ if (typeof start !== "number" || typeof end !== "number" || end <= start) return null;
61
+ const text = source.slice(start, end);
62
+ return `${start}:${end}:${bodyRangeHash(text)}`;
63
+ }
64
+
65
+ function markRange(node: MdastNode, range: string) {
66
+ node.data = { ...node.data, hProperties: { ...node.data?.hProperties, [BODY_RANGE_ATTRIBUTE]: range } };
67
+ }
68
+
69
+ /**
70
+ * Preview only. Marks each paragraph and heading the page can edit in place
71
+ * with the range of its inline source in the body. A tight list item
72
+ * renders without its paragraph, so the item carries the mark.
73
+ */
74
+ function remarkBodyRanges() {
75
+ return (tree: MdastNode, file: { value: unknown }) => {
76
+ const source = String(file.value);
77
+ const walk = (node: MdastNode) => {
78
+ if (node.type === "listItem" && !node.spread && node.children?.length === 1) {
79
+ const range = inlineRange(node.children[0]!, source);
80
+ if (range) markRange(node, range);
81
+ return;
82
+ }
83
+ const range = inlineRange(node, source);
84
+ if (range) {
85
+ markRange(node, range);
86
+ return;
87
+ }
88
+ node.children?.forEach(walk);
89
+ };
90
+ walk(tree);
91
+ };
92
+ }
93
+
32
94
  export async function compileMdx(
33
95
  source: string,
34
96
  components?: MdxComponents,
97
+ options?: { bodyRanges?: boolean },
35
98
  ): Promise<ReactNode> {
36
99
  if (!source.trim()) return null;
37
100
 
38
101
  try {
39
102
  const { default: Content } = await evaluate(source, {
40
103
  ...runtime,
41
- remarkPlugins: [remarkGfm],
104
+ remarkPlugins: options?.bodyRanges ? [remarkGfm, remarkBodyRanges] : [remarkGfm],
42
105
  baseUrl: import.meta.url,
43
106
  });
44
107
  return createElement(Content, { components: mdxComponentsWithFallback(source, components) });
@@ -50,7 +113,7 @@ export async function compileMdx(
50
113
 
51
114
  export async function renderDoc(
52
115
  doc: { body: string },
53
- options?: { components?: MdxComponents },
116
+ options?: { components?: MdxComponents; bodyRanges?: boolean },
54
117
  ): Promise<ReactNode> {
55
- return compileMdx(doc.body, options?.components);
118
+ return compileMdx(doc.body, options?.components, { bodyRanges: options?.bodyRanges });
56
119
  }
@@ -1,7 +1,7 @@
1
1
  // packages/next/src/preview-refresh.tsx
2
2
  "use client";
3
3
 
4
- import { useCallback, useEffect, useState, startTransition, type ReactNode } from "react";
4
+ import { useCallback, useEffect, useRef, useState, startTransition, type ReactNode } from "react";
5
5
  import { useRouter } from "next/navigation";
6
6
  import { PREVIEW_CHECKOUT_QUERY } from "@backmatter/core";
7
7
  import {
@@ -13,6 +13,7 @@ import {
13
13
  type PreviewTransport,
14
14
  } from "@backmatter/core/preview";
15
15
  import { POINTER_ARM_EVENT } from "@backmatter/studio/src/chat/pointer-arm";
16
+ import { installInlineEdit } from "@backmatter/studio/src/inline-edit-page";
16
17
  import { installPreviewPointer } from "@backmatter/studio/src/install-preview-pointer";
17
18
  import { registerPreviewPointerHost } from "@backmatter/studio/src/preview-pointer-host";
18
19
  import { findPointedElement, highlightPointedElement } from "@backmatter/studio/src/site-pointer";
@@ -152,6 +153,8 @@ export function PreviewClient({
152
153
  const [removed, setRemoved] = useState(false);
153
154
  const [error, setError] = useState<string | null>(null);
154
155
  const originsKey = dashboardOrigins.join("\0");
156
+ // A render that arrives while someone edits text in place waits until they finish.
157
+ const heldNode = useRef<{ value: ReactNode } | null>(null);
155
158
 
156
159
  useEffect(() => {
157
160
  const ref: PreviewChannelRef = {
@@ -214,10 +217,26 @@ export function PreviewClient({
214
217
  window.dispatchEvent(new CustomEvent(POINTER_ARM_EVENT, { detail: { on: false } }));
215
218
  },
216
219
  });
220
+ const inlineEdit = installInlineEdit(document, {
221
+ ignore: (target) =>
222
+ target.closest("[data-backmatter-devbar], [data-backmatter-panel]") !== null,
223
+ onEdit: (edit) => session.edit(edit),
224
+ onModeChange: (on) => session?.editMode(on),
225
+ onHistory: (step) => session.editHistory(step),
226
+ // The document's own content. The host's header and footer links keep navigating.
227
+ content: "[data-backmatter-preview]",
228
+ onIdle: () => {
229
+ const held = heldNode.current;
230
+ heldNode.current = null;
231
+ // In a transition, so a render that suspends keeps this page up instead
232
+ // of the Suspense fallback (the page as it first loaded).
233
+ if (held) startTransition(() => setNode(held.value));
234
+ },
235
+ });
217
236
  session = createPreviewPage({
218
237
  ref,
219
238
  transport,
220
- capabilities: ["point"],
239
+ capabilities: ["point", "inline-edit"],
221
240
  subscribeSse: (onEvent) => subscribeDocStream(ref, onEvent),
222
241
  renderer: async (_ref, doc) => {
223
242
  const result = await renderPreview(ref, doc, checkoutToken);
@@ -228,8 +247,15 @@ export function PreviewClient({
228
247
  onApplied: (_doc, value) => {
229
248
  setError(null);
230
249
  setRemoved(false);
231
- setNode(value as ReactNode);
250
+ if (inlineEdit.editing()) heldNode.current = { value: value as ReactNode };
251
+ else {
252
+ startTransition(() => setNode(value as ReactNode));
253
+ // The stand-in for a formatted edit goes once React has painted the new render.
254
+ requestAnimationFrame(() => requestAnimationFrame(() => inlineEdit.rendered()));
255
+ }
232
256
  },
257
+ onEditable: (fields, markdown) => inlineEdit.setEditable(fields, markdown),
258
+ onEditMode: (on) => inlineEdit.setOn(on),
233
259
  onError: (message) => setError(message),
234
260
  onRemoved: () => {
235
261
  setRemoved(true);
@@ -266,6 +292,7 @@ export function PreviewClient({
266
292
  unsubscribeTree();
267
293
  stopHost();
268
294
  previewPointer.dispose();
295
+ inlineEdit.dispose();
269
296
  session.close();
270
297
  windowTransport?.close();
271
298
  };
@@ -171,7 +171,7 @@ export function createRenderPreview(
171
171
  body: doc.body,
172
172
  raw: doc.body,
173
173
  },
174
- { ...options, models: cms.models },
174
+ { ...options, models: cms.models, preview: true },
175
175
  data,
176
176
  ),
177
177
  );
package/src/routes.ts CHANGED
@@ -288,6 +288,7 @@ export function createCatchAll<Models extends readonly ModelDef[]>(
288
288
  layouts: options.layouts,
289
289
  sources: options.sources,
290
290
  render: options.render,
291
+ preview: preview.enabled,
291
292
  },
292
293
  data,
293
294
  ),
@@ -10,6 +10,7 @@ import studioPkg from "@backmatter/studio/package.json";
10
10
  import { SiteWidget } from "@backmatter/studio/widget";
11
11
  import { markerCookie } from "./gate";
12
12
  import { clearHeldPreview } from "./preview-hold";
13
+ import { siteEditorTransport } from "./site-channel";
13
14
  import { subscribeSiteDoc } from "./site-doc-bridge";
14
15
  import { readSiteDoc, sameSiteDoc, type SiteDocRef } from "./site-doc";
15
16
 
@@ -147,6 +148,7 @@ export function SiteChrome({
147
148
  version={studioPkg.version}
148
149
  dashboardHref={dashboardUrl}
149
150
  onSignOut={leave}
151
+ previewTransport={siteEditorTransport()}
150
152
  />
151
153
  );
152
154
  }