feat(*): 创作与运维 - 新增图片尺寸预设和系统性能面板并优化图片组动画

This commit is contained in:
ddCat
2026-09-07 14:03:50 +08:00
parent df94c3bdf1
commit bd639745ac
41 changed files with 2785 additions and 353 deletions

View File

@@ -43,6 +43,7 @@ export type CanvasNodeContentProps = {
textareaRef: RefObject<HTMLTextAreaElement | null>;
isBatchRoot: boolean;
batchCount: number;
batchPreviewNodes?: CanvasNodeData[];
batchExpanded: boolean;
batchOpening: boolean;
batchRecovering: boolean;
@@ -398,13 +399,13 @@ function ImageNodeContent(props: CanvasNodeContentProps) {
: props.node.metadata?.status === "error"
? <ErrorContent node={props.node} theme={props.theme} onRetry={props.onRetry} onReloadResource={props.onReloadResource} />
: <EmptyImageContent {...props} isBatchRoot={false} />;
return <BatchFrame batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} theme={props.theme} onToggleBatch={props.onToggleBatch}>{content}</BatchFrame>;
return <BatchFrame batchPreviewNodes={props.batchPreviewNodes} batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} theme={props.theme} onToggleBatch={props.onToggleBatch}>{content}</BatchFrame>;
}
if (!props.node.metadata?.content) return <EmptyImageContent {...props} />;
return <ImageContent node={props.node} theme={props.theme} isBatchRoot={props.isBatchRoot} batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} onToggleBatch={props.onToggleBatch} />;
return <ImageContent batchPreviewNodes={props.batchPreviewNodes} node={props.node} theme={props.theme} isBatchRoot={props.isBatchRoot} batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} onToggleBatch={props.onToggleBatch} />;
}
function EmptyImageContent({ node, theme, isBatchRoot, batchCount, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: CanvasNodeContentProps) {
function EmptyImageContent({ node, theme, isBatchRoot, batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: CanvasNodeContentProps) {
const isCharacterReference = node.metadata?.workflowKind === "character" && node.metadata?.characterView === "multi";
const content = (
<div className="flex h-full w-full flex-col items-center justify-center gap-3" style={{ color: theme.node.placeholder }}>
@@ -417,7 +418,7 @@ function EmptyImageContent({ node, theme, isBatchRoot, batchCount, batchExpanded
) : <span className="text-[var(--fs-tiny)] tracking-[0.18em] opacity-50">空图片节点</span>}
</div>
);
if (isBatchRoot) return <BatchFrame batchCount={batchCount} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>{content}</BatchFrame>;
if (isBatchRoot) return <BatchFrame batchPreviewNodes={batchPreviewNodes} batchCount={batchCount} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>{content}</BatchFrame>;
return content;
}
@@ -571,7 +572,7 @@ function EmptyMediaContent({ icon, label, color }: { icon: ReactNode; label: str
return <div className="flex h-full w-full flex-col items-center justify-center gap-3" style={{ color }}>{icon}<span className="text-sm">{label}</span></div>;
}
function ImageContent({ node, theme, isBatchRoot, batchCount, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: Pick<CanvasNodeContentProps, "node" | "theme" | "isBatchRoot" | "batchCount" | "batchExpanded" | "batchOpening" | "batchRecovering" | "onToggleBatch">) {
function ImageContent({ node, theme, isBatchRoot, batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: Pick<CanvasNodeContentProps, "node" | "theme" | "isBatchRoot" | "batchCount" | "batchPreviewNodes" | "batchExpanded" | "batchOpening" | "batchRecovering" | "onToggleBatch">) {
const imageContainerRef = useRef<HTMLDivElement>(null);
const nearViewport = useNearViewport(imageContainerRef);
const { url, loading } = useNodeResourceUrl(node, nearViewport);
@@ -615,7 +616,7 @@ function ImageContent({ node, theme, isBatchRoot, batchCount, batchExpanded, bat
};
return (
<BatchFrame batchCount={isBatchRoot ? batchCount : 0} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>
<BatchFrame batchPreviewNodes={batchPreviewNodes} batchCount={isBatchRoot ? batchCount : 0} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>
<div ref={imageContainerRef} className="h-full w-full overflow-hidden rounded-[var(--node-radius)]">
{url ? <img src={url} alt={node.title} loading="lazy" decoding="async" draggable={false} onDragStart={(event) => event.preventDefault()} onLoad={(event) => fitToImage(event.currentTarget)} className={`pointer-events-none block h-full w-full select-none ${node.metadata?.freeResize ? "object-fill" : "object-contain"}`} /> : <div className="grid size-full place-items-center" style={{ color: theme.node.muted }}>{loading ? <LoaderCircle className="size-5 animate-spin" /> : <ImageIcon className="size-5 opacity-45" />}</div>}
</div>
@@ -695,7 +696,14 @@ export function CanvasNodeImageInfo({ node }: { node: CanvasNodeData }) {
return <span className="ml-auto max-w-full shrink-0 truncate rounded-[var(--r-sm)] bg-black/55 px-2 py-1 text-[var(--fs-label)] font-medium leading-none text-white backdrop-blur-sm">{width} x {height}{size ? ` · ${size}` : ""}</span>;
}
function BatchFrame({ batchCount, batchExpanded, batchOpening, batchRecovering, theme, onToggleBatch, children }: { batchCount: number; batchExpanded: boolean; batchOpening: boolean; batchRecovering: boolean; theme: CanvasTheme; onToggleBatch?: () => void; children: ReactNode }) {
function BatchPreviewImage({ node }: { node: CanvasNodeData }) {
const ref = useRef<HTMLDivElement>(null);
const nearViewport = useNearViewport(ref);
const { url } = useNodeResourceUrl(node, nearViewport);
return <div ref={ref} className="h-full w-full overflow-hidden rounded-[inherit]">{url ? <img src={url} alt={`子图预览:${node.title}`} className="h-full w-full object-contain" draggable={false} /> : null}</div>;
}
function BatchFrame({ batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, theme, onToggleBatch, children }: { batchCount: number; batchPreviewNodes?: CanvasNodeData[]; batchExpanded: boolean; batchOpening: boolean; batchRecovering: boolean; theme: CanvasTheme; onToggleBatch?: () => void; children: ReactNode }) {
const isBatchRoot = batchCount > 1;
return (
<div className="group/batch relative h-full w-full overflow-visible" onDoubleClick={isBatchRoot ? (event) => { event.stopPropagation(); onToggleBatch?.(); } : undefined}>
@@ -704,7 +712,7 @@ function BatchFrame({ batchCount, batchExpanded, batchOpening, batchRecovering,
{Array.from({ length: Math.min(batchCount - 1, 5) }).map((_, index) => (
<div
key={index}
className="absolute rounded-[inherit] transition-all duration-300 group-hover/batch:translate-x-2"
className="absolute rounded-[var(--r-lg)] transition-all duration-300 group-hover/batch:translate-x-2"
style={{
inset: 0,
background: theme.node.panel,
@@ -713,7 +721,9 @@ function BatchFrame({ batchCount, batchExpanded, batchOpening, batchRecovering,
transform: batchOpening || batchRecovering ? `translate(${54 + index * 22}px, ${20 + index * 12}px) rotate(${8 + index * 5}deg) scale(.98)` : `translate(${34 + index * 18}px, ${14 + index * 10}px) rotate(${6 + index * 4}deg)`,
zIndex: -index - 1,
}}
/>
>
{batchPreviewNodes?.[index] ? <BatchPreviewImage node={batchPreviewNodes[index]} /> : null}
</div>
))}
</div>
) : null}

View File

@@ -37,6 +37,7 @@ type CanvasNodeProps = {
renderNodeContent?: (node: CanvasNodeData) => ReactNode;
drawingProjectId?: string;
batchCount?: number;
batchPreviewNodes?: CanvasNodeData[];
batchExpanded?: boolean;
batchClosing?: boolean;
batchOpening?: boolean;
@@ -83,6 +84,7 @@ export const CanvasNode = React.memo(function CanvasNode({
renderNodeContent,
drawingProjectId,
batchCount = 0,
batchPreviewNodes,
batchExpanded = false,
batchClosing = false,
batchOpening = false,
@@ -347,8 +349,8 @@ export const CanvasNode = React.memo(function CanvasNode({
"--batch-from-x": `${batchMotion?.x || 0}px`,
"--batch-from-y": `${batchMotion?.y || 0}px`,
"--batch-from-rotate": `${6 + (batchMotion?.index || 0) * 4}deg`,
animation: data.metadata?.batchRootId ? (batchClosing ? `canvas-batch-child-out var(--motion-dur-base-calc) var(--motion-ease-in-out) both` : `canvas-batch-child-in var(--motion-dur-slow-calc) var(--motion-ease-out) both`) : undefined,
animationDelay: data.metadata?.batchRootId ? `${batchClosing ? 0 : 45 + (batchMotion?.index || 0) * 24}ms` : undefined,
animation: isBatchChild && (batchClosing || batchOpening) ? (batchClosing ? `canvas-batch-child-out var(--motion-dur-base-calc) var(--motion-ease-in-out) both` : `canvas-batch-child-in var(--motion-dur-slow-calc) var(--motion-ease-out) both`) : undefined,
animationDelay: isBatchChild && (batchClosing || batchOpening) ? `${batchClosing ? 0 : 45 + (batchMotion?.index || 0) * 24}ms` : undefined,
} as React.CSSProperties
}
>
@@ -363,6 +365,7 @@ export const CanvasNode = React.memo(function CanvasNode({
textareaRef={textareaRef}
isBatchRoot={isBatchRoot}
batchCount={batchCount}
batchPreviewNodes={batchPreviewNodes}
batchExpanded={batchExpanded}
batchOpening={batchOpening}
batchRecovering={batchRecovering}
@@ -494,6 +497,7 @@ function areCanvasNodePropsEqual(previous: CanvasNodeProps, next: CanvasNodeProp
previous.renderNodeContent === next.renderNodeContent &&
previous.drawingProjectId === next.drawingProjectId &&
previous.batchCount === next.batchCount &&
previous.batchPreviewNodes === next.batchPreviewNodes &&
previous.batchExpanded === next.batchExpanded &&
previous.batchClosing === next.batchClosing &&
previous.batchOpening === next.batchOpening &&
@@ -548,7 +552,7 @@ function NodeLockBadge({ theme }: { theme: CanvasTheme }) {
function BatchToggleBadge({ count, expanded, theme, onToggle }: { count: number; expanded: boolean; theme: CanvasTheme; onToggle: () => void }) {
return (
<button type="button" className="canvas-node-tool-button inline-flex h-7 shrink-0 items-center gap-1 rounded-md border px-2 text-[var(--fs-tiny)] font-semibold backdrop-blur-md" style={{ background: `${theme.toolbar.panel}d9`, borderColor: `${theme.toolbar.border}cc`, color: theme.node.text }} aria-label={expanded ? "图片组已展开" : "图片组已收起"} onClick={(event) => { event.stopPropagation(); onToggle(); }} onMouseDown={(event) => event.stopPropagation()} onPointerDown={(event) => event.stopPropagation()}>
<button type="button" className="canvas-node-tool-button inline-flex h-7 shrink-0 items-center gap-1 rounded-md border px-2 text-[var(--fs-tiny)] font-semibold backdrop-blur-md" style={{ background: `${theme.toolbar.panel}d9`, borderColor: `${theme.toolbar.border}cc`, color: theme.node.text }} aria-expanded={expanded} aria-label={expanded ? "收起图片组" : "展开图片组"} onClick={(event) => { event.stopPropagation(); onToggle(); }} onMouseDown={(event) => event.stopPropagation()} onPointerDown={(event) => event.stopPropagation()}>
<span className="leading-none" style={{ color: theme.accent.primary }}>{count}</span>
<ChevronRight className={`size-3 opacity-55 transition-transform ${expanded ? "rotate-90" : ""}`} />
</button>

View File

@@ -158,7 +158,7 @@ export function CanvasConnectionCreateMenu({ pending, viewport, viewportSize, co
const reducedMotion = useReducedMotion();
const menuRef = useRef<HTMLDivElement>(null);
const { bringToFront, zIndex } = useCanvasOverlayLayer("connection-create-menu", "var(--z-modal-overlay)");
const menuWidth = 248;
const menuWidth = Math.min(288, viewportSize.width - 24);
const menuHeight = canCreateDrawing ? 456 : 412;
const gap = 12;
const initialPosition = getConnectionMenuPosition(pending.position, viewport, viewportSize, menuWidth, menuHeight, gap);
@@ -188,10 +188,10 @@ export function CanvasConnectionCreateMenu({ pending, viewport, viewportSize, co
initial={reducedMotion ? { opacity: 0 } : { opacity: 0, y: 6, scale: 0.97, rotateX: 2 }}
animate={{ opacity: 1, y: 0, scale: 1, rotateX: 0 }}
transition={{ duration: aceternityMotion.duration.instant, ease: aceternityMotion.easing.enter }}
className="aceternity-floating-panel absolute w-[248px] origin-top-left overflow-hidden rounded-[var(--r-2xl)] border p-2 backdrop-blur-2xl"
className="aceternity-floating-panel absolute origin-top-left overflow-x-hidden overflow-y-auto rounded-[var(--r-2xl)] border p-2 backdrop-blur-2xl"
data-canvas-no-zoom
data-connection-create-menu
style={{ left: initialPosition.left, top: initialPosition.top, zIndex, background: theme.spatial.elevated, borderColor: theme.toolbar.border, color: theme.node.text }}
style={{ width: menuWidth, maxHeight: Math.max(120, viewportSize.height - 84), left: initialPosition.left, top: initialPosition.top, zIndex, background: theme.spatial.elevated, borderColor: theme.toolbar.border, color: theme.node.text }}
onMouseDown={(event) => event.stopPropagation()}
onPointerDownCapture={bringToFront}
onFocusCapture={bringToFront}
@@ -205,7 +205,7 @@ export function CanvasConnectionCreateMenu({ pending, viewport, viewportSize, co
</span>
<button type="button" className="grid size-6 shrink-0 place-items-center rounded-full border opacity-55 transition-opacity hover:opacity-100" style={{ background: theme.spatial.surface, borderColor: theme.toolbar.border }} onClick={onClose} aria-label="关闭连线创建菜单"><X className="size-3" /></button>
</div>
<div className="grid gap-1">
<div className="grid min-w-0 grid-cols-1 gap-1">
<ConnectionCreateOption motionEnabled={!reducedMotion} icon={<List className="size-4" />} title="文本生成" disabledReason={getDisabledReason(CanvasNodeType.Text)} onClick={() => onCreate(CanvasNodeType.Text)} />
<ConnectionCreateOption motionEnabled={!reducedMotion} icon={<Clapperboard className="size-4" />} title="分镜脚本" disabledReason={getDisabledReason(CanvasNodeType.Script)} onClick={() => onCreate(CanvasNodeType.Script)} />
<ConnectionCreateOption motionEnabled={!reducedMotion} icon={<ImageIcon className="size-4" />} title="图片生成" disabledReason={getDisabledReason(CanvasNodeType.Image)} onClick={() => onCreate(CanvasNodeType.Image)} />
@@ -225,7 +225,7 @@ function ConnectionCreateOption({ motionEnabled, icon, title, description, disab
<span className="grid size-7 shrink-0 place-items-center rounded-[var(--r-md)] opacity-65 transition-opacity group-hover:opacity-100 [&_svg]:size-3.5" style={{ background: theme.toolbar.itemHover }}>{icon}</span>
<span className="min-w-0 flex-1">
<span className="flex items-center gap-2 text-[var(--fs-tiny)] font-semibold leading-4">{title}</span>
{disabledReason || description ? <span className="mt-0.5 block truncate text-[var(--fs-micro)]" style={{ color: theme.node.muted }}>{disabledReason || description}</span> : null}
{disabledReason || description ? <span className="mt-0.5 block whitespace-normal break-words text-[var(--fs-micro)] leading-relaxed" style={{ color: theme.node.muted }}>{disabledReason || description}</span> : null}
</span>
<ChevronRight className="size-3.5 shrink-0 opacity-35 transition-transform group-hover:translate-x-0.5" />
</motion.button>

View File

@@ -1,8 +1,10 @@
import { type ReactNode, useState } from "react";
import { ImageSizePicker } from "./image-size-picker";
import { imageResolutionUsesQuality } from "@/lib/image-size-presets";
import { type ReactNode } from "react";
import { ConfigProvider, Switch } from "antd";
import { type CanvasTheme } from "@/lib/canvas-theme";
import { buildImageResolutionOptions, formatImageResolutionSize, imageRatioForSize, imageResolutionChoices, imageResolutionOption, imageSizeForResolution, supportsImageResolutionPresets, type ImageResolutionChoice } from "@/lib/image-resolution-tiers";
import { buildImageResolutionOptions, formatImageResolutionSize } from "@/lib/image-resolution-tiers";
import { modelCapabilityConfigFor, normalizeImageValue, type ImageCapabilityConfig } from "@/lib/model-capabilities";
import { mergedImageCapabilityConfig } from "@/lib/model-selection";
import { modelOptionName, resolveModelChannel, type AiConfig } from "@/stores/use-config-store";
@@ -14,8 +16,8 @@ const qualityOptions = [
{ value: "low", label: "低" },
{ value: "1k", label: "1K" },
{ value: "2k", label: "2K" },
{ value: "4k", label: "4K" },
];
const DIMENSION_STEP = 16;
type AspectOption = { value: string; label: string; width: number; height: number; icon: string; size?: string };
@@ -50,7 +52,6 @@ type ImageSettingsPanelProps = {
};
export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle = true, showCount = true, className = "w-[304px] space-y-3 rounded-2xl px-1 py-0.5", maxCount = 15, quickCount = 3 }: ImageSettingsPanelProps) {
const [snapDimensionToStep, setSnapDimensionToStep] = useState(true);
const profile = mergedImageCapabilityConfig(config, config.model || config.imageModel);
const normalized = normalizeImageValue(profile, config);
const quality = normalized.quality;
@@ -58,43 +59,8 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
const effectiveMaxCount = Math.min(maxCount, profile.maxOutputs);
const count = Math.max(1, Math.min(effectiveMaxCount, Number(normalized.count)));
const activeSize = normalized.size;
const pixelSizeValues = profile.size.values.filter((value) => value.trim().toLowerCase() !== "auto");
const hasResolutionPresets = supportsImageResolutionPresets(profile.size);
const resolutionOptions = hasResolutionPresets ? buildImageResolutionOptions(pixelSizeValues) : [];
const activeResolution = activeSize === "auto" ? undefined : imageResolutionOption(resolutionOptions, activeSize);
const activeRatio = activeResolution?.ratio || imageRatioForSize(activeSize);
const resolutionChoices = hasResolutionPresets ? imageResolutionChoices(profile.size.values) : [];
// 只有一个分辨率层级时,分辨率切换器没有实际选择意义;更重要的是不能因此把比例列表裁剪成当前层级的 3 个像素尺寸。
// 例如历史 `*` 配置恢复为标准值后,虽然包含 1024x1024/1536x1024/1024x1536,实际仍应展示完整的比例和尺寸选项。
const usesResolutionPicker = resolutionChoices.length > 1;
const availableAspects: AspectOption[] = usesResolutionPicker && activeSize === "auto"
? []
: usesResolutionPicker && activeResolution
? resolutionOptions.filter((item) => item.tier === activeResolution.tier).map((item) => ({ value: item.ratio, label: item.ratio, size: item.size, width: item.width, height: item.height, icon: item.width === item.height ? "square" : item.width > item.height ? "landscape" : "portrait" }))
: imageAspectOptions(profile);
const selectedAspect = availableAspects.find((item) => imageOptionValue(profile, item) === activeSize || item.value === activeSize) || availableAspects.find((item) => item.label === activeRatio);
const dimensions = readSizeDimensions(activeSize, selectedAspect || aspectOptions[0]);
const activeQualityOptions = profile.quality.values.map((value) => qualityOptions.find((item) => item.value === value) || { value, label: value });
const priceTiers = imageModelPriceTiers(config);
const selectAspect = (value: string) => {
const option = availableAspects.find((item) => item.value === value);
onConfigChange("size", option ? imageOptionValue(profile, option) : "auto");
};
const selectResolution = (choice: ImageResolutionChoice) => {
if (choice === "auto") {
onConfigChange("size", "auto");
return;
}
const ratio = activeRatio || availableAspects[0]?.label;
const size = imageSizeForResolution(resolutionOptions, choice, ratio) || resolutionOptions.find((item) => item.tier === choice)?.size;
if (size) onConfigChange("size", size);
};
const updateDimension = (key: "width" | "height", value: number | null) => {
const next = Math.max(1, Math.floor(value || dimensions[key] || 1024));
const width = key === "width" ? next : dimensions.width;
const height = key === "height" ? next : dimensions.height;
onConfigChange("size", `${alignDimension(width, snapDimensionToStep)}x${alignDimension(height, snapDimensionToStep)}`);
};
const activeQualityOptions = profile.quality.values.map((value) => qualityOptions.find((item) => item.value === value) || { value, label: value });
const priceTiers = imageModelPriceTiers(config);
return (
<ImageSettingsTheme theme={theme}>
@@ -108,7 +74,7 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
}}
>
{showTitle ? <div className="text-base font-semibold">图像设置</div> : null}
{profile.quality.supported ? <div className="space-y-2">
{profile.quality.supported && !imageResolutionUsesQuality(profile) ? <div className="space-y-2">
<SettingTitle color={theme.node.muted}>{isGrokResolutionQuality(profile) ? "分辨率" : "质量"}</SettingTitle>
<div className={`grid gap-1.5 ${activeQualityOptions.length <= 2 ? "grid-cols-2" : "grid-cols-4"}`}>
{activeQualityOptions.map((item) => (
@@ -133,52 +99,7 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
/>
</span>
</div> : null}
{resolutionChoices.length ? <div className="space-y-2">
<SettingTitle color={theme.node.muted}>分辨率</SettingTitle>
<div className={`grid gap-1.5 ${resolutionChoices.length <= 2 ? "grid-cols-2" : resolutionChoices.length === 4 ? "grid-cols-4" : "grid-cols-3"}`}>
{resolutionChoices.map((choice) => (
<OptionPill key={choice} selected={choice === "auto" ? activeSize === "auto" : activeResolution?.tier === choice} theme={theme} onClick={() => selectResolution(choice)}>
{choice === "auto" ? "自动" : choice.toUpperCase()}
</OptionPill>
))}
</div>
</div> : null}
{profile.size.allowCustom ? <div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<SettingTitle color={theme.node.muted}>尺寸</SettingTitle>
<div className="flex items-center gap-2">
<span className="text-xs font-medium" style={{ color: theme.node.muted }}>
16倍数对齐
</span>
<span title="输入完成后自动向上补成 16 的倍数" onMouseDown={(event) => event.stopPropagation()}>
<Switch size="small" checked={snapDimensionToStep} onChange={setSnapDimensionToStep} />
</span>
</div>
</div>
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-1.5">
<DimensionInput prefix="W" value={dimensions.width} disabled={activeSize === "auto"} theme={theme} alignToStep={snapDimensionToStep} onChange={(value) => updateDimension("width", value)} />
<span className="text-sm opacity-45">↔</span>
<DimensionInput prefix="H" value={dimensions.height} disabled={activeSize === "auto"} theme={theme} alignToStep={snapDimensionToStep} onChange={(value) => updateDimension("height", value)} />
</div>
</div> : null}
{availableAspects.length ? <div className="space-y-2">
<SettingTitle color={theme.node.muted}>尺寸或比例</SettingTitle>
<div className="grid grid-cols-4 gap-1.5 min-[380px]:grid-cols-5">
{availableAspects.map((item) => (
<button
key={item.value}
type="button"
className="flex h-[52px] cursor-pointer flex-col items-center justify-center gap-0.5 rounded-lg bg-transparent text-[var(--fs-label)] transition-colors hover:brightness-110 focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1"
style={{ background: selectedAspect?.value === item.value ? theme.toolbar.activeBg : "transparent", color: theme.node.text, outlineColor: theme.node.muted }}
onMouseDown={(event) => event.stopPropagation()}
onClick={() => selectAspect(item.value)}
>
<AspectIcon type={item.icon} width={item.width} height={item.height} color={theme.node.text} />
<span className="whitespace-nowrap">{item.label}</span>
</button>
))}
</div>
</div> : null}
<ImageSizePicker profile={profile} size={activeSize} quality={quality} onChange={(size, nextQuality) => { onConfigChange("size", size); if (nextQuality) onConfigChange("quality", nextQuality); }} />
{showCount && effectiveMaxCount > 1 ? (
<div className="space-y-2">
<SettingTitle color={theme.node.muted}>生成张数</SettingTitle>
@@ -197,45 +118,6 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
);
}
function imageOptionAllowed(profile: ImageCapabilityConfig, option: AspectOption) {
if (profile.size.parameter === "none") return false;
if (profile.size.allowCustom && profile.size.values.length === 0) return true;
return [option.value, option.size, option.width && option.height ? `${option.width}x${option.height}` : ""].filter(Boolean).some((value) => profile.size.values.includes(String(value)));
}
// 宽高比选项直接取模型配置 values(与创作页面一致),不在白名单里的比例(如 8:1)也能显示。
function imageAspectOptions(profile: ImageCapabilityConfig): AspectOption[] {
if (profile.size.parameter === "none") return [];
const values = profile.size.values.filter((value) => value.trim().toLowerCase() !== "auto");
if (!values.length) return profile.size.allowCustom ? aspectOptions.filter((item) => item.value !== "auto") : [];
return values.map((value) => {
const known = aspectOptions.find((item) => (item.size || item.value) === value || item.value === value);
if (known) return known;
const parts = ratioParts(value);
return { value, label: value, size: value, width: parts?.width || 0, height: parts?.height || 0, icon: "custom" };
});
}
function ratioParts(value: string) {
const pixel = value.trim().match(/^(\d+)x(\d+)$/i);
if (pixel) {
const divisor = gcd(Number(pixel[1]), Number(pixel[2]));
return { width: Number(pixel[1]) / divisor, height: Number(pixel[2]) / divisor };
}
const ratio = value.trim().match(/^(\d+):(\d+)$/);
if (!ratio) return undefined;
return { width: Number(ratio[1]), height: Number(ratio[2]) };
}
function gcd(a: number, b: number): number {
return b ? gcd(b, a % b) : a;
}
function imageOptionValue(profile: ImageCapabilityConfig, option: AspectOption) {
const candidates = [option.size, option.value, option.width && option.height ? `${option.width}x${option.height}` : ""].filter(Boolean).map(String);
return candidates.find((value) => profile.size.values.includes(value)) || option.size || option.value || "auto";
}
export function ImageSettingsTheme({ theme, children }: { theme: CanvasTheme; children: ReactNode }) {
return (
<ConfigProvider
@@ -250,12 +132,12 @@ export function ImageSettingsTheme({ theme, children }: { theme: CanvasTheme; ch
}
export function imageQualityLabel(value: string) {
return ({ auto: "自动", high: "高", medium: "中", low: "低", "1k": "1K", "2k": "2K" } as Record<string, string>)[value] || value || "默认";
return ({ auto: "自动", high: "高", medium: "中", low: "低", "1k": "1K", "2k": "2K", "4k": "4K" } as Record<string, string>)[value.toLowerCase()] || value || "默认";
}
function isGrokResolutionQuality(profile: ImageCapabilityConfig) {
const values = profile.quality.values.map((item) => item.toLowerCase());
return values.includes("1k") || values.includes("2k");
return values.some((value) => ["1k", "2k", "4k"].includes(value));
}
export function imageSizeLabel(size: string) {
@@ -292,35 +174,6 @@ function OptionPill({ selected, disabled = false, theme, onClick, children }: {
);
}
function DimensionInput({ prefix, value, disabled, theme, alignToStep, onChange }: { prefix: string; value: number; disabled: boolean; theme: CanvasTheme; alignToStep: boolean; onChange: (value: number | null) => void }) {
const commit = (input: HTMLInputElement) => {
const next = alignDimension(Math.max(1, Math.floor(Number(input.value) || value || 1024)), alignToStep);
input.value = String(next);
onChange(next);
};
return (
<label className="flex h-8 overflow-hidden rounded-lg text-xs" style={{ background: theme.toolbar.itemHover, color: theme.node.text, opacity: disabled ? 0.55 : 1 }}>
<span className="grid w-8 place-items-center" style={{ color: theme.node.muted }}>
{prefix}
</span>
<input
type="number"
min={1}
disabled={disabled}
className="min-w-0 flex-1 bg-transparent px-2 outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
defaultValue={value || ""}
key={`${prefix}-${value}`}
onBlur={(event) => commit(event.currentTarget)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
onMouseDown={(event) => event.stopPropagation()}
/>
</label>
);
}
function CountInput({ value, quickCount, max, theme, onChange }: { value: number; quickCount: number; max: number; theme: CanvasTheme; onChange: (value: number | null) => void }) {
const commit = (input: HTMLInputElement) => {
const next = Math.max(1, Math.min(max, Math.floor(Number(input.value) || 1)));
@@ -349,18 +202,6 @@ function CountInput({ value, quickCount, max, theme, onChange }: { value: number
);
}
function AspectIcon({ type, width, height, color }: { type: string; width: number; height: number; color: string }) {
if (type === "auto") return null;
const ratio = width / Math.max(1, height);
const boxWidth = ratio >= 1 ? 22 : Math.max(9, 22 * ratio);
const boxHeight = ratio >= 1 ? Math.max(9, 22 / ratio) : 22;
return (
<span className="grid h-6 w-8 place-items-center">
<span className="border-2" style={{ width: boxWidth, height: boxHeight, borderColor: color }} />
</span>
);
}
function SettingTitle({ children, color }: { children: string; color: string }) {
return (
<div className="text-xs font-medium" style={{ color }}>
@@ -368,15 +209,3 @@ function SettingTitle({ children, color }: { children: string; color: string })
</div>
);
}
function readSizeDimensions(size: string, fallback: { width: number; height: number }) {
const match = size?.match(/^(\d+)x(\d+)$/);
return {
width: match ? Number(match[1]) : fallback.width,
height: match ? Number(match[2]) : fallback.height,
};
}
function alignDimension(value: number, enabled: boolean) {
return enabled ? Math.ceil(value / DIMENSION_STEP) * DIMENSION_STEP : value;
}

View File

@@ -0,0 +1,264 @@
.image-size-picker,
.image-size-presets-editor {
display: grid;
min-width: 0;
gap: 10px;
width: 100%;
}
.image-size-label {
font-size: var(--fs-label);
font-weight: 600;
}
.image-size-tiers {
display: grid;
grid-auto-flow: column;
grid-auto-columns: minmax(0, 1fr);
gap: 6px;
}
.image-size-tiers button,
.image-size-ratios button,
.image-size-auto {
border: 0;
border-radius: var(--r-md);
color: inherit;
background: var(--library-surface);
padding: 8px;
min-width: 0;
cursor: pointer;
}
.image-size-tiers button[aria-pressed="true"],
.image-size-ratios button[aria-pressed="true"],
.image-size-auto[aria-pressed="true"] {
background: var(--library-surface-hover);
box-shadow: inset 0 0 0 1px var(--library-selected-stroke);
}
.image-size-tiers button:disabled {
opacity: 0.3;
cursor: not-allowed;
}
.image-size-picker button:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}
.image-size-ratios {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(62px, 1fr));
gap: 6px;
}
.image-size-ratios button {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 62px;
font-size: var(--fs-label);
overflow-wrap: anywhere;
}
.image-size-ratio-icon {
display: block;
width: 26px;
border: 1px solid currentColor;
border-radius: 2px;
opacity: 0.6;
}
.image-size-output {
padding: 9px 10px;
border-radius: var(--r-md);
background: var(--library-surface);
font-size: var(--fs-label);
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
.image-size-hint,
.image-size-error {
margin: 0;
font-size: var(--fs-label);
line-height: 1.6;
overflow-wrap: anywhere;
}
.image-size-hint {
opacity: 0.6;
}
.image-size-error {
color: var(--destructive);
}
.image-size-custom summary {
cursor: pointer;
font-size: var(--fs-label);
padding: 6px 0;
}
.image-size-custom-input {
display: flex;
min-width: 0;
gap: 6px;
margin-top: 8px;
}
.image-size-custom-input input {
min-width: 0;
}
.image-size-preset-group {
display: grid;
grid-template-columns: 64px minmax(0, 1fr);
min-width: 0;
gap: 16px;
padding: 16px;
border-radius: var(--r-lg);
background: var(--library-surface);
}
.image-size-presets-editor {
container: image-presets / inline-size;
}
.image-size-editor-intro {
margin: 0 0 2px;
color: var(--muted-foreground);
font-size: var(--fs-label);
line-height: 1.6;
}
.image-size-preset-heading {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
padding-top: 4px;
}
.image-size-preset-heading strong {
font-size: var(--fs-body);
font-variant-numeric: tabular-nums;
}
.image-size-preset-heading > span,
.image-size-defaults-heading > span {
color: var(--muted-foreground);
font-size: var(--fs-label);
}
.image-size-preset-body {
display: grid;
gap: 10px;
min-width: 0;
}
.image-size-preset-options {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 84px), 1fr));
gap: 6px;
}
.image-size-preset-option,
.image-size-default-options button {
min-width: 0;
border: 0;
border-radius: var(--r-md);
background: var(--library-icon-surface);
color: inherit;
font-size: var(--fs-label);
cursor: pointer;
}
.image-size-preset-option {
display: grid;
gap: 5px;
padding: 10px 8px;
text-align: left;
overflow-wrap: anywhere;
}
.image-size-preset-option-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
font-weight: 600;
}
.image-size-preset-option-label svg {
flex: 0 0 auto;
}
.image-size-preset-option small {
color: var(--muted-foreground);
font-size: var(--fs-label);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.image-size-preset-option:hover:not(:disabled),
.image-size-default-options button:hover:not(:disabled) {
background: var(--library-surface-hover);
}
.image-size-presets-editor button[aria-pressed="true"] {
background: var(--library-surface-hover);
box-shadow: inset 0 0 0 1px var(--library-selected-stroke);
}
.image-size-presets-editor button:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}
.image-size-presets-editor button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.image-size-preset-add {
display: flex;
gap: 8px;
width: min(100%, 304px);
min-width: 0;
}
.image-size-preset-add input {
min-width: 0;
}
.image-size-defaults {
display: grid;
gap: 10px;
padding-block: 6px;
min-width: 0;
}
.image-size-defaults-heading {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 8px;
font-size: var(--fs-label);
}
.image-size-default-options {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.image-size-default-options button {
padding: 7px 10px;
background: var(--library-surface);
overflow-wrap: anywhere;
}
.admin-image-protocol-editor {
container: image-protocol / inline-size;
}
.admin-capability-protocol-grid.admin-image-protocol-grid {
grid-template-columns: minmax(0, 1fr) minmax(0, 2fr);
align-items: start;
gap: 16px;
}
.admin-image-size-card {
grid-column: 1 / -1;
}
.admin-image-size-intro {
display: grid;
grid-template-columns: minmax(0, 320px) minmax(0, 1fr);
align-items: center;
gap: 16px;
margin-bottom: 4px;
}
@container image-presets (max-width: 560px) {
.image-size-preset-group {
grid-template-columns: minmax(0, 1fr);
gap: 10px;
padding: 12px;
}
.image-size-preset-heading {
flex-direction: row;
align-items: baseline;
gap: 8px;
padding-top: 0;
}
}
@container image-protocol (max-width: 640px) {
.admin-capability-protocol-grid.admin-image-protocol-grid,
.admin-image-size-intro {
grid-template-columns: minmax(0, 1fr);
}
.admin-image-size-intro {
gap: 8px;
}
}

View File

@@ -0,0 +1,174 @@
import { useState } from "react";
import "./image-size-picker.css";
import { Input, Button } from "antd";
import type { ImageCapabilityConfig } from "@/lib/model-capabilities";
import { IMAGE_RESOLUTIONS, imagePresetForRatio, imagePresetValue, imageQualityForTier, imageResolutionUsesQuality, imageSizePresets, imageTierAvailable } from "@/lib/image-size-presets";
import { buildImageResolutionOptions, type ImageResolutionOption, type ImageResolutionTier } from "@/lib/image-resolution-tiers";
import { resolveImageRequestSize, validateImageSize } from "@/services/api/image-validation";
export function ImageSizePicker({ profile, size, quality, onChange }: { profile: ImageCapabilityConfig; size: string; quality?: string; onChange: (size: string, quality?: string) => void }) {
const presets = imageSizePresets(profile).filter((preset) => imageTierAvailable(profile, preset.tier));
const visibleTiers = IMAGE_RESOLUTIONS.filter((value) => presets.some((preset) => preset.tier === value));
const [chosenTier, setChosenTier] = useState<ImageResolutionTier>("1k");
const [customPreset, setCustomPreset] = useState<ImageResolutionOption>();
const [custom, setCustom] = useState("");
const [error, setError] = useState("");
const matches = (preset: ImageResolutionOption) =>
imagePresetValue(profile, preset) === size && (profile.size.parameter !== "aspect_ratio" || !imageResolutionUsesQuality(profile) || imageQualityForTier(profile, preset.tier) === (quality || profile.quality.default));
let resolvedLegacySize: string | undefined;
if (profile.size.parameter === "size" && size.includes(":")) {
try {
resolvedLegacySize = resolveImageRequestSize(profile, quality, size)?.value;
} catch {
/* 保留旧值,交由请求校验报告错误。 */
}
}
let restoredCustom: ImageResolutionOption | undefined;
if (profile.size.allowCustom && size !== "auto") {
try {
if (profile.size.parameter === "size") restoredCustom = buildImageResolutionOptions([resolvedLegacySize || size])[0];
else if (profile.size.parameter === "aspect_ratio") {
const restoredTier = IMAGE_RESOLUTIONS.find((value) => imageQualityForTier(profile, value) === (quality || profile.quality.default)) || "1k";
restoredCustom = imagePresetForRatio(restoredTier, size);
}
} catch {
/* 无效配置不伪装成已选中的有效预设,交由请求校验处理。 */
}
}
const active =
(profile.size.allowCustom && customPreset && imageTierAvailable(profile, customPreset.tier) && matches(customPreset) ? customPreset : undefined) ||
presets.find(matches) ||
presets.find((preset) => preset.size === resolvedLegacySize) ||
(restoredCustom && imageTierAvailable(profile, restoredCustom.tier) ? restoredCustom : undefined);
const available = (value: ImageResolutionTier) => imageTierAvailable(profile, value) && (profile.size.allowCustom || presets.some((preset) => preset.tier === value));
const tier =
(active && visibleTiers.includes(active.tier) ? active.tier : undefined) ||
(profile.size.parameter === "aspect_ratio" ? visibleTiers.find((value) => imageQualityForTier(profile, value) === (quality || profile.quality.default)) : undefined) ||
(visibleTiers.includes(chosenTier) ? chosenTier : visibleTiers[0]) ||
"1k";
const choices = presets.filter((preset) => preset.tier === tier);
const select = (preset: ImageResolutionOption) => {
if (!available(preset.tier)) return;
setChosenTier(preset.tier);
setCustomPreset(preset);
setError("");
onChange(imagePresetValue(profile, preset), profile.size.parameter === "aspect_ratio" ? imageQualityForTier(profile, preset.tier) : undefined);
};
const makeCustom = (next: ImageResolutionTier, ratio: string) => {
const preset = imagePresetForRatio(next, ratio);
// 精确支持值保持原值;支持值之外的像素仍遵守请求端的 16px 步长。
if (profile.size.parameter === "size" && !profile.size.values.includes(preset.size)) {
preset.width = Math.round(preset.width / 16) * 16;
preset.height = Math.round(preset.height / 16) * 16;
preset.size = `${preset.width}x${preset.height}`;
validateImageSize(preset.width, preset.height);
}
return preset;
};
const changeTier = (next: ImageResolutionTier) => {
const ratio = active?.ratio || (size.includes(":") ? size : "1:1");
const candidate = presets.find((preset) => preset.tier === next && preset.ratio === ratio);
try {
if (candidate) select(candidate);
else if (profile.size.allowCustom) select(makeCustom(next, ratio));
else {
const first = presets.find((preset) => preset.tier === next);
if (first) select(first);
}
} catch (reason) {
setError(reason instanceof Error ? reason.message : "尺寸格式无效");
}
};
const applyCustom = () => {
try {
if (custom.includes(":") || custom.includes(":")) {
select(makeCustom(tier, custom));
return;
}
const match = custom.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/i);
if (!match) throw new Error("输入比例 16:9,或像素 1824x1024");
const width = Number(match[1]),
height = Number(match[2]);
if (profile.size.parameter === "aspect_ratio") {
select(makeCustom(tier, `${width}:${height}`));
return;
}
const value = `${width}x${height}`;
validateImageSize(width, height, !profile.size.values.includes(value));
const preset = presets.find((item) => item.size === value) || {
...imagePresetForRatio(width * height <= 2_000_000 ? "1k" : width * height <= 4_300_000 ? "2k" : "4k", `${width}:${height}`),
width,
height,
size: value,
};
select(preset);
} catch (reason) {
setError(reason instanceof Error ? reason.message : "尺寸格式无效");
}
};
if (profile.size.parameter === "none") return null;
return (
<div className="image-size-picker">
{visibleTiers.length ? (
<>
<div className="image-size-label">分辨率</div>
<div className="image-size-tiers">
{visibleTiers.map((value) => (
<button type="button" key={value} aria-pressed={size !== "auto" && active?.tier === value} onClick={() => changeTier(value)}>
{value.toUpperCase()}
</button>
))}
</div>
</>
) : null}
{profile.size.values.includes("auto") ? (
<button
type="button"
className="image-size-auto"
aria-pressed={size === "auto"}
onClick={() => {
setError("");
onChange("auto");
}}
>
自动尺寸
</button>
) : null}
{choices.length ? <div className="image-size-label">宽高比</div> : null}
<div className="image-size-ratios">
{choices.map((preset) => (
<button
type="button"
key={`${preset.ratio}:${preset.size}`}
title={`${preset.ratio} · ${preset.width} × ${preset.height}`}
aria-pressed={size !== "auto" && active?.size === preset.size && active?.tier === tier}
onClick={() => select(preset)}
>
<span className="image-size-ratio-icon" style={{ width: 24 * Math.min(1, preset.width / preset.height), height: 24 * Math.min(1, preset.height / preset.width) }} />
<span>{preset.ratio}</span>
</button>
))}
</div>
{!choices.length ? <p className="image-size-hint">未配置预设尺寸{profile.size.allowCustom ? ",可输入自定义比例或尺寸" : ""}</p> : null}
<output aria-live="polite" className="image-size-output">
{size === "auto" ? "尺寸由模型决定" : active ? `${active.ratio} · ${active.width} × ${active.height} px` : size.replace("x", " × ")}
</output>
{profile.size.parameter === "aspect_ratio" ? <p className="image-size-hint">尺寸为换算参考,实际像素由模型决定{!imageResolutionUsesQuality(profile) ? ";当前协议未配置独立分辨率" : ""}。</p> : null}
{profile.size.allowCustom ? (
<details className="image-size-custom">
<summary>自定义比例或尺寸</summary>
<div className="image-size-custom-input">
<Input aria-label="自定义比例或尺寸" placeholder="16:9 或 1824x1024" value={custom} onChange={(event) => setCustom(event.target.value)} onPressEnter={applyCustom} />
<Button onClick={applyCustom}>应用</Button>
</div>
</details>
) : null}
{error ? (
<p role="alert" className="image-size-error">
{error}
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,134 @@
import { useId, useState } from "react";
import { Button, Input } from "antd";
import { Check, Plus } from "lucide-react";
import "./image-size-picker.css";
import type { ImageCapabilityConfig } from "@/lib/model-capabilities";
import { IMAGE_RATIOS, IMAGE_RESOLUTIONS, imagePresetForRatio, imageSizeConfigWithPresets, imageSizePresets, imageTierAvailable } from "@/lib/image-size-presets";
import type { ImageResolutionTier } from "@/lib/image-resolution-tiers";
export function ImageSizePresetsEditor({ profile, disabled, onChange }: { profile: ImageCapabilityConfig; disabled?: boolean; onChange: (size: ImageCapabilityConfig["size"]) => void }) {
const presets = imageSizePresets(profile);
const id = useId();
const [drafts, setDrafts] = useState<Partial<Record<ImageResolutionTier, string>>>({});
const [errors, setErrors] = useState<Partial<Record<ImageResolutionTier, string>>>({});
const update = (tier: ImageResolutionTier, ratios: string[]) => {
if (disabled) return false;
try {
const next = [
...new Map(
ratios.map((ratio) => {
const normalized = imagePresetForRatio(tier, ratio);
const preset = presets.find((preset) => preset.tier === tier && preset.ratio === normalized.ratio) || normalized;
return [preset.ratio, preset] as const;
}),
).values(),
];
onChange(imageSizeConfigWithPresets(profile, [...presets.filter((preset) => preset.tier !== tier), ...next]));
setErrors((current) => ({ ...current, [tier]: "" }));
return true;
} catch (reason) {
setErrors((current) => ({ ...current, [tier]: reason instanceof Error ? reason.message : "比例格式无效" }));
return false;
}
};
const addRatio = (tier: ImageResolutionTier) => {
const ratios = (drafts[tier] || "")
.split(/[,,\n]/)
.map((value) => value.trim())
.filter(Boolean);
if (!ratios.length) return;
if (update(tier, [...presets.filter((preset) => preset.tier === tier).map((preset) => preset.ratio), ...ratios])) {
setDrafts((current) => ({ ...current, [tier]: "" }));
}
};
return (
<div className="image-size-presets-editor">
<p className="image-size-editor-intro">点选支持的比例,再次点击可移除。尺寸自动换算,已有精确尺寸保持不变。</p>
{IMAGE_RESOLUTIONS.map((tier) => {
const items = presets.filter((preset) => preset.tier === tier);
const ratios = [...new Set([...IMAGE_RATIOS, ...items.map((item) => item.ratio)])];
return (
<section key={tier} className="image-size-preset-group" aria-labelledby={`${id}-${tier}-title`}>
<header className="image-size-preset-heading">
<strong id={`${id}-${tier}-title`}>{tier.toUpperCase()}</strong>
<span>{items.length ? `${items.length} 个比例` : "未启用"}</span>
</header>
<div className="image-size-preset-body">
{!imageTierAvailable(profile, tier) ? <p className="image-size-hint">需先配置此档位对应的质量值,用户端才会开放。</p> : null}
<div className="image-size-preset-options" role="group" aria-label={`${tier.toUpperCase()} 支持的宽高比`}>
{ratios.map((ratio) => {
const selected = items.find((item) => item.ratio === ratio);
const dimensions = selected || imagePresetForRatio(tier, ratio);
return (
<button
key={ratio}
type="button"
disabled={disabled}
aria-pressed={Boolean(selected)}
aria-label={`${tier.toUpperCase()} ${ratio}`}
className="image-size-preset-option"
title={`${ratio} · ${dimensions.width} × ${dimensions.height} px${selected ? " · 点击移除" : " · 点击添加"}`}
onClick={() => update(tier, selected ? items.filter((item) => item.ratio !== ratio).map((item) => item.ratio) : [...items.map((item) => item.ratio), ratio])}
>
<span className="image-size-preset-option-label">
<span>{ratio}</span>
{selected ? <Check size={12} aria-hidden="true" /> : <Plus size={12} aria-hidden="true" />}
</span>
<small>
{dimensions.width} × {dimensions.height}
</small>
</button>
);
})}
</div>
<div className="image-size-preset-add">
<Input
aria-label={`${tier.toUpperCase()} 自定义比例`}
aria-invalid={Boolean(errors[tier])}
aria-describedby={errors[tier] ? `${id}-${tier}-error` : undefined}
disabled={disabled}
placeholder="其他比例,如 17:11"
value={drafts[tier] || ""}
onChange={(event) => {
setDrafts((current) => ({ ...current, [tier]: event.target.value }));
setErrors((current) => ({ ...current, [tier]: "" }));
}}
onPressEnter={(event) => {
event.preventDefault();
event.stopPropagation();
addRatio(tier);
}}
/>
<Button disabled={disabled || !drafts[tier]?.trim()} icon={<Plus size={14} />} onClick={() => addRatio(tier)} aria-label={`添加 ${tier.toUpperCase()} 比例`}>
添加
</Button>
</div>
{errors[tier] ? (
<p id={`${id}-${tier}-error`} role="alert" className="image-size-error">
{errors[tier]}
</p>
) : null}
</div>
</section>
);
})}
<div className="image-size-defaults">
<div className="image-size-defaults-heading">
<strong>默认输出</strong>
<span>用户选择模型时的初始尺寸</span>
</div>
<div className="image-size-default-options" role="group" aria-label="默认输出">
{profile.size.values.map((value) => {
const preset = presets.find((item) => (profile.size.parameter === "aspect_ratio" ? item.ratio === value : item.size === value));
const label = value === "auto" ? "自动" : preset && profile.size.parameter === "size" ? `${preset.tier.toUpperCase()} · ${preset.ratio}` : value;
return (
<button key={value} type="button" disabled={disabled} aria-pressed={profile.size.default === value} title={value} aria-label={`默认输出 ${label} ${value}`} onClick={() => onChange({ ...profile.size, default: value })}>
{label}
</button>
);
})}
</div>
</div>
</div>
);
}

View File

@@ -1,3 +1,5 @@
import { ImageSizePresetsEditor } from "./image-size-presets-editor";
import { imageSizeConfigWithPresets, imageSizePresets } from "@/lib/image-size-presets";
import { Input, InputNumber, Segmented, Select, Switch } from "antd";
import type { ReactNode } from "react";
@@ -18,20 +20,8 @@ const operationOptions = [
{ label: "音频生视频", value: "audio_to_video" },
];
function formatImageSizeTagLabel(size: string): string {
const raw = size.trim();
if (raw === "1:1") return "1:1 (方图)";
if (raw === "16:9") return "16:9 (横屏)";
if (raw === "9:16") return "9:16 (竖屏)";
if (raw === "1024x1024") return "1024x1024 (1:1)";
if (raw === "2048x2048") return "2048x2048 (2K 方)";
if (raw === "3840x2160") return "3840x2160 (4K 横屏)";
if (raw === "2160x3840") return "2160x3840 (4K 竖屏)";
return raw;
}
function imageSizeOptions(values: string[]) {
return values.map((v) => ({ label: formatImageSizeTagLabel(v), value: v }));
function ImageSizeHelp() {
return <p className="text-[var(--fs-label)] leading-relaxed text-foreground/60">按分辨率配置支持的比例,尺寸自动换算。size 发送像素,aspect_ratio 发送比例;独立分辨率由模型协议适配。实际输出尺寸以上游为准。</p>;
}
type Props = {
@@ -434,57 +424,40 @@ function ImageCapabilityEditor({ value, onChange, protocol, model, disabled, sec
if (section === "protocol") {
return (
<div className="admin-capability-protocol-editor">
<div className="admin-capability-protocol-grid">
<ProtocolParameterCard step="01" title="输出数量" description="设置单次生成图片数量">
<NumberField label="单次生成张数" value={profile.maxOutputs} min={1} disabled={disabled} onChange={(maxOutputs) => update({ maxOutputs: maxOutputs || 1 })} />
</ProtocolParameterCard>
<ProtocolParameterCard step="02" title="尺寸参数" description="定义尺寸字段、支持值与默认值">
<Segmented
block
disabled={disabled}
value={profile.size.parameter}
options={[
{ label: "不发送", value: "none" },
{ label: "size", value: "size" },
{ label: "aspect_ratio", value: "aspect_ratio" },
]}
onChange={(value) => {
const parameter = value as ImageCapabilityConfig["size"]["parameter"];
updateSize(
parameter === "none"
? { parameter, values: [], default: "auto", allowCustom: false }
: { parameter, values: profile.size.values.length ? profile.size.values : ["1:1"], default: profile.size.default === "auto" ? "1:1" : profile.size.default },
);
}}
/>
<div className="admin-capability-protocol-editor admin-image-protocol-editor">
<div className="admin-capability-protocol-grid admin-image-protocol-grid">
<ProtocolParameterCard step="01" title="尺寸参数" description="按分辨率配置可用画幅,直接点选或输入比例" className="admin-image-size-card">
<div className="admin-image-size-intro">
<Segmented
block
disabled={disabled}
value={profile.size.parameter}
options={[
{ label: "不发送", value: "none" },
{ label: "size", value: "size" },
{ label: "aspect_ratio", value: "aspect_ratio" },
]}
onChange={(value) => {
const parameter = value as ImageCapabilityConfig["size"]["parameter"];
updateSize(
parameter === "none"
? { parameter, values: [], presets: undefined, default: "auto", allowCustom: false }
: imageSizeConfigWithPresets({ ...profile, size: { ...profile.size, parameter } }, imageSizePresets(profile)),
);
}}
/>
<ImageSizeHelp />
</div>
{profile.size.parameter !== "none" ? (
<>
<Field label="支持值">
<Select
mode="tags"
className="admin-capability-tags w-full"
disabled={disabled}
value={profile.size.values}
options={imageSizeOptions(profile.size.values)}
tokenSeparators={[","]}
placeholder="例如 1:1、1024x1024"
onChange={(values) => updateSize({ values, default: values.includes(profile.size.default) || profile.size.allowCustom ? profile.size.default : values[0] || "auto" })}
/>
</Field>
<Field label="默认值">
<Select
className="w-full"
disabled={disabled}
value={profile.size.default}
options={profile.size.values.map((item) => ({ label: item, value: item }))}
onChange={(defaultValue) => updateSize({ default: defaultValue })}
/>
</Field>
<ImageSizePresetsEditor profile={profile} disabled={disabled} onChange={updateSize} />
<ParameterField label="允许自定义" description="允许支持值之外的尺寸" supported={profile.size.allowCustom} disabled={disabled} onChange={(allowCustom) => updateSize({ allowCustom })} />
</>
) : null}
</ProtocolParameterCard>
<ProtocolParameterCard step="02" title="输出数量" description="设置单次生成图片数量">
<NumberField label="单次生成张数" value={profile.maxOutputs} min={1} disabled={disabled} onChange={(maxOutputs) => update({ maxOutputs: maxOutputs || 1 })} />
</ProtocolParameterCard>
<ProtocolParameterCard step="03" title="可选参数" description="控制质量、背景与响应格式">
<ParameterField label="图片质量" description="发送 quality 参数" supported={profile.quality.supported} disabled={disabled} onChange={(supported) => updateQuality({ supported })} />
{profile.quality.supported ? (
@@ -543,6 +516,7 @@ function ImageCapabilityEditor({ value, onChange, protocol, model, disabled, sec
<NumberField label="单次生成张数" value={profile.maxOutputs} min={1} disabled={disabled} onChange={(maxOutputs) => update({ maxOutputs: maxOutputs || 1 })} />
</CapabilityBlock>
<CapabilityBlock title="尺寸参数">
<ImageSizeHelp />
<Segmented
block
disabled={disabled}
@@ -555,38 +529,14 @@ function ImageCapabilityEditor({ value, onChange, protocol, model, disabled, sec
onChange={(value) => {
const parameter = value as ImageCapabilityConfig["size"]["parameter"];
updateSize(
parameter === "none"
? { parameter, values: [], default: "auto", allowCustom: false }
: { parameter, values: profile.size.values.length ? profile.size.values : ["1:1"], default: profile.size.default === "auto" ? "1:1" : profile.size.default },
parameter === "none" ? { parameter, values: [], presets: undefined, default: "auto", allowCustom: false } : imageSizeConfigWithPresets({ ...profile, size: { ...profile.size, parameter } }, imageSizePresets(profile)),
);
}}
/>
{profile.size.parameter !== "none" ? (
<>
<Field label="支持值">
<Select
mode="tags"
className="admin-capability-tags w-full"
disabled={disabled}
value={profile.size.values}
options={imageSizeOptions(profile.size.values)}
tokenSeparators={[","]}
placeholder="例如 1:1、1024x1024"
onChange={(values) => updateSize({ values, default: values.includes(profile.size.default) || profile.size.allowCustom ? profile.size.default : values[0] || "auto" })}
/>
</Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="默认值">
<Select
className="w-full"
disabled={disabled}
value={profile.size.default}
options={profile.size.values.map((item) => ({ label: item, value: item }))}
onChange={(defaultValue) => updateSize({ default: defaultValue })}
/>
</Field>
<ParameterField label="允许自定义" description="允许用户输入支持值之外的尺寸" supported={profile.size.allowCustom} disabled={disabled} onChange={(allowCustom) => updateSize({ allowCustom })} />
</div>
<ImageSizePresetsEditor profile={profile} disabled={disabled} onChange={updateSize} />
<ParameterField label="允许自定义" description="允许用户输入支持值之外的尺寸" supported={profile.size.allowCustom} disabled={disabled} onChange={(allowCustom) => updateSize({ allowCustom })} />
</>
) : null}
</CapabilityBlock>
@@ -665,9 +615,9 @@ function ReferenceCard({ title, description, children }: { title: string; descri
);
}
function ProtocolParameterCard({ step, title, description, children }: { step: string; title: string; description: string; children: ReactNode }) {
function ProtocolParameterCard({ step, title, description, children, className = "" }: { step: string; title: string; description: string; children: ReactNode; className?: string }) {
return (
<section className="admin-capability-protocol-card">
<section className={`admin-capability-protocol-card ${className}`}>
<header className="admin-capability-protocol-card-heading">
<span>{step}</span>
<div>