@backmatter/next 0.0.52 → 0.0.54

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.52",
3
+ "version": "0.0.54",
4
4
  "description": "Experimental Next.js adapter for Backmatter. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -47,10 +47,10 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@backmatter/core": "^0.0.41",
50
+ "@backmatter/core": "^0.0.42",
51
51
  "@mdx-js/mdx": "^3.1.1",
52
52
  "remark-gfm": "^4.0.1",
53
- "@backmatter/studio": "^0.0.29"
53
+ "@backmatter/studio": "^0.0.31"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "next": ">=16.3.0",
@@ -0,0 +1,175 @@
1
+ // packages/next/src/block-gallery-client.tsx
2
+ "use client";
3
+
4
+ // Client side of the block gallery. The shell covers the host's layout (its
5
+ // header, footer and dev bar) with a scrolling panel, so only blocks show
6
+ // while the site's CSS still applies. It takes live props from Studio and
7
+ // reports which example the editor wants to open. Each block is boxed so a
8
+ // fixed or full-height block stays in its own frame, and a block that throws
9
+ // shows a note instead of breaking the page.
10
+ import { Component, useEffect, useState, startTransition, type ReactNode } from "react";
11
+ import { useRouter } from "next/navigation";
12
+ import {
13
+ BLOCK_GALLERY_OPEN_MESSAGE,
14
+ blockGalleryPath,
15
+ isBlockGalleryPropsMessage,
16
+ readBlockGalleryQuery,
17
+ } from "@backmatter/core";
18
+
19
+ function referrerOrigin(): string {
20
+ try {
21
+ return document.referrer ? new URL(document.referrer).origin : "";
22
+ } catch {
23
+ return "";
24
+ }
25
+ }
26
+
27
+ function postToStudio(message: unknown) {
28
+ if (window.parent === window) return;
29
+ window.parent.postMessage(message, referrerOrigin() || "*");
30
+ }
31
+
32
+ export function BlockGalleryShell({
33
+ single,
34
+ dashboardOrigins,
35
+ children,
36
+ }: {
37
+ single: boolean;
38
+ dashboardOrigins: string[];
39
+ children?: ReactNode;
40
+ }) {
41
+ const router = useRouter();
42
+ const [background, setBackground] = useState("#fff");
43
+
44
+ useEffect(() => {
45
+ const color = getComputedStyle(document.body).backgroundColor;
46
+ if (color && color !== "rgba(0, 0, 0, 0)" && color !== "transparent") setBackground(color);
47
+ }, []);
48
+
49
+ useEffect(() => {
50
+ if (!single) return;
51
+ const allowed = new Set([window.location.origin, referrerOrigin(), ...dashboardOrigins]);
52
+ const onMessage = (event: MessageEvent) => {
53
+ if (!allowed.has(event.origin) || !isBlockGalleryPropsMessage(event.data)) return;
54
+ const query = readBlockGalleryQuery(new URLSearchParams(window.location.search));
55
+ if (query.blocks.length !== 1 || query.example === undefined) return;
56
+ // Keep the rest of the query (the checkout token, for one).
57
+ const next = new URL(blockGalleryPath({ ...query, props: event.data.props }), window.location.origin);
58
+ for (const [key, value] of new URLSearchParams(window.location.search)) {
59
+ if (!next.searchParams.has(key)) next.searchParams.set(key, value);
60
+ }
61
+ const href = `${next.pathname}${next.search}`;
62
+ startTransition(() => router.replace(href, { scroll: false }));
63
+ };
64
+ window.addEventListener("message", onMessage);
65
+ return () => window.removeEventListener("message", onMessage);
66
+ }, [single, dashboardOrigins, router]);
67
+
68
+ return (
69
+ <div
70
+ data-backmatter-block-gallery=""
71
+ style={{
72
+ position: "fixed",
73
+ inset: 0,
74
+ zIndex: 2147483000,
75
+ overflowY: "auto",
76
+ overscrollBehavior: "contain",
77
+ background,
78
+ }}
79
+ >
80
+ {children}
81
+ </div>
82
+ );
83
+ }
84
+
85
+ class BlockBoundary extends Component<{ block: string; children?: ReactNode }, { failed: boolean }> {
86
+ state = { failed: false };
87
+ static getDerivedStateFromError() {
88
+ return { failed: true };
89
+ }
90
+ render() {
91
+ if (!this.state.failed) return this.props.children;
92
+ return <Note>{`${this.props.block} could not render with these props.`}</Note>;
93
+ }
94
+ }
95
+
96
+ function Note({ children }: { children: ReactNode }) {
97
+ return (
98
+ <p
99
+ style={{
100
+ margin: 0,
101
+ padding: "32px 24px",
102
+ font: "13px/1.4 system-ui, sans-serif",
103
+ color: "#71717a",
104
+ textAlign: "center",
105
+ }}
106
+ >
107
+ {children}
108
+ </p>
109
+ );
110
+ }
111
+
112
+ const bar: React.CSSProperties = {
113
+ display: "flex",
114
+ alignItems: "center",
115
+ justifyContent: "space-between",
116
+ gap: 12,
117
+ padding: "10px 16px",
118
+ borderTop: "1px solid rgba(24,24,27,0.1)",
119
+ borderBottom: "1px solid rgba(24,24,27,0.1)",
120
+ background: "#fafafa",
121
+ color: "#18181b",
122
+ font: "500 13px/1.3 system-ui, sans-serif",
123
+ };
124
+
125
+ export function BlockGalleryItem({
126
+ block,
127
+ example,
128
+ exampleName,
129
+ single,
130
+ missing,
131
+ children,
132
+ }: {
133
+ block: string;
134
+ example: number;
135
+ exampleName: string;
136
+ single: boolean;
137
+ missing?: boolean;
138
+ children?: ReactNode;
139
+ }) {
140
+ return (
141
+ <section data-backmatter-gallery-block={block} data-backmatter-gallery-example={example}>
142
+ {single ? null : (
143
+ <div style={bar}>
144
+ <span>
145
+ {block}
146
+ <span style={{ color: "#71717a", fontWeight: 400 }}>{` · ${exampleName}`}</span>
147
+ </span>
148
+ <button
149
+ type="button"
150
+ onClick={() => postToStudio({ type: BLOCK_GALLERY_OPEN_MESSAGE, block, example })}
151
+ style={{
152
+ appearance: "none",
153
+ border: "1px solid rgba(24,24,27,0.15)",
154
+ borderRadius: 6,
155
+ background: "#fff",
156
+ color: "inherit",
157
+ font: "inherit",
158
+ padding: "4px 10px",
159
+ cursor: "pointer",
160
+ }}
161
+ >
162
+ Edit props
163
+ </button>
164
+ </div>
165
+ )}
166
+ <div style={{ position: "relative", transform: "translateZ(0)", contain: "paint" }}>
167
+ {missing ? (
168
+ <Note>{`No block named ${block} on this site.`}</Note>
169
+ ) : (
170
+ <BlockBoundary block={block}>{children}</BlockBoundary>
171
+ )}
172
+ </div>
173
+ </section>
174
+ );
175
+ }
@@ -0,0 +1,108 @@
1
+ // packages/next/src/block-gallery.ts
2
+ // Server side of the block gallery (`/_backmatter/blocks`): load each block
3
+ // module through the host's loaders, read the examples its definition
4
+ // declares, and render one component per example. Nothing here reads content.
5
+ import { createElement, type ComponentType, type ReactNode } from "react";
6
+ import {
7
+ imageUrlFromUnknown,
8
+ placeholderBlockProps,
9
+ type BlockExample,
10
+ type BlockGalleryQuery,
11
+ } from "@backmatter/core";
12
+ import {
13
+ asBlockLoader,
14
+ resolveBlockComponent,
15
+ type BlockComponents,
16
+ type BlockModule,
17
+ } from "./page-render";
18
+ import { BlockGalleryItem, BlockGalleryShell } from "./block-gallery-client";
19
+
20
+ export type GalleryEntry = {
21
+ block: string;
22
+ /** Index into the block's examples (0 for the placeholder). */
23
+ example: number;
24
+ exampleName: string;
25
+ /** The block rendered with the example's props; null when the block is unknown. */
26
+ element: ReactNode;
27
+ };
28
+
29
+ type DefinitionLike = {
30
+ fields?: Record<string, { kind: string; options?: readonly string[]; min?: number }>;
31
+ examples?: readonly BlockExample[];
32
+ };
33
+
34
+ function definitionOf(mod: BlockModule): DefinitionLike {
35
+ const def = mod.default;
36
+ return def && typeof def === "object" ? (def as DefinitionLike) : {};
37
+ }
38
+
39
+ function examplesOf(def: DefinitionLike): BlockExample[] {
40
+ const examples = Array.isArray(def.examples) ? def.examples : [];
41
+ if (examples.length > 0) return [...examples];
42
+ return [{ name: "Placeholder", props: placeholderBlockProps(def.fields ?? {}) }];
43
+ }
44
+
45
+ function renderBlock(Cmp: ComponentType<any>, props: Record<string, unknown>): ReactNode {
46
+ const resolved: Record<string, unknown> = {};
47
+ for (const [name, value] of Object.entries(props)) resolved[name] = imageUrlFromUnknown(value);
48
+ return createElement(Cmp, resolved);
49
+ }
50
+
51
+ /** One entry per example to show, in query order. */
52
+ export async function loadGalleryEntries(
53
+ query: BlockGalleryQuery,
54
+ blocks: BlockComponents | undefined,
55
+ ): Promise<GalleryEntry[]> {
56
+ const single = query.blocks.length === 1 && query.example !== undefined;
57
+ const perBlock = await Promise.all(
58
+ query.blocks.map(async (name): Promise<GalleryEntry[]> => {
59
+ const entry = blocks?.[name];
60
+ if (!entry) return [{ block: name, example: 0, exampleName: "Unknown block", element: null }];
61
+ const mod = await asBlockLoader(name, entry)();
62
+ const Cmp = resolveBlockComponent(mod, name);
63
+ const examples = examplesOf(definitionOf(mod));
64
+ const picked = single
65
+ ? [Math.min(query.example!, examples.length - 1)]
66
+ : examples.map((_, index) => index);
67
+ return picked.map((index) => {
68
+ const example = examples[index]!;
69
+ const props = single && query.props ? query.props : example.props;
70
+ return {
71
+ block: name,
72
+ example: index,
73
+ exampleName: example.name,
74
+ element: Cmp ? renderBlock(Cmp, props) : null,
75
+ };
76
+ });
77
+ }),
78
+ );
79
+ return perBlock.flat();
80
+ }
81
+
82
+ /** The gallery page body. `single` hides the per-example bars. */
83
+ export async function renderBlockGallery(
84
+ query: BlockGalleryQuery,
85
+ blocks: BlockComponents | undefined,
86
+ options: { dashboardOrigins?: readonly string[] } = {},
87
+ ): Promise<ReactNode> {
88
+ const entries = await loadGalleryEntries(query, blocks);
89
+ const single = query.blocks.length === 1 && query.example !== undefined;
90
+ return createElement(
91
+ BlockGalleryShell,
92
+ { single, dashboardOrigins: [...(options.dashboardOrigins ?? [])] },
93
+ entries.map((entry) =>
94
+ createElement(
95
+ BlockGalleryItem,
96
+ {
97
+ key: `${entry.block}:${entry.example}`,
98
+ block: entry.block,
99
+ example: entry.example,
100
+ exampleName: entry.exampleName,
101
+ single,
102
+ missing: entry.element === null,
103
+ },
104
+ entry.element,
105
+ ),
106
+ ),
107
+ );
108
+ }
package/src/routes.ts CHANGED
@@ -7,11 +7,13 @@ import { Fragment, Suspense, createElement, type ReactNode } from "react";
7
7
  import { HeldPreview, HoldPreview } from "./preview-hold";
8
8
  import {
9
9
  DEFAULT_TEMPLATE_SLUG,
10
+ isBlockGallerySegments,
10
11
  isRoutable,
11
12
  isTemplateSlug,
12
13
  matchRoute,
13
14
  PREVIEW_CHECKOUT_QUERY,
14
15
  PREVIEW_COOKIE,
16
+ readBlockGalleryQuery,
15
17
  readPreviewCookie,
16
18
  routeSegments,
17
19
  type BackmatterDoc,
@@ -28,6 +30,7 @@ import { renderLayoutDoc, type DocLayout } from "./layout-doc";
28
30
  import { previewContentForCheckout, runWithPreviewContent } from "./preview-content";
29
31
  import { previewUnavailable } from "./preview-ui";
30
32
  import { SiteDocBridge } from "./site-doc-bridge";
33
+ import { renderBlockGallery } from "./block-gallery";
31
34
  import { requireSource, resolveSourceData } from "./source-data";
32
35
 
33
36
  export const CATCH_ALL_PARAM = "backmatter";
@@ -176,6 +179,16 @@ async function resolvePreviewState(
176
179
  }
177
180
  }
178
181
 
182
+ /**
183
+ * The block gallery shows only example props from the repository, never
184
+ * content, but it is still an editor page: draft mode with a valid preview
185
+ * session, or `next dev`.
186
+ */
187
+ export function blockGalleryAllowed(preview: PreviewState): boolean {
188
+ if (previewReplacesPublished(preview) && !preview.error) return true;
189
+ return process.env.NODE_ENV === "development";
190
+ }
191
+
179
192
  export function createCatchAll<Models extends readonly ModelDef[]>(
180
193
  cms: BackmatterClient<Models>,
181
194
  options: CatchAllOptions = {},
@@ -365,8 +378,20 @@ export function createCatchAll<Models extends readonly ModelDef[]>(
365
378
  return failFor();
366
379
  }
367
380
 
381
+ async function blockGallery(
382
+ searchParams: Promise<CatchAllSearchParams> | CatchAllSearchParams | undefined,
383
+ ): Promise<ReactNode> {
384
+ const preview = await resolvePreviewState(cms, options.preview, searchParams);
385
+ if (!blockGalleryAllowed(preview)) return failFor();
386
+ const query = readBlockGalleryQuery((await searchParams) ?? {});
387
+ return renderBlockGallery(query, options.blocks, {
388
+ dashboardOrigins: options.dashboardOrigins,
389
+ });
390
+ }
391
+
368
392
  const CmsRoute: CatchAllRoute["CmsRoute"] = async ({ params, searchParams }) => {
369
393
  const resolved = await cachedRouteParams(params);
394
+ if (isBlockGallerySegments(resolved[CATCH_ALL_PARAM])) return blockGallery(searchParams);
370
395
  const hit = resolve(resolved[CATCH_ALL_PARAM]);
371
396
  if (!hit) return failFor();
372
397
  const preview = await resolvePreviewState(cms, options.preview, searchParams);
@@ -381,6 +406,8 @@ export function createCatchAll<Models extends readonly ModelDef[]>(
381
406
  searchParams?: Promise<CatchAllSearchParams> | CatchAllSearchParams;
382
407
  }) => {
383
408
  const resolved = await params;
409
+ // The gallery is never published; the preview branch draws it.
410
+ if (isBlockGallerySegments(resolved[CATCH_ALL_PARAM])) return null;
384
411
  const hit = resolve(resolved[CATCH_ALL_PARAM]);
385
412
  if (!hit) return failFor();
386
413
  const body = await publishedBody(hit.type, hit.slug);
@@ -396,6 +423,9 @@ export function createCatchAll<Models extends readonly ModelDef[]>(
396
423
  searchParams?: Promise<CatchAllSearchParams> | CatchAllSearchParams;
397
424
  }) => {
398
425
  const resolved = await params;
426
+ if (isBlockGallerySegments(resolved[CATCH_ALL_PARAM])) {
427
+ return createElement(HoldPreview, null, await blockGallery(searchParams));
428
+ }
399
429
  const hit = resolve(resolved[CATCH_ALL_PARAM]);
400
430
  if (!hit) return null;
401
431
  const preview = await resolvePreviewState(cms, options.preview, searchParams);
@@ -449,6 +479,7 @@ export function createCatchAll<Models extends readonly ModelDef[]>(
449
479
 
450
480
  const generateMetadata: CatchAllRoute["generateMetadata"] = async ({ params }) => {
451
481
  const resolved = await cachedRouteParams(params);
482
+ if (isBlockGallerySegments(resolved[CATCH_ALL_PARAM])) return { title: "Blocks" };
452
483
  const hit = resolve(resolved[CATCH_ALL_PARAM]);
453
484
  if (!hit) return {};
454
485
  const loaded = await loadRouteDoc(hit, cms.getDoc, false);