Preserve partial creation replies on stream failure
Some checks failed
CI / verify (push) Has been cancelled
Some checks failed
CI / verify (push) Has been cancelled
This commit is contained in:
@@ -107,12 +107,17 @@ test('creation hub reflects updated draft title summary and counts after rerende
|
||||
const rpgButton = screen.getByRole('button', { name: /角色扮演/u });
|
||||
const puzzleButton = screen.getByRole('button', { name: /拼图.*创意礼物/u });
|
||||
const match3dButton = screen.getByRole('button', { name: /抓大鹅/u });
|
||||
const squareHoleButton = screen.getByRole('button', { name: /方洞挑战/u });
|
||||
expect(
|
||||
rpgButton.compareDocumentPosition(puzzleButton) &
|
||||
Node.DOCUMENT_POSITION_FOLLOWING,
|
||||
).toBeTruthy();
|
||||
expect((rpgButton as HTMLButtonElement).disabled).toBe(false);
|
||||
expect((match3dButton as HTMLButtonElement).disabled).toBe(false);
|
||||
expect((squareHoleButton as HTMLButtonElement).disabled).toBe(false);
|
||||
expect(
|
||||
within(squareHoleButton).getAllByText('反直觉形状分拣').length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(
|
||||
within(match3dButton).getAllByText('经典消除玩法').length,
|
||||
).toBeGreaterThan(0);
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { BigFishWorkSummary } from '../../../packages/shared/src/contracts/
|
||||
import type { CustomWorldWorkSummary } from '../../../packages/shared/src/contracts/customWorldAgent';
|
||||
import type { Match3DWorkSummary } from '../../../packages/shared/src/contracts/match3dWorks';
|
||||
import type { PuzzleWorkSummary } from '../../../packages/shared/src/contracts/puzzleWorkSummary';
|
||||
import type { SquareHoleWorkSummary } from '../../../packages/shared/src/contracts/squareHoleWorks';
|
||||
import type { CustomWorldLibraryEntry } from '../../../packages/shared/src/contracts/runtime';
|
||||
import type { CustomWorldProfile } from '../../types';
|
||||
import type { PlatformCreationTypeId } from '../platform-entry/platformEntryCreationTypes';
|
||||
@@ -48,6 +49,9 @@ type CustomWorldCreationHubProps = {
|
||||
match3dItems?: Match3DWorkSummary[];
|
||||
onOpenMatch3DDetail?: (item: Match3DWorkSummary) => void;
|
||||
onDeleteMatch3D?: ((item: Match3DWorkSummary) => void) | null;
|
||||
squareHoleItems?: SquareHoleWorkSummary[];
|
||||
onOpenSquareHoleDetail?: (item: SquareHoleWorkSummary) => void;
|
||||
onDeleteSquareHole?: ((item: SquareHoleWorkSummary) => void) | null;
|
||||
puzzleItems?: PuzzleWorkSummary[];
|
||||
onOpenPuzzleDetail?: (item: PuzzleWorkSummary) => void;
|
||||
onDeletePuzzle?: ((item: PuzzleWorkSummary) => void) | null;
|
||||
@@ -137,6 +141,9 @@ export function CustomWorldCreationHub({
|
||||
match3dItems = [],
|
||||
onOpenMatch3DDetail,
|
||||
onDeleteMatch3D = null,
|
||||
squareHoleItems = [],
|
||||
onOpenSquareHoleDetail,
|
||||
onDeleteSquareHole = null,
|
||||
puzzleItems = [],
|
||||
onOpenPuzzleDetail,
|
||||
onDeletePuzzle = null,
|
||||
@@ -152,10 +159,12 @@ export function CustomWorldCreationHub({
|
||||
rpgLibraryEntries,
|
||||
bigFishItems,
|
||||
match3dItems,
|
||||
squareHoleItems,
|
||||
puzzleItems,
|
||||
canDeleteRpg: Boolean(onDeletePublished),
|
||||
canDeleteBigFish: Boolean(onDeleteBigFish),
|
||||
canDeleteMatch3D: Boolean(onDeleteMatch3D),
|
||||
canDeleteSquareHole: Boolean(onDeleteSquareHole),
|
||||
canDeletePuzzle: Boolean(onDeletePuzzle),
|
||||
}),
|
||||
[
|
||||
@@ -164,10 +173,12 @@ export function CustomWorldCreationHub({
|
||||
match3dItems,
|
||||
onDeleteBigFish,
|
||||
onDeleteMatch3D,
|
||||
onDeleteSquareHole,
|
||||
onDeletePublished,
|
||||
onDeletePuzzle,
|
||||
puzzleItems,
|
||||
rpgLibraryEntries,
|
||||
squareHoleItems,
|
||||
],
|
||||
);
|
||||
const [metricSnapshot] = useState<WorkMetricSnapshot>(() =>
|
||||
@@ -201,6 +212,9 @@ export function CustomWorldCreationHub({
|
||||
case 'match3d':
|
||||
onOpenMatch3DDetail?.(item.source.item);
|
||||
return;
|
||||
case 'square-hole':
|
||||
onOpenSquareHoleDetail?.(item.source.item);
|
||||
return;
|
||||
case 'rpg':
|
||||
if (item.status === 'draft') {
|
||||
onOpenDraft(item.source.item);
|
||||
@@ -237,6 +251,12 @@ export function CustomWorldCreationHub({
|
||||
onDeleteMatch3D?.(sourceItem);
|
||||
};
|
||||
}
|
||||
case 'square-hole': {
|
||||
const sourceItem = item.source.item;
|
||||
return () => {
|
||||
onDeleteSquareHole?.(sourceItem);
|
||||
};
|
||||
}
|
||||
case 'rpg': {
|
||||
const sourceItem = item.source.item;
|
||||
return () => {
|
||||
|
||||
@@ -40,7 +40,7 @@ export function CustomWorldCreationStartCard({
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="-mx-1 flex snap-x gap-2 overflow-x-auto px-1 pb-1 scrollbar-hide sm:mx-0 sm:grid sm:gap-3 sm:overflow-visible sm:px-0 sm:pb-0 sm:grid-cols-2 xl:grid-cols-5 xl:gap-2.5">
|
||||
<div className="-mx-1 flex snap-x gap-2 overflow-x-auto px-1 pb-1 scrollbar-hide sm:mx-0 sm:grid sm:gap-3 sm:overflow-visible sm:px-0 sm:pb-0 sm:grid-cols-2 xl:grid-cols-6 xl:gap-2.5">
|
||||
{visibleCreationTypes.map((item) => {
|
||||
const disabled = item.locked || busy;
|
||||
|
||||
|
||||
@@ -2,16 +2,23 @@ import type { BigFishWorkSummary } from '../../../packages/shared/src/contracts/
|
||||
import type { CustomWorldWorkSummary } from '../../../packages/shared/src/contracts/customWorldAgent';
|
||||
import type { Match3DWorkSummary } from '../../../packages/shared/src/contracts/match3dWorks';
|
||||
import type { PuzzleWorkSummary } from '../../../packages/shared/src/contracts/puzzleWorkSummary';
|
||||
import type { SquareHoleWorkSummary } from '../../../packages/shared/src/contracts/squareHoleWorks';
|
||||
import type { CustomWorldLibraryEntry } from '../../../packages/shared/src/contracts/runtime';
|
||||
import { buildPublicWorkStagePath } from '../../routing/appPageRoutes';
|
||||
import {
|
||||
buildBigFishPublicWorkCode,
|
||||
buildMatch3DPublicWorkCode,
|
||||
buildPuzzlePublicWorkCode,
|
||||
buildSquareHolePublicWorkCode,
|
||||
} from '../../services/publicWorkCode';
|
||||
import type { CustomWorldProfile } from '../../types';
|
||||
|
||||
export type CreationWorkShelfKind = 'rpg' | 'big-fish' | 'match3d' | 'puzzle';
|
||||
export type CreationWorkShelfKind =
|
||||
| 'rpg'
|
||||
| 'big-fish'
|
||||
| 'match3d'
|
||||
| 'square-hole'
|
||||
| 'puzzle';
|
||||
export type CreationWorkShelfStatus = 'draft' | 'published';
|
||||
|
||||
export type CreationWorkShelfBadgeTone = 'warm' | 'success' | 'neutral';
|
||||
@@ -56,6 +63,10 @@ export type CreationWorkShelfSource =
|
||||
kind: 'match3d';
|
||||
item: Match3DWorkSummary;
|
||||
}
|
||||
| {
|
||||
kind: 'square-hole';
|
||||
item: SquareHoleWorkSummary;
|
||||
}
|
||||
| {
|
||||
kind: 'puzzle';
|
||||
item: PuzzleWorkSummary;
|
||||
@@ -87,10 +98,12 @@ export function buildCreationWorkShelfItems(params: {
|
||||
rpgLibraryEntries?: CustomWorldLibraryEntry<CustomWorldProfile>[];
|
||||
bigFishItems: BigFishWorkSummary[];
|
||||
match3dItems?: Match3DWorkSummary[];
|
||||
squareHoleItems?: SquareHoleWorkSummary[];
|
||||
puzzleItems: PuzzleWorkSummary[];
|
||||
canDeleteRpg?: boolean;
|
||||
canDeleteBigFish?: boolean;
|
||||
canDeleteMatch3D?: boolean;
|
||||
canDeleteSquareHole?: boolean;
|
||||
canDeletePuzzle?: boolean;
|
||||
}) {
|
||||
const {
|
||||
@@ -98,10 +111,12 @@ export function buildCreationWorkShelfItems(params: {
|
||||
rpgLibraryEntries = [],
|
||||
bigFishItems,
|
||||
match3dItems = [],
|
||||
squareHoleItems = [],
|
||||
puzzleItems,
|
||||
canDeleteRpg = false,
|
||||
canDeleteBigFish = false,
|
||||
canDeleteMatch3D = false,
|
||||
canDeleteSquareHole = false,
|
||||
canDeletePuzzle = false,
|
||||
} = params;
|
||||
|
||||
@@ -115,6 +130,9 @@ export function buildCreationWorkShelfItems(params: {
|
||||
...match3dItems.map((item) =>
|
||||
mapMatch3DWorkToShelfItem(item, canDeleteMatch3D),
|
||||
),
|
||||
...squareHoleItems.map((item) =>
|
||||
mapSquareHoleWorkToShelfItem(item, canDeleteSquareHole),
|
||||
),
|
||||
...puzzleItems.map((item) =>
|
||||
mapPuzzleWorkToShelfItem(item, canDeletePuzzle),
|
||||
),
|
||||
@@ -319,6 +337,50 @@ function mapPuzzleWorkToShelfItem(
|
||||
};
|
||||
}
|
||||
|
||||
function mapSquareHoleWorkToShelfItem(
|
||||
item: SquareHoleWorkSummary,
|
||||
canDelete: boolean,
|
||||
): CreationWorkShelfItem {
|
||||
const status = item.publicationStatus === 'published' ? 'published' : 'draft';
|
||||
const publicWorkCode =
|
||||
status === 'published'
|
||||
? buildSquareHolePublicWorkCode(item.profileId)
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: item.workId,
|
||||
kind: 'square-hole',
|
||||
status,
|
||||
title: item.gameName,
|
||||
summary: item.summary,
|
||||
updatedAt: item.updatedAt,
|
||||
coverImageSrc: item.coverImageSrc ?? null,
|
||||
coverRenderMode: 'image',
|
||||
coverCharacterImageSrcs: [],
|
||||
publicWorkCode,
|
||||
sharePath:
|
||||
publicWorkCode && status === 'published'
|
||||
? buildPublicWorkStagePath('work-detail', publicWorkCode)
|
||||
: null,
|
||||
openActionLabel: status === 'published' ? '查看详情' : '继续创作',
|
||||
canDelete,
|
||||
canShare: status === 'published' && Boolean(publicWorkCode),
|
||||
badges: [
|
||||
buildStatusBadge(status),
|
||||
{ id: 'type', label: '方洞', tone: 'neutral' },
|
||||
],
|
||||
metrics:
|
||||
status === 'published'
|
||||
? buildPublishedMetrics({
|
||||
playCount: item.playCount,
|
||||
remixCount: 0,
|
||||
likeCount: 0,
|
||||
})
|
||||
: [],
|
||||
source: { kind: 'square-hole', item },
|
||||
};
|
||||
}
|
||||
|
||||
function buildPublishedMetrics(params: {
|
||||
playCount?: number | null;
|
||||
remixCount?: number | null;
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface PlatformEntryCreationTypeModalProps {
|
||||
onSelectRpg: () => void;
|
||||
onSelectBigFish: () => void;
|
||||
onSelectMatch3D: () => void;
|
||||
onSelectSquareHole: () => void;
|
||||
onSelectPuzzle: () => void;
|
||||
}
|
||||
|
||||
@@ -74,6 +75,7 @@ export function PlatformEntryCreationTypeModal({
|
||||
onSelectRpg,
|
||||
onSelectBigFish,
|
||||
onSelectMatch3D,
|
||||
onSelectSquareHole,
|
||||
onSelectPuzzle,
|
||||
}: PlatformEntryCreationTypeModalProps) {
|
||||
if (!isOpen) {
|
||||
@@ -93,7 +95,7 @@ export function PlatformEntryCreationTypeModal({
|
||||
closeDisabled={isBusy}
|
||||
size="lg"
|
||||
>
|
||||
<div className="grid gap-3 sm:grid-cols-5">
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{visibleCreationTypes.map((item) => (
|
||||
<CreationTypeCard
|
||||
key={item.id}
|
||||
@@ -109,6 +111,9 @@ export function PlatformEntryCreationTypeModal({
|
||||
if (item.id === 'match3d') {
|
||||
onSelectMatch3D();
|
||||
}
|
||||
if (item.id === 'square-hole') {
|
||||
onSelectSquareHole();
|
||||
}
|
||||
if (item.id === 'puzzle') {
|
||||
onSelectPuzzle();
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -60,6 +60,9 @@ function getSourceLabel(entry: PlatformPublicGalleryCard) {
|
||||
if ('sourceType' in entry && entry.sourceType === 'match3d') {
|
||||
return '抓大鹅';
|
||||
}
|
||||
if ('sourceType' in entry && entry.sourceType === 'square-hole') {
|
||||
return '方洞挑战';
|
||||
}
|
||||
return 'RPG';
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ test('new work entry config controls visibility and open order', () => {
|
||||
'rpg',
|
||||
'puzzle',
|
||||
'match3d',
|
||||
'square-hole',
|
||||
'airp',
|
||||
'visual-novel',
|
||||
]);
|
||||
|
||||
@@ -25,6 +25,9 @@ export type SelectionStage =
|
||||
| 'match3d-agent-workspace'
|
||||
| 'match3d-result'
|
||||
| 'match3d-runtime'
|
||||
| 'square-hole-agent-workspace'
|
||||
| 'square-hole-result'
|
||||
| 'square-hole-runtime'
|
||||
| 'puzzle-agent-workspace'
|
||||
| 'puzzle-generating'
|
||||
| 'puzzle-result'
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/* @vitest-environment jsdom */
|
||||
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import { useEffect } from 'react';
|
||||
import { expect, test, vi } from 'vitest';
|
||||
|
||||
import { usePlatformCreationAgentFlowController } from './usePlatformCreationAgentFlowController';
|
||||
|
||||
type TestSession = {
|
||||
sessionId: string;
|
||||
messages: Array<{
|
||||
id: string;
|
||||
role: string;
|
||||
kind?: string;
|
||||
text: string;
|
||||
createdAt?: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
type TestMessagePayload = {
|
||||
clientMessageId: string;
|
||||
text: string;
|
||||
};
|
||||
|
||||
function TestHarness({
|
||||
streamMessage,
|
||||
}: {
|
||||
streamMessage: (
|
||||
sessionId: string,
|
||||
payload: TestMessagePayload,
|
||||
options?: { onUpdate?: (text: string) => void },
|
||||
) => Promise<TestSession>;
|
||||
}) {
|
||||
const flow = usePlatformCreationAgentFlowController<
|
||||
TestSession,
|
||||
Record<string, never>,
|
||||
{ session: TestSession },
|
||||
TestMessagePayload,
|
||||
{ action: string },
|
||||
{ session: TestSession }
|
||||
>({
|
||||
client: {
|
||||
createSession: async () => ({
|
||||
session: {
|
||||
sessionId: 'session-1',
|
||||
messages: [],
|
||||
},
|
||||
}),
|
||||
getSession: async () => ({
|
||||
session: {
|
||||
sessionId: 'session-1',
|
||||
messages: [],
|
||||
},
|
||||
}),
|
||||
streamMessage,
|
||||
executeAction: async () => ({
|
||||
session: {
|
||||
sessionId: 'session-1',
|
||||
messages: [],
|
||||
},
|
||||
}),
|
||||
selectSession: (response) => response.session,
|
||||
},
|
||||
createPayload: {},
|
||||
workspaceStage: 'match3d-agent-workspace',
|
||||
resultStage: 'match3d-result',
|
||||
platformStage: 'platform',
|
||||
isCompileAction: () => false,
|
||||
resolveErrorMessage: (error, fallback) =>
|
||||
error instanceof Error ? error.message : fallback,
|
||||
errorMessages: {
|
||||
open: '打开失败',
|
||||
restoreMissingSession: '缺少会话',
|
||||
restore: '恢复失败',
|
||||
submit: '发送失败',
|
||||
execute: '执行失败',
|
||||
},
|
||||
enterCreateTab: () => {},
|
||||
setSelectionStage: () => {},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
void flow.openWorkspace({});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void flow.submitMessage({
|
||||
clientMessageId: 'client-message-1',
|
||||
text: '做一个办公室文具方洞挑战',
|
||||
});
|
||||
}}
|
||||
>
|
||||
发送
|
||||
</button>
|
||||
<div data-testid="messages">
|
||||
{flow.session?.messages.map((message) => (
|
||||
<div key={message.id}>{`${message.role}:${message.kind}:${message.text}`}</div>
|
||||
))}
|
||||
</div>
|
||||
{flow.error ? <div>{flow.error}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
test('creation agent flow preserves streamed assistant text when stream fails', async () => {
|
||||
const streamMessage = vi.fn(async (_sessionId, _payload, options) => {
|
||||
options?.onUpdate?.('先把方洞万能的反差定住。');
|
||||
throw new Error('方洞挑战聊天生成失败:LLM 请求超时');
|
||||
});
|
||||
|
||||
render(<TestHarness streamMessage={streamMessage} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: '发送' })).toBeTruthy();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
screen.getByRole('button', { name: '发送' }).click();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText('方洞挑战聊天生成失败:LLM 请求超时'),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('messages').textContent).toContain(
|
||||
'user:chat:做一个办公室文具方洞挑战',
|
||||
);
|
||||
expect(screen.getByTestId('messages').textContent).toContain(
|
||||
'assistant:warning:先把方洞万能的反差定住。',
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
|
||||
import type { TextStreamOptions } from '../../services/aiTypes';
|
||||
import type { SelectionStage } from './platformEntryTypes';
|
||||
@@ -104,6 +104,16 @@ function buildOptimisticMessage<TMessagePayload extends CreationAgentMessageLike
|
||||
};
|
||||
}
|
||||
|
||||
function buildInterruptedAssistantMessage(text: string) {
|
||||
return {
|
||||
id: `assistant-interrupted-${Date.now().toString(36)}`,
|
||||
role: 'assistant',
|
||||
kind: 'warning',
|
||||
text: text.trim(),
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 轻量作品 Agent 创作流程的通用前端控制器。
|
||||
* 这里只处理跨玩法一致的会话、流式消息、忙碌态与草稿恢复,玩法结果页和运行态动作留给外层。
|
||||
@@ -130,6 +140,18 @@ export function usePlatformCreationAgentFlowController<
|
||||
const [isBusy, setIsBusy] = useState(false);
|
||||
const [streamingReplyText, setStreamingReplyText] = useState('');
|
||||
const [isStreamingReply, setIsStreamingReply] = useState(false);
|
||||
const latestStreamingReplyTextRef = useRef('');
|
||||
|
||||
const updateStreamingReplyText = useCallback((text: string) => {
|
||||
latestStreamingReplyTextRef.current = text;
|
||||
setStreamingReplyText(text);
|
||||
}, []);
|
||||
|
||||
const resetStreamingReply = useCallback(() => {
|
||||
latestStreamingReplyTextRef.current = '';
|
||||
setStreamingReplyText('');
|
||||
setIsStreamingReply(false);
|
||||
}, []);
|
||||
|
||||
const openWorkspace = useCallback(async (createPayload?: TCreatePayload) => {
|
||||
if (isBusy) {
|
||||
@@ -138,8 +160,7 @@ export function usePlatformCreationAgentFlowController<
|
||||
|
||||
setIsBusy(true);
|
||||
setError(null);
|
||||
setStreamingReplyText('');
|
||||
setIsStreamingReply(false);
|
||||
resetStreamingReply();
|
||||
|
||||
try {
|
||||
const response = await options.client.createSession(
|
||||
@@ -159,7 +180,7 @@ export function usePlatformCreationAgentFlowController<
|
||||
} finally {
|
||||
setIsBusy(false);
|
||||
}
|
||||
}, [isBusy, options]);
|
||||
}, [isBusy, options, resetStreamingReply]);
|
||||
|
||||
const restoreDraft = useCallback(
|
||||
async (sessionId: string | null | undefined) => {
|
||||
@@ -171,8 +192,7 @@ export function usePlatformCreationAgentFlowController<
|
||||
|
||||
setIsBusy(true);
|
||||
setError(null);
|
||||
setStreamingReplyText('');
|
||||
setIsStreamingReply(false);
|
||||
resetStreamingReply();
|
||||
|
||||
try {
|
||||
const response = await options.client.getSession(normalizedSessionId);
|
||||
@@ -194,7 +214,7 @@ export function usePlatformCreationAgentFlowController<
|
||||
setIsBusy(false);
|
||||
}
|
||||
},
|
||||
[options],
|
||||
[options, resetStreamingReply],
|
||||
);
|
||||
|
||||
const submitMessage = useCallback(
|
||||
@@ -206,7 +226,7 @@ export function usePlatformCreationAgentFlowController<
|
||||
const optimisticMessage = buildOptimisticMessage(payload);
|
||||
|
||||
setError(null);
|
||||
setStreamingReplyText('');
|
||||
updateStreamingReplyText('');
|
||||
setIsStreamingReply(true);
|
||||
setSession((current) =>
|
||||
current
|
||||
@@ -223,12 +243,28 @@ export function usePlatformCreationAgentFlowController<
|
||||
session.sessionId,
|
||||
payload,
|
||||
{
|
||||
onUpdate: setStreamingReplyText,
|
||||
onUpdate: updateStreamingReplyText,
|
||||
},
|
||||
);
|
||||
setSession(nextSession);
|
||||
setStreamingReplyText('');
|
||||
updateStreamingReplyText('');
|
||||
} catch (caughtError) {
|
||||
const interruptedReplyText =
|
||||
latestStreamingReplyTextRef.current.trim();
|
||||
// 上游流可能在已经吐出可读回复后才失败;把这段回复落进本地消息列表,避免 UI 收尾时突然消失。
|
||||
if (interruptedReplyText) {
|
||||
const interruptedMessage =
|
||||
buildInterruptedAssistantMessage(interruptedReplyText);
|
||||
setSession((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
messages: [...current.messages, interruptedMessage],
|
||||
updatedAt: interruptedMessage.createdAt,
|
||||
}
|
||||
: current,
|
||||
);
|
||||
}
|
||||
setError(
|
||||
options.resolveErrorMessage(caughtError, options.errorMessages.submit),
|
||||
);
|
||||
@@ -236,7 +272,7 @@ export function usePlatformCreationAgentFlowController<
|
||||
setIsStreamingReply(false);
|
||||
}
|
||||
},
|
||||
[isStreamingReply, options, session],
|
||||
[isStreamingReply, options, session, updateStreamingReplyText],
|
||||
);
|
||||
|
||||
const executeAction = useCallback(
|
||||
@@ -284,17 +320,15 @@ export function usePlatformCreationAgentFlowController<
|
||||
|
||||
const leaveFlow = useCallback(() => {
|
||||
setError(null);
|
||||
setStreamingReplyText('');
|
||||
setIsStreamingReply(false);
|
||||
resetStreamingReply();
|
||||
options.enterCreateTab();
|
||||
options.setSelectionStage(options.platformStage);
|
||||
}, [options]);
|
||||
}, [options, resetStreamingReply]);
|
||||
|
||||
const resetTransientState = useCallback(() => {
|
||||
setError(null);
|
||||
setStreamingReplyText('');
|
||||
setIsStreamingReply(false);
|
||||
}, []);
|
||||
resetStreamingReply();
|
||||
}, [resetStreamingReply]);
|
||||
|
||||
return {
|
||||
session,
|
||||
|
||||
@@ -82,6 +82,7 @@ import {
|
||||
isBigFishGalleryEntry,
|
||||
isMatch3DGalleryEntry,
|
||||
isPuzzleGalleryEntry,
|
||||
isSquareHoleGalleryEntry,
|
||||
type PlatformPublicGalleryCard,
|
||||
type PlatformWorldCardLike,
|
||||
resolvePlatformWorldCoverImage,
|
||||
@@ -1134,7 +1135,9 @@ function buildPublicGalleryCardKey(entry: PlatformPublicGalleryCard) {
|
||||
? 'puzzle'
|
||||
: isMatch3DGalleryEntry(entry)
|
||||
? 'match3d'
|
||||
: 'rpg';
|
||||
: isSquareHoleGalleryEntry(entry)
|
||||
? 'square-hole'
|
||||
: 'rpg';
|
||||
return `${kind}:${entry.ownerUserId}:${entry.profileId}`;
|
||||
}
|
||||
|
||||
@@ -1242,7 +1245,9 @@ function describePublicGalleryCardKind(entry: PlatformPublicGalleryCard) {
|
||||
? '拼图'
|
||||
: isMatch3DGalleryEntry(entry)
|
||||
? '抓鹅'
|
||||
: describePlatformThemeLabel(entry.themeMode);
|
||||
: isSquareHoleGalleryEntry(entry)
|
||||
? '方洞'
|
||||
: describePlatformThemeLabel(entry.themeMode);
|
||||
return formatPlatformWorkDisplayTag(kind);
|
||||
}
|
||||
|
||||
@@ -1514,6 +1519,12 @@ function formatPlayedWorkType(value: string | null | undefined) {
|
||||
if (normalizedValue === 'puzzle') {
|
||||
return '拼图';
|
||||
}
|
||||
if (normalizedValue === 'match3d' || normalizedValue === 'match_3d') {
|
||||
return '抓鹅';
|
||||
}
|
||||
if (normalizedValue === 'square-hole' || normalizedValue === 'square_hole') {
|
||||
return '方洞';
|
||||
}
|
||||
if (normalizedValue === 'big_fish' || normalizedValue === 'big-fish') {
|
||||
return '大鱼';
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BigFishWorkSummary } from '../../../packages/shared/src/contracts/
|
||||
import type { Match3DWorkSummary } from '../../../packages/shared/src/contracts/match3dWorks';
|
||||
import type { PuzzleDraftLevel } from '../../../packages/shared/src/contracts/puzzleAgentDraft';
|
||||
import type { PuzzleWorkSummary } from '../../../packages/shared/src/contracts/puzzleWorkSummary';
|
||||
import type { SquareHoleWorkSummary } from '../../../packages/shared/src/contracts/squareHoleWorks';
|
||||
import type {
|
||||
CustomWorldGalleryCard,
|
||||
CustomWorldLibraryEntry,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
buildBigFishPublicWorkCode,
|
||||
buildMatch3DPublicWorkCode,
|
||||
buildPuzzlePublicWorkCode,
|
||||
buildSquareHolePublicWorkCode,
|
||||
} from '../../services/publicWorkCode';
|
||||
import type { CustomWorldProfile } from '../../types';
|
||||
|
||||
@@ -23,6 +25,7 @@ export type PlatformWorldCardLike =
|
||||
| CustomWorldLibraryEntry<CustomWorldProfile>
|
||||
| PlatformBigFishGalleryCard
|
||||
| PlatformMatch3DGalleryCard
|
||||
| PlatformSquareHoleGalleryCard
|
||||
| PlatformPuzzleGalleryCard;
|
||||
|
||||
export type PlatformPuzzleGalleryCard = {
|
||||
@@ -97,10 +100,33 @@ export type PlatformMatch3DGalleryCard = {
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type PlatformSquareHoleGalleryCard = {
|
||||
sourceType: 'square-hole';
|
||||
workId: string;
|
||||
profileId: string;
|
||||
sourceSessionId?: string | null;
|
||||
publicWorkCode: string;
|
||||
ownerUserId: string;
|
||||
authorDisplayName: string;
|
||||
worldName: string;
|
||||
subtitle: string;
|
||||
summaryText: string;
|
||||
coverImageSrc: string | null;
|
||||
themeTags: string[];
|
||||
playCount?: number;
|
||||
remixCount?: number;
|
||||
likeCount?: number;
|
||||
recentPlayCount7d?: number;
|
||||
visibility: 'published';
|
||||
publishedAt: string | null;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type PlatformPublicGalleryCard =
|
||||
| CustomWorldGalleryCard
|
||||
| PlatformBigFishGalleryCard
|
||||
| PlatformMatch3DGalleryCard
|
||||
| PlatformSquareHoleGalleryCard
|
||||
| PlatformPuzzleGalleryCard;
|
||||
|
||||
export function isLibraryWorldEntry(
|
||||
@@ -127,6 +153,12 @@ export function isMatch3DGalleryEntry(
|
||||
return 'sourceType' in entry && entry.sourceType === 'match3d';
|
||||
}
|
||||
|
||||
export function isSquareHoleGalleryEntry(
|
||||
entry: PlatformWorldCardLike,
|
||||
): entry is PlatformSquareHoleGalleryCard {
|
||||
return 'sourceType' in entry && entry.sourceType === 'square-hole';
|
||||
}
|
||||
|
||||
export function mapPuzzleWorkToPlatformGalleryCard(
|
||||
work: PuzzleWorkSummary,
|
||||
): PlatformPuzzleGalleryCard {
|
||||
@@ -180,6 +212,33 @@ export function mapMatch3DWorkToPlatformGalleryCard(
|
||||
};
|
||||
}
|
||||
|
||||
export function mapSquareHoleWorkToPlatformGalleryCard(
|
||||
work: SquareHoleWorkSummary,
|
||||
): PlatformSquareHoleGalleryCard {
|
||||
return {
|
||||
sourceType: 'square-hole',
|
||||
workId: work.workId,
|
||||
profileId: work.profileId,
|
||||
sourceSessionId: work.sourceSessionId ?? null,
|
||||
publicWorkCode: buildSquareHolePublicWorkCode(work.profileId),
|
||||
ownerUserId: work.ownerUserId,
|
||||
authorDisplayName: '玩家',
|
||||
worldName: work.gameName,
|
||||
subtitle: '反直觉形状分拣',
|
||||
summaryText: work.summary,
|
||||
coverImageSrc: work.coverImageSrc ?? null,
|
||||
themeTags:
|
||||
work.tags.length > 0 ? work.tags : [work.themeText, '方洞挑战'],
|
||||
playCount: work.playCount ?? 0,
|
||||
remixCount: 0,
|
||||
likeCount: 0,
|
||||
recentPlayCount7d: 0,
|
||||
visibility: 'published',
|
||||
publishedAt: work.publishedAt ?? null,
|
||||
updatedAt: work.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function mapBigFishWorkToPlatformGalleryCard(
|
||||
work: BigFishWorkSummary,
|
||||
): PlatformBigFishGalleryCard {
|
||||
@@ -371,6 +430,12 @@ export function buildPlatformWorldTags(entry: PlatformWorldCardLike) {
|
||||
return entry.themeTags.length > 0 ? entry.themeTags.slice(0, 3) : ['抓大鹅'];
|
||||
}
|
||||
|
||||
if (isSquareHoleGalleryEntry(entry)) {
|
||||
return entry.themeTags.length > 0
|
||||
? entry.themeTags.slice(0, 3)
|
||||
: ['方洞'];
|
||||
}
|
||||
|
||||
if (!isLibraryWorldEntry(entry)) {
|
||||
return [
|
||||
describePlatformThemeLabel(entry.themeMode),
|
||||
@@ -449,6 +514,10 @@ export function resolvePlatformPublicWorkCode(
|
||||
return entry.publicWorkCode;
|
||||
}
|
||||
|
||||
if (isSquareHoleGalleryEntry(entry)) {
|
||||
return entry.publicWorkCode;
|
||||
}
|
||||
|
||||
return entry.publicWorkCode;
|
||||
}
|
||||
|
||||
|
||||
149
src/components/square-hole-creation/SquareHoleAgentWorkspace.tsx
Normal file
149
src/components/square-hole-creation/SquareHoleAgentWorkspace.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
import type {
|
||||
ExecuteSquareHoleActionRequest,
|
||||
SendSquareHoleMessageRequest,
|
||||
SquareHoleAnchorItemResponse,
|
||||
SquareHoleSessionSnapshot,
|
||||
} from '../../../packages/shared/src/contracts/squareHoleAgent';
|
||||
import {
|
||||
buildCreationAgentChatMessage,
|
||||
createCreationAgentChatQuickActions,
|
||||
createCreationAgentClientMessageId,
|
||||
resolveCreationAgentQuickActionMessage,
|
||||
} from '../../services/creation-agent';
|
||||
import {
|
||||
type CreationAgentAnchorView,
|
||||
type CreationAgentSessionView,
|
||||
type CreationAgentTheme,
|
||||
CreationAgentWorkspace,
|
||||
} from '../creation-agent';
|
||||
|
||||
type SquareHoleAgentWorkspaceProps = {
|
||||
session: SquareHoleSessionSnapshot | null;
|
||||
streamingReplyText?: string;
|
||||
isStreamingReply?: boolean;
|
||||
isBusy?: boolean;
|
||||
error?: string | null;
|
||||
onBack: () => void;
|
||||
onSubmitMessage: (payload: SendSquareHoleMessageRequest) => void;
|
||||
onExecuteAction: (payload: ExecuteSquareHoleActionRequest) => void;
|
||||
};
|
||||
|
||||
const SQUARE_HOLE_AGENT_THEME: CreationAgentTheme = {
|
||||
accentTextClass: 'text-sky-100/86',
|
||||
accentBgClass: 'bg-cyan-200',
|
||||
accentButtonClass: 'bg-cyan-200 shadow-slate-950/20',
|
||||
userBubbleClass: 'bg-slate-950 text-white',
|
||||
heroClass:
|
||||
'border border-cyan-100/18 bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.28),transparent_34%),radial-gradient(circle_at_bottom_right,rgba(248,113,113,0.2),transparent_32%),linear-gradient(135deg,rgba(15,23,42,0.96),rgba(20,83,45,0.92))]',
|
||||
anchorGridClass: 'grid gap-2 sm:grid-cols-4',
|
||||
};
|
||||
|
||||
const SQUARE_HOLE_QUICK_ACTIONS = [
|
||||
...createCreationAgentChatQuickActions(),
|
||||
{
|
||||
key: 'square-hole-auto-config',
|
||||
label: '自动配置',
|
||||
},
|
||||
];
|
||||
|
||||
function mapSquareHoleAnchor(
|
||||
anchor: SquareHoleAnchorItemResponse,
|
||||
): CreationAgentAnchorView {
|
||||
return {
|
||||
key: anchor.key,
|
||||
label: anchor.label,
|
||||
value: anchor.value,
|
||||
status: anchor.status,
|
||||
};
|
||||
}
|
||||
|
||||
function mapSquareHoleSession(
|
||||
session: SquareHoleSessionSnapshot,
|
||||
): CreationAgentSessionView {
|
||||
// 中文注释:方洞工作台只展示共创对话和四个创作锚点,正式运行规则由后端运行态快照裁决。
|
||||
const chatMessages = session.messages.filter(
|
||||
(message) =>
|
||||
message.kind === 'chat' ||
|
||||
message.kind === 'summary' ||
|
||||
message.kind === 'warning',
|
||||
);
|
||||
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
title: null,
|
||||
assistantSummary: null,
|
||||
currentTurn: session.currentTurn,
|
||||
progressPercent: session.progressPercent,
|
||||
anchors: [
|
||||
session.anchorPack.theme,
|
||||
session.anchorPack.twistRule,
|
||||
session.anchorPack.shapeCount,
|
||||
session.anchorPack.difficulty,
|
||||
].map(mapSquareHoleAnchor),
|
||||
messages: chatMessages,
|
||||
recommendedReplies: [],
|
||||
};
|
||||
}
|
||||
|
||||
function buildSquareHoleChatPayload({
|
||||
text,
|
||||
quickFillRequested = false,
|
||||
}: {
|
||||
text: string;
|
||||
quickFillRequested?: boolean;
|
||||
}) {
|
||||
return buildCreationAgentChatMessage({
|
||||
clientMessageId: createCreationAgentClientMessageId('square-hole'),
|
||||
text,
|
||||
quickFillRequested,
|
||||
});
|
||||
}
|
||||
|
||||
export function SquareHoleAgentWorkspace({
|
||||
session,
|
||||
streamingReplyText = '',
|
||||
isStreamingReply = false,
|
||||
isBusy = false,
|
||||
error = null,
|
||||
onBack,
|
||||
onSubmitMessage,
|
||||
onExecuteAction,
|
||||
}: SquareHoleAgentWorkspaceProps) {
|
||||
return (
|
||||
<CreationAgentWorkspace
|
||||
session={session ? mapSquareHoleSession(session) : null}
|
||||
theme={SQUARE_HOLE_AGENT_THEME}
|
||||
loadingText="正在准备方洞挑战共创工作区..."
|
||||
composerPlaceholder="题材、反差规则、形状数量、难度..."
|
||||
primaryActionLabel="生成结果页"
|
||||
streamingReplyText={streamingReplyText}
|
||||
isStreamingReply={isStreamingReply}
|
||||
isBusy={isBusy}
|
||||
error={error}
|
||||
quickActions={SQUARE_HOLE_QUICK_ACTIONS}
|
||||
onBack={onBack}
|
||||
onSubmitText={(text) => {
|
||||
onSubmitMessage(buildSquareHoleChatPayload({ text }));
|
||||
}}
|
||||
onPrimaryAction={() => {
|
||||
onExecuteAction({ action: 'square_hole_compile_draft' });
|
||||
}}
|
||||
onQuickAction={(action) => {
|
||||
const quickActionMessage =
|
||||
action.key === 'square-hole-auto-config'
|
||||
? {
|
||||
text: '自动配置',
|
||||
quickFillRequested: true,
|
||||
}
|
||||
: resolveCreationAgentQuickActionMessage(
|
||||
action.key,
|
||||
'请总结一下当前方洞挑战设定。',
|
||||
);
|
||||
|
||||
onSubmitMessage(buildSquareHoleChatPayload(quickActionMessage));
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default SquareHoleAgentWorkspace;
|
||||
1
src/components/square-hole-creation/index.ts
Normal file
1
src/components/square-hole-creation/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { SquareHoleAgentWorkspace } from './SquareHoleAgentWorkspace';
|
||||
580
src/components/square-hole-result/SquareHoleResultView.tsx
Normal file
580
src/components/square-hole-result/SquareHoleResultView.tsx
Normal file
@@ -0,0 +1,580 @@
|
||||
import {
|
||||
ArrowLeft,
|
||||
CheckCircle2,
|
||||
ImagePlus,
|
||||
Loader2,
|
||||
Play,
|
||||
Send,
|
||||
} from 'lucide-react';
|
||||
import { type ChangeEvent, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import type { SquareHoleResultDraft } from '../../../packages/shared/src/contracts/squareHoleAgent';
|
||||
import type {
|
||||
PutSquareHoleWorkRequest,
|
||||
SquareHoleWorkProfile,
|
||||
} from '../../../packages/shared/src/contracts/squareHoleWorks';
|
||||
import {
|
||||
publishSquareHoleWork,
|
||||
updateSquareHoleWork,
|
||||
} from '../../services/square-hole-works';
|
||||
import { ResolvedAssetImage } from '../ResolvedAssetImage';
|
||||
|
||||
type SquareHoleResultViewProps = {
|
||||
profile: SquareHoleWorkProfile;
|
||||
draft?: SquareHoleResultDraft | null;
|
||||
isBusy?: boolean;
|
||||
error?: string | null;
|
||||
onBack: () => void;
|
||||
onSaved?: (profile: SquareHoleWorkProfile) => void;
|
||||
onPublished?: (profile: SquareHoleWorkProfile) => void;
|
||||
onStartTestRun: (profile: SquareHoleWorkProfile) => void;
|
||||
};
|
||||
|
||||
type SquareHoleAutoSaveState = 'idle' | 'saving' | 'saved' | 'error';
|
||||
|
||||
type SquareHoleResultEditState = {
|
||||
gameName: string;
|
||||
summary: string;
|
||||
tagsText: string;
|
||||
coverImageSrc: string;
|
||||
themeText: string;
|
||||
twistRule: string;
|
||||
shapeCountText: string;
|
||||
difficultyText: string;
|
||||
};
|
||||
|
||||
const SQUARE_HOLE_AUTOSAVE_DEBOUNCE_MS = 600;
|
||||
|
||||
function normalizeTags(value: string) {
|
||||
return [
|
||||
...new Set(
|
||||
value
|
||||
.split(/[\n,,、]/u)
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
function normalizeShapeCount(value: string) {
|
||||
const parsed = Number.parseInt(value.trim(), 10);
|
||||
return Number.isFinite(parsed) && parsed >= 6 && parsed <= 24
|
||||
? parsed
|
||||
: null;
|
||||
}
|
||||
|
||||
function normalizeDifficulty(value: string) {
|
||||
const parsed = Number.parseInt(value.trim(), 10);
|
||||
return Number.isFinite(parsed) && parsed >= 1 && parsed <= 10
|
||||
? parsed
|
||||
: null;
|
||||
}
|
||||
|
||||
function createEditState(
|
||||
profile: SquareHoleWorkProfile,
|
||||
): SquareHoleResultEditState {
|
||||
return {
|
||||
gameName: profile.gameName,
|
||||
summary: profile.summary,
|
||||
tagsText: profile.tags.join(','),
|
||||
coverImageSrc: profile.coverImageSrc?.trim() || '',
|
||||
themeText: profile.themeText,
|
||||
twistRule: profile.twistRule,
|
||||
shapeCountText: String(profile.shapeCount),
|
||||
difficultyText: String(profile.difficulty),
|
||||
};
|
||||
}
|
||||
|
||||
function buildSavePayload(
|
||||
editState: SquareHoleResultEditState,
|
||||
): PutSquareHoleWorkRequest | null {
|
||||
const shapeCount = normalizeShapeCount(editState.shapeCountText);
|
||||
const difficulty = normalizeDifficulty(editState.difficultyText);
|
||||
const gameName = editState.gameName.trim();
|
||||
const themeText = editState.themeText.trim();
|
||||
const twistRule = editState.twistRule.trim();
|
||||
const summary = editState.summary.trim();
|
||||
const tags = normalizeTags(editState.tagsText);
|
||||
|
||||
if (
|
||||
!gameName ||
|
||||
!themeText ||
|
||||
!twistRule ||
|
||||
!summary ||
|
||||
tags.length === 0 ||
|
||||
!shapeCount ||
|
||||
!difficulty
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
gameName,
|
||||
themeText,
|
||||
twistRule,
|
||||
summary,
|
||||
tags,
|
||||
coverImageSrc: editState.coverImageSrc.trim() || null,
|
||||
shapeCount,
|
||||
difficulty,
|
||||
};
|
||||
}
|
||||
|
||||
function buildPublishBlockers(editState: SquareHoleResultEditState) {
|
||||
const blockers = [
|
||||
...(editState.gameName.trim() ? [] : ['游戏名称不能为空。']),
|
||||
...(editState.themeText.trim() ? [] : ['题材主题不能为空。']),
|
||||
...(editState.twistRule.trim() ? [] : ['反差规则不能为空。']),
|
||||
...(editState.summary.trim() ? [] : ['简介不能为空。']),
|
||||
...(normalizeTags(editState.tagsText).length > 0
|
||||
? []
|
||||
: ['至少需要 1 个标签。']),
|
||||
...(normalizeShapeCount(editState.shapeCountText)
|
||||
? []
|
||||
: ['形状数量需要在 6 到 24 之间。']),
|
||||
...(normalizeDifficulty(editState.difficultyText)
|
||||
? []
|
||||
: ['难度必须为 1 到 10。']),
|
||||
];
|
||||
|
||||
return [...new Set(blockers)];
|
||||
}
|
||||
|
||||
function readImageAsDataUrl(file: File) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
if (!file.type.startsWith('image/')) {
|
||||
reject(new Error('请选择图片文件。'));
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onerror = () => reject(new Error('封面图读取失败,请重试。'));
|
||||
reader.onload = () => resolve(String(reader.result || ''));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
function buildPlayableProfile(
|
||||
profile: SquareHoleWorkProfile,
|
||||
editState: SquareHoleResultEditState,
|
||||
) {
|
||||
const payload = buildSavePayload(editState);
|
||||
if (!payload) {
|
||||
return profile;
|
||||
}
|
||||
|
||||
return {
|
||||
...profile,
|
||||
gameName: payload.gameName,
|
||||
themeText: payload.themeText ?? profile.themeText,
|
||||
twistRule: payload.twistRule,
|
||||
summary: payload.summary,
|
||||
tags: payload.tags,
|
||||
coverImageSrc: payload.coverImageSrc,
|
||||
shapeCount: payload.shapeCount,
|
||||
difficulty: payload.difficulty,
|
||||
};
|
||||
}
|
||||
|
||||
function SquareHoleResultHeader({
|
||||
autoSaveState,
|
||||
isBusy,
|
||||
onBack,
|
||||
}: {
|
||||
autoSaveState: SquareHoleAutoSaveState;
|
||||
isBusy: boolean;
|
||||
onBack: () => void;
|
||||
}) {
|
||||
const badge =
|
||||
autoSaveState === 'saving' ? (
|
||||
<div className="platform-pill platform-pill--warm px-3 py-1 text-[11px]">
|
||||
保存中
|
||||
</div>
|
||||
) : autoSaveState === 'saved' ? (
|
||||
<div className="platform-pill platform-pill--success px-3 py-1 text-[11px]">
|
||||
已自动保存
|
||||
</div>
|
||||
) : autoSaveState === 'error' ? (
|
||||
<div className="platform-pill platform-pill--rose px-3 py-1 text-[11px]">
|
||||
保存失败
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBack}
|
||||
disabled={isBusy}
|
||||
className={`platform-button platform-button--ghost min-h-0 self-start px-3 py-1.5 text-[11px] ${isBusy ? 'opacity-45' : ''}`}
|
||||
>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
返回
|
||||
</span>
|
||||
</button>
|
||||
{badge}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SquareHoleResultView({
|
||||
profile,
|
||||
draft = null,
|
||||
isBusy = false,
|
||||
error = null,
|
||||
onBack,
|
||||
onSaved,
|
||||
onPublished,
|
||||
onStartTestRun,
|
||||
}: SquareHoleResultViewProps) {
|
||||
const [editState, setEditState] = useState(() => createEditState(profile));
|
||||
const [autoSaveState, setAutoSaveState] =
|
||||
useState<SquareHoleAutoSaveState>('idle');
|
||||
const [localError, setLocalError] = useState<string | null>(null);
|
||||
const [isPublishing, setIsPublishing] = useState(false);
|
||||
const [isStartingTestRun, setIsStartingTestRun] = useState(false);
|
||||
const blockers = useMemo(() => buildPublishBlockers(editState), [editState]);
|
||||
const canSubmit = blockers.length === 0;
|
||||
|
||||
useEffect(() => {
|
||||
setEditState(createEditState(profile));
|
||||
setAutoSaveState('idle');
|
||||
setLocalError(null);
|
||||
}, [profile.profileId, profile.updatedAt]);
|
||||
|
||||
useEffect(() => {
|
||||
const payload = buildSavePayload(editState);
|
||||
if (!payload) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const currentTags = normalizeTags(profile.tags.join(','));
|
||||
const changed =
|
||||
payload.gameName !== profile.gameName ||
|
||||
payload.themeText !== profile.themeText ||
|
||||
payload.twistRule !== profile.twistRule ||
|
||||
payload.summary !== profile.summary ||
|
||||
(payload.coverImageSrc ?? '') !== (profile.coverImageSrc ?? '') ||
|
||||
payload.shapeCount !== profile.shapeCount ||
|
||||
payload.difficulty !== profile.difficulty ||
|
||||
payload.tags.length !== currentTags.length ||
|
||||
payload.tags.some((tag, index) => tag !== currentTags[index]);
|
||||
|
||||
if (!changed) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
setAutoSaveState('saving');
|
||||
setLocalError(null);
|
||||
let cancelled = false;
|
||||
const timer = window.setTimeout(() => {
|
||||
void updateSquareHoleWork(profile.profileId, payload)
|
||||
.then(({ item }) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setAutoSaveState('saved');
|
||||
onSaved?.(item);
|
||||
})
|
||||
.catch((saveError) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setAutoSaveState('error');
|
||||
setLocalError(
|
||||
saveError instanceof Error ? saveError.message : '自动保存失败。',
|
||||
);
|
||||
});
|
||||
}, SQUARE_HOLE_AUTOSAVE_DEBOUNCE_MS);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [editState, onSaved, profile]);
|
||||
|
||||
const saveNow = async () => {
|
||||
const payload = buildSavePayload(editState);
|
||||
if (!payload) {
|
||||
setLocalError(blockers[0] ?? '请补全作品信息。');
|
||||
return null;
|
||||
}
|
||||
|
||||
setAutoSaveState('saving');
|
||||
setLocalError(null);
|
||||
const { item } = await updateSquareHoleWork(profile.profileId, payload);
|
||||
setAutoSaveState('saved');
|
||||
onSaved?.(item);
|
||||
return item;
|
||||
};
|
||||
|
||||
const handleCoverImageChange = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0] ?? null;
|
||||
event.target.value = '';
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const dataUrl = await readImageAsDataUrl(file);
|
||||
setEditState((current) => ({
|
||||
...current,
|
||||
coverImageSrc: dataUrl,
|
||||
}));
|
||||
setLocalError(null);
|
||||
} catch (caughtError) {
|
||||
setLocalError(
|
||||
caughtError instanceof Error ? caughtError.message : '封面图读取失败。',
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStartTestRun = async () => {
|
||||
if (!canSubmit || isStartingTestRun) {
|
||||
setLocalError(blockers[0] ?? null);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsStartingTestRun(true);
|
||||
try {
|
||||
const savedProfile = await saveNow();
|
||||
onStartTestRun(savedProfile ?? buildPlayableProfile(profile, editState));
|
||||
} catch (caughtError) {
|
||||
setLocalError(
|
||||
caughtError instanceof Error ? caughtError.message : '启动试玩前保存失败。',
|
||||
);
|
||||
} finally {
|
||||
setIsStartingTestRun(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePublish = async () => {
|
||||
if (!canSubmit || isPublishing) {
|
||||
setLocalError(blockers[0] ?? null);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPublishing(true);
|
||||
try {
|
||||
const savedProfile = await saveNow();
|
||||
const { item } = await publishSquareHoleWork(
|
||||
savedProfile?.profileId ?? profile.profileId,
|
||||
);
|
||||
onPublished?.(item);
|
||||
setLocalError(null);
|
||||
} catch (caughtError) {
|
||||
setLocalError(
|
||||
caughtError instanceof Error ? caughtError.message : '发布方洞挑战失败。',
|
||||
);
|
||||
} finally {
|
||||
setIsPublishing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const busy = isBusy || isPublishing || isStartingTestRun;
|
||||
const displayError = error ?? localError;
|
||||
|
||||
return (
|
||||
<div className="platform-remap-surface mx-auto flex h-full min-h-0 w-full flex-col xl:max-w-[min(100%,88rem)]">
|
||||
<SquareHoleResultHeader
|
||||
autoSaveState={autoSaveState}
|
||||
isBusy={busy}
|
||||
onBack={onBack}
|
||||
/>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto pr-1">
|
||||
<div className="grid gap-3 lg:grid-cols-[minmax(17rem,0.72fr)_minmax(0,1fr)]">
|
||||
<section className="platform-subpanel rounded-[1.5rem] p-4 sm:p-5">
|
||||
<div className="aspect-[4/3] overflow-hidden rounded-[1.25rem] border border-[var(--platform-subpanel-border)] bg-[radial-gradient(circle_at_42%_30%,rgba(125,211,252,0.28),transparent_34%),linear-gradient(135deg,rgba(15,23,42,0.16),rgba(20,184,166,0.18))]">
|
||||
{editState.coverImageSrc ? (
|
||||
<ResolvedAssetImage
|
||||
src={editState.coverImageSrc}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="grid h-full w-full place-items-center text-slate-700">
|
||||
<ImagePlus className="h-10 w-10" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<label className="platform-button platform-button--ghost mt-3 flex min-h-10 cursor-pointer items-center justify-center gap-2 px-3 py-2 text-sm">
|
||||
<ImagePlus className="h-4 w-4" />
|
||||
封面图
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="sr-only"
|
||||
disabled={busy}
|
||||
onChange={handleCoverImageChange}
|
||||
/>
|
||||
</label>
|
||||
<div className="mt-3 grid grid-cols-3 gap-2 text-center text-xs font-bold text-[var(--platform-text-base)]">
|
||||
<div className="rounded-[1rem] bg-white/68 px-2 py-2">
|
||||
{editState.shapeCountText || '-'} 个
|
||||
</div>
|
||||
<div className="rounded-[1rem] bg-white/68 px-2 py-2">
|
||||
难度 {editState.difficultyText || '-'}
|
||||
</div>
|
||||
<div className="rounded-[1rem] bg-white/68 px-2 py-2">
|
||||
{draft?.publishReady ?? profile.publishReady ? '可发布' : '草稿'}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="platform-subpanel rounded-[1.5rem] p-4 sm:p-5">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="block sm:col-span-2">
|
||||
<span className="text-xs font-bold tracking-[0.18em] text-[var(--platform-text-soft)]">
|
||||
游戏名称
|
||||
</span>
|
||||
<input
|
||||
value={editState.gameName}
|
||||
disabled={busy}
|
||||
onChange={(event) =>
|
||||
setEditState({ ...editState, gameName: event.target.value })
|
||||
}
|
||||
className="mt-2 w-full rounded-[1rem] border border-[var(--platform-subpanel-border)] bg-white/86 px-3 py-3 text-base font-semibold text-[var(--platform-text-strong)] outline-none"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="block sm:col-span-2">
|
||||
<span className="text-xs font-bold tracking-[0.18em] text-[var(--platform-text-soft)]">
|
||||
标签
|
||||
</span>
|
||||
<input
|
||||
value={editState.tagsText}
|
||||
disabled={busy}
|
||||
onChange={(event) =>
|
||||
setEditState({ ...editState, tagsText: event.target.value })
|
||||
}
|
||||
className="mt-2 w-full rounded-[1rem] border border-[var(--platform-subpanel-border)] bg-white/86 px-3 py-3 text-sm font-semibold text-[var(--platform-text-strong)] outline-none"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="block sm:col-span-2">
|
||||
<span className="text-xs font-bold tracking-[0.18em] text-[var(--platform-text-soft)]">
|
||||
简介
|
||||
</span>
|
||||
<textarea
|
||||
value={editState.summary}
|
||||
disabled={busy}
|
||||
onChange={(event) =>
|
||||
setEditState({ ...editState, summary: event.target.value })
|
||||
}
|
||||
rows={3}
|
||||
className="mt-2 w-full resize-none rounded-[1rem] border border-[var(--platform-subpanel-border)] bg-white/86 px-3 py-3 text-sm leading-6 text-[var(--platform-text-strong)] outline-none"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="block">
|
||||
<span className="text-xs font-bold tracking-[0.18em] text-[var(--platform-text-soft)]">
|
||||
题材主题
|
||||
</span>
|
||||
<input
|
||||
value={editState.themeText}
|
||||
disabled={busy}
|
||||
onChange={(event) =>
|
||||
setEditState({ ...editState, themeText: event.target.value })
|
||||
}
|
||||
className="mt-2 w-full rounded-[1rem] border border-[var(--platform-subpanel-border)] bg-white/86 px-3 py-3 text-sm font-semibold text-[var(--platform-text-strong)] outline-none"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="block">
|
||||
<span className="text-xs font-bold tracking-[0.18em] text-[var(--platform-text-soft)]">
|
||||
反差规则
|
||||
</span>
|
||||
<input
|
||||
value={editState.twistRule}
|
||||
disabled={busy}
|
||||
onChange={(event) =>
|
||||
setEditState({ ...editState, twistRule: event.target.value })
|
||||
}
|
||||
className="mt-2 w-full rounded-[1rem] border border-[var(--platform-subpanel-border)] bg-white/86 px-3 py-3 text-sm font-semibold text-[var(--platform-text-strong)] outline-none"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="block">
|
||||
<span className="text-xs font-bold tracking-[0.18em] text-[var(--platform-text-soft)]">
|
||||
形状数量
|
||||
</span>
|
||||
<input
|
||||
value={editState.shapeCountText}
|
||||
inputMode="numeric"
|
||||
disabled={busy}
|
||||
onChange={(event) =>
|
||||
setEditState({
|
||||
...editState,
|
||||
shapeCountText: event.target.value,
|
||||
})
|
||||
}
|
||||
className="mt-2 w-full rounded-[1rem] border border-[var(--platform-subpanel-border)] bg-white/86 px-3 py-3 text-sm font-semibold text-[var(--platform-text-strong)] outline-none"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="block">
|
||||
<span className="text-xs font-bold tracking-[0.18em] text-[var(--platform-text-soft)]">
|
||||
难度
|
||||
</span>
|
||||
<input
|
||||
value={editState.difficultyText}
|
||||
inputMode="numeric"
|
||||
disabled={busy}
|
||||
onChange={(event) =>
|
||||
setEditState({
|
||||
...editState,
|
||||
difficultyText: event.target.value,
|
||||
})
|
||||
}
|
||||
className="mt-2 w-full rounded-[1rem] border border-[var(--platform-subpanel-border)] bg-white/86 px-3 py-3 text-sm font-semibold text-[var(--platform-text-strong)] outline-none"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{displayError ? (
|
||||
<div className="platform-banner platform-banner--danger mt-3 rounded-2xl text-sm leading-6">
|
||||
{displayError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-3 flex flex-col gap-2 pb-[max(0.25rem,env(safe-area-inset-bottom))] sm:flex-row sm:justify-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleStartTestRun}
|
||||
disabled={!canSubmit || busy}
|
||||
className={`platform-button platform-button--ghost min-h-11 justify-center gap-2 px-5 py-3 ${!canSubmit || busy ? 'cursor-not-allowed opacity-55' : ''}`}
|
||||
>
|
||||
{isStartingTestRun ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Play className="h-4 w-4" />
|
||||
)}
|
||||
试玩
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePublish}
|
||||
disabled={!canSubmit || busy}
|
||||
className={`platform-button platform-button--primary min-h-11 justify-center gap-2 px-5 py-3 ${!canSubmit || busy ? 'cursor-not-allowed opacity-55' : ''}`}
|
||||
>
|
||||
{isPublishing ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : profile.publicationStatus === 'published' ? (
|
||||
<CheckCircle2 className="h-4 w-4" />
|
||||
) : (
|
||||
<Send className="h-4 w-4" />
|
||||
)}
|
||||
{profile.publicationStatus === 'published' ? '更新发布' : '发布'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SquareHoleResultView;
|
||||
1
src/components/square-hole-result/index.ts
Normal file
1
src/components/square-hole-result/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { SquareHoleResultView } from './SquareHoleResultView';
|
||||
380
src/components/square-hole-runtime/SquareHoleRuntimeShell.tsx
Normal file
380
src/components/square-hole-runtime/SquareHoleRuntimeShell.tsx
Normal file
@@ -0,0 +1,380 @@
|
||||
import {
|
||||
ArrowLeft,
|
||||
CheckCircle2,
|
||||
Clock3,
|
||||
RotateCcw,
|
||||
Shapes,
|
||||
Sparkles,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import type {
|
||||
DropSquareHoleShapeRequest,
|
||||
SquareHoleDropResponse,
|
||||
SquareHoleHoleSnapshot,
|
||||
SquareHoleRunSnapshot,
|
||||
} from '../../../packages/shared/src/contracts/squareHoleRuntime';
|
||||
|
||||
type SquareHoleRuntimeShellProps = {
|
||||
run: SquareHoleRunSnapshot | null;
|
||||
isBusy?: boolean;
|
||||
error?: string | null;
|
||||
onBack: () => void;
|
||||
onRestart: () => void;
|
||||
onDropShape: (
|
||||
payload: DropSquareHoleShapeRequest,
|
||||
) => Promise<SquareHoleDropResponse>;
|
||||
onOptimisticRunChange?: (run: SquareHoleRunSnapshot) => void;
|
||||
onTimeExpired?: () => void;
|
||||
};
|
||||
|
||||
type PendingDrop = {
|
||||
clientEventId: string;
|
||||
holeId: string;
|
||||
};
|
||||
|
||||
function isRunning(run: SquareHoleRunSnapshot) {
|
||||
return run.status.toLowerCase() === 'running';
|
||||
}
|
||||
|
||||
function formatTimer(value: number) {
|
||||
const totalSeconds = Math.max(0, Math.ceil(value / 1000));
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function buildClientEventId(runId: string, holeId: string) {
|
||||
return `square-hole-drop-${runId}-${holeId}-${Date.now()}-${Math.round(
|
||||
Math.random() * 1_000_000,
|
||||
)}`;
|
||||
}
|
||||
|
||||
function getHoleShapeClass(hole: SquareHoleHoleSnapshot) {
|
||||
const kind = hole.holeKind.toLowerCase();
|
||||
if (kind.includes('circle')) {
|
||||
return 'rounded-full';
|
||||
}
|
||||
if (kind.includes('triangle')) {
|
||||
return 'square-hole-runtime__hole-cut--triangle';
|
||||
}
|
||||
if (kind.includes('diamond')) {
|
||||
return 'rotate-45 rounded-[0.75rem]';
|
||||
}
|
||||
if (kind.includes('star')) {
|
||||
return 'square-hole-runtime__hole-cut--star';
|
||||
}
|
||||
if (kind.includes('arch')) {
|
||||
return 'rounded-t-full rounded-b-[0.85rem]';
|
||||
}
|
||||
return 'rounded-[0.85rem]';
|
||||
}
|
||||
|
||||
function getShapePreviewClass(shapeKind: string) {
|
||||
const kind = shapeKind.toLowerCase();
|
||||
if (kind.includes('circle')) {
|
||||
return 'rounded-full';
|
||||
}
|
||||
if (kind.includes('triangle')) {
|
||||
return 'square-hole-runtime__shape--triangle';
|
||||
}
|
||||
if (kind.includes('diamond')) {
|
||||
return 'rotate-45 rounded-[0.8rem]';
|
||||
}
|
||||
if (kind.includes('star')) {
|
||||
return 'square-hole-runtime__shape--star';
|
||||
}
|
||||
if (kind.includes('arch')) {
|
||||
return 'rounded-t-full rounded-b-[0.9rem]';
|
||||
}
|
||||
return 'rounded-[0.9rem]';
|
||||
}
|
||||
|
||||
function SquareHoleSettlement({
|
||||
run,
|
||||
onBack,
|
||||
onRestart,
|
||||
}: {
|
||||
run: SquareHoleRunSnapshot;
|
||||
onBack: () => void;
|
||||
onRestart: () => void;
|
||||
}) {
|
||||
if (isRunning(run)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const won = run.status.toLowerCase() === 'won';
|
||||
const stopped = run.status.toLowerCase() === 'stopped';
|
||||
const title = won ? '挑战完成' : stopped ? '已停止' : '本轮失败';
|
||||
return (
|
||||
<div className="absolute inset-0 z-[80] flex items-center justify-center bg-slate-950/64 px-5 backdrop-blur-sm">
|
||||
<section
|
||||
className="w-full max-w-sm rounded-[1.5rem] border border-white/18 bg-white/94 p-5 text-slate-950 shadow-[0_26px_70px_rgba(15,23,42,0.34)]"
|
||||
role="dialog"
|
||||
aria-label={title}
|
||||
>
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<span
|
||||
className={`flex h-11 w-11 items-center justify-center rounded-full ${
|
||||
won
|
||||
? 'bg-emerald-100 text-emerald-700'
|
||||
: 'bg-rose-100 text-rose-700'
|
||||
}`}
|
||||
>
|
||||
{won ? <CheckCircle2 size={24} /> : <XCircle size={24} />}
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="text-xl font-black">{title}</h2>
|
||||
<p className="text-sm font-semibold text-slate-500">
|
||||
{run.completedShapeCount}/{run.totalShapeCount} · {run.score} 分
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-black text-slate-700"
|
||||
onClick={onBack}
|
||||
>
|
||||
返回
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-xl bg-slate-950 px-4 py-3 text-sm font-black text-white"
|
||||
onClick={onRestart}
|
||||
>
|
||||
再来一局
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SquareHoleRuntimeShell({
|
||||
run,
|
||||
isBusy = false,
|
||||
error = null,
|
||||
onBack,
|
||||
onRestart,
|
||||
onDropShape,
|
||||
onOptimisticRunChange,
|
||||
onTimeExpired,
|
||||
}: SquareHoleRuntimeShellProps) {
|
||||
const [pendingDrop, setPendingDrop] = useState<PendingDrop | null>(null);
|
||||
const [timeLeftMs, setTimeLeftMs] = useState(run?.remainingMs ?? 0);
|
||||
const [feedbackPulseId, setFeedbackPulseId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setTimeLeftMs(run?.remainingMs ?? 0);
|
||||
}, [run?.remainingMs, run?.snapshotVersion]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!run || !isRunning(run)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
setTimeLeftMs((current) => {
|
||||
const next = Math.max(0, current - 1000);
|
||||
if (next <= 0) {
|
||||
onTimeExpired?.();
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
return () => window.clearInterval(timer);
|
||||
}, [onTimeExpired, run]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!feedbackPulseId) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const timer = window.setTimeout(() => setFeedbackPulseId(null), 620);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [feedbackPulseId]);
|
||||
|
||||
const progressText = useMemo(() => {
|
||||
if (!run) {
|
||||
return '0/0';
|
||||
}
|
||||
return `${run.completedShapeCount}/${run.totalShapeCount}`;
|
||||
}, [run]);
|
||||
|
||||
const dropToHole = async (holeId: string) => {
|
||||
if (!run || !isRunning(run) || pendingDrop || isBusy) {
|
||||
return;
|
||||
}
|
||||
|
||||
const clientEventId = buildClientEventId(run.runId, holeId);
|
||||
setPendingDrop({ clientEventId, holeId });
|
||||
setFeedbackPulseId(null);
|
||||
|
||||
try {
|
||||
const response = await onDropShape({
|
||||
runId: run.runId,
|
||||
holeId,
|
||||
clientSnapshotVersion: run.snapshotVersion,
|
||||
clientEventId,
|
||||
droppedAtMs: Date.now(),
|
||||
});
|
||||
setFeedbackPulseId(clientEventId);
|
||||
onOptimisticRunChange?.(response.run);
|
||||
} finally {
|
||||
setPendingDrop(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (!run) {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center bg-slate-950 text-white">
|
||||
{isBusy ? '载入中' : (error ?? '暂无运行态')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const currentShape = run.currentShape;
|
||||
const feedback = run.lastFeedback;
|
||||
|
||||
return (
|
||||
<main className="relative flex min-h-dvh w-full justify-center overflow-hidden bg-[#101827] text-white">
|
||||
<div className="absolute inset-0 bg-[radial-gradient(circle_at_50%_10%,rgba(125,211,252,0.32),transparent_27%),radial-gradient(circle_at_80%_80%,rgba(248,113,113,0.24),transparent_34%),linear-gradient(180deg,#1f3a5f_0%,#152238_48%,#111827_100%)]" />
|
||||
<div
|
||||
className="relative flex min-h-dvh min-w-0 flex-col overflow-hidden px-3 pb-[calc(env(safe-area-inset-bottom,0px)+0.8rem)] pt-[calc(env(safe-area-inset-top,0px)+0.65rem)]"
|
||||
style={{
|
||||
boxSizing: 'border-box',
|
||||
maxWidth: '100vw',
|
||||
width: 'min(100vw, 24rem)',
|
||||
}}
|
||||
>
|
||||
<header className="flex items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-10 w-10 items-center justify-center rounded-full border border-white/16 bg-black/24 text-white backdrop-blur"
|
||||
onClick={onBack}
|
||||
aria-label="返回"
|
||||
>
|
||||
<ArrowLeft size={20} />
|
||||
</button>
|
||||
<div className="flex items-center gap-2 rounded-full border border-white/16 bg-black/26 px-3 py-2 text-sm font-black backdrop-blur">
|
||||
<Clock3 size={16} />
|
||||
<span>{formatTimer(timeLeftMs)}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-10 w-10 items-center justify-center rounded-full border border-white/16 bg-black/24 text-white backdrop-blur"
|
||||
onClick={onRestart}
|
||||
aria-label="重新开始"
|
||||
>
|
||||
<RotateCcw size={18} />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section className="mt-3 grid w-full min-w-0 grid-cols-3 gap-2 overflow-hidden text-center text-[0.72rem] font-black">
|
||||
<div className="rounded-2xl border border-white/14 bg-black/20 px-2 py-2 backdrop-blur">
|
||||
{progressText}
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/14 bg-black/20 px-2 py-2 backdrop-blur">
|
||||
{run.score} 分
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/14 bg-black/20 px-2 py-2 backdrop-blur">
|
||||
{run.combo} 连
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="mt-3 rounded-[1.5rem] border border-white/14 bg-black/18 p-3 shadow-[0_18px_42px_rgba(15,23,42,0.28)] backdrop-blur">
|
||||
<div className="flex items-center justify-between gap-2 text-xs font-bold text-white/68">
|
||||
<span>{run.ruleLabel}</span>
|
||||
<span>v{run.snapshotVersion}</span>
|
||||
</div>
|
||||
<div className="mt-3 flex min-h-[12rem] items-center justify-center rounded-[1.35rem] border border-white/10 bg-white/10">
|
||||
{currentShape ? (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div
|
||||
className={`h-24 w-24 shadow-[0_18px_38px_rgba(15,23,42,0.34)] ${getShapePreviewClass(
|
||||
currentShape.shapeKind,
|
||||
)}`}
|
||||
style={{
|
||||
background:
|
||||
currentShape.color ||
|
||||
'linear-gradient(135deg,#f8fafc,#38bdf8)',
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2 text-base font-black">
|
||||
<Shapes size={18} />
|
||||
<span>{currentShape.label}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm font-bold text-white/70">等待下一块</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="mt-3 grid grid-cols-2 gap-2">
|
||||
{run.holes.map((hole) => {
|
||||
const isPending = pendingDrop?.holeId === hole.holeId;
|
||||
return (
|
||||
<button
|
||||
key={hole.holeId}
|
||||
type="button"
|
||||
disabled={!isRunning(run) || Boolean(pendingDrop) || isBusy}
|
||||
className={`min-h-[6.25rem] rounded-[1.35rem] border border-white/14 bg-black/22 p-2 text-white shadow-[0_12px_28px_rgba(15,23,42,0.24)] backdrop-blur transition active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-58 ${
|
||||
isPending ? 'ring-2 ring-cyan-200/70' : ''
|
||||
}`}
|
||||
onClick={() => {
|
||||
void dropToHole(hole.holeId);
|
||||
}}
|
||||
aria-label={`投入 ${hole.label}`}
|
||||
>
|
||||
<span className="mx-auto grid h-12 w-12 place-items-center rounded-2xl bg-white/88 p-2">
|
||||
<span
|
||||
className={`block h-full w-full bg-slate-950 ${getHoleShapeClass(
|
||||
hole,
|
||||
)}`}
|
||||
/>
|
||||
</span>
|
||||
<span className="mt-2 block truncate text-sm font-black">
|
||||
{hole.label}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
|
||||
<section className="mt-auto min-h-[3.5rem] pt-3">
|
||||
{feedback ? (
|
||||
<div
|
||||
className={`rounded-[1.2rem] border px-3 py-2 text-center text-sm font-black ${
|
||||
feedback.accepted
|
||||
? 'border-emerald-200/35 bg-emerald-400/18 text-emerald-50'
|
||||
: 'border-rose-200/35 bg-rose-400/18 text-rose-50'
|
||||
}`}
|
||||
>
|
||||
{feedback.message}
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="rounded-[1.2rem] border border-rose-200/35 bg-rose-400/18 px-3 py-2 text-center text-sm font-black text-rose-50">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{feedbackPulseId && feedback?.accepted ? (
|
||||
<div className="pointer-events-none absolute inset-0 z-[70] flex items-center justify-center">
|
||||
<div className="flex h-24 w-24 items-center justify-center rounded-full bg-white/24 text-cyan-100 shadow-[0_0_42px_rgba(255,255,255,0.72)] backdrop-blur-sm">
|
||||
<Sparkles size={42} />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<SquareHoleSettlement run={run} onBack={onBack} onRestart={onRestart} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export default SquareHoleRuntimeShell;
|
||||
1
src/components/square-hole-runtime/index.ts
Normal file
1
src/components/square-hole-runtime/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { SquareHoleRuntimeShell } from './SquareHoleRuntimeShell';
|
||||
@@ -46,6 +46,14 @@ export const NEW_WORK_ENTRY_CONFIG = {
|
||||
visible: true,
|
||||
open: true,
|
||||
},
|
||||
{
|
||||
id: 'square-hole',
|
||||
title: '方洞挑战',
|
||||
subtitle: '反直觉形状分拣',
|
||||
badge: '可创建',
|
||||
visible: true,
|
||||
open: true,
|
||||
},
|
||||
{
|
||||
id: 'airp',
|
||||
title: 'AIRP',
|
||||
|
||||
@@ -1528,6 +1528,27 @@ body {
|
||||
opacity: 0.52;
|
||||
}
|
||||
|
||||
.square-hole-runtime__shape--triangle,
|
||||
.square-hole-runtime__hole-cut--triangle {
|
||||
clip-path: polygon(50% 5%, 94% 92%, 6% 92%);
|
||||
}
|
||||
|
||||
.square-hole-runtime__shape--star,
|
||||
.square-hole-runtime__hole-cut--star {
|
||||
clip-path: polygon(
|
||||
50% 4%,
|
||||
61% 36%,
|
||||
95% 36%,
|
||||
67% 55%,
|
||||
79% 88%,
|
||||
50% 68%,
|
||||
21% 88%,
|
||||
33% 55%,
|
||||
5% 36%,
|
||||
39% 36%
|
||||
);
|
||||
}
|
||||
|
||||
.platform-tab {
|
||||
border: 1px solid var(--platform-subpanel-border);
|
||||
border-radius: 9999px;
|
||||
|
||||
@@ -17,6 +17,9 @@ const STAGE_ROUTE_ENTRIES = [
|
||||
['match3d-agent-workspace', '/creation/match3d/agent'],
|
||||
['match3d-result', '/creation/match3d/result'],
|
||||
['match3d-runtime', '/runtime/match3d'],
|
||||
['square-hole-agent-workspace', '/creation/square-hole/agent'],
|
||||
['square-hole-result', '/creation/square-hole/result'],
|
||||
['square-hole-runtime', '/runtime/square-hole'],
|
||||
['puzzle-agent-workspace', '/creation/puzzle/agent'],
|
||||
['puzzle-result', '/creation/puzzle/result'],
|
||||
['puzzle-gallery-detail', '/gallery/puzzle/detail'],
|
||||
|
||||
@@ -51,3 +51,28 @@ test('readCreationAgentSessionFromSse flushes decoder tail and handles CRLF boun
|
||||
title: '世界共创',
|
||||
});
|
||||
});
|
||||
|
||||
test('readCreationAgentSessionFromSse keeps streamed updates before error event', async () => {
|
||||
const encoder = new TextEncoder();
|
||||
const response = createChunkedStreamResponse([
|
||||
encoder.encode(
|
||||
'event: reply_delta\ndata: {"text":"先把方洞万能的反差定住。"}\n\n',
|
||||
),
|
||||
encoder.encode(
|
||||
'event: error\ndata: {"message":"方洞挑战聊天生成失败:LLM 请求超时"}\n\n',
|
||||
),
|
||||
]);
|
||||
const updates: string[] = [];
|
||||
|
||||
await expect(
|
||||
readCreationAgentSessionFromSse(response, {
|
||||
fallbackMessage: '发送失败',
|
||||
incompleteMessage: '结果不完整',
|
||||
onUpdate: (text) => {
|
||||
updates.push(text);
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow('方洞挑战聊天生成失败:LLM 请求超时');
|
||||
|
||||
expect(updates).toEqual(['先把方洞万能的反差定住。']);
|
||||
});
|
||||
|
||||
@@ -29,6 +29,14 @@ export function buildMatch3DPublicWorkCode(profileId: string) {
|
||||
return `M3-${suffix}`;
|
||||
}
|
||||
|
||||
export function buildSquareHolePublicWorkCode(profileId: string) {
|
||||
const normalized = normalizePublicCodeText(profileId);
|
||||
const fallback = normalized || '00000000';
|
||||
const suffix = fallback.slice(-8).padStart(8, '0');
|
||||
|
||||
return `SH-${suffix}`;
|
||||
}
|
||||
|
||||
export function isSamePuzzlePublicWorkCode(keyword: string, profileId: string) {
|
||||
const normalizedKeyword = normalizePublicCodeText(keyword);
|
||||
|
||||
@@ -61,3 +69,16 @@ export function isSameMatch3DPublicWorkCode(keyword: string, profileId: string)
|
||||
normalizedKeyword === normalizePublicCodeText(profileId)
|
||||
);
|
||||
}
|
||||
|
||||
export function isSameSquareHolePublicWorkCode(
|
||||
keyword: string,
|
||||
profileId: string,
|
||||
) {
|
||||
const normalizedKeyword = normalizePublicCodeText(keyword);
|
||||
|
||||
return (
|
||||
normalizedKeyword ===
|
||||
normalizePublicCodeText(buildSquareHolePublicWorkCode(profileId)) ||
|
||||
normalizedKeyword === normalizePublicCodeText(profileId)
|
||||
);
|
||||
}
|
||||
|
||||
8
src/services/square-hole-creation/index.ts
Normal file
8
src/services/square-hole-creation/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export {
|
||||
createSquareHoleCreationSession,
|
||||
executeSquareHoleCreationAction,
|
||||
getSquareHoleCreationSession,
|
||||
sendSquareHoleCreationMessage,
|
||||
squareHoleCreationClient,
|
||||
streamSquareHoleCreationMessage,
|
||||
} from './squareHoleCreationClient';
|
||||
@@ -0,0 +1,87 @@
|
||||
import type {
|
||||
CreateSquareHoleSessionRequest,
|
||||
ExecuteSquareHoleActionRequest,
|
||||
SendSquareHoleMessageRequest,
|
||||
SquareHoleActionResponse,
|
||||
SquareHoleSessionResponse,
|
||||
SquareHoleSessionSnapshot,
|
||||
} from '../../../packages/shared/src/contracts/squareHoleAgent';
|
||||
import type { TextStreamOptions } from '../aiTypes';
|
||||
import { createCreationAgentClient } from '../creation-agent';
|
||||
|
||||
const SQUARE_HOLE_AGENT_API_BASE = '/api/creation/square-hole/sessions';
|
||||
|
||||
const squareHoleAgentHttpClient = createCreationAgentClient<
|
||||
CreateSquareHoleSessionRequest,
|
||||
SquareHoleSessionResponse,
|
||||
SquareHoleSessionResponse,
|
||||
SquareHoleSessionSnapshot,
|
||||
SendSquareHoleMessageRequest,
|
||||
SquareHoleSessionResponse,
|
||||
ExecuteSquareHoleActionRequest,
|
||||
SquareHoleActionResponse
|
||||
>({
|
||||
apiBase: SQUARE_HOLE_AGENT_API_BASE,
|
||||
messages: {
|
||||
createSession: '创建方洞挑战共创会话失败',
|
||||
getSession: '读取方洞挑战共创会话失败',
|
||||
sendMessage: '发送方洞挑战共创消息失败',
|
||||
streamIncomplete: '方洞挑战共创消息流式结果不完整',
|
||||
executeAction: '执行方洞挑战共创操作失败',
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* 创建方洞挑战 Agent 共创会话。
|
||||
*/
|
||||
export function createSquareHoleCreationSession(
|
||||
payload: CreateSquareHoleSessionRequest = {},
|
||||
) {
|
||||
return squareHoleAgentHttpClient.createSession(payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取方洞挑战 Agent 会话快照。
|
||||
*/
|
||||
export function getSquareHoleCreationSession(sessionId: string) {
|
||||
return squareHoleAgentHttpClient.getSession(sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 非流式发送方洞挑战 Agent 消息,保留为 SSE 降级入口。
|
||||
*/
|
||||
export function sendSquareHoleCreationMessage(
|
||||
sessionId: string,
|
||||
payload: SendSquareHoleMessageRequest,
|
||||
) {
|
||||
return squareHoleAgentHttpClient.sendMessage(sessionId, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式发送方洞挑战 Agent 消息。
|
||||
*/
|
||||
export function streamSquareHoleCreationMessage(
|
||||
sessionId: string,
|
||||
payload: SendSquareHoleMessageRequest,
|
||||
options: TextStreamOptions = {},
|
||||
) {
|
||||
return squareHoleAgentHttpClient.streamMessage(sessionId, payload, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行方洞挑战创作操作,例如生成草稿作品。
|
||||
*/
|
||||
export function executeSquareHoleCreationAction(
|
||||
sessionId: string,
|
||||
payload: ExecuteSquareHoleActionRequest,
|
||||
) {
|
||||
return squareHoleAgentHttpClient.executeAction(sessionId, payload);
|
||||
}
|
||||
|
||||
export const squareHoleCreationClient = {
|
||||
createSession: createSquareHoleCreationSession,
|
||||
getSession: getSquareHoleCreationSession,
|
||||
sendMessage: sendSquareHoleCreationMessage,
|
||||
streamMessage: streamSquareHoleCreationMessage,
|
||||
executeAction: executeSquareHoleCreationAction,
|
||||
};
|
||||
9
src/services/square-hole-runtime/index.ts
Normal file
9
src/services/square-hole-runtime/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export {
|
||||
dropSquareHoleShape,
|
||||
finishSquareHoleTimeUp,
|
||||
getSquareHoleRun,
|
||||
restartSquareHoleRun,
|
||||
squareHoleRuntimeClient,
|
||||
startSquareHoleRun,
|
||||
stopSquareHoleRun,
|
||||
} from './squareHoleRuntimeClient';
|
||||
123
src/services/square-hole-runtime/squareHoleRuntimeClient.ts
Normal file
123
src/services/square-hole-runtime/squareHoleRuntimeClient.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import type {
|
||||
DropSquareHoleShapeRequest,
|
||||
SquareHoleDropResponse,
|
||||
SquareHoleRunResponse,
|
||||
StopSquareHoleRunRequest,
|
||||
} from '../../../packages/shared/src/contracts/squareHoleRuntime';
|
||||
import { type ApiRetryOptions, requestJson } from '../apiClient';
|
||||
|
||||
const SQUARE_HOLE_RUNTIME_READ_RETRY: ApiRetryOptions = {
|
||||
maxRetries: 1,
|
||||
baseDelayMs: 120,
|
||||
maxDelayMs: 360,
|
||||
};
|
||||
const SQUARE_HOLE_RUNTIME_WRITE_RETRY: ApiRetryOptions = {
|
||||
maxRetries: 1,
|
||||
baseDelayMs: 120,
|
||||
maxDelayMs: 360,
|
||||
retryUnsafeMethods: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* 基于作品启动一局方洞挑战正式 run。
|
||||
*/
|
||||
export function startSquareHoleRun(profileId: string) {
|
||||
return requestJson<SquareHoleRunResponse>(
|
||||
`/api/runtime/square-hole/works/${encodeURIComponent(profileId)}/runs`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ profileId }),
|
||||
},
|
||||
'启动方洞挑战失败',
|
||||
{ retry: SQUARE_HOLE_RUNTIME_WRITE_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取方洞挑战运行态快照。
|
||||
*/
|
||||
export function getSquareHoleRun(runId: string) {
|
||||
return requestJson<SquareHoleRunResponse>(
|
||||
`/api/runtime/square-hole/runs/${encodeURIComponent(runId)}`,
|
||||
{ method: 'GET' },
|
||||
'读取方洞挑战运行快照失败',
|
||||
{ retry: SQUARE_HOLE_RUNTIME_READ_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交一次洞口选择,由后端做权威确认。
|
||||
*/
|
||||
export function dropSquareHoleShape(
|
||||
runId: string,
|
||||
payload: DropSquareHoleShapeRequest,
|
||||
) {
|
||||
return requestJson<SquareHoleDropResponse>(
|
||||
`/api/runtime/square-hole/runs/${encodeURIComponent(runId)}/drop`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...payload,
|
||||
runId: payload.runId ?? runId,
|
||||
}),
|
||||
},
|
||||
'确认方洞挑战投入失败',
|
||||
{ retry: SQUARE_HOLE_RUNTIME_WRITE_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止当前方洞挑战运行态。
|
||||
*/
|
||||
export function stopSquareHoleRun(
|
||||
runId: string,
|
||||
payload: StopSquareHoleRunRequest = {
|
||||
clientActionId: `square-hole-stop-${Date.now()}`,
|
||||
},
|
||||
) {
|
||||
return requestJson<SquareHoleRunResponse>(
|
||||
`/api/runtime/square-hole/runs/${encodeURIComponent(runId)}/stop`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
'停止方洞挑战失败',
|
||||
{ retry: SQUARE_HOLE_RUNTIME_WRITE_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于当前 run 重开一局。
|
||||
*/
|
||||
export function restartSquareHoleRun(runId: string) {
|
||||
return requestJson<SquareHoleRunResponse>(
|
||||
`/api/runtime/square-hole/runs/${encodeURIComponent(runId)}/restart`,
|
||||
{ method: 'POST' },
|
||||
'重新开始方洞挑战失败',
|
||||
{ retry: SQUARE_HOLE_RUNTIME_WRITE_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 前端倒计时归零后通知后端确认失败状态。
|
||||
*/
|
||||
export function finishSquareHoleTimeUp(runId: string) {
|
||||
return requestJson<SquareHoleRunResponse>(
|
||||
`/api/runtime/square-hole/runs/${encodeURIComponent(runId)}/time-up`,
|
||||
{ method: 'POST' },
|
||||
'同步方洞挑战倒计时失败',
|
||||
{ retry: SQUARE_HOLE_RUNTIME_WRITE_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
export const squareHoleRuntimeClient = {
|
||||
dropShape: dropSquareHoleShape,
|
||||
finishTimeUp: finishSquareHoleTimeUp,
|
||||
getRun: getSquareHoleRun,
|
||||
restartRun: restartSquareHoleRun,
|
||||
startRun: startSquareHoleRun,
|
||||
stopRun: stopSquareHoleRun,
|
||||
};
|
||||
9
src/services/square-hole-works/index.ts
Normal file
9
src/services/square-hole-works/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export {
|
||||
deleteSquareHoleWork,
|
||||
getSquareHoleWorkDetail,
|
||||
listSquareHoleGallery,
|
||||
listSquareHoleWorks,
|
||||
publishSquareHoleWork,
|
||||
squareHoleWorksClient,
|
||||
updateSquareHoleWork,
|
||||
} from './squareHoleWorksClient';
|
||||
113
src/services/square-hole-works/squareHoleWorksClient.ts
Normal file
113
src/services/square-hole-works/squareHoleWorksClient.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import type {
|
||||
PutSquareHoleWorkRequest,
|
||||
SquareHoleWorkDetailResponse,
|
||||
SquareHoleWorkMutationResponse,
|
||||
SquareHoleWorksResponse,
|
||||
} from '../../../packages/shared/src/contracts/squareHoleWorks';
|
||||
import { type ApiRetryOptions, requestJson } from '../apiClient';
|
||||
|
||||
const SQUARE_HOLE_WORKS_API_BASE = '/api/creation/square-hole/works';
|
||||
const SQUARE_HOLE_GALLERY_API_BASE = '/api/runtime/square-hole/gallery';
|
||||
const SQUARE_HOLE_WORKS_READ_RETRY: ApiRetryOptions = {
|
||||
maxRetries: 1,
|
||||
baseDelayMs: 120,
|
||||
maxDelayMs: 360,
|
||||
};
|
||||
const SQUARE_HOLE_WORKS_WRITE_RETRY: ApiRetryOptions = {
|
||||
maxRetries: 1,
|
||||
baseDelayMs: 120,
|
||||
maxDelayMs: 360,
|
||||
retryUnsafeMethods: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取当前用户的方洞挑战作品列表。
|
||||
*/
|
||||
export function listSquareHoleWorks() {
|
||||
return requestJson<SquareHoleWorksResponse>(
|
||||
SQUARE_HOLE_WORKS_API_BASE,
|
||||
{ method: 'GET' },
|
||||
'读取方洞挑战作品列表失败',
|
||||
{ retry: SQUARE_HOLE_WORKS_READ_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取公开方洞挑战作品列表。
|
||||
*/
|
||||
export function listSquareHoleGallery() {
|
||||
return requestJson<SquareHoleWorksResponse>(
|
||||
SQUARE_HOLE_GALLERY_API_BASE,
|
||||
{ method: 'GET' },
|
||||
'读取方洞挑战广场失败',
|
||||
{
|
||||
retry: SQUARE_HOLE_WORKS_READ_RETRY,
|
||||
skipAuth: true,
|
||||
skipRefresh: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取方洞挑战作品详情。
|
||||
*/
|
||||
export function getSquareHoleWorkDetail(profileId: string) {
|
||||
return requestJson<SquareHoleWorkDetailResponse>(
|
||||
`${SQUARE_HOLE_WORKS_API_BASE}/${encodeURIComponent(profileId)}`,
|
||||
{ method: 'GET' },
|
||||
'读取方洞挑战作品详情失败',
|
||||
{ retry: SQUARE_HOLE_WORKS_READ_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存结果页可编辑字段。
|
||||
*/
|
||||
export function updateSquareHoleWork(
|
||||
profileId: string,
|
||||
payload: PutSquareHoleWorkRequest,
|
||||
) {
|
||||
return requestJson<SquareHoleWorkMutationResponse>(
|
||||
`${SQUARE_HOLE_WORKS_API_BASE}/${encodeURIComponent(profileId)}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
'更新方洞挑战作品失败',
|
||||
{ retry: SQUARE_HOLE_WORKS_WRITE_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布方洞挑战作品。发布门槛由后端最终确认。
|
||||
*/
|
||||
export function publishSquareHoleWork(profileId: string) {
|
||||
return requestJson<SquareHoleWorkMutationResponse>(
|
||||
`${SQUARE_HOLE_WORKS_API_BASE}/${encodeURIComponent(profileId)}/publish`,
|
||||
{ method: 'POST' },
|
||||
'发布方洞挑战作品失败',
|
||||
{ retry: SQUARE_HOLE_WORKS_WRITE_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除当前用户的方洞挑战作品,并返回删除后的列表。
|
||||
*/
|
||||
export function deleteSquareHoleWork(profileId: string) {
|
||||
return requestJson<SquareHoleWorksResponse>(
|
||||
`${SQUARE_HOLE_WORKS_API_BASE}/${encodeURIComponent(profileId)}`,
|
||||
{ method: 'DELETE' },
|
||||
'删除方洞挑战作品失败',
|
||||
{ retry: SQUARE_HOLE_WORKS_WRITE_RETRY },
|
||||
);
|
||||
}
|
||||
|
||||
export const squareHoleWorksClient = {
|
||||
delete: deleteSquareHoleWork,
|
||||
getDetail: getSquareHoleWorkDetail,
|
||||
listGallery: listSquareHoleGallery,
|
||||
list: listSquareHoleWorks,
|
||||
publish: publishSquareHoleWork,
|
||||
update: updateSquareHoleWork,
|
||||
};
|
||||
Reference in New Issue
Block a user