Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: extract useUniverseGallery hook from UniverseBuilder page (#2532)

Adam Eivy8244ccb1763a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 548d87c91b..87a586b0a3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -51,4 +51,5 @@
- **[issue-2525] Extract shared `migrationMarker` helpers using `atomicWrite`.** Eleven boot-time migration/repair/reconcile scripts under `server/scripts/` each hand-rolled `markerExists`/`readMarker`/`writeMarker` on top of `readFile(...).catch(() => null)` and a non-atomic `writeFile(JSON.stringify(...))`, so a crash mid-write could leave a truncated marker a later boot misreads as "not applied." The three helpers now live once in `server/lib/migrationMarker.js` (anchored under `PATHS.data`, built on the existing `tryReadFile`/`atomicWrite`/`safeJSONParse`), are barrel- and README-cataloged, and carry their own unit test. Marker filenames, gate semantics, and payloads are unchanged; the write path is now atomic (temp file + rename).
- **[issue-2522] Deep-link Tribe tabs and fix form label associations.** The Tribe page's active section (Circle / Map / Care Queue / Focus) lived in local `useState`, so a section couldn't be shared, bookmarked, or survive a reload. It now reads from a `?tab=` URL search param (default `circle` omitted for a clean `/tribe`) with a valid-tab fallback for stale/unknown values — matching the PromptManager convention. Separately, the `StylePresetPicker` style-preset `<label>` and the Loops "Interval" `<label>` had no `htmlFor`/`id` pairing; both now associate with their control via a `useId()`-generated id so click-to-focus and screen readers work.
- **[issue-2527] Route client localStorage and keyboard activation through the shared `safeStorage`/`a11yKeyboard` helpers.** Several client sites bypassed the guarded `safeStorage` helpers with raw `window.localStorage` + hand-rolled `try/catch` (or `typeof window` guards), and several non-`<button>` clickables reimplemented the Enter/Space `onKeyDown` handler inline. Storage reads/writes in `Security.jsx`, `PipelineManuscriptEditor.jsx`, `voiceVisibility.js`, `MortalLoomBanner.jsx`, `WhileAwayWidget.jsx`, and `ManuscriptReadAloud.jsx` now go through `safeReadStorage`/`safeReadJsonStorage`/`safeWriteStorage`/`safeRemoveStorage`; keyboard activation in `IngredientPicker.jsx`, `ManuscriptReadAloud.jsx`, `EditorialHealthPanel.jsx`, `TribeCircleMap.jsx`, and `GenomeTab.jsx` now spreads `clickableProps(handler)` (which supplies `role`/`tabIndex`/`onKeyDown` via the shared `onActivateKeyDown`). Behavior is preserved — same storage keys, same JSON-parse fallbacks and corrupt-entry cleanup, same Enter/Space activation.
+- **[issue-2532] Extract the Universe Builder's page-level lightbox into a `useUniverseGallery` hook.** `UniverseBuilder.jsx` inlined ~160 lines of gallery/preview plumbing — the filename→image-sidecar metadata map, the `listImageGallery()` refetch effect (keyed on `runs.length` + a per-job-completion bump), the `previewItems` derivation across variations/composite sheets/style probes/canon+character-sheet refs (namespaced-key dedupe), and the `usePreviewRoute`/`useMediaPreviewActions`/`useMediaAnnotations` wiring. That cohesive concern now lives in `client/src/hooks/useUniverseGallery.js` (takes `{ draft, runsLength }`, returns `{ previewItems, preview, setPreview, previewActions, openPreviewByFilename, openVariationPreview, annotations, updateAnnotation, bumpGalleryRefresh }`), thinning the page shell toward the WritersRoom pattern. Pure structural refactor — behavior identical, no route-contract change; the UniverseBuilder page suite and hooks barrel test stay green. Further hook/panel extractions (draft/expand/canon/bulk-render for UniverseBuilder, `useShellSession` for Shell) remain.
- **[issue-2545] Add `aria-label`s to icon-only controls and fix Templates/MessageDetail form labels.** Several icon-only buttons exposed their purpose only via `title` (unreliable for screen readers): the MessageDetail toolbar (Reply, voice-mode toggle, AI Reply, Refresh, Archive, Delete), MusicVideo scene move-up/move-down/delete, MediaCard hide/delete, the MediaJobsQueue per-job cancel, Review's edit save/cancel, and DuplicateGroup rename now carry an `aria-label` matching their `title`. The MessageDetail reply `<textarea>` (previously placeholder-only) gains an `aria-label`, and the Templates "Target Directory" `<label>` is now wired to its input via `htmlFor`/`id` so click-to-focus and screen readers work. Accessibility attributes only — no behavior or styling change.
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index f7d3e0a43a..d9da893681 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -151,6 +151,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useRenderJobQueue` | Per-entry render-job queue for the Universe Builder — `pendingByEntryId` (entryId → jobId[]), `pendingHeadByEntryId` (first jobId per entry for single-subscription thumbs), `enqueueEntryJobs` (append variation/canon jobs), `clearPendingForEntry` (shift a jobId out, or drop the entry). | Universe Builder render orchestration. Don't re-roll the per-entry pending-jobs reducer. |
| `useUniverse` | Loads the universe record for a `universeId` with mount/cancel guards; returns `[universe, setUniverse, loading, error]` (setter exposed for optimistic post-mutation updates). | Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. |
| `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |
+| `useUniverseGallery` | Page-level lightbox + gallery-metadata concern for the Universe Builder. Takes `{ draft, runsLength }`; hydrates a filename→sidecar map (prompt/seed/model), derives `previewItems` across variations, composite sheets, style probes, and canon/character-sheet refs (namespaced-key dedupe), and wires `usePreviewRoute` + `useMediaPreviewActions` + `useMediaAnnotations`. Returns `{ previewItems, preview, setPreview, previewActions, openPreviewByFilename, openVariationPreview, annotations, updateAnnotation, bumpGalleryRefresh }`. | Universe Builder image lightbox — don't re-roll the gallery-sidecar/previewItems derivation. |
| `useUniverseNav` | `goToWorld(id)` → navigate to `/universes/:id`, preserve `location.search`. | Any Universe Builder caller that needs to switch worlds via URL. |
| `useVoiceUiSync` | Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. |
| `useMoltworldWs` | Moltworld WebSocket feed. | Moltworld surfaces only. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 29ba960d0a..926f4ee7e2 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -46,6 +46,7 @@ export { default as useRowDraft } from './useRowDraft.js';
export { default as useTheme } from './useTheme.js';
export { default as useUniverse } from './useUniverse.js';
export { default as useUniverseAction } from './useUniverseAction.js';
+export { default as useUniverseGallery } from './useUniverseGallery.js';
export { default as useVideoDownload } from './useVideoDownload.js';
export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';
export { default as useReferenceAudioImport } from './useReferenceAudioImport.js';
diff --git a/client/src/hooks/useUniverseGallery.js b/client/src/hooks/useUniverseGallery.js
new file mode 100644
index 0000000000..705f1001bd
--- /dev/null
+++ b/client/src/hooks/useUniverseGallery.js
@@ -0,0 +1,209 @@
+import { useState, useEffect, useMemo, useCallback } from 'react';
+import { listImageGallery } from '../services/apiImageVideo';
+import { descriptorForCanonEntry } from '../lib/canonPrompt';
+import { listSheetPointers } from '../lib/sheetPointers';
+import usePreviewRoute from './usePreviewRoute';
+import useMediaPreviewActions from './useMediaPreviewActions';
+import { useMediaAnnotations } from './useMediaAnnotations';
+
+// Page-level lightbox + gallery-metadata concern for the Universe Builder.
+// Extracted from UniverseBuilder.jsx (#2532) so the route shell stays thin.
+// A single MediaPreview at this level covers EVERY thumb on the page:
+// variations, composite sheets, canon imageRefs, style probes, and character
+// reference sheets — so clicking any image opens the same full-detail modal
+// History / Collections / ImageGen use, with the same actions (Refine / Remix
+// / SendToVideo / Clean / AddToCollection / Download / notes).
+//
+// Inputs:
+// - draft: the editable universe draft. `previewItems` is derived from its
+// categories / compositeSheets / styleImageRefs / canon arrays.
+// - runsLength: `runs.length` — advances on initial-load and queue-time, used
+// (alongside `galleryRefreshKey`) to trigger the gallery-metadata refetch.
+//
+// Returns the full preview/gallery bundle the page wires into UI:
+// previewItems, preview, setPreview, previewActions,
+// openPreviewByFilename, openVariationPreview, annotations, updateAnnotation,
+// bumpGalleryRefresh.
+export default function useUniverseGallery({ draft, runsLength }) {
+ // Filename → full image-metadata-sidecar record (prompt, negativePrompt,
+ // modelId, width, height, seed, etc.). Hydrates `previewItems` with the
+ // ACTUAL prompt that was used to render the image — without this the
+ // modal would only see the variation's label, and Refine Prompt / Remix
+ // / Send to Video would all open with empty fields. Loaded once per
+ // mount via `listImageGallery()` (the same call the History page uses)
+ // and refreshed whenever a render completes (universe `runs` advances).
+ const [galleryByFilename, setGalleryByFilename] = useState(() => new Map());
+ // Bumped on every job completion so the gallery-metadata fetch below
+ // re-runs once the new sidecar exists on disk. Keying the fetch only on
+ // `runs.length` was insufficient: that advances when a run is queued or
+ // loaded, NOT when one of its jobs completes — so a freshly rendered
+ // thumb would open the lightbox with label-only metadata until a full
+ // page reload.
+ const [galleryRefreshKey, setGalleryRefreshKey] = useState(0);
+ const bumpGalleryRefresh = useCallback(() => setGalleryRefreshKey((k) => k + 1), []);
+ useEffect(() => {
+ let cancelled = false;
+ listImageGallery().then((list) => {
+ if (cancelled) return;
+ const map = new Map();
+ for (const item of Array.isArray(list) ? list : []) {
+ if (item?.filename) map.set(item.filename, item);
+ }
+ setGalleryByFilename(map);
+ }).catch(() => { /* non-fatal; modal falls back to filename-only display */ });
+ return () => { cancelled = true; };
+ // `runsLength` covers initial-load and queue-time; `galleryRefreshKey`
+ // covers per-job completion (see bumpGalleryRefresh callers).
+ }, [runsLength, galleryRefreshKey]);
+ const { annotations, updateAnnotation } = useMediaAnnotations();
+ const previewItems = useMemo(() => {
+ const out = [];
+ // Dedupe by full namespaced key (`image:<filename>` vs
+ // `canon-sheet:<filename>`) so a gallery image and a character reference
+ // sheet that share a basename can coexist in the items list — without the
+ // namespace, the first-pushed item would suppress the second and the
+ // preview-URL resolver would never see the other asset.
+ const seen = new Set();
+ const pushFilename = (filename, label) => {
+ if (typeof filename !== 'string' || !filename) return;
+ const key = `image:${filename}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ // Pull the real prompt + render settings out of the gallery metadata
+ // map when available so the lightbox shows the full prompt that was
+ // sent to the renderer (with universe style influences, variation
+ // prompt fragment, etc.), not just the row's display label.
+ // Falls back to the label-only shape for filenames not in the gallery
+ // (legacy renders or pending re-fetch).
+ const meta = galleryByFilename.get(filename) || null;
+ out.push({
+ // Same `image:<filename>` key normalizeImage() stamps everywhere
+ // else — History, Collections, ImageGen — so a star/note added
+ // from this lightbox is the SAME annotation record those pages
+ // already read. A page-local key would silently fork the user's
+ // favorites by surface.
+ key: `image:${filename}`,
+ kind: 'image',
+ filename,
+ previewUrl: `/data/images/${filename}`,
+ downloadUrl: `/data/images/${filename}`,
+ prompt: meta?.prompt || label || filename,
+ negativePrompt: meta?.negativePrompt || null,
+ modelId: meta?.modelId || meta?.model || null,
+ width: meta?.width ?? null,
+ height: meta?.height ?? null,
+ seed: meta?.seed ?? null,
+ steps: meta?.steps ?? null,
+ guidance: meta?.guidance ?? null,
+ quantize: meta?.quantize ?? null,
+ // `raw` carries the original sidecar so MediaLightbox's "Refine
+ // Prompt" / clean / remix downstream handlers can pull any field
+ // the spec doesn't surface at the top level.
+ raw: meta,
+ });
+ };
+ const cats = draft?.categories && typeof draft.categories === 'object' ? draft.categories : {};
+ for (const [bucketKey, bucket] of Object.entries(cats)) {
+ const variations = Array.isArray(bucket?.variations) ? bucket.variations : [];
+ for (const v of variations) {
+ const refs = Array.isArray(v?.imageRefs) ? v.imageRefs : [];
+ for (const f of refs) pushFilename(f, `${bucketKey} · ${v.label}`);
+ }
+ }
+ const sheets = Array.isArray(draft?.compositeSheets) ? draft.compositeSheets : [];
+ for (const s of sheets) {
+ const refs = Array.isArray(s?.imageRefs) ? s.imageRefs : [];
+ for (const f of refs) pushFilename(f, `Composite · ${s.label}`);
+ }
+ // Base style probe renders — same `image:<filename>` namespace so the
+ // lightbox finds them and reuses the gallery sidecar metadata.
+ const styleRefs = Array.isArray(draft?.styleImageRefs) ? draft.styleImageRefs : [];
+ for (const f of styleRefs) pushFilename(f, 'Base style');
+ // Canon refs — characters / places / objects. Hydrate from the gallery
+ // sidecar so the modal shows the ACTUAL render prompt (the same one the
+ // History page sees), not just the character description. The descriptor
+ // string is only used as a fallback label when no sidecar exists (legacy
+ // canon renders without metadata). Character reference sheets live in a
+ // different static prefix (`/data/image-refs/`) so they get a dedicated
+ // `canon-sheet:<filename>` key + don't collide with gallery entries.
+ const canonKinds = [
+ { key: 'characters', singular: 'character' },
+ { key: 'places', singular: 'place' },
+ { key: 'objects', singular: 'object' },
+ ];
+ for (const kind of canonKinds) {
+ const list = Array.isArray(draft?.[kind.key]) ? draft[kind.key] : [];
+ for (const entry of list) {
+ const descriptor = descriptorForCanonEntry(kind.key, entry) || '';
+ const fallbackLabel = `${entry.name}${descriptor ? `: ${descriptor}` : ''}`;
+ const refs = Array.isArray(entry?.imageRefs) ? entry.imageRefs : [];
+ for (const f of refs) pushFilename(f, fallbackLabel);
+ if (kind.key === 'characters') {
+ for (const { variant, filename } of listSheetPointers(entry)) {
+ const sheetKey = `canon-sheet:${variant}:${filename}`;
+ if (seen.has(sheetKey)) continue;
+ seen.add(sheetKey);
+ out.push({
+ key: sheetKey,
+ kind: 'image',
+ filename,
+ previewUrl: `/data/image-refs/${filename}`,
+ downloadUrl: `/data/image-refs/${filename}`,
+ prompt: `${entry.name} — character reference sheet (${variant})`,
+ });
+ }
+ }
+ }
+ }
+ return out;
+ }, [draft, galleryByFilename]);
+ const [preview, setPreview] = usePreviewRoute(previewItems);
+ // Shared preview action handlers (Remix / SendToVideo / Clean) so the
+ // universe lightbox opens the same downstream pages with the same params
+ // as the History grid + Image Gen page. `onCleanComplete` splices the
+ // cleaned image into the local gallery map so the next preview open
+ // shows it immediately — no full refetch needed.
+ const previewActions = useMediaPreviewActions({
+ onCleanComplete: useCallback((cleaned) => {
+ if (!cleaned?.filename) return;
+ setGalleryByFilename((prev) => {
+ const next = new Map(prev);
+ next.set(cleaned.filename, cleaned);
+ return next;
+ });
+ }, []),
+ });
+ // Generic filename → preview opener used by every clickable thumb on the
+ // page (variation grids, composite sheets, canon entries, character
+ // reference sheets). `opts.isSheet` forces a key match against the
+ // `canon-sheet:<variant>:` prefix so a basename collision with a gallery
+ // image can't route the lightbox to `/data/images/` instead of
+ // `/data/image-refs/`. The exact variant id isn't known at this callsite
+ // (the panel reads the field; the variant only lives inside the key),
+ // so match on the `canon-sheet:` prefix + filename suffix instead of an
+ // exact equality compare. Pre-variant keys (`canon-sheet:<filename>`)
+ // still match this prefix check.
+ const openPreviewByFilename = useCallback((filename, opts) => {
+ if (!filename) return;
+ const sheetMatch = opts?.isSheet
+ ? previewItems.find((i) => typeof i.key === 'string' && i.key.startsWith('canon-sheet:') && i.filename === filename)
+ : null;
+ const match = sheetMatch || previewItems.find((i) => i.filename === filename);
+ if (match) setPreview(match);
+ }, [previewItems, setPreview]);
+ // Legacy name retained for the variation/composite call sites that pass a
+ // single filename — same implementation, different label.
+ const openVariationPreview = openPreviewByFilename;
+
+ return {
+ previewItems,
+ preview,
+ setPreview,
+ previewActions,
+ openPreviewByFilename,
+ openVariationPreview,
+ annotations,
+ updateAnnotation,
+ bumpGalleryRefresh,
+ };
+}
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 5b41f13a3b..6596bf8fb2 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -49,15 +49,10 @@ import EntryCard from '../components/universe/EntryCard';
import EntryThumbSlot from '../components/universe/EntryThumbSlot';
import useMediaJobProgress from '../hooks/useMediaJobProgress';
import MediaPreview from '../components/media/MediaPreview';
-import useMediaPreviewActions from '../hooks/useMediaPreviewActions';
-import usePreviewRoute from '../hooks/usePreviewRoute';
-import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
-import { listImageGallery } from '../services/apiImageVideo';
+import useUniverseGallery from '../hooks/useUniverseGallery';
import TabPills from '../components/ui/TabPills';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';
-import { descriptorForCanonEntry } from '../lib/canonPrompt';
-import { listSheetPointers } from '../lib/sheetPointers';
import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';
import { sameJsonShape } from '../lib/sameJsonShape';
import { capImageRefs } from '../lib/bibleLimits';
@@ -354,184 +349,21 @@ export default function UniverseBuilder() {
);
const [runs, setRuns] = useState([]);
- // Page-level lightbox state. Single MediaPreview at this level covers
- // EVERY thumb on the page: variations, composite sheets, canon imageRefs,
- // and character reference sheets — so clicking any image opens the same
- // full-detail modal History / Collections / ImageGen use, with the same
- // actions (Refine / Remix / SendToVideo / Clean / AddToCollection /
- // Download / notes). Canon previews used to live inside UniverseCanonSection
- // and showed only a refine/add/download subset against the character
- // description; lifting state up here is what unifies them. URL-driven
- // (`?preview=<filename>`) via `usePreviewRoute(previewItems)` below.
- // Filename → full image-metadata-sidecar record (prompt, negativePrompt,
- // modelId, width, height, seed, etc.). Hydrates `previewItems` with the
- // ACTUAL prompt that was used to render the image — without this the
- // modal would only see the variation's label, and Refine Prompt / Remix
- // / Send to Video would all open with empty fields. Loaded once per
- // mount via `listImageGallery()` (the same call the History page uses)
- // and refreshed whenever a render completes (universe `runs` advances).
- const [galleryByFilename, setGalleryByFilename] = useState(() => new Map());
- // Bumped on every job completion so the gallery-metadata fetch below
- // re-runs once the new sidecar exists on disk. Keying the fetch only on
- // `runs.length` was insufficient: that advances when a run is queued or
- // loaded, NOT when one of its jobs completes — so a freshly rendered
- // thumb would open the lightbox with label-only metadata until a full
- // page reload.
- const [galleryRefreshKey, setGalleryRefreshKey] = useState(0);
- const bumpGalleryRefresh = useCallback(() => setGalleryRefreshKey((k) => k + 1), []);
- useEffect(() => {
- let cancelled = false;
- listImageGallery().then((list) => {
- if (cancelled) return;
- const map = new Map();
- for (const item of Array.isArray(list) ? list : []) {
- if (item?.filename) map.set(item.filename, item);
- }
- setGalleryByFilename(map);
- }).catch(() => { /* non-fatal; modal falls back to filename-only display */ });
- return () => { cancelled = true; };
- // `runs.length` covers initial-load and queue-time; `galleryRefreshKey`
- // covers per-job completion (see bumpGalleryRefresh callers).
- }, [runs.length, galleryRefreshKey]);
- const { annotations, updateAnnotation } = useMediaAnnotations();
- const previewItems = useMemo(() => {
- const out = [];
- // Dedupe by full namespaced key (`image:<filename>` vs
- // `canon-sheet:<filename>`) so a gallery image and a character reference
- // sheet that share a basename can coexist in the items list — without the
- // namespace, the first-pushed item would suppress the second and the
- // preview-URL resolver would never see the other asset.
- const seen = new Set();
- const pushFilename = (filename, label) => {
- if (typeof filename !== 'string' || !filename) return;
- const key = `image:${filename}`;
- if (seen.has(key)) return;
- seen.add(key);
- // Pull the real prompt + render settings out of the gallery metadata
- // map when available so the lightbox shows the full prompt that was
- // sent to the renderer (with universe style influences, variation
- // prompt fragment, etc.), not just the row's display label.
- // Falls back to the label-only shape for filenames not in the gallery
- // (legacy renders or pending re-fetch).
- const meta = galleryByFilename.get(filename) || null;
- out.push({
- // Same `image:<filename>` key normalizeImage() stamps everywhere
- // else — History, Collections, ImageGen — so a star/note added
- // from this lightbox is the SAME annotation record those pages
- // already read. A page-local key would silently fork the user's
- // favorites by surface.
- key: `image:${filename}`,
- kind: 'image',
- filename,
- previewUrl: `/data/images/${filename}`,
- downloadUrl: `/data/images/${filename}`,
- prompt: meta?.prompt || label || filename,
- negativePrompt: meta?.negativePrompt || null,
- modelId: meta?.modelId || meta?.model || null,
- width: meta?.width ?? null,
- height: meta?.height ?? null,
- seed: meta?.seed ?? null,
- steps: meta?.steps ?? null,
- guidance: meta?.guidance ?? null,
- quantize: meta?.quantize ?? null,
- // `raw` carries the original sidecar so MediaLightbox's "Refine
- // Prompt" / clean / remix downstream handlers can pull any field
- // the spec doesn't surface at the top level.
- raw: meta,
- });
- };
- const cats = draft?.categories && typeof draft.categories === 'object' ? draft.categories : {};
- for (const [bucketKey, bucket] of Object.entries(cats)) {
- const variations = Array.isArray(bucket?.variations) ? bucket.variations : [];
- for (const v of variations) {
- const refs = Array.isArray(v?.imageRefs) ? v.imageRefs : [];
- for (const f of refs) pushFilename(f, `${bucketKey} · ${v.label}`);
- }
- }
- const sheets = Array.isArray(draft?.compositeSheets) ? draft.compositeSheets : [];
- for (const s of sheets) {
- const refs = Array.isArray(s?.imageRefs) ? s.imageRefs : [];
- for (const f of refs) pushFilename(f, `Composite · ${s.label}`);
- }
- // Base style probe renders — same `image:<filename>` namespace so the
- // lightbox finds them and reuses the gallery sidecar metadata.
- const styleRefs = Array.isArray(draft?.styleImageRefs) ? draft.styleImageRefs : [];
- for (const f of styleRefs) pushFilename(f, 'Base style');
- // Canon refs — characters / places / objects. Hydrate from the gallery
- // sidecar so the modal shows the ACTUAL render prompt (the same one the
- // History page sees), not just the character description. The descriptor
- // string is only used as a fallback label when no sidecar exists (legacy
- // canon renders without metadata). Character reference sheets live in a
- // different static prefix (`/data/image-refs/`) so they get a dedicated
- // `canon-sheet:<filename>` key + don't collide with gallery entries.
- const canonKinds = [
- { key: 'characters', singular: 'character' },
- { key: 'places', singular: 'place' },
- { key: 'objects', singular: 'object' },
- ];
- for (const kind of canonKinds) {
- const list = Array.isArray(draft?.[kind.key]) ? draft[kind.key] : [];
- for (const entry of list) {
- const descriptor = descriptorForCanonEntry(kind.key, entry) || '';
- const fallbackLabel = `${entry.name}${descriptor ? `: ${descriptor}` : ''}`;
- const refs = Array.isArray(entry?.imageRefs) ? entry.imageRefs : [];
- for (const f of refs) pushFilename(f, fallbackLabel);
- if (kind.key === 'characters') {
- for (const { variant, filename } of listSheetPointers(entry)) {
- const sheetKey = `canon-sheet:${variant}:${filename}`;
- if (seen.has(sheetKey)) continue;
- seen.add(sheetKey);
- out.push({
- key: sheetKey,
- kind: 'image',
- filename,
- previewUrl: `/data/image-refs/${filename}`,
- downloadUrl: `/data/image-refs/${filename}`,
- prompt: `${entry.name} — character reference sheet (${variant})`,
- });
- }
- }
- }
- }
- return out;
- }, [draft, galleryByFilename]);
- const [preview, setPreview] = usePreviewRoute(previewItems);
- // Shared preview action handlers (Remix / SendToVideo / Clean) so the
- // universe lightbox opens the same downstream pages with the same params
- // as the History grid + Image Gen page. `onCleanComplete` splices the
- // cleaned image into the local gallery map so the next preview open
- // shows it immediately — no full refetch needed.
- const previewActions = useMediaPreviewActions({
- onCleanComplete: useCallback((cleaned) => {
- if (!cleaned?.filename) return;
- setGalleryByFilename((prev) => {
- const next = new Map(prev);
- next.set(cleaned.filename, cleaned);
- return next;
- });
- }, []),
- });
- // Generic filename → preview opener used by every clickable thumb on the
- // page (variation grids, composite sheets, canon entries, character
- // reference sheets). `opts.isSheet` forces a key match against the
- // `canon-sheet:<variant>:` prefix so a basename collision with a gallery
- // image can't route the lightbox to `/data/images/` instead of
- // `/data/image-refs/`. The exact variant id isn't known at this callsite
- // (the panel reads the field; the variant only lives inside the key),
- // so match on the `canon-sheet:` prefix + filename suffix instead of an
- // exact equality compare. Pre-variant keys (`canon-sheet:<filename>`)
- // still match this prefix check.
- const openPreviewByFilename = useCallback((filename, opts) => {
- if (!filename) return;
- const sheetMatch = opts?.isSheet
- ? previewItems.find((i) => typeof i.key === 'string' && i.key.startsWith('canon-sheet:') && i.filename === filename)
- : null;
- const match = sheetMatch || previewItems.find((i) => i.filename === filename);
- if (match) setPreview(match);
- }, [previewItems, setPreview]);
- // Legacy name retained for the variation/composite call sites that pass a
- // single filename — same implementation, different label.
- const openVariationPreview = openPreviewByFilename;
+ // Page-level lightbox + gallery-metadata concern. A single MediaPreview at
+ // this level covers EVERY thumb on the page: variations, composite sheets,
+ // canon imageRefs, style probes, and character reference sheets — so clicking
+ // any image opens the same full-detail modal History / Collections / ImageGen
+ // use, with the same actions (Refine / Remix / SendToVideo / Clean /
+ // AddToCollection / Download / notes). URL-driven (`?preview=<filename>`).
+ // Extracted to useUniverseGallery (#2532) — see the hook for the
+ // gallery-sidecar hydration, dedupe-by-namespaced-key, and refetch-trigger
+ // rationale. `runs.length` (initial-load + queue-time) and per-job
+ // completion (`bumpGalleryRefresh`) both drive the metadata refetch.
+ const {
+ previewItems, preview, setPreview, previewActions,
+ openPreviewByFilename, openVariationPreview,
+ annotations, updateAnnotation, bumpGalleryRefresh,
+ } = useUniverseGallery({ draft, runsLength: runs.length });
// Two-click delete: first click flips this to the world id; a second
// click within the live render confirms. Avoids window.confirm per