@backmatter/studio 0.0.20 → 0.0.21

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.
Files changed (57) hide show
  1. package/dist/chunks/{UiKitApp-C269OA8v.js → UiKitApp-CMMcsaX4.js} +2 -2
  2. package/dist/chunks/{WorkspaceRoutes-B4B5jjje.js → WorkspaceRoutes-DW0sLdpJ.js} +27141 -26241
  3. package/dist/chunks/dashboard-By0P4Yny.js +1879 -0
  4. package/dist/chunks/{index-7-TtXaMq.js → index-DTPUqaHE.js} +1 -1
  5. package/dist/dashboard.js +2 -2
  6. package/dist/index.js +205 -194
  7. package/dist/site-widget.css +208 -0
  8. package/dist/site-widget.js +10495 -9947
  9. package/dist/studio.css +276 -32
  10. package/package.json +2 -2
  11. package/src/App.tsx +7 -1
  12. package/src/api.ts +106 -13
  13. package/src/chat/ChatFiles.tsx +261 -0
  14. package/src/chat/ChatMessage.tsx +5 -0
  15. package/src/chat/ChatPanel.tsx +218 -14
  16. package/src/chat/ChatProvider.tsx +72 -22
  17. package/src/chat/Composer.tsx +83 -6
  18. package/src/chat/PendingFileRow.tsx +188 -0
  19. package/src/chat/chat-context.ts +7 -1
  20. package/src/chat/chat-helpers.ts +49 -0
  21. package/src/chat/chat-state.ts +17 -6
  22. package/src/chat/icons.tsx +28 -0
  23. package/src/chat/model-copy.ts +41 -0
  24. package/src/chat/pending-files.ts +236 -0
  25. package/src/chat/side-width.ts +48 -0
  26. package/src/chrome/AppShell.tsx +9 -1
  27. package/src/chrome/CommandPalette.tsx +7 -0
  28. package/src/chrome/ContentExplorerSidebar.tsx +43 -74
  29. package/src/chrome/folder-create-context.ts +56 -11
  30. package/src/chrome/hotkeys.ts +8 -0
  31. package/src/fields/FieldControl.tsx +331 -115
  32. package/src/fields/LinkFieldInput.tsx +13 -6
  33. package/src/fields/array-item-title.ts +28 -0
  34. package/src/fields/field-label.ts +8 -0
  35. package/src/host-pointer.ts +2 -0
  36. package/src/install-preview-pointer.ts +1 -0
  37. package/src/pages/BlockPicker.tsx +362 -0
  38. package/src/pages/BlocksList.tsx +39 -67
  39. package/src/pages/CliAuthorizePage.tsx +138 -25
  40. package/src/pages/DocEditorPage.tsx +95 -18
  41. package/src/pages/EmbedPublishPage.tsx +40 -2
  42. package/src/pages/LoginPage.tsx +118 -31
  43. package/src/pages/SettingsSchemaPage.tsx +19 -3
  44. package/src/pages/WorkspaceLayout.tsx +16 -1
  45. package/src/pages/block-picker.ts +116 -0
  46. package/src/pages/editor-grab.ts +61 -13
  47. package/src/pages/preview-split.ts +24 -0
  48. package/src/pages/session-preview.ts +1 -0
  49. package/src/replica/types.ts +2 -0
  50. package/src/sign-in-link.ts +45 -0
  51. package/src/site-pointer.ts +14 -1
  52. package/src/site-widget.tsx +12 -1
  53. package/src/ui/Field.tsx +26 -0
  54. package/src/workspace/schema-source.tsx +126 -0
  55. package/dist/chunks/dashboard-DeNgythd.js +0 -1779
  56. package/src/site-devbar-overlay-inject.ts +0 -15
  57. package/src/site-publish-menu.tsx +0 -33
@@ -1,8 +1,14 @@
1
1
  // packages/studio/src/pages/LoginPage.tsx
2
- import { useEffect, useState } from "react";
2
+ import { useEffect, useRef, useState } from "react";
3
3
  import { useSearchParams } from "react-router";
4
4
  import * as stylex from "@stylexjs/stylex";
5
5
  import { fetchAuthConfig } from "../api";
6
+ import {
7
+ signInLinkError,
8
+ signInLinkVerifyUrl,
9
+ withoutSignInLinkError,
10
+ } from "../sign-in-link";
11
+ import { apiUrl } from "../studio-config";
6
12
  import { authClient } from "../auth-client";
7
13
  import { GithubIcon } from "../chrome/icons";
8
14
  import { colors, space, type } from "../styles/tokens.stylex";
@@ -19,11 +25,12 @@ const legal = {
19
25
 
20
26
  export function LoginPage() {
21
27
  const [params] = useSearchParams();
22
- const [error, setError] = useState<string | null>(null);
28
+ const [error, setError] = useState<string | null>(() => signInLinkError(params.get("error")));
23
29
  const [notice, setNotice] = useState<string | null>(null);
24
30
  const [busy, setBusy] = useState(false);
25
31
  const [github, setGithub] = useState<boolean | null>(null);
26
32
  const invitedEmail = params.get("token") ? (params.get("email") ?? "") : "";
33
+ const emailField = useRef<HTMLInputElement>(null);
27
34
  const [email, setEmail] = useState(invitedEmail || (params.get("email") ?? ""));
28
35
  const [password, setPassword] = useState("");
29
36
  const [name, setName] = useState("");
@@ -31,13 +38,21 @@ export function LoginPage() {
31
38
  const [accepted, setAccepted] = useState(false);
32
39
  const signupBlocked = mode === "signup" && !accepted;
33
40
 
41
+ useEffect(() => {
42
+ // A failed sign-in link lands here with `?error=`. Show it once, then
43
+ // drop it so a reload or the next callback does not carry it.
44
+ if (params.has("error")) {
45
+ window.history.replaceState(null, "", withoutSignInLinkError(window.location.href));
46
+ }
47
+ }, [params]);
48
+
34
49
  useEffect(() => {
35
50
  void fetchAuthConfig()
36
51
  .then((config) => setGithub(config.github))
37
52
  .catch(() => setGithub(false));
38
53
  }, []);
39
54
 
40
- const callbackURL = window.location.href;
55
+ const callbackURL = withoutSignInLinkError(window.location.href);
41
56
 
42
57
  async function onGithub() {
43
58
  setBusy(true);
@@ -54,10 +69,20 @@ export function LoginPage() {
54
69
  }
55
70
 
56
71
  async function onMagicLink() {
57
- setBusy(true);
72
+ // Chrome keeps an autofilled value from React state until the user
73
+ // interacts with the page, so read the field itself.
74
+ const field = emailField.current;
75
+ const address = (field?.value || email).trim();
58
76
  setError(null);
59
77
  setNotice(null);
60
- const result = await authClient().signIn.magicLink({ email, callbackURL });
78
+ if (!address || (field && !field.checkValidity())) {
79
+ setError("Enter your email address first.");
80
+ field?.focus();
81
+ return;
82
+ }
83
+ setEmail(address);
84
+ setBusy(true);
85
+ const result = await authClient().signIn.magicLink({ email: address, callbackURL });
61
86
  setBusy(false);
62
87
  if (result.error) {
63
88
  setError(result.error.message ?? "Could not send the magic link");
@@ -70,6 +95,7 @@ export function LoginPage() {
70
95
  e.preventDefault();
71
96
  setBusy(true);
72
97
  setError(null);
98
+ setNotice(null);
73
99
  const result =
74
100
  mode === "signup"
75
101
  ? await authClient().signUp.email({ email, password, name, callbackURL })
@@ -103,26 +129,6 @@ export function LoginPage() {
103
129
  <div {...stylex.props(styles.actions)}>
104
130
  {error ? <Text tone="danger">{error}</Text> : null}
105
131
  {notice ? <Text tone="muted">{notice}</Text> : null}
106
- <p {...stylex.props(styles.legal)}>
107
- By continuing you agree to the{" "}
108
- <a href={legal.terms} {...stylex.props(styles.legalLink)}>Terms</a> and the{" "}
109
- <a href={legal.dpa} {...stylex.props(styles.legalLink)}>Data Processing Agreement</a>,
110
- and you acknowledge the{" "}
111
- <a href={legal.privacy} {...stylex.props(styles.legalLink)}>Privacy policy</a>.
112
- A consumer who asks us to start the service now loses the 14-day right of withdrawal
113
- once it has begun.
114
- </p>
115
- {mode === "signup" ? (
116
- <label {...stylex.props(styles.accept)}>
117
- <input
118
- type="checkbox"
119
- checked={accepted}
120
- onChange={(event) => setAccepted(event.target.checked)}
121
- {...stylex.props(styles.checkbox)}
122
- />
123
- <span>I agree, and I ask Backmatter to start the service now.</span>
124
- </label>
125
- ) : null}
126
132
  <form onSubmit={(e) => void onPassword(e)} {...stylex.props(styles.form)}>
127
133
  {mode === "signup" ? (
128
134
  <input
@@ -136,6 +142,7 @@ export function LoginPage() {
136
142
  ) : null}
137
143
  <input
138
144
  required
145
+ ref={emailField}
139
146
  type="email"
140
147
  value={email}
141
148
  onChange={(e) => setEmail(e.target.value)}
@@ -153,6 +160,17 @@ export function LoginPage() {
153
160
  autoComplete={mode === "signup" ? "new-password" : "current-password"}
154
161
  {...stylex.props(styles.field)}
155
162
  />
163
+ {mode === "signup" ? (
164
+ <label {...stylex.props(styles.accept)}>
165
+ <input
166
+ type="checkbox"
167
+ checked={accepted}
168
+ onChange={(event) => setAccepted(event.target.checked)}
169
+ {...stylex.props(styles.checkbox)}
170
+ />
171
+ <span>I agree, and I ask Backmatter to start the service now.</span>
172
+ </label>
173
+ ) : null}
156
174
  <button
157
175
  type="submit"
158
176
  disabled={busy || signupBlocked}
@@ -163,9 +181,9 @@ export function LoginPage() {
163
181
  </form>
164
182
  <button
165
183
  type="button"
166
- disabled={busy || !email || signupBlocked}
184
+ disabled={busy || signupBlocked}
167
185
  onClick={() => void onMagicLink()}
168
- {...stylex.props(styles.secondary, (busy || !email || signupBlocked) && styles.ctaDisabled)}
186
+ {...stylex.props(styles.secondary, (busy || signupBlocked) && styles.ctaDisabled)}
169
187
  >
170
188
  Email me a magic link
171
189
  </button>
@@ -187,6 +205,66 @@ export function LoginPage() {
187
205
  Continue with GitHub
188
206
  </button>
189
207
  </div>
208
+ <p {...stylex.props(styles.legal)}>
209
+ By continuing you agree to the{" "}
210
+ <a href={legal.terms} {...stylex.props(styles.legalLink)}>Terms</a> and the{" "}
211
+ <a href={legal.dpa} {...stylex.props(styles.legalLink)}>Data Processing Agreement</a>,
212
+ and you acknowledge the{" "}
213
+ <a href={legal.privacy} {...stylex.props(styles.legalLink)}>Privacy policy</a>.
214
+ A consumer who asks us to start the service now loses the 14-day right of withdrawal
215
+ once it has begun.
216
+ </p>
217
+ </div>
218
+ </main>
219
+ );
220
+ }
221
+
222
+ /**
223
+ * Where a magic-link email lands. Mail scanners open the link before the
224
+ * person does, so the token is spent only when they press the button.
225
+ */
226
+ export function SignInLinkPage() {
227
+ const [busy, setBusy] = useState(false);
228
+ const verifyUrl = signInLinkVerifyUrl(apiUrl(), window.location.search, window.location.origin);
229
+
230
+ return (
231
+ <main {...stylex.props(darkTheme, styles.main)}>
232
+ <div {...stylex.props(styles.glow)} aria-hidden />
233
+ <div {...stylex.props(styles.panel)}>
234
+ <div {...stylex.props(styles.markWrap)}>
235
+ <LoginMark />
236
+ </div>
237
+ <h1 {...stylex.props(styles.heading)}>Finish signing in</h1>
238
+ <div {...stylex.props(styles.lead)}>
239
+ <Text tone="muted">
240
+ {verifyUrl
241
+ ? "Sign in to Backmatter in this browser."
242
+ : "This sign-in link is incomplete. Send yourself a new one."}
243
+ </Text>
244
+ </div>
245
+ <div {...stylex.props(styles.actions)}>
246
+ {verifyUrl ? (
247
+ <button
248
+ type="button"
249
+ disabled={busy}
250
+ onClick={() => {
251
+ setBusy(true);
252
+ window.location.assign(verifyUrl);
253
+ }}
254
+ {...stylex.props(styles.cta, busy && styles.ctaDisabled)}
255
+ >
256
+ Sign in
257
+ </button>
258
+ ) : (
259
+ <button
260
+ type="button"
261
+ onClick={() => window.location.assign("/")}
262
+ {...stylex.props(styles.cta)}
263
+ >
264
+ Back to sign in
265
+ </button>
266
+ )}
267
+ </div>
190
268
  </div>
191
269
  </main>
192
270
  );
@@ -365,15 +443,24 @@ const styles = stylex.create({
365
443
  color: colors.textMuted,
366
444
  },
367
445
  legal: {
446
+ maxWidth: "320px",
368
447
  margin: 0,
369
- fontSize: type.sm,
370
- lineHeight: 1.5,
448
+ marginTop: "32px",
449
+ fontSize: type.xs,
450
+ lineHeight: 1.6,
371
451
  color: colors.textMuted,
372
- textAlign: "left",
452
+ textAlign: "center",
453
+ textWrap: "pretty",
373
454
  },
374
455
  legalLink: {
375
- color: colors.text,
456
+ color: "inherit",
457
+ textDecorationColor: "rgba(161,161,170,0.4)",
376
458
  textUnderlineOffset: "2px",
459
+ [hover]: {
460
+ ":hover": {
461
+ color: "#d4d4d8",
462
+ },
463
+ },
377
464
  },
378
465
  accept: {
379
466
  display: "flex",
@@ -7,6 +7,11 @@ import { Text } from "../ui/Text";
7
7
  import * as stylex from "@stylexjs/stylex";
8
8
  import { space, type } from "../styles/tokens.stylex";
9
9
  import type { WorkspaceOutletContext } from "../workspace/types";
10
+ import {
11
+ SchemaFailureList,
12
+ SchemaSourceNote,
13
+ useSchemaSource,
14
+ } from "../workspace/schema-source";
10
15
 
11
16
  export function SettingsSchemaPage() {
12
17
  const { workspace } = useOutletContext<WorkspaceOutletContext>();
@@ -14,6 +19,8 @@ export function SettingsSchemaPage() {
14
19
  const [schemaBranch, setSchemaBranch] = useState<string | null>(null);
15
20
  const [schemaJson, setSchemaJson] = useState("");
16
21
  const [error, setError] = useState<string | null>(null);
22
+ const schemaSource = useSchemaSource();
23
+ const failures = schemaSource?.failures ?? [];
17
24
 
18
25
  useEffect(() => {
19
26
  function load() {
@@ -53,11 +60,20 @@ export function SettingsSchemaPage() {
53
60
  Schema snapshot
54
61
  </Text>
55
62
  <Text tone="muted" size="sm">
56
- {schemaVersion
57
- ? `v${schemaVersion}${schemaBranch ? ` · ${schemaBranch}` : ""}`
58
- : "none"}
63
+ {schemaVersion ? `v${schemaVersion}` : schemaBranch ? `none · ${schemaBranch}` : "none"}{" "}
64
+ {schemaVersion ? <SchemaSourceNote source={schemaSource} /> : null}
59
65
  </Text>
60
66
  </div>
67
+ <div {...stylex.props(failures.length > 0 && styles.block)}>
68
+ <SchemaFailureList
69
+ failures={failures}
70
+ title={
71
+ failures.length === 1
72
+ ? "A file failed to evaluate on the last import. Its definition is missing or out of date."
73
+ : `${failures.length} files failed to evaluate on the last import. Their definitions are missing or out of date.`
74
+ }
75
+ />
76
+ </div>
61
77
  {schemaJson ? (
62
78
  <pre {...stylex.props(styles.pre)}>{schemaJson}</pre>
63
79
  ) : (
@@ -11,6 +11,7 @@ import { useReplicaState } from "../replica/useReplica";
11
11
  import { PageFrame } from "../ui/Page";
12
12
  import { Text } from "../ui/Text";
13
13
  import type { WorkspaceOutletContext } from "../workspace/types";
14
+ import { SchemaSourceProvider, type SchemaSource } from "../workspace/schema-source";
14
15
  import {
15
16
  isWorkspaceContentIndexPath,
16
17
  isWorkspaceEditorPath,
@@ -44,6 +45,18 @@ export function WorkspaceLayout() {
44
45
  const models = slot?.schema?.payload.models ?? EMPTY_MODELS;
45
46
  const blocks = slot?.schema?.payload.blocks ?? EMPTY_BLOCKS;
46
47
  const richtext = slot?.schema?.payload.richtext ?? EMPTY_RICHTEXT;
48
+ const schema = slot?.schema ?? null;
49
+ const schemaSource = useMemo<SchemaSource | null>(
50
+ () =>
51
+ schema
52
+ ? {
53
+ branch: schema.branch,
54
+ createdAt: schema.createdAt,
55
+ failures: schema.payload.failures ?? [],
56
+ }
57
+ : null,
58
+ [schema],
59
+ );
47
60
 
48
61
  const reload = useCallback(async () => {
49
62
  if (!workspace) return;
@@ -106,7 +119,9 @@ export function WorkspaceLayout() {
106
119
  wide={isHome}
107
120
  flush={isEditor || isContentIndex || isTypeIndex || isSettings || isMedia || isCode}
108
121
  >
109
- <Outlet context={outletContext} />
122
+ <SchemaSourceProvider value={schemaSource}>
123
+ <Outlet context={outletContext} />
124
+ </SchemaSourceProvider>
110
125
  </PageFrame>
111
126
  );
112
127
  }
@@ -0,0 +1,116 @@
1
+ // packages/studio/src/pages/block-picker.ts
2
+ // What the "Add block" picker shows for each block: the declared thumbnail,
3
+ // or a wireframe sketched from the block's fields so every block has a
4
+ // picture even without preview metadata.
5
+ import type { BlockSnapshot, SchemaField } from "../api";
6
+
7
+ export type WireShape =
8
+ | { kind: "chip" }
9
+ | { kind: "heading" }
10
+ | { kind: "text" }
11
+ | { kind: "image" }
12
+ | { kind: "button" }
13
+ | { kind: "cards"; count: number };
14
+
15
+ export type BlockWireframe = {
16
+ /** "split" puts the single image beside the other shapes. */
17
+ layout: "stack" | "split";
18
+ shapes: WireShape[];
19
+ };
20
+
21
+ const MAX_SHAPES = 6;
22
+ const HEADING_NAME = /(title|heading|headline)/i;
23
+ const CHIP_NAME = /(kicker|eyebrow|tag|badge|label|category)/i;
24
+ const BUTTON_NAME = /(cta|button|action)/i;
25
+
26
+ function shapeForField(name: string, field: SchemaField): WireShape | null {
27
+ switch (field.kind) {
28
+ case "image":
29
+ case "media":
30
+ return field.multiple ? { kind: "cards", count: 3 } : { kind: "image" };
31
+ case "link":
32
+ return { kind: "button" };
33
+ case "array":
34
+ case "blocks":
35
+ return { kind: "cards", count: 3 };
36
+ case "relation":
37
+ return field.multiple ? { kind: "cards", count: 3 } : { kind: "text" };
38
+ case "object":
39
+ return { kind: "text" };
40
+ case "text":
41
+ if (field.options?.length) return { kind: "chip" };
42
+ if (BUTTON_NAME.test(name)) return { kind: "button" };
43
+ if (CHIP_NAME.test(name)) return { kind: "chip" };
44
+ if (HEADING_NAME.test(name)) return { kind: "heading" };
45
+ return { kind: "text" };
46
+ default:
47
+ // number, boolean and unknown kinds are settings, not visible content.
48
+ return null;
49
+ }
50
+ }
51
+
52
+ /** A rough layout of the block, in field declaration order. */
53
+ export function blockWireframe(block: Pick<BlockSnapshot, "fields">): BlockWireframe {
54
+ const shapes: WireShape[] = [];
55
+ let images = 0;
56
+ let headings = 0;
57
+ for (const [name, field] of Object.entries(block.fields ?? {})) {
58
+ let shape = shapeForField(name, field);
59
+ if (!shape) continue;
60
+ if (shape.kind === "heading" && headings++ > 0) shape = { kind: "text" };
61
+ if (shape.kind === "image" && images++ > 0) continue;
62
+ const last = shapes[shapes.length - 1];
63
+ if (shape.kind === "text" && last?.kind === "text") continue;
64
+ if (shape.kind === "button" && last?.kind === "button") continue;
65
+ shapes.push(shape);
66
+ if (shapes.length === MAX_SHAPES) break;
67
+ }
68
+ if (shapes.length === 0) return { layout: "stack", shapes: [{ kind: "text" }] };
69
+ const hasCards = shapes.some((s) => s.kind === "cards");
70
+ const split = images === 1 && shapes.length > 1 && !hasCards;
71
+ return { layout: split ? "split" : "stack", shapes };
72
+ }
73
+
74
+ /**
75
+ * `<img src>` for a declared preview. A site path resolves against the site
76
+ * URL; without one it stays relative, which works when Studio runs on the site.
77
+ */
78
+ export function blockPreviewSrc(
79
+ preview: string | undefined,
80
+ siteUrl: string | null | undefined,
81
+ ): string | null {
82
+ const value = preview?.trim();
83
+ if (!value) return null;
84
+ if (value.startsWith("/")) {
85
+ if (value.startsWith("//")) return null;
86
+ const base = siteUrl?.trim().replace(/\/+$/, "");
87
+ return base ? `${base}${value}` : value;
88
+ }
89
+ try {
90
+ const url = new URL(value);
91
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+
97
+ function humanize(name: string): string {
98
+ const spaced = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ");
99
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
100
+ }
101
+
102
+ /**
103
+ * Placeholder props for a site-supplied `defineStudio` preview component shown
104
+ * in the picker. Scalars only; anything richer is left unset.
105
+ */
106
+ export function sampleBlockProps(
107
+ fields: Record<string, SchemaField> | undefined,
108
+ ): Record<string, unknown> {
109
+ const props: Record<string, unknown> = {};
110
+ for (const [name, field] of Object.entries(fields ?? {})) {
111
+ if (field.kind === "text") props[name] = field.options?.[0] ?? humanize(name);
112
+ else if (field.kind === "number") props[name] = field.min ?? 0;
113
+ else if (field.kind === "boolean") props[name] = false;
114
+ }
115
+ return props;
116
+ }
@@ -1,39 +1,87 @@
1
1
  // packages/studio/src/pages/editor-grab.ts
2
- import { samePreviewRef, type PreviewChannelRef } from "@backmatter/core/preview";
2
+ import { normalizePointerQuote, samePreviewRef, type PreviewChannelRef } from "@backmatter/core/preview";
3
3
 
4
4
  export type EditorGrab = {
5
- blockId: string;
5
+ /** Null when the click was outside any rendered block. */
6
+ blockId: string | null;
6
7
  blockType: string | null;
7
8
  blockIndex: number | null;
8
9
  quote: string;
9
10
  shift: boolean;
11
+ /** Block prop the page marked on the clicked text. */
12
+ field?: string;
10
13
  };
11
14
 
15
+ export type EditorGrabBlock = { id: string; type: string; props: Record<string, unknown> };
16
+
12
17
  export type EditorGrabDecision =
13
18
  | { action: "ignore" }
14
19
  | {
15
20
  action: "add";
16
- blockId: string;
21
+ blockId: string | null;
17
22
  blockType: string | null;
18
23
  blockIndex: number | null;
19
24
  quote: string;
25
+ field?: string;
20
26
  }
21
27
  | { action: "open"; blockId: string };
22
28
 
29
+ /** The string prop whose text is the quote, or holds it. Null when none or several. */
30
+ function fieldForQuote(props: Record<string, unknown>, quote: string): string | null {
31
+ const needle = normalizePointerQuote(quote).toLowerCase();
32
+ if (!needle) return null;
33
+ const texts = Object.entries(props).flatMap(([name, value]) =>
34
+ typeof value === "string" ? [[name, normalizePointerQuote(value).toLowerCase()] as const] : [],
35
+ );
36
+ const exact = texts.filter(([, text]) => text === needle);
37
+ if (exact.length === 1) return exact[0]![0];
38
+ if (exact.length > 1) return null;
39
+ const holding = texts.filter(([, text]) => text.includes(needle));
40
+ return holding.length === 1 ? holding[0]![0] : null;
41
+ }
42
+
43
+ /**
44
+ * What a click in the preview does to the open document. A click the form
45
+ * cannot map to a block still points at the document with its text.
46
+ */
23
47
  export function editorGrabAction(input: {
24
48
  grabRef: PreviewChannelRef;
25
49
  openRef: PreviewChannelRef;
26
- blockIds: readonly string[];
50
+ blocks: readonly EditorGrabBlock[];
27
51
  grab: EditorGrab;
28
52
  }): EditorGrabDecision {
29
53
  if (!samePreviewRef(input.grabRef, input.openRef)) return { action: "ignore" };
30
- if (!input.blockIds.includes(input.grab.blockId)) return { action: "ignore" };
31
- if (input.grab.shift) return { action: "open", blockId: input.grab.blockId };
32
- return {
33
- action: "add",
34
- blockId: input.grab.blockId,
35
- blockType: input.grab.blockType,
36
- blockIndex: input.grab.blockIndex,
37
- quote: input.grab.quote,
38
- };
54
+ const { grab } = input;
55
+ const block = grab.blockId ? input.blocks.find((row) => row.id === grab.blockId) : undefined;
56
+ if (block) {
57
+ if (grab.shift) return { action: "open", blockId: block.id };
58
+ const marked = grab.field && Object.hasOwn(block.props, grab.field) ? grab.field : null;
59
+ const field = marked ?? fieldForQuote(block.props, grab.quote);
60
+ return {
61
+ action: "add",
62
+ blockId: block.id,
63
+ blockType: grab.blockType ?? block.type,
64
+ blockIndex: grab.blockIndex,
65
+ quote: grab.quote,
66
+ ...(field ? { field } : {}),
67
+ };
68
+ }
69
+ if (grab.shift || !grab.quote) return { action: "ignore" };
70
+ return { action: "add", blockId: null, blockType: null, blockIndex: null, quote: grab.quote };
71
+ }
72
+
73
+ /**
74
+ * A hello from the preview. A page for another document, or one that cannot
75
+ * point, disarms. A page for the open document that loaded again (a refresh
76
+ * re-runs its session) gets the armed pointer back.
77
+ */
78
+ export function editorHelloAction(input: {
79
+ hello: PreviewChannelRef;
80
+ openRef: PreviewChannelRef;
81
+ capabilities?: readonly string[];
82
+ armed: boolean;
83
+ }): { canPoint: boolean; disarm: boolean; rearm: boolean } {
84
+ const canPoint =
85
+ samePreviewRef(input.hello, input.openRef) && (input.capabilities?.includes("point") ?? false);
86
+ return { canPoint, disarm: !canPoint, rearm: canPoint && input.armed };
39
87
  }
@@ -28,3 +28,27 @@ export function persistPreviewPct(value: number) {
28
28
  // ignore quota / private mode
29
29
  }
30
30
  }
31
+
32
+ export const EDITOR_HIDDEN_KEY = "backmatter-editor-hidden";
33
+
34
+ type FlagStore = {
35
+ getItem(key: string): string | null;
36
+ setItem(key: string, value: string): void;
37
+ };
38
+
39
+ /** Whether the person hid the document editor to give the preview the room. */
40
+ export function readEditorHidden(store?: FlagStore): boolean {
41
+ try {
42
+ return (store ?? localStorage).getItem(EDITOR_HIDDEN_KEY) === "1";
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+
48
+ export function persistEditorHidden(hidden: boolean, store?: FlagStore) {
49
+ try {
50
+ (store ?? localStorage).setItem(EDITOR_HIDDEN_KEY, hidden ? "1" : "0");
51
+ } catch {
52
+ // ignore quota / private mode
53
+ }
54
+ }
@@ -78,6 +78,7 @@ export function bindSessionPreview(options: {
78
78
  ...(grab.line ? { line: grab.line } : {}),
79
79
  ...(grab.column ? { column: grab.column } : {}),
80
80
  ...(grab.stack ? { stack: grab.stack } : {}),
81
+ ...(grab.field ? { field: grab.field } : {}),
81
82
  });
82
83
  },
83
84
  onPoint(on) {
@@ -17,6 +17,8 @@ export type ReplicaSchema = {
17
17
  id: string;
18
18
  version: number;
19
19
  branch?: string;
20
+ /** ISO time the snapshot was written. */
21
+ createdAt?: string;
20
22
  payload: SchemaPayload;
21
23
  } | null;
22
24
 
@@ -0,0 +1,45 @@
1
+ // packages/studio/src/sign-in-link.ts
2
+ // A magic-link email opens `/sign-in/link` in the Studio, not the API's
3
+ // verify endpoint. Mail scanners open every link in a message, and the token
4
+ // works once, so only a click on that page spends it.
5
+
6
+ export function isSignInLinkPath(pathname: string): boolean {
7
+ return pathname.replace(/\/$/, "") === "/sign-in/link";
8
+ }
9
+
10
+ /** The API URL that spends the token, or null when the link has none. */
11
+ export function signInLinkVerifyUrl(
12
+ apiBase: string,
13
+ search: string,
14
+ studioOrigin: string,
15
+ ): string | null {
16
+ const params = new URLSearchParams(search);
17
+ const token = params.get("token");
18
+ if (!token) return null;
19
+ const verify = new URL(`${apiBase}/api/auth/magic-link/verify`);
20
+ verify.searchParams.set("token", token);
21
+ // Without a callback better-auth answers JSON instead of redirecting.
22
+ verify.searchParams.set("callbackURL", params.get("callbackURL") || `${studioOrigin}/`);
23
+ for (const key of ["newUserCallbackURL", "errorCallbackURL"]) {
24
+ const value = params.get(key);
25
+ if (value) verify.searchParams.set(key, value);
26
+ }
27
+ return verify.toString();
28
+ }
29
+
30
+ /** What to tell someone better-auth sent back with `?error=`. */
31
+ export function signInLinkError(code: string | null): string | null {
32
+ if (!code) return null;
33
+ if (code === "INVALID_TOKEN") {
34
+ return "This sign-in link has expired or was already used. Send yourself a new one.";
35
+ }
36
+ return "That sign-in link did not work. Send yourself a new one.";
37
+ }
38
+
39
+ /** The address without the error better-auth appended. */
40
+ export function withoutSignInLinkError(href: string): string {
41
+ const url = new URL(href);
42
+ url.searchParams.delete("error");
43
+ url.searchParams.delete("error_description");
44
+ return url.toString();
45
+ }
@@ -10,6 +10,8 @@ export type PointerGrab = {
10
10
  blockType: string | null;
11
11
  blockIndex: number | null;
12
12
  quote: string;
13
+ /** Block prop the clicked text came from, when the page marks it with `data-backmatter-field`. */
14
+ field: string | null;
13
15
  } & ElementOrigin;
14
16
 
15
17
  const EMPTY_ORIGIN: ElementOrigin = {
@@ -29,6 +31,16 @@ function presentAttr(el: Element, name: string): string | null {
29
31
  return value ? value : null;
30
32
  }
31
33
 
34
+ const FIELD_NAME = /^[\w.$-]{1,80}$/;
35
+
36
+ /** The prop named by the nearest `data-backmatter-field`, inside the block when there is one. */
37
+ function fieldOf(target: Element, marker: Element | null): string | null {
38
+ const holder = target.closest("[data-backmatter-field]");
39
+ if (!holder || (marker && holder !== marker && !marker.contains(holder))) return null;
40
+ const name = holder.getAttribute("data-backmatter-field");
41
+ return name && FIELD_NAME.test(name) ? name : null;
42
+ }
43
+
32
44
  /** Resolve the block marker and visible text under a click. Clicks on the bar are ignored. */
33
45
  export function grabAt(target: Element | null, bar: Element | null): PointerGrab | null {
34
46
  if (!target) return null;
@@ -42,7 +54,7 @@ export function grabAt(target: Element | null, bar: Element | null): PointerGrab
42
54
  const origin = readElementOrigin(target) ?? EMPTY_ORIGIN;
43
55
  if (!marker) {
44
56
  if (!quote && !origin.component && !origin.file) return null;
45
- return { blockId: null, blockType: null, blockIndex: null, quote, ...origin };
57
+ return { blockId: null, blockType: null, blockIndex: null, quote, field: fieldOf(target, null), ...origin };
46
58
  }
47
59
  const indexRaw = marker.getAttribute("data-backmatter-index");
48
60
  const blockIndex = indexRaw !== null && /^\d+$/.test(indexRaw) ? Number(indexRaw) : null;
@@ -51,6 +63,7 @@ export function grabAt(target: Element | null, bar: Element | null): PointerGrab
51
63
  blockType: presentAttr(marker, "data-backmatter-type"),
52
64
  blockIndex,
53
65
  quote,
66
+ field: fieldOf(target, marker),
54
67
  ...origin,
55
68
  };
56
69
  }