feat(HEL-884): locate canvas occupancy, accurate card handling, close the delete loop
- GET /api/library/media/usage: read-only occupancy report per file — every live canvas card with canvas title, project/session scope, and the real consequence of deleting that card (deletes_file / keep reason) - _path_on_canvas joins canvas: orphan nodes (canvas row gone, FK-cascade dead metadata) no longer count as occupancy; they are reported as invalid references with totals instead of blocking deletion - canvas deleteNode: keep_file=true release-only variant (card removed, file always preserved); artifact cards with a live pending/running job refuse deletion (409) so completion events cannot resurrect them - library UI: occupancy modal on kept(on_canvas) with locate / delete card (accurate impact text) / release-only actions, per-path free-file delete closing the loop, invalid-reference note, offset paging for large counts, library selection persisted across canvas round-trips - canvas UI: ?locate=<node> deep-link centers the card (computed viewport, no store.fitView — its nodes write-back looped the graph rebuild effect), gold ring highlight + dismiss, back-to-library chip - i18n keys for all 7 languages; e2e runner + 32-check real-browser regression on isolated data Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -772,6 +772,37 @@ export interface LibraryMediaItem {
|
||||
mtime: string;
|
||||
}
|
||||
|
||||
/** Where one library file is still used on a canvas (HEL-884). */
|
||||
export interface LibraryUsageScope {
|
||||
kind: "project" | "session" | null;
|
||||
id: number | null;
|
||||
title: string | null;
|
||||
}
|
||||
|
||||
export interface LibraryUsageCard {
|
||||
canvas_id: number;
|
||||
canvas_title: string;
|
||||
node_id: number;
|
||||
node_title: string | null;
|
||||
node_type: string;
|
||||
node_status: string;
|
||||
job_id: number | null;
|
||||
job_running: boolean;
|
||||
scope: LibraryUsageScope;
|
||||
deleting_card_deletes_file: boolean;
|
||||
file_keep_reason: string | null;
|
||||
}
|
||||
|
||||
export interface LibraryMediaUsage {
|
||||
path: string;
|
||||
usages: LibraryUsageCard[];
|
||||
valid_total: number;
|
||||
invalid: { node_id: number; canvas_id: number; node_title: string | null }[];
|
||||
invalid_total: number;
|
||||
offset: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
// ── Five-stage creation workbench (HEL-614) ─────────────────────────────
|
||||
|
||||
export type WorkbenchStageKey =
|
||||
@@ -942,6 +973,10 @@ export interface LibraryDeleteResult {
|
||||
|
||||
export const libraryApi = {
|
||||
list: () => api<LibraryMediaItem[]>("/api/library/media"),
|
||||
usage: (path: string, offset = 0) =>
|
||||
api<LibraryMediaUsage>(
|
||||
`/api/library/media/usage?path=${encodeURIComponent(path)}&offset=${offset}`,
|
||||
),
|
||||
deleteMany: (paths: string[]) =>
|
||||
api<{
|
||||
ok: boolean;
|
||||
@@ -1343,9 +1378,9 @@ export const canvasApi = {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
deleteNode: (canvasId: number, nodeId: number) =>
|
||||
deleteNode: (canvasId: number, nodeId: number, keepFile = false) =>
|
||||
api<{ ok: boolean; file_deleted?: boolean; reason?: string | null }>(
|
||||
`/api/canvas/${canvasId}/nodes/${nodeId}`,
|
||||
`/api/canvas/${canvasId}/nodes/${nodeId}${keepFile ? "?keep_file=true" : ""}`,
|
||||
{ method: "DELETE" },
|
||||
),
|
||||
tidy: (canvasId: number) =>
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
artifactPath: string | null;
|
||||
kind: 'image' | 'video';
|
||||
status: string;
|
||||
/** HEL-884 locate deep-link: this card is the one being looked for. */
|
||||
located?: boolean;
|
||||
/** Called on media click: opens the large preview (no navigation). */
|
||||
onOpenMedia?: (kind: 'image' | 'video') => void;
|
||||
}
|
||||
@@ -65,7 +67,9 @@
|
||||
<div
|
||||
class="canvas-card artifact-node a-viewfinder"
|
||||
class:a-in-frame={selected}
|
||||
class:located={data.located}
|
||||
data-kind={data.kind}
|
||||
data-testid={data.located ? 'located-card' : undefined}
|
||||
>
|
||||
<header>
|
||||
<span class="type-chip">{data.kind}</span>
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
imagePath: string | null;
|
||||
/** Clip path — when set the card becomes a playable video card. */
|
||||
videoPath: string | null;
|
||||
/** HEL-884 locate deep-link: this card is the one being looked for. */
|
||||
located?: boolean;
|
||||
/** Called on card click: opens the large media preview (no navigation). */
|
||||
onOpenMedia?: (kind: 'image' | 'video') => void;
|
||||
}
|
||||
@@ -56,7 +58,9 @@
|
||||
<div
|
||||
class="canvas-card entity-node a-viewfinder"
|
||||
class:a-in-frame={selected}
|
||||
class:located={data.located}
|
||||
data-kind={data.entityType}
|
||||
data-testid={data.located ? 'located-card' : undefined}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={activate}
|
||||
|
||||
@@ -75,6 +75,30 @@
|
||||
.canvas-root .svelte-flow__node:focus-visible .canvas-card {
|
||||
border-color: color-mix(in srgb, var(--scene) 45%, transparent);
|
||||
}
|
||||
/* HEL-884 locate deep-link: the looked-for card gets an unmistakable gold
|
||||
ring + soft pulse until dismissed (20s) so it reads at any zoom. */
|
||||
.canvas-card.located {
|
||||
border-color: var(--gold);
|
||||
box-shadow:
|
||||
0 0 0 3px color-mix(in srgb, var(--gold) 45%, transparent),
|
||||
var(--sh-2);
|
||||
}
|
||||
html[data-motion="full"] .canvas-card.located {
|
||||
animation: located-pulse 1.6s var(--ease-out) infinite;
|
||||
}
|
||||
@keyframes located-pulse {
|
||||
0%,
|
||||
100% {
|
||||
box-shadow:
|
||||
0 0 0 3px color-mix(in srgb, var(--gold) 45%, transparent),
|
||||
var(--sh-2);
|
||||
}
|
||||
50% {
|
||||
box-shadow:
|
||||
0 0 0 6px color-mix(in srgb, var(--gold) 22%, transparent),
|
||||
var(--sh-2);
|
||||
}
|
||||
}
|
||||
.canvas-card:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
@@ -308,6 +308,11 @@ export const de: Dict = {
|
||||
"canvas.noChatYet": "Noch kein Chat auf diesem Canvas",
|
||||
"canvas.collapseChat": "Chat einklappen",
|
||||
"canvas.expandChat": "Chat ausklappen",
|
||||
"canvas.locateMissing":
|
||||
"Karte nicht gefunden — sie wurde möglicherweise bereits gelöscht",
|
||||
"canvas.located": "Gesuchte Karte gefunden",
|
||||
"canvas.backToLibrary": "Zurück zur Mediathek",
|
||||
"canvas.locateDismiss": "Markierung aufheben",
|
||||
"canvas.deleteBlocked":
|
||||
"Projekt-Assets und laufende Jobs können hier nicht gelöscht werden – über die Projekt-Assets ersetzen",
|
||||
"canvas.deleteFailed": "{count} Karte(n) konnten nicht gelöscht werden",
|
||||
|
||||
@@ -301,6 +301,11 @@ export const en = {
|
||||
"canvas.noChatYet": "No chat on this canvas yet",
|
||||
"canvas.collapseChat": "Collapse chat",
|
||||
"canvas.expandChat": "Expand chat",
|
||||
"canvas.locateMissing":
|
||||
"Could not find that card — it may have been deleted already",
|
||||
"canvas.located": "Located the card you were looking for",
|
||||
"canvas.backToLibrary": "Back to library",
|
||||
"canvas.locateDismiss": "Dismiss highlight",
|
||||
"canvas.deleteBlocked":
|
||||
"Project assets and running jobs can’t be deleted here — replace them from Project Assets",
|
||||
"canvas.deleteFailed": "Could not delete {count} card(s)",
|
||||
|
||||
@@ -310,6 +310,11 @@ export const es: Dict = {
|
||||
"canvas.noChatYet": "Aún no hay ningún chat en este canvas",
|
||||
"canvas.collapseChat": "Contraer chat",
|
||||
"canvas.expandChat": "Expandir chat",
|
||||
"canvas.locateMissing":
|
||||
"No se encontró la tarjeta; puede que ya se haya borrado",
|
||||
"canvas.located": "Tarjeta buscada localizada",
|
||||
"canvas.backToLibrary": "Volver a la biblioteca",
|
||||
"canvas.locateDismiss": "Quitar resaltado",
|
||||
"canvas.deleteBlocked":
|
||||
"Los assets del proyecto y los trabajos en curso no se pueden eliminar aquí – reemplázalos desde los assets del proyecto",
|
||||
"canvas.deleteFailed": "No se pudieron eliminar {count} tarjeta(s)",
|
||||
|
||||
@@ -312,6 +312,11 @@ export const fr: Dict = {
|
||||
"canvas.noChatYet": "Pas encore de discussion sur ce canevas",
|
||||
"canvas.collapseChat": "Réduire la discussion",
|
||||
"canvas.expandChat": "Développer la discussion",
|
||||
"canvas.locateMissing":
|
||||
"Carte introuvable — elle a peut-être déjà été supprimée",
|
||||
"canvas.located": "Carte recherchée localisée",
|
||||
"canvas.backToLibrary": "Retour à la médiathèque",
|
||||
"canvas.locateDismiss": "Retirer le surlignage",
|
||||
"canvas.deleteBlocked":
|
||||
"Les assets de projet et les jobs en cours ne peuvent pas être supprimés ici – remplacez-les depuis les assets du projet",
|
||||
"canvas.deleteFailed": "Impossible de supprimer {count} carte(s)",
|
||||
|
||||
@@ -307,6 +307,11 @@ export const ja: Dict = {
|
||||
"canvas.noChatYet": "このキャンバスにはまだチャットがありません",
|
||||
"canvas.collapseChat": "チャットを折りたたむ",
|
||||
"canvas.expandChat": "チャットを展開",
|
||||
"canvas.locateMissing":
|
||||
"カードが見つかりません。既に削除された可能性があります",
|
||||
"canvas.located": "探していたカードを表示しました",
|
||||
"canvas.backToLibrary": "ライブラリに戻る",
|
||||
"canvas.locateDismiss": "ハイライトを解除",
|
||||
"canvas.deleteBlocked":
|
||||
"プロジェクトのアセットや実行中のジョブはここでは削除できません – プロジェクトのアセットから置き換えてください",
|
||||
"canvas.deleteFailed": "{count} 枚のカードを削除できませんでした",
|
||||
|
||||
@@ -304,6 +304,10 @@ export const ko: Dict = {
|
||||
"canvas.noChatYet": "이 캔버스에는 아직 채팅이 없습니다",
|
||||
"canvas.collapseChat": "채팅 접기",
|
||||
"canvas.expandChat": "채팅 펼치기",
|
||||
"canvas.locateMissing": "카드를 찾을 수 없어요. 이미 삭제되었을 수 있어요",
|
||||
"canvas.located": "찾던 카드를 표시했어요",
|
||||
"canvas.backToLibrary": "라이브러리로 돌아가기",
|
||||
"canvas.locateDismiss": "강조 끄기",
|
||||
"canvas.deleteBlocked":
|
||||
"프로젝트 애셋과 실행 중인 작업은 여기서 삭제할 수 없습니다 – 프로젝트 애셋에서 교체하세요",
|
||||
"canvas.deleteFailed": "{count}개 카드를 삭제하지 못했습니다",
|
||||
|
||||
@@ -295,6 +295,10 @@ export const zh: Dict = {
|
||||
"canvas.noChatYet": "此画布尚无对话",
|
||||
"canvas.collapseChat": "收起对话",
|
||||
"canvas.expandChat": "展开对话",
|
||||
"canvas.locateMissing": "没有找到这张卡片,可能已被删除",
|
||||
"canvas.located": "已定位到要找的卡片",
|
||||
"canvas.backToLibrary": "返回素材库",
|
||||
"canvas.locateDismiss": "取消高亮",
|
||||
"canvas.deleteBlocked":
|
||||
"项目素材和正在运行的任务无法在此删除 – 请在项目素材中替换它们",
|
||||
"canvas.deleteFailed": "未能删除 {count} 张卡片",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from '$app/paths';
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { untrack } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/state';
|
||||
import { toStore } from 'svelte/store';
|
||||
@@ -146,6 +147,99 @@
|
||||
// internally, so proxies must never reach it.
|
||||
let nodes = $state.raw<Node[]>([]);
|
||||
|
||||
// ---- locate deep-link (?locate=<canvas node id>, HEL-884) -----------
|
||||
// The library occupancy modal links here; the card is centered, ringed
|
||||
// and stays identifiable, with a chip to jump back to the material.
|
||||
let locateNodeId = $state<number | null>(null);
|
||||
let highlightId = $state<number | null>(null);
|
||||
let flowPanelEl = $state<HTMLElement | null>(null);
|
||||
let locateHandled = false;
|
||||
let locateMissingReported = false;
|
||||
let locateTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
onDestroy(() => clearTimeout(locateTimer));
|
||||
|
||||
$effect(() => {
|
||||
if (locateHandled || canvas == null) return;
|
||||
const param = page.url.searchParams.get('locate');
|
||||
if (param == null) return;
|
||||
locateHandled = true;
|
||||
const nid = Number(param);
|
||||
if (Number.isFinite(nid) && nid > 0) {
|
||||
locateNodeId = nid;
|
||||
clearTimeout(locateTimer);
|
||||
locateTimer = setTimeout(() => {
|
||||
highlightId = null;
|
||||
locateNodeId = null;
|
||||
}, 20000);
|
||||
}
|
||||
replaceUrlParam('locate');
|
||||
});
|
||||
|
||||
/** Center the camera on one card by writing the bound viewport directly.
|
||||
* Svelte Flow's store.fitView() round-trips the bound nodes array and
|
||||
* looped the graph-rebuild effect (effect_update_depth_exceeded), so the
|
||||
* transform is computed from the graph position + measured card box.
|
||||
* Retries across a few frames — on SPA navigation the pane mounts with
|
||||
* zero size and the card's DOM box arrives one frame later. */
|
||||
let centerRetryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
onDestroy(() => clearTimeout(centerRetryTimer));
|
||||
function centerOnLocatedNode(nodeId: number, attempt = 0) {
|
||||
const panel = flowPanelEl;
|
||||
const node = $canvasQuery.data?.nodes.find((n) => n.id === nodeId);
|
||||
if (!panel || !node) return;
|
||||
if (panel.clientWidth < 2 || panel.clientHeight < 2) {
|
||||
if (attempt < 30 && locateNodeId === nodeId) {
|
||||
clearTimeout(centerRetryTimer);
|
||||
centerRetryTimer = setTimeout(
|
||||
() => centerOnLocatedNode(nodeId, attempt + 1),
|
||||
80,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let w = 220;
|
||||
let h = 200;
|
||||
const el = panel.querySelector(
|
||||
`.svelte-flow__node[data-id="cn-${nodeId}"]`,
|
||||
) as HTMLElement | null;
|
||||
if (el && el.offsetWidth && el.offsetHeight) {
|
||||
w = el.offsetWidth;
|
||||
h = el.offsetHeight;
|
||||
}
|
||||
const zoom = Math.min(viewport.zoom > 0 ? viewport.zoom : 1, 1);
|
||||
viewport = {
|
||||
zoom,
|
||||
x: panel.clientWidth / 2 - (node.x + w / 2) * zoom,
|
||||
y: panel.clientHeight / 2 - (node.y + h / 2) * zoom,
|
||||
};
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (locateNodeId == null) return;
|
||||
const graph = $canvasQuery.data;
|
||||
if (!graph) return;
|
||||
if (graph.nodes.some((n) => n.id === locateNodeId)) {
|
||||
if (highlightId !== locateNodeId) highlightId = locateNodeId;
|
||||
// Untracked: centering reads viewport.zoom and writes viewport —
|
||||
// tracked, that read+write pair is a self-retriggering loop.
|
||||
const nid = locateNodeId;
|
||||
untrack(() => centerOnLocatedNode(nid));
|
||||
} else if (
|
||||
!locateMissingReported &&
|
||||
!$canvasQuery.isLoading &&
|
||||
!$canvasQuery.isFetching
|
||||
) {
|
||||
locateMissingReported = true;
|
||||
toast.error(t('canvas.locateMissing'));
|
||||
locateNodeId = null;
|
||||
}
|
||||
});
|
||||
|
||||
function backToLibrary() {
|
||||
if (history.length > 1) history.back();
|
||||
else goto(resolve('/library'));
|
||||
}
|
||||
|
||||
// ---- media preview (lightbox) ------------------------------------------
|
||||
// Card clicks open the large preview here; nothing navigates away.
|
||||
let preview = $state<{
|
||||
@@ -224,6 +318,7 @@
|
||||
? 'running'
|
||||
: (jobs.find((j) => j.id === n.job_id)?.status ?? n.status),
|
||||
jobId: n.job_id,
|
||||
located: n.id === highlightId,
|
||||
onOpenMedia: (kind: 'image' | 'video') =>
|
||||
openMediaPreview(kind, n.artifact_path, n.title ?? 'Artifact'),
|
||||
},
|
||||
@@ -240,6 +335,7 @@
|
||||
title: n.title ?? 'Untitled',
|
||||
imagePath: media.imagePath,
|
||||
videoPath: media.videoPath,
|
||||
located: n.id === highlightId,
|
||||
onOpenMedia: (kind: 'image' | 'video') =>
|
||||
kind === 'video'
|
||||
? openMediaPreview(
|
||||
@@ -1150,7 +1246,7 @@
|
||||
onToggleCollapse={toggleRail}
|
||||
/>
|
||||
|
||||
<main class="flow-panel">
|
||||
<main class="flow-panel" bind:this={flowPanelEl}>
|
||||
<div class="titlecard" data-testid="titlecard">
|
||||
{#if titleEditing}
|
||||
<input
|
||||
@@ -1210,6 +1306,32 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if highlightId != null}
|
||||
<div class="locate-chip" data-testid="locate-chip">
|
||||
<span>{t('canvas.located')}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="locate-back"
|
||||
onclick={backToLibrary}
|
||||
>
|
||||
<Icon name="chevron-left" size={14} />
|
||||
{t('canvas.backToLibrary')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="locate-dismiss"
|
||||
onclick={() => {
|
||||
clearTimeout(locateTimer);
|
||||
highlightId = null;
|
||||
locateNodeId = null;
|
||||
}}
|
||||
aria-label={t('canvas.locateDismiss')}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<SvelteFlow
|
||||
bind:nodes
|
||||
bind:viewport
|
||||
@@ -1268,6 +1390,7 @@
|
||||
</div>
|
||||
</Panel>
|
||||
{/if}
|
||||
|
||||
</SvelteFlow>
|
||||
</main>
|
||||
|
||||
@@ -1398,6 +1521,7 @@
|
||||
}
|
||||
.titlecard,
|
||||
.tidy-btn,
|
||||
.locate-chip,
|
||||
.canvas-empty-hint,
|
||||
.chat-expand {
|
||||
background: var(--glass);
|
||||
@@ -1405,6 +1529,62 @@
|
||||
border: 1px solid var(--line-2);
|
||||
box-shadow: var(--sh-1);
|
||||
}
|
||||
.locate-chip {
|
||||
position: absolute;
|
||||
top: 14px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 5;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
height: 38px;
|
||||
padding: 0 6px 0 14px;
|
||||
border-color: color-mix(in srgb, var(--gold) 45%, transparent);
|
||||
border-radius: var(--r-pill);
|
||||
font-size: 12.5px;
|
||||
color: var(--tx-1);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.locate-chip > span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.locate-back {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 28px;
|
||||
padding: 0 12px;
|
||||
border: 0;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--grad-gold);
|
||||
color: var(--tx-inv);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.locate-back:hover {
|
||||
box-shadow: var(--sh-2);
|
||||
}
|
||||
.locate-dismiss {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border: 0;
|
||||
border-radius: var(--r-sm);
|
||||
background: transparent;
|
||||
color: var(--tx-3);
|
||||
font-size: 15px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.locate-dismiss:hover {
|
||||
color: var(--tx-1);
|
||||
background: rgb(var(--ink) / 0.06);
|
||||
}
|
||||
.titlecard {
|
||||
position: absolute;
|
||||
top: 14px;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { goto } from "$app/navigation";
|
||||
import { resolve } from "$app/paths";
|
||||
import {
|
||||
createMutation,
|
||||
createQuery,
|
||||
@@ -7,9 +9,12 @@
|
||||
import { SvelteSet } from "svelte/reactivity";
|
||||
import {
|
||||
libraryApi,
|
||||
canvasApi,
|
||||
assetUrl,
|
||||
apiErrorMessage,
|
||||
type LibraryMediaItem,
|
||||
type LibraryMediaUsage,
|
||||
type LibraryUsageCard,
|
||||
} from "$lib/api";
|
||||
import ManagementPage from "$lib/components/manage/ManagementPage.svelte";
|
||||
import AttachToProject from "$lib/components/AttachToProject.svelte";
|
||||
@@ -18,6 +23,7 @@
|
||||
import Icon from "$lib/components/ui/Icon.svelte";
|
||||
import Button from "$lib/components/ui/Button.svelte";
|
||||
import Modal from "$lib/components/ui/Modal.svelte";
|
||||
import { storageGet, storageSet } from "$lib/storage";
|
||||
import { toast } from "$lib/toast";
|
||||
import "./library-v2.css";
|
||||
const client = useQueryClient();
|
||||
@@ -38,6 +44,32 @@
|
||||
fullscreen = $state(false);
|
||||
const selected = new SvelteSet<string>();
|
||||
let anchor = $state<string | null>(null);
|
||||
// Survive navigate-away-and-back (canvas locate round-trip): the original
|
||||
// selection is restored so the user continues where they left off.
|
||||
const SELECTION_KEY = "calliope.library.selection";
|
||||
let selectionRestored = false;
|
||||
$effect(() => {
|
||||
if (!items.length) return;
|
||||
if (selected.size === 0 && !selectionRestored) {
|
||||
selectionRestored = true;
|
||||
try {
|
||||
const saved = JSON.parse(storageGet(SELECTION_KEY) ?? "null") as {
|
||||
current?: string | null;
|
||||
paths?: string[];
|
||||
} | null;
|
||||
for (const p of saved?.paths ?? [])
|
||||
if (items.some((i) => i.path === p)) selected.add(p);
|
||||
if (saved?.current && items.some((i) => i.path === saved.current))
|
||||
current = saved.current;
|
||||
} catch {
|
||||
// corrupted cache — start fresh
|
||||
}
|
||||
}
|
||||
storageSet(
|
||||
SELECTION_KEY,
|
||||
JSON.stringify({ current, paths: [...selected] }),
|
||||
);
|
||||
});
|
||||
let meta = $state<
|
||||
Record<string, { width: number; height: number; duration?: number }>
|
||||
>({});
|
||||
@@ -192,12 +224,147 @@
|
||||
`未能删除 ${kept.length} 个文件 · ${keptSummary(kept)}`,
|
||||
);
|
||||
}
|
||||
// HEL-884: canvas-held files get the real occupancy report — which
|
||||
// canvas, which card, and what to do about it.
|
||||
const onCanvas = [
|
||||
...new Set(
|
||||
kept.filter((r) => r.reason === "on_canvas").map((r) => r.path),
|
||||
),
|
||||
];
|
||||
if (onCanvas.length) {
|
||||
usageData = {};
|
||||
usageFetched = {};
|
||||
usageLoading = {};
|
||||
usageError = {};
|
||||
usagePaths = onCanvas;
|
||||
}
|
||||
selected.clear();
|
||||
deletePaths = [];
|
||||
void client.invalidateQueries({ queryKey: ["library-media"] });
|
||||
},
|
||||
onError: (e) => toast.error(`删除请求失败:${apiErrorMessage(e)}`),
|
||||
});
|
||||
|
||||
// ---- canvas occupancy report (HEL-884) ---------------------------------
|
||||
// Read-only per-file usage: which canvas card holds the file, in which
|
||||
// project/session, plus explicit actions (locate / delete card / release).
|
||||
let usagePaths = $state<string[]>([]);
|
||||
let usageData = $state<Record<string, LibraryMediaUsage>>({});
|
||||
let usageLoading = $state<Record<string, boolean>>({});
|
||||
let usageError = $state<Record<string, string>>({});
|
||||
let usageFetched = $state<Record<string, boolean>>({});
|
||||
let pendingAction = $state<{
|
||||
kind: "delete" | "release";
|
||||
path: string;
|
||||
card: LibraryUsageCard;
|
||||
} | null>(null);
|
||||
let usageBusy = $state(false);
|
||||
|
||||
async function loadUsage(path: string, offset = 0) {
|
||||
usageLoading = { ...usageLoading, [path]: true };
|
||||
usageError = { ...usageError, [path]: "" };
|
||||
try {
|
||||
const data = await libraryApi.usage(path, offset);
|
||||
const prev = offset > 0 ? usageData[path] : null;
|
||||
usageData = {
|
||||
...usageData,
|
||||
[path]: prev
|
||||
? { ...data, usages: [...prev.usages, ...data.usages] }
|
||||
: data,
|
||||
};
|
||||
usageFetched = { ...usageFetched, [path]: true };
|
||||
} catch (e) {
|
||||
usageError = { ...usageError, [path]: apiErrorMessage(e) };
|
||||
} finally {
|
||||
usageLoading = { ...usageLoading, [path]: false };
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
for (const p of usagePaths)
|
||||
if (!usageFetched[p] && !usageLoading[p]) void loadUsage(p);
|
||||
});
|
||||
|
||||
// Entries whose file disappeared (deleted together with its card) leave
|
||||
// the modal on the next list refresh — the loop closed itself.
|
||||
$effect(() => {
|
||||
if (!items.length || !usagePaths.length) return;
|
||||
const alive = usagePaths.filter((p) => items.some((i) => i.path === p));
|
||||
if (alive.length !== usagePaths.length) usagePaths = alive;
|
||||
});
|
||||
|
||||
function scopeText(card: LibraryUsageCard) {
|
||||
if (card.scope.kind === "project")
|
||||
return card.scope.title
|
||||
? `项目「${card.scope.title}」`
|
||||
: "所属项目已不存在";
|
||||
if (card.scope.kind === "session")
|
||||
return card.scope.title
|
||||
? `会话「${card.scope.title}」`
|
||||
: "所属会话已不存在";
|
||||
return "独立画布";
|
||||
}
|
||||
|
||||
function keepReasonText(card: LibraryUsageCard) {
|
||||
switch (card.file_keep_reason) {
|
||||
case "referenced":
|
||||
return "文件仍被其他卡片或项目使用,删除卡片后文件保留";
|
||||
case "project_owned":
|
||||
return "文件属于项目输出,删除卡片不会删除文件";
|
||||
case "outside_assets":
|
||||
return "文件不在素材库删除范围内,删除卡片不会删除文件";
|
||||
default:
|
||||
return "删除卡片不会删除文件";
|
||||
}
|
||||
}
|
||||
|
||||
function locateCard(card: LibraryUsageCard) {
|
||||
usagePaths = [];
|
||||
pendingAction = null;
|
||||
goto(resolve(`/canvas/${card.canvas_id}?locate=${card.node_id}`));
|
||||
}
|
||||
|
||||
async function performUsageAction() {
|
||||
if (!pendingAction || usageBusy) return;
|
||||
const { kind, path, card } = pendingAction;
|
||||
usageBusy = true;
|
||||
try {
|
||||
const res = await canvasApi.deleteNode(
|
||||
card.canvas_id,
|
||||
card.node_id,
|
||||
kind === "release",
|
||||
);
|
||||
pendingAction = null;
|
||||
if (kind === "release")
|
||||
toast.success("已仅移除卡片,原文件保留在素材库");
|
||||
else if (res.file_deleted)
|
||||
toast.success("卡片已删除,文件已一并删除");
|
||||
else toast.success("卡片已删除,文件保留");
|
||||
void loadUsage(path);
|
||||
void client.invalidateQueries({ queryKey: ["library-media"] });
|
||||
} catch (e) {
|
||||
toast.error(`处理卡片失败:${apiErrorMessage(e)}`);
|
||||
} finally {
|
||||
usageBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFreedFile(path: string) {
|
||||
try {
|
||||
const res = await libraryApi.deleteMany([path]);
|
||||
const r = res.results[0];
|
||||
if (r?.status === "deleted") {
|
||||
toast.success("文件已删除");
|
||||
usagePaths = usagePaths.filter((p) => p !== path);
|
||||
} else {
|
||||
toast.error(`未能删除 · ${KEPT_REASONS[r?.reason ?? "other"] ?? "无法删除"}`);
|
||||
if (r?.reason === "on_canvas") void loadUsage(path);
|
||||
}
|
||||
void client.invalidateQueries({ queryKey: ["library-media"] });
|
||||
} catch (e) {
|
||||
toast.error(`删除请求失败:${apiErrorMessage(e)}`);
|
||||
}
|
||||
}
|
||||
function attached(path: string, title: string) {
|
||||
attachPaths = attachPaths.filter((p) => p !== path);
|
||||
selected.delete(path);
|
||||
@@ -534,6 +701,131 @@
|
||||
}}
|
||||
/>{/if}
|
||||
</Modal>
|
||||
<Modal
|
||||
open={usagePaths.length > 0}
|
||||
title="画布占用详情"
|
||||
size="lg"
|
||||
onclose={() => {
|
||||
usagePaths = [];
|
||||
pendingAction = null;
|
||||
}}
|
||||
>
|
||||
{#each usagePaths as path (path)}{@const item = items.find((i) => i.path === path)}{@const usage = usageData[path]}
|
||||
<section class="usage-file">
|
||||
<header class="usage-head">
|
||||
{#if item}<SafeMedia
|
||||
src={assetUrl(item.path)}
|
||||
kind={item.kind}
|
||||
alt={item.name}
|
||||
controls={false}
|
||||
/>{/if}
|
||||
<div class="usage-title">
|
||||
<b>{item?.name ?? path}</b>
|
||||
<span>删除被保留,因为仍在画布中使用。逐个处理下面的卡片后即可删除。</span>
|
||||
</div>
|
||||
</header>
|
||||
{#if usageLoading[path] && !usage}<p class="usage-empty">正在核对占用…</p>
|
||||
{:else if usageError[path]}
|
||||
<p class="usage-empty usage-error">占用信息读取失败:{usageError[path]}</p>
|
||||
<Button size="sm" onclick={() => loadUsage(path)}>重试</Button>
|
||||
{:else if usage}
|
||||
{#if usage.usages.length === 0 && usage.invalid_total === 0}
|
||||
<div class="usage-free">
|
||||
<p>当前没有画布卡片占用此文件了,现在可以删除。</p>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
onclick={() => deleteFreedFile(path)}>删除此文件</Button
|
||||
>
|
||||
</div>
|
||||
{:else}
|
||||
<ul class="usage-list">
|
||||
{#each usage.usages as card (card.canvas_id * 1e9 + card.node_id)}
|
||||
<li class="usage-card">
|
||||
<div class="u-info">
|
||||
<b title={card.node_title ?? ""}>「{card.node_title || "未命名卡片"}」</b>
|
||||
<span class="u-where">
|
||||
画布「{card.canvas_title}」· {scopeText(card)} · 卡片 #{card.node_id}
|
||||
</span>
|
||||
{#if card.job_running}
|
||||
<span class="u-effect u-warn">生成中,完成后才能处理这张卡</span>
|
||||
{:else if card.deleting_card_deletes_file}
|
||||
<span class="u-effect u-danger"
|
||||
>删除卡片将同时删除文件(这是最后一份引用)</span
|
||||
>
|
||||
{:else}
|
||||
<span class="u-effect">{keepReasonText(card)}</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="u-actions">
|
||||
<Button size="sm" variant="ghost" onclick={() => locateCard(card)}
|
||||
><Icon name="pin" size={14} />定位</Button
|
||||
>
|
||||
{#if !card.job_running}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
onclick={() =>
|
||||
(pendingAction = { kind: "delete", path, card })}>删除卡片…</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onclick={() =>
|
||||
(pendingAction = { kind: "release", path, card })}
|
||||
>仅移除卡片</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{#if usage.usages.length < usage.valid_total}
|
||||
<button
|
||||
class="usage-more"
|
||||
onclick={() => loadUsage(path, usage.usages.length)}
|
||||
>还有 {usage.valid_total - usage.usages.length} 处引用,展开下一批(每次 {usage.limit} 条)</button
|
||||
>
|
||||
{/if}
|
||||
{#if usage.invalid_total > 0}
|
||||
<p class="usage-invalid">
|
||||
另有 {usage.invalid_total} 条已失效引用(所属画布已不存在),不占用此文件,也无需处理。
|
||||
</p>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
</section>
|
||||
{/each}
|
||||
{#if pendingAction}{@const card = pendingAction.card}
|
||||
<div class="usage-confirm" role="alertdialog" aria-label="确认处理画布卡片">
|
||||
{#if pendingAction.kind === "delete"}
|
||||
<p>
|
||||
删除画布「{card.canvas_title}」({scopeText(card)})的卡片「{card
|
||||
.node_title || "未命名卡片"}」?
|
||||
{#if card.deleting_card_deletes_file}
|
||||
该文件没有其他引用,删除卡片时会<b>同时删除文件</b>。
|
||||
{:else}
|
||||
{keepReasonText(card)}。
|
||||
{/if}
|
||||
</p>
|
||||
{:else}
|
||||
<p>
|
||||
仅移除画布「{card.canvas_title}」({scopeText(card)})的卡片「{card
|
||||
.node_title || "未命名卡片"}」?卡片会从画布消失,<b>原文件保留</b>在素材库,可继续删除或另作他用。
|
||||
</p>
|
||||
{/if}
|
||||
<div class="usage-confirm-actions">
|
||||
<Button variant="ghost" onclick={() => (pendingAction = null)}>取消</Button>
|
||||
<Button
|
||||
variant={pendingAction.kind === "delete" ? "danger" : "secondary"}
|
||||
loading={usageBusy}
|
||||
onclick={performUsageAction}
|
||||
>{pendingAction.kind === "delete" ? "确认删除卡片" : "确认仅移除"}</Button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
{#if fullscreen && focused}<ImageLightbox
|
||||
src={assetUrl(focused.path)}
|
||||
alt={focused.name}
|
||||
|
||||
@@ -630,6 +630,155 @@
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
/* ── Canvas occupancy report (HEL-884) ───────────────────────────── */
|
||||
.usage-file {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 10px 0;
|
||||
}
|
||||
.usage-file + .usage-file {
|
||||
border-top: 1px solid var(--line-2);
|
||||
}
|
||||
.usage-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.usage-head img,
|
||||
.usage-head video {
|
||||
width: 56px;
|
||||
height: 42px;
|
||||
border-radius: var(--r-sm);
|
||||
object-fit: cover;
|
||||
flex: none;
|
||||
}
|
||||
.usage-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
.usage-title b {
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.usage-title span {
|
||||
font-size: 11.5px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.usage-empty {
|
||||
font-size: 12px;
|
||||
color: var(--tx-2);
|
||||
}
|
||||
.usage-error {
|
||||
color: var(--err);
|
||||
}
|
||||
.usage-free {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
justify-content: space-between;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--ok) 32%, transparent);
|
||||
border-radius: var(--r-md);
|
||||
background: color-mix(in srgb, var(--ok) 8%, transparent);
|
||||
}
|
||||
.usage-free p {
|
||||
font-size: 12.5px;
|
||||
margin: 0;
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.usage-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.usage-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
justify-content: space-between;
|
||||
padding: 9px 11px;
|
||||
border: 1px solid var(--line-2);
|
||||
border-radius: var(--r-md);
|
||||
}
|
||||
.u-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
.u-info b {
|
||||
font-size: 12.5px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.u-where {
|
||||
font-size: 11.5px;
|
||||
color: var(--tx-2);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.u-effect {
|
||||
font-size: 11px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.u-effect.u-warn {
|
||||
color: var(--warn, var(--gold));
|
||||
}
|
||||
.u-effect.u-danger {
|
||||
color: var(--err);
|
||||
}
|
||||
.u-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex: none;
|
||||
}
|
||||
.usage-more {
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--tx-2);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
padding: 4px 0;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
.usage-more:hover {
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.usage-invalid {
|
||||
font-size: 11.5px;
|
||||
color: var(--tx-3);
|
||||
margin: 0;
|
||||
}
|
||||
.usage-confirm {
|
||||
margin-top: 12px;
|
||||
padding: 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--err) 30%, transparent);
|
||||
border-radius: var(--r-md);
|
||||
background: color-mix(in srgb, var(--err) 6%, transparent);
|
||||
}
|
||||
.usage-confirm p {
|
||||
margin: 0 0 10px;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.55;
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.usage-confirm-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
html[data-motion="full"] .selbar.on {
|
||||
animation: library-selection var(--t-base) var(--ease-out);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user