@backmatter/studio 0.0.25 → 0.0.26

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.
@@ -3,7 +3,7 @@ var st = (e, t, n) => t in e ? rt(e, t, { enumerable: !0, configurable: !0, writ
3
3
  var $ = (e, t, n) => st(e, typeof t != "symbol" ? t + "" : t, n);
4
4
  import { jsxs as w, jsx as i, Fragment as re } from "react/jsx-runtime";
5
5
  import { useRef as qe, useCallback as it, useSyncExternalStore as at, useState as E, useEffect as W, lazy as ot, Suspense as lt } from "react";
6
- import { X as Ie, V as R, k as ze, an as Be, ao as be, ap as ct, aq as ut, ar as Fe, as as Me, at as De, au as dt, av as ft, P as He, aw as ht, ax as ae, ah as K, Z as We, ay as xt, az as $e, ai as pt, ak as se, aa as Q, ab as Z, Y as oe, aA as gt, W as F, aB as mt, J as we, aC as ee, aj as yt, aD as vt, aE as bt, aF as wt, aG as kt, aH as St, f as Rt, aI as Et, a6 as _t, aJ as jt, aK as Tt, z as Pt, B as Ot, I as Lt, aL as Nt, aM as Ut, aN as At, K as Ct, aO as qt, R as It, L as zt, M as Bt, N as Ft, O as D, Q as Mt, U as Dt } from "./WorkspaceRoutes-DuwT2y7A.js";
6
+ import { X as Ie, V as R, k as ze, an as Be, ao as be, ap as ct, aq as ut, ar as Fe, as as Me, at as De, au as dt, av as ft, P as He, aw as ht, ax as ae, ah as K, Z as We, ay as xt, az as $e, ai as pt, ak as se, aa as Q, ab as Z, Y as oe, aA as gt, W as F, aB as mt, J as we, aC as ee, aj as yt, aD as vt, aE as bt, aF as wt, aG as kt, aH as St, f as Rt, aI as Et, a6 as _t, aJ as jt, aK as Tt, z as Pt, B as Ot, I as Lt, aL as Nt, aM as Ut, aN as At, K as Ct, aO as qt, R as It, L as zt, M as Bt, N as Ft, O as D, Q as Mt, U as Dt } from "./WorkspaceRoutes-DyjBryic.js";
7
7
  const te = /* @__PURE__ */ Object.create(null), G = (e) => {
8
8
  var t, n;
9
9
  return ((t = globalThis.process) == null ? void 0 : t.env) || ((n = globalThis.Deno) == null ? void 0 : n.env.toObject()) || globalThis.__env__ || (e ? te : globalThis);
@@ -1823,7 +1823,7 @@ function Or(e) {
1823
1823
  const t = e.replace(/\/$/, "") || "/";
1824
1824
  return t === "/__ui" || /^\/__ui\/[^/]+$/.test(t);
1825
1825
  }
1826
- const Lr = ot(() => import("./UiKitApp-BW_SpUgQ.js").then((e) => ({
1826
+ const Lr = ot(() => import("./UiKitApp-1D9pdRrI.js").then((e) => ({
1827
1827
  default: e.UiKitApp
1828
1828
  })));
1829
1829
  function Ir() {
@@ -1,7 +1,7 @@
1
1
  var Rs = Object.defineProperty;
2
2
  var Es = (r, e, t) => e in r ? Rs(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
3
3
  var M = (r, e, t) => Es(r, typeof e != "symbol" ? e + "" : e, t);
4
- import { aP as Bt, aQ as Bs, aR as a0, aS as ct, aT as xt, aU as ea, aV as Gn, aW as Is, aX as Ls, aY as Ds, aZ as La, a_ as Ps, a$ as Os, b0 as Le, b1 as qs } from "./WorkspaceRoutes-DuwT2y7A.js";
4
+ import { aP as Bt, aQ as Bs, aR as a0, aS as ct, aT as xt, aU as ea, aV as Gn, aW as Is, aX as Ls, aY as Ds, aZ as La, a_ as Ps, a$ as Os, b0 as Le, b1 as qs } from "./WorkspaceRoutes-DyjBryic.js";
5
5
  function Fs() {
6
6
  return {
7
7
  enter: {
package/dist/dashboard.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as a, i as s } from "./chunks/dashboard-RFDdTeMV.js";
2
- import { G as t, H as f } from "./chunks/WorkspaceRoutes-DuwT2y7A.js";
1
+ import { A as a, i as s } from "./chunks/dashboard-KULxBe3u.js";
2
+ import { G as t, H as f } from "./chunks/WorkspaceRoutes-DyjBryic.js";
3
3
  export {
4
4
  a as DashboardApp,
5
5
  t as configureStudio,
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { jsx as t, jsxs as u, Fragment as he } from "react/jsx-runtime";
2
2
  import { useLayoutEffect as pe, useEffect as p, useRef as ee, useState as m, useMemo as fe } from "react";
3
- import { i as te, T as ge, E as be, C as ye, a as we, b as ve, u as ke, D as V, c as ne, d as H, e as qe, f as re, g as W, h as ze, p as Ee, j as Ce, k as w, l as v, m as Ne, n as Se, o as L, s as Le, r as Pe, q as Re, t as je, v as Ue, w as Te, x as Me, y as $e, z as Fe, B as Be, A as Oe, S as Ae, F as De, G as ie, H as U, I as Ge, J as _e, K as Ie, R as Ke, L as Ve, M as He, N as We, O as P, P as X, Q as Xe, U as Je, V as J, W as Qe } from "./chunks/WorkspaceRoutes-DuwT2y7A.js";
4
- import { X as kt } from "./chunks/WorkspaceRoutes-DuwT2y7A.js";
3
+ import { i as te, T as ge, E as be, C as ye, a as we, b as ve, u as ke, D as V, c as ne, d as H, e as qe, f as re, g as W, h as ze, p as Ee, j as Ce, k as w, l as v, m as Ne, n as Se, o as L, s as Le, r as Pe, q as Re, t as je, v as Ue, w as Te, x as Me, y as $e, z as Fe, B as Be, A as Oe, S as Ae, F as De, G as ie, H as U, I as Ge, J as _e, K as Ie, R as Ke, L as Ve, M as He, N as We, O as P, P as X, Q as Xe, U as Je, V as J, W as Qe } from "./chunks/WorkspaceRoutes-DyjBryic.js";
4
+ import { X as kt } from "./chunks/WorkspaceRoutes-DyjBryic.js";
5
5
  import { u as Ye, S as Ze } from "./chunks/define-studio-DlYjgrwr.js";
6
6
  import { d as zt } from "./chunks/define-studio-DlYjgrwr.js";
7
7
  const R = {
package/dist/studio.css CHANGED
@@ -673,6 +673,10 @@
673
673
  aspect-ratio: 16 / 10;
674
674
  }
675
675
 
676
+ .x6grhm {
677
+ aspect-ratio: 3 / 4;
678
+ }
679
+
676
680
  .x1fx9mx7 {
677
681
  backdrop-filter: blur(28px) saturate(1.15);
678
682
  }
@@ -3264,6 +3268,10 @@
3264
3268
  width: min(1080px, 100vw - 32px);
3265
3269
  }
3266
3270
 
3271
+ .x1kbbaoq {
3272
+ width: min(320px, 70%);
3273
+ }
3274
+
3267
3275
  .x3bfboh {
3268
3276
  width: min(360px, 38vw);
3269
3277
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backmatter/studio",
3
- "version": "0.0.25",
3
+ "version": "0.0.26",
4
4
  "description": "The Backmatter editing surface: document editor, AI chat, publish. Mounted on your site or hosted on the dashboard.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -56,7 +56,7 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "@ai-sdk/react": "^4.0.100",
59
- "@backmatter/core": "^0.0.40",
59
+ "@backmatter/core": "^0.0.41",
60
60
  "@base-ui/react": "^1.6.0",
61
61
  "@central-icons-react/round-outlined-radius-2-stroke-1.5": "1.2.15",
62
62
  "@dnd-kit/abstract": "^0.5.0",
package/src/api.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // packages/studio/src/api.ts
2
- import type { Problem } from "@backmatter/core";
2
+ import type { MediaKind, Problem } from "@backmatter/core";
3
3
  import { replicaQuery, type ReplicaCache } from "./replica/cache";
4
4
  import type { ReplicaBody } from "./replica/types";
5
5
  import { apiCredentials, apiHeaders, apiUrl, reportUnauthorized } from "./studio-config";
@@ -210,6 +210,8 @@ export type WorkspaceUsage = {
210
210
 
211
211
  export type CatalogMedia = {
212
212
  id: string;
213
+ /** An image has variants and a thumbnail; a PDF is served whole. */
214
+ kind: MediaKind;
213
215
  filename: string;
214
216
  contentType: string;
215
217
  byteSize: number;
@@ -218,7 +220,9 @@ export type CatalogMedia = {
218
220
  alt: string;
219
221
  caption: string;
220
222
  url: string;
221
- thumbUrl: string;
223
+ /** Null for a PDF. */
224
+ thumbUrl: string | null;
225
+ /** Empty for a PDF. */
222
226
  variants: Record<string, string>;
223
227
  createdAt: string;
224
228
  };
@@ -374,6 +378,8 @@ export type SchemaField = {
374
378
  where?: Record<string, string | number | boolean>;
375
379
  /** For blocks fields: layout of the "Add block" picker. */
376
380
  picker?: BlockPickerView;
381
+ /** For media fields: the kinds it may hold. Absent means images only. */
382
+ accept?: MediaKind[];
377
383
  /** Guidance from the site developer: what goes here. */
378
384
  description?: string;
379
385
  };
@@ -1042,10 +1048,12 @@ export function deleteWorkspaceMcp(workspaceId: string, id: string) {
1042
1048
 
1043
1049
  export function fetchMedia(
1044
1050
  workspaceId: string,
1045
- input: { query?: string; cursor?: string } = {},
1051
+ input: { query?: string; cursor?: string; kinds?: readonly MediaKind[]; ids?: readonly string[] } = {},
1046
1052
  ) {
1047
1053
  const params = new URLSearchParams();
1054
+ if (input.ids) params.set("ids", input.ids.join(","));
1048
1055
  if (input.query) params.set("q", input.query);
1056
+ if (input.kinds?.length) params.set("kind", input.kinds.join(","));
1049
1057
  if (input.cursor) params.set("cursor", input.cursor);
1050
1058
  const query = params.size ? `?${params}` : "";
1051
1059
  return api<{ total: number; media: CatalogMedia[]; nextCursor: string | null }>(
@@ -1,7 +1,7 @@
1
1
  // packages/studio/src/pages/MediaFieldInput.tsx
2
- import { useCallback, useEffect, useRef, useState, type DragEvent, type KeyboardEvent } from "react";
2
+ import { useCallback, useEffect, useMemo, useRef, useState, type DragEvent, type KeyboardEvent } from "react";
3
3
  import { Dialog } from "@base-ui/react/dialog";
4
- import { mediaIdFromUrl, mediaVariantUrl } from "@backmatter/core";
4
+ import { isLegacyImageUrl, mediaIdFromUrl, mediaKindOf, mediaVariantUrl, type MediaKind } from "@backmatter/core";
5
5
  import * as stylex from "@stylexjs/stylex";
6
6
  import { fetchMedia, uploadMedia, type CatalogMedia, type SchemaField } from "../api";
7
7
  import { useOutletContext } from "react-router";
@@ -10,7 +10,8 @@ import { Button } from "../ui/Button";
10
10
  import { Text } from "../ui/Text";
11
11
  import { cx, isTransitioning } from "../ui/popup";
12
12
  import type { WorkspaceOutletContext } from "../workspace/types";
13
- import { rejectionReason } from "./media-grid";
13
+ import { isPdfMedia, rejectionReason } from "./media-grid";
14
+ import { PdfTile } from "./PdfTile";
14
15
  import {
15
16
  acceptedDrop,
16
17
  appendMediaUrls,
@@ -27,16 +28,26 @@ type PendingUpload = {
27
28
  key: string;
28
29
  filename: string;
29
30
  previewUrl: string;
31
+ pdf: boolean;
30
32
  };
31
33
 
32
34
  const hover = "@media (hover: hover)";
33
35
  const GALLERY_PER_ROW = 4;
34
36
 
35
- function thumbForUrl(url: string): string | null {
37
+ /**
38
+ * A 400px variant for an image; null for a PDF, for a URL that is not media,
39
+ * and for a /media/ URL whose kind the catalog has not told us yet. Only an
40
+ * /img/ URL is known to be an image without the catalog.
41
+ */
42
+ function thumbForUrl(url: string, details: CatalogMedia | null, catalogLoaded: boolean): string | null {
36
43
  const id = mediaIdFromUrl(url);
37
- return id ? mediaVariantUrl(CDN_ORIGIN, id, 400) : null;
44
+ if (!id) return null;
45
+ if (details ? isPdfMedia(details) : !catalogLoaded && !isLegacyImageUrl(url)) return null;
46
+ return mediaVariantUrl(CDN_ORIGIN, id, 400);
38
47
  }
39
48
 
49
+ const IMAGES_ONLY: readonly MediaKind[] = ["image"];
50
+
40
51
  export function MediaFieldInput({
41
52
  field,
42
53
  value,
@@ -51,6 +62,10 @@ export function MediaFieldInput({
51
62
  }) {
52
63
  const { workspace } = useOutletContext<WorkspaceOutletContext>();
53
64
  const multiple = field.multiple === true;
65
+ const accept = field.accept?.length ? field.accept : IMAGES_ONLY;
66
+ const acceptKey = accept.join(",");
67
+ const kinds = useMemo(() => acceptKey.split(",") as MediaKind[], [acceptKey]);
68
+ const noun = kinds.includes("pdf") ? "file" : "image";
54
69
  const parsed = editorUrls(value, multiple);
55
70
  const savedUrls = parsed.urls;
56
71
 
@@ -101,7 +116,7 @@ export function MediaFieldInput({
101
116
  const accepted: File[] = [];
102
117
  const rejected: string[] = [];
103
118
  for (const file of files) {
104
- const reason = rejectionReason(file);
119
+ const reason = rejectionReason(file, kinds);
105
120
  if (reason) rejected.push(reason);
106
121
  else accepted.push(file);
107
122
  }
@@ -118,6 +133,7 @@ export function MediaFieldInput({
118
133
  key: crypto.randomUUID(),
119
134
  filename: file.name,
120
135
  previewUrl: URL.createObjectURL(file),
136
+ pdf: mediaKindOf(file.type) === "pdf",
121
137
  file,
122
138
  }));
123
139
  setPending((current) => [
@@ -126,6 +142,7 @@ export function MediaFieldInput({
126
142
  key: item.key,
127
143
  filename: item.filename,
128
144
  previewUrl: item.previewUrl,
145
+ pdf: item.pdf,
129
146
  })),
130
147
  ]);
131
148
 
@@ -149,7 +166,7 @@ export function MediaFieldInput({
149
166
  });
150
167
  }
151
168
  },
152
- [multiple, readOnly, workspace.id, write],
169
+ [multiple, readOnly, workspace.id, write, kinds],
153
170
  );
154
171
 
155
172
  const onFieldDrop = useCallback(
@@ -210,6 +227,8 @@ export function MediaFieldInput({
210
227
  const selectedUrl = showThumb ? savedUrls[0]! : null;
211
228
  const catalogKey = savedUrls.map((url) => mediaIdFromUrl(url) ?? "").join("\n");
212
229
  const [catalog, setCatalog] = useState<CatalogMedia[]>([]);
230
+ const [loadedKey, setLoadedKey] = useState<string | null>(null);
231
+ const catalogLoaded = loadedKey === catalogKey;
213
232
 
214
233
  useEffect(() => {
215
234
  if (!catalogKey) {
@@ -217,12 +236,17 @@ export function MediaFieldInput({
217
236
  return;
218
237
  }
219
238
  let cancelled = false;
220
- void fetchMedia(workspace.id)
239
+ // The URL does not say image or PDF; the catalog rows for these ids do.
240
+ const ids = [...new Set(catalogKey.split("\n").filter(Boolean))];
241
+ void fetchMedia(workspace.id, { ids })
221
242
  .then((page) => {
222
243
  if (!cancelled) setCatalog(page.media);
223
244
  })
224
245
  .catch(() => {
225
246
  if (!cancelled) setCatalog([]);
247
+ })
248
+ .finally(() => {
249
+ if (!cancelled) setLoadedKey(catalogKey);
226
250
  });
227
251
  return () => {
228
252
  cancelled = true;
@@ -233,6 +257,11 @@ export function MediaFieldInput({
233
257
  const id = mediaIdFromUrl(url);
234
258
  return id ? catalog.find((item) => item.id === id) ?? null : null;
235
259
  };
260
+ const isPdfUrl = (url: string) => {
261
+ const details = detailsFor(url);
262
+ return details ? isPdfMedia(details) : false;
263
+ };
264
+ const thumbFor = (url: string) => thumbForUrl(url, detailsFor(url), catalogLoaded);
236
265
  const leadDetails = selectedUrl ? detailsFor(selectedUrl) : null;
237
266
  const galleryFilled = multiple && (showThumb || pending.length > 0);
238
267
  const hiddenCount = multiple && showThumb ? Math.max(0, savedUrls.length - GALLERY_PER_ROW) : 0;
@@ -251,13 +280,13 @@ export function MediaFieldInput({
251
280
  <div {...stylex.props(styles.galleryStack)}>
252
281
  <div ref={gridRef} data-media-grid {...stylex.props(styles.galleryGrid)}>
253
282
  {galleryUrls.map((url, index) => {
254
- const thumb = thumbForUrl(url);
283
+ const thumb = thumbFor(url);
255
284
  return (
256
285
  <div
257
286
  key={`${url}-${index}`}
258
287
  data-media-thumb
259
288
  role="group"
260
- aria-label={`Image ${index + 1} of ${savedUrls.length}`}
289
+ aria-label={`${noun === "image" ? "Image" : "File"} ${index + 1} of ${savedUrls.length}`}
261
290
  aria-keyshortcuts={readOnly ? undefined : "Alt+ArrowLeft Alt+ArrowRight"}
262
291
  tabIndex={readOnly ? undefined : 0}
263
292
  draggable={!readOnly}
@@ -280,7 +309,9 @@ export function MediaFieldInput({
280
309
  }}
281
310
  onDrop={(event) => onThumbDrop(index, event)}
282
311
  >
283
- {thumb ? (
312
+ {isPdfUrl(url) ? (
313
+ <PdfTile size="sm" xstyle={styles.galleryTile} />
314
+ ) : thumb ? (
284
315
  <img src={thumb} alt="" draggable={false} {...stylex.props(styles.galleryTile)} />
285
316
  ) : (
286
317
  <div {...stylex.props(styles.galleryTile, styles.moreEmpty)} />
@@ -288,7 +319,7 @@ export function MediaFieldInput({
288
319
  {readOnly || (field.required === true && savedUrls.length === 1) ? null : (
289
320
  <button
290
321
  type="button"
291
- aria-label="Remove image"
322
+ aria-label={`Remove ${noun}`}
292
323
  {...stylex.props(styles.galleryRemove)}
293
324
  onClick={() => removeAt(index)}
294
325
  >
@@ -300,13 +331,17 @@ export function MediaFieldInput({
300
331
  })}
301
332
  {pending.map((item) => (
302
333
  <div key={item.key} {...stylex.props(styles.thumbWrap)}>
303
- <img src={item.previewUrl} alt="" {...stylex.props(styles.galleryTile, styles.pending)} />
334
+ {item.pdf ? (
335
+ <PdfTile size="sm" xstyle={[styles.galleryTile, styles.pending]} />
336
+ ) : (
337
+ <img src={item.previewUrl} alt="" {...stylex.props(styles.galleryTile, styles.pending)} />
338
+ )}
304
339
  </div>
305
340
  ))}
306
341
  {readOnly ? null : (
307
342
  <button
308
343
  type="button"
309
- aria-label="Add images"
344
+ aria-label={`Add ${noun}s`}
310
345
  {...stylex.props(styles.galleryTile, styles.addTile)}
311
346
  onClick={openModal}
312
347
  >
@@ -327,6 +362,8 @@ export function MediaFieldInput({
327
362
  ) : multiple && pending[0] ? (
328
363
  <FileCard
329
364
  src={pending[0].previewUrl}
365
+ pdf={pending[0].pdf}
366
+ noun={noun}
330
367
  name={pending[0].filename}
331
368
  meta="Uploading"
332
369
  readOnly
@@ -337,11 +374,13 @@ export function MediaFieldInput({
337
374
  ) : multiple ? (
338
375
  <div {...stylex.props(styles.thumbRow)} />
339
376
  ) : wrongShapeOne ? (
340
- <Text tone="muted">Choose one image</Text>
377
+ <Text tone="muted">{`Choose one ${noun}`}</Text>
341
378
  ) : showThumb ? (
342
379
  <FileCard
343
- src={thumbForUrl(selectedUrl!) ?? selectedUrl!}
344
- name={leadDetails?.filename ?? "Image"}
380
+ src={thumbFor(selectedUrl!)}
381
+ pdf={isPdfUrl(selectedUrl!)}
382
+ noun={noun}
383
+ name={leadDetails?.filename ?? (isPdfUrl(selectedUrl!) ? "PDF" : "Image")}
345
384
  meta={leadDetails ? mediaMeta(leadDetails) : null}
346
385
  readOnly={readOnly}
347
386
  required={field.required === true}
@@ -351,6 +390,8 @@ export function MediaFieldInput({
351
390
  ) : pending[0] ? (
352
391
  <FileCard
353
392
  src={pending[0].previewUrl}
393
+ pdf={pending[0].pdf}
394
+ noun={noun}
354
395
  name={pending[0].filename}
355
396
  meta="Uploading"
356
397
  readOnly
@@ -359,7 +400,7 @@ export function MediaFieldInput({
359
400
  onRemove={() => undefined}
360
401
  />
361
402
  ) : (
362
- <div {...stylex.props(styles.placeholder)}>No image</div>
403
+ <div {...stylex.props(styles.placeholder)}>{`No ${noun}`}</div>
363
404
  )}
364
405
  {readOnly || galleryFilled || (!multiple && showThumb && !wrongShapeOne) ? null : (
365
406
  <Button variant="secondary" onClick={openModal}>
@@ -400,6 +441,7 @@ export function MediaFieldInput({
400
441
  <div {...stylex.props(styles.gallery)}>
401
442
  <MediaGalleryPage
402
443
  pick
444
+ accept={kinds}
403
445
  pickedUrls={checkUrls}
404
446
  onToggleUrl={
405
447
  multiple
@@ -434,6 +476,8 @@ export function MediaFieldInput({
434
476
 
435
477
  function FileCard({
436
478
  src,
479
+ pdf,
480
+ noun,
437
481
  name,
438
482
  meta,
439
483
  readOnly,
@@ -441,7 +485,11 @@ function FileCard({
441
485
  onEdit,
442
486
  onRemove,
443
487
  }: {
444
- src: string;
488
+ /** Null while the kind is unknown: a blank thumbnail, never a broken image. */
489
+ src: string | null;
490
+ /** Show the PDF tile in place of an image thumbnail. */
491
+ pdf: boolean;
492
+ noun: string;
445
493
  name: string;
446
494
  meta: string | null;
447
495
  readOnly?: boolean;
@@ -451,20 +499,26 @@ function FileCard({
451
499
  }) {
452
500
  return (
453
501
  <div {...stylex.props(styles.fileCard)} data-media-file>
454
- <img src={src} alt="" {...stylex.props(styles.fileThumb)} />
502
+ {pdf ? (
503
+ <PdfTile size="sm" xstyle={styles.fileThumb} />
504
+ ) : src ? (
505
+ <img src={src} alt="" {...stylex.props(styles.fileThumb)} />
506
+ ) : (
507
+ <div {...stylex.props(styles.fileThumb)} />
508
+ )}
455
509
  <div {...stylex.props(styles.fileText)}>
456
510
  <span {...stylex.props(styles.fileName)}>{name}</span>
457
511
  {meta ? <span {...stylex.props(styles.fileMeta)}>{meta}</span> : null}
458
512
  </div>
459
513
  {readOnly ? null : (
460
514
  <div {...stylex.props(styles.fileActions)}>
461
- <button type="button" aria-label="Edit image" {...stylex.props(styles.iconBtn)} onClick={onEdit}>
515
+ <button type="button" aria-label={`Edit ${noun}`} {...stylex.props(styles.iconBtn)} onClick={onEdit}>
462
516
  <PencilIcon />
463
517
  </button>
464
518
  {required ? null : (
465
519
  <button
466
520
  type="button"
467
- aria-label="Remove image"
521
+ aria-label={`Remove ${noun}`}
468
522
  {...stylex.props(styles.iconBtn)}
469
523
  onClick={onRemove}
470
524
  >
@@ -9,6 +9,7 @@ import {
9
9
  import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
10
10
  import { useOutletContext, useSearchParams } from "react-router";
11
11
  import * as stylex from "@stylexjs/stylex";
12
+ import { MEDIA_KINDS, mediaKindOf, type MediaKind } from "@backmatter/core";
12
13
  import { deleteMedia, describeMedia, fetchMedia, uploadMedia } from "../api";
13
14
  import { Input } from "../ui/Input";
14
15
  import { colors, radius, space, type, z } from "../styles/tokens.stylex";
@@ -23,7 +24,9 @@ import {
23
24
  describeMedia as rememberDescription,
24
25
  emptyMediaGrid,
25
26
  failUpload,
27
+ fileInputAccept,
26
28
  finishUpload,
29
+ isPdfMedia,
27
30
  lightboxImageId,
28
31
  mediaIdAfterRemoval,
29
32
  nextMediaIndex,
@@ -37,6 +40,7 @@ import {
37
40
  type PendingUpload,
38
41
  } from "./media-grid";
39
42
  import { MediaLightbox } from "./MediaLightbox";
43
+ import { PdfTile } from "./PdfTile";
40
44
 
41
45
  const CELL = 168;
42
46
  const hover = "@media (hover: hover)";
@@ -46,12 +50,18 @@ export function MediaGalleryPage({
46
50
  onPick,
47
51
  pickedUrls,
48
52
  onToggleUrl,
53
+ accept = MEDIA_KINDS,
49
54
  }: {
50
55
  pick?: boolean;
51
56
  onPick?: (url: string) => void;
52
57
  pickedUrls?: string[];
53
58
  onToggleUrl?: (url: string) => void;
59
+ /** Kinds to list and to take as uploads. The library page takes every kind. */
60
+ accept?: readonly MediaKind[];
54
61
  }) {
62
+ // Callers may pass a fresh array each render; the joined list is the identity.
63
+ const acceptKey = accept.join(",");
64
+ const kinds = useMemo(() => acceptKey.split(",") as MediaKind[], [acceptKey]);
55
65
  const { workspace } = useOutletContext<WorkspaceOutletContext>();
56
66
  const [searchParams, setSearchParams] = useSearchParams();
57
67
  const [state, setState] = useState<MediaGridState>(emptyMediaGrid);
@@ -99,7 +109,11 @@ export function MediaGalleryPage({
99
109
  loadingPage.current = true;
100
110
  if (!cursor) setState((current) => ({ ...current, nextCursor: null }));
101
111
  try {
102
- const page = await fetchMedia(workspace.id, { query: query || undefined, cursor });
112
+ const page = await fetchMedia(workspace.id, {
113
+ query: query || undefined,
114
+ cursor,
115
+ ...(kinds.length < MEDIA_KINDS.length ? { kinds } : {}),
116
+ });
103
117
  if (ticket !== request.current) return;
104
118
  setState((current) => receivePage(current, page, cursor ? "append" : "replace"));
105
119
  setError(null);
@@ -113,7 +127,7 @@ export function MediaGalleryPage({
113
127
  }
114
128
  }
115
129
  },
116
- [query, workspace.id],
130
+ [query, workspace.id, kinds],
117
131
  );
118
132
 
119
133
  useEffect(() => {
@@ -133,7 +147,7 @@ export function MediaGalleryPage({
133
147
  const accepted: File[] = [];
134
148
  const names: string[] = [];
135
149
  for (const file of files) {
136
- const reason = rejectionReason(file);
150
+ const reason = rejectionReason(file, kinds);
137
151
  if (reason) names.push(reason);
138
152
  else accepted.push(file);
139
153
  }
@@ -143,6 +157,7 @@ export function MediaGalleryPage({
143
157
  key: crypto.randomUUID(),
144
158
  filename: file.name,
145
159
  previewUrl: URL.createObjectURL(file),
160
+ kind: mediaKindOf(file.type),
146
161
  file,
147
162
  }));
148
163
  setState((current) => beginUploads(current, items));
@@ -161,17 +176,17 @@ export function MediaGalleryPage({
161
176
  });
162
177
  }
163
178
  },
164
- [workspace.id],
179
+ [workspace.id, kinds],
165
180
  );
166
181
 
167
182
  const chooseFiles = useCallback(() => {
168
183
  const input = document.createElement("input");
169
184
  input.type = "file";
170
- input.accept = "image/jpeg,image/png,image/webp,image/gif,image/avif";
185
+ input.accept = fileInputAccept(kinds);
171
186
  input.multiple = true;
172
187
  input.onchange = () => uploadFiles(Array.from(input.files ?? []));
173
188
  input.click();
174
- }, [uploadFiles]);
189
+ }, [uploadFiles, kinds]);
175
190
 
176
191
  useEffect(() => {
177
192
  const hasFiles = (event: DragEvent) =>
@@ -436,7 +451,7 @@ export function MediaGalleryPage({
436
451
  >
437
452
  {showEmpty && query ? (
438
453
  <div {...stylex.props(styles.emptyState)}>
439
- <Text tone="muted">No images match this search.</Text>
454
+ <Text tone="muted">No media matches this search.</Text>
440
455
  </div>
441
456
  ) : showEmpty ? (
442
457
  <div
@@ -453,10 +468,19 @@ export function MediaGalleryPage({
453
468
  <IconCloudUpload size={22} ariaHidden />
454
469
  </div>
455
470
  <Text as="h2" size="lg" weight="medium">
456
- Drop images to upload
471
+ {kinds.includes("image")
472
+ ? kinds.includes("pdf")
473
+ ? "Drop images or PDFs to upload"
474
+ : "Drop images to upload"
475
+ : "Drop PDFs to upload"}
457
476
  </Text>
458
477
  <Text tone="muted" size="sm">
459
- JPEG, PNG, WebP, GIF, and AVIF, up to 20 MB.
478
+ {`${[
479
+ kinds.includes("image") ? "JPEG, PNG, WebP, GIF, AVIF" : null,
480
+ kinds.includes("pdf") ? "PDF" : null,
481
+ ]
482
+ .filter(Boolean)
483
+ .join(", ")}, up to 20 MB.`}
460
484
  </Text>
461
485
  <div {...stylex.props(styles.emptyAction)}>
462
486
  <Button variant="secondary" onClick={chooseFiles}>
@@ -474,7 +498,11 @@ export function MediaGalleryPage({
474
498
  >
475
499
  {cell.kind === "pending" ? (
476
500
  <figure {...stylex.props(styles.figure, styles.placed)}>
477
- <img src={cell.item.previewUrl} alt="" {...stylex.props(styles.image, styles.dimmed)} />
501
+ {cell.item.kind === "pdf" ? (
502
+ <PdfTile name={cell.item.filename} xstyle={[styles.image, styles.dimmed]} />
503
+ ) : (
504
+ <img src={cell.item.previewUrl} alt="" {...stylex.props(styles.image, styles.dimmed)} />
505
+ )}
478
506
  {cell.item.status === "error" ? (
479
507
  <figcaption {...stylex.props(styles.caption)}>{cell.item.error}</figcaption>
480
508
  ) : (
@@ -590,7 +618,11 @@ function MediaHit({
590
618
  )}
591
619
  onClick={onOpen}
592
620
  >
593
- <img src={item.thumbUrl} alt={item.alt?.trim() || item.filename} {...stylex.props(styles.image)} />
621
+ {isPdfMedia(item) || !item.thumbUrl ? (
622
+ <PdfTile name={item.filename} xstyle={styles.image} />
623
+ ) : (
624
+ <img src={item.thumbUrl} alt={item.alt?.trim() || item.filename} {...stylex.props(styles.image)} />
625
+ )}
594
626
  </button>
595
627
  );
596
628
  if (!menu) {