中文版 AI 姿势参考图库 · 1439 组 / 2878 张图片 / 完整汉化 · 零依赖静态画廊
feat(studio): add scoped randomization for reference slots
H-Boleb51acc21a6cf
diff --git a/src/lib/randomRecipe.ts b/src/lib/randomRecipe.tsnew file mode 100644index 0000000..9ad60e2--- /dev/null+++ b/src/lib/randomRecipe.ts@@ -0,0 +1,28 @@+import type { CostumeItem, PortraitItem, PoseItem, RecipeState } from '@/types/gallery'++export type ReferenceSlot = 'portrait' | 'costume' | 'pose'+export type RandomScope = 'similar' | 'all'+export interface ReferencePools { portraits?: PortraitItem[]; costumes?: CostumeItem[]; poses?: PoseItem[] }++/** Pools are already filtered by the current safety setting. */+export function randomSlot(recipe: RecipeState, slot: ReferenceSlot, scope: RandomScope, pools: ReferencePools, useDepth: boolean): RecipeState | null {+ const current = recipe[slot]+ if (scope === 'similar' && current?.source === 'upload') return null+ let candidates: Array<PortraitItem | CostumeItem | PoseItem>+ if (slot === 'portrait') {+ const selected = recipe.portrait+ candidates = (pools.portraits || []).filter((item) => item.source !== 'upload' && item.id !== current?.id &&+ (scope === 'all' || !selected || (item.分区 === selected.分区 && item.发长 === selected.发长)))+ } else if (slot === 'costume') {+ const selected = recipe.costume+ candidates = (pools.costumes || []).filter((item) => item.source !== 'upload' && item.id !== current?.id &&+ (scope === 'all' || !selected || (item.source === selected.source && (item.一级分类 || '现实') === (selected.一级分类 || '现实') && item.分类 === selected.分类)))+ } else {+ const selected = recipe.pose+ candidates = (pools.poses || []).filter((item) => item.source !== 'upload' && item.id !== current?.id &&+ (scope === 'all' || !selected || (item.体系 === selected.体系 && item.分类 === selected.分类)))+ }+ if (!candidates.length) return null+ const picked = candidates[Math.floor(Math.random() * candidates.length)]+ return { ...recipe, [slot]: slot === 'pose' ? { ...picked, useDepth } : picked }+}diff --git a/src/routes/studio.tsx b/src/routes/studio.tsxindex b0c39cd..44c076f 100644--- a/src/routes/studio.tsx+++ b/src/routes/studio.tsx@@ -57,6 +57,7 @@ import {} from '@/services/aiGenerator'import { poseImagePath, poseThumbPath, referenceImageUrl, uploadedReferences } from '@/lib/recipeImages'import { useStudio } from '@/store/studioStore'+import type { RandomScope, ReferenceSlot } from '@/lib/randomRecipe'import type {ComfyUiParams,DoubaoParams,@@ -103,6 +104,7 @@ function StudioPage() {updateDoubaoParams,updateComfyUiParams,randomizeRecipe,+ randomizeSlot,removeHistoryItem,clearHistory,} = useStudio()@@ -112,6 +114,8 @@ function StudioPage() {const slotInputRef = useRef<HTMLInputElement | null>(null)const uploadSlotRef = useRef<'portrait' | 'costume' | 'pose'>('portrait')const [uploadingSlot, setUploadingSlot] = useState<string | null>(null)+ const [randomizingSlot, setRandomizingSlot] = useState<ReferenceSlot | null>(null)+ const [randomScopes, setRandomScopes] = useState<Record<ReferenceSlot, RandomScope>>({ portrait: 'similar', costume: 'similar', pose: 'similar' })const [showReferenceErrors, setShowReferenceErrors] = useState(false)const referenceErrorsRef = useRef<HTMLDivElement | null>(null)@@ -327,6 +331,31 @@ function StudioPage() {})}+ const handleRandomSlot = async (slot: ReferenceSlot) => {+ const expectedId = recipe[slot]?.id ?? null+ setRandomizingSlot(slot)+ try {+ const pools = slot === 'portrait' ? { portraits: await qc.ensureQueryData(portraitsQuery) }+ : slot === 'costume' ? { costumes: await qc.ensureQueryData(costumesQuery) }+ : { poses: (await qc.ensureQueryData(posesQuery)).items }+ randomizeSlot(slot, randomScopes[slot], pools, expectedId)+ } catch {+ toast.error('素材库加载失败,请稍后重试')+ } finally {+ setRandomizingSlot(null)+ }+ }++ const randomControls = (slot: ReferenceSlot, label: string) => <div className="flex basis-full flex-wrap items-center gap-2 border-t pt-2">+ <Select value={randomScopes[slot]} onValueChange={(value) => setRandomScopes((current) => ({ ...current, [slot]: value as RandomScope }))}>+ <SelectTrigger aria-label={`${label}换样范围`} className="min-h-11 w-24"><SelectValue /></SelectTrigger>+ <SelectContent><SelectItem value="similar">同类</SelectItem><SelectItem value="all">全部</SelectItem></SelectContent>+ </Select>+ <Button type="button" variant="outline" className="min-h-11" disabled={uploadingSlot !== null || randomizingSlot !== null} onClick={() => void handleRandomSlot(slot)} aria-label={`${label}换一个`}>+ {randomizingSlot === slot ? <LoaderCircleIcon className="size-4 animate-spin motion-reduce:animate-none" /> : <DicesIcon className="size-4" />}换一个+ </Button>+ </div>+const handleUploadFiles = async (e: ChangeEvent<HTMLInputElement>) => {const files = Array.from(e.target.files || [])await processFiles(files)@@ -449,7 +478,7 @@ function StudioPage() {{/* 3 个核心图库槽位:手机端单列舒展展示,平板/桌面端三列并排 */}<div className="grid min-w-0 grid-cols-1 gap-2 @min-[42rem]/section:grid-cols-3">{/* 人像槽 */}- <div className={`relative flex min-w-0 items-start gap-2.5 rounded-xl bg-background p-2.5 ${showReferenceErrors && missingReferences.includes('人像') ? 'ring-1 ring-destructive' : ''}`}>+ <div className={`relative flex min-w-0 flex-wrap items-start gap-2.5 rounded-xl bg-background p-2.5 ${showReferenceErrors && missingReferences.includes('人像') ? 'ring-1 ring-destructive' : ''}`}>{recipe.portrait ? (<><button type="button" aria-label="放大人像参考图" className="shrink-0 cursor-zoom-in overflow-hidden rounded-lg transition-opacity hover:opacity-80 focus-visible:outline-2 focus-visible:outline-ring" onClick={() => {@@ -490,16 +519,17 @@ function StudioPage() {</div><span className="truncate text-xs">+ 选人像</span></Link>- <Button type="button" variant="ghost" size="sm" aria-label="上传人像参考图" aria-describedby={showReferenceErrors && missingReferences.includes('人像') ? 'reference-errors' : undefined} aria-busy={uploadingSlot === 'portrait'} disabled={uploadingSlot !== null} className="h-12 shrink-0 border-l px-2 text-xs" onClick={() => { uploadSlotRef.current = 'portrait'; slotInputRef.current?.click() }}>+ <Button type="button" variant="ghost" size="sm" aria-label="上传人像参考图" aria-describedby={showReferenceErrors && missingReferences.includes('人像') ? 'reference-errors' : undefined} aria-busy={uploadingSlot === 'portrait'} disabled={uploadingSlot !== null || randomizingSlot !== null} className="h-12 shrink-0 border-l px-2 text-xs" onClick={() => { uploadSlotRef.current = 'portrait'; slotInputRef.current?.click() }}>{uploadingSlot === 'portrait' ? <LoaderCircleIcon className="size-3.5 animate-spin motion-reduce:animate-none" /> : <ImagePlusIcon className="size-3.5" />}{uploadingSlot === 'portrait' ? '处理中' : '上传'}</Button></>)}+ {randomControls('portrait', '人像')}</div>{/* 服装槽 */}- <div className={`relative flex min-w-0 items-start gap-2.5 rounded-xl bg-background p-2.5 ${showReferenceErrors && missingReferences.includes('服装') ? 'ring-1 ring-destructive' : ''}`}>+ <div className={`relative flex min-w-0 flex-wrap items-start gap-2.5 rounded-xl bg-background p-2.5 ${showReferenceErrors && missingReferences.includes('服装') ? 'ring-1 ring-destructive' : ''}`}>{recipe.costume ? (<><button type="button" aria-label="放大服装参考图" className="shrink-0 cursor-zoom-in overflow-hidden rounded-lg transition-opacity hover:opacity-80 focus-visible:outline-2 focus-visible:outline-ring" onClick={() => {@@ -540,16 +570,17 @@ function StudioPage() {</div><span className="truncate text-xs">+ 选服装</span></Link>- <Button type="button" variant="ghost" size="sm" aria-label="上传服装参考图" aria-describedby={showReferenceErrors && missingReferences.includes('服装') ? 'reference-errors' : undefined} aria-busy={uploadingSlot === 'costume'} disabled={uploadingSlot !== null} className="h-12 shrink-0 border-l px-2 text-xs" onClick={() => { uploadSlotRef.current = 'costume'; slotInputRef.current?.click() }}>+ <Button type="button" variant="ghost" size="sm" aria-label="上传服装参考图" aria-describedby={showReferenceErrors && missingReferences.includes('服装') ? 'reference-errors' : undefined} aria-busy={uploadingSlot === 'costume'} disabled={uploadingSlot !== null || randomizingSlot !== null} className="h-12 shrink-0 border-l px-2 text-xs" onClick={() => { uploadSlotRef.current = 'costume'; slotInputRef.current?.click() }}>{uploadingSlot === 'costume' ? <LoaderCircleIcon className="size-3.5 animate-spin motion-reduce:animate-none" /> : <ImagePlusIcon className="size-3.5" />}{uploadingSlot === 'costume' ? '处理中' : '上传'}</Button></>)}+ {randomControls('costume', '服装')}</div>{/* 姿势槽 */}- <div className={`relative flex min-w-0 items-start gap-2.5 rounded-xl bg-background p-2.5 ${showReferenceErrors && missingReferences.includes('姿势') ? 'ring-1 ring-destructive' : ''}`}>+ <div className={`relative flex min-w-0 flex-wrap items-start gap-2.5 rounded-xl bg-background p-2.5 ${showReferenceErrors && missingReferences.includes('姿势') ? 'ring-1 ring-destructive' : ''}`}>{recipe.pose ? (<><button type="button" aria-label="放大姿势参考图" className="shrink-0 cursor-zoom-in overflow-hidden rounded-lg transition-opacity hover:opacity-80 focus-visible:outline-2 focus-visible:outline-ring" onClick={() => {@@ -629,12 +660,13 @@ function StudioPage() {</div><span className="truncate text-xs">+ 选姿势</span></Link>- <Button type="button" variant="ghost" size="sm" aria-label="上传姿势参考图" aria-describedby={showReferenceErrors && missingReferences.includes('姿势') ? 'reference-errors' : undefined} aria-busy={uploadingSlot === 'pose'} disabled={uploadingSlot !== null} className="h-12 shrink-0 border-l px-2 text-xs" onClick={() => { uploadSlotRef.current = 'pose'; slotInputRef.current?.click() }}>+ <Button type="button" variant="ghost" size="sm" aria-label="上传姿势参考图" aria-describedby={showReferenceErrors && missingReferences.includes('姿势') ? 'reference-errors' : undefined} aria-busy={uploadingSlot === 'pose'} disabled={uploadingSlot !== null || randomizingSlot !== null} className="h-12 shrink-0 border-l px-2 text-xs" onClick={() => { uploadSlotRef.current = 'pose'; slotInputRef.current?.click() }}>{uploadingSlot === 'pose' ? <LoaderCircleIcon className="size-3.5 animate-spin motion-reduce:animate-none" /> : <ImagePlusIcon className="size-3.5" />}{uploadingSlot === 'pose' ? '处理中' : '上传'}</Button></>)}+ {randomControls('pose', '姿势')}</div></div>diff --git a/src/store/studioStore.tsx b/src/store/studioStore.tsxindex 0fe9f13..2dbe6a7 100644--- a/src/store/studioStore.tsx+++ b/src/store/studioStore.tsx@@ -15,6 +15,7 @@ import { idbRead, idbWrite } from '@/lib/idbStorage'import { parseParameterWorkflow, workflowIdentity } from '@/lib/comfyWorkflowParameters'import { durableImage, snapshotGeneration } from '@/lib/generationSnapshot'import { recipeBackup } from '@/lib/recipeImages'+import { randomSlot, type RandomScope, type ReferencePools, type ReferenceSlot } from '@/lib/randomRecipe'import {buildRecipePrompt,COMFYUI_WORKFLOW_TEMPLATES,@@ -230,6 +231,7 @@ interface StudioContextValue {setWorkflowImage: (nodeId: string, image: ExtraReferenceImage | null, identity: string) => voidclearRecipe: () => voidrandomizeRecipe: (pools: { portraits?: PortraitItem[]; costumes?: CostumeItem[]; poses?: PoseItem[] }) => void+ randomizeSlot: (slot: ReferenceSlot, scope: RandomScope, pools: ReferencePools, expectedId?: string | null) => voidupdateApiConfig: (patch: Partial<ApiConfig>) => voidupdateProviderConfig: (provider: ImageProviderId, patch: Partial<ProviderEndpointConfig>) => voidupdateGptParams: (patch: Partial<GptParams>) => void@@ -290,6 +292,8 @@ export function StudioProvider({ children }: { children: ReactNode }) {const [ageGateOpen, setAgeGateOpen] = useState(false)const pendingUnlockCbRef = useRef<(() => void) | null>(null)const [poseDepthMode, setPoseDepthModeState] = useState<boolean>(() => Boolean(recipe.pose?.useDepth))+ const randomContext = useRef({ recipe, safeMode, poseDepthMode })+ useEffect(() => { randomContext.current = { recipe, safeMode, poseDepthMode } }, [recipe, safeMode, poseDepthMode])// 提升到根部 Provider 的生成状态,路由切换不会卸载或中断const [customPrompt, setCustomPrompt] = useState<string | null>(null)@@ -516,6 +520,25 @@ export function StudioProvider({ children }: { children: ReactNode }) {toast.success(safeMode ? '已随机抽取一套角色配方(安全模式)' : '已随机抽取一套角色配方')}+ const randomizeSlot = (slot: ReferenceSlot, scope: RandomScope, pools: ReferencePools, expectedId?: string | null) => {+ const current = randomContext.current+ if (expectedId !== undefined && (current.recipe[slot]?.id ?? null) !== expectedId) {+ toast.info('参考已更改,本次换样已取消')+ return+ }+ const next = randomSlot(current.recipe, slot, scope, {+ ...pools,+ costumes: (pools.costumes || []).filter((item) => !current.safeMode || !isNsfwCostume(item)),+ poses: (pools.poses || []).filter((item) => !current.safeMode || !isNsfwPose(item)),+ }, current.poseDepthMode)+ if (!next) {+ toast.info(scope === 'similar' ? '没有其他同类素材,可切到“全部”再试' : '没有其他可用素材')+ return+ }+ setRecipe((previous) => ({ ...previous, [slot]: next[slot] }))+ toast.success(`已更换${{ portrait: '人像', costume: '服装', pose: '姿势' }[slot]},其他参考保持不变`)+ }+const updateApiConfig = (patch: Partial<ApiConfig>) => {setApiConfig((prev) => {const next = { ...prev, ...patch }@@ -725,6 +748,7 @@ export function StudioProvider({ children }: { children: ReactNode }) {setWorkflowImage,clearRecipe,randomizeRecipe,+ randomizeSlot,updateApiConfig,updateProviderConfig,updateGptParams,