@backmatter/studio 0.0.22 → 0.0.24

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.
@@ -4,9 +4,9 @@ import { RestrictToVerticalAxis } from "@dnd-kit/abstract/modifiers";
4
4
  import { DragDropProvider } from "@dnd-kit/react";
5
5
  import { isSortable, useSortable } from "@dnd-kit/react/sortable";
6
6
  import * as stylex from "@stylexjs/stylex";
7
- import type { BlockSnapshot, SchemaField } from "../api";
8
- import { useBlockConfig } from "../define-studio";
9
- import { FieldControl } from "../fields/FieldControl";
7
+ import type { BlockPickerView, BlockSnapshot, SchemaField } from "../api";
8
+ import { useBlockConfig, useStudioDefinition } from "../define-studio";
9
+ import { FieldControl, useIsSwitchField } from "../fields/FieldControl";
10
10
  import { fieldLabel } from "../fields/field-label";
11
11
  import { omitField } from "../fields/omit-field";
12
12
  import { Button } from "../ui/Button";
@@ -14,6 +14,8 @@ import { Field } from "../ui/Field";
14
14
  import { Text } from "../ui/Text";
15
15
  import { colors, radius, space, type } from "../styles/tokens.stylex";
16
16
  import { BlockPicker } from "./BlockPicker";
17
+ import { BlockLibraryDialog } from "./BlockLibrary";
18
+ import { resolvePickerView } from "./block-groups";
17
19
  import {
18
20
  SchemaFailureList,
19
21
  SchemaSourceNote,
@@ -100,6 +102,7 @@ function BlockItem({
100
102
  const def = catalog.find((b) => b.name === block.type);
101
103
  const fieldEntries = Object.entries(def?.fields ?? {});
102
104
  const config = useBlockConfig(block.type);
105
+ const isSwitch = useIsSwitchField(models);
103
106
  const Preview = config?.preview;
104
107
 
105
108
  return (
@@ -109,7 +112,16 @@ function BlockItem({
109
112
  data-block-id={block.id}
110
113
  {...stylex.props(styles.item, isDragging && styles.itemDragging)}
111
114
  >
112
- <div {...stylex.props(styles.itemBar)}>
115
+ <div
116
+ data-block-bar=""
117
+ {...stylex.props(styles.itemBar)}
118
+ // The label button carries the keyboard and screen reader toggle;
119
+ // its click bubbles here, and so does a click on the row around it.
120
+ onClick={(event) => {
121
+ if ((event.target as Element).closest("[data-drag-handle], [data-block-actions]")) return;
122
+ onToggle();
123
+ }}
124
+ >
113
125
  <button
114
126
  ref={handleRef}
115
127
  type="button"
@@ -123,9 +135,9 @@ function BlockItem({
123
135
  </button>
124
136
  <button
125
137
  type="button"
138
+ data-block-toggle=""
126
139
  {...stylex.props(styles.toggle)}
127
140
  aria-expanded={open}
128
- onClick={onToggle}
129
141
  >
130
142
  {config?.icon ? (
131
143
  <span {...stylex.props(styles.icon)} aria-hidden>
@@ -136,7 +148,7 @@ function BlockItem({
136
148
  {config?.label ?? block.type}
137
149
  </Text>
138
150
  </button>
139
- <div {...stylex.props(styles.itemActions)}>
151
+ <div data-block-actions="" {...stylex.props(styles.itemActions)}>
140
152
  <Button
141
153
  variant="ghost"
142
154
  disabled={readOnly}
@@ -170,6 +182,7 @@ function BlockItem({
170
182
  <Field
171
183
  key={name}
172
184
  label={fieldLabel(name, field)}
185
+ inline={isSwitch(field)}
173
186
  hint={
174
187
  field.description ? (
175
188
  <span {...stylex.props(styles.fieldGuidance)}>{field.description}</span>
@@ -204,6 +217,7 @@ export function BlocksList({
204
217
  readOnly,
205
218
  focusBlock,
206
219
  siteUrl,
220
+ picker,
207
221
  onChange,
208
222
  }: {
209
223
  blocks: BlockInstance[];
@@ -215,9 +229,13 @@ export function BlocksList({
215
229
  focusBlock?: { id: string; nonce: number } | null;
216
230
  /** Resolves site-path block previews (`/block-previews/hero.png`). */
217
231
  siteUrl?: string | null;
232
+ /** The blocks field's `picker` view; the site's `defineStudio({ blockPicker })` otherwise. */
233
+ picker?: BlockPickerView;
218
234
  onChange: (next: BlockInstance[]) => void;
219
235
  }) {
220
236
  const [openId, setOpenId] = useState<string | null>(null);
237
+ const definition = useStudioDefinition();
238
+ const pickerView = resolvePickerView(catalog, { field: picker, site: definition.blockPicker });
221
239
  const schemaSource = useSchemaSource();
222
240
  const failures = blockFailures(schemaSource);
223
241
  const listRef = useRef<HTMLDivElement>(null);
@@ -298,6 +316,13 @@ export function BlocksList({
298
316
  <Text tone="muted" size="sm">
299
317
  No blocks in the schema.
300
318
  </Text>
319
+ ) : pickerView === "grouped" ? (
320
+ <BlockLibraryDialog
321
+ catalog={catalog}
322
+ siteUrl={siteUrl}
323
+ disabled={readOnly}
324
+ onPick={add}
325
+ />
301
326
  ) : (
302
327
  <BlockPicker
303
328
  catalog={catalog}
@@ -338,8 +363,16 @@ const styles = stylex.create({
338
363
  borderBottomStyle: "solid",
339
364
  borderBottomColor: colors.border,
340
365
  backgroundColor: colors.bgSurface,
366
+ // The list stays overflow-visible for menus and drag, so the end rows
367
+ // round their own corners to sit inside its border.
368
+ ":first-child": {
369
+ borderTopLeftRadius: `calc(${radius.md} - 1px)`,
370
+ borderTopRightRadius: `calc(${radius.md} - 1px)`,
371
+ },
341
372
  ":last-child": {
342
373
  borderBottomWidth: 0,
374
+ borderBottomLeftRadius: `calc(${radius.md} - 1px)`,
375
+ borderBottomRightRadius: `calc(${radius.md} - 1px)`,
343
376
  },
344
377
  },
345
378
  itemDragging: {
@@ -368,6 +401,16 @@ const styles = stylex.create({
368
401
  paddingInlineEnd: space.md,
369
402
  paddingInlineStart: space.xs,
370
403
  paddingBlock: space.sm,
404
+ // Follows the row's rounded end corners so the hover stays inside them.
405
+ borderRadius: "inherit",
406
+ cursor: "pointer",
407
+ transitionProperty: "background-color",
408
+ transitionDuration: "120ms",
409
+ [hover]: {
410
+ ":hover": {
411
+ backgroundColor: `color-mix(in srgb, ${colors.bgHover} 50%, transparent)`,
412
+ },
413
+ },
371
414
  },
372
415
  handle: {
373
416
  display: "inline-flex",
@@ -412,6 +455,7 @@ const styles = stylex.create({
412
455
  color: colors.text,
413
456
  font: "inherit",
414
457
  textAlign: "start",
458
+ cursor: "pointer",
415
459
  },
416
460
  itemActions: {
417
461
  display: "flex",
@@ -421,7 +465,7 @@ const styles = stylex.create({
421
465
  itemBody: {
422
466
  display: "flex",
423
467
  flexDirection: "column",
424
- gap: space.md,
468
+ gap: space.xl,
425
469
  paddingInline: space.md,
426
470
  paddingBottom: space.md,
427
471
  },
@@ -20,7 +20,7 @@ import {
20
20
  type SchemaPayload,
21
21
  type SchemaField,
22
22
  } from "../api";
23
- import { FieldControl } from "../fields/FieldControl";
23
+ import { FieldControl, useIsSwitchField } from "../fields/FieldControl";
24
24
  import { loadRelationDocuments } from "../fields/load-relation-documents";
25
25
  import { omitField } from "../fields/omit-field";
26
26
  import { linkDocumentTypes } from "../fields/link-targets";
@@ -198,6 +198,7 @@ export function DocEditorPage() {
198
198
  const [confirmRevert, setConfirmRevert] = useState(false);
199
199
  const [saveState, setSaveState] = useState<SaveState>("idle");
200
200
  const [previewKey, setPreviewKey] = useState(0);
201
+ const isSwitch = useIsSwitchField(models);
201
202
  const [previewLoading, setPreviewLoading] = useState(true);
202
203
  const [previewFrame, setPreviewFrame] = useState(0);
203
204
  const [previewOffer, setPreviewOffer] = useState<PreviewChannelRef | null>(null);
@@ -976,7 +977,7 @@ export function DocEditorPage() {
976
977
  </div>
977
978
  </div>
978
979
  {previewUrl ? (
979
- <PreviewViewport size={previewSize} dragging={dragging}>
980
+ <PreviewViewport size={previewSize} dragging={dragging} loading={previewLoading}>
980
981
  <iframe
981
982
  key={`${previewKey}-${previewUrl}`}
982
983
  ref={previewFrameRef}
@@ -1005,11 +1006,7 @@ export function DocEditorPage() {
1005
1006
  </Link>
1006
1007
  </div>
1007
1008
  ) : (
1008
- <div
1009
- {...stylex.props(styles.iframe)}
1010
- aria-busy="true"
1011
- aria-label="Preview waiting for checkout"
1012
- />
1009
+ <PreviewViewport size={previewSize} loading loadingLabel="Loading checkout…" />
1013
1010
  )}
1014
1011
  </aside>
1015
1012
 
@@ -1129,7 +1126,7 @@ export function DocEditorPage() {
1129
1126
  detailNames.map((name) => {
1130
1127
  const field = fieldDefs[name]!;
1131
1128
  return (
1132
- <Field key={name} label={fieldLabel(name)}>
1129
+ <Field key={name} label={fieldLabel(name)} inline={isSwitch(field)}>
1133
1130
  <FieldControl
1134
1131
  name={name}
1135
1132
  field={field}
@@ -1147,6 +1144,7 @@ export function DocEditorPage() {
1147
1144
  documentLists={documentLists}
1148
1145
  readOnly={blocksReadOnly}
1149
1146
  siteUrl={siteUrl}
1147
+ picker={field.picker}
1150
1148
  onChange={onBlocksChange}
1151
1149
  />
1152
1150
  )}
@@ -1169,6 +1167,7 @@ export function DocEditorPage() {
1169
1167
  readOnly={aiEditing || parseFailed}
1170
1168
  focusBlock={blockFocus}
1171
1169
  siteUrl={siteUrl}
1170
+ picker={fieldDefs[blocksField]?.picker}
1172
1171
  onChange={(next) => {
1173
1172
  markEdited();
1174
1173
  setFrontmatter((prev) => ({ ...prev, [blocksField]: next }));
@@ -1532,7 +1531,7 @@ const styles = stylex.create({
1532
1531
  form: {
1533
1532
  display: "flex",
1534
1533
  flexDirection: "column",
1535
- gap: space.lg,
1534
+ gap: space.xl,
1536
1535
  paddingBottom: space.xxl,
1537
1536
  },
1538
1537
  });
@@ -1,12 +1,14 @@
1
1
  // packages/studio/src/pages/PreviewSize.tsx
2
2
  import type { KeyboardEvent, ReactNode } from "react";
3
3
  import * as stylex from "@stylexjs/stylex";
4
+ import { Snake } from "loading-dev";
4
5
  import {
5
6
  IconImac,
6
7
  IconPhone,
7
8
  IconTablet,
8
9
  } from "@central-icons-react/round-outlined-radius-2-stroke-1.5";
9
- import { colors, radius } from "../styles/tokens.stylex";
10
+ import { colors, radius, space } from "../styles/tokens.stylex";
11
+ import { Text } from "../ui/Text";
10
12
  import { Tooltip } from "../ui/Tooltip";
11
13
  import {
12
14
  previewFrameWidth,
@@ -77,15 +79,22 @@ export function PreviewSizeSwitch({
77
79
  );
78
80
  }
79
81
 
80
- /** Centers a fixed-width preview and scrolls sideways when the pane is narrower. */
82
+ /**
83
+ * Centers a fixed-width preview and scrolls sideways when the pane is narrower.
84
+ * While `loading`, a loader covers the page until it has something to show.
85
+ */
81
86
  export function PreviewViewport({
82
87
  size,
83
88
  dragging = false,
89
+ loading = false,
90
+ loadingLabel = "Loading preview…",
84
91
  children,
85
92
  }: {
86
93
  size: PreviewSize;
87
94
  dragging?: boolean;
88
- children: ReactNode;
95
+ loading?: boolean;
96
+ loadingLabel?: string;
97
+ children?: ReactNode;
89
98
  }) {
90
99
  const width = previewFrameWidth(size);
91
100
  const viewport = stylex.props(styles.viewport, dragging && styles.dragging);
@@ -97,6 +106,14 @@ export function PreviewViewport({
97
106
  style={width === null ? slot.style : { ...slot.style, width }}
98
107
  >
99
108
  {children}
109
+ {loading ? (
110
+ <div role="status" {...stylex.props(styles.loader)}>
111
+ <span {...stylex.props(styles.loaderMark)} aria-hidden>
112
+ <Snake size={20} />
113
+ </span>
114
+ <Text tone="muted" size="sm">{loadingLabel}</Text>
115
+ </div>
116
+ ) : null}
100
117
  </div>
101
118
  </div>
102
119
  );
@@ -104,6 +121,11 @@ export function PreviewViewport({
104
121
 
105
122
  const hover = "@media (hover: hover)";
106
123
 
124
+ const appear = stylex.keyframes({
125
+ from: { opacity: 0 },
126
+ to: { opacity: 1 },
127
+ });
128
+
107
129
  const styles = stylex.create({
108
130
  group: {
109
131
  display: "inline-flex",
@@ -170,6 +192,29 @@ const styles = stylex.create({
170
192
  minHeight: 0,
171
193
  backgroundColor: colors.bgSurface,
172
194
  },
195
+ loader: {
196
+ position: "absolute",
197
+ inset: 0,
198
+ display: "flex",
199
+ flexDirection: "column",
200
+ alignItems: "center",
201
+ justifyContent: "center",
202
+ gap: space.md,
203
+ backgroundColor: colors.bgSurface,
204
+ // A page that loads at once never shows the loader.
205
+ animationName: appear,
206
+ animationDuration: "150ms",
207
+ animationDelay: "150ms",
208
+ animationTimingFunction: "ease-out",
209
+ animationFillMode: "both",
210
+ "@media (prefers-reduced-motion: reduce)": {
211
+ animationName: "none",
212
+ },
213
+ },
214
+ loaderMark: {
215
+ display: "flex",
216
+ color: colors.textMuted,
217
+ },
173
218
  slotFixed: {
174
219
  flexGrow: 0,
175
220
  flexShrink: 0,
@@ -18,6 +18,7 @@ import {
18
18
  isWorkspaceHomePath,
19
19
  isWorkspaceCodePath,
20
20
  isWorkspaceMediaPath,
21
+ isWorkspaceBlocksPath,
21
22
  isWorkspaceSettingsPath,
22
23
  isWorkspaceTypeIndexPath,
23
24
  } from "../workspace-path";
@@ -34,6 +35,7 @@ export function WorkspaceLayout() {
34
35
  const isTypeIndex = isWorkspaceTypeIndexPath(location.pathname);
35
36
  const isSettings = isWorkspaceSettingsPath(location.pathname);
36
37
  const isMedia = isWorkspaceMediaPath(location.pathname);
38
+ const isBlocks = isWorkspaceBlocksPath(location.pathname);
37
39
  const isCode = isWorkspaceCodePath(location.pathname);
38
40
  const isHome = isWorkspaceHomePath(location.pathname);
39
41
  const { userId } = useAppChrome();
@@ -117,7 +119,7 @@ export function WorkspaceLayout() {
117
119
  return (
118
120
  <PageFrame
119
121
  wide={isHome}
120
- flush={isEditor || isContentIndex || isTypeIndex || isSettings || isMedia || isCode}
122
+ flush={isEditor || isContentIndex || isTypeIndex || isSettings || isMedia || isBlocks || isCode}
121
123
  >
122
124
  <SchemaSourceProvider value={schemaSource}>
123
125
  <Outlet context={outletContext} />
@@ -0,0 +1,120 @@
1
+ // packages/studio/src/pages/block-groups.ts
2
+ // How the "Add block" picker sorts blocks into groups, and whether it opens on
3
+ // the groups or on every block at once.
4
+ import { BLOCK_GROUPS } from "@backmatter/core";
5
+ import type { BlockPickerView, BlockSnapshot } from "../api";
6
+
7
+ /** Site overrides for one block group, from `defineStudio({ blockGroups })`. */
8
+ export type StudioBlockGroupConfig = {
9
+ label?: string;
10
+ description?: string;
11
+ /** Cover image: an http(s) URL or a site path like "/block-previews/pricing.png". */
12
+ cover?: string;
13
+ /** Lower comes first. Groups without one keep the default order after these. */
14
+ order?: number;
15
+ };
16
+
17
+ export type BlockGroupView = {
18
+ /** The `group` key the blocks declare; "" collects blocks without one. */
19
+ name: string;
20
+ label: string;
21
+ description?: string;
22
+ blocks: BlockSnapshot[];
23
+ /** Block drawn as the group's cover when `coverSrc` is unset. */
24
+ cover: BlockSnapshot;
25
+ coverSrc?: string;
26
+ };
27
+
28
+ /** Auto view groups once the catalog has more blocks than this. */
29
+ export const AUTO_GROUP_THRESHOLD = 8;
30
+
31
+ const BUILTIN_ORDER = Object.keys(BLOCK_GROUPS);
32
+
33
+ function titleCase(name: string): string {
34
+ return name
35
+ .split("-")
36
+ .filter(Boolean)
37
+ .map((part) => part[0]!.toUpperCase() + part.slice(1))
38
+ .join(" ");
39
+ }
40
+
41
+ function defaultRank(name: string): number {
42
+ if (name === "") return Number.MAX_SAFE_INTEGER;
43
+ const builtin = BUILTIN_ORDER.indexOf(name);
44
+ return builtin >= 0 ? builtin : BUILTIN_ORDER.length;
45
+ }
46
+
47
+ export function groupBlocks(
48
+ catalog: BlockSnapshot[],
49
+ settings: Record<string, StudioBlockGroupConfig> = {},
50
+ ): BlockGroupView[] {
51
+ const byName = new Map<string, BlockSnapshot[]>();
52
+ for (const block of catalog) {
53
+ const name = block.group ?? "";
54
+ const list = byName.get(name);
55
+ if (list) list.push(block);
56
+ else byName.set(name, [block]);
57
+ }
58
+ const groups: BlockGroupView[] = [];
59
+ for (const [name, blocks] of byName) {
60
+ const setting = settings[name] ?? {};
61
+ const builtin = (BLOCK_GROUPS as Record<string, { label: string; description: string }>)[name];
62
+ const description = setting.description ?? builtin?.description;
63
+ groups.push({
64
+ name,
65
+ label: setting.label ?? builtin?.label ?? (name ? titleCase(name) : "Other"),
66
+ ...(description ? { description } : {}),
67
+ blocks,
68
+ cover: blocks.find((b) => b.preview) ?? blocks[0]!,
69
+ ...(setting.cover ? { coverSrc: setting.cover } : {}),
70
+ });
71
+ }
72
+ return groups.sort((a, b) => {
73
+ const oa = settings[a.name]?.order;
74
+ const ob = settings[b.name]?.order;
75
+ if (oa !== undefined || ob !== undefined) {
76
+ if (oa === undefined) return 1;
77
+ if (ob === undefined) return -1;
78
+ if (oa !== ob) return oa - ob;
79
+ }
80
+ const ra = defaultRank(a.name);
81
+ const rb = defaultRank(b.name);
82
+ if (ra !== rb) return ra - rb;
83
+ return a.name.localeCompare(b.name);
84
+ });
85
+ }
86
+
87
+ /**
88
+ * The picker layout: the blocks field's `picker`, else the site default, else
89
+ * "auto". A catalog in fewer than two groups is always flat.
90
+ */
91
+ export function resolvePickerView(
92
+ catalog: BlockSnapshot[],
93
+ views: { field?: BlockPickerView; site?: BlockPickerView },
94
+ ): "grouped" | "flat" {
95
+ const groups = new Set(catalog.map((b) => b.group ?? ""));
96
+ if (groups.size < 2) return "flat";
97
+ const view = views.field ?? views.site ?? "auto";
98
+ if (view === "auto") return catalog.length > AUTO_GROUP_THRESHOLD ? "grouped" : "flat";
99
+ return view;
100
+ }
101
+
102
+ /** Blocks whose name, label, description or group label contain every word of the query. */
103
+ export function searchBlocks(
104
+ groups: BlockGroupView[],
105
+ query: string,
106
+ labelOf: (block: BlockSnapshot) => string = (b) => b.name,
107
+ ): BlockSnapshot[] {
108
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
109
+ if (words.length === 0) return [];
110
+ const hits: BlockSnapshot[] = [];
111
+ for (const group of groups) {
112
+ for (const block of group.blocks) {
113
+ const text = [block.name, labelOf(block), block.description ?? "", group.label]
114
+ .join(" ")
115
+ .toLowerCase();
116
+ if (words.every((w) => text.includes(w))) hits.push(block);
117
+ }
118
+ }
119
+ return hits;
120
+ }
package/src/ui/Field.tsx CHANGED
@@ -6,18 +6,26 @@ import { colors, space, type } from "../styles/tokens.stylex";
6
6
  export function Field({
7
7
  label,
8
8
  hint,
9
+ inline = false,
9
10
  children,
10
11
  }: {
11
12
  label: string;
12
13
  /** Functional note under the control: counts, ids, shortcuts. */
13
14
  hint?: React.ReactNode;
15
+ /** Puts a small control, such as a switch, on the label's row at the far side. */
16
+ inline?: boolean;
14
17
  children: React.ReactNode;
15
18
  }) {
16
19
  return (
17
- <label {...stylex.props(styles.field)} onClickCapture={keepButtonsUnpressed}>
18
- <span {...stylex.props(styles.label)}>{label}</span>
20
+ <label
21
+ {...stylex.props(styles.field, inline && styles.fieldInline)}
22
+ onClickCapture={keepButtonsUnpressed}
23
+ >
24
+ <span {...stylex.props(styles.label, inline && styles.labelInline)}>{label}</span>
19
25
  {children}
20
- {hint ? <span {...stylex.props(styles.hint)}>{hint}</span> : null}
26
+ {hint ? (
27
+ <span {...stylex.props(styles.hint, inline && styles.hintInline)}>{hint}</span>
28
+ ) : null}
21
29
  </label>
22
30
  );
23
31
  }
@@ -63,6 +71,20 @@ const styles = stylex.create({
63
71
  display: "block",
64
72
  fontSize: type.md,
65
73
  },
74
+ fieldInline: {
75
+ display: "flex",
76
+ flexWrap: "wrap",
77
+ alignItems: "center",
78
+ justifyContent: "space-between",
79
+ columnGap: space.lg,
80
+ minHeight: "24px",
81
+ },
82
+ labelInline: {
83
+ marginBottom: 0,
84
+ },
85
+ hintInline: {
86
+ flexBasis: "100%",
87
+ },
66
88
  label: {
67
89
  display: "block",
68
90
  marginBottom: space.sm,
@@ -23,6 +23,10 @@ export function mediaPath(slug: string) {
23
23
  return `/${slug}/media`;
24
24
  }
25
25
 
26
+ export function blocksPath(slug: string) {
27
+ return `/${slug}/blocks`;
28
+ }
29
+
26
30
  export function codeSessionPath(slug: string) {
27
31
  return `/${slug}/code`;
28
32
  }
@@ -83,6 +87,10 @@ export function isWorkspaceMediaPath(pathname: string) {
83
87
  return /\/media\/?$/.test(pathname);
84
88
  }
85
89
 
90
+ export function isWorkspaceBlocksPath(pathname: string) {
91
+ return /\/blocks\/?$/.test(pathname);
92
+ }
93
+
86
94
  export function isWorkspaceCodePath(pathname: string) {
87
95
  return /\/code\/?$/.test(pathname);
88
96
  }