Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 51a79230d5 | |||
| be1a1dae60 | |||
| 71701e27ae | |||
| 2781663c61 | |||
| 185431788c | |||
| 922e0bdc58 |
@@ -1,286 +1,5 @@
|
||||
/**
|
||||
* 封面选择器
|
||||
* 抽帧选封面 + 上传自定义封面 + 智能封面推荐
|
||||
* 封面选择器入口(向后兼容)
|
||||
* 实际实现位于 ./cover-selector/ 目录
|
||||
*/
|
||||
import React, { useCallback, useRef, useState } from "react"
|
||||
import { Drawer } from "antd"
|
||||
import type { CoverConfig, CoverMode } from "../types"
|
||||
import { DEFAULT_COVER_CONFIG } from "../types"
|
||||
|
||||
interface CoverSelectorProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
config: CoverConfig
|
||||
onChange: (config: CoverConfig) => void
|
||||
totalDuration: number
|
||||
}
|
||||
|
||||
/** 封面模式标签 */
|
||||
const MODE_LABELS: Record<CoverMode, string> = {
|
||||
auto: "智能封面",
|
||||
frame: "抽帧选封面",
|
||||
upload: "上传封面",
|
||||
}
|
||||
|
||||
/** 封面模式图标 */
|
||||
const MODE_ICONS: Record<CoverMode, string> = {
|
||||
auto: "🤖",
|
||||
frame: "🎞️",
|
||||
upload: "📤",
|
||||
}
|
||||
|
||||
const CoverSelector: React.FC<CoverSelectorProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
config,
|
||||
onChange,
|
||||
totalDuration,
|
||||
}) => {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
const update = useCallback(
|
||||
(partial: Partial<CoverConfig>) => {
|
||||
onChange({ ...config, ...partial })
|
||||
},
|
||||
[config, onChange],
|
||||
)
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
onChange({ ...DEFAULT_COVER_CONFIG, enabled: config.enabled })
|
||||
}, [config.enabled, onChange])
|
||||
|
||||
/** 切换模式 */
|
||||
const handleModeChange = useCallback(
|
||||
(mode: CoverMode) => {
|
||||
update({ mode })
|
||||
},
|
||||
[update],
|
||||
)
|
||||
|
||||
/** 处理文件上传 */
|
||||
const handleFileUpload = useCallback(
|
||||
(file: File) => {
|
||||
if (!file.type.startsWith("image/")) return
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e) => {
|
||||
const url = e.target?.result as string
|
||||
update({ upload_url: url, thumbnail_url: url, mode: "upload" })
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
},
|
||||
[update],
|
||||
)
|
||||
|
||||
/** 拖拽上传 */
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file) handleFileUpload(file)
|
||||
},
|
||||
[handleFileUpload],
|
||||
)
|
||||
|
||||
/** 使用 AI 推荐时间 */
|
||||
const handleUseAiSuggestion = useCallback(() => {
|
||||
if (config.ai_suggested_time !== null) {
|
||||
update({ frame_time: config.ai_suggested_time, mode: "frame" })
|
||||
}
|
||||
}, [config.ai_suggested_time, update])
|
||||
|
||||
/** 格式化时间 */
|
||||
const formatTime = (seconds: number) => {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = Math.floor(seconds % 60)
|
||||
const ms = Math.floor((seconds % 1) * 10)
|
||||
return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}.${ms}`
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
title="封面选择"
|
||||
placement="right"
|
||||
width={440}
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
className="cover-selector-drawer"
|
||||
>
|
||||
{/* 顶部开关 */}
|
||||
<div className="cover-header">
|
||||
<span className="cover-header-label">启用自定义封面</span>
|
||||
<label className="cover-switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={config.enabled}
|
||||
onChange={(e) => update({ enabled: e.target.checked })}
|
||||
/>
|
||||
<span className="cover-switch-slider" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* 模式选择 */}
|
||||
<div className="cover-mode-section">
|
||||
<div className="cover-section-title">封面来源</div>
|
||||
<div className="cover-mode-tabs">
|
||||
{(["auto", "frame", "upload"] as CoverMode[]).map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
className={`cover-mode-tab${config.mode === m ? " active" : ""}`}
|
||||
onClick={() => handleModeChange(m)}
|
||||
>
|
||||
<span className="cover-mode-icon">{MODE_ICONS[m]}</span>
|
||||
<span className="cover-mode-label">{MODE_LABELS[m]}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 模式内容区 */}
|
||||
<div className="cover-mode-content">
|
||||
{/* 智能封面 */}
|
||||
{config.mode === "auto" && (
|
||||
<div className="cover-auto-section">
|
||||
<div className="cover-auto-desc">
|
||||
AI 将分析视频内容,自动选择最具吸引力的画面作为封面。
|
||||
</div>
|
||||
{config.ai_suggested_time !== null ? (
|
||||
<div className="cover-auto-suggestion">
|
||||
<div className="cover-auto-badge">AI 推荐</div>
|
||||
<div className="cover-auto-time">
|
||||
推荐时间点:{formatTime(config.ai_suggested_time)}
|
||||
</div>
|
||||
<button className="cover-auto-use-btn" onClick={handleUseAiSuggestion}>
|
||||
使用此时间点
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="cover-auto-pending">
|
||||
<div className="cover-auto-spinner" />
|
||||
<span>AI 分析中...(生成视频后自动推荐)</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 抽帧选封面 */}
|
||||
{config.mode === "frame" && (
|
||||
<div className="cover-frame-section">
|
||||
<div className="cover-frame-preview">
|
||||
<div className="cover-frame-placeholder">
|
||||
<span className="cover-frame-icon">🎞️</span>
|
||||
<span className="cover-frame-time">{formatTime(config.frame_time)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="cover-frame-timeline">
|
||||
<div className="cover-frame-slider-header">
|
||||
<span className="cover-frame-slider-label">拖动选择封面帧</span>
|
||||
<span className="cover-frame-slider-value">{formatTime(config.frame_time)}</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
className="cover-frame-slider"
|
||||
min={0}
|
||||
max={Math.max(totalDuration, 1)}
|
||||
step={0.1}
|
||||
value={config.frame_time}
|
||||
onChange={(e) => update({ frame_time: Number(e.target.value) })}
|
||||
/>
|
||||
<div className="cover-frame-range">
|
||||
<span>00:00</span>
|
||||
<span>{formatTime(totalDuration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{/* 快捷时间点 */}
|
||||
<div className="cover-frame-quick">
|
||||
<span className="cover-quick-label">快捷选帧:</span>
|
||||
{[0, 0.25, 0.5, 0.75].map((ratio) => {
|
||||
const t = totalDuration * ratio
|
||||
return (
|
||||
<button
|
||||
key={ratio}
|
||||
className="cover-quick-btn"
|
||||
onClick={() => update({ frame_time: t })}
|
||||
>
|
||||
{formatTime(t)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 上传封面 */}
|
||||
{config.mode === "upload" && (
|
||||
<div className="cover-upload-section">
|
||||
<div
|
||||
className={`cover-upload-area${isDragging ? " dragging" : ""}`}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={handleDrop}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
{config.upload_url ? (
|
||||
<div className="cover-upload-preview">
|
||||
<img src={config.upload_url} alt="封面预览" />
|
||||
<div className="cover-upload-overlay">点击更换</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="cover-upload-placeholder">
|
||||
<span className="cover-upload-icon">📤</span>
|
||||
<span className="cover-upload-text">点击或拖拽上传封面图片</span>
|
||||
<span className="cover-upload-hint">支持 JPG / PNG,建议 16:9 比例</span>
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
style={{ display: "none" }}
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleFileUpload(file)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 封面预览 */}
|
||||
<div className="cover-preview-section">
|
||||
<div className="cover-section-title">封面预览</div>
|
||||
<div className="cover-preview-box">
|
||||
{config.upload_url ? (
|
||||
<img src={config.upload_url} alt="封面预览" className="cover-preview-img" />
|
||||
) : (
|
||||
<div className="cover-preview-placeholder">
|
||||
<span className="cover-preview-icon">🖼️</span>
|
||||
<span className="cover-preview-text">
|
||||
{config.mode === "auto"
|
||||
? "AI 智能选择"
|
||||
: config.mode === "frame"
|
||||
? `帧 ${formatTime(config.frame_time)}`
|
||||
: "未上传封面"}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="cover-preview-ratio">16:9</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部 */}
|
||||
<div className="cover-footer">
|
||||
<button className="cover-reset-btn" onClick={handleReset}>
|
||||
重置封面
|
||||
</button>
|
||||
</div>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default CoverSelector
|
||||
export { default } from "./cover-selector"
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import React from "react"
|
||||
import type { CoverConfig } from "../../types"
|
||||
|
||||
interface CoverAutoModeProps {
|
||||
config: CoverConfig
|
||||
formatTime: (s: number) => string
|
||||
onUseAiSuggestion: () => void
|
||||
}
|
||||
|
||||
/** 智能封面模式面板 */
|
||||
export const CoverAutoMode: React.FC<CoverAutoModeProps> = ({
|
||||
config,
|
||||
formatTime,
|
||||
onUseAiSuggestion,
|
||||
}) => (
|
||||
<div className="cover-auto-section">
|
||||
<div className="cover-auto-desc">AI 将分析视频内容,自动选择最具吸引力的画面作为封面。</div>
|
||||
{config.ai_suggested_time !== null ? (
|
||||
<div className="cover-auto-suggestion">
|
||||
<div className="cover-auto-badge">AI 推荐</div>
|
||||
<div className="cover-auto-time">推荐时间点:{formatTime(config.ai_suggested_time)}</div>
|
||||
<button className="cover-auto-use-btn" onClick={onUseAiSuggestion}>
|
||||
使用此时间点
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="cover-auto-pending">
|
||||
<div className="cover-auto-spinner" />
|
||||
<span>AI 分析中...(生成视频后自动推荐)</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
interface CoverFrameModeProps {
|
||||
config: CoverConfig
|
||||
totalDuration: number
|
||||
formatTime: (s: number) => string
|
||||
onFrameTimeChange: (time: number) => void
|
||||
}
|
||||
|
||||
/** 抽帧选封面模式面板 */
|
||||
export const CoverFrameMode: React.FC<CoverFrameModeProps> = ({
|
||||
config,
|
||||
totalDuration,
|
||||
formatTime,
|
||||
onFrameTimeChange,
|
||||
}) => (
|
||||
<div className="cover-frame-section">
|
||||
<div className="cover-frame-preview">
|
||||
<div className="cover-frame-placeholder">
|
||||
<span className="cover-frame-icon">🎞️</span>
|
||||
<span className="cover-frame-time">{formatTime(config.frame_time)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="cover-frame-timeline">
|
||||
<div className="cover-frame-slider-header">
|
||||
<span className="cover-frame-slider-label">拖动选择封面帧</span>
|
||||
<span className="cover-frame-slider-value">{formatTime(config.frame_time)}</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
className="cover-frame-slider"
|
||||
min={0}
|
||||
max={Math.max(totalDuration, 1)}
|
||||
step={0.1}
|
||||
value={config.frame_time}
|
||||
onChange={(e) => onFrameTimeChange(Number(e.target.value))}
|
||||
/>
|
||||
<div className="cover-frame-range">
|
||||
<span>00:00</span>
|
||||
<span>{formatTime(totalDuration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="cover-frame-quick">
|
||||
<span className="cover-quick-label">快捷选帧:</span>
|
||||
{[0, 0.25, 0.5, 0.75].map((ratio) => {
|
||||
const t = totalDuration * ratio
|
||||
return (
|
||||
<button key={ratio} className="cover-quick-btn" onClick={() => onFrameTimeChange(t)}>
|
||||
{formatTime(t)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
interface CoverUploadModeProps {
|
||||
config: CoverConfig
|
||||
isDragging: boolean
|
||||
fileInputRef: React.RefObject<HTMLInputElement>
|
||||
onDragOver: (e: React.DragEvent) => void
|
||||
onDragLeave: () => void
|
||||
onDrop: (e: React.DragEvent) => void
|
||||
onAreaClick: () => void
|
||||
onFileChange: (file: File) => void
|
||||
}
|
||||
|
||||
/** 上传封面模式面板 */
|
||||
export const CoverUploadMode: React.FC<CoverUploadModeProps> = ({
|
||||
config,
|
||||
isDragging,
|
||||
fileInputRef,
|
||||
onDragOver,
|
||||
onDragLeave,
|
||||
onDrop,
|
||||
onAreaClick,
|
||||
onFileChange,
|
||||
}) => (
|
||||
<div className="cover-upload-section">
|
||||
<div
|
||||
className={`cover-upload-area${isDragging ? " dragging" : ""}`}
|
||||
onDragOver={onDragOver}
|
||||
onDragLeave={onDragLeave}
|
||||
onDrop={onDrop}
|
||||
onClick={onAreaClick}
|
||||
>
|
||||
{config.upload_url ? (
|
||||
<div className="cover-upload-preview">
|
||||
<img src={config.upload_url} alt="封面预览" />
|
||||
<div className="cover-upload-overlay">点击更换</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="cover-upload-placeholder">
|
||||
<span className="cover-upload-icon">📤</span>
|
||||
<span className="cover-upload-text">点击或拖拽上传封面图片</span>
|
||||
<span className="cover-upload-hint">支持 JPG / PNG,建议 16:9 比例</span>
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
style={{ display: "none" }}
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) onFileChange(file)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* 封面选择器
|
||||
* 抽帧选封面 + 上传自定义封面 + 智能封面推荐
|
||||
*/
|
||||
import React from "react"
|
||||
import { Drawer } from "antd"
|
||||
import type { CoverConfig, CoverMode } from "../../types"
|
||||
import { useCoverSelector, MODE_LABELS, MODE_ICONS } from "./useCoverSelector"
|
||||
import { CoverAutoMode, CoverFrameMode, CoverUploadMode } from "./CoverModePanels"
|
||||
|
||||
interface CoverSelectorProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
config: CoverConfig
|
||||
onChange: (config: CoverConfig) => void
|
||||
totalDuration: number
|
||||
}
|
||||
|
||||
const CoverSelector: React.FC<CoverSelectorProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
config,
|
||||
onChange,
|
||||
totalDuration,
|
||||
}) => {
|
||||
const {
|
||||
fileInputRef,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
update,
|
||||
handleReset,
|
||||
handleModeChange,
|
||||
handleFileUpload,
|
||||
handleDrop,
|
||||
handleUseAiSuggestion,
|
||||
formatTime,
|
||||
} = useCoverSelector({ config, onChange })
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
title="封面选择"
|
||||
placement="right"
|
||||
width={440}
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
className="cover-selector-drawer"
|
||||
>
|
||||
{/* 顶部开关 */}
|
||||
<div className="cover-header">
|
||||
<span className="cover-header-label">启用自定义封面</span>
|
||||
<label className="cover-switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={config.enabled}
|
||||
onChange={(e) => update({ enabled: e.target.checked })}
|
||||
/>
|
||||
<span className="cover-switch-slider" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* 模式选择 */}
|
||||
<div className="cover-mode-section">
|
||||
<div className="cover-section-title">封面来源</div>
|
||||
<div className="cover-mode-tabs">
|
||||
{(["auto", "frame", "upload"] as CoverMode[]).map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
className={`cover-mode-tab${config.mode === m ? " active" : ""}`}
|
||||
onClick={() => handleModeChange(m)}
|
||||
>
|
||||
<span className="cover-mode-icon">{MODE_ICONS[m]}</span>
|
||||
<span className="cover-mode-label">{MODE_LABELS[m]}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 模式内容区 */}
|
||||
<div className="cover-mode-content">
|
||||
{config.mode === "auto" && (
|
||||
<CoverAutoMode
|
||||
config={config}
|
||||
formatTime={formatTime}
|
||||
onUseAiSuggestion={handleUseAiSuggestion}
|
||||
/>
|
||||
)}
|
||||
|
||||
{config.mode === "frame" && (
|
||||
<CoverFrameMode
|
||||
config={config}
|
||||
totalDuration={totalDuration}
|
||||
formatTime={formatTime}
|
||||
onFrameTimeChange={(t) => update({ frame_time: t })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{config.mode === "upload" && (
|
||||
<CoverUploadMode
|
||||
config={config}
|
||||
isDragging={isDragging}
|
||||
fileInputRef={fileInputRef}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={handleDrop}
|
||||
onAreaClick={() => fileInputRef.current?.click()}
|
||||
onFileChange={handleFileUpload}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 封面预览 */}
|
||||
<div className="cover-preview-section">
|
||||
<div className="cover-section-title">封面预览</div>
|
||||
<div className="cover-preview-box">
|
||||
{config.upload_url ? (
|
||||
<img src={config.upload_url} alt="封面预览" className="cover-preview-img" />
|
||||
) : (
|
||||
<div className="cover-preview-placeholder">
|
||||
<span className="cover-preview-icon">🖼️</span>
|
||||
<span className="cover-preview-text">
|
||||
{config.mode === "auto"
|
||||
? "AI 智能选择"
|
||||
: config.mode === "frame"
|
||||
? `帧 ${formatTime(config.frame_time)}`
|
||||
: "未上传封面"}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="cover-preview-ratio">16:9</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部 */}
|
||||
<div className="cover-footer">
|
||||
<button className="cover-reset-btn" onClick={handleReset}>
|
||||
重置封面
|
||||
</button>
|
||||
</div>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default CoverSelector
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useCallback, useRef, useState } from "react"
|
||||
import type { CoverConfig, CoverMode } from "../../types"
|
||||
import { DEFAULT_COVER_CONFIG } from "../../types"
|
||||
|
||||
/** 封面模式标签 */
|
||||
export const MODE_LABELS: Record<CoverMode, string> = {
|
||||
auto: "智能封面",
|
||||
frame: "抽帧选封面",
|
||||
upload: "上传封面",
|
||||
}
|
||||
|
||||
/** 封面模式图标 */
|
||||
export const MODE_ICONS: Record<CoverMode, string> = {
|
||||
auto: "🤖",
|
||||
frame: "🎞️",
|
||||
upload: "📤",
|
||||
}
|
||||
|
||||
interface UseCoverSelectorOptions {
|
||||
config: CoverConfig
|
||||
onChange: (config: CoverConfig) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 封面选择器 Hook
|
||||
* 封装状态管理、文件上传、模式切换等逻辑
|
||||
*/
|
||||
export function useCoverSelector({ config, onChange }: UseCoverSelectorOptions) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
const update = useCallback(
|
||||
(partial: Partial<CoverConfig>) => {
|
||||
onChange({ ...config, ...partial })
|
||||
},
|
||||
[config, onChange],
|
||||
)
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
onChange({ ...DEFAULT_COVER_CONFIG, enabled: config.enabled })
|
||||
}, [config.enabled, onChange])
|
||||
|
||||
const handleModeChange = useCallback(
|
||||
(mode: CoverMode) => {
|
||||
update({ mode })
|
||||
},
|
||||
[update],
|
||||
)
|
||||
|
||||
const handleFileUpload = useCallback(
|
||||
(file: File) => {
|
||||
if (!file.type.startsWith("image/")) return
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e) => {
|
||||
const url = e.target?.result as string
|
||||
update({ upload_url: url, thumbnail_url: url, mode: "upload" })
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
},
|
||||
[update],
|
||||
)
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file) handleFileUpload(file)
|
||||
},
|
||||
[handleFileUpload],
|
||||
)
|
||||
|
||||
const handleUseAiSuggestion = useCallback(() => {
|
||||
if (config.ai_suggested_time !== null) {
|
||||
update({ frame_time: config.ai_suggested_time, mode: "frame" })
|
||||
}
|
||||
}, [config.ai_suggested_time, update])
|
||||
|
||||
const formatTime = (seconds: number) => {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = Math.floor(seconds % 60)
|
||||
const ms = Math.floor((seconds % 1) * 10)
|
||||
return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}.${ms}`
|
||||
}
|
||||
|
||||
return {
|
||||
fileInputRef,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
update,
|
||||
handleReset,
|
||||
handleModeChange,
|
||||
handleFileUpload,
|
||||
handleDrop,
|
||||
handleUseAiSuggestion,
|
||||
formatTime,
|
||||
}
|
||||
}
|
||||
Executable → Regular
+258
-46
@@ -1,88 +1,300 @@
|
||||
/**
|
||||
* 任务历史页面 — V21 设计系统
|
||||
* 页面头部 + 圆角胶囊 Tab 筛选(含计数)+ 卡片式任务列表 + 分页 + 空状态
|
||||
* 使用 useQuery 对接后端真实 API(api/tasks.ts)
|
||||
*/
|
||||
import React from "react"
|
||||
import { PageHeader, LoadingState, ErrorState, EmptyState } from "./components/States"
|
||||
import { HistoryTabs, TaskItem, Pagination } from "./components/TaskList"
|
||||
import { useTaskHistory } from "./hooks/useTaskHistory"
|
||||
import React, { useState } from "react"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { Button } from "@/components/ui"
|
||||
import { getUserTasks, retryTask, type TaskItem } from "@/api/tasks"
|
||||
import "./history.css"
|
||||
|
||||
/* ============================================================
|
||||
* 类型 & 常量
|
||||
* ============================================================ */
|
||||
type TaskStatus = "completed" | "processing" | "pending" | "failed"
|
||||
|
||||
const statusLabel: Record<TaskStatus, string> = {
|
||||
completed: "已完成",
|
||||
processing: "进行中",
|
||||
pending: "排队中",
|
||||
failed: "失败",
|
||||
}
|
||||
|
||||
/** 将后端 status 字符串映射为前端 TaskStatus */
|
||||
const normalizeStatus = (s: string): TaskStatus => {
|
||||
const map: Record<string, TaskStatus> = {
|
||||
completed: "completed",
|
||||
succeeded: "completed",
|
||||
success: "completed",
|
||||
processing: "processing",
|
||||
running: "processing",
|
||||
pending: "pending",
|
||||
queued: "pending",
|
||||
failed: "failed",
|
||||
error: "failed",
|
||||
}
|
||||
return map[s] ?? "pending"
|
||||
}
|
||||
|
||||
/** 格式化日期 */
|
||||
const formatDate = (iso?: string | null): string => {
|
||||
if (!iso) return "—"
|
||||
const d = new Date(iso)
|
||||
if (isNaN(d.getTime())) return "—"
|
||||
const pad = (n: number) => String(n).padStart(2, "0")
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
* Tab 配置
|
||||
* ============================================================ */
|
||||
interface TabConfig {
|
||||
key: string
|
||||
label: string
|
||||
statusFilter?: TaskStatus
|
||||
}
|
||||
|
||||
const tabs: TabConfig[] = [
|
||||
{ key: "all", label: "全部" },
|
||||
{ key: "processing", label: "进行中", statusFilter: "processing" },
|
||||
{ key: "completed", label: "已完成", statusFilter: "completed" },
|
||||
{ key: "failed", label: "失败", statusFilter: "failed" },
|
||||
]
|
||||
|
||||
/* ============================================================
|
||||
* 分页配置
|
||||
* ============================================================ */
|
||||
const PAGE_SIZE = 10
|
||||
|
||||
/* ============================================================
|
||||
* 组件
|
||||
* ============================================================ */
|
||||
const TaskHistory: React.FC = () => {
|
||||
const [activeTab, setActiveTab] = useState("all")
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// ── 获取任务列表 ──
|
||||
const {
|
||||
activeTab,
|
||||
currentPage,
|
||||
totalPages,
|
||||
tabs,
|
||||
tabCounts,
|
||||
paginatedTasks,
|
||||
data: tasks = [],
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
retryLoading,
|
||||
setCurrentPage,
|
||||
handleTabChange,
|
||||
handleRetry,
|
||||
handleView,
|
||||
refetch,
|
||||
} = useTaskHistory()
|
||||
} = useQuery<TaskItem[], Error>({
|
||||
queryKey: ["tasks"],
|
||||
queryFn: getUserTasks,
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
// Loading 状态
|
||||
// ── 重试任务 mutation ──
|
||||
const retryMutation = useMutation({
|
||||
mutationFn: retryTask,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["tasks"] })
|
||||
},
|
||||
})
|
||||
|
||||
// 将后端数据映射为页面展示用的结构
|
||||
const mappedTasks = tasks.map((t) => ({
|
||||
id: t.id,
|
||||
name: t.user_message || t.task_type,
|
||||
type: t.task_type,
|
||||
template: t.template_id,
|
||||
status: normalizeStatus(t.status),
|
||||
date: formatDate(t.created_at),
|
||||
duration: undefined as string | undefined,
|
||||
progress: t.progress,
|
||||
retryable: t.retryable,
|
||||
errorMessage: t.error_message,
|
||||
}))
|
||||
|
||||
// 获取当前 Tab 的筛选状态
|
||||
const currentTab = tabs.find((t) => t.key === activeTab)
|
||||
const statusFilter = currentTab?.statusFilter
|
||||
|
||||
// 过滤任务
|
||||
const filteredTasks = statusFilter
|
||||
? mappedTasks.filter((t) => t.status === statusFilter)
|
||||
: mappedTasks
|
||||
|
||||
// 计算各 Tab 的数量
|
||||
const tabCounts: Record<string, number> = {
|
||||
all: mappedTasks.length,
|
||||
processing: mappedTasks.filter((t) => t.status === "processing").length,
|
||||
completed: mappedTasks.filter((t) => t.status === "completed").length,
|
||||
failed: mappedTasks.filter((t) => t.status === "failed").length,
|
||||
}
|
||||
|
||||
// 分页
|
||||
const totalPages = Math.ceil(filteredTasks.length / PAGE_SIZE)
|
||||
const paginatedTasks = filteredTasks.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE)
|
||||
|
||||
// 切换 Tab 时重置页码
|
||||
const handleTabChange = (key: string) => {
|
||||
setActiveTab(key)
|
||||
setCurrentPage(1)
|
||||
}
|
||||
|
||||
// 重试任务
|
||||
const handleRetry = (taskId: string) => {
|
||||
retryMutation.mutate(taskId)
|
||||
}
|
||||
|
||||
// 查看任务详情
|
||||
const handleView = (taskId: string) => {
|
||||
// TODO: 跳转到任务详情页(待路由实现)
|
||||
console.log("查看任务:", taskId)
|
||||
}
|
||||
|
||||
// ── Loading 状态 ──
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="xx-history-page">
|
||||
<PageHeader />
|
||||
<LoadingState />
|
||||
<div className="xx-history-header">
|
||||
<h2>任务历史</h2>
|
||||
<p>查看和管理所有生成任务</p>
|
||||
</div>
|
||||
<div className="xx-history-empty">
|
||||
<div className="xx-history-empty-icon">⏳</div>
|
||||
<h3>加载中...</h3>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Error 状态
|
||||
// ── Error 状态 ──
|
||||
if (isError) {
|
||||
return (
|
||||
<div className="xx-history-page">
|
||||
<PageHeader />
|
||||
<ErrorState message={error?.message} onRetry={() => refetch()} />
|
||||
<div className="xx-history-header">
|
||||
<h2>任务历史</h2>
|
||||
<p>查看和管理所有生成任务</p>
|
||||
</div>
|
||||
<div className="xx-history-empty">
|
||||
<div className="xx-history-empty-icon">❌</div>
|
||||
<h3>加载失败</h3>
|
||||
<p>{error?.message || "网络异常,请稍后重试"}</p>
|
||||
<Button buttonType="primary" buttonSize="md" onClick={() => refetch()}>
|
||||
重新加载
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const totalCount = tabCounts[activeTab] ?? paginatedTasks.length
|
||||
|
||||
return (
|
||||
<div className="xx-history-page">
|
||||
<PageHeader />
|
||||
{/* ── 页面头部 ──────────────────────────────────────────── */}
|
||||
<div className="xx-history-header">
|
||||
<h2>任务历史</h2>
|
||||
<p>查看和管理所有生成任务</p>
|
||||
</div>
|
||||
|
||||
<HistoryTabs
|
||||
tabs={tabs}
|
||||
activeTab={activeTab}
|
||||
tabCounts={tabCounts}
|
||||
onChange={handleTabChange}
|
||||
/>
|
||||
{/* ── Tab 切换 ──────────────────────────────────────────── */}
|
||||
<div className="xx-history-tabs">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
className={`xx-history-tab${activeTab === tab.key ? " active" : ""}`}
|
||||
onClick={() => handleTabChange(tab.key)}
|
||||
>
|
||||
{tab.label}
|
||||
<span className="xx-history-tab-count">{tabCounts[tab.key]}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 任务列表 */}
|
||||
{/* ── 任务列表 ──────────────────────────────────────────── */}
|
||||
{paginatedTasks.length === 0 ? (
|
||||
<EmptyState activeTab={activeTab} />
|
||||
<div className="xx-history-empty">
|
||||
<div className="xx-history-empty-icon">📭</div>
|
||||
<h3>暂无任务记录</h3>
|
||||
<p>{activeTab === "all" ? "点击上方按钮开始创建任务" : "当前分类下没有任务"}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="xx-history-task-list">
|
||||
{paginatedTasks.map((task) => (
|
||||
<TaskItem
|
||||
key={task.id}
|
||||
task={task}
|
||||
onRetry={handleRetry}
|
||||
onView={handleView}
|
||||
retryLoading={retryLoading}
|
||||
/>
|
||||
<div key={task.id} className="xx-history-task-item">
|
||||
{/* 任务信息 */}
|
||||
<div className="xx-history-task-info">
|
||||
<h4>{task.name}</h4>
|
||||
<span>
|
||||
{task.type} · 模板:{task.template}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 状态标签 */}
|
||||
<span className={`xx-history-status xx-history-status--${task.status}`}>
|
||||
{statusLabel[task.status]}
|
||||
</span>
|
||||
|
||||
{/* 时间区 */}
|
||||
<div className="xx-history-task-time">
|
||||
<span>{task.date}</span>
|
||||
{task.status === "completed" ? (
|
||||
<span>完成</span>
|
||||
) : task.status === "processing" ? (
|
||||
<span>进度 {task.progress}%</span>
|
||||
) : task.status === "failed" ? (
|
||||
<span>{task.errorMessage || "请重试"}</span>
|
||||
) : (
|
||||
<span>等待中</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="xx-history-task-action">
|
||||
{task.status === "failed" && task.retryable ? (
|
||||
<Button
|
||||
buttonType="ghost"
|
||||
buttonSize="sm"
|
||||
onClick={() => handleRetry(task.id)}
|
||||
disabled={retryMutation.isPending}
|
||||
>
|
||||
{retryMutation.isPending ? "重试中..." : "重试"}
|
||||
</Button>
|
||||
) : (
|
||||
<Button buttonType="ghost" buttonSize="sm" onClick={() => handleView(task.id)}>
|
||||
查看
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
total={totalCount}
|
||||
onChange={setCurrentPage}
|
||||
/>
|
||||
{/* ── 分页 ──────────────────────────────────────────────── */}
|
||||
{totalPages > 1 && (
|
||||
<div className="xx-history-pagination">
|
||||
<button
|
||||
className="xx-history-page-btn"
|
||||
disabled={currentPage === 1}
|
||||
onClick={() => setCurrentPage(currentPage - 1)}
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
|
||||
<button
|
||||
key={page}
|
||||
className={`xx-history-page-btn${currentPage === page ? " active" : ""}`}
|
||||
onClick={() => setCurrentPage(page)}
|
||||
>
|
||||
{page}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className="xx-history-page-btn"
|
||||
disabled={currentPage === totalPages}
|
||||
onClick={() => setCurrentPage(currentPage + 1)}
|
||||
>
|
||||
›
|
||||
</button>
|
||||
<span className="xx-history-page-info">共 {filteredTasks.length} 条</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import React from "react"
|
||||
import { Button } from "@/components/ui"
|
||||
|
||||
interface LoadingStateProps {
|
||||
title?: string
|
||||
}
|
||||
|
||||
/** 加载状态 */
|
||||
export const LoadingState: React.FC<LoadingStateProps> = ({ title = "加载中..." }) => (
|
||||
<div className="xx-history-empty">
|
||||
<div className="xx-history-empty-icon">⏳</div>
|
||||
<h3>{title}</h3>
|
||||
</div>
|
||||
)
|
||||
|
||||
interface ErrorStateProps {
|
||||
message?: string
|
||||
onRetry: () => void
|
||||
}
|
||||
|
||||
/** 错误状态 */
|
||||
export const ErrorState: React.FC<ErrorStateProps> = ({ message, onRetry }) => (
|
||||
<div className="xx-history-empty">
|
||||
<div className="xx-history-empty-icon">❌</div>
|
||||
<h3>加载失败</h3>
|
||||
<p>{message || "网络异常,请稍后重试"}</p>
|
||||
<Button buttonType="primary" buttonSize="md" onClick={onRetry}>
|
||||
重新加载
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
|
||||
interface EmptyStateProps {
|
||||
activeTab?: string
|
||||
}
|
||||
|
||||
/** 空状态 */
|
||||
export const EmptyState: React.FC<EmptyStateProps> = ({ activeTab = "all" }) => (
|
||||
<div className="xx-history-empty">
|
||||
<div className="xx-history-empty-icon">📭</div>
|
||||
<h3>暂无任务记录</h3>
|
||||
<p>{activeTab === "all" ? "点击上方按钮开始创建任务" : "当前分类下没有任务"}</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
/** 页面头部 */
|
||||
export const PageHeader: React.FC = () => (
|
||||
<div className="xx-history-header">
|
||||
<h2>任务历史</h2>
|
||||
<p>查看和管理所有生成任务</p>
|
||||
</div>
|
||||
)
|
||||
@@ -1,142 +0,0 @@
|
||||
import React from "react"
|
||||
import { Button } from "@/components/ui"
|
||||
import type { TabConfig } from "../constants"
|
||||
import type { MappedTask } from "../hooks/useTaskHistory"
|
||||
import { statusLabel } from "../constants"
|
||||
|
||||
interface HistoryTabsProps {
|
||||
tabs: TabConfig[]
|
||||
activeTab: string
|
||||
tabCounts: Record<string, number>
|
||||
onChange: (key: string) => void
|
||||
}
|
||||
|
||||
/** Tab 切换栏 */
|
||||
export const HistoryTabs: React.FC<HistoryTabsProps> = ({
|
||||
tabs,
|
||||
activeTab,
|
||||
tabCounts,
|
||||
onChange,
|
||||
}) => (
|
||||
<div className="xx-history-tabs">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
className={`xx-history-tab${activeTab === tab.key ? " active" : ""}`}
|
||||
onClick={() => onChange(tab.key)}
|
||||
>
|
||||
{tab.label}
|
||||
<span className="xx-history-tab-count">{tabCounts[tab.key]}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
interface TaskItemProps {
|
||||
task: MappedTask
|
||||
onRetry: (id: string) => void
|
||||
onView: (id: string) => void
|
||||
retryLoading?: boolean
|
||||
}
|
||||
|
||||
/** 单个任务卡片 */
|
||||
export const TaskItem: React.FC<TaskItemProps> = ({ task, onRetry, onView, retryLoading }) => {
|
||||
const getSubText = () => {
|
||||
switch (task.status) {
|
||||
case "completed":
|
||||
return "完成"
|
||||
case "processing":
|
||||
return `进度 ${task.progress}%`
|
||||
case "failed":
|
||||
return task.errorMessage || "请重试"
|
||||
default:
|
||||
return "等待中"
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="xx-history-task-item">
|
||||
{/* 任务信息 */}
|
||||
<div className="xx-history-task-info">
|
||||
<h4>{task.name}</h4>
|
||||
<span>
|
||||
{task.type} · 模板:{task.template}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 状态标签 */}
|
||||
<span className={`xx-history-status xx-history-status--${task.status}`}>
|
||||
{statusLabel[task.status]}
|
||||
</span>
|
||||
|
||||
{/* 时间区 */}
|
||||
<div className="xx-history-task-time">
|
||||
<span>{task.date}</span>
|
||||
<span>{getSubText()}</span>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="xx-history-task-action">
|
||||
{task.status === "failed" && task.retryable ? (
|
||||
<Button
|
||||
buttonType="ghost"
|
||||
buttonSize="sm"
|
||||
onClick={() => onRetry(task.id)}
|
||||
disabled={retryLoading}
|
||||
>
|
||||
{retryLoading ? "重试中..." : "重试"}
|
||||
</Button>
|
||||
) : (
|
||||
<Button buttonType="ghost" buttonSize="sm" onClick={() => onView(task.id)}>
|
||||
查看
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface PaginationProps {
|
||||
currentPage: number
|
||||
totalPages: number
|
||||
total: number
|
||||
onChange: (page: number) => void
|
||||
}
|
||||
|
||||
/** 分页组件 */
|
||||
export const Pagination: React.FC<PaginationProps> = ({
|
||||
currentPage,
|
||||
totalPages,
|
||||
total,
|
||||
onChange,
|
||||
}) => {
|
||||
if (totalPages <= 1) return null
|
||||
return (
|
||||
<div className="xx-history-pagination">
|
||||
<button
|
||||
className="xx-history-page-btn"
|
||||
disabled={currentPage === 1}
|
||||
onClick={() => onChange(currentPage - 1)}
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
|
||||
<button
|
||||
key={page}
|
||||
className={`xx-history-page-btn${currentPage === page ? " active" : ""}`}
|
||||
onClick={() => onChange(page)}
|
||||
>
|
||||
{page}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className="xx-history-page-btn"
|
||||
disabled={currentPage === totalPages}
|
||||
onClick={() => onChange(currentPage + 1)}
|
||||
>
|
||||
›
|
||||
</button>
|
||||
<span className="xx-history-page-info">共 {total} 条</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/** 任务状态 */
|
||||
export type TaskStatus = "completed" | "processing" | "pending" | "failed"
|
||||
|
||||
/** 状态标签 */
|
||||
export const statusLabel: Record<TaskStatus, string> = {
|
||||
completed: "已完成",
|
||||
processing: "进行中",
|
||||
pending: "排队中",
|
||||
failed: "失败",
|
||||
}
|
||||
|
||||
/** Tab 配置 */
|
||||
export interface TabConfig {
|
||||
key: string
|
||||
label: string
|
||||
statusFilter?: TaskStatus
|
||||
}
|
||||
|
||||
/** 默认 Tab 列表 */
|
||||
export const TABS: TabConfig[] = [
|
||||
{ key: "all", label: "全部" },
|
||||
{ key: "processing", label: "进行中", statusFilter: "processing" },
|
||||
{ key: "completed", label: "已完成", statusFilter: "completed" },
|
||||
{ key: "failed", label: "失败", statusFilter: "failed" },
|
||||
]
|
||||
|
||||
/** 每页数量 */
|
||||
export const PAGE_SIZE = 10
|
||||
@@ -1,131 +0,0 @@
|
||||
import { useState, useMemo, useCallback } from "react"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { getUserTasks, retryTask, type TaskItem } from "@/api/tasks"
|
||||
import { TABS, PAGE_SIZE, type TabConfig } from "../constants"
|
||||
import { normalizeStatus, formatDate } from "../utils"
|
||||
|
||||
/** 映射后的任务列表项 */
|
||||
export interface MappedTask {
|
||||
id: string
|
||||
name: string
|
||||
type: string
|
||||
template?: string
|
||||
status: "completed" | "processing" | "pending" | "failed"
|
||||
date: string
|
||||
progress?: number
|
||||
retryable?: boolean
|
||||
errorMessage?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务历史业务 Hook
|
||||
*/
|
||||
export const useTaskHistory = () => {
|
||||
const [activeTab, setActiveTab] = useState("all")
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// 获取任务列表
|
||||
const {
|
||||
data: tasks = [],
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
refetch,
|
||||
} = useQuery<TaskItem[], Error>({
|
||||
queryKey: ["tasks"],
|
||||
queryFn: getUserTasks,
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
// 重试 mutation
|
||||
const retryMutation = useMutation({
|
||||
mutationFn: retryTask,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["tasks"] })
|
||||
},
|
||||
})
|
||||
|
||||
// 映射后端数据
|
||||
const mappedTasks: MappedTask[] = useMemo(
|
||||
() =>
|
||||
tasks.map((t) => ({
|
||||
id: t.id,
|
||||
name: t.user_message || t.task_type,
|
||||
type: t.task_type,
|
||||
template: t.template_id,
|
||||
status: normalizeStatus(t.status),
|
||||
date: formatDate(t.created_at),
|
||||
progress: t.progress,
|
||||
retryable: t.retryable,
|
||||
errorMessage: t.error_message,
|
||||
})),
|
||||
[tasks],
|
||||
)
|
||||
|
||||
// 当前 Tab 筛选
|
||||
const currentTabConfig: TabConfig | undefined = TABS.find((t) => t.key === activeTab)
|
||||
const statusFilter = currentTabConfig?.statusFilter
|
||||
|
||||
// 过滤任务
|
||||
const filteredTasks = useMemo(
|
||||
() => (statusFilter ? mappedTasks.filter((t) => t.status === statusFilter) : mappedTasks),
|
||||
[mappedTasks, statusFilter],
|
||||
)
|
||||
|
||||
// 各 Tab 计数
|
||||
const tabCounts: Record<string, number> = useMemo(
|
||||
() => ({
|
||||
all: mappedTasks.length,
|
||||
processing: mappedTasks.filter((t) => t.status === "processing").length,
|
||||
completed: mappedTasks.filter((t) => t.status === "completed").length,
|
||||
failed: mappedTasks.filter((t) => t.status === "failed").length,
|
||||
}),
|
||||
[mappedTasks],
|
||||
)
|
||||
|
||||
// 分页
|
||||
const totalPages = Math.ceil(filteredTasks.length / PAGE_SIZE)
|
||||
const paginatedTasks = filteredTasks.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE)
|
||||
|
||||
// 切换 Tab
|
||||
const handleTabChange = useCallback((key: string) => {
|
||||
setActiveTab(key)
|
||||
setCurrentPage(1)
|
||||
}, [])
|
||||
|
||||
// 重试
|
||||
const handleRetry = useCallback(
|
||||
(taskId: string) => {
|
||||
retryMutation.mutate(taskId)
|
||||
},
|
||||
[retryMutation],
|
||||
)
|
||||
|
||||
// 查看详情
|
||||
const handleView = useCallback((taskId: string) => {
|
||||
// TODO: 跳转到任务详情页(待路由实现)
|
||||
console.log("查看任务:", taskId)
|
||||
}, [])
|
||||
|
||||
return {
|
||||
// 状态
|
||||
activeTab,
|
||||
currentPage,
|
||||
totalPages,
|
||||
// 数据
|
||||
tabs: TABS,
|
||||
tabCounts,
|
||||
paginatedTasks,
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
retryLoading: retryMutation.isPending,
|
||||
// 操作
|
||||
setCurrentPage,
|
||||
handleTabChange,
|
||||
handleRetry,
|
||||
handleView,
|
||||
refetch,
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { TaskStatus } from "./constants"
|
||||
|
||||
/** 将后端 status 字符串映射为前端 TaskStatus */
|
||||
export const normalizeStatus = (s: string): TaskStatus => {
|
||||
const map: Record<string, TaskStatus> = {
|
||||
completed: "completed",
|
||||
succeeded: "completed",
|
||||
success: "completed",
|
||||
processing: "processing",
|
||||
running: "processing",
|
||||
pending: "pending",
|
||||
queued: "pending",
|
||||
failed: "failed",
|
||||
error: "failed",
|
||||
}
|
||||
return map[s] ?? "pending"
|
||||
}
|
||||
|
||||
/** 格式化日期 */
|
||||
export const formatDate = (iso?: string | null): string => {
|
||||
if (!iso) return "—"
|
||||
const d = new Date(iso)
|
||||
if (isNaN(d.getTime())) return "—"
|
||||
const pad = (n: number) => String(n).padStart(2, "0")
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
Reference in New Issue
Block a user