Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
253 changes: 223 additions & 30 deletions src/canvas/CreationAssetList.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { useCallback, useEffect, useId, useRef, useState } from "react";
import type { Asset, CanvasItem } from "../contracts/generated.ts";
import {
useCallback,
useDeferredValue,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import type {
Asset,
CanvasItem,
ProjectSnapshot,
} from "../contracts/generated.ts";
import {
assetReference,
creationClient,
Expand Down Expand Up @@ -59,6 +71,42 @@ interface Listing {
eventCursor: number;
counts: Record<Category, number>;
}
type Loaded = Omit<Listing, "counts">;
/** Pages from different project revisions are retried this many times before
* the list reports that the project changed. */
const CHANGED_RETRIES = 2;
/** A refresh of the open list waits this long after the previous read ends,
* so a busy project reads it at most once per gap instead of once per event. */
const REFRESH_GAP_MS = 2000;
/** The parts of a snapshot the asset list is computed from: assets, the
* canvas nodes that own them (title, visibility, binding), current results,
* pinned references and the editor documents listed or counted as usage.
* Moving, resizing or restyling nodes leaves it unchanged. */
function listingFingerprint(snapshot: ProjectSnapshot) {
return JSON.stringify([
snapshot.undoClearedThrough,
snapshot.assets.map((asset) => [asset.id, asset.name, asset.kind]),
snapshot.canvasItems.map((item) => [
item.id,
item.kind,
item.title,
item.visible,
item.parentId,
item.binding,
]),
snapshot.generationSpecs.map((spec) => [spec.id, spec.currentResultId]),
snapshot.results.map((result) => [result.id, result.asset.assetId]),
snapshot.references.map((ref) => [
ref.id,
ref.active,
ref.binding === "pinned" ? ref.source.assetId : null,
]),
snapshot.editorDocuments.map((document) => [
document.id,
document.revision,
]),
]);
}
interface NodeRow {
itemId: string;
title: string;
Expand Down Expand Up @@ -95,8 +143,10 @@ export function CreationAssetList({
return key ? t(key) : label;
};
const [text, setText] = useState(""),
[visibility, setVisibility] = useState("all"),
[query, setQuery] = useState("");
[visibility, setVisibility] = useState("all");
// Filtering runs in the browser over the loaded list, so typing never waits
// for the server; the deferred value keeps long lists from blocking input.
const query = useDeferredValue(text);
const [category, setCategory] = useState<Category>("all");
const [preview, setPreview] = useState<AssetPreview | null>(null);
const previewTimer = useRef<number | undefined>(undefined);
Expand Down Expand Up @@ -131,8 +181,30 @@ export function CreationAssetList({
};
const rowsId = useId();
const [loading, setLoading] = useState(true);
const [listing, setListing] = useState<Listing | null>(null),
// The whole unfiltered listing; search, visibility and type only narrow it.
const [loaded, setLoaded] = useState<Loaded | null>(null),
[error, setError] = useState("");
const [revision, setRevision] = useState(0);
// The project whose complete list is on screen, and whether it changed
// again while a load was already running.
const shown = useRef<string | null>(null);
const reading = useRef(false),
stale = useRef(false);
// A background refresh failed; the rows on screen are kept but may be old.
const [outdated, setOutdated] = useState(false);
const loadFinished = useRef(0);
const refreshTimer = useRef<number | undefined>(undefined);
const scheduleRefresh = useCallback(() => {
if (refreshTimer.current !== undefined) return;
refreshTimer.current = window.setTimeout(
() => {
refreshTimer.current = undefined;
if (reading.current) stale.current = true;
else if (shown.current === projectId) setRevision((n) => n + 1);
},
Math.max(0, loadFinished.current + REFRESH_GAP_MS - Date.now()),
);
}, [projectId]);
const [selected, setSelected] = useState<string[]>([]),
[busy, setBusy] = useState(false),
[attempt, setAttempt] = useState(0);
Expand Down Expand Up @@ -175,60 +247,157 @@ export function CreationAssetList({
document.removeEventListener("keydown", escape, true);
};
}, [anchor, busy, onClose]);
useEffect(() => {
const timer = window.setTimeout(() => setQuery(text), 200);
return () => window.clearTimeout(timer);
}, [text]);
useEffect(() => {
const controller = new AbortController();
let active = true;
setListing(null);
// A refresh keeps the current rows on screen until the new list is whole.
const refreshing = shown.current === projectId;
if (!refreshing) {
shown.current = null;
setLoaded(null);
setOutdated(false);
}
// This read sees every change made so far, so a refresh waiting for the
// gap is no longer needed.
window.clearTimeout(refreshTimer.current);
refreshTimer.current = undefined;
reading.current = true;
stale.current = false;
setLoading(true);
setError("");
void (async () => {
const rows: Row[] = [];
const nodes: NodeRow[] = [];
let rows: Row[] = [];
let nodes: NodeRow[] = [];
let total = Infinity,
cursor = 0;
cursor = 0,
retries = 0;
while (rows.length + nodes.length < total) {
const page = await request<Listing>(
`${creationPath(projectId)}/asset-list?text=${encodeURIComponent(query)}&visibility=${visibility}&category=${category}&offset=${rows.length + nodes.length}&limit=200`,
`${creationPath(projectId)}/asset-list?offset=${rows.length + nodes.length}&limit=200`,
{ signal: controller.signal },
);
if ((rows.length || nodes.length) && page.eventCursor !== cursor)
throw new Error(t("canvasNodes.assets.changed"));
if ((rows.length || nodes.length) && page.eventCursor !== cursor) {
// Pages from different project revisions never form one list.
if (retries++ >= CHANGED_RETRIES)
throw new Error(t("canvasNodes.assets.changed"));
rows = [];
nodes = [];
total = Infinity;
continue;
}
rows.push(...page.items);
nodes.push(...(page.nodes ?? []));
total = page.total;
cursor = page.eventCursor;
if (active)
setListing({
if (active && !refreshing)
setLoaded({
items: [...rows],
nodes: [...nodes],
total,
eventCursor: cursor,
counts: page.counts,
});
if (!page.items.length && !page.nodes?.length) break;
}
if (active) {
setLoaded({ items: rows, nodes, total, eventCursor: cursor });
shown.current = projectId;
reading.current = false;
loadFinished.current = Date.now();
setLoading(false);
setSelected((ids) =>
ids.filter((id) => rows.some((row) => row.asset.id === id)),
);
setOutdated(false);
if (stale.current) scheduleRefresh();
}
})().catch((reason) => {
if (active) {
setListing(null);
setLoading(false);
setError(errorMessage(reason));
if (!active) return;
reading.current = false;
loadFinished.current = Date.now();
setLoading(false);
if (refreshing) {
// A failed refresh keeps the list on screen and marks it as possibly
// old; the next project change refreshes it again.
setOutdated(true);
if (stale.current) scheduleRefresh();
return;
}
shown.current = null;
setLoaded(null);
setError(errorMessage(reason));
});
return () => {
active = false;
controller.abort();
};
}, [projectId, query, visibility, category, attempt]);
}, [projectId, attempt, revision, scheduleRefresh]);
// Reload when a change to the project can change the list while it is open,
// e.g. an agent adds media. Other events, such as moving nodes, are ignored.
// A change during a load reloads once that load is done, and reloads keep
// REFRESH_GAP_MS apart, so a busy project cannot keep the list reading.
useEffect(() => {
const client = creationClient(projectId);
let seen = client.snapshot ? listingFingerprint(client.snapshot) : "";
const stop = client.listen((snapshot) => {
const next = listingFingerprint(snapshot);
if (next === seen) return;
seen = next;
if (reading.current) stale.current = true;
else if (shown.current === projectId) scheduleRefresh();
});
return () => {
stop();
window.clearTimeout(refreshTimer.current);
refreshTimer.current = undefined;
};
}, [projectId, scheduleRefresh]);
const listing = useMemo(() => {
if (!loaded) return null;
// Like the server's asset search: name or owning node title, ignoring
// case. toLowerCase is close to Python's casefold but not identical
// (casefold also folds "ß" to "ss").
const needle = query.toLowerCase();
const items = loaded.items.filter(
(row) =>
(visibility === "all" ||
row.owners.some((owner) => owner.visible) ===
(visibility === "visible")) &&
(row.asset.name.toLowerCase().includes(needle) ||
row.owners.some((owner) =>
owner.title.toLowerCase().includes(needle),
)),
);
const nodes = loaded.nodes.filter(
(row) =>
(visibility === "all" || row.visible === (visibility === "visible")) &&
row.title.toLowerCase().includes(needle),
);
const counts = Object.fromEntries(
CATEGORIES.map((entry) => [entry.id, 0]),
) as Record<Category, number>;
counts.all = items.length + nodes.length;
for (const row of items)
for (const kind of row.categories)
if (kind !== "all" && kind in counts) counts[kind as Category] += 1;
for (const row of nodes) counts[row.kind] += 1;
return {
items:
category === "all"
? items
: items.filter((row) => row.categories.includes(category)),
nodes:
category === "all"
? nodes
: nodes.filter((row) => row.kind === category),
counts,
};
}, [loaded, query, visibility, category]);
useEffect(() => {
if (loading || !listing) return;
setSelected((ids) => {
const next = ids.filter((id) =>
listing.items.some((row) => row.asset.id === id),
);
return next.length === ids.length ? ids : next;
});
}, [listing, loading]);
useEffect(clearPreview, [category, query, visibility, clearPreview]);
const perform = async (action: () => Promise<void>) => {
setBusy(true);
Expand Down Expand Up @@ -278,6 +447,18 @@ export function CreationAssetList({
deleting.impact.fingerprint,
);
if (alive.current) {
// The receipt confirms the deletion; drop the rows now instead of
// leaving them on screen until the refreshed list arrives.
const removed = new Set(deleting.ids);
setLoaded((current) => {
if (!current) return current;
const items = current.items.filter((row) => !removed.has(row.asset.id));
return {
...current,
items,
total: current.total - (current.items.length - items.length),
};
});
setDeleting(null);
setSelected([]);
setAttempt((n) => n + 1);
Expand Down Expand Up @@ -519,13 +700,25 @@ export function CreationAssetList({
{loading && !error && (
<p role="status">
{t("canvasNodes.assets.loading")}
{listing &&
{loaded &&
loaded.items.length + loaded.nodes.length < loaded.total &&
t("canvasNodes.assets.progress", {
shown: listing.items.length + listing.nodes.length,
total: listing.total,
shown: loaded.items.length + loaded.nodes.length,
total: loaded.total,
})}
</p>
)}
{outdated && !loading && !error && (
<p role="status">
{t("canvasNodes.assets.outdated")}
<button
disabled={busy}
onClick={() => setAttempt((n) => n + 1)}
>
{t("canvasNodes.assets.reload")}
</button>
</p>
)}
<div
id={rowsId}
className="cw-creation-asset-rows"
Expand Down
20 changes: 12 additions & 8 deletions src/canvas/CreationAssetPreview.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import type { Asset } from "../contracts/generated.ts";
import { creationClient } from "../backend/creationClient.ts";
import { creationClient, MEDIA_PRIORITY } from "../backend/creationClient.ts";
import { CanvasIcon } from "./CanvasIcon.tsx";
import { useT } from "../i18n/I18nProvider.tsx";

Expand All @@ -26,28 +26,32 @@ export function HoverPreview({
const [content, setContent] = useState<string>();
const [failed, setFailed] = useState(false);
useEffect(() => {
let active = true;
const asset = preview.asset;
if (!asset) return;
const controller = new AbortController();
const client = creationClient(projectId);
// A video preview reads the whole file. Read it like on-screen canvas media
// so leaving the row abandons it; otherwise moving the pointer down a list
// of videos queues every file ahead of the canvas's own media.
const pending =
asset.kind === "image"
? client.thumbnailUrl(asset.id)
: asset.kind === "text" && asset.metadata.size <= 65536
? client.textContent(asset.id)
: asset.kind === "video"
? client.mediaUrl(asset.id)
? client.mediaUrl(asset.id, {
signal: controller.signal,
priority: MEDIA_PRIORITY.visible,
})
: Promise.resolve("");
void pending
.then((value) => {
if (active) setContent(value);
if (!controller.signal.aborted) setContent(value);
})
.catch(() => {
if (active) setFailed(true);
if (!controller.signal.aborted) setFailed(true);
});
return () => {
active = false;
};
return () => controller.abort();
}, [projectId, preview.asset]);
useLayoutEffect(() => {
const element = panel.current!;
Expand Down
1 change: 1 addition & 0 deletions src/i18n/messages/en-US/canvasNodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export const canvasNodes = {
"canvasNodes.assets.subject": "Subjects",
"canvasNodes.assets.timeline": "Timelines",
"canvasNodes.assets.changed": "The asset list changed. Read it again.",
"canvasNodes.assets.outdated": "The asset list may be out of date.",
"canvasNodes.assets.versionChanged":
"This asset's current version changed. Choose from the updated list.",
"canvasNodes.assets.nodeChanged":
Expand Down
Loading
Loading