合并 master 并保留外部生成 worker 模式

合入 master 的拼消消、微信能力、OpenSSL 3.2 和 SpacetimeDB 2.4.1 更新
保留外部内容生成 queue/inline、worker lease 与动态扩缩容口径
补齐拼图后台图片生成队列轮询和运行态返回恢复
同步容器、生产运维和 Hermes 共享记忆中的 worker 文档
This commit is contained in:
2026-06-09 16:55:32 +08:00
497 changed files with 66318 additions and 13329 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
import type { ReactNode } from 'react';
import React, { type ReactNode } from 'react';
import type { CustomWorldCoverRenderMode } from '../services/customWorldCover';
import { ResolvedAssetImage } from './ResolvedAssetImage';
@@ -74,6 +74,12 @@ describe('CustomWorldGenerationView', () => {
expect((container.firstChild as HTMLElement).className).toContain(
'z-[1]',
);
expect((container.firstChild as HTMLElement).className).toContain(
'overflow-hidden',
);
expect((container.firstChild as HTMLElement).className).not.toContain(
'overflow-y-auto',
);
const pageVideo = screen.getByTestId(
'generation-page-background-video',
@@ -114,6 +120,14 @@ describe('CustomWorldGenerationView', () => {
expect(screen.getByTestId('generation-hero-elapsed-card').className).toContain(
'bg-white/58',
);
expect(
screen.getByTestId('generation-hero-wait-card').parentElement
?.className,
).toContain('mt-3');
expect(
screen.getByTestId('generation-hero-wait-card').parentElement
?.className,
).toContain('px-0');
expect(screen.getByText('预计等待').className).toContain('text-[9px]');
expect(screen.getByText('已耗时').className).toContain('text-[9px]');
expect(screen.getByText('预计等待').parentElement?.className).toContain(
@@ -231,6 +245,10 @@ describe('CustomWorldGenerationView', () => {
expect(
screen.getByTestId('generation-current-step-card').className,
).toContain('bg-white/58');
expect(
screen.getByTestId('generation-current-step-card').parentElement
?.className,
).toContain('mt-5');
expect(
screen.getByRole('progressbar', { name: '编译草稿 进度' }),
).toBeTruthy();
@@ -238,10 +256,11 @@ describe('CustomWorldGenerationView', () => {
expect(screen.queryByText('写回结果')).toBeNull();
expect(screen.queryByText('当前批次')).toBeNull();
expect(screen.queryByText('正在整理当前设定步骤')).toBeNull();
expect(screen.queryByText('竖屏生成题材')).toBeNull();
},
);
test('keeps the setting information panel as compact information cards', () => {
test('does not render setting information cards on generation pages', () => {
render(
<CustomWorldGenerationView
settingText="大鱼吃小鱼题材"
@@ -258,19 +277,15 @@ describe('CustomWorldGenerationView', () => {
backLabel="返回创作中心"
settingDescription={null}
settingActionLabel={null}
settingTitle="当前大鱼吃小鱼信息"
progressTitle="大鱼吃小鱼草稿生成进度"
/>,
);
expect(screen.getByText('当前大鱼吃小鱼信息')).toBeTruthy();
expect(screen.getByText('当前大鱼吃小鱼信息').className).toContain('text-[13px]');
expect(screen.getByText('题材')).toBeTruthy();
expect(screen.getByText('题材').className).toContain('text-[9px]');
expect(screen.getByText('火锅')).toBeTruthy();
expect(screen.getByText('火锅').className).toContain('text-[13px]');
expect(screen.getByText('素材数量')).toBeTruthy();
expect(screen.getByText('20 种素材')).toBeTruthy();
expect(screen.queryByText('当前大鱼吃小鱼信息')).toBeNull();
expect(screen.queryByText('题材')).toBeNull();
expect(screen.queryByText('火锅')).toBeNull();
expect(screen.queryByText('素材数量')).toBeNull();
expect(screen.queryByText('20 种素材')).toBeNull();
expect(screen.queryByText('大鱼吃小鱼题材')).toBeNull();
expect(screen.getByTestId('generation-page-background-video')).toBeTruthy();
});
+14 -93
View File
@@ -97,33 +97,18 @@ function resolveCurrentGenerationStep(
);
}
function buildFallbackRenderKey(
value: string | null | undefined,
fallback: string,
) {
const normalizedValue = value?.trim();
return normalizedValue ? normalizedValue : fallback;
}
export function CustomWorldGenerationView({
settingText,
anchorEntries = [],
progress,
isGenerating,
onBack,
onEditSetting,
onRetry,
onInterrupt,
backLabel = '返回',
settingActionLabel = '修改设定',
retryLabel = '重新开始生成',
interruptLabel = '中断世界生成',
settingTitle = '玩家设定',
settingDescription = '这段文本会直接驱动本轮世界框架、角色与场景生成。',
progressTitle = '生成进度',
activeBadgeLabel = '世界建设中',
idleBadgeLabel = '等待操作',
structuredEmptyText = '正在整理当前设定结构,请稍后。',
hideBatchModule = false,
}: CustomWorldGenerationViewProps) {
void hideBatchModule;
@@ -138,12 +123,6 @@ export function CustomWorldGenerationView({
: isGenerating
? '进行中'
: '待处理';
const hasStructuredAnchors = anchorEntries.length > 0;
// 允许不同生成场景按需隐藏第二模块的说明和次级返回动作。
const normalizedSettingActionLabel = settingActionLabel?.trim() ?? '';
const normalizedSettingDescription = settingDescription?.trim() ?? '';
const hasSettingActionLabel = normalizedSettingActionLabel.length > 0;
const hasSettingDescription = normalizedSettingDescription.length > 0;
const estimatedWaitText =
progress?.estimatedRemainingMs != null
? formatDuration(progress.estimatedRemainingMs)
@@ -153,11 +132,10 @@ export function CustomWorldGenerationView({
return (
<div
className="relative isolate z-[1] -mx-3 -my-3 flex h-[calc(100%+1.5rem)] min-h-0 flex-col overflow-y-auto overscroll-y-contain bg-transparent px-4 pb-[max(1.25rem,env(safe-area-inset-bottom))] pt-4 text-[#3d1f10] sm:mx-0 sm:my-0 sm:h-full sm:rounded-[2rem] sm:px-5 sm:pt-5"
style={{ WebkitOverflowScrolling: 'touch' }}
className="relative isolate z-[1] -mx-3 -my-3 flex h-[calc(100%+1.5rem)] min-h-0 flex-col overflow-hidden bg-transparent px-4 pb-[max(1.25rem,env(safe-area-inset-bottom))] pt-4 text-[#3d1f10] sm:mx-0 sm:my-0 sm:h-full sm:rounded-[2rem] sm:px-5 sm:pt-5"
>
<GenerationPageBackdrop />
<div className="relative z-10 mb-6 flex shrink-0 items-center justify-between gap-3 py-2 sm:mb-6">
<div className="relative z-30 mb-4 flex shrink-0 items-center justify-between gap-3 py-2 sm:mb-5">
<button
type="button"
onClick={onBack}
@@ -171,7 +149,10 @@ export function CustomWorldGenerationView({
</div>
</div>
<div className="relative z-10 flex flex-none flex-col gap-4">
<div
className="relative z-10 flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-y-contain"
style={{ WebkitOverflowScrolling: 'touch' }}
>
<section className="overflow-hidden px-0 pb-2 pt-0 sm:px-0">
<GenerationProgressHero
title={progressTitle}
@@ -181,7 +162,7 @@ export function CustomWorldGenerationView({
elapsedText={elapsedText}
/>
<div className="mt-[-0.15rem] px-0 sm:px-0">
<div className="mt-5 px-0 sm:mt-[-0.15rem] sm:px-0">
<GenerationCurrentStepCard
label={currentStepLabel}
statusLabel={currentStepStatusLabel}
@@ -191,24 +172,13 @@ export function CustomWorldGenerationView({
<div className="mt-4 flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:justify-end">
{!isGenerating ? (
<>
{hasSettingActionLabel ? (
<button
type="button"
onClick={onEditSetting}
className="platform-button platform-button--ghost min-h-0 rounded-full px-4 py-2 text-sm"
>
{normalizedSettingActionLabel}
</button>
) : null}
<button
type="button"
onClick={onRetry}
className="platform-button platform-button--primary w-full sm:w-auto"
>
{retryLabel}
</button>
</>
<button
type="button"
onClick={onRetry}
className="platform-button platform-button--primary w-full sm:w-auto"
>
{retryLabel}
</button>
) : onInterrupt ? (
<button
type="button"
@@ -220,55 +190,6 @@ export function CustomWorldGenerationView({
) : null}
</div>
</section>
<section className="overflow-hidden rounded-[1.75rem] border border-[#eadcd1] bg-[rgba(255,250,246,0.92)] px-4 py-4 shadow-[0_20px_56px_rgba(112,57,30,0.08)] backdrop-blur-[5px] sm:px-5 sm:py-5">
<div className="mb-4 flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="text-[13px] font-black tracking-[0.08em] text-[#111111]">
{settingTitle}
</div>
{hasSettingDescription ? (
<div className="mt-2 text-[13px] leading-6 text-[#7e6656]">
{normalizedSettingDescription}
</div>
) : null}
</div>
{hasSettingActionLabel ? (
<button
type="button"
onClick={onEditSetting}
disabled={isGenerating}
className={`platform-button platform-button--ghost min-h-0 px-3 py-1.5 text-[11px] ${isGenerating ? 'cursor-not-allowed opacity-40' : ''}`}
>
{normalizedSettingActionLabel}
</button>
) : null}
</div>
{hasStructuredAnchors ? (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{anchorEntries.map((entry, index) => (
<div
key={buildFallbackRenderKey(
entry.id,
`anchor-entry-${index}`,
)}
className="rounded-[1.15rem] border border-[#ead6c7] bg-white/74 px-4 py-4"
>
<div className="text-[9px] font-bold tracking-[0.12em] text-[#8e6f5d] sm:text-[10px]">
{entry.label}
</div>
<div className="mt-2 whitespace-pre-line text-[13px] leading-7 text-[#111111]">
{entry.value}
</div>
</div>
))}
</div>
) : (
<div className="whitespace-pre-line rounded-[1.15rem] border border-[#ead6c7] bg-white/74 px-4 py-4 text-[13px] leading-7 text-[#111111] md:max-h-[16rem] md:overflow-y-auto">
{settingText || structuredEmptyText}
</div>
)}
</section>
</div>
</div>
);
+2 -2
View File
@@ -133,7 +133,7 @@ export function GenerationProgressHero({
const ringFillDasharray = `${ringMetrics.progressLength.toFixed(2)} ${ringMetrics.circumference.toFixed(2)}`;
return (
<div className="relative mx-auto flex w-full min-w-0 max-w-[60rem] flex-col items-center px-1 pb-1 pt-1 sm:pt-4">
<div className="relative mx-auto flex w-full min-w-0 max-w-[60rem] flex-col items-center px-0 pb-1 pt-1 sm:pt-4">
<div className="sr-only">
{title}
{phaseLabel ? ` ${phaseLabel}` : ''}
@@ -215,7 +215,7 @@ export function GenerationProgressHero({
</div>
</div>
<div className="relative z-20 mt-[-0.3rem] grid w-full grid-cols-2 gap-2 px-0.5 sm:absolute sm:inset-0 sm:mt-0 sm:block sm:px-0">
<div className="relative z-20 mt-3 grid w-full grid-cols-2 gap-2 px-0 sm:absolute sm:inset-0 sm:mt-0 sm:block sm:px-0">
<div
className="w-full rounded-[1.1rem] border border-white/58 bg-white/58 px-2.5 py-2 text-center shadow-[0_14px_30px_rgba(112,57,30,0.10)] backdrop-blur-md sm:absolute sm:left-0 sm:top-1/2 sm:w-[8rem] sm:-translate-y-1/2 sm:px-3 sm:py-2.5"
data-testid="generation-hero-wait-card"
+30 -18
View File
@@ -1,6 +1,7 @@
import { type ImgHTMLAttributes, useEffect, useState } from 'react';
import React, { type ImgHTMLAttributes, useEffect, useState } from 'react';
import { useResolvedAssetReadUrl } from '../hooks/useResolvedAssetReadUrl';
import { RuntimeResourcePendingMarker } from './common/RuntimeResourcePendingMarker';
type ResolvedAssetImageProps = Omit<
ImgHTMLAttributes<HTMLImageElement>,
@@ -19,39 +20,50 @@ export function ResolvedAssetImage({
onError,
...rest
}: ResolvedAssetImageProps) {
const { resolvedUrl } = useResolvedAssetReadUrl(src, {
const { resolvedUrl, isResolving, shouldResolve } = useResolvedAssetReadUrl(src, {
refreshKey,
});
const normalizedSource = src?.trim() ?? '';
const normalizedFallbackSrc = fallbackSrc?.trim() ?? '';
const [useFallbackSrc, setUseFallbackSrc] = useState(false);
const finalSrc =
useFallbackSrc && normalizedFallbackSrc
? normalizedFallbackSrc
: resolvedUrl || normalizedFallbackSrc;
const pendingMarker = (
<RuntimeResourcePendingMarker
source={normalizedSource}
kind="image"
isPending={shouldResolve && isResolving}
/>
);
useEffect(() => {
setUseFallbackSrc(false);
}, [normalizedFallbackSrc, resolvedUrl]);
if (!finalSrc) {
return null;
return pendingMarker;
}
return (
<img
{...rest}
src={finalSrc}
alt={alt}
onError={(event) => {
if (
normalizedFallbackSrc &&
!useFallbackSrc &&
finalSrc !== normalizedFallbackSrc
) {
setUseFallbackSrc(true);
}
onError?.(event);
}}
/>
<>
{pendingMarker}
<img
{...rest}
src={finalSrc}
alt={alt}
onError={(event) => {
if (
normalizedFallbackSrc &&
!useFallbackSrc &&
finalSrc !== normalizedFallbackSrc
) {
setUseFallbackSrc(true);
}
onError?.(event);
}}
/>
</>
);
}
+72 -7
View File
@@ -17,10 +17,13 @@ const baseUser: AuthUser = {
displayName: '138****8000',
avatarUrl: null,
publicUserCode: 'user-tester',
phoneNumber: '13800138000',
phoneNumberMasked: '138****8000',
loginMethod: 'phone',
bindingStatus: 'active',
wechatBound: true,
wechatDisplayName: '微信旅人甲',
wechatAccount: 'wx-openid-bind-001',
};
function renderAccountModal(overrides?: {
@@ -112,6 +115,10 @@ test('settings header uses a generic title instead of the phone number', () => {
expect(screen.queryByText('当前主题')).toBeNull();
expect(screen.queryByRole('button', { name: '退出登录' })).toBeNull();
expect(screen.queryByRole('button', { name: '退出全部设备' })).toBeNull();
expect(screen.getByRole('button', { name: //u })).toBeTruthy();
expect(screen.getByRole('button', { name: //u })).toBeTruthy();
expect(screen.queryByRole('button', { name: //u })).toBeNull();
expect(screen.queryByRole('button', { name: //u })).toBeNull();
});
test('direct account entry does not render the settings shell as another dialog', () => {
@@ -129,12 +136,70 @@ test('direct account entry does not render the settings shell as another dialog'
).toBeNull();
});
test('account panel uses compact binding cards and keeps logout actions at the bottom', () => {
renderAccountModal({ entryMode: 'account' });
const accountDialog = screen.getByRole('dialog', { name: '账号信息' });
expect(within(accountDialog).getByText('账号信息')).toBeTruthy();
expect(within(accountDialog).queryByText('身份信息')).toBeNull();
expect(
within(accountDialog).queryByText(
'统一查看身份、安全状态、登录设备与最近操作。',
),
).toBeNull();
expect(within(accountDialog).queryByText('登录方式')).toBeNull();
expect(within(accountDialog).getByText('绑定手机号')).toBeTruthy();
expect(within(accountDialog).getByText('13800138000')).toBeTruthy();
expect(within(accountDialog).queryByText('138****8000')).toBeNull();
expect(within(accountDialog).getByText('绑定微信')).toBeTruthy();
expect(within(accountDialog).getByText('微信旅人甲')).toBeTruthy();
expect(within(accountDialog).queryByText('wx-openid-bind-001')).toBeNull();
const compactCards = accountDialog.querySelectorAll(
'[data-account-binding-card]',
);
expect(compactCards).toHaveLength(2);
expect(
within(compactCards[0] as HTMLElement).getByRole('button', {
name: '更换手机号',
}),
).toBeTruthy();
expect(
within(compactCards[1] as HTMLElement).getByRole('button', {
name: '更换微信号',
}),
).toBeTruthy();
const accountContent =
accountDialog.querySelector('[data-account-content]') ?? accountDialog;
expect(
accountContent.lastElementChild?.getAttribute('data-account-actions'),
).toBe('true');
});
test('account panel avoids bare bound label when wechat display name is missing', () => {
renderAccountModal({
entryMode: 'account',
user: {
...baseUser,
wechatDisplayName: null,
wechatAccount: 'openid_abcdef123456',
},
});
const accountDialog = screen.getByRole('dialog', { name: '账号信息' });
expect(within(accountDialog).getByText('绑定微信')).toBeTruthy();
expect(within(accountDialog).getByText('微信账号尾号 123456')).toBeTruthy();
expect(within(accountDialog).queryByText('openid_abcdef123456')).toBeNull();
expect(within(accountDialog).queryByText('已绑定')).toBeNull();
});
test('account actions open in independent panels instead of inline expansion', async () => {
const user = userEvent.setup();
renderAccountModal();
await user.click(screen.getByRole('button', { name: /账号信息/ }));
await user.click(screen.getByRole('button', { name: /账号与安全/ }));
const accountDialog = screen.getByRole('dialog', { name: '账号信息' });
expect(accountDialog).toBeTruthy();
@@ -162,7 +227,7 @@ test('nested settings panels keep back navigation without an extra close action'
renderAccountModal();
await user.click(screen.getByRole('button', { name: /账号信息/ }));
await user.click(screen.getByRole('button', { name: /账号与安全/ }));
const accountDialog = screen.getByRole('dialog', { name: '账号信息' });
const accountHeader = accountDialog.firstElementChild as HTMLElement | null;
@@ -201,7 +266,7 @@ test('settings overlays move focus away from inert triggers and restore it on ba
renderAccountModal();
const accountTrigger = screen.getByRole('button', { name: /账号信息/ });
const accountTrigger = screen.getByRole('button', { name: /账号与安全/ });
expect(document.activeElement).not.toBe(accountTrigger);
await user.click(accountTrigger);
@@ -283,7 +348,7 @@ test('account panel includes merged security devices and audit sections', async
],
});
await user.click(screen.getByRole('button', { name: /账号信息/ }));
await user.click(screen.getByRole('button', { name: /账号与安全/ }));
const accountDialog = screen.getByRole('dialog', { name: '账号信息' });
expect(within(accountDialog).getByText('安全状态')).toBeTruthy();
@@ -324,7 +389,7 @@ test('current merged session group hides kick action and shows count', async ()
],
});
await user.click(screen.getByRole('button', { name: /账号信息/ }));
await user.click(screen.getByRole('button', { name: /账号与安全/ }));
const accountDialog = screen.getByRole('dialog', { name: '账号信息' });
expect(within(accountDialog).getByText('2 个会话')).toBeTruthy();
@@ -348,7 +413,7 @@ test('remote merged session group can be revoked with loading state', async () =
revokingSessionIds: ['usess_remote'],
});
await user.click(screen.getByRole('button', { name: /账号信息/ }));
await user.click(screen.getByRole('button', { name: /账号与安全/ }));
const accountDialog = screen.getByRole('dialog', { name: '账号信息' });
const revokeButton = within(accountDialog).getByRole('button', {
@@ -373,7 +438,7 @@ test('remote session revoke passes the grouped session payload', async () => {
onRevokeSession,
});
await user.click(screen.getByRole('button', { name: /账号信息/ }));
await user.click(screen.getByRole('button', { name: /账号与安全/ }));
await user.click(
within(screen.getByRole('dialog', { name: '账号信息' })).getByRole(
'button',
+118 -114
View File
@@ -1,3 +1,4 @@
import { ArrowLeft } from 'lucide-react';
import {
type ReactNode,
useCallback,
@@ -65,8 +66,8 @@ const SETTINGS_SECTIONS: Array<{
label: string;
detail: string;
}> = [
{ id: 'appearance', label: '主题外观', detail: '亮暗主题' },
{ id: 'account', label: '账号信息', detail: '身份与安全' },
{ id: 'appearance', label: '主题设置', detail: '亮暗主题' },
{ id: 'account', label: '账号与安全', detail: '身份与设备' },
];
const ACCOUNT_MODAL_MAX_HEIGHT =
@@ -93,17 +94,6 @@ function normalizeSettingsSection(
return null;
}
function resolveLoginMethodLabel(loginMethod: AuthUser['loginMethod']) {
switch (loginMethod) {
case 'wechat':
return '微信登录';
case 'phone':
return '手机号登录';
default:
return '账号登录';
}
}
function formatSessionTime(value: string) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
@@ -119,6 +109,15 @@ function formatSessionTime(value: string) {
});
}
function formatBoundWechatAccount(value: string | null | undefined) {
const normalized = value?.trim();
if (!normalized) {
return null;
}
return `微信账号尾号 ${normalized.slice(-6)}`;
}
function SettingsEntryCard({
label,
detail,
@@ -166,7 +165,7 @@ function OverlayPanel({
onClose,
children,
}: {
eyebrow: string;
eyebrow?: string;
title: string;
description?: string;
action?: ReactNode;
@@ -184,12 +183,16 @@ function OverlayPanel({
style={{ maxHeight: ACCOUNT_MODAL_MAX_HEIGHT }}
onClick={(event) => event.stopPropagation()}
>
<div className="flex items-start justify-between gap-4">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-xs uppercase tracking-[0.28em] text-[var(--platform-cool-text)]">
{eyebrow}
</div>
<div className="mt-2 text-2xl font-semibold text-[var(--platform-text-strong)]">
{eyebrow ? (
<div className="text-xs uppercase tracking-[0.28em] text-[var(--platform-cool-text)]">
{eyebrow}
</div>
) : null}
<div
className={`${eyebrow ? 'mt-2 text-2xl' : 'text-xl sm:text-2xl'} font-semibold text-[var(--platform-text-strong)]`}
>
{title}
</div>
{description ? (
@@ -204,9 +207,10 @@ function OverlayPanel({
<button
type="button"
autoFocus
className="platform-button platform-button--ghost min-h-0 rounded-full px-3 py-1.5 text-xs"
className="platform-button platform-button--ghost min-h-0 gap-1.5 rounded-full px-3 py-1.5 text-xs"
onClick={onBack}
>
<ArrowLeft className="h-3.5 w-3.5" />
</button>
) : (
@@ -446,17 +450,18 @@ export function AccountModal({
? '正在同步平台设置...'
: '平台设置已同步';
const accountSummaryCards = [
['登录方式', resolveLoginMethodLabel(user.loginMethod)],
['手机号', user.phoneNumberMasked || '未绑定'],
['微信绑定', user.wechatBound ? '已绑定' : '未绑定'],
] as const;
const boundPhoneNumber =
user.phoneNumber?.trim() || user.phoneNumberMasked || '未绑定';
const boundWechatDisplayName =
user.wechatDisplayName?.trim() ||
formatBoundWechatAccount(user.wechatAccount) ||
(user.wechatBound ? '微信账号已绑定' : '未绑定');
const sectionSummaries: Record<PrimarySettingsSection, string> = {
appearance:
platformTheme === 'dark' ? '当前使用暗色主题。' : '当前使用亮色主题。',
account:
user.phoneNumberMasked || user.wechatBound
user.phoneNumber || user.phoneNumberMasked || user.wechatBound
? '查看身份、安全状态、登录设备与操作记录。'
: '查看账号绑定状态与安全记录。',
};
@@ -524,7 +529,7 @@ export function AccountModal({
{activeSection === 'appearance' ? (
<OverlayPanel
eyebrow="平台偏好"
title="主题外观"
title="主题设置"
description="切换平台亮色或暗色主题。"
onBack={closeSectionPanel}
onClose={onClose}
@@ -568,70 +573,79 @@ export function AccountModal({
{activeSection === 'account' ? (
<OverlayPanel
eyebrow="身份信息"
title="账号信息"
description="统一查看身份、安全状态、登录设备与最近操作。"
standalone={isDirectAccountMode}
onBack={isDirectAccountMode ? undefined : closeSectionPanel}
onClose={onClose}
>
<div className="flex min-h-0 flex-col gap-4">
<div data-account-content className="flex min-h-0 flex-col gap-3">
{accountNotice ? (
<div className="platform-banner platform-banner--success text-sm">
{accountNotice}
</div>
) : null}
<div className="grid gap-3 sm:grid-cols-2">
{accountSummaryCards.map(([label, value]) => (
<div
key={label}
className="platform-subpanel rounded-2xl px-4 py-3"
>
<div className="text-xs tracking-[0.18em] text-[var(--platform-text-soft)]">
{label}
</div>
<div className="mt-2 text-sm font-semibold text-[var(--platform-text-strong)]">
{value}
<div className="grid gap-2.5 sm:grid-cols-2">
<div
data-account-binding-card
className="platform-subpanel rounded-2xl px-3.5 py-3"
>
<div className="flex items-start justify-between gap-3">
<div className="text-sm font-semibold text-[var(--platform-text-strong)]">
</div>
<button
type="button"
className="min-h-0 shrink-0 rounded-full px-0 text-[11px] font-semibold text-[var(--platform-cool-text)]"
onClick={(event) => {
changePhoneTriggerRef.current = event.currentTarget;
setAccountNotice('');
resetChangePhoneDraft();
setIsChangePhonePanelOpen(true);
}}
>
</button>
</div>
))}
<div className="mt-1.5 break-all text-sm font-semibold text-[var(--platform-text-strong)]">
{boundPhoneNumber}
</div>
</div>
<div
data-account-binding-card
className="platform-subpanel rounded-2xl px-3.5 py-3"
>
<div className="flex items-start justify-between gap-3">
<div className="text-sm font-semibold text-[var(--platform-text-strong)]">
</div>
<button
type="button"
className="min-h-0 shrink-0 rounded-full px-0 text-[11px] font-semibold text-[var(--platform-cool-text)]"
onClick={() => {
setAccountNotice('更换微信号功能暂未接入。');
}}
>
</button>
</div>
<div className="mt-1.5 break-all text-sm font-semibold text-[var(--platform-text-strong)]">
{boundWechatDisplayName}
</div>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<button
type="button"
className="platform-button platform-button--ghost h-11 w-full text-sm"
onClick={() => {
void onLogout();
}}
>
退
</button>
<button
type="button"
className="platform-button platform-button--danger h-11 w-full text-sm"
onClick={() => {
void onLogoutAll();
}}
>
退
</button>
</div>
<div className="platform-subpanel rounded-2xl px-4 py-4">
<div className="platform-subpanel rounded-2xl px-3.5 py-3">
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-base font-semibold text-[var(--platform-text-strong)]">
<div className="text-sm font-semibold text-[var(--platform-text-strong)]">
</div>
<div className="mt-1 text-sm text-[var(--platform-text-base)]">
</div>
</div>
<button
type="button"
className="platform-button platform-button--ghost min-h-0 rounded-full px-3 py-1.5 text-[11px]"
className="min-h-0 shrink-0 rounded-full px-0 text-[11px] font-semibold text-[var(--platform-cool-text)]"
onClick={(event) => {
passwordTriggerRef.current = event.currentTarget;
setAccountNotice('');
@@ -644,40 +658,12 @@ export function AccountModal({
</div>
</div>
<div className="platform-subpanel rounded-2xl px-4 py-4">
<div className="platform-subpanel rounded-2xl px-3.5 py-3">
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-base font-semibold text-[var(--platform-text-strong)]">
</div>
<div className="mt-1 text-sm text-[var(--platform-text-base)]">
</div>
</div>
<button
type="button"
className="platform-button platform-button--ghost min-h-0 rounded-full px-3 py-1.5 text-[11px]"
onClick={(event) => {
changePhoneTriggerRef.current = event.currentTarget;
setAccountNotice('');
resetChangePhoneDraft();
setIsChangePhonePanelOpen(true);
}}
>
</button>
</div>
</div>
<div className="platform-subpanel rounded-2xl px-4 py-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="text-base font-semibold text-[var(--platform-text-strong)]">
<div className="text-sm font-semibold text-[var(--platform-text-strong)]">
</div>
<div className="mt-1 text-sm text-[var(--platform-text-base)]">
</div>
</div>
<button
type="button"
@@ -690,7 +676,7 @@ export function AccountModal({
</button>
</div>
<div className="mt-4 grid gap-3">
<div className="mt-3 grid gap-2.5">
{loadingRiskBlocks ? (
<div className="rounded-2xl border border-[var(--platform-subpanel-border)] px-4 py-3 text-sm text-[var(--platform-text-soft)]">
...
@@ -734,15 +720,12 @@ export function AccountModal({
</div>
</div>
<div className="platform-subpanel rounded-2xl px-4 py-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="platform-subpanel rounded-2xl px-3.5 py-3">
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-base font-semibold text-[var(--platform-text-strong)]">
<div className="text-sm font-semibold text-[var(--platform-text-strong)]">
</div>
<div className="mt-1 text-sm text-[var(--platform-text-base)]">
</div>
</div>
<button
type="button"
@@ -755,7 +738,7 @@ export function AccountModal({
</button>
</div>
<div className="mt-4 grid gap-3">
<div className="mt-3 grid gap-2.5">
{loadingSessions ? (
<div className="rounded-2xl border border-[var(--platform-subpanel-border)] px-4 py-3 text-sm text-[var(--platform-text-soft)]">
...
@@ -818,15 +801,12 @@ export function AccountModal({
</div>
</div>
<div className="platform-subpanel rounded-2xl px-4 py-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="platform-subpanel rounded-2xl px-3.5 py-3">
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-base font-semibold text-[var(--platform-text-strong)]">
<div className="text-sm font-semibold text-[var(--platform-text-strong)]">
</div>
<div className="mt-1 text-sm text-[var(--platform-text-base)]">
</div>
</div>
<button
type="button"
@@ -839,7 +819,7 @@ export function AccountModal({
</button>
</div>
<div className="mt-4 grid gap-3">
<div className="mt-3 grid gap-2.5">
{loadingAuditLogs ? (
<div className="rounded-2xl border border-[var(--platform-subpanel-border)] px-4 py-3 text-sm text-[var(--platform-text-soft)]">
...
@@ -873,6 +853,30 @@ export function AccountModal({
)}
</div>
</div>
<div
data-account-actions
className="grid gap-2.5 pt-1 sm:grid-cols-2"
>
<button
type="button"
className="platform-button platform-button--ghost h-10 w-full text-sm"
onClick={() => {
void onLogout();
}}
>
退
</button>
<button
type="button"
className="platform-button platform-button--danger h-10 w-full text-sm"
onClick={() => {
void onLogoutAll();
}}
>
退
</button>
</div>
</div>
{isChangePhonePanelOpen ? (
+18 -2
View File
@@ -3,11 +3,11 @@
import { act, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useState } from 'react';
import { beforeEach, expect, test, vi } from 'vitest';
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import type { AuthSessionSummary, AuthUser } from '../../services/authService';
import { LEGAL_CONSENT_STORAGE_KEY } from '../common/legalDocuments';
import { AuthGate } from './AuthGate';
import { AuthGate, setAuthGateReloadForTest } from './AuthGate';
import { useAuthUi } from './AuthUiContext';
const authMocks = vi.hoisted(() => ({
@@ -107,6 +107,7 @@ beforeEach(() => {
vi.clearAllMocks();
window.localStorage.clear();
window.history.replaceState(null, '', '/');
setAuthGateReloadForTest(vi.fn());
authMocks.consumeAuthCallbackResult.mockReturnValue(null);
authMocks.ensureStoredAccessToken.mockResolvedValue('jwt-existing-token');
authMocks.getStoredAccessToken.mockReturnValue('');
@@ -158,6 +159,10 @@ beforeEach(() => {
authMocks.requestWechatMiniProgramPhoneLogin.mockResolvedValue(true);
});
afterEach(() => {
setAuthGateReloadForTest(null);
});
async function acceptLegalConsent(
user: ReturnType<typeof userEvent.setup>,
dialog: HTMLElement,
@@ -382,6 +387,8 @@ test('auth gate keeps sms and password entries available when login options requ
test('auth gate opens a login modal for protected actions and resumes after login', async () => {
const user = userEvent.setup();
const onAuthenticated = vi.fn();
const reload = vi.fn();
setAuthGateReloadForTest(reload);
authMocks.getAuthLoginOptions.mockResolvedValue({
availableLoginMethods: ['phone'],
@@ -411,6 +418,7 @@ test('auth gate opens a login modal for protected actions and resumes after logi
);
expect(authMocks.getCurrentAuthUser).toHaveBeenCalledTimes(1);
expect(onAuthenticated).toHaveBeenCalledTimes(1);
expect(reload).toHaveBeenCalledTimes(1);
});
expect(screen.queryByRole('dialog', { name: '账号入口' })).toBeNull();
@@ -636,6 +644,8 @@ test('registration invite modal can skip when invite code is empty', async () =>
test('auth state refresh keeps mounted platform content and local tab state', async () => {
const user = userEvent.setup();
const reload = vi.fn();
setAuthGateReloadForTest(reload);
authMocks.getCurrentAuthUser.mockResolvedValue({
user: mockUser,
availableLoginMethods: ['phone'],
@@ -674,10 +684,13 @@ test('auth state refresh keeps mounted platform content and local tab state', as
expect(authMocks.getCurrentAuthUser).toHaveBeenCalledTimes(2);
});
expect(screen.getByText('当前Tab:创作')).toBeTruthy();
expect(reload).not.toHaveBeenCalled();
});
test('logout withdraws user context before backend request finishes', async () => {
const user = userEvent.setup();
const reload = vi.fn();
setAuthGateReloadForTest(reload);
authMocks.getCurrentAuthUser.mockResolvedValue({
user: mockUser,
availableLoginMethods: ['phone'],
@@ -703,11 +716,14 @@ test('logout withdraws user context before backend request finishes', async () =
expect(await screen.findByText('当前用户:未登录')).toBeTruthy();
expect(screen.getByText('私有数据:不可读取')).toBeTruthy();
expect(authMocks.logoutAuthUser).toHaveBeenCalledTimes(1);
expect(reload).not.toHaveBeenCalled();
await act(async () => {
resolveLogout();
await logoutPromise;
});
expect(reload).toHaveBeenCalledTimes(1);
});
test('auth gate shows sms send feedback in the login modal', async () => {
+87 -33
View File
@@ -65,6 +65,18 @@ type AuthStatus =
const REQUIRED_LOGIN_METHODS: AuthLoginMethod[] = ['phone', 'password'];
let reloadCurrentPageForAuthStateChange = () => {
window.location.reload();
};
export function setAuthGateReloadForTest(handler: (() => void) | null) {
reloadCurrentPageForAuthStateChange =
handler ??
(() => {
window.location.reload();
});
}
function readInviteCodeFromLocation(): string {
const params = new URLSearchParams(window.location.search || '');
return (params.get('inviteCode') || params.get('invite_code') || '')
@@ -140,6 +152,8 @@ export function AuthGate({ children }: AuthGateProps) {
const autoOpenedInviteCodeRef = useRef<string | null>(null);
const hasRenderedPlatformContentRef = useRef(false);
const authHydrateVersionRef = useRef(0);
const lastStableAuthPresenceRef = useRef<boolean | null>(null);
const pendingAuthStateReloadRef = useRef(false);
const canKeepPlatformContentMounted =
hasRenderedPlatformContentRef.current &&
(status === 'checking' || status === 'recovering');
@@ -152,36 +166,64 @@ export function AuthGate({ children }: AuthGateProps) {
hasRenderedPlatformContentRef.current = true;
}
const markAuthStateReloadIfChanged = useCallback(
(
nextUser: AuthUser | null,
options: { reloadOnChange?: boolean } = {},
) => {
const nextHasUser = Boolean(nextUser);
const previousHasUser = lastStableAuthPresenceRef.current;
if (previousHasUser === null) {
lastStableAuthPresenceRef.current = nextHasUser;
return;
}
lastStableAuthPresenceRef.current = nextHasUser;
if (
previousHasUser !== nextHasUser &&
options.reloadOnChange !== false
) {
pendingAuthStateReloadRef.current = true;
}
},
[],
);
const activateReadyUser = useCallback((nextUser: AuthUser) => {
// 受保护业务 hook 只在 readyUser 暴露后启动,必须先保证请求层能带 Bearer token。
authHydrateVersionRef.current += 1;
markAuthStateReloadIfChanged(nextUser);
setUser(nextUser);
setStatus('ready');
}, []);
}, [markAuthStateReloadIfChanged]);
const clearLocalAuthenticatedState = useCallback(() => {
// 退出动作必须先收回前端鉴权上下文,再等待后端吊销完成。
// 否则平台壳层会在无刷新状态下继续暴露旧用户的私有作品缓存
authHydrateVersionRef.current += 1;
pendingProtectedActionRef.current = null;
setUser(null);
setStatus('unauthenticated');
setShowLoginModal(false);
setShowRegistrationInviteModal(false);
setShowSettingsModal(false);
setSettingsEntryMode('settings');
setInitialSettingsSection(null);
setSessions([]);
setRevokingSessionIds([]);
setAuditLogs([]);
setRiskBlocks([]);
setLoginCaptchaChallenge(null);
setBindCaptchaChallenge(null);
setChangePhoneCaptchaChallenge(null);
setPendingInviteCode('');
setRegistrationInviteError('');
setError('');
}, []);
const clearLocalAuthenticatedState = useCallback(
(options: { reloadOnChange?: boolean } = {}) => {
// 退出动作必须先收回前端鉴权上下文,再等待后端吊销完成
// 否则平台壳层会在无刷新状态下继续暴露旧用户的私有作品缓存。
authHydrateVersionRef.current += 1;
markAuthStateReloadIfChanged(null, options);
pendingProtectedActionRef.current = null;
setUser(null);
setStatus('unauthenticated');
setShowLoginModal(false);
setShowRegistrationInviteModal(false);
setShowSettingsModal(false);
setSettingsEntryMode('settings');
setInitialSettingsSection(null);
setSessions([]);
setRevokingSessionIds([]);
setAuditLogs([]);
setRiskBlocks([]);
setLoginCaptchaChallenge(null);
setBindCaptchaChallenge(null);
setChangePhoneCaptchaChallenge(null);
setPendingInviteCode('');
setRegistrationInviteError('');
setError('');
},
[markAuthStateReloadIfChanged],
);
const restoreAuthSession = useCallback(async () => {
const hadLocalAccessToken = Boolean(getStoredAccessToken());
@@ -234,7 +276,7 @@ export function AuthGate({ children }: AuthGateProps) {
}, []);
const logoutCurrentSession = useCallback(async () => {
clearLocalAuthenticatedState();
clearLocalAuthenticatedState({ reloadOnChange: false });
try {
await logoutAuthUser();
} catch (logoutError) {
@@ -243,11 +285,13 @@ export function AuthGate({ children }: AuthGateProps) {
? logoutError.message
: '退出登录失败,请刷新页面确认状态。',
);
} finally {
reloadCurrentPageForAuthStateChange();
}
}, [clearLocalAuthenticatedState]);
const logoutAllSessions = useCallback(async () => {
clearLocalAuthenticatedState();
clearLocalAuthenticatedState({ reloadOnChange: false });
try {
await logoutAllAuthSessions();
} catch (logoutError) {
@@ -256,6 +300,8 @@ export function AuthGate({ children }: AuthGateProps) {
? logoutError.message
: '退出全部设备失败,请刷新页面确认状态。',
);
} finally {
reloadCurrentPageForAuthStateChange();
}
}, [clearLocalAuthenticatedState]);
@@ -386,6 +432,7 @@ export function AuthGate({ children }: AuthGateProps) {
return;
}
markAuthStateReloadIfChanged(null);
setUser(null);
setStatus('unauthenticated');
} catch (optionsError) {
@@ -394,6 +441,7 @@ export function AuthGate({ children }: AuthGateProps) {
}
setAvailableLoginMethods(REQUIRED_LOGIN_METHODS);
markAuthStateReloadIfChanged(null);
setUser(null);
// 中文注释:登录方式接口失败时按产品约定保留验证码和密码登录入口;
// 这里不展示接口读取错误,避免用户误以为登录本身不可用。
@@ -413,6 +461,7 @@ export function AuthGate({ children }: AuthGateProps) {
return;
}
if (restoredSession.kind === 'guest') {
markAuthStateReloadIfChanged(null);
setAvailableLoginMethods(
normalizeAvailableLoginMethods(
restoredSession.session?.availableLoginMethods,
@@ -423,6 +472,7 @@ export function AuthGate({ children }: AuthGateProps) {
}
const nextSession = restoredSession.session;
markAuthStateReloadIfChanged(nextSession.user);
setUser(nextSession.user);
setAvailableLoginMethods(
normalizeAvailableLoginMethods(nextSession.availableLoginMethods),
@@ -470,19 +520,23 @@ export function AuthGate({ children }: AuthGateProps) {
window.removeEventListener(AUTH_STATE_EVENT, handleAuthStateChange);
window.removeEventListener('hashchange', handleAuthHashChange);
};
}, [restoreAuthSession]);
}, [markAuthStateReloadIfChanged, restoreAuthSession]);
useEffect(() => {
if (!readyUser) {
setShowSettingsModal(false);
return;
} else {
setShowLoginModal(false);
const pendingAction = pendingProtectedActionRef.current;
pendingProtectedActionRef.current = null;
pendingAction?.();
}
setShowLoginModal(false);
const pendingAction = pendingProtectedActionRef.current;
pendingProtectedActionRef.current = null;
pendingAction?.();
if (pendingAuthStateReloadRef.current) {
pendingAuthStateReloadRef.current = false;
reloadCurrentPageForAuthStateChange();
}
}, [readyUser]);
useEffect(() => {
@@ -15,10 +15,6 @@ vi.mock('../../services/bark-battle-creation', () => ({
updateBarkBattleDraftConfig: vi.fn(),
}));
vi.mock('./BarkBattlePreviewCard', () => ({
BarkBattlePreviewCard: () => <div></div>,
}));
const draft = {
draftId: 'bark-battle-draft-1',
workId: 'BB-12345678',
@@ -61,6 +57,12 @@ describe('BarkBattleGeneratingView', () => {
expect(container.firstChild).toBeTruthy();
expect((container.firstChild as HTMLElement).className).toContain('z-[1]');
expect((container.firstChild as HTMLElement).className).toContain(
'overflow-hidden',
);
expect((container.firstChild as HTMLElement).className).not.toContain(
'overflow-y-auto',
);
expect(screen.getByText('总进度')).toBeTruthy();
expect(screen.getByText('总进度').className).toContain('text-[9px]');
const pageVideo = screen.getByTestId(
@@ -100,6 +102,14 @@ describe('BarkBattleGeneratingView', () => {
expect(screen.getByTestId('generation-hero-elapsed-card').className).toContain(
'bg-white/58',
);
expect(
screen.getByTestId('generation-hero-wait-card').parentElement
?.className,
).toContain('mt-3');
expect(
screen.getByTestId('generation-hero-wait-card').parentElement
?.className,
).toContain('px-0');
expect(screen.getByText('预计等待').className).toContain('text-[9px]');
expect(screen.getByText('已耗时').className).toContain('text-[9px]');
expect(screen.getByText('预计等待').parentElement?.className).toContain(
@@ -218,7 +228,13 @@ describe('BarkBattleGeneratingView', () => {
expect(
screen.getByTestId('generation-current-step-card').className,
).toContain('bg-white/58');
expect(screen.getByText('预览信息').className).toContain('text-[13px]');
expect(
screen.getByTestId('generation-current-step-card').parentElement
?.className,
).toContain('mt-5');
expect(screen.queryByText('预览信息')).toBeNull();
expect(screen.queryByText('汪汪声浪预览')).toBeNull();
expect(screen.queryByText('霓虹公园擂台')).toBeNull();
expect(screen.queryByText('对手形象')).toBeNull();
expect(screen.queryByText('竞技背景')).toBeNull();
expect(onComplete).not.toHaveBeenCalled();
@@ -17,7 +17,6 @@ import {
GenerationPageBackdrop,
GenerationProgressHero,
} from '../GenerationProgressHero';
import { BarkBattlePreviewCard } from './BarkBattlePreviewCard';
type BarkBattleGeneratingViewProps = {
draft: BarkBattleDraftConfig;
@@ -355,54 +354,49 @@ export function BarkBattleGeneratingView({
}, [draft, onComplete, onError]);
return (
<div className="relative isolate z-[1] -mx-3 -my-3 flex h-[calc(100%+1.5rem)] min-h-0 flex-col overflow-y-auto bg-transparent px-4 pb-[max(1.25rem,env(safe-area-inset-bottom))] pt-4 text-[#3d1f10] sm:mx-0 sm:my-0 sm:h-full sm:rounded-[2rem] sm:px-5 sm:pt-5 xl:px-6 xl:pb-5 xl:pt-5">
<div className="relative isolate z-[1] -mx-3 -my-3 flex h-[calc(100%+1.5rem)] min-h-0 flex-col overflow-hidden bg-transparent px-4 pb-[max(1.25rem,env(safe-area-inset-bottom))] pt-4 text-[#3d1f10] sm:mx-0 sm:my-0 sm:h-full sm:rounded-[2rem] sm:px-5 sm:pt-5 xl:px-6 xl:pb-5 xl:pt-5">
<GenerationPageBackdrop />
<div className="relative z-10 mx-auto flex w-full max-w-[48rem] flex-col">
<div className="mb-6 flex shrink-0 items-center justify-between gap-3 sm:mb-6">
<button
type="button"
onClick={onBack}
disabled={isBusy}
className={`inline-flex items-center gap-2 rounded-full bg-transparent px-0 py-2 text-xs font-black text-[#171411] sm:text-sm ${isBusy ? 'opacity-45' : ''}`}
>
<ArrowLeft className="h-5 w-5" strokeWidth={2.6} />
<span className="break-keep"></span>
</button>
<span className="rounded-full border border-[#f05816] bg-white/72 px-3 py-1.5 text-[11px] font-black tracking-[0.08em] text-[#df6118] shadow-[0_12px_30px_rgba(214,77,31,0.08)] backdrop-blur-md sm:px-4 sm:text-xs">
</span>
</div>
<div className="relative z-30 mx-auto mb-4 flex w-full max-w-[48rem] shrink-0 items-center justify-between gap-3 sm:mb-5">
<button
type="button"
onClick={onBack}
disabled={isBusy}
className={`inline-flex items-center gap-2 rounded-full bg-transparent px-0 py-2 text-xs font-black text-[#171411] sm:text-sm ${isBusy ? 'opacity-45' : ''}`}
>
<ArrowLeft className="h-5 w-5" strokeWidth={2.6} />
<span className="break-keep"></span>
</button>
<span className="rounded-full border border-[#f05816] bg-white/72 px-3 py-1.5 text-[11px] font-black tracking-[0.08em] text-[#df6118] shadow-[0_12px_30px_rgba(214,77,31,0.08)] backdrop-blur-md sm:px-4 sm:text-xs">
</span>
</div>
<section className="flex flex-col gap-4">
<div className="grid content-start gap-3 overflow-hidden px-0 pb-0 pt-0">
<GenerationProgressHero
title="汪汪声浪素材生成进度"
phaseLabel={draft.title || '未命名声浪竞技场'}
progressValue={progressValue}
estimatedWaitText="3 分钟"
elapsedText={formatGenerationDuration(elapsedMs)}
<div
className="relative z-10 mx-auto flex min-h-0 w-full max-w-[48rem] flex-1 flex-col overflow-y-auto overscroll-y-contain"
style={{ WebkitOverflowScrolling: 'touch' }}
>
<section className="grid content-start gap-3 overflow-hidden px-0 pb-2 pt-0">
<GenerationProgressHero
title="汪汪声浪素材生成进度"
phaseLabel={draft.title || '未命名声浪竞技场'}
progressValue={progressValue}
estimatedWaitText="3 分钟"
elapsedText={formatGenerationDuration(elapsedMs)}
/>
<div className="mt-5 sm:mt-[-0.15rem]">
<GenerationCurrentStepCard
label={currentStepLabel}
statusLabel={currentStepStatusLabel}
progressValue={currentStepProgress}
/>
<div className="mt-[-0.15rem]">
<GenerationCurrentStepCard
label={currentStepLabel}
statusLabel={currentStepStatusLabel}
progressValue={currentStepProgress}
/>
</div>
{error || primaryFailureMessage ? (
<div className="rounded-[1.4rem] border border-[#d88969]/35 bg-white/76 px-4 py-3 text-sm leading-6 text-[#a6402f] backdrop-blur-md">
{error ?? primaryFailureMessage}
</div>
) : null}
</div>
<section className="overflow-hidden rounded-[1.75rem] border border-[#eadcd1] bg-[rgba(255,250,246,0.92)] px-4 py-4 shadow-[0_20px_56px_rgba(112,57,30,0.08)] backdrop-blur-[5px] sm:px-5 sm:py-5">
<div className="mb-4 text-[13px] font-black tracking-[0.08em] text-[#111111]">
{error || primaryFailureMessage ? (
<div className="rounded-[1.4rem] border border-[#d88969]/35 bg-white/76 px-4 py-3 text-sm leading-6 text-[#a6402f] backdrop-blur-md">
{error ?? primaryFailureMessage}
</div>
<BarkBattlePreviewCard config={previewDraft} />
</section>
) : null}
</section>
</div>
</div>
@@ -0,0 +1,300 @@
/* @vitest-environment jsdom */
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ComponentProps } from 'react';
import { afterEach, expect, test, vi } from 'vitest';
import {
CreativeAudioInputPanel,
} from './CreativeAudioInputPanel';
import type { CreativeAudioAsset } from './creativeAudioFileAsset';
type TestAudioAsset = CreativeAudioAsset;
const originalMediaRecorder = globalThis.MediaRecorder;
const originalMediaDevices = navigator.mediaDevices;
afterEach(() => {
globalThis.MediaRecorder = originalMediaRecorder;
Object.defineProperty(navigator, 'mediaDevices', {
configurable: true,
value: originalMediaDevices,
});
vi.restoreAllMocks();
});
function buildAsset(overrides: Partial<TestAudioAsset> = {}): TestAudioAsset {
return {
assetId: 'asset-test',
audioSrc: 'blob:audio-preview',
audioObjectKey: '',
assetObjectId: '',
source: 'uploaded',
prompt: 'hit.wav',
durationMs: 800,
...overrides,
};
}
function renderPanel(
overrides: Partial<ComponentProps<typeof CreativeAudioInputPanel<TestAudioAsset>>> = {},
) {
const onAssetChange = vi.fn();
const onError = vi.fn();
const readFileAsAsset = vi.fn(async (file: File, source: 'uploaded' | 'recorded') =>
buildAsset({
audioSrc: `blob:${source}`,
source,
prompt: file.name,
}),
);
const rendered = render(
<CreativeAudioInputPanel<TestAudioAsset>
title="敲击音效"
defaultLabel="默认木鱼音"
asset={null}
buildRecordedFileName={() => 'recorded-hit.webm'}
onAssetChange={onAssetChange}
onError={onError}
readFileAsAsset={readFileAsAsset}
{...overrides}
/>,
);
return { ...rendered, onAssetChange, onError, readFileAsAsset };
}
function getUploadInput() {
const input = screen
.getByText('上传')
.closest('label')
?.querySelector('input[type="file"]') as HTMLInputElement | null;
expect(input).not.toBeNull();
return input!;
}
test('音频面板按需显示最长限制标签', () => {
renderPanel({ limitLabel: '最长 1 秒' });
expect(screen.getByText('最长 1 秒')).toBeTruthy();
});
test('音频面板未传限制标签时不渲染限制提示', () => {
renderPanel();
expect(screen.queryByText('最长 1 秒')).toBeNull();
});
test('音频面板无资产时显示默认音效文案', () => {
renderPanel();
expect(screen.getByText('默认木鱼音')).toBeTruthy();
});
test('音频面板有预览地址时渲染 audio 控件', () => {
const { container } = render(
<CreativeAudioInputPanel<TestAudioAsset>
title="敲击音效"
defaultLabel="默认木鱼音"
asset={buildAsset({ audioSrc: 'blob:preview' })}
buildRecordedFileName={() => 'recorded-hit.webm'}
onAssetChange={() => {}}
onError={() => {}}
/>,
);
expect(container.querySelector('audio')?.getAttribute('src')).toBe(
'blob:preview',
);
});
test('音频面板有资产但无预览地址时显示已选择状态', () => {
renderPanel({ asset: buildAsset({ audioSrc: '' }) });
expect(screen.getByText('音效已选择')).toBeTruthy();
});
test('点击重置清空当前音频资产', () => {
const onAssetChange = vi.fn();
renderPanel({
asset: buildAsset(),
onAssetChange,
});
fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(onAssetChange).toHaveBeenCalledWith(null);
});
test('取消上传选择时不读取音频', () => {
const { readFileAsAsset, onAssetChange } = renderPanel();
fireEvent.change(getUploadInput(), { target: { files: [] } });
expect(readFileAsAsset).not.toHaveBeenCalled();
expect(onAssetChange).not.toHaveBeenCalled();
});
test('上传音频成功后清空错误并写入资产', async () => {
const audioFile = new File(['audio'], 'hit.webm', { type: 'audio/webm' });
const { readFileAsAsset, onAssetChange, onError } = renderPanel();
fireEvent.change(getUploadInput(), { target: { files: [audioFile] } });
await waitFor(() =>
expect(readFileAsAsset).toHaveBeenCalledWith(audioFile, 'uploaded'),
);
await waitFor(() => expect(onAssetChange).toHaveBeenCalledTimes(1));
expect(onError).toHaveBeenCalledWith(null);
});
test('上传音频失败时提示错误且不写入资产', async () => {
const readFileAsAsset = vi.fn(async () => {
throw new Error('音频最长 1 秒。');
});
const onAssetChange = vi.fn();
const onError = vi.fn();
renderPanel({ readFileAsAsset, onAssetChange, onError });
fireEvent.change(getUploadInput(), {
target: {
files: [new File(['audio'], 'hit.webm', { type: 'audio/webm' })],
},
});
await waitFor(() => expect(onError).toHaveBeenCalledWith('音频最长 1 秒。'));
expect(onAssetChange).not.toHaveBeenCalled();
});
test('浏览器不支持录音时提示错误', async () => {
Object.defineProperty(navigator, 'mediaDevices', {
configurable: true,
value: undefined,
});
globalThis.MediaRecorder = undefined as unknown as typeof MediaRecorder;
const { onError } = renderPanel();
fireEvent.click(screen.getByRole('button', { name: '录音' }));
await waitFor(() =>
expect(onError).toHaveBeenCalledWith('当前浏览器不支持录音。'),
);
});
test('录音启动失败时透传启动错误', async () => {
Object.defineProperty(navigator, 'mediaDevices', {
configurable: true,
value: {
getUserMedia: vi.fn(async () => {
throw new Error('麦克风拒绝授权。');
}),
},
});
globalThis.MediaRecorder = class {
start = vi.fn();
stop = vi.fn();
} as unknown as typeof MediaRecorder;
const { onError } = renderPanel();
fireEvent.click(screen.getByRole('button', { name: '录音' }));
await waitFor(() => expect(onError).toHaveBeenCalledWith('麦克风拒绝授权。'));
});
test('录音停止后按 recorded 来源读取音频', async () => {
const stopTrack = vi.fn();
const recorderInstances: Array<{
ondataavailable: ((event: BlobEvent) => void) | null;
onstop: (() => void) | null;
}> = [];
Object.defineProperty(navigator, 'mediaDevices', {
configurable: true,
value: {
getUserMedia: vi.fn(async () => ({
getTracks: () => [{ stop: stopTrack }],
})),
},
});
globalThis.MediaRecorder = class {
mimeType = 'audio/webm';
ondataavailable: ((event: BlobEvent) => void) | null = null;
onstop: (() => void) | null = null;
constructor() {
recorderInstances.push(this);
}
start = vi.fn();
stop = vi.fn(() => {
this.ondataavailable?.({
data: new Blob(['recorded-audio'], { type: 'audio/webm' }),
} as BlobEvent);
this.onstop?.();
});
} as unknown as typeof MediaRecorder;
const { readFileAsAsset, onAssetChange } = renderPanel();
fireEvent.click(screen.getByRole('button', { name: '录音' }));
await waitFor(() => expect(screen.getByRole('button', { name: '停止' })).toBeTruthy());
fireEvent.click(screen.getByRole('button', { name: '停止' }));
await waitFor(() => expect(readFileAsAsset).toHaveBeenCalledTimes(1));
const [recordedFile, source] = readFileAsAsset.mock.calls[0]!;
expect(recordedFile).toBeInstanceOf(File);
expect((recordedFile as File).name).toBe('recorded-hit.webm');
expect(source).toBe('recorded');
expect(stopTrack).toHaveBeenCalledTimes(1);
await waitFor(() => expect(onAssetChange).toHaveBeenCalledTimes(1));
expect(recorderInstances).toHaveLength(1);
});
test('录音保存失败时提示错误', async () => {
Object.defineProperty(navigator, 'mediaDevices', {
configurable: true,
value: {
getUserMedia: vi.fn(async () => ({
getTracks: () => [],
})),
},
});
globalThis.MediaRecorder = class {
mimeType = 'audio/webm';
ondataavailable: ((event: BlobEvent) => void) | null = null;
onstop: (() => void) | null = null;
start = vi.fn();
stop = vi.fn(() => this.onstop?.());
} as unknown as typeof MediaRecorder;
const readFileAsAsset = vi.fn(async () => {
throw new Error('音频声音过小,请重新录制或上传。');
});
const onError = vi.fn();
renderPanel({ readFileAsAsset, onError });
fireEvent.click(screen.getByRole('button', { name: '录音' }));
await waitFor(() => expect(screen.getByRole('button', { name: '停止' })).toBeTruthy());
fireEvent.click(screen.getByRole('button', { name: '停止' }));
await waitFor(() =>
expect(onError).toHaveBeenCalledWith('音频声音过小,请重新录制或上传。'),
);
});
test('禁用状态不启动录音也不允许上传', () => {
const getUserMedia = vi.fn();
Object.defineProperty(navigator, 'mediaDevices', {
configurable: true,
value: { getUserMedia },
});
const { container } = renderPanel({ disabled: true });
fireEvent.click(screen.getByRole('button', { name: '录音' }));
expect(getUserMedia).not.toHaveBeenCalled();
const input = container.querySelector('input[type="file"]');
expect(input).not.toBeNull();
expect((input as HTMLInputElement).disabled).toBe(true);
});
@@ -1,20 +1,16 @@
import { Mic, Pause, Upload } from 'lucide-react';
import { useRef, useState } from 'react';
export type CreativeAudioAsset = {
assetId: string;
audioSrc: string;
audioObjectKey: string;
assetObjectId: string;
source: string;
prompt?: string | null;
durationMs?: number | null;
};
import {
type CreativeAudioAsset,
readCreativeAudioFileAsAsset,
} from './creativeAudioFileAsset';
type CreativeAudioInputPanelProps<TAsset extends CreativeAudioAsset> = {
disabled?: boolean;
title: string;
defaultLabel: string;
limitLabel?: string;
asset: TAsset | null;
buildRecordedFileName: () => string;
onAssetChange: (asset: TAsset | null) => void;
@@ -25,36 +21,11 @@ type CreativeAudioInputPanelProps<TAsset extends CreativeAudioAsset> = {
) => Promise<TAsset>;
};
export function readCreativeAudioFileAsAsset<TAsset extends CreativeAudioAsset>(
file: File,
source: 'uploaded' | 'recorded',
) {
return new Promise<TAsset>((resolve, reject) => {
const reader = new FileReader();
reader.onerror = () => reject(new Error('音频读取失败,请重试。'));
reader.onload = () => {
if (typeof reader.result !== 'string') {
reject(new Error('音频读取失败,请重试。'));
return;
}
resolve({
assetId: `local-${source}-${Date.now()}`,
audioSrc: reader.result,
audioObjectKey: '',
assetObjectId: '',
source,
prompt: file.name,
durationMs: null,
} as TAsset);
};
reader.readAsDataURL(file);
});
}
export function CreativeAudioInputPanel<TAsset extends CreativeAudioAsset>({
disabled = false,
title,
defaultLabel,
limitLabel,
asset,
buildRecordedFileName,
onAssetChange,
@@ -124,8 +95,15 @@ export function CreativeAudioInputPanel<TAsset extends CreativeAudioAsset>({
return (
<section className="platform-subpanel rounded-[1.25rem] p-4">
<div className="mb-3 flex items-center justify-between gap-3">
<div className="text-sm font-black text-[var(--platform-text-strong)]">
{title}
<div className="flex min-w-0 items-center gap-2">
<div className="text-sm font-black text-[var(--platform-text-strong)]">
{title}
</div>
{limitLabel ? (
<div className="rounded-full bg-white/70 px-2 py-1 text-[11px] font-black text-[var(--platform-text-soft)]">
{limitLabel}
</div>
) : null}
</div>
{asset ? (
<button
@@ -287,6 +287,118 @@ test('creative image input panel supports a preview-only main image mode', () =>
expect(onSubmit).toHaveBeenCalledTimes(1);
});
test('creative image input panel can preview the main image and keep upload on a corner button', () => {
const onMainImageFileSelect = vi.fn();
const inputClickSpy = vi
.spyOn(HTMLInputElement.prototype, 'click')
.mockImplementation(() => undefined);
try {
render(
<CreativeImageInputPanel
mainImageClickMode="preview"
uploadedImageSrc="/generated-puzzle-assets/session/level/image.png"
uploadedImageAlt="拼图关卡图"
mainImageInputId="level-image-upload-input"
promptTextareaId="level-prompt-input"
prompt="旧街灯牌下的猫。"
promptLabel="画面描述"
aiRedraw
promptReferenceImages={[]}
imageModelPicker={null}
submitLabel="重新生成画面"
submitDisabled={false}
labels={{
imageField: '画面图',
uploadImage: '上传参考图',
replaceImage: '更换参考图',
emptyImageHint: '上传图片/填写画面描述',
removeImage: '移除参考图',
removeImageConfirmTitle: '移除参考图?',
removeImageConfirmBody: '移除后可重新上传或选择历史图片。',
promptReferenceUpload: '上传参考图',
promptReferencePreviewAlt: '参考图预览',
closePromptReferencePreview: '关闭参考图预览',
previewMainImage: '查看关卡图片',
closeMainImagePreview: '关闭关卡图片预览',
}}
onMainImageFileSelect={onMainImageFileSelect}
onMainImageRemove={() => {}}
onAiRedrawChange={() => {}}
onPromptChange={() => {}}
onSubmit={() => {}}
/>,
);
fireEvent.click(screen.getByRole('button', { name: '查看关卡图片' }));
expect(screen.getByRole('dialog', { name: '查看关卡图片' })).toBeTruthy();
expect(screen.getAllByAltText('拼图关卡图').length).toBeGreaterThanOrEqual(2);
fireEvent.click(
screen.getByRole('button', { name: '关闭关卡图片预览' }),
);
fireEvent.click(screen.getByRole('button', { name: '更换参考图' }));
expect(inputClickSpy).toHaveBeenCalledTimes(1);
fireEvent.change(screen.getByLabelText('上传参考图', { selector: 'input' }), {
target: {
files: [new File(['a'], 'level-reference.png', { type: 'image/png' })],
},
});
expect(onMainImageFileSelect).toHaveBeenCalledWith(expect.any(File));
} finally {
inputClickSpy.mockRestore();
}
});
test('creative image input panel can hide upload and history controls independently', () => {
render(
<CreativeImageInputPanel
uploadedImageSrc="/generated-puzzle-assets/session/level/image.png"
uploadedImageAlt="拼图关卡图"
canUploadMainImage={false}
canUseImageHistory={false}
mainImageInputId="level-image-upload-input"
promptTextareaId="level-prompt-input"
prompt="旧街灯牌下的猫。"
promptLabel="画面描述"
aiRedraw
promptReferenceImages={[]}
imageModelPicker={null}
submitLabel="重新生成画面"
submitDisabled={false}
labels={{
imageField: '画面图',
uploadImage: '上传参考图',
replaceImage: '更换参考图',
emptyImageHint: '上传图片/填写画面描述',
removeImage: '移除参考图',
removeImageConfirmTitle: '移除参考图?',
removeImageConfirmBody: '移除后可重新上传或选择历史图片。',
promptReferenceUpload: '上传参考图',
promptReferencePreviewAlt: '参考图预览',
closePromptReferencePreview: '关闭参考图预览',
previewMainImage: '查看关卡图片',
closeMainImagePreview: '关闭关卡图片预览',
history: '选择历史图片',
}}
onMainImageFileSelect={() => {}}
onMainImageRemove={() => {}}
onAiRedrawChange={() => {}}
onPromptChange={() => {}}
onHistoryClick={() => {}}
onSubmit={() => {}}
/>,
);
expect(screen.getByRole('button', { name: '查看关卡图片' })).toBeTruthy();
expect(screen.queryByRole('button', { name: '更换参考图' })).toBeNull();
expect(
screen.queryByLabelText('上传参考图', { selector: 'input' }),
).toBeNull();
expect(screen.queryByRole('button', { name: '选择历史图片' })).toBeNull();
});
test('creative image input panel does not show empty upload hint over a non-removable image', () => {
render(
<CreativeImageInputPanel
+117 -31
View File
@@ -6,7 +6,7 @@ import {
Trash2,
X,
} from 'lucide-react';
import { type ReactNode, useEffect, useState } from 'react';
import { type ReactNode, useEffect, useRef, useState } from 'react';
import { ResolvedAssetImage } from '../ResolvedAssetImage';
@@ -28,6 +28,8 @@ export type CreativeImageInputPanelLabels = {
promptReferenceUpload: string;
promptReferencePreviewAlt: string;
closePromptReferencePreview: string;
previewMainImage?: string;
closeMainImagePreview?: string;
history?: string;
};
@@ -37,6 +39,9 @@ export type CreativeImageInputPanelProps = {
disabled?: boolean;
isSubmitting?: boolean;
mainImageMode?: 'edit' | 'preview';
mainImageClickMode?: 'upload' | 'preview';
canUploadMainImage?: boolean;
canUseImageHistory?: boolean;
canRemoveMainImage?: boolean;
canToggleAiRedraw?: boolean;
canUploadPromptReferences?: boolean;
@@ -82,6 +87,9 @@ export function CreativeImageInputPanel({
disabled = false,
isSubmitting = false,
mainImageMode = 'edit',
mainImageClickMode = 'preview',
canUploadMainImage = true,
canUseImageHistory = true,
canRemoveMainImage = true,
canToggleAiRedraw = true,
canUploadPromptReferences,
@@ -117,8 +125,10 @@ export function CreativeImageInputPanel({
onHistoryClick,
onSubmit,
}: CreativeImageInputPanelProps) {
const mainImageInputRef = useRef<HTMLInputElement | null>(null);
const [previewReferenceImage, setPreviewReferenceImage] =
useState<CreativeImageInputReferenceImage | null>(null);
const [isMainImagePreviewOpen, setIsMainImagePreviewOpen] = useState(false);
const [isRemoveImageConfirmOpen, setIsRemoveImageConfirmOpen] =
useState(false);
const showPrompt = mainImageMode === 'preview' || !uploadedImageSrc || aiRedraw;
@@ -127,10 +137,19 @@ export function CreativeImageInputPanel({
const promptReferenceUploadDisabled =
disabled || promptReferenceImages.length >= promptReferenceLimit;
const canEditMainImage = mainImageMode === 'edit';
const isMainImageUploadEnabled = canEditMainImage && canUploadMainImage;
const shouldShowHistoryButton =
canEditMainImage && canUseImageHistory && Boolean(onHistoryClick);
const shouldPreviewMainImage =
mainImageClickMode === 'preview' && Boolean(uploadedImageSrc);
const shouldShowMainImageUploadButton =
isMainImageUploadEnabled && shouldPreviewMainImage;
useEffect(() => {
if (uploadedImageSrc) {
setPreviewReferenceImage(null);
} else {
setIsMainImagePreviewOpen(false);
}
}, [uploadedImageSrc]);
@@ -187,35 +206,48 @@ export function CreativeImageInputPanel({
</div>
<div className={imageFrameClassName}>
<div className={imageCardClassName}>
{canEditMainImage ? (
<>
<input
id={mainImageInputId}
type="file"
accept={mainImageAccept}
disabled={disabled}
aria-label={labels.uploadImage}
onChange={(event) => {
const file = event.currentTarget.files?.[0] ?? null;
event.currentTarget.value = '';
if (file) {
onMainImageFileSelect(file);
}
}}
className="sr-only"
/>
<label
htmlFor={mainImageInputId}
className={`absolute inset-0 z-0 cursor-pointer ${disabled ? 'cursor-not-allowed' : ''}`}
title={
uploadedImageSrc ? labels.replaceImage : labels.uploadImage
{isMainImageUploadEnabled ? (
<input
ref={mainImageInputRef}
id={mainImageInputId}
type="file"
accept={mainImageAccept}
disabled={disabled}
aria-label={labels.uploadImage}
onChange={(event) => {
const file = event.currentTarget.files?.[0] ?? null;
event.currentTarget.value = '';
if (file) {
onMainImageFileSelect(file);
}
>
<span className="sr-only">
{uploadedImageSrc ? labels.replaceImage : labels.uploadImage}
</span>
</label>
</>
}}
className="sr-only"
/>
) : null}
{shouldPreviewMainImage ? (
<button
type="button"
className="absolute inset-0 z-[2] cursor-zoom-in"
aria-label={labels.previewMainImage ?? uploadedImageAlt}
title={labels.previewMainImage ?? uploadedImageAlt}
onClick={() => setIsMainImagePreviewOpen(true)}
/>
) : isMainImageUploadEnabled ? (
<label
htmlFor={mainImageInputId}
className={`absolute inset-0 z-0 cursor-pointer ${disabled ? 'cursor-not-allowed' : ''}`}
title={
uploadedImageSrc
? labels.replaceImage
: labels.uploadImage
}
>
<span className="sr-only">
{uploadedImageSrc
? labels.replaceImage
: labels.uploadImage}
</span>
</label>
) : null}
{uploadedImageSrc ? (
<ResolvedAssetImage
@@ -232,7 +264,19 @@ export function CreativeImageInputPanel({
</span>
)}
<div className="pointer-events-none absolute inset-0 z-[1] bg-[linear-gradient(180deg,rgba(255,255,255,0.12)_0%,rgba(255,255,255,0.04)_42%,rgba(255,255,255,0.18)_100%)]" />
{canEditMainImage && onHistoryClick ? (
{shouldShowMainImageUploadButton ? (
<button
type="button"
disabled={disabled}
onClick={() => mainImageInputRef.current?.click()}
className="absolute bottom-3 right-3 z-10 inline-flex h-10 w-10 items-center justify-center rounded-full border border-white/80 bg-white/94 text-[var(--platform-text-strong)] shadow-sm backdrop-blur transition hover:text-[var(--platform-accent)] disabled:cursor-not-allowed disabled:opacity-55"
aria-label={labels.replaceImage}
title={labels.replaceImage}
>
<ImagePlus className="h-4 w-4" />
</button>
) : null}
{shouldShowHistoryButton ? (
<button
type="button"
disabled={disabled}
@@ -284,7 +328,7 @@ export function CreativeImageInputPanel({
>
<Trash2 className="h-4 w-4" />
</button>
) : canEditMainImage && !uploadedImageSrc ? (
) : isMainImageUploadEnabled && !uploadedImageSrc ? (
<label
htmlFor={mainImageInputId}
className={`absolute bottom-9 left-1/2 z-10 -translate-x-1/2 whitespace-nowrap text-center text-sm font-black text-[var(--platform-text-strong)] drop-shadow-[0_1px_0_rgba(255,255,255,0.82)] transition hover:text-[var(--platform-accent)] sm:bottom-10 ${
@@ -477,6 +521,48 @@ export function CreativeImageInputPanel({
</div>
) : null}
{isMainImagePreviewOpen && uploadedImageSrc ? (
<div
className="platform-modal-backdrop fixed inset-0 z-[82] flex items-center justify-center px-4 py-6"
onClick={() => setIsMainImagePreviewOpen(false)}
>
<div
role="dialog"
aria-modal="true"
aria-labelledby="creative-image-main-preview-title"
className="platform-modal-shell platform-remap-surface w-full max-w-4xl rounded-[1.35rem] p-3 shadow-[0_24px_70px_rgba(15,23,42,0.22)]"
onClick={(event) => event.stopPropagation()}
>
<div className="mb-3 flex items-center justify-between gap-3 px-1">
<div
id="creative-image-main-preview-title"
className="min-w-0 truncate text-sm font-black text-[var(--platform-text-strong)]"
>
{labels.previewMainImage ?? uploadedImageAlt}
</div>
<button
type="button"
aria-label={
labels.closeMainImagePreview ?? labels.closePromptReferencePreview
}
onClick={() => setIsMainImagePreviewOpen(false)}
className="platform-profile-icon-button flex h-8 w-8 shrink-0 items-center justify-center rounded-full"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="max-h-[82vh] overflow-hidden rounded-[1rem] bg-black/5">
<ResolvedAssetImage
src={uploadedImageSrc}
refreshKey={uploadedImageRefreshKey}
alt={uploadedImageAlt}
className="h-full max-h-[82vh] w-full object-contain"
/>
</div>
</div>
</div>
) : null}
{isRemoveImageConfirmOpen ? (
<div className="platform-modal-backdrop fixed inset-0 z-[80] flex items-center justify-center px-4 py-6">
<div
@@ -0,0 +1,29 @@
type RuntimeResourcePendingMarkerProps = {
source?: string | null;
isPending?: boolean;
kind?: string;
};
export const RUNTIME_RESOURCE_PENDING_SELECTOR =
'[data-runtime-resource-pending="true"]';
export function RuntimeResourcePendingMarker({
source,
isPending = true,
kind,
}: RuntimeResourcePendingMarkerProps) {
const normalizedSource = source?.trim() ?? '';
if (!isPending || !normalizedSource) {
return null;
}
return (
<span
hidden
aria-hidden="true"
data-runtime-resource-pending="true"
data-runtime-resource-src={normalizedSource}
data-runtime-resource-kind={kind}
/>
);
}
@@ -0,0 +1,35 @@
export type CreativeAudioAsset = {
assetId: string;
audioSrc: string;
audioObjectKey: string;
assetObjectId: string;
source: string;
prompt?: string | null;
durationMs?: number | null;
};
export function readCreativeAudioFileAsAsset<TAsset extends CreativeAudioAsset>(
file: File,
source: 'uploaded' | 'recorded',
) {
return new Promise<TAsset>((resolve, reject) => {
const reader = new FileReader();
reader.onerror = () => reject(new Error('音频读取失败,请重试。'));
reader.onload = () => {
if (typeof reader.result !== 'string') {
reject(new Error('音频读取失败,请重试。'));
return;
}
resolve({
assetId: `local-${source}-${Date.now()}`,
audioSrc: reader.result,
audioObjectKey: '',
assetObjectId: '',
source,
prompt: file.name,
durationMs: null,
} as TAsset);
};
reader.readAsDataURL(file);
});
}
@@ -0,0 +1,241 @@
import { afterEach, expect, test, vi } from 'vitest';
import {
encodePcmChannelsToWavBlob,
findAudibleFrameRange,
normalizeAudioBufferSection,
prepareCreativeAudioFileForLocalUse,
} from './creativeAudioProcessing';
const originalAudioContext = globalThis.AudioContext;
const originalCreateObjectUrl = URL.createObjectURL;
afterEach(() => {
globalThis.AudioContext = originalAudioContext;
URL.createObjectURL = originalCreateObjectUrl;
vi.restoreAllMocks();
});
function createAudioBufferStub(
channels: number[][],
sampleRate = 1000,
): AudioBuffer {
return {
length: channels[0]?.length ?? 0,
numberOfChannels: channels.length,
sampleRate,
duration: (channels[0]?.length ?? 0) / sampleRate,
getChannelData: (channel: number) =>
new Float32Array(channels[channel] ?? []),
} as AudioBuffer;
}
function installAudioContextMock(
decodeAudioData: (bytes: ArrayBuffer) => Promise<AudioBuffer>,
) {
globalThis.AudioContext = class {
decodeAudioData = decodeAudioData;
close = vi.fn();
} as unknown as typeof AudioContext;
}
test('prepareCreativeAudioFileForLocalUse rejects empty audio files', async () => {
await expect(
prepareCreativeAudioFileForLocalUse(
new File([], 'empty.webm', { type: 'audio/webm' }),
'uploaded',
),
).rejects.toThrow('音频文件为空,请重新选择。');
});
test('prepareCreativeAudioFileForLocalUse rejects non-audio files', async () => {
await expect(
prepareCreativeAudioFileForLocalUse(
new File(['not-audio'], 'note.txt', { type: 'text/plain' }),
'uploaded',
),
).rejects.toThrow('请选择音频文件。');
});
test('prepareCreativeAudioFileForLocalUse reports decode failures', async () => {
installAudioContextMock(async () => {
throw new Error('decode failed');
});
await expect(
prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], 'broken.webm', { type: 'audio/webm' }),
'uploaded',
),
).rejects.toThrow('音频解码失败,请重新选择。');
});
test('prepareCreativeAudioFileForLocalUse rejects when AudioContext is unavailable', async () => {
globalThis.AudioContext = undefined as unknown as typeof AudioContext;
await expect(
prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], 'hit.webm', { type: 'audio/webm' }),
'uploaded',
),
).rejects.toThrow('当前浏览器不支持音频处理。');
});
test('prepareCreativeAudioFileForLocalUse rejects all-silent audio', async () => {
installAudioContextMock(async () => createAudioBufferStub([[0, 0.001, 0]], 1000));
await expect(
prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], 'silent.webm', { type: 'audio/webm' }),
'recorded',
),
).rejects.toThrow('音频声音过小,请重新录制或上传。');
});
test('prepareCreativeAudioFileForLocalUse allows audio exactly at the visible limit', async () => {
URL.createObjectURL = vi.fn(() => 'blob:one-second-audio');
installAudioContextMock(async () =>
createAudioBufferStub([Array.from({ length: 1000 }, () => 0.2)], 1000),
);
const asset = await prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], 'one-second.webm', { type: 'audio/webm' }),
'uploaded',
);
expect(asset.durationMs).toBe(1000);
expect(asset.audioSrc).toBe('blob:one-second-audio');
});
test('prepareCreativeAudioFileForLocalUse rejects audio longer than the visible limit after trimming', async () => {
installAudioContextMock(async () =>
createAudioBufferStub([[0, ...Array.from({ length: 1001 }, () => 0.2), 0]], 1000),
);
await expect(
prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], 'long.webm', { type: 'audio/webm' }),
'uploaded',
),
).rejects.toThrow('音频最长 1 秒。');
});
test('findAudibleFrameRange trims quiet leading and trailing frames', () => {
const buffer = createAudioBufferStub([
[0, 0.003, 0.02, 0.2, -0.03, 0.004],
[0, 0, 0, 0.05, 0, 0],
]);
expect(findAudibleFrameRange(buffer, 0.01)).toEqual({
startFrame: 2,
frameCount: 3,
});
});
test('normalizeAudioBufferSection pulls samples toward -15 LKFS approximation', () => {
const buffer = createAudioBufferStub([[0.02, -0.02, 0.02, -0.02]], 1000);
const normalized = normalizeAudioBufferSection(
buffer,
{ startFrame: 0, frameCount: 4 },
{ targetLkfs: -15, peakCeiling: 0.98 },
);
const channel = normalized[0];
expect(channel).toBeDefined();
const rms = Math.sqrt(
channel!.reduce((sum, sample) => sum + sample * sample, 0) /
channel!.length,
);
expect(rms).toBeCloseTo(Math.pow(10, -15 / 20), 3);
});
test('normalizeAudioBufferSection avoids clipping when target gain is too high', () => {
const buffer = createAudioBufferStub([[0.8, -0.8, 0.4, -0.4]], 1000);
const normalized = normalizeAudioBufferSection(
buffer,
{ startFrame: 0, frameCount: 4 },
{ targetLkfs: 0, peakCeiling: 0.5 },
);
const channel = normalized[0];
expect(channel).toBeDefined();
const peak = Math.max(...channel!.map((sample) => Math.abs(sample)));
expect(peak).toBeLessThanOrEqual(0.5);
});
test('normalizeAudioBufferSection rejects zero-energy sections', () => {
const buffer = createAudioBufferStub([[0, 0, 0]], 1000);
expect(() =>
normalizeAudioBufferSection(buffer, { startFrame: 0, frameCount: 3 }),
).toThrow('音频声音过小,请重新录制或上传。');
});
test('prepareCreativeAudioFileForLocalUse writes trimmed normalized wav blob', async () => {
URL.createObjectURL = vi.fn(() => 'blob:processed-audio');
installAudioContextMock(async () =>
createAudioBufferStub([[0, 0, 0.12, -0.12, 0]], 1000),
);
const asset = await prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], 'hit.webm', { type: 'audio/webm' }),
'uploaded',
);
const bytes = await asset.blob.arrayBuffer();
expect(asset.fileName).toBe('hit.wav');
expect(asset.mimeType).toBe('audio/wav');
expect(asset.audioSrc).toBe('blob:processed-audio');
expect(asset.durationMs).toBe(2);
expect(String.fromCharCode(...new Uint8Array(bytes, 0, 4))).toBe('RIFF');
expect(String.fromCharCode(...new Uint8Array(bytes, 8, 4))).toBe('WAVE');
});
test('prepareCreativeAudioFileForLocalUse still succeeds without object URL support', async () => {
URL.createObjectURL = undefined as unknown as typeof URL.createObjectURL;
installAudioContextMock(async () =>
createAudioBufferStub([[0.12, -0.12]], 1000),
);
const asset = await prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], 'hit.webm', { type: 'audio/webm' }),
'recorded',
);
expect(asset.audioSrc).toBe('');
expect(asset.previewUrl).toBe('');
});
test('prepareCreativeAudioFileForLocalUse normalizes processed wav file names', async () => {
URL.createObjectURL = vi.fn(() => 'blob:processed-audio');
installAudioContextMock(async () =>
createAudioBufferStub([[0.12, -0.12]], 1000),
);
await expect(
prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], 'hit-sound', { type: 'audio/webm' }),
'uploaded',
),
).resolves.toMatchObject({ fileName: 'hit-sound.wav' });
await expect(
prepareCreativeAudioFileForLocalUse(
new File(['audio-bytes'], ' ', { type: 'audio/webm' }),
'uploaded',
),
).resolves.toMatchObject({ fileName: 'creative-audio.wav' });
});
test('encodePcmChannelsToWavBlob writes pcm16 wav bytes', async () => {
const blob = encodePcmChannelsToWavBlob(
[new Float32Array([0.25, -0.5])],
1000,
);
const bytes = await blob.arrayBuffer();
const view = new DataView(bytes);
expect(blob.type).toBe('audio/wav');
expect(view.getUint32(40, true)).toBe(4);
expect(view.getInt16(44, true)).toBeCloseTo(8191, -1);
expect(view.getInt16(46, true)).toBeCloseTo(-16384, -1);
});
@@ -0,0 +1,308 @@
import {
type CreativeAudioAsset,
} from './creativeAudioFileAsset';
type BrowserAudioGlobal = typeof globalThis & {
webkitAudioContext?: typeof AudioContext;
};
export type CreativeAudioSource = 'uploaded' | 'recorded';
export type PendingCreativeAudioAsset = CreativeAudioAsset & {
fileName: string;
mimeType: string;
blob: Blob;
source: CreativeAudioSource;
previewUrl: string;
durationMs: number;
};
export type CreativeAudioProcessingOptions = {
maxDurationMs?: number;
silenceThreshold?: number;
targetLkfs?: number;
peakCeiling?: number;
};
export type AudibleFrameRange = {
startFrame: number;
frameCount: number;
};
const DEFAULT_MAX_DURATION_MS = 1000;
const DEFAULT_SILENCE_THRESHOLD = 0.01;
const DEFAULT_TARGET_LKFS = -15;
const DEFAULT_PEAK_CEILING = 0.98;
const WAV_HEADER_BYTE_LENGTH = 44;
const WAV_BITS_PER_SAMPLE = 16;
const WAV_BYTES_PER_SAMPLE = WAV_BITS_PER_SAMPLE / 8;
export async function prepareCreativeAudioFileForLocalUse(
file: File,
source: CreativeAudioSource,
options: CreativeAudioProcessingOptions = {},
): Promise<PendingCreativeAudioAsset> {
validateCreativeAudioFile(file);
const decodedBuffer = await decodeCreativeAudioFile(file);
const range = findAudibleFrameRange(
decodedBuffer,
options.silenceThreshold ?? DEFAULT_SILENCE_THRESHOLD,
);
if (!range) {
throw new Error('音频声音过小,请重新录制或上传。');
}
const durationMs = Math.round(
(range.frameCount / decodedBuffer.sampleRate) * 1000,
);
const maxDurationMs = options.maxDurationMs ?? DEFAULT_MAX_DURATION_MS;
if (durationMs > maxDurationMs) {
throw new Error(`音频最长 ${formatDurationSeconds(maxDurationMs)} 秒。`);
}
const normalized = normalizeAudioBufferSection(decodedBuffer, range, {
targetLkfs: options.targetLkfs ?? DEFAULT_TARGET_LKFS,
peakCeiling: options.peakCeiling ?? DEFAULT_PEAK_CEILING,
});
const blob = encodePcmChannelsToWavBlob(normalized, decodedBuffer.sampleRate);
const fileName = buildProcessedAudioFileName(file.name);
const previewUrl =
typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function'
? URL.createObjectURL(blob)
: '';
return {
assetId: `local-${source}-${Date.now()}`,
audioSrc: previewUrl,
audioObjectKey: '',
assetObjectId: '',
source,
prompt: file.name,
durationMs,
fileName,
mimeType: blob.type,
blob,
previewUrl,
};
}
export function findAudibleFrameRange(
buffer: AudioBuffer,
silenceThreshold = DEFAULT_SILENCE_THRESHOLD,
): AudibleFrameRange | null {
const threshold = Math.max(0, silenceThreshold);
let startFrame: number | null = null;
let endFrame: number | null = null;
for (let frameIndex = 0; frameIndex < buffer.length; frameIndex += 1) {
if (isFrameAudible(buffer, frameIndex, threshold)) {
startFrame = frameIndex;
break;
}
}
if (startFrame === null) {
return null;
}
for (let frameIndex = buffer.length - 1; frameIndex >= startFrame; frameIndex -= 1) {
if (isFrameAudible(buffer, frameIndex, threshold)) {
endFrame = frameIndex;
break;
}
}
if (endFrame === null) {
return null;
}
return {
startFrame,
frameCount: endFrame - startFrame + 1,
};
}
export function normalizeAudioBufferSection(
buffer: AudioBuffer,
range: AudibleFrameRange,
options: Pick<CreativeAudioProcessingOptions, 'targetLkfs' | 'peakCeiling'> = {},
) {
const channelCount = Math.max(1, buffer.numberOfChannels);
const targetLkfs = options.targetLkfs ?? DEFAULT_TARGET_LKFS;
const peakCeiling = Math.max(0.01, options.peakCeiling ?? DEFAULT_PEAK_CEILING);
const channels = Array.from({ length: channelCount }, (_value, channelIndex) =>
copyChannelSection(buffer, channelIndex, range),
);
const stats = measurePcmStats(channels);
if (stats.rms <= 0 || stats.peak <= 0) {
throw new Error('音频声音过小,请重新录制或上传。');
}
// 浏览器端近似:用全通道 RMS 估算 LKFS,再按 GY/T 377-2023 目标值拉到 -15 LKFS。
const targetLinear = Math.pow(10, targetLkfs / 20);
const loudnessGain = targetLinear / stats.rms;
const protectedGain = Math.min(loudnessGain, peakCeiling / stats.peak);
return channels.map((channel) =>
Float32Array.from(channel, (sample) => clampSample(sample * protectedGain)),
);
}
export function encodePcmChannelsToWavBlob(
channels: Float32Array[],
sampleRate: number,
) {
const channelCount = Math.max(1, channels.length);
const frameCount = channels[0]?.length ?? 0;
const dataByteLength = frameCount * channelCount * WAV_BYTES_PER_SAMPLE;
const output = new ArrayBuffer(WAV_HEADER_BYTE_LENGTH + dataByteLength);
const view = new DataView(output);
writeAscii(view, 0, 'RIFF');
view.setUint32(4, 36 + dataByteLength, true);
writeAscii(view, 8, 'WAVE');
writeAscii(view, 12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, channelCount, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * channelCount * WAV_BYTES_PER_SAMPLE, true);
view.setUint16(32, channelCount * WAV_BYTES_PER_SAMPLE, true);
view.setUint16(34, WAV_BITS_PER_SAMPLE, true);
writeAscii(view, 36, 'data');
view.setUint32(40, dataByteLength, true);
let outputOffset = WAV_HEADER_BYTE_LENGTH;
for (let frameIndex = 0; frameIndex < frameCount; frameIndex += 1) {
for (let channelIndex = 0; channelIndex < channelCount; channelIndex += 1) {
const sample = channels[channelIndex]?.[frameIndex] ?? 0;
view.setInt16(outputOffset, toSignedPcm16(sample), true);
outputOffset += WAV_BYTES_PER_SAMPLE;
}
}
return new Blob([output], { type: 'audio/wav' });
}
function validateCreativeAudioFile(file: File) {
if (file.size <= 0) {
throw new Error('音频文件为空,请重新选择。');
}
if (!resolveFileMimeType(file).startsWith('audio/')) {
throw new Error('请选择音频文件。');
}
}
async function decodeCreativeAudioFile(file: File) {
const AudioContextConstructor = getAudioContextConstructor();
if (!AudioContextConstructor) {
throw new Error('当前浏览器不支持音频处理。');
}
const context = new AudioContextConstructor();
try {
const bytes = await file.arrayBuffer();
return await context.decodeAudioData(bytes.slice(0));
} catch {
throw new Error('音频解码失败,请重新选择。');
} finally {
void context.close();
}
}
function getAudioContextConstructor() {
const audioGlobal = globalThis as BrowserAudioGlobal;
return audioGlobal.AudioContext ?? audioGlobal.webkitAudioContext ?? null;
}
function resolveFileMimeType(file: File) {
if (file.type.trim()) {
return file.type.trim();
}
return '';
}
function isFrameAudible(
buffer: AudioBuffer,
frameIndex: number,
threshold: number,
) {
for (
let channelIndex = 0;
channelIndex < buffer.numberOfChannels;
channelIndex += 1
) {
const channelData = buffer.getChannelData(channelIndex);
if (Math.abs(channelData[frameIndex] ?? 0) > threshold) {
return true;
}
}
return false;
}
function copyChannelSection(
buffer: AudioBuffer,
channelIndex: number,
range: AudibleFrameRange,
) {
const source =
channelIndex < buffer.numberOfChannels
? buffer.getChannelData(channelIndex)
: new Float32Array(buffer.length);
const output = new Float32Array(range.frameCount);
for (let frameOffset = 0; frameOffset < range.frameCount; frameOffset += 1) {
output[frameOffset] = source[range.startFrame + frameOffset] ?? 0;
}
return output;
}
function measurePcmStats(channels: Float32Array[]) {
let sumSquares = 0;
let peak = 0;
let sampleCount = 0;
for (const channel of channels) {
for (const sample of channel) {
sumSquares += sample * sample;
peak = Math.max(peak, Math.abs(sample));
sampleCount += 1;
}
}
return {
rms: sampleCount > 0 ? Math.sqrt(sumSquares / sampleCount) : 0,
peak,
};
}
function clampSample(sample: number) {
return Math.max(-1, Math.min(1, sample));
}
function toSignedPcm16(sample: number) {
const clamped = clampSample(sample);
return clamped < 0
? Math.round(clamped * 0x8000)
: Math.round(clamped * 0x7fff);
}
function writeAscii(view: DataView, offset: number, value: string) {
for (let index = 0; index < value.length; index += 1) {
view.setUint8(offset + index, value.charCodeAt(index));
}
}
function buildProcessedAudioFileName(fileName: string) {
const normalizedName = fileName.trim();
if (!normalizedName) {
return 'creative-audio.wav';
}
return /\.[^.]+$/u.test(normalizedName)
? normalizedName.replace(/\.[^.]+$/u, '.wav')
: `${normalizedName}.wav`;
}
function formatDurationSeconds(durationMs: number) {
return Number.isInteger(durationMs / 1000)
? String(durationMs / 1000)
: (durationMs / 1000).toFixed(1);
}
@@ -0,0 +1,77 @@
import { expect, test } from 'vitest';
import {
buildLeadingSilenceTrimmedWavBlob,
findFirstAudibleFrame,
} from './creativeAudioSilenceTrim';
function createAudioBufferStub(
channels: number[][],
sampleRate = 1000,
): AudioBuffer {
return {
length: channels[0]?.length ?? 0,
numberOfChannels: channels.length,
sampleRate,
duration: (channels[0]?.length ?? 0) / sampleRate,
getChannelData: (channel: number) =>
new Float32Array(channels[channel] ?? []),
} as AudioBuffer;
}
test('findFirstAudibleFrame skips leading frames that are silent across all channels', () => {
const buffer = createAudioBufferStub([
[0, 0.003, -0.006, 0.012, 0.02],
[0, -0.004, 0.009, 0, 0],
]);
expect(findFirstAudibleFrame(buffer, 0.01)).toBe(3);
});
test('buildLeadingSilenceTrimmedWavBlob writes a wav that starts at the first audible frame', async () => {
const buffer = createAudioBufferStub(
[
[0, 0, 0, 0.25, -0.5],
[0, 0, 0, -0.25, 0.5],
],
1000,
);
const blob = buildLeadingSilenceTrimmedWavBlob(buffer, {
silenceThreshold: 0.01,
minimumTrimDurationMs: 1,
});
expect(blob).not.toBeNull();
expect(blob?.type).toBe('audio/wav');
const bytes = await blob!.arrayBuffer();
const view = new DataView(bytes);
expect(String.fromCharCode(...new Uint8Array(bytes, 0, 4))).toBe('RIFF');
expect(String.fromCharCode(...new Uint8Array(bytes, 8, 4))).toBe('WAVE');
expect(String.fromCharCode(...new Uint8Array(bytes, 36, 4))).toBe('data');
expect(view.getUint32(40, true)).toBe(8);
expect(view.getInt16(44, true)).toBeCloseTo(8191, -1);
expect(view.getInt16(46, true)).toBeCloseTo(-8192, -1);
expect(view.getInt16(48, true)).toBeCloseTo(-16384, -1);
expect(view.getInt16(50, true)).toBeCloseTo(16383, -1);
});
test('buildLeadingSilenceTrimmedWavBlob keeps the original recording when no leading silence is removable', () => {
const startsImmediately = createAudioBufferStub([[0.2, 0.1, 0.05]], 1000);
const allSilent = createAudioBufferStub([[0, 0.001, -0.001]], 1000);
expect(
buildLeadingSilenceTrimmedWavBlob(startsImmediately, {
silenceThreshold: 0.01,
minimumTrimDurationMs: 1,
}),
).toBeNull();
expect(
buildLeadingSilenceTrimmedWavBlob(allSilent, {
silenceThreshold: 0.01,
minimumTrimDurationMs: 1,
}),
).toBeNull();
});
@@ -0,0 +1,190 @@
type BrowserAudioGlobal = typeof globalThis & {
webkitAudioContext?: typeof AudioContext;
};
export type LeadingSilenceTrimOptions = {
silenceThreshold?: number;
minimumTrimDurationMs?: number;
};
const DEFAULT_SILENCE_THRESHOLD = 0.01;
const DEFAULT_MINIMUM_TRIM_DURATION_MS = 20;
const WAV_HEADER_BYTE_LENGTH = 44;
const WAV_BITS_PER_SAMPLE = 16;
const WAV_BYTES_PER_SAMPLE = WAV_BITS_PER_SAMPLE / 8;
export function findFirstAudibleFrame(
buffer: AudioBuffer,
silenceThreshold = DEFAULT_SILENCE_THRESHOLD,
) {
const threshold = Math.max(0, silenceThreshold);
for (let frameIndex = 0; frameIndex < buffer.length; frameIndex += 1) {
for (
let channelIndex = 0;
channelIndex < buffer.numberOfChannels;
channelIndex += 1
) {
const channelData = buffer.getChannelData(channelIndex);
if (Math.abs(channelData[frameIndex] ?? 0) > threshold) {
return frameIndex;
}
}
}
return null;
}
export function buildLeadingSilenceTrimmedWavBlob(
buffer: AudioBuffer,
options: LeadingSilenceTrimOptions = {},
) {
const silenceThreshold =
options.silenceThreshold ?? DEFAULT_SILENCE_THRESHOLD;
const minimumTrimDurationMs =
options.minimumTrimDurationMs ?? DEFAULT_MINIMUM_TRIM_DURATION_MS;
const firstAudibleFrame = findFirstAudibleFrame(buffer, silenceThreshold);
if (firstAudibleFrame === null) {
return null;
}
const minimumTrimFrames = Math.max(
1,
Math.round((buffer.sampleRate * minimumTrimDurationMs) / 1000),
);
if (firstAudibleFrame < minimumTrimFrames) {
return null;
}
const frameCount = buffer.length - firstAudibleFrame;
if (frameCount <= 0) {
return null;
}
return encodeAudioBufferSectionToWavBlob(
buffer,
firstAudibleFrame,
frameCount,
);
}
export async function trimLeadingSilenceFromRecordedAudioFile(
file: File,
options: LeadingSilenceTrimOptions = {},
) {
try {
const decodedBuffer = await decodeRecordedAudioFile(file);
if (!decodedBuffer) {
return file;
}
const trimmedBlob = buildLeadingSilenceTrimmedWavBlob(
decodedBuffer,
options,
);
if (!trimmedBlob) {
return file;
}
return new File([trimmedBlob], buildTrimmedAudioFileName(file.name), {
type: trimmedBlob.type,
lastModified: Date.now(),
});
} catch {
// 录音裁剪只是体验优化,浏览器解码失败时必须保留用户刚录好的原始文件。
return file;
}
}
function getAudioContextConstructor() {
const audioGlobal = globalThis as BrowserAudioGlobal;
return audioGlobal.AudioContext ?? audioGlobal.webkitAudioContext ?? null;
}
async function decodeRecordedAudioFile(file: File) {
const AudioContextConstructor = getAudioContextConstructor();
if (!AudioContextConstructor) {
return null;
}
const context = new AudioContextConstructor();
try {
const bytes = await file.arrayBuffer();
return await context.decodeAudioData(bytes.slice(0));
} finally {
void context.close();
}
}
function encodeAudioBufferSectionToWavBlob(
buffer: AudioBuffer,
startFrame: number,
frameCount: number,
) {
// MediaRecorder 输出格式不稳定;解码后统一写成 WAV,避免再依赖浏览器重新编码。
const channelCount = Math.max(1, buffer.numberOfChannels);
const dataByteLength =
frameCount * channelCount * WAV_BYTES_PER_SAMPLE;
const output = new ArrayBuffer(WAV_HEADER_BYTE_LENGTH + dataByteLength);
const view = new DataView(output);
const channelData = Array.from({ length: channelCount }, (_value, index) =>
index < buffer.numberOfChannels
? buffer.getChannelData(index)
: new Float32Array(buffer.length),
);
writeAscii(view, 0, 'RIFF');
view.setUint32(4, 36 + dataByteLength, true);
writeAscii(view, 8, 'WAVE');
writeAscii(view, 12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, channelCount, true);
view.setUint32(24, buffer.sampleRate, true);
view.setUint32(
28,
buffer.sampleRate * channelCount * WAV_BYTES_PER_SAMPLE,
true,
);
view.setUint16(32, channelCount * WAV_BYTES_PER_SAMPLE, true);
view.setUint16(34, WAV_BITS_PER_SAMPLE, true);
writeAscii(view, 36, 'data');
view.setUint32(40, dataByteLength, true);
let outputOffset = WAV_HEADER_BYTE_LENGTH;
for (let frameOffset = 0; frameOffset < frameCount; frameOffset += 1) {
const sourceFrame = startFrame + frameOffset;
for (let channelIndex = 0; channelIndex < channelCount; channelIndex += 1) {
const sample = channelData[channelIndex]?.[sourceFrame] ?? 0;
view.setInt16(outputOffset, toSignedPcm16(sample), true);
outputOffset += WAV_BYTES_PER_SAMPLE;
}
}
return new Blob([output], { type: 'audio/wav' });
}
function toSignedPcm16(sample: number) {
const clamped = Math.max(-1, Math.min(1, sample));
return clamped < 0
? Math.round(clamped * 0x8000)
: Math.round(clamped * 0x7fff);
}
function writeAscii(view: DataView, offset: number, value: string) {
for (let index = 0; index < value.length; index += 1) {
view.setUint8(offset + index, value.charCodeAt(index));
}
}
function buildTrimmedAudioFileName(fileName: string) {
const normalizedName = fileName.trim();
if (!normalizedName) {
return 'recorded-audio.wav';
}
return /\.[^.]+$/u.test(normalizedName)
? normalizedName.replace(/\.[^.]+$/u, '.wav')
: `${normalizedName}.wav`;
}
@@ -10,7 +10,7 @@ import type { BabyObjectMatchDraft } from '../../../packages/shared/src/contract
import type { SquareHoleWorkSummary } from '../../../packages/shared/src/contracts/squareHoleWorks';
import type { CreationEntryConfig } from '../../services/creationEntryConfigService';
import { derivePlatformCreationTypes } from '../platform-entry/platformEntryCreationTypes';
import { CustomWorldCreationHub } from './CustomWorldCreationHub';
import { CustomWorldCreationHub } from './CustomWorldCreationHub.testAdapter';
const noopCreateType = () => {};
@@ -1043,14 +1043,10 @@ test('creation hub opens persisted rpg drafts by card click', async () => {
expect(openedItems).toEqual([persistedDraft]);
});
test('creation hub published share icon copies share text without opening the card', async () => {
test('creation hub published share icon opens unified share payload without opening the card', async () => {
const user = userEvent.setup();
const writeText = vi.fn(async () => undefined);
const onOpenPuzzleDetail = vi.fn();
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
const onShareWork = vi.fn();
render(
<CustomWorldCreationHub
@@ -1081,6 +1077,7 @@ test('creation hub published share icon copies share text without opening the ca
onOpenDraft={() => {}}
onEnterPublished={() => {}}
onOpenPuzzleDetail={onOpenPuzzleDetail}
onShareWork={onShareWork}
entryConfig={testEntryConfig}
creationTypes={testCreationTypes}
/>,
@@ -1092,19 +1089,12 @@ test('creation hub published share icon copies share text without opening the ca
await user.click(shareButton);
expect(writeText).toHaveBeenCalledWith(
expect.stringContaining('邀请你来玩《沉钟拼图'),
);
expect(writeText).toHaveBeenCalledWith(
expect.stringContaining('作品号:PZ-PROFILE1'),
);
expect(writeText).toHaveBeenCalledWith(
expect.stringContaining('/gallery/puzzle/detail?work=PZ-PROFILE1'),
);
expect(onShareWork).toHaveBeenCalledWith({
title: '沉钟拼图',
publicWorkCode: 'PZ-PROFILE1',
stage: 'puzzle-gallery-detail',
});
expect(onOpenPuzzleDetail).not.toHaveBeenCalled();
expect(
await screen.findByRole('button', { name: '分享内容已复制' }),
).toBeTruthy();
});
test('creation hub published share icon is shown directly on the card header', () => {
@@ -4,7 +4,7 @@ import { expect, test } from 'vitest';
import type { CreationEntryConfig } from '../../services/creationEntryConfigService';
import { derivePlatformCreationTypes } from '../platform-entry/platformEntryCreationTypes';
import { buildCreationWorkShelfItems } from './creationWorkShelf';
import { CustomWorldCreationHub } from './CustomWorldCreationHub';
import { CustomWorldCreationHub } from './CustomWorldCreationHub.testAdapter';
const noopCreateType = () => {};
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -241,7 +241,7 @@ test('creation start card renders reference-aligned banner and template metadata
expect(html).toContain('creation-template-card__body');
expect(html).toContain('creation-template-card__cost-badge');
expect(html).toContain('拼图关卡创作');
expect(html).toContain('10-20泥点数');
expect(html).toContain('10泥点数');
expect(html).toContain('即将开放');
expect(html).toContain('data-locked="true"');
expect(html).toContain('暂未开放');
@@ -292,7 +292,62 @@ test('locked creation template card replaces mud point cost with unavailable sta
expect(html).toContain('data-locked="true"');
expect(html).toContain('即将开放');
expect(html).toContain('暂未开放');
expect(html).not.toContain('10-20泥点数');
expect(html).not.toContain('10泥点数');
});
test('creation template card renders mud point cost from unified creation spec', () => {
const config = {
...testEntryConfig,
creationTypes: [
{
id: 'puzzle',
title: '拼图',
subtitle: '拼图关卡创作',
badge: '可创建',
imageSrc: '/creation-type-references/puzzle.webp',
visible: true,
open: true,
sortOrder: 30,
categoryId: 'recommended',
categoryLabel: '热门推荐',
categorySortOrder: 20,
updatedAtMicros: 1,
unifiedCreationSpec: {
playId: 'puzzle',
title: '拼图',
mudPointCost: 12,
workspaceStage: 'puzzle-agent-workspace',
generationStage: 'puzzle-generating',
resultStage: 'puzzle-result',
fields: [
{
id: 'pictureDescription',
kind: 'text',
label: '画面描述',
required: true,
},
],
},
},
],
} satisfies CreationEntryConfig;
const html = renderToStaticMarkup(
<CustomWorldCreationHub
items={[]}
loading={false}
error={null}
onRetry={() => {}}
onCreateType={noopCreateType}
onOpenDraft={() => {}}
onEnterPublished={() => {}}
entryConfig={config}
creationTypes={derivePlatformCreationTypes(config.creationTypes)}
mode="start-only"
/>,
);
expect(html).toContain('12泥点数');
expect(html).not.toContain('10泥点数');
});
test('creation start card falls back to legacy single banner when eventBanners is empty', () => {
@@ -525,6 +580,7 @@ test('creation start card maps backend jump-hop draft to template card', () => {
profileId: 'jump-hop-profile-1',
ownerUserId: 'user-1',
sourceSessionId: 'jump-hop-session-1',
themeText: '跳一跳生成草稿',
workTitle: '跳一跳生成草稿',
workDescription: '后端仍在生成跳一跳玩法。',
themeTags: ['跳一跳'],
@@ -0,0 +1,128 @@
import { isPlatformCreationTypeVisible } from '../platform-entry/platformEntryCreationTypes';
import {
buildCreationWorkShelfItems,
type CreationWorkShelfItem,
} from './creationWorkShelf';
import {
CustomWorldCreationHub as CustomWorldCreationHubView,
} from './CustomWorldCreationHub';
type ShelfBuilderParams = Parameters<typeof buildCreationWorkShelfItems>[0];
type HubViewProps = Parameters<typeof CustomWorldCreationHubView>[0];
type LegacyCustomWorldCreationHubProps = Omit<HubViewProps, 'shelfItems'> &
Partial<
Omit<ShelfBuilderParams, 'rpgItems' | 'bigFishItems' | 'puzzleItems'>
> & {
shelfItems?: CreationWorkShelfItem[];
items?: ShelfBuilderParams['rpgItems'];
bigFishItems?: ShelfBuilderParams['bigFishItems'];
puzzleItems?: ShelfBuilderParams['puzzleItems'];
onOpenDraft?: ShelfBuilderParams['onOpenRpgDraft'];
onEnterPublished?: ShelfBuilderParams['onEnterRpgPublished'];
onDeletePublished?: ShelfBuilderParams['onDeleteRpg'] | null;
getWorkState?: ShelfBuilderParams['getItemState'];
};
/** 测试用 Adapter:旧 fixture 先转成 shelfItems,生产 Hub Interface 保持窄面。 */
export function CustomWorldCreationHub({
shelfItems,
items = [],
rpgLibraryEntries = [],
bigFishItems = [],
match3dItems = [],
squareHoleItems = [],
jumpHopItems = [],
woodenFishItems = [],
puzzleItems = [],
babyObjectMatchItems = [],
barkBattleItems = [],
visualNovelItems = [],
onOpenDraft,
onEnterPublished,
onDeletePublished = null,
onOpenBigFishDetail,
onDeleteBigFish,
onOpenMatch3DDetail,
onDeleteMatch3D,
onOpenSquareHoleDetail,
onDeleteSquareHole,
onOpenJumpHopDetail,
onDeleteJumpHop,
onOpenWoodenFishDetail,
onDeleteWoodenFish,
onOpenPuzzleDetail,
onDeletePuzzle,
onClaimPuzzlePointIncentive,
onOpenBabyObjectMatchDetail,
onDeleteBabyObjectMatch,
onOpenBarkBattleDetail,
onDeleteBarkBattle,
onOpenVisualNovelDetail,
onDeleteVisualNovel,
getItemState,
getWorkState,
creationTypes,
...props
}: LegacyCustomWorldCreationHubProps) {
const isSquareHoleCreationVisible = isPlatformCreationTypeVisible(
creationTypes,
'square-hole',
);
const resolvedShelfItems =
shelfItems ??
buildCreationWorkShelfItems({
rpgItems: items,
rpgLibraryEntries,
bigFishItems,
match3dItems,
squareHoleItems: isSquareHoleCreationVisible ? squareHoleItems : [],
jumpHopItems,
woodenFishItems,
puzzleItems,
babyObjectMatchItems,
barkBattleItems,
visualNovelItems,
canDeleteRpg: Boolean(onDeletePublished),
canDeleteBigFish: Boolean(onDeleteBigFish),
canDeleteMatch3D: Boolean(onDeleteMatch3D),
canDeleteSquareHole: Boolean(onDeleteSquareHole),
canDeleteJumpHop: Boolean(onDeleteJumpHop),
canDeleteWoodenFish: Boolean(onDeleteWoodenFish),
canDeletePuzzle: Boolean(onDeletePuzzle),
canDeleteBabyObjectMatch: Boolean(onDeleteBabyObjectMatch),
canDeleteBarkBattle: Boolean(onDeleteBarkBattle),
canDeleteVisualNovel: Boolean(onDeleteVisualNovel),
onOpenRpgDraft: onOpenDraft,
onEnterRpgPublished: onEnterPublished,
onDeleteRpg: onDeletePublished ?? undefined,
onOpenBigFishDetail,
onDeleteBigFish,
onOpenMatch3DDetail,
onDeleteMatch3D,
onOpenSquareHoleDetail,
onDeleteSquareHole,
onOpenJumpHopDetail,
onDeleteJumpHop,
onOpenWoodenFishDetail,
onDeleteWoodenFish,
onOpenPuzzleDetail,
onDeletePuzzle,
onClaimPuzzlePointIncentive,
onOpenBabyObjectMatchDetail,
onDeleteBabyObjectMatch,
onOpenBarkBattleDetail,
onDeleteBarkBattle,
onOpenVisualNovelDetail,
onDeleteVisualNovel,
getItemState: getItemState ?? getWorkState,
});
return (
<CustomWorldCreationHubView
{...props}
creationTypes={creationTypes}
shelfItems={resolvedShelfItems}
/>
);
}
@@ -1,29 +1,16 @@
import { useEffect, useMemo, useState } from 'react';
import type { BarkBattleWorkSummary } from '../../../packages/shared/src/contracts/barkBattle';
import type { BigFishWorkSummary } from '../../../packages/shared/src/contracts/bigFishWorkSummary';
import type { CustomWorldWorkSummary } from '../../../packages/shared/src/contracts/customWorldAgent';
import type { BabyObjectMatchDraft } from '../../../packages/shared/src/contracts/edutainmentBabyObject';
import type { JumpHopWorkSummaryResponse } from '../../../packages/shared/src/contracts/jumpHop';
import type { Match3DWorkSummary } from '../../../packages/shared/src/contracts/match3dWorks';
import type { PuzzleWorkSummary } from '../../../packages/shared/src/contracts/puzzleWorkSummary';
import type { WoodenFishWorkSummaryResponse } from '../../../packages/shared/src/contracts/woodenFish';
import type { CustomWorldLibraryEntry } from '../../../packages/shared/src/contracts/runtime';
import type { SquareHoleWorkSummary } from '../../../packages/shared/src/contracts/squareHoleWorks';
import type { VisualNovelWorkSummary } from '../../../packages/shared/src/contracts/visualNovel';
import { resolveSelectionStageFromPath } from '../../routing/appPageRoutes';
import type { CreationEntryConfig } from '../../services/creationEntryConfigService';
import type { CustomWorldProfile } from '../../types';
import type { PublishShareModalPayload } from '../common/publishShareModalModel';
import type {
PlatformCreationTypeCard,
PlatformCreationTypeId,
} from '../platform-entry/platformEntryCreationTypes';
import { isPlatformCreationTypeVisible } from '../platform-entry/platformEntryCreationTypes';
import {
buildCreationWorkShelfItems,
getCreationWorkShelfItemTime,
type CreationWorkShelfItem,
type CreationWorkShelfMetricId,
type CreationWorkShelfRuntimeState,
getCreationWorkShelfItemTime,
} from './creationWorkShelf';
import {
CustomWorldCreationStartCard,
@@ -47,7 +34,7 @@ type WorkMetricSnapshot = Record<
>;
type CustomWorldCreationHubProps = {
items: CustomWorldWorkSummary[];
shelfItems: CreationWorkShelfItem[];
loading: boolean;
error: string | null;
onRetry: () => void;
@@ -55,46 +42,10 @@ type CustomWorldCreationHubProps = {
entryConfig: CreationEntryConfig;
creationTypes: readonly PlatformCreationTypeCard[];
onCreateType: (type: PlatformCreationTypeId) => void;
onOpenDraft: (item: CustomWorldWorkSummary) => void;
onEnterPublished: (profileId: string) => void;
onDeletePublished?: ((item: CustomWorldWorkSummary) => void) | null;
deletingWorkId?: string | null;
rpgLibraryEntries?: CustomWorldLibraryEntry<CustomWorldProfile>[];
bigFishItems?: BigFishWorkSummary[];
onOpenBigFishDetail?: (item: BigFishWorkSummary) => void;
onDeleteBigFish?: ((item: BigFishWorkSummary) => void) | null;
match3dItems?: Match3DWorkSummary[];
onOpenMatch3DDetail?: (item: Match3DWorkSummary) => void;
onDeleteMatch3D?: ((item: Match3DWorkSummary) => void) | null;
squareHoleItems?: SquareHoleWorkSummary[];
onOpenSquareHoleDetail?: (item: SquareHoleWorkSummary) => void;
onDeleteSquareHole?: ((item: SquareHoleWorkSummary) => void) | null;
jumpHopItems?: JumpHopWorkSummaryResponse[];
onOpenJumpHopDetail?: (item: JumpHopWorkSummaryResponse) => void;
onDeleteJumpHop?: ((item: JumpHopWorkSummaryResponse) => void) | null;
woodenFishItems?: WoodenFishWorkSummaryResponse[];
onOpenWoodenFishDetail?:
| ((item: WoodenFishWorkSummaryResponse) => void)
| null;
onDeleteWoodenFish?: ((item: WoodenFishWorkSummaryResponse) => void) | null;
puzzleItems?: PuzzleWorkSummary[];
onOpenPuzzleDetail?: (item: PuzzleWorkSummary) => void;
onDeletePuzzle?: ((item: PuzzleWorkSummary) => void) | null;
onClaimPuzzlePointIncentive?: ((item: PuzzleWorkSummary) => void) | null;
claimingPuzzleProfileId?: string | null;
babyObjectMatchItems?: BabyObjectMatchDraft[];
onOpenBabyObjectMatchDetail?: ((item: BabyObjectMatchDraft) => void) | null;
onDeleteBabyObjectMatch?: ((item: BabyObjectMatchDraft) => void) | null;
barkBattleItems?: BarkBattleWorkSummary[];
onOpenBarkBattleDetail?: ((item: BarkBattleWorkSummary) => void) | null;
onDeleteBarkBattle?: ((item: BarkBattleWorkSummary) => void) | null;
visualNovelItems?: VisualNovelWorkSummary[];
onOpenVisualNovelDetail?: ((item: VisualNovelWorkSummary) => void) | null;
onDeleteVisualNovel?: ((item: VisualNovelWorkSummary) => void) | null;
getWorkState?: (
item: CreationWorkShelfItem,
) => CreationWorkShelfRuntimeState | null;
onOpenShelfItem?: (item: CreationWorkShelfItem) => void;
onShareWork?: ((payload: PublishShareModalPayload) => void) | null;
// 中文注释:底部加号入口可传入后端作品架摘要,用于推导最近使用过的模板。
recentWorkItems?: CreationWorkShelfItem[];
mode?: 'full' | 'start-only' | 'works-only';
@@ -163,9 +114,44 @@ function writeWorkMetricSnapshot(items: CreationWorkShelfItem[]) {
}
}
function resolveShelfShareStage(
sharePath: string,
): PublishShareModalPayload['stage'] | null {
let pathname = '';
try {
pathname = new URL(sharePath, 'https://genarrative.local').pathname;
} catch {
pathname = sharePath.split(/[?#]/u)[0] ?? '';
}
const stage = resolveSelectionStageFromPath(pathname);
return stage === 'platform' ? null : stage;
}
function buildCreationWorkShelfSharePayload(
item: CreationWorkShelfItem,
): PublishShareModalPayload | null {
const publicWorkCode = item.publicWorkCode?.trim();
const sharePath = item.sharePath?.trim();
if (!publicWorkCode || !sharePath) {
return null;
}
const stage = resolveShelfShareStage(sharePath);
if (!stage) {
return null;
}
return {
title: item.title,
publicWorkCode,
stage,
};
}
/** 渲染底部加号创作入口页与草稿作品架,最近创作复用最近使用过的模板入口。 */
export function CustomWorldCreationHub({
items,
shelfItems,
loading,
error,
onRetry,
@@ -173,137 +159,15 @@ export function CustomWorldCreationHub({
entryConfig,
creationTypes,
onCreateType,
onOpenDraft,
onEnterPublished,
onDeletePublished = null,
deletingWorkId = null,
rpgLibraryEntries = [],
bigFishItems = [],
onOpenBigFishDetail,
onDeleteBigFish = null,
match3dItems = [],
onOpenMatch3DDetail,
onDeleteMatch3D = null,
squareHoleItems = [],
onOpenSquareHoleDetail,
onDeleteSquareHole = null,
jumpHopItems = [],
onOpenJumpHopDetail,
onDeleteJumpHop = null,
woodenFishItems = [],
onOpenWoodenFishDetail = null,
onDeleteWoodenFish = null,
puzzleItems = [],
onOpenPuzzleDetail,
onDeletePuzzle = null,
onClaimPuzzlePointIncentive = null,
claimingPuzzleProfileId = null,
babyObjectMatchItems = [],
onOpenBabyObjectMatchDetail = null,
onDeleteBabyObjectMatch = null,
barkBattleItems = [],
onOpenBarkBattleDetail = null,
onDeleteBarkBattle = null,
visualNovelItems = [],
onOpenVisualNovelDetail = null,
onDeleteVisualNovel = null,
getWorkState,
onOpenShelfItem,
onShareWork = null,
recentWorkItems: recentWorkSourceItems,
mode = 'full',
}: CustomWorldCreationHubProps) {
const [activeFilter, setActiveFilter] =
useState<CustomWorldWorkFilter>('all');
const isSquareHoleCreationVisible = isPlatformCreationTypeVisible(
creationTypes,
'square-hole',
);
const shelfItems = useMemo(
() =>
buildCreationWorkShelfItems({
rpgItems: items,
rpgLibraryEntries,
bigFishItems,
match3dItems,
squareHoleItems: isSquareHoleCreationVisible ? squareHoleItems : [],
jumpHopItems,
woodenFishItems,
puzzleItems,
babyObjectMatchItems,
barkBattleItems,
visualNovelItems,
canDeleteRpg: Boolean(onDeletePublished),
canDeleteBigFish: Boolean(onDeleteBigFish),
canDeleteMatch3D: Boolean(onDeleteMatch3D),
canDeleteSquareHole:
isSquareHoleCreationVisible && Boolean(onDeleteSquareHole),
canDeleteJumpHop: Boolean(onDeleteJumpHop),
canDeleteWoodenFish: Boolean(onDeleteWoodenFish),
canDeletePuzzle: Boolean(onDeletePuzzle),
canDeleteBabyObjectMatch: Boolean(onDeleteBabyObjectMatch),
canDeleteBarkBattle: Boolean(onDeleteBarkBattle),
canDeleteVisualNovel: Boolean(onDeleteVisualNovel),
onOpenRpgDraft: onOpenDraft,
onEnterRpgPublished: onEnterPublished,
onDeleteRpg: onDeletePublished ?? undefined,
onOpenBigFishDetail,
onDeleteBigFish: onDeleteBigFish ?? undefined,
onOpenMatch3DDetail,
onDeleteMatch3D: onDeleteMatch3D ?? undefined,
onOpenSquareHoleDetail,
onDeleteSquareHole: onDeleteSquareHole ?? undefined,
onOpenJumpHopDetail: onOpenJumpHopDetail ?? undefined,
onDeleteJumpHop: onDeleteJumpHop ?? undefined,
onOpenWoodenFishDetail: onOpenWoodenFishDetail ?? undefined,
onDeleteWoodenFish: onDeleteWoodenFish ?? undefined,
onOpenPuzzleDetail,
onDeletePuzzle: onDeletePuzzle ?? undefined,
onClaimPuzzlePointIncentive: onClaimPuzzlePointIncentive ?? undefined,
onOpenBabyObjectMatchDetail: onOpenBabyObjectMatchDetail ?? undefined,
onDeleteBabyObjectMatch: onDeleteBabyObjectMatch ?? undefined,
onOpenBarkBattleDetail: onOpenBarkBattleDetail ?? undefined,
onDeleteBarkBattle: onDeleteBarkBattle ?? undefined,
onOpenVisualNovelDetail: onOpenVisualNovelDetail ?? undefined,
onDeleteVisualNovel: onDeleteVisualNovel ?? undefined,
getItemState: getWorkState,
}),
[
bigFishItems,
isSquareHoleCreationVisible,
babyObjectMatchItems,
barkBattleItems,
items,
match3dItems,
onDeleteBigFish,
onDeleteMatch3D,
onDeleteSquareHole,
onDeletePublished,
onDeletePuzzle,
onDeleteBabyObjectMatch,
onDeleteBarkBattle,
onDeleteVisualNovel,
onDeleteJumpHop,
onDeleteWoodenFish,
onClaimPuzzlePointIncentive,
onOpenBigFishDetail,
onOpenDraft,
onOpenMatch3DDetail,
onOpenBabyObjectMatchDetail,
onOpenBarkBattleDetail,
onOpenPuzzleDetail,
onOpenSquareHoleDetail,
onOpenVisualNovelDetail,
onOpenWoodenFishDetail,
onEnterPublished,
getWorkState,
puzzleItems,
rpgLibraryEntries,
onOpenJumpHopDetail,
jumpHopItems,
woodenFishItems,
visualNovelItems,
],
);
const [metricSnapshot] = useState<WorkMetricSnapshot>(() =>
readWorkMetricSnapshot(),
);
@@ -341,44 +205,8 @@ export function CustomWorldCreationHub({
function handleOpenShelfItem(item: CreationWorkShelfItem) {
onOpenShelfItem?.(item);
switch (item.source.kind) {
case 'puzzle':
onOpenPuzzleDetail?.(item.source.item);
return;
case 'baby-object-match':
onOpenBabyObjectMatchDetail?.(item.source.item);
return;
case 'visual-novel':
onOpenVisualNovelDetail?.(item.source.item);
return;
case 'bark-battle':
onOpenBarkBattleDetail?.(item.source.item);
return;
case 'big-fish':
onOpenBigFishDetail?.(item.source.item);
return;
case 'match3d':
onOpenMatch3DDetail?.(item.source.item);
return;
case 'square-hole':
onOpenSquareHoleDetail?.(item.source.item);
return;
case 'jump-hop':
onOpenJumpHopDetail?.(item.source.item);
return;
case 'wooden-fish':
onOpenWoodenFishDetail?.(item.source.item);
return;
case 'rpg':
if (item.status === 'draft') {
onOpenDraft(item.source.item);
return;
}
if (item.source.item.profileId) {
onEnterPublished(item.source.item.profileId);
}
}
// 中文注释:玩法差异由 Work Shelf Adapter 承载,Hub 只负责响应卡片点击。
item.actions.open();
}
function buildDeleteAction(item: CreationWorkShelfItem) {
@@ -389,6 +217,17 @@ export function CustomWorldCreationHub({
return item.actions.delete ?? null;
}
function buildShareAction(item: CreationWorkShelfItem) {
const payload = buildCreationWorkShelfSharePayload(item);
if (!payload) {
return null;
}
return () => {
onShareWork?.(payload);
};
}
function buildPointIncentiveAction(item: CreationWorkShelfItem) {
return item.actions.claimPointIncentive ?? null;
}
@@ -464,6 +303,7 @@ export function CustomWorldCreationHub({
}}
onDelete={buildDeleteAction(item)}
deleteBusy={deletingWorkId === item.id}
onShare={buildShareAction(item)}
onClaimPointIncentive={buildPointIncentiveAction(item)}
pointIncentiveBusy={
item.source.kind === 'puzzle' &&

Some files were not shown because too many files have changed in this diff Show More