@backmatter/core 0.0.41 → 0.0.42

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.41",
3
+ "version": "0.0.42",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -0,0 +1,124 @@
1
+ // packages/core/src/block-gallery.ts
2
+ // The block gallery: a page on the host, reachable only in draft mode, that
3
+ // renders blocks with their examples so Studio's block library can show the
4
+ // real components. Studio builds the URL and posts messages; the host reads
5
+ // both. This file is the contract between them.
6
+
7
+ /** Path the host's catch-all serves the gallery on. */
8
+ export const BLOCK_GALLERY_PATH = "/_backmatter/blocks";
9
+
10
+ /** Studio → gallery: render the single block with these props. */
11
+ export const BLOCK_GALLERY_PROPS_MESSAGE = "backmatter:block-gallery-props";
12
+
13
+ /** Gallery → Studio: the editor asked to open one block example. */
14
+ export const BLOCK_GALLERY_OPEN_MESSAGE = "backmatter:block-gallery-open";
15
+
16
+ const MAX_BLOCKS = 100;
17
+ const BLOCK_NAME = /^[A-Z][A-Za-z0-9]*$/;
18
+
19
+ export type BlockGalleryQuery = {
20
+ /** Block names in display order. One name with `example` set is the single view. */
21
+ blocks: string[];
22
+ /** Index into the block's examples. Set only in the single view. */
23
+ example?: number;
24
+ /** Props that replace the example's, from Studio's editor. Single view only. */
25
+ props?: Record<string, unknown>;
26
+ };
27
+
28
+ export type BlockGalleryPropsMessage = {
29
+ type: typeof BLOCK_GALLERY_PROPS_MESSAGE;
30
+ props: Record<string, unknown>;
31
+ };
32
+
33
+ export type BlockGalleryOpenMessage = {
34
+ type: typeof BLOCK_GALLERY_OPEN_MESSAGE;
35
+ block: string;
36
+ example: number;
37
+ };
38
+
39
+ /** True for the gallery path, with or without a trailing slash. */
40
+ export function isBlockGalleryPath(pathname: string): boolean {
41
+ return pathname.replace(/\/+$/, "") === BLOCK_GALLERY_PATH;
42
+ }
43
+
44
+ export function isBlockGallerySegments(segments: readonly string[] | undefined): boolean {
45
+ return isBlockGalleryPath(`/${(segments ?? []).join("/")}`);
46
+ }
47
+
48
+ function toBase64Url(text: string): string {
49
+ const bytes = new TextEncoder().encode(text);
50
+ let binary = "";
51
+ for (const byte of bytes) binary += String.fromCharCode(byte);
52
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
53
+ }
54
+
55
+ function fromBase64Url(value: string): string {
56
+ const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
57
+ const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
58
+ return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
59
+ }
60
+
61
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
62
+ return !!value && typeof value === "object" && !Array.isArray(value);
63
+ }
64
+
65
+ /** Gallery path and query for these blocks. */
66
+ export function blockGalleryPath(query: BlockGalleryQuery): string {
67
+ const params = new URLSearchParams();
68
+ params.set("blocks", query.blocks.join(","));
69
+ if (query.example !== undefined) params.set("example", String(query.example));
70
+ if (query.props) params.set("props", toBase64Url(JSON.stringify(query.props)));
71
+ return `${BLOCK_GALLERY_PATH}?${params}`;
72
+ }
73
+
74
+ type SearchInput = URLSearchParams | Record<string, string | string[] | undefined>;
75
+
76
+ function first(search: SearchInput, key: string): string | undefined {
77
+ if (search instanceof URLSearchParams) return search.get(key) ?? undefined;
78
+ const raw = search[key];
79
+ return Array.isArray(raw) ? raw[0] : raw;
80
+ }
81
+
82
+ /** The query a gallery request asks for. Unknown or malformed parts are dropped. */
83
+ export function readBlockGalleryQuery(search: SearchInput): BlockGalleryQuery {
84
+ const blocks = [
85
+ ...new Set(
86
+ (first(search, "blocks") ?? "")
87
+ .split(",")
88
+ .map((name) => name.trim())
89
+ .filter((name) => BLOCK_NAME.test(name)),
90
+ ),
91
+ ].slice(0, MAX_BLOCKS);
92
+ const query: BlockGalleryQuery = { blocks };
93
+ if (blocks.length !== 1) return query;
94
+ const example = Number(first(search, "example"));
95
+ if (Number.isInteger(example) && example >= 0) query.example = example;
96
+ const raw = first(search, "props");
97
+ if (raw && query.example !== undefined) {
98
+ try {
99
+ const props = JSON.parse(fromBase64Url(raw)) as unknown;
100
+ if (isPlainObject(props)) query.props = props;
101
+ } catch {
102
+ // A broken props value shows the example as declared.
103
+ }
104
+ }
105
+ return query;
106
+ }
107
+
108
+ export function isBlockGalleryPropsMessage(value: unknown): value is BlockGalleryPropsMessage {
109
+ return (
110
+ isPlainObject(value) && value.type === BLOCK_GALLERY_PROPS_MESSAGE && isPlainObject(value.props)
111
+ );
112
+ }
113
+
114
+ export function isBlockGalleryOpenMessage(value: unknown): value is BlockGalleryOpenMessage {
115
+ return (
116
+ isPlainObject(value) &&
117
+ value.type === BLOCK_GALLERY_OPEN_MESSAGE &&
118
+ typeof value.block === "string" &&
119
+ BLOCK_NAME.test(value.block) &&
120
+ typeof value.example === "number" &&
121
+ Number.isInteger(value.example) &&
122
+ value.example >= 0
123
+ );
124
+ }
package/src/block.ts CHANGED
@@ -33,6 +33,17 @@ export type BlockMeta = {
33
33
  * without one get a wireframe drawn from their fields.
34
34
  */
35
35
  preview?: string;
36
+ /**
37
+ * Named props that show the block in Studio's block library, one render per
38
+ * example. Never content: nothing reads them on a published page.
39
+ */
40
+ examples?: readonly BlockExample[];
41
+ };
42
+
43
+ /** One named set of props a block shows itself with in the block library. */
44
+ export type BlockExample = {
45
+ name: string;
46
+ props: Record<string, unknown>;
36
47
  };
37
48
 
38
49
  export type BlockDef<C = unknown> = BlockMeta & {
@@ -83,9 +94,58 @@ function readBlockMeta(value: Record<string, unknown>, strict: boolean): BlockMe
83
94
  bad('block.preview must be an https:// URL or a site path like "/block-previews/hero.png"');
84
95
  } else meta.preview = value.preview.trim();
85
96
  }
97
+ if (value.examples !== undefined) {
98
+ const examples = readBlockExamples(value.examples, strict);
99
+ if (examples === null) bad("block.examples must be a list of { name, props } with a name and an object of props");
100
+ else if (examples.length > 0) meta.examples = examples;
101
+ }
86
102
  return meta;
87
103
  }
88
104
 
105
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
106
+ return !!value && typeof value === "object" && !Array.isArray(value);
107
+ }
108
+
109
+ /** Valid examples; null when `strict` and any entry is bad (otherwise bad ones are dropped). */
110
+ function readBlockExamples(value: unknown, strict: boolean): BlockExample[] | null {
111
+ if (!Array.isArray(value)) return strict ? null : [];
112
+ const out: BlockExample[] = [];
113
+ for (const entry of value) {
114
+ const name = isPlainObject(entry) && typeof entry.name === "string" ? entry.name.trim() : "";
115
+ if (!name || !isPlainObject(entry) || !isPlainObject(entry.props)) {
116
+ if (strict) return null;
117
+ continue;
118
+ }
119
+ out.push({ name, props: { ...entry.props } });
120
+ }
121
+ return out;
122
+ }
123
+
124
+ function humanize(name: string): string {
125
+ const words = name
126
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
127
+ .replace(/[_-]+/g, " ")
128
+ .trim()
129
+ .toLowerCase();
130
+ return words ? words[0]!.toUpperCase() + words.slice(1) : name;
131
+ }
132
+
133
+ /**
134
+ * Stand-in props for a block without examples: a label for text, the first
135
+ * option, the minimum, false. Richer fields stay unset.
136
+ */
137
+ export function placeholderBlockProps(
138
+ fields: Record<string, { kind: string; options?: readonly string[]; min?: number }>,
139
+ ): Record<string, unknown> {
140
+ const props: Record<string, unknown> = {};
141
+ for (const [name, field] of Object.entries(fields)) {
142
+ if (field.kind === "text") props[name] = field.options?.[0] ?? humanize(name);
143
+ else if (field.kind === "number") props[name] = field.min ?? 0;
144
+ else if (field.kind === "boolean") props[name] = false;
145
+ }
146
+ return props;
147
+ }
148
+
89
149
  /** An http(s) URL or a root-relative path (not protocol-relative). */
90
150
  export function isBlockPreviewSrc(value: string): boolean {
91
151
  if (value.startsWith("/")) return !value.startsWith("//") && !/\s/.test(value);
package/src/index.ts CHANGED
@@ -62,6 +62,7 @@ export type {
62
62
  BlockSnapshot,
63
63
  InferBlockProps,
64
64
  BlockMeta,
65
+ BlockExample,
65
66
  } from "./block";
66
67
  export type { BlockGroupInfo, BlockPlacement, BuiltinBlockGroup } from "./block-groups";
67
68
  export { BLOCK_GROUPS, blockGroupInfo, blockLayoutWarnings, blockRules } from "./block-groups";
@@ -70,6 +71,7 @@ export {
70
71
  serializeBlock,
71
72
  parseBlockSnapshot,
72
73
  isBlockPreviewSrc,
74
+ placeholderBlockProps,
73
75
  RESERVED_BLOCK_PROP,
74
76
  } from "./block";
75
77
 
@@ -233,3 +235,17 @@ export {
233
235
  linkSide,
234
236
  splitInternalLink,
235
237
  } from "./link-address";
238
+ export {
239
+ BLOCK_GALLERY_PATH,
240
+ BLOCK_GALLERY_PROPS_MESSAGE,
241
+ BLOCK_GALLERY_OPEN_MESSAGE,
242
+ blockGalleryPath,
243
+ readBlockGalleryQuery,
244
+ isBlockGalleryPath,
245
+ isBlockGallerySegments,
246
+ isBlockGalleryPropsMessage,
247
+ isBlockGalleryOpenMessage,
248
+ type BlockGalleryQuery,
249
+ type BlockGalleryPropsMessage,
250
+ type BlockGalleryOpenMessage,
251
+ } from "./block-gallery";