Files
aigc-home/calliope-web/src/lib/components/studio/RefImageGrid.svelte
T

318 lines
8.5 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script lang="ts">
import ImageLightbox from '$lib/components/ImageLightbox.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import { assetUrl } from '$lib/api';
import {
IMAGE_SLOT_ACCEPT,
formatBytes,
mediaSlotAccept,
uploadBaseName,
type MediaSlotKind,
} from '$lib/comfy/imageFile';
import { t } from '$lib/i18n.svelte';
/**
* Reference-media list as numbered composer tiles (spec-v2 §3.3 参考图):
* 1…N in the order they reach the workflow — click a tile to preview it (replace from the preview toolbar),
* ✕ to remove; a dashed add tile while below `max`; rejected files show
* as red tiles that take no place in the list.
*/
interface Reject {
name: string;
message: string;
}
interface Props {
previewContext?: unknown;
label: string;
paths: string[];
max: number;
/** Media family of the slots — drives thumbnails, accept and copy. */
mediaKind?: MediaSlotKind;
/** Byte sizes of files uploaded in this session, by server path. */
sizes?: Record<string, number>;
/** Name of the file being uploaded (add or replace), if any. */
uploadingName?: string;
/** Index being replaced while uploading (-1 = adding). */
uploadingIndex?: number;
rejects?: Reject[];
/** Below the minimum after a blocked 生成 (amber add tile). */
need?: boolean;
error?: string;
allowFromResults?: boolean;
/** Anchor id on the add tile so 「还缺:…」 can jump focus here. */
anchorId?: string;
onAdd: (files: File[]) => void;
onReplace: (index: number, file: File) => void;
onRemove: (index: number) => void;
onDismissReject: (index: number) => void;
onFromResults?: () => void;
onFromScene?: () => void;
}
let {
previewContext,
label,
paths,
max,
mediaKind = 'image',
sizes = {},
uploadingName,
uploadingIndex = -1,
rejects = [],
need = false,
error,
allowFromResults = false,
anchorId,
onAdd,
onReplace,
onRemove,
onDismissReject,
onFromResults,
onFromScene,
}: Props = $props();
let previewIndex = $state<number | null>(null);
$effect(() => {
void previewContext;
void paths;
void mediaKind;
previewIndex = null;
});
const previewPath = $derived(
previewIndex == null ? '' : (paths[previewIndex] ?? ''),
);
let addInput = $state<HTMLInputElement | null>(null);
let replaceInput = $state<HTMLInputElement | null>(null);
let replaceIndex = $state(-1);
let dragDepth = $state(0);
let dims = $state<Record<string, string>>({});
let durations = $state<Record<string, number>>({});
const uploading = $derived(!!uploadingName);
const remaining = $derived(Math.max(0, max - paths.length));
const accept = $derived(
mediaKind === 'image' ? IMAGE_SLOT_ACCEPT : mediaSlotAccept(mediaKind),
);
const isMedia = $derived(mediaKind !== 'image');
const hintLabel = $derived(
isMedia
? t('studio.refHintMedia', { n: paths.length, max })
: t('studio.refHint', { n: paths.length, max }),
);
function noteDuration(path: string, e: Event): void {
const el = e.currentTarget as HTMLVideoElement | HTMLAudioElement | null;
if (el && Number.isFinite(el.duration)) durations = { ...durations, [path]: el.duration };
}
function noteDims(path: string, e: Event) {
const img = e.currentTarget as HTMLImageElement;
if (img.naturalWidth) dims = { ...dims, [path]: `${img.naturalWidth}×${img.naturalHeight}` };
}
function metaOf(path: string): string {
const d = durations[path];
return [
uploadBaseName(path),
dims[path],
d != null && Number.isFinite(d) ? `${d.toFixed(1)}s` : null,
sizes[path] != null ? formatBytes(sizes[path]) : null,
]
.filter(Boolean)
.join(' · ');
}
function pickAdd() {
if (uploading || !addInput) return;
addInput.value = '';
addInput.click();
}
function pickReplace(i: number) {
if (uploading || !replaceInput) return;
replaceIndex = i;
replaceInput.value = '';
replaceInput.click();
}
function onDrop(e: DragEvent) {
e.preventDefault();
e.stopPropagation();
dragDepth = 0;
if (uploading) return;
const files = Array.from(e.dataTransfer?.files ?? []);
if (files.length) onAdd(files);
}
</script>
<ImageLightbox
src={previewPath ? assetUrl(previewPath) : null}
kind={mediaKind}
alt={label}
caption={previewPath ? metaOf(previewPath) : ''}
images={paths.map((path) => assetUrl(path) ?? '')}
index={previewIndex ?? 0}
onnavigate={(i) => (previewIndex = i)}
onClose={() => (previewIndex = null)}
onReplace={() => {
const i = previewIndex;
previewIndex = null;
if (i != null) pickReplace(i);
}}
/>
<div class="a-slot">
<div class="a-slot-label">
<span>{label}</span>
<span class="req" aria-hidden="true">*</span>
<span class="mono">{hintLabel}</span>
{#if onFromScene}<button type="button" class="a-btn ghost xs" onclick={onFromScene}>从三维搭景截取</button>{/if}
{#if allowFromResults && onFromResults && remaining > 0}
<button type="button" class="a-btn ghost xs" onclick={onFromResults}>
{t('studio.slotFromResultsShort')}
</button>
{/if}
</div>
<input
bind:this={addInput}
type="file"
class="sr-file"
tabindex="-1"
aria-hidden="true"
{accept}
multiple
onchange={(e) => {
const files = Array.from(e.currentTarget.files ?? []);
if (files.length) onAdd(files);
}}
/>
<input
bind:this={replaceInput}
type="file"
class="sr-file"
tabindex="-1"
aria-hidden="true"
{accept}
onchange={(e) => {
const f = e.currentTarget.files?.[0];
if (f && replaceIndex >= 0) onReplace(replaceIndex, f);
}}
/>
<div class="a-slot-row">
{#each paths as path, i (path + i)}
<div class="a-tile">
<button
type="button"
class="a-tile-hit"
title={`${t('lightbox.mediaPreview')} · ${metaOf(path)}`}
aria-label={`${t('lightbox.mediaPreview')} ${label} ${i + 1}`}
disabled={uploading}
onclick={() => (previewIndex = i)}
>
{#if mediaKind === 'image'}
<img src={assetUrl(path)} alt="" onload={(e) => noteDims(path, e)} />
{:else if mediaKind === 'video'}
<video
src={assetUrl(path)}
preload="metadata"
muted
playsinline
onloadedmetadata={(e) => noteDuration(path, e)}
></video>
{:else}
<Icon name="music" size={18} />
<audio src={assetUrl(path)} preload="metadata" onloadedmetadata={(e) => noteDuration(path, e)}
></audio>
{/if}
</button>
<span class="a-tile-idx">{i + 1}</span>
{#if uploadingIndex === i}
<span class="a-tile-ring" title={uploadingName}><i></i></span>
{:else}
<button
type="button"
class="a-tile-x"
aria-label={isMedia
? t('studio.refRemoveMedia', { kind: label, n: i + 1 })
: t('studio.refRemove', { n: i + 1 })}
onclick={() => onRemove(i)}
>
<Icon name="close" size={10} />
</button>
{/if}
</div>
{/each}
{#each rejects as rej, i (rej.name + i)}
<div class="a-tile bad" title={`${rej.name} · ${rej.message}`} role="img" aria-label={rej.name}>
<Icon name="alert" size={16} />
<button
type="button"
class="a-tile-x"
aria-label={`${t('studio.deleteBtn')} ${rej.name}`}
onclick={() => onDismissReject(i)}
>
<Icon name="close" size={10} />
</button>
</div>
{/each}
{#if remaining > 0}
<button
type="button"
id={anchorId}
class="a-tile add"
class:drag={dragDepth > 0}
class:need={need && !error?.trim()}
class:bad={!!error?.trim()}
title={isMedia
? t('studio.refAddSubMedia', { n: remaining, max })
: t('studio.refAddSub', { n: remaining, max })}
aria-label={isMedia ? t('studio.refAddMedia', { kind: label }) : t('studio.refAdd')}
aria-busy={uploading || undefined}
disabled={uploading}
onclick={pickAdd}
ondragenter={(e) => {
e.preventDefault();
dragDepth += 1;
}}
ondragleave={() => (dragDepth = Math.max(0, dragDepth - 1))}
ondragover={(e) => e.preventDefault()}
ondrop={onDrop}
>
{#if uploading && uploadingIndex < 0}
<span class="a-tile-ring" title={uploadingName}><i></i></span>
{:else}
<Icon name="plus" size={18} />
{/if}
</button>
{/if}
</div>
{#if remaining === 0}
<span class="a-slot-hint">{isMedia ? t('studio.refFullMedia', { max }) : t('studio.refFull', { max })}</span>
{/if}
{#each rejects as rej, i (rej.name + i)}
<span class="a-slot-hint err" role="alert">{rej.message}</span>
{/each}
{#if error?.trim()}<span class="a-slot-hint err" role="alert">{error}</span>{/if}
</div>
<style>
.sr-file {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
border: 0;
}
audio {
display: none;
}
</style>