Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2d7f1c3a71 | |||
| 8637ed1576 | |||
| 6bcd255e85 | |||
| 17c6b0e3bd |
@@ -1,23 +1,23 @@
|
||||
name: CI/CD Pipeline
|
||||
true:
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
tags:
|
||||
- "v*"
|
||||
- v*
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
schedule:
|
||||
- cron: "0 19 * * *"
|
||||
- cron: '0 19 * * *' # UTC 19:00 = 北京时间凌晨3:00,每日全量CI回归
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
reason:
|
||||
description: 触发原因
|
||||
description: "触发原因"
|
||||
required: false
|
||||
default: 手动触发 - CI漏触发补跑
|
||||
default: "手动触发 - CI漏触发补跑"
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
@@ -4,7 +4,6 @@ export const ROUTE_TITLE_MAP: Record<string, string> = {
|
||||
"/app/generate": "智能剪辑",
|
||||
"/app/assets": "视频库",
|
||||
"/app/voices": "配音库",
|
||||
"/app/titles": "标题库",
|
||||
"/app/products": "成片库",
|
||||
"/app/templates": "模板库",
|
||||
"/app/history": "任务历史",
|
||||
|
||||
@@ -6,7 +6,6 @@ import React from "react"
|
||||
import {
|
||||
DashboardOutlined,
|
||||
FileOutlined,
|
||||
FileTextOutlined,
|
||||
AudioOutlined,
|
||||
EditOutlined,
|
||||
VideoCameraOutlined,
|
||||
@@ -51,12 +50,6 @@ export const NAV_ITEMS: NavItem[] = [
|
||||
path: "/app/assets",
|
||||
icon: React.createElement(FileOutlined),
|
||||
},
|
||||
{
|
||||
key: "titles",
|
||||
label: "标题库",
|
||||
path: "/app/titles",
|
||||
icon: React.createElement(FileTextOutlined),
|
||||
},
|
||||
{
|
||||
key: "scripts",
|
||||
label: "文案库",
|
||||
@@ -160,12 +153,6 @@ export const NAV_GROUPS: NavGroup[] = [
|
||||
path: "/app/voices",
|
||||
icon: React.createElement(AudioOutlined),
|
||||
},
|
||||
{
|
||||
key: "titles",
|
||||
label: "标题库",
|
||||
path: "/app/titles",
|
||||
icon: React.createElement(FileTextOutlined),
|
||||
},
|
||||
{
|
||||
key: "scripts",
|
||||
label: "文案库",
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
/**
|
||||
* 文案库页面 — Issue #1811(v2 完整版) + #1893 AI 能力
|
||||
* 文案库页面 — Issue #1811(#1894 方向修正后)
|
||||
* 功能:
|
||||
* - 列表页:卡片列表,搜索(标题/正文)、分类标签筛选、分页
|
||||
* 每条卡片展示:title、content 前 100 字摘要、title_text、分类 Tag、tags、使用次数、时间
|
||||
* 每条卡片展示:title(标题)、content 前 100 字摘要、分类 Tag、tags、使用次数、时间
|
||||
* 操作:编辑 / 删除 / 复制 / 使用(跳创作页预填)
|
||||
* - 新建/编辑弹窗:title、content 多行、segments(按空行自动拆分+手动编辑)、title_text、title_category、
|
||||
* title_config(字体/颜色/位置/字号)、tags
|
||||
* - #1893 AI 能力:
|
||||
* - 新建/编辑弹窗:标题(原"名称")、正文(含 AI 改写)、分类、标签
|
||||
* - #1893/#1894 AI 能力:
|
||||
* - 顶部「🎬 从抖音提取」按钮 → 输入抖音链接 → ASR 提取文案 → 自动填充到新建弹窗
|
||||
* - 新建/编辑弹窗中 content 下方「✨ AI 改写」按钮(带风格选择) → 对比弹窗让用户确认
|
||||
* - title 旁「✨ AI 生成标题」按钮 → 候选列表一键填入
|
||||
* - 正文下方「✨ AI 改写」按钮 → 点击直接执行(美化 loading spinner + "正在改写..."),
|
||||
* 成功自动替换正文并 toast「改写成功」1s 自动关闭;失败 toast 错误
|
||||
* - 标题旁「✨ AI 生成标题」按钮 → 候选列表一键填入
|
||||
* - 删除确认(Popconfirm)
|
||||
* - 对接 api/scripts CRUD(mock 阶段 SCRIPTS_API_MOCK=true,AI 接口始终走真实 API)
|
||||
*
|
||||
* 风格对齐标题库(.xx-scripts-* 命名,沿用 CSS 变量)
|
||||
*/
|
||||
import React, { useCallback, useEffect, useState } from "react"
|
||||
import {
|
||||
@@ -22,8 +20,6 @@ import {
|
||||
Empty,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
List,
|
||||
Modal,
|
||||
Pagination,
|
||||
Popconfirm,
|
||||
@@ -59,13 +55,7 @@ import {
|
||||
aiGenerateTitles,
|
||||
REWRITE_STYLE_OPTIONS,
|
||||
} from "@/api/scripts"
|
||||
import type {
|
||||
ScriptItem,
|
||||
ScriptCategory,
|
||||
ScriptUpsertRequest,
|
||||
RewriteStyle,
|
||||
AiRewriteResponse,
|
||||
} from "@/api/scripts"
|
||||
import type { ScriptItem, ScriptCategory, ScriptUpsertRequest, RewriteStyle } from "@/api/scripts"
|
||||
import { SCRIPT_CATEGORY_LABEL } from "@/api/scripts"
|
||||
import "./scripts.css"
|
||||
|
||||
@@ -81,19 +71,6 @@ const CATEGORY_OPTIONS: { value: ScriptCategory | "all"; label: string }[] = [
|
||||
})),
|
||||
]
|
||||
|
||||
const FONT_OPTIONS = [
|
||||
{ value: "default", label: "默认" },
|
||||
{ value: "bold", label: "粗体" },
|
||||
{ value: "handwritten", label: "手写" },
|
||||
{ value: "serif", label: "衬线" },
|
||||
]
|
||||
|
||||
const POSITION_OPTIONS = [
|
||||
{ value: "top", label: "顶部" },
|
||||
{ value: "center", label: "居中" },
|
||||
{ value: "bottom", label: "底部" },
|
||||
] as const
|
||||
|
||||
/** 提取后端返回的错误 detail(全局拦截器可能已弹 toast,但这里再兜一层) */
|
||||
function extractErrMsg(err: unknown, fallback: string): string {
|
||||
const e = err as {
|
||||
@@ -132,11 +109,9 @@ const ScriptLibrary: React.FC = () => {
|
||||
const [douyinUrl, setDouyinUrl] = useState("")
|
||||
const [douyinLoading, setDouyinLoading] = useState(false)
|
||||
|
||||
// AI 改写
|
||||
const [rewriteModalOpen, setRewriteModalOpen] = useState(false)
|
||||
// AI 改写(#1894: 点击直接执行,美化 loading + 1s 自动关闭 toast,不弹确认弹窗)
|
||||
const [rewriteStyle, setRewriteStyle] = useState<RewriteStyle>("口语化")
|
||||
const [rewriteLoading, setRewriteLoading] = useState(false)
|
||||
const [rewriteResult, setRewriteResult] = useState<AiRewriteResponse | null>(null)
|
||||
|
||||
// AI 生成标题
|
||||
const [titleGenLoading, setTitleGenLoading] = useState(false)
|
||||
@@ -176,19 +151,8 @@ const ScriptLibrary: React.FC = () => {
|
||||
content: "",
|
||||
segments: [],
|
||||
tags: [],
|
||||
title_text: "",
|
||||
title_category: "other",
|
||||
title_config: {
|
||||
font: "default",
|
||||
color: "#ffffff",
|
||||
stroke: "#000000",
|
||||
position: "center",
|
||||
size: 48,
|
||||
bold: true,
|
||||
italic: false,
|
||||
},
|
||||
})
|
||||
setRewriteResult(null)
|
||||
setTitleCandidates([])
|
||||
}
|
||||
|
||||
@@ -205,17 +169,8 @@ const ScriptLibrary: React.FC = () => {
|
||||
content: item.content,
|
||||
segments: item.segments ?? item.content.split(/\n\n+/).filter(Boolean),
|
||||
tags: item.tags ?? [],
|
||||
title_text: item.title_text ?? "",
|
||||
title_category: item.title_category ?? "other",
|
||||
title_config: item.title_config ?? {
|
||||
font: "default",
|
||||
color: "#ffffff",
|
||||
stroke: "#000000",
|
||||
position: "center",
|
||||
size: 48,
|
||||
},
|
||||
})
|
||||
setRewriteResult(null)
|
||||
setTitleCandidates([])
|
||||
setModalOpen(true)
|
||||
}
|
||||
@@ -223,7 +178,6 @@ const ScriptLibrary: React.FC = () => {
|
||||
const closeModal = () => {
|
||||
setModalOpen(false)
|
||||
setEditing(null)
|
||||
setRewriteResult(null)
|
||||
setTitleCandidates([])
|
||||
}
|
||||
|
||||
@@ -237,9 +191,8 @@ const ScriptLibrary: React.FC = () => {
|
||||
content: values.content,
|
||||
segments: values.segments?.filter(Boolean) ?? values.content.split(/\n\n+/).filter(Boolean),
|
||||
tags: values.tags ?? [],
|
||||
title_text: values.title_text?.trim() || undefined,
|
||||
title_category: values.title_category,
|
||||
title_config: values.title_config,
|
||||
// #1894: 配套标题 / 标题样式配置字段已从 UI 移除,后端即将删除,不再传
|
||||
}
|
||||
if (editing) {
|
||||
await updateScript(editing.id, payload)
|
||||
@@ -343,17 +296,7 @@ const ScriptLibrary: React.FC = () => {
|
||||
title: "",
|
||||
content: res.text,
|
||||
tags: [],
|
||||
title_text: "",
|
||||
title_category: "other",
|
||||
title_config: {
|
||||
font: "default",
|
||||
color: "#ffffff",
|
||||
stroke: "#000000",
|
||||
position: "center",
|
||||
size: 48,
|
||||
bold: true,
|
||||
italic: false,
|
||||
},
|
||||
})
|
||||
setModalOpen(true)
|
||||
} catch (err) {
|
||||
@@ -363,18 +306,18 @@ const ScriptLibrary: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** 执行 AI 改写,结果写入 rewriteResult 让用户对比确认 */
|
||||
const handleAiRewrite = async () => {
|
||||
/** #1894: 执行 AI 改写,完成后自动替换正文并 toast 1 秒关闭 */
|
||||
const handleAiRewrite = async (style: RewriteStyle) => {
|
||||
const content = form.getFieldValue("content") as string | undefined
|
||||
if (!content || !content.trim()) {
|
||||
message.warning("请先填写文案正文再改写")
|
||||
return
|
||||
}
|
||||
setRewriteLoading(true)
|
||||
setRewriteResult(null)
|
||||
try {
|
||||
const res = await aiRewriteScript({ content, style: rewriteStyle })
|
||||
setRewriteResult(res)
|
||||
const res = await aiRewriteScript({ content, style })
|
||||
form.setFieldsValue({ content: res.rewritten })
|
||||
message.success({ content: "改写成功", duration: 1 })
|
||||
} catch (err) {
|
||||
message.error(extractErrMsg(err, "AI 改写失败"))
|
||||
} finally {
|
||||
@@ -382,15 +325,6 @@ const ScriptLibrary: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** 应用改写结果:替换 content 字段,关闭改写弹窗 */
|
||||
const applyRewrite = () => {
|
||||
if (!rewriteResult) return
|
||||
form.setFieldsValue({ content: rewriteResult.rewritten })
|
||||
setRewriteResult(null)
|
||||
setRewriteModalOpen(false)
|
||||
message.success("已应用改写结果")
|
||||
}
|
||||
|
||||
/** 执行 AI 生成标题,生成候选 */
|
||||
const handleGenerateTitles = async () => {
|
||||
const content = form.getFieldValue("content") as string | undefined
|
||||
@@ -527,13 +461,6 @@ const ScriptLibrary: React.FC = () => {
|
||||
|
||||
<div className="xx-script-preview">{preview(s.content)}</div>
|
||||
|
||||
{s.title_text && (
|
||||
<div className="xx-script-title-text">
|
||||
<span className="xx-script-label">配套标题:</span>
|
||||
{s.title_text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{s.tags && s.tags.length > 0 && (
|
||||
<div className="xx-script-tags">
|
||||
<TagsOutlined
|
||||
@@ -590,21 +517,13 @@ const ScriptLibrary: React.FC = () => {
|
||||
layout="vertical"
|
||||
initialValues={{
|
||||
title_category: "other",
|
||||
title_config: {
|
||||
font: "default",
|
||||
color: "#ffffff",
|
||||
stroke: "#000000",
|
||||
position: "center",
|
||||
size: 48,
|
||||
bold: true,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Form.Item
|
||||
name="title"
|
||||
label={
|
||||
<span>
|
||||
名称
|
||||
标题
|
||||
{/* #1893 UX: disabled 时原生 title 在 antd Button 上不触发,
|
||||
用 Tooltip + span 包裹保证提示可见 */}
|
||||
<Tooltip
|
||||
@@ -626,9 +545,9 @@ const ScriptLibrary: React.FC = () => {
|
||||
</Tooltip>
|
||||
</span>
|
||||
}
|
||||
rules={[{ required: true, message: "请填写文案名称" }, { max: 200 }]}
|
||||
rules={[{ required: true, message: "请填写视频标题" }, { max: 200 }]}
|
||||
>
|
||||
<Input placeholder="给这段文案起个名字" maxLength={200} />
|
||||
<Input placeholder="输入视频标题" maxLength={200} />
|
||||
</Form.Item>
|
||||
|
||||
{/* AI 生成标题候选列表 */}
|
||||
@@ -661,9 +580,9 @@ const ScriptLibrary: React.FC = () => {
|
||||
<TextArea placeholder="在这里输入文案正文…" rows={6} maxLength={10000} />
|
||||
</Form.Item>
|
||||
|
||||
{/* AI 改写工具条 */}
|
||||
{/* AI 改写工具条(#1894 UX:点击直接执行,自定义渐变圆环 loading) */}
|
||||
<div className="xx-ai-rewrite-bar">
|
||||
<Space size={8} wrap>
|
||||
<Space size={8} wrap align="center">
|
||||
<Select
|
||||
value={rewriteStyle}
|
||||
onChange={setRewriteStyle}
|
||||
@@ -672,30 +591,19 @@ const ScriptLibrary: React.FC = () => {
|
||||
size="small"
|
||||
disabled={rewriteLoading}
|
||||
/>
|
||||
{/* #1893 UX: content 为空时禁用改写按钮并给提示,避免用户点了才弹 warning */}
|
||||
<Tooltip title={contentEmpty ? "请先填写文案正文再改写" : ""}>
|
||||
<span style={{ display: "inline-flex" }}>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<RobotOutlined />}
|
||||
loading={rewriteLoading}
|
||||
disabled={contentEmpty}
|
||||
onClick={() => {
|
||||
// 每次打开重置上一次结果,避免误看旧对比
|
||||
if (!rewriteLoading) {
|
||||
setRewriteResult(null)
|
||||
setRewriteModalOpen(true)
|
||||
}
|
||||
}}
|
||||
>
|
||||
✨ AI 改写
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<RobotOutlined />}
|
||||
disabled={contentEmpty || rewriteLoading}
|
||||
onClick={() => handleAiRewrite(rewriteStyle)}
|
||||
>
|
||||
✨ AI 改写
|
||||
</Button>
|
||||
{rewriteLoading && (
|
||||
<span className="xx-ai-rewrite-loading">
|
||||
<span className="xx-ai-rewrite-spinner" />
|
||||
<span className="xx-ai-rewrite-loading-text">正在改写...</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
{rewriteResult && !contentEmpty && (
|
||||
<Button size="small" type="link" onClick={() => setRewriteModalOpen(true)}>
|
||||
查看上一次改写结果
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
@@ -704,57 +612,6 @@ const ScriptLibrary: React.FC = () => {
|
||||
<Input />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="title_text" label="配套标题(选填)" rules={[{ max: 200 }]}>
|
||||
<Input placeholder="使用此文案时自动带入的标题文本" maxLength={200} />
|
||||
</Form.Item>
|
||||
|
||||
<Space size={16} style={{ display: "flex" }}>
|
||||
<Form.Item name="title_category" label="分类" style={{ flex: 1, marginBottom: 0 }}>
|
||||
<Select options={CATEGORY_OPTIONS.filter((o) => o.value !== "all")} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name={["title_config", "position"]}
|
||||
label="标题位置"
|
||||
style={{ flex: 1, marginBottom: 0 }}
|
||||
>
|
||||
<Select options={POSITION_OPTIONS as unknown as { value: string; label: string }[]} />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
|
||||
<Space size={16} style={{ display: "flex", marginTop: 12 }}>
|
||||
<Form.Item
|
||||
name={["title_config", "font"]}
|
||||
label="字体"
|
||||
style={{ flex: 1, marginBottom: 0 }}
|
||||
>
|
||||
<Select options={FONT_OPTIONS} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name={["title_config", "size"]}
|
||||
label="字号"
|
||||
style={{ flex: 1, marginBottom: 0 }}
|
||||
>
|
||||
<InputNumber min={20} max={120} style={{ width: "100%" }} addonAfter="px" />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
|
||||
<Space size={16} style={{ display: "flex", marginTop: 12 }}>
|
||||
<Form.Item
|
||||
name={["title_config", "color"]}
|
||||
label="文字颜色"
|
||||
style={{ flex: 1, marginBottom: 0 }}
|
||||
>
|
||||
<Input type="color" style={{ width: "100%", height: 32, padding: 4 }} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name={["title_config", "stroke"]}
|
||||
label="描边色"
|
||||
style={{ flex: 1, marginBottom: 0 }}
|
||||
>
|
||||
<Input type="color" style={{ width: "100%", height: 32, padding: 4 }} />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
|
||||
<Form.Item name="tags" label="标签" style={{ marginTop: 12 }}>
|
||||
<Select
|
||||
mode="tags"
|
||||
@@ -798,81 +655,6 @@ const ScriptLibrary: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* AI 改写对比弹窗 */}
|
||||
<Modal
|
||||
title={`✨ AI 改写(${rewriteStyle}风格)`}
|
||||
open={rewriteModalOpen}
|
||||
onCancel={() => !rewriteLoading && setRewriteModalOpen(false)}
|
||||
maskClosable={!rewriteLoading}
|
||||
closable={!rewriteLoading}
|
||||
footer={
|
||||
rewriteResult ? (
|
||||
<Space>
|
||||
<Button onClick={() => setRewriteModalOpen(false)}>保留原文</Button>
|
||||
<Button type="primary" onClick={applyRewrite}>
|
||||
应用改写
|
||||
</Button>
|
||||
</Space>
|
||||
) : (
|
||||
<Button disabled={rewriteLoading} onClick={() => setRewriteModalOpen(false)}>
|
||||
关闭
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
width={640}
|
||||
destroyOnClose={false}
|
||||
>
|
||||
{!rewriteResult && !rewriteLoading && (
|
||||
<Paragraph type="secondary" style={{ marginBottom: 16 }}>
|
||||
将以「{rewriteStyle}」风格改写正文,生成后可对比确认是否应用。
|
||||
</Paragraph>
|
||||
)}
|
||||
{rewriteLoading && (
|
||||
<div className="xx-ai-loading-hint" style={{ padding: "32px 0" }}>
|
||||
<Spin tip="AI 改写中…" />
|
||||
</div>
|
||||
)}
|
||||
{rewriteResult && (
|
||||
<List
|
||||
dataSource={[
|
||||
{ label: "原文", text: rewriteResult.original, type: "original" },
|
||||
{
|
||||
label: `改写(${rewriteResult.style})`,
|
||||
text: rewriteResult.rewritten,
|
||||
type: "rewrite",
|
||||
},
|
||||
]}
|
||||
renderItem={(item) => (
|
||||
<List.Item className="xx-ai-rewrite-item">
|
||||
<div className="xx-ai-rewrite-block">
|
||||
<div className="xx-ai-rewrite-label">
|
||||
<Tag color={item.type === "original" ? "default" : "purple"}>{item.label}</Tag>
|
||||
</div>
|
||||
<Paragraph
|
||||
className="xx-ai-rewrite-text"
|
||||
style={{ whiteSpace: "pre-wrap", marginBottom: 0 }}
|
||||
>
|
||||
{item.text}
|
||||
</Paragraph>
|
||||
</div>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{!rewriteResult && !rewriteLoading && (
|
||||
<div style={{ textAlign: "center" }}>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<RobotOutlined />}
|
||||
loading={rewriteLoading}
|
||||
onClick={handleAiRewrite}
|
||||
>
|
||||
开始改写
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -258,3 +258,51 @@
|
||||
background: linear-gradient(180deg, #faf5ff 0%, #ffffff 100%);
|
||||
border: 1px solid #eee6ff;
|
||||
}
|
||||
|
||||
/* #1894: AI 改写内联 loading —— 渐变圆环旋转动画,替代 antd 默认 Spin */
|
||||
.xx-ai-rewrite-loading {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-left: 4px;
|
||||
}
|
||||
.xx-ai-rewrite-spinner {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid transparent;
|
||||
border-top-color: #9254de;
|
||||
border-right-color: #722ed1;
|
||||
background:
|
||||
linear-gradient(#fff, #fff) padding-box,
|
||||
conic-gradient(from 0deg, #9254de, #4096ff, #9254de) border-box;
|
||||
-webkit-mask:
|
||||
linear-gradient(#000 0 0) content-box,
|
||||
linear-gradient(#000 0 0);
|
||||
-webkit-mask-composite: xor;
|
||||
mask-composite: exclude;
|
||||
animation: xx-ai-rewrite-spin 0.9s linear infinite;
|
||||
}
|
||||
@keyframes xx-ai-rewrite-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
.xx-ai-rewrite-loading-text {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary, #666);
|
||||
background: linear-gradient(90deg, #722ed1, #4096ff, #722ed1);
|
||||
background-size: 200% 100%;
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
animation: xx-ai-rewrite-text-shimmer 2s linear infinite;
|
||||
}
|
||||
@keyframes xx-ai-rewrite-text-shimmer {
|
||||
0% {
|
||||
background-position: 0% 0;
|
||||
}
|
||||
100% {
|
||||
background-position: 200% 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
/**
|
||||
* 升级/降级/续费页面
|
||||
* 升级/降级/续费页面(#1894 清理后:价格统一走 /subscription/plans API)
|
||||
*/
|
||||
import React from "react"
|
||||
import React, { useEffect, useMemo, useState } from "react"
|
||||
import { Modal } from "@/components/ui"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import type { PlanId } from "@/api/subscription/types"
|
||||
import type { PlanId, SubscriptionPlan, BillingCycle } from "@/api/subscription/types"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import { Button } from "@/components/ui"
|
||||
import { PLANS_META, getPlanName, getPlanPrice } from "./constants"
|
||||
import { getPlanName } from "./constants"
|
||||
import { getSubscriptionPlans } from "@/api/subscription"
|
||||
import { BillingCycleSwitch, Spinner } from "./components/SubscriptionUI"
|
||||
import { useSubscription } from "./hooks/useSubscription"
|
||||
import "./UpgradeSubscription.css"
|
||||
@@ -30,18 +31,53 @@ const UpgradeSubscription: React.FC = () => {
|
||||
handleCancel,
|
||||
} = useSubscription()
|
||||
|
||||
// #1894: 从 /subscription/plans 拉真实价格,不使用任何硬编码价格
|
||||
const [apiPlans, setApiPlans] = useState<SubscriptionPlan[]>([])
|
||||
useEffect(() => {
|
||||
getSubscriptionPlans()
|
||||
.then((r) => setApiPlans(r.plans))
|
||||
.catch(() => setApiPlans([]))
|
||||
}, [])
|
||||
|
||||
const planMap = useMemo(() => {
|
||||
const m = new Map<string, SubscriptionPlan>()
|
||||
apiPlans.forEach((p) => m.set(p.plan_id, p))
|
||||
return m
|
||||
}, [apiPlans])
|
||||
|
||||
const getPlanDisplay = (planId: PlanId) => {
|
||||
const apiPlan = planMap.get(planId)
|
||||
const name = apiPlan?.name ?? getPlanName(planId)
|
||||
// 年卡按年价,月/季卡按总价
|
||||
const isYearly = planId === "yearly"
|
||||
const priceCents = apiPlan?.price_cents ?? 0
|
||||
const monthlyCents =
|
||||
apiPlan?.monthly_price_cents ??
|
||||
(apiPlan && apiPlan.duration_days > 0
|
||||
? Math.round(apiPlan.price_cents / (apiPlan.duration_days / 30))
|
||||
: 0)
|
||||
return {
|
||||
name,
|
||||
priceYuan: priceCents / 100,
|
||||
monthlyYuan: monthlyCents / 100,
|
||||
billingLabel: isYearly ? "/年" : planId === "quarterly" ? "/季" : "/月",
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpgradeClick = () => {
|
||||
if (!subscription) return
|
||||
if (selectedPlan === subscription.plan_id && billingCycle === subscription.billing_cycle) {
|
||||
return
|
||||
}
|
||||
|
||||
const plan = PLANS_META[selectedPlan]
|
||||
const price = getPlanPrice(selectedPlan, billingCycle)
|
||||
const display = getPlanDisplay(selectedPlan)
|
||||
const cycleLabel = billingCycle === "monthly" ? "月付" : "年付"
|
||||
const priceLabel =
|
||||
display.priceYuan > 0 ? `费用 ¥${display.priceYuan}${display.billingLabel}` : "免费"
|
||||
|
||||
Modal.confirm({
|
||||
title: "确认变更套餐",
|
||||
content: `即将变更为「${plan.name}」(${billingCycle === "monthly" ? "月付" : "年付"}),${price > 0 ? `费用 ¥${price}${billingCycle === "monthly" ? "/月" : "/年"}` : "免费"}。变更立即生效。`,
|
||||
content: `即将变更为「${display.name}」(${cycleLabel}),${priceLabel}。变更立即生效。`,
|
||||
okText: "确认变更",
|
||||
cancelText: "取消",
|
||||
onOk: executeChangePlan,
|
||||
@@ -77,13 +113,13 @@ const UpgradeSubscription: React.FC = () => {
|
||||
|
||||
<div className="xx-upgrade-plans">
|
||||
{PAID_PLANS.map((planId) => {
|
||||
const plan = PLANS_META[planId]
|
||||
const display = getPlanDisplay(planId)
|
||||
const isCurrent = planId === currentPlan
|
||||
// 年卡显示年价,其他显示月价
|
||||
const monthlyPrice = plan.priceYuan
|
||||
const yearlyPrice = plan.yearlyPriceYuan || plan.priceYuan * 12
|
||||
// 年卡显示年价,其他显示月价折算
|
||||
const monthlyPrice = display.monthlyYuan
|
||||
const yearlyPrice = display.priceYuan
|
||||
// 选中季卡时默认切到月付周期;年卡切到年付
|
||||
const resolvedCycle: "monthly" | "yearly" = planId === "yearly" ? "yearly" : "monthly"
|
||||
const resolvedCycle: BillingCycle = planId === "yearly" ? "yearly" : "monthly"
|
||||
return (
|
||||
<div
|
||||
key={planId}
|
||||
@@ -94,7 +130,7 @@ const UpgradeSubscription: React.FC = () => {
|
||||
}}
|
||||
>
|
||||
{isCurrent && <div className="xx-current-badge">当前</div>}
|
||||
<h3>{plan.name}</h3>
|
||||
<h3>{display.name}</h3>
|
||||
<div className="xx-price">
|
||||
<BillingCycleSwitch
|
||||
value={billingCycle}
|
||||
|
||||
@@ -1,32 +1,13 @@
|
||||
/**
|
||||
* 订阅套餐元数据
|
||||
* 价格硬编码兜底,真实价格以 GET /subscription/plans 为准
|
||||
* 订阅套餐元数据(#1894 清理后)
|
||||
*
|
||||
* - 套餐名兜底:API 失败时用 getPlanName 展示档位名
|
||||
* - 价格已统一走 GET /subscription/plans 动态获取,此处不再硬编码价格
|
||||
* (旧 getPlanPrice / PLANS_META.priceYuan / yearlyPriceYuan 已移除)
|
||||
*/
|
||||
import type { PlanId, BillingCycle } from "@/api/subscription/types"
|
||||
|
||||
export const PLANS_META: Record<
|
||||
PlanId,
|
||||
{ name: string; priceYuan: number; yearlyPriceYuan: number }
|
||||
> = {
|
||||
free: { name: "免费版", priceYuan: 0, yearlyPriceYuan: 0 },
|
||||
monthly: { name: "月度会员", priceYuan: 19.9, yearlyPriceYuan: 0 },
|
||||
quarterly: { name: "季度会员", priceYuan: 39.9, yearlyPriceYuan: 0 },
|
||||
yearly: { name: "年度会员", priceYuan: 0, yearlyPriceYuan: 159 },
|
||||
}
|
||||
import type { PlanId } from "@/api/subscription/types"
|
||||
import { PLAN_LABEL } from "@/api/subscription/types"
|
||||
|
||||
/** 套餐展示名兜底(优先使用 API 返回的 plan.name / PLAN_LABEL) */
|
||||
export const getPlanName = (planId: PlanId | string): string =>
|
||||
PLANS_META[planId as PlanId]?.name ?? "免费版"
|
||||
|
||||
/**
|
||||
* 获取展示价格(元)
|
||||
* - monthly 周期:月卡/季卡按自身价格,年卡按月折算
|
||||
* - yearly 周期:年卡按年价,其他按年价 * 12
|
||||
*/
|
||||
export const getPlanPrice = (planId: PlanId | string, cycle: BillingCycle): number => {
|
||||
const plan = PLANS_META[planId as PlanId]
|
||||
if (!plan) return 0
|
||||
if (cycle === "yearly") {
|
||||
return plan.yearlyPriceYuan > 0 ? plan.yearlyPriceYuan : plan.priceYuan * 12
|
||||
}
|
||||
return plan.priceYuan
|
||||
}
|
||||
PLAN_LABEL[planId as PlanId] ?? "免费版"
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
/**
|
||||
* 标题库页面 — V21 设计系统
|
||||
* 两栏布局:左侧分类列表(220px)+ 右侧标题卡片网格(3列)
|
||||
* 支持:标题卡片展示、AI 生成标题、复制/编辑/删除、收藏、分类筛选、搜索
|
||||
* 对接后端真实 API(GET/POST/PUT/DELETE /titles)
|
||||
*/
|
||||
import React from "react"
|
||||
import { useTitleLibrary } from "./hooks/useTitleLibrary"
|
||||
import { useTitleEdit } from "./hooks/useTitleEdit"
|
||||
import { useTitleAI } from "./hooks/useTitleAI"
|
||||
import { CategorySidebar } from "./components/title-library/CategorySidebar"
|
||||
import { FilterBar } from "./components/title-library/FilterBar"
|
||||
import { TitleGrid } from "./components/title-library/TitleGrid"
|
||||
import { CreateTitleModal } from "./components/title-library/CreateTitleModal"
|
||||
import { AIGenerateModal } from "./components/title-library/AIGenerateModal"
|
||||
import "./titles.css"
|
||||
|
||||
const TitleLibrary: React.FC = () => {
|
||||
const {
|
||||
categories,
|
||||
activeCatId,
|
||||
filteredTitles,
|
||||
searchText,
|
||||
filterType,
|
||||
filterIndustry,
|
||||
filterFrequency,
|
||||
createMutation,
|
||||
updateMutation,
|
||||
setActiveCatId,
|
||||
setSearchText,
|
||||
setFilterType,
|
||||
setFilterIndustry,
|
||||
setFilterFrequency,
|
||||
handleToggleFavorite,
|
||||
handleCopy,
|
||||
handleDelete,
|
||||
} = useTitleLibrary()
|
||||
|
||||
const {
|
||||
editingId,
|
||||
editText,
|
||||
setEditText,
|
||||
createTitleModalOpen,
|
||||
setCreateTitleModalOpen,
|
||||
newTitleContent,
|
||||
setNewTitleContent,
|
||||
newTitleType,
|
||||
setNewTitleType,
|
||||
handleStartEdit,
|
||||
handleSaveEdit,
|
||||
handleCancelEdit,
|
||||
handleCreateTitle,
|
||||
handleCloseCreateModal,
|
||||
} = useTitleEdit({ updateMutation, createMutation })
|
||||
|
||||
const {
|
||||
aiModalOpen,
|
||||
setAiModalOpen,
|
||||
aiKeyword,
|
||||
setAiKeyword,
|
||||
aiLoading,
|
||||
aiResults,
|
||||
handleAIGenerate,
|
||||
handleAdoptAITitle,
|
||||
handleCopyAI,
|
||||
handleCloseAIModal,
|
||||
} = useTitleAI({ createMutation })
|
||||
|
||||
return (
|
||||
<div className="xx-titles-page">
|
||||
<div className="xx-titles-layout">
|
||||
{/* 左侧:分类列表 */}
|
||||
<CategorySidebar
|
||||
categories={categories}
|
||||
activeCatId={activeCatId}
|
||||
onSelect={setActiveCatId}
|
||||
/>
|
||||
|
||||
{/* 右侧:内容区 */}
|
||||
<div className="xx-titles-content">
|
||||
<FilterBar
|
||||
searchText={searchText}
|
||||
onSearchChange={setSearchText}
|
||||
filterType={filterType}
|
||||
onFilterTypeChange={setFilterType}
|
||||
filterIndustry={filterIndustry}
|
||||
onFilterIndustryChange={setFilterIndustry}
|
||||
filterFrequency={filterFrequency}
|
||||
onFilterFrequencyChange={setFilterFrequency}
|
||||
onCreateClick={() => setCreateTitleModalOpen(true)}
|
||||
onAIClick={() => setAiModalOpen(true)}
|
||||
/>
|
||||
|
||||
<TitleGrid
|
||||
titles={filteredTitles}
|
||||
editingId={editingId}
|
||||
editText={editText}
|
||||
searchText={searchText}
|
||||
onEditChange={setEditText}
|
||||
onStartEdit={handleStartEdit}
|
||||
onSaveEdit={handleSaveEdit}
|
||||
onCancelEdit={handleCancelEdit}
|
||||
onCopy={handleCopy}
|
||||
onDelete={handleDelete}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 新建标题弹窗 */}
|
||||
<CreateTitleModal
|
||||
open={createTitleModalOpen}
|
||||
newTitleContent={newTitleContent}
|
||||
newTitleType={newTitleType}
|
||||
onContentChange={setNewTitleContent}
|
||||
onTypeChange={setNewTitleType}
|
||||
onCancel={handleCloseCreateModal}
|
||||
onSubmit={handleCreateTitle}
|
||||
/>
|
||||
|
||||
{/* AI 生成标题弹窗 */}
|
||||
<AIGenerateModal
|
||||
open={aiModalOpen}
|
||||
aiKeyword={aiKeyword}
|
||||
aiLoading={aiLoading}
|
||||
aiResults={aiResults}
|
||||
onKeywordChange={setAiKeyword}
|
||||
onGenerate={handleAIGenerate}
|
||||
onCancel={handleCloseAIModal}
|
||||
onCopy={handleCopyAI}
|
||||
onAdopt={handleAdoptAITitle}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default TitleLibrary
|
||||
@@ -1,121 +0,0 @@
|
||||
import React from "react"
|
||||
import Modal from "@/components/ui/Modal"
|
||||
import { CopyOutlined, CheckOutlined } from "@ant-design/icons"
|
||||
import { Button, Input } from "@/components/ui"
|
||||
import { AI_KEYWORD_MAX_LENGTH } from "../../constants/titleLibrary"
|
||||
|
||||
interface AIGenerateModalProps {
|
||||
open: boolean
|
||||
aiKeyword: string
|
||||
aiLoading: boolean
|
||||
aiResults: string[]
|
||||
onKeywordChange: (keyword: string) => void
|
||||
onGenerate: () => void
|
||||
onCancel: () => void
|
||||
onCopy: (text: string) => void
|
||||
onAdopt: (text: string) => void
|
||||
}
|
||||
|
||||
export const AIGenerateModal: React.FC<AIGenerateModalProps> = ({
|
||||
open,
|
||||
aiKeyword,
|
||||
aiLoading,
|
||||
aiResults,
|
||||
onKeywordChange,
|
||||
onGenerate,
|
||||
onCancel,
|
||||
onCopy,
|
||||
onAdopt,
|
||||
}) => {
|
||||
return (
|
||||
<Modal
|
||||
title="AI 生成标题"
|
||||
open={open}
|
||||
onCancel={onCancel}
|
||||
onOk={onGenerate}
|
||||
okText={aiLoading ? "生成中..." : "生成"}
|
||||
cancelText="关闭"
|
||||
okButtonProps={{ disabled: aiLoading }}
|
||||
destroyOnClose
|
||||
width={640}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 16,
|
||||
padding: "8px 0",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 6,
|
||||
fontSize: "var(--font-size-sm)",
|
||||
color: "var(--text-secondary)",
|
||||
}}
|
||||
>
|
||||
输入关键词或主题
|
||||
</div>
|
||||
<Input
|
||||
placeholder="例如:美食探店、科技评测、旅行攻略..."
|
||||
value={aiKeyword}
|
||||
onChange={(e) => onKeywordChange(e.target.value)}
|
||||
maxLength={AI_KEYWORD_MAX_LENGTH}
|
||||
onPressEnter={onGenerate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* AI 加载动画 */}
|
||||
{aiLoading && (
|
||||
<div className="xx-ai-loading">
|
||||
<div className="xx-ai-loading-dots">
|
||||
<div className="xx-ai-loading-dot" />
|
||||
<div className="xx-ai-loading-dot" />
|
||||
<div className="xx-ai-loading-dot" />
|
||||
</div>
|
||||
<span>AI 正在生成标题候选...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI 生成结果列表 */}
|
||||
{aiResults.length > 0 && (
|
||||
<div className="xx-ai-results">
|
||||
<div
|
||||
style={{
|
||||
fontSize: "var(--font-size-sm)",
|
||||
color: "var(--text-secondary)",
|
||||
marginBottom: 4,
|
||||
}}
|
||||
>
|
||||
已生成 {aiResults.length} 个候选标题,点击采纳或复制:
|
||||
</div>
|
||||
{aiResults.map((text, idx) => (
|
||||
<div key={idx} className="xx-ai-result-item">
|
||||
<span className="xx-ai-result-text">{text}</span>
|
||||
<div className="xx-ai-result-actions">
|
||||
<Button
|
||||
buttonType="ghost"
|
||||
buttonSize="sm"
|
||||
icon={<CopyOutlined />}
|
||||
onClick={() => onCopy(text)}
|
||||
>
|
||||
复制
|
||||
</Button>
|
||||
<Button
|
||||
buttonType="primary"
|
||||
buttonSize="sm"
|
||||
icon={<CheckOutlined />}
|
||||
onClick={() => onAdopt(text)}
|
||||
>
|
||||
采纳
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import React from "react"
|
||||
import { FileTextOutlined } from "@ant-design/icons"
|
||||
import type { CategoryItem } from "../../types/titleLibrary"
|
||||
|
||||
interface CategorySidebarProps {
|
||||
categories: CategoryItem[]
|
||||
activeCatId: string
|
||||
onSelect: (catId: string) => void
|
||||
}
|
||||
|
||||
export const CategorySidebar: React.FC<CategorySidebarProps> = ({
|
||||
categories,
|
||||
activeCatId,
|
||||
onSelect,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-title-category-list">
|
||||
{categories.map((cat) => (
|
||||
<div
|
||||
key={cat.id}
|
||||
className={`xx-title-category-item${cat.id === activeCatId ? " active" : ""}`}
|
||||
onClick={() => onSelect(cat.id)}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
}}
|
||||
>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<h4 style={{ margin: 0 }}>
|
||||
<FileTextOutlined /> {cat.name}
|
||||
</h4>
|
||||
<span>{cat.count} 条</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import React from "react"
|
||||
import Modal from "@/components/ui/Modal"
|
||||
import { Input, Select } from "@/components/ui"
|
||||
import type { TitleType } from "../../types/titleLibrary"
|
||||
import { TITLE_MAX_LENGTH } from "../../constants/titleLibrary"
|
||||
|
||||
const TITLE_TYPE_CREATE_OPTIONS: Array<{ value: TitleType; label: string }> = [
|
||||
{ value: "hot", label: "爆款" },
|
||||
{ value: "normal", label: "常规" },
|
||||
{ value: "creative", label: "创意" },
|
||||
]
|
||||
|
||||
interface CreateTitleModalProps {
|
||||
open: boolean
|
||||
newTitleContent: string
|
||||
newTitleType: TitleType
|
||||
onContentChange: (content: string) => void
|
||||
onTypeChange: (type: TitleType) => void
|
||||
onCancel: () => void
|
||||
onSubmit: () => void
|
||||
}
|
||||
|
||||
export const CreateTitleModal: React.FC<CreateTitleModalProps> = ({
|
||||
open,
|
||||
newTitleContent,
|
||||
newTitleType,
|
||||
onContentChange,
|
||||
onTypeChange,
|
||||
onCancel,
|
||||
onSubmit,
|
||||
}) => {
|
||||
return (
|
||||
<Modal
|
||||
title="新建标题"
|
||||
open={open}
|
||||
onCancel={onCancel}
|
||||
onOk={onSubmit}
|
||||
okText="创建"
|
||||
cancelText="取消"
|
||||
destroyOnClose
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 16,
|
||||
padding: "8px 0",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 6,
|
||||
fontSize: "var(--font-size-sm)",
|
||||
color: "var(--text-secondary)",
|
||||
}}
|
||||
>
|
||||
标题内容
|
||||
</div>
|
||||
<Input.TextArea
|
||||
placeholder="请输入标题内容"
|
||||
value={newTitleContent}
|
||||
onChange={(e) => onContentChange(e.target.value)}
|
||||
rows={3}
|
||||
maxLength={TITLE_MAX_LENGTH}
|
||||
showCount
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 6,
|
||||
fontSize: "var(--font-size-sm)",
|
||||
color: "var(--text-secondary)",
|
||||
}}
|
||||
>
|
||||
标题类型
|
||||
</div>
|
||||
<Select
|
||||
value={newTitleType}
|
||||
onChange={(v) => onTypeChange(v as TitleType)}
|
||||
style={{ width: "100%" }}
|
||||
options={TITLE_TYPE_CREATE_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import React from "react"
|
||||
import { SearchOutlined, PlusOutlined, RobotOutlined } from "@ant-design/icons"
|
||||
import { Button, Input, Select } from "@/components/ui"
|
||||
import type { Frequency } from "../../types/titleLibrary"
|
||||
import {
|
||||
TITLE_TYPE_OPTIONS,
|
||||
INDUSTRY_OPTIONS,
|
||||
FREQUENCY_OPTIONS,
|
||||
} from "../../constants/titleLibrary"
|
||||
|
||||
interface FilterBarProps {
|
||||
searchText: string
|
||||
onSearchChange: (text: string) => void
|
||||
filterType: string
|
||||
onFilterTypeChange: (value: string) => void
|
||||
filterIndustry: string
|
||||
onFilterIndustryChange: (value: string) => void
|
||||
filterFrequency: Frequency
|
||||
onFilterFrequencyChange: (value: Frequency) => void
|
||||
onCreateClick: () => void
|
||||
onAIClick: () => void
|
||||
}
|
||||
|
||||
export const FilterBar: React.FC<FilterBarProps> = ({
|
||||
searchText,
|
||||
onSearchChange,
|
||||
filterType,
|
||||
onFilterTypeChange,
|
||||
filterIndustry,
|
||||
onFilterIndustryChange,
|
||||
filterFrequency,
|
||||
onFilterFrequencyChange,
|
||||
onCreateClick,
|
||||
onAIClick,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-titles-filters">
|
||||
<div className="xx-titles-filters-left">
|
||||
<Input
|
||||
placeholder="搜索标题关键词..."
|
||||
prefix={<SearchOutlined />}
|
||||
value={searchText}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
allowClear
|
||||
style={{ width: 220 }}
|
||||
/>
|
||||
<Select
|
||||
value={filterType}
|
||||
onChange={onFilterTypeChange}
|
||||
style={{ width: 110 }}
|
||||
options={TITLE_TYPE_OPTIONS}
|
||||
/>
|
||||
<Select
|
||||
value={filterIndustry}
|
||||
onChange={onFilterIndustryChange}
|
||||
style={{ width: 110 }}
|
||||
options={INDUSTRY_OPTIONS}
|
||||
/>
|
||||
<Select
|
||||
value={filterFrequency}
|
||||
onChange={(v) => onFilterFrequencyChange(v as Frequency)}
|
||||
style={{ width: 120 }}
|
||||
options={FREQUENCY_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
<div className="xx-titles-filters-right">
|
||||
<Button buttonType="ghost" buttonSize="sm" icon={<PlusOutlined />} onClick={onCreateClick}>
|
||||
新建标题
|
||||
</Button>
|
||||
<Button buttonType="primary" buttonSize="sm" icon={<RobotOutlined />} onClick={onAIClick}>
|
||||
AI 生成标题
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import React from "react"
|
||||
import { Popconfirm } from "antd"
|
||||
import {
|
||||
StarOutlined,
|
||||
StarFilled,
|
||||
EditOutlined,
|
||||
CopyOutlined,
|
||||
DeleteOutlined,
|
||||
CheckOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import type { TitleData } from "../../types/titleLibrary"
|
||||
import { typeLabel } from "../../utils/titleLibrary"
|
||||
|
||||
interface TitleCardProps {
|
||||
title: TitleData
|
||||
isEditing: boolean
|
||||
editText: string
|
||||
onEditChange: (text: string) => void
|
||||
onStartEdit: () => void
|
||||
onSaveEdit: () => void
|
||||
onCancelEdit: () => void
|
||||
onCopy: () => void
|
||||
onDelete: () => void
|
||||
onToggleFavorite: () => void
|
||||
}
|
||||
|
||||
export const TitleCard: React.FC<TitleCardProps> = ({
|
||||
title,
|
||||
isEditing,
|
||||
editText,
|
||||
onEditChange,
|
||||
onStartEdit,
|
||||
onSaveEdit,
|
||||
onCancelEdit,
|
||||
onCopy,
|
||||
onDelete,
|
||||
onToggleFavorite,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-title-card">
|
||||
{/* 收藏按钮 */}
|
||||
<button
|
||||
className="xx-title-fav-btn"
|
||||
onClick={onToggleFavorite}
|
||||
title={title.isFavorited ? "取消收藏" : "收藏"}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 12,
|
||||
right: 12,
|
||||
color: title.isFavorited ? "#f59e0b" : "var(--text-tertiary)",
|
||||
}}
|
||||
>
|
||||
{title.isFavorited ? <StarFilled /> : <StarOutlined />}
|
||||
</button>
|
||||
|
||||
{/* 标题文本 / 编辑区 */}
|
||||
{isEditing ? (
|
||||
<textarea
|
||||
className="xx-title-card-edit"
|
||||
value={editText}
|
||||
onChange={(e) => onEditChange(e.target.value)}
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
onSaveEdit()
|
||||
}
|
||||
if (e.key === "Escape") {
|
||||
onCancelEdit()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="xx-title-card-text" style={{ paddingRight: 24 }}>
|
||||
{title.content}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 底部元信息 */}
|
||||
<div className="xx-title-card-meta">
|
||||
<div className="xx-title-card-meta-left">
|
||||
<span className={`xx-title-type-tag ${title.type}`}>{typeLabel(title.type)}</span>
|
||||
<span className="xx-title-card-stat">使用 {title.usageCount} 次</span>
|
||||
<span className="xx-title-card-stat">{title.createdAt}</span>
|
||||
</div>
|
||||
|
||||
<div className="xx-title-card-actions">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<button className="xx-title-card-action-btn" onClick={onSaveEdit} title="保存">
|
||||
<CheckOutlined />
|
||||
</button>
|
||||
<button className="xx-title-card-action-btn" onClick={onCancelEdit} title="取消">
|
||||
✕
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button className="xx-title-card-action-btn" onClick={onCopy} title="复制">
|
||||
<CopyOutlined />
|
||||
</button>
|
||||
<button className="xx-title-card-action-btn" onClick={onStartEdit} title="编辑">
|
||||
<EditOutlined />
|
||||
</button>
|
||||
<Popconfirm
|
||||
title="确定删除此标题?"
|
||||
onConfirm={onDelete}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<button className="xx-title-card-action-btn danger" title="删除">
|
||||
<DeleteOutlined />
|
||||
</button>
|
||||
</Popconfirm>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import React from "react"
|
||||
import { FileTextOutlined } from "@ant-design/icons"
|
||||
import { TitleCard } from "./TitleCard"
|
||||
import type { TitleData } from "../../types/titleLibrary"
|
||||
|
||||
interface TitleGridProps {
|
||||
titles: TitleData[]
|
||||
editingId: string | null
|
||||
editText: string
|
||||
searchText: string
|
||||
onEditChange: (text: string) => void
|
||||
onStartEdit: (title: TitleData) => void
|
||||
onSaveEdit: () => void
|
||||
onCancelEdit: () => void
|
||||
onCopy: (title: TitleData) => void
|
||||
onDelete: (id: string) => void
|
||||
onToggleFavorite: (id: string) => void
|
||||
}
|
||||
|
||||
export const TitleGrid: React.FC<TitleGridProps> = ({
|
||||
titles,
|
||||
editingId,
|
||||
editText,
|
||||
searchText,
|
||||
onEditChange,
|
||||
onStartEdit,
|
||||
onSaveEdit,
|
||||
onCancelEdit,
|
||||
onCopy,
|
||||
onDelete,
|
||||
onToggleFavorite,
|
||||
}) => {
|
||||
if (titles.length > 0) {
|
||||
return (
|
||||
<div className="xx-title-grid">
|
||||
{titles.map((title) => (
|
||||
<TitleCard
|
||||
key={title.id}
|
||||
title={title}
|
||||
isEditing={editingId === title.id}
|
||||
editText={editingId === title.id ? editText : ""}
|
||||
onEditChange={onEditChange}
|
||||
onStartEdit={() => onStartEdit(title)}
|
||||
onSaveEdit={onSaveEdit}
|
||||
onCancelEdit={onCancelEdit}
|
||||
onCopy={() => onCopy(title)}
|
||||
onDelete={() => onDelete(title.id)}
|
||||
onToggleFavorite={() => onToggleFavorite(title.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="xx-titles-empty">
|
||||
<div className="xx-titles-empty-icon">
|
||||
<FileTextOutlined />
|
||||
</div>
|
||||
<p>{searchText ? "未找到匹配的标题" : "暂无标题,点击「新建标题」或「AI 生成标题」开始"}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { TitleType, Industry, Frequency } from "../types/titleLibrary"
|
||||
|
||||
export const TITLE_TYPE_OPTIONS: Array<{ value: TitleType | "all"; label: string }> = [
|
||||
{ value: "all", label: "全部类型" },
|
||||
{ value: "hot", label: "爆款" },
|
||||
{ value: "normal", label: "常规" },
|
||||
{ value: "creative", label: "创意" },
|
||||
]
|
||||
|
||||
export const INDUSTRY_OPTIONS: Array<{ value: Industry | "all"; label: string }> = [
|
||||
{ value: "all", label: "全部行业" },
|
||||
{ value: "food", label: "美食" },
|
||||
{ value: "tech", label: "科技" },
|
||||
{ value: "beauty", label: "美妆" },
|
||||
{ value: "education", label: "教育" },
|
||||
{ value: "travel", label: "旅行" },
|
||||
]
|
||||
|
||||
export const FREQUENCY_OPTIONS: Array<{ value: Frequency; label: string }> = [
|
||||
{ value: "all", label: "全部频率" },
|
||||
{ value: "high", label: "高频使用" },
|
||||
{ value: "medium", label: "中频使用" },
|
||||
{ value: "low", label: "低频使用" },
|
||||
]
|
||||
|
||||
export const FREQUENCY_THRESHOLDS = {
|
||||
high: 100,
|
||||
medium: 30,
|
||||
} as const
|
||||
|
||||
export const AI_GENERATE_DELAY = 2000
|
||||
export const TITLE_MAX_LENGTH = 200
|
||||
export const AI_KEYWORD_MAX_LENGTH = 100
|
||||
export const ALL_CATEGORY_ID = "cat-all"
|
||||
@@ -1,84 +0,0 @@
|
||||
import { useState, useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import type { UseMutationResult } from "@tanstack/react-query"
|
||||
import type { TitleItem } from "@/api/titles"
|
||||
import { copyToClipboard } from "../utils/titleLibrary"
|
||||
import { AI_GENERATE_DELAY } from "../constants/titleLibrary"
|
||||
|
||||
interface UseTitleAIProps {
|
||||
createMutation: UseMutationResult<TitleItem, Error, string, unknown>
|
||||
}
|
||||
|
||||
const generateMockTitles = (keyword: string): string[] => [
|
||||
`${keyword}:这个方法让我事半功倍!`,
|
||||
`关于${keyword},99%的人都不知道的事`,
|
||||
`${keyword}全攻略,看完这篇就够了`,
|
||||
`我花了 3 个月研究${keyword},总结出这些经验`,
|
||||
`${keyword}避坑指南,帮你省下 1000 块`,
|
||||
]
|
||||
|
||||
export const useTitleAI = ({ createMutation }: UseTitleAIProps) => {
|
||||
const [aiModalOpen, setAiModalOpen] = useState(false)
|
||||
const [aiKeyword, setAiKeyword] = useState("")
|
||||
const [aiLoading, setAiLoading] = useState(false)
|
||||
const [aiResults, setAiResults] = useState<string[]>([])
|
||||
|
||||
/* AI 生成标题 */
|
||||
const handleAIGenerate = useCallback(() => {
|
||||
if (!aiKeyword.trim()) {
|
||||
message.warning("请输入关键词或主题")
|
||||
return
|
||||
}
|
||||
setAiLoading(true)
|
||||
setAiResults([])
|
||||
|
||||
setTimeout(() => {
|
||||
const results = generateMockTitles(aiKeyword.trim())
|
||||
setAiResults(results)
|
||||
setAiLoading(false)
|
||||
}, AI_GENERATE_DELAY)
|
||||
}, [aiKeyword])
|
||||
|
||||
/* 采纳 AI 生成的标题 */
|
||||
const handleAdoptAITitle = useCallback(
|
||||
(text: string) => {
|
||||
createMutation.mutate(text, {
|
||||
onSuccess: () => {
|
||||
message.success("标题已采纳并添加到标题库")
|
||||
},
|
||||
})
|
||||
},
|
||||
[createMutation],
|
||||
)
|
||||
|
||||
/* 复制 AI 生成的标题 */
|
||||
const handleCopyAI = useCallback(async (text: string) => {
|
||||
const ok = await copyToClipboard(text)
|
||||
if (ok) {
|
||||
message.success("已复制到剪贴板")
|
||||
} else {
|
||||
message.error("复制失败")
|
||||
}
|
||||
}, [])
|
||||
|
||||
/* 关闭 AI 弹窗 */
|
||||
const handleCloseAIModal = useCallback(() => {
|
||||
setAiModalOpen(false)
|
||||
setAiLoading(false)
|
||||
setAiResults([])
|
||||
setAiKeyword("")
|
||||
}, [])
|
||||
|
||||
return {
|
||||
aiModalOpen,
|
||||
setAiModalOpen,
|
||||
aiKeyword,
|
||||
setAiKeyword,
|
||||
aiLoading,
|
||||
aiResults,
|
||||
handleAIGenerate,
|
||||
handleAdoptAITitle,
|
||||
handleCopyAI,
|
||||
handleCloseAIModal,
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
import { useState, useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import type { TitleData, TitleType } from "../types/titleLibrary"
|
||||
import type { UseMutationResult } from "@tanstack/react-query"
|
||||
import type { TitleItem } from "@/api/titles"
|
||||
|
||||
interface UseTitleEditProps {
|
||||
updateMutation: UseMutationResult<TitleItem, Error, { id: string; content: string }, unknown>
|
||||
createMutation: UseMutationResult<TitleItem, Error, string, unknown>
|
||||
}
|
||||
|
||||
export const useTitleEdit = ({ updateMutation, createMutation }: UseTitleEditProps) => {
|
||||
/* 编辑状态 */
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [editText, setEditText] = useState("")
|
||||
|
||||
/* 新建标题弹窗 */
|
||||
const [createTitleModalOpen, setCreateTitleModalOpen] = useState(false)
|
||||
const [newTitleContent, setNewTitleContent] = useState("")
|
||||
const [newTitleType, setNewTitleType] = useState<TitleType>("normal")
|
||||
|
||||
/* 开始编辑 */
|
||||
const handleStartEdit = useCallback((title: TitleData) => {
|
||||
setEditingId(title.id)
|
||||
setEditText(title.content)
|
||||
}, [])
|
||||
|
||||
/* 保存编辑 */
|
||||
const handleSaveEdit = useCallback(() => {
|
||||
if (!editText.trim()) {
|
||||
message.warning("标题内容不能为空")
|
||||
return
|
||||
}
|
||||
if (editingId) {
|
||||
updateMutation.mutate({ id: editingId, content: editText.trim() })
|
||||
}
|
||||
setEditingId(null)
|
||||
setEditText("")
|
||||
message.success("标题已更新")
|
||||
}, [editingId, editText, updateMutation])
|
||||
|
||||
/* 取消编辑 */
|
||||
const handleCancelEdit = useCallback(() => {
|
||||
setEditingId(null)
|
||||
setEditText("")
|
||||
}, [])
|
||||
|
||||
/* 新建标题提交 */
|
||||
const handleCreateTitle = useCallback(() => {
|
||||
if (!newTitleContent.trim()) {
|
||||
message.warning("请输入标题内容")
|
||||
return
|
||||
}
|
||||
createMutation.mutate(newTitleContent.trim(), {
|
||||
onSuccess: () => {
|
||||
setCreateTitleModalOpen(false)
|
||||
setNewTitleContent("")
|
||||
setNewTitleType("normal")
|
||||
message.success("标题创建成功")
|
||||
},
|
||||
})
|
||||
}, [newTitleContent, createMutation])
|
||||
|
||||
/* 关闭新建弹窗 */
|
||||
const handleCloseCreateModal = useCallback(() => {
|
||||
setCreateTitleModalOpen(false)
|
||||
setNewTitleContent("")
|
||||
setNewTitleType("normal")
|
||||
}, [])
|
||||
|
||||
return {
|
||||
editingId,
|
||||
editText,
|
||||
setEditText,
|
||||
createTitleModalOpen,
|
||||
setCreateTitleModalOpen,
|
||||
newTitleContent,
|
||||
setNewTitleContent,
|
||||
newTitleType,
|
||||
setNewTitleType,
|
||||
handleStartEdit,
|
||||
handleSaveEdit,
|
||||
handleCancelEdit,
|
||||
handleCreateTitle,
|
||||
handleCloseCreateModal,
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { useTitleFilters } from "./useTitleFilters"
|
||||
import { useTitleMutations } from "./useTitleMutations"
|
||||
import { useTitleData } from "./useTitleData"
|
||||
import { useTitleActions } from "./useTitleActions"
|
||||
|
||||
export const useTitleLibrary = () => {
|
||||
/* 数据获取与派生 */
|
||||
const { titles, categories, activeCatId, activeCategory, setActiveCatId } = useTitleData()
|
||||
|
||||
/* 筛选 */
|
||||
const {
|
||||
searchText,
|
||||
filterType,
|
||||
filterIndustry,
|
||||
filterFrequency,
|
||||
setSearchText,
|
||||
setFilterType,
|
||||
setFilterIndustry,
|
||||
setFilterFrequency,
|
||||
filteredTitles,
|
||||
} = useTitleFilters(titles, categories, activeCatId, activeCategory)
|
||||
|
||||
/* CRUD mutations */
|
||||
const { createMutation, updateMutation, deleteMutation } = useTitleMutations()
|
||||
|
||||
/* 操作 handlers */
|
||||
const { handleToggleFavorite, handleCopy, handleDelete } = useTitleActions(deleteMutation)
|
||||
|
||||
return {
|
||||
/* 状态 */
|
||||
titles,
|
||||
categories,
|
||||
activeCatId,
|
||||
activeCategory,
|
||||
filteredTitles,
|
||||
searchText,
|
||||
filterType,
|
||||
filterIndustry,
|
||||
filterFrequency,
|
||||
/* mutations */
|
||||
createMutation,
|
||||
updateMutation,
|
||||
deleteMutation,
|
||||
/* setters */
|
||||
setActiveCatId,
|
||||
setSearchText,
|
||||
setFilterType,
|
||||
setFilterIndustry,
|
||||
setFilterFrequency,
|
||||
/* handlers */
|
||||
handleToggleFavorite,
|
||||
handleCopy,
|
||||
handleDelete,
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import type { UseMutationResult } from "@tanstack/react-query"
|
||||
import type { TitleData } from "../../types/titleLibrary"
|
||||
import { copyToClipboard } from "../../utils/titleLibrary"
|
||||
|
||||
export const useTitleActions = (
|
||||
deleteMutation: UseMutationResult<void, Error, string, unknown>,
|
||||
) => {
|
||||
/* 操作:收藏 */
|
||||
const handleToggleFavorite = useCallback((_id: string) => {
|
||||
message.info("收藏功能即将上线")
|
||||
}, [])
|
||||
|
||||
/* 操作:复制 */
|
||||
const handleCopy = useCallback(async (title: TitleData) => {
|
||||
const ok = await copyToClipboard(title.content)
|
||||
if (ok) {
|
||||
message.success("已复制到剪贴板")
|
||||
} else {
|
||||
message.error("复制失败")
|
||||
}
|
||||
}, [])
|
||||
|
||||
/* 操作:删除 */
|
||||
const handleDelete = useCallback(
|
||||
(id: string) => {
|
||||
deleteMutation.mutate(id)
|
||||
},
|
||||
[deleteMutation],
|
||||
)
|
||||
|
||||
return { handleToggleFavorite, handleCopy, handleDelete }
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { useMemo, useState } from "react"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { getTitles } from "@/api/titles"
|
||||
import type { TitleData, CategoryItem } from "../../types/titleLibrary"
|
||||
import { toTitleData } from "../../utils/titleLibrary"
|
||||
import { ALL_CATEGORY_ID } from "../../constants/titleLibrary"
|
||||
|
||||
export const useTitleData = () => {
|
||||
/* 分类 */
|
||||
const [activeCatId, setActiveCatId] = useState<string>(ALL_CATEGORY_ID)
|
||||
|
||||
/* 数据获取 */
|
||||
const { data: apiTitles = [] } = useQuery({
|
||||
queryKey: ["titles"],
|
||||
queryFn: getTitles,
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const titles: TitleData[] = useMemo(() => apiTitles.map(toTitleData), [apiTitles])
|
||||
|
||||
/* 动态派生分类 */
|
||||
const categories: CategoryItem[] = useMemo(() => {
|
||||
const cats = new Map<string, number>()
|
||||
apiTitles.forEach((t) => {
|
||||
const cat = t.category || "未分类"
|
||||
cats.set(cat, (cats.get(cat) || 0) + 1)
|
||||
})
|
||||
return [
|
||||
{ id: ALL_CATEGORY_ID, name: "全部标题", count: apiTitles.length },
|
||||
...Array.from(cats.entries()).map(([name, count]) => ({
|
||||
id: `cat-${name}`,
|
||||
name,
|
||||
count,
|
||||
})),
|
||||
]
|
||||
}, [apiTitles])
|
||||
|
||||
const activeCategory = categories.find((c) => c.id === activeCatId)
|
||||
|
||||
return {
|
||||
titles,
|
||||
categories,
|
||||
activeCatId,
|
||||
activeCategory,
|
||||
setActiveCatId,
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { useMemo, useState } from "react"
|
||||
import type { TitleData, CategoryItem, Frequency } from "../../types/titleLibrary"
|
||||
import { ALL_CATEGORY_ID, FREQUENCY_THRESHOLDS } from "../../constants/titleLibrary"
|
||||
|
||||
export const useTitleFilters = (
|
||||
titles: TitleData[],
|
||||
_categories: CategoryItem[],
|
||||
activeCatId: string,
|
||||
activeCategory: CategoryItem | undefined,
|
||||
) => {
|
||||
const [searchText, setSearchText] = useState("")
|
||||
const [filterType, setFilterType] = useState<string>("all")
|
||||
const [filterIndustry, setFilterIndustry] = useState<string>("all")
|
||||
const [filterFrequency, setFilterFrequency] = useState<Frequency>("all")
|
||||
|
||||
/* 派生:筛选后的标题列表 */
|
||||
const filteredTitles = useMemo(() => {
|
||||
let list = titles
|
||||
|
||||
/* 按分类过滤 */
|
||||
if (activeCatId !== ALL_CATEGORY_ID) {
|
||||
const catName = activeCategory?.name || ""
|
||||
if (catName) {
|
||||
list = list.filter((t) => t.category === catName)
|
||||
}
|
||||
}
|
||||
|
||||
/* 按类型筛选 */
|
||||
if (filterType !== "all") {
|
||||
list = list.filter((t) => t.type === filterType)
|
||||
}
|
||||
|
||||
/* 按行业筛选 */
|
||||
if (filterIndustry !== "all") {
|
||||
list = list.filter((t) => t.industry === filterIndustry)
|
||||
}
|
||||
|
||||
/* 按使用频率筛选 */
|
||||
if (filterFrequency !== "all") {
|
||||
switch (filterFrequency) {
|
||||
case "high":
|
||||
list = list.filter((t) => t.usageCount >= FREQUENCY_THRESHOLDS.high)
|
||||
break
|
||||
case "medium":
|
||||
list = list.filter(
|
||||
(t) =>
|
||||
t.usageCount >= FREQUENCY_THRESHOLDS.medium &&
|
||||
t.usageCount < FREQUENCY_THRESHOLDS.high,
|
||||
)
|
||||
break
|
||||
case "low":
|
||||
list = list.filter((t) => t.usageCount < FREQUENCY_THRESHOLDS.medium)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/* 搜索 */
|
||||
if (searchText.trim()) {
|
||||
const q = searchText.trim().toLowerCase()
|
||||
list = list.filter((t) => t.content.toLowerCase().includes(q))
|
||||
}
|
||||
|
||||
return list
|
||||
}, [titles, activeCatId, activeCategory, filterType, filterIndustry, filterFrequency, searchText])
|
||||
|
||||
return {
|
||||
searchText,
|
||||
setSearchText,
|
||||
filterType,
|
||||
setFilterType,
|
||||
filterIndustry,
|
||||
setFilterIndustry,
|
||||
filterFrequency,
|
||||
setFilterFrequency,
|
||||
filteredTitles,
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { message } from "antd"
|
||||
import { createTitle, updateTitle, deleteTitle } from "@/api/titles"
|
||||
|
||||
export const useTitleMutations = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (content: string) => createTitle({ content }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["titles"] })
|
||||
},
|
||||
onError: () => message.error("创建标题失败"),
|
||||
})
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, content }: { id: string; content: string }) => updateTitle(id, { content }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["titles"] })
|
||||
},
|
||||
onError: () => message.error("更新标题失败"),
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteTitle(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["titles"] })
|
||||
message.success("标题已删除")
|
||||
},
|
||||
onError: () => message.error("删除标题失败"),
|
||||
})
|
||||
|
||||
return { createMutation, updateMutation, deleteMutation }
|
||||
}
|
||||
@@ -1,488 +0,0 @@
|
||||
/**
|
||||
* 标题库页面 - V21 设计系统样式
|
||||
* 两栏布局:左侧分类列表(220px)+ 右侧标题卡片网格(3列)
|
||||
* 统一使用 CSS 变量,支持深色/浅色主题
|
||||
*/
|
||||
@import "../../styles/global.css";
|
||||
|
||||
/* ============================================================
|
||||
页面容器
|
||||
============================================================ */
|
||||
.xx-titles-page {
|
||||
min-height: 100%;
|
||||
padding: var(--space-xl);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
两栏布局
|
||||
============================================================ */
|
||||
.xx-titles-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr;
|
||||
gap: 20px;
|
||||
align-items: start;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
左侧分类列表
|
||||
============================================================ */
|
||||
.xx-title-category-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-sm);
|
||||
position: sticky;
|
||||
top: var(--space-md);
|
||||
align-self: start;
|
||||
}
|
||||
|
||||
.xx-title-category-item {
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-primary);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 14px;
|
||||
cursor: pointer;
|
||||
transition: var(--transition-all);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.xx-title-category-item:hover {
|
||||
border-color: var(--primary-color);
|
||||
background: var(--primary-soft);
|
||||
}
|
||||
|
||||
.xx-title-category-item.active {
|
||||
border-color: var(--primary-color);
|
||||
background: var(--primary-soft);
|
||||
box-shadow: var(--shadow-primary);
|
||||
}
|
||||
|
||||
.xx-title-category-item h4 {
|
||||
margin: 0 0 var(--space-xs);
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.xx-title-category-item span {
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.xx-title-category-delete {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-tertiary);
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
border-radius: var(--radius-xs);
|
||||
font-size: var(--font-size-sm);
|
||||
transition: var(--transition-all);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.xx-title-category-item:hover .xx-title-category-delete {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.xx-title-category-delete:hover {
|
||||
color: var(--error-color);
|
||||
background: var(--error-soft);
|
||||
}
|
||||
|
||||
.xx-title-category-add {
|
||||
border: 1px dashed var(--border-color);
|
||||
background: transparent;
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 14px;
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--font-size-sm);
|
||||
transition: var(--transition-all);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-xs);
|
||||
}
|
||||
|
||||
.xx-title-category-add:hover {
|
||||
border-color: var(--primary-color);
|
||||
color: var(--primary-color);
|
||||
background: var(--primary-soft);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
右侧内容区
|
||||
============================================================ */
|
||||
.xx-titles-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-lg);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
筛选栏
|
||||
============================================================ */
|
||||
.xx-titles-filters {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-md);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.xx-titles-filters-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
|
||||
.xx-titles-filters-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
标题卡片网格(3列)
|
||||
============================================================ */
|
||||
.xx-title-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
标题卡片
|
||||
============================================================ */
|
||||
.xx-title-card {
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-primary);
|
||||
border-radius: var(--radius-md);
|
||||
padding: var(--space-md);
|
||||
transition: var(--transition-all);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.xx-title-card:hover {
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* 标题文本 */
|
||||
.xx-title-card-text {
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
/* 最多3行,超出省略 */
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* 编辑态 */
|
||||
.xx-title-card-edit {
|
||||
width: 100%;
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.5;
|
||||
border: 1px solid var(--primary-color);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 6px 10px;
|
||||
background: var(--bg-primary);
|
||||
outline: none;
|
||||
resize: vertical;
|
||||
min-height: 60px;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.xx-title-card-edit:focus {
|
||||
box-shadow: 0 0 0 2px var(--primary-soft);
|
||||
}
|
||||
|
||||
/* 底部元信息 */
|
||||
.xx-title-card-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-sm);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.xx-title-card-meta-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xs);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* 类型标签 */
|
||||
.xx-title-type-tag {
|
||||
padding: 2px 10px;
|
||||
border-radius: var(--radius-full);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-medium);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.xx-title-type-tag.hot {
|
||||
background: var(--error-soft);
|
||||
color: var(--error-color);
|
||||
}
|
||||
|
||||
.xx-title-type-tag.normal {
|
||||
background: var(--primary-soft);
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.xx-title-type-tag.creative {
|
||||
background: var(--warning-soft);
|
||||
color: var(--warning-color);
|
||||
}
|
||||
|
||||
/* 深色模式 */
|
||||
.dark .xx-title-type-tag.hot,
|
||||
[data-theme="dark"] .xx-title-type-tag.hot {
|
||||
background: rgba(220, 38, 38, 0.15);
|
||||
color: var(--error-color);
|
||||
}
|
||||
|
||||
.dark .xx-title-type-tag.normal,
|
||||
[data-theme="dark"] .xx-title-type-tag.normal {
|
||||
background: var(--primary-soft);
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.dark .xx-title-type-tag.creative,
|
||||
[data-theme="dark"] .xx-title-type-tag.creative {
|
||||
background: rgba(202, 138, 4, 0.15);
|
||||
color: var(--warning-color);
|
||||
}
|
||||
|
||||
/* 使用次数 & 时间 */
|
||||
.xx-title-card-stat {
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--text-tertiary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 操作按钮区 */
|
||||
.xx-title-card-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xs);
|
||||
}
|
||||
|
||||
.xx-title-card-action-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-tertiary);
|
||||
cursor: pointer;
|
||||
padding: 4px 6px;
|
||||
border-radius: var(--radius-xs);
|
||||
font-size: var(--font-size-sm);
|
||||
transition: var(--transition-all);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xxs);
|
||||
}
|
||||
|
||||
.xx-title-card-action-btn:hover {
|
||||
color: var(--primary-color);
|
||||
background: var(--primary-soft);
|
||||
}
|
||||
|
||||
.xx-title-card-action-btn.danger:hover {
|
||||
color: var(--error-color);
|
||||
background: var(--error-soft);
|
||||
}
|
||||
|
||||
/* 收藏按钮 */
|
||||
.xx-title-fav-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-md);
|
||||
padding: var(--space-xxs);
|
||||
line-height: 1;
|
||||
transition: var(--transition-all);
|
||||
}
|
||||
|
||||
.xx-title-fav-btn:hover {
|
||||
transform: scale(1.2);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
空状态
|
||||
============================================================ */
|
||||
.xx-titles-empty {
|
||||
text-align: center;
|
||||
padding: var(--space-3xl) var(--space-xl);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.xx-titles-empty-icon {
|
||||
font-size: var(--font-size-3xl);
|
||||
margin-bottom: var(--space-md);
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
AI 生成结果列表
|
||||
============================================================ */
|
||||
.xx-ai-results {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-sm);
|
||||
margin-top: var(--space-md);
|
||||
}
|
||||
|
||||
.xx-ai-result-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-sm);
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-secondary);
|
||||
transition: var(--transition-all);
|
||||
}
|
||||
|
||||
.xx-ai-result-item:hover {
|
||||
border-color: var(--primary-color);
|
||||
background: var(--primary-soft);
|
||||
}
|
||||
|
||||
.xx-ai-result-text {
|
||||
flex: 1;
|
||||
font-size: var(--font-size-base);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.xx-ai-result-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xs);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* AI 加载动画 */
|
||||
.xx-ai-loading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--space-md);
|
||||
padding: var(--space-xl);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.xx-ai-loading-dots {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.xx-ai-loading-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: var(--radius-full);
|
||||
background: var(--primary-color);
|
||||
animation: ai-dot-bounce 1.4s ease-in-out infinite both;
|
||||
}
|
||||
|
||||
.xx-ai-loading-dot:nth-child(1) {
|
||||
animation-delay: 0s;
|
||||
}
|
||||
.xx-ai-loading-dot:nth-child(2) {
|
||||
animation-delay: 0.16s;
|
||||
}
|
||||
.xx-ai-loading-dot:nth-child(3) {
|
||||
animation-delay: 0.32s;
|
||||
}
|
||||
|
||||
@keyframes ai-dot-bounce {
|
||||
0%,
|
||||
80%,
|
||||
100% {
|
||||
transform: scale(0.4);
|
||||
opacity: 0.4;
|
||||
}
|
||||
40% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
响应式
|
||||
============================================================ */
|
||||
@media (max-width: 1200px) {
|
||||
.xx-titles-layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.xx-title-category-list {
|
||||
flex-direction: row;
|
||||
overflow-x: auto;
|
||||
position: static;
|
||||
gap: var(--space-sm);
|
||||
padding-bottom: var(--space-sm);
|
||||
}
|
||||
|
||||
.xx-title-category-item {
|
||||
min-width: 160px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.xx-title-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.xx-titles-page {
|
||||
padding: var(--space-md);
|
||||
}
|
||||
|
||||
.xx-title-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.xx-titles-filters {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.xx-titles-filters-left,
|
||||
.xx-titles-filters-right {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.xx-titles-page {
|
||||
padding: var(--space-sm);
|
||||
}
|
||||
|
||||
.xx-title-card {
|
||||
padding: 12px;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
export type TitleType = "hot" | "normal" | "creative"
|
||||
export type Industry = "general" | "food" | "tech" | "beauty" | "education" | "travel"
|
||||
export type Frequency = "all" | "high" | "medium" | "low"
|
||||
|
||||
export interface TitleData {
|
||||
id: string
|
||||
content: string
|
||||
type: TitleType
|
||||
industry: Industry
|
||||
category: string
|
||||
usageCount: number
|
||||
isFavorited: boolean
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface CategoryItem {
|
||||
id: string
|
||||
name: string
|
||||
count: number
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { TitleData, TitleType } from "../types/titleLibrary"
|
||||
import type { TitleItem } from "@/api/titles"
|
||||
|
||||
export const typeLabel = (type: TitleType): string => {
|
||||
switch (type) {
|
||||
case "hot":
|
||||
return "爆款"
|
||||
case "normal":
|
||||
return "常规"
|
||||
case "creative":
|
||||
return "创意"
|
||||
}
|
||||
}
|
||||
|
||||
/** 后端 TitleItem → 前端 TitleData 映射 */
|
||||
export const toTitleData = (item: TitleItem): TitleData => ({
|
||||
id: item.id,
|
||||
content: item.content,
|
||||
type: (item.category as TitleType) || "normal",
|
||||
industry: "general",
|
||||
category: item.category || "未分类",
|
||||
usageCount: 0,
|
||||
isFavorited: false,
|
||||
createdAt: item.created_at?.slice(0, 10) || "",
|
||||
})
|
||||
|
||||
/** 复制文本到剪贴板 */
|
||||
export const copyToClipboard = async (text: string): Promise<boolean> => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
return true
|
||||
} catch {
|
||||
/* 降级方案 */
|
||||
const textarea = document.createElement("textarea")
|
||||
textarea.value = text
|
||||
textarea.style.position = "fixed"
|
||||
textarea.style.opacity = "0"
|
||||
document.body.appendChild(textarea)
|
||||
textarea.select()
|
||||
try {
|
||||
document.execCommand("copy")
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
} finally {
|
||||
document.body.removeChild(textarea)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,10 +20,6 @@ const appChildren: RouteObject[] = [
|
||||
path: "assets",
|
||||
lazy: lazyRoute(() => import("@/pages/assets/AssetLibrary")),
|
||||
},
|
||||
{
|
||||
path: "titles",
|
||||
lazy: lazyRoute(() => import("@/pages/titles/TitleLibrary")),
|
||||
},
|
||||
{
|
||||
path: "scripts",
|
||||
lazy: lazyRoute(() => import("@/pages/scripts/ScriptLibrary")),
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
import React from "react"
|
||||
import { describe, expect, it, vi } from "vitest"
|
||||
import { render } from "@testing-library/react"
|
||||
import { MemoryRouter } from "react-router-dom"
|
||||
|
||||
vi.mock("@/components/layout/PageHead", () => ({
|
||||
default: ({ title }: { title: string }) => <div data-testid="page-head">{title}</div>,
|
||||
}))
|
||||
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: () => ({ data: [], isLoading: false, isError: false, refetch: vi.fn() }),
|
||||
useMutation: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isLoading: false }),
|
||||
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
|
||||
}))
|
||||
|
||||
vi.mock("@/components/ui", () => ({
|
||||
Button: ({ children, onClick }: any) => <button onClick={onClick}>{children}</button>,
|
||||
Input: ({ placeholder }: any) => <input placeholder={placeholder} />,
|
||||
Select: ({ options }: any) => (
|
||||
<select>
|
||||
{options?.map((o: any) => (
|
||||
<option key={o.value}>{o.label}</option>
|
||||
))}
|
||||
</select>
|
||||
),
|
||||
Modal: ({ open, children }: any) => (open ? <div role="dialog">{children}</div> : null),
|
||||
Empty: () => <div>Empty</div>,
|
||||
Card: ({ children }: any) => <div>{children}</div>,
|
||||
Tag: ({ children }: any) => <span>{children}</span>,
|
||||
Tooltip: ({ children }: any) => <span>{children}</span>,
|
||||
}))
|
||||
|
||||
vi.mock("antd", () => ({
|
||||
Modal: ({ open, children }: any) => (open ? <div role="dialog">{children}</div> : null),
|
||||
message: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },
|
||||
Popconfirm: ({ children }: any) => <span>{children}</span>,
|
||||
Form: ({ children }: any) => <form>{children}</form>,
|
||||
Input: ({ placeholder }: any) => <input placeholder={placeholder} />,
|
||||
InputNumber: () => <input type="number" />,
|
||||
}))
|
||||
|
||||
vi.mock("@ant-design/icons", () => ({
|
||||
PlusOutlined: () => <span />,
|
||||
EditOutlined: () => <span />,
|
||||
DeleteOutlined: () => <span />,
|
||||
SearchOutlined: () => <span />,
|
||||
FileTextOutlined: () => <span />,
|
||||
CopyOutlined: () => <span />,
|
||||
RobotOutlined: () => <span />,
|
||||
CheckOutlined: () => <span />,
|
||||
StarOutlined: () => <span />,
|
||||
}))
|
||||
|
||||
vi.mock("@/api/titles", () => ({
|
||||
getTitles: vi.fn().mockResolvedValue([]),
|
||||
createTitle: vi.fn().mockResolvedValue({ success: true }),
|
||||
updateTitle: vi.fn().mockResolvedValue({ success: true }),
|
||||
deleteTitle: vi.fn().mockResolvedValue({ success: true }),
|
||||
}))
|
||||
|
||||
vi.mock("@/store/authStore", () => ({
|
||||
useAuthStore: (sel: any) => sel({ user: { id: "1", vip_level: 0 }, isAuthenticated: true }),
|
||||
}))
|
||||
|
||||
vi.mock("@/pages/titles/titles.css", () => ({}))
|
||||
|
||||
import TitleLibrary from "@/pages/titles/TitleLibrary"
|
||||
import "@/pages/titles/types/titleLibrary"
|
||||
import "@/pages/titles/constants/titleLibrary"
|
||||
import "@/pages/titles/utils/titleLibrary"
|
||||
import "@/pages/titles/hooks/useTitleLibrary"
|
||||
import "@/pages/titles/hooks/useTitleEdit"
|
||||
import "@/pages/titles/hooks/useTitleAI"
|
||||
import "@/pages/titles/components/title-library/TitleCard"
|
||||
import "@/pages/titles/components/title-library/CategorySidebar"
|
||||
import "@/pages/titles/components/title-library/FilterBar"
|
||||
import "@/pages/titles/components/title-library/TitleGrid"
|
||||
import "@/pages/titles/components/title-library/CreateTitleModal"
|
||||
import "@/pages/titles/components/title-library/AIGenerateModal"
|
||||
|
||||
describe("TitleLibrary Page", () => {
|
||||
it("should render without crashing", () => {
|
||||
const { container } = render(
|
||||
<MemoryRouter>
|
||||
<TitleLibrary />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
expect(container.firstChild).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -1,29 +0,0 @@
|
||||
/**
|
||||
* TitleLibrary 模块 smoke test
|
||||
* 建立完整依赖链,确保 vitest related 模式能匹配到
|
||||
* titles 目录下所有文件的改动
|
||||
*/
|
||||
import { describe, it, expect } from "vitest"
|
||||
|
||||
// 主组件
|
||||
import "@/pages/titles/TitleLibrary"
|
||||
|
||||
// Hooks
|
||||
import "@/pages/titles/hooks/useTitleLibrary"
|
||||
import "@/pages/titles/hooks/useTitleLibrary/useTitleData"
|
||||
import "@/pages/titles/hooks/useTitleLibrary/useTitleFilters"
|
||||
import "@/pages/titles/hooks/useTitleLibrary/useTitleMutations"
|
||||
import "@/pages/titles/hooks/useTitleLibrary/useTitleActions"
|
||||
|
||||
// 类型与常量
|
||||
import "@/pages/titles/types/titleLibrary"
|
||||
import "@/pages/titles/constants/titleLibrary"
|
||||
|
||||
// 工具函数
|
||||
import "@/pages/titles/utils/titleLibrary"
|
||||
|
||||
describe("TitleLibrary module smoke test", () => {
|
||||
it("should load all title modules", () => {
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
"""验证 extract-from-douyin 在各种失败场景返回正确的 HTTP 状态码(绝不能 500)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
@@ -6,9 +7,8 @@ import types
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from app.auth import AuthenticatedUser
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
|
||||
class _FakeUser:
|
||||
@@ -24,6 +24,7 @@ def fake_user():
|
||||
|
||||
class _FakeYDLBase:
|
||||
"""通用假 yt-dlp 基类"""
|
||||
|
||||
extract_info_result = None
|
||||
extract_info_raises = None
|
||||
prepare_filename_result = "/tmp/fake.mp4"
|
||||
@@ -57,6 +58,7 @@ def _install_fake_ytdlp(fake_ydl_class, *, download_error_cls=None):
|
||||
|
||||
def _import_target():
|
||||
from app.api.routes import scripts_ai
|
||||
|
||||
return scripts_ai
|
||||
|
||||
|
||||
@@ -67,14 +69,18 @@ def test_download_http404_returns_400_not_500(fake_user):
|
||||
|
||||
class DownloadError(Exception):
|
||||
pass
|
||||
|
||||
class FailingYDL(_FakeYDLBase):
|
||||
extract_info_raises = DownloadError("ERROR: Unable to download webpage: HTTP Error 404: Not Found")
|
||||
|
||||
_install_fake_ytdlp(FailingYDL, download_error_cls=DownloadError)
|
||||
|
||||
with mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
scripts_ai.extract_from_douyin(request=body, current_user=fake_user, db=mock.MagicMock())
|
||||
assert exc.value.status_code == status.HTTP_400_BAD_REQUEST, f"应为400,实际 {exc.value.status_code}: {exc.value.detail}"
|
||||
assert (
|
||||
exc.value.status_code == status.HTTP_400_BAD_REQUEST
|
||||
), f"应为400,实际 {exc.value.status_code}: {exc.value.detail}"
|
||||
assert "无法解析" in exc.value.detail or "抖音" in exc.value.detail
|
||||
|
||||
|
||||
@@ -85,8 +91,10 @@ def test_download_network_error_returns_502_not_500(fake_user):
|
||||
|
||||
class DownloadError(Exception):
|
||||
pass
|
||||
|
||||
class NetErrYDL(_FakeYDLBase):
|
||||
extract_info_raises = DownloadError("ERROR: Connection reset by peer")
|
||||
|
||||
_install_fake_ytdlp(NetErrYDL, download_error_cls=DownloadError)
|
||||
|
||||
with mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)):
|
||||
@@ -102,6 +110,7 @@ def test_info_none_returns_400(fake_user):
|
||||
|
||||
class NoneInfoYDL(_FakeYDLBase):
|
||||
extract_info_result = None
|
||||
|
||||
_install_fake_ytdlp(NoneInfoYDL)
|
||||
|
||||
with mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)):
|
||||
@@ -113,16 +122,21 @@ def test_info_none_returns_400(fake_user):
|
||||
def test_asr_not_configured_returns_503(fake_user):
|
||||
scripts_ai = _import_target()
|
||||
from app.services.script_asr_service import ASRNotConfiguredError
|
||||
|
||||
body = scripts_ai.ExtractFromDouyinRequest(url="https://v.douyin.com/abc/")
|
||||
|
||||
import os.path
|
||||
|
||||
class OkYDL(_FakeYDLBase):
|
||||
extract_info_result = {"id":"x","duration":10,"title":"t"}
|
||||
extract_info_result = {"id": "x", "duration": 10, "title": "t"}
|
||||
|
||||
_install_fake_ytdlp(OkYDL)
|
||||
with mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)), \
|
||||
mock.patch.object(scripts_ai.os.path, "isfile", return_value=True), \
|
||||
mock.patch.object(scripts_ai.os.path, "getsize", return_value=1024), \
|
||||
mock.patch.object(scripts_ai, "transcribe_to_text", side_effect=ASRNotConfiguredError("未配置")):
|
||||
with (
|
||||
mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)),
|
||||
mock.patch.object(scripts_ai.os.path, "isfile", return_value=True),
|
||||
mock.patch.object(scripts_ai.os.path, "getsize", return_value=1024),
|
||||
mock.patch.object(scripts_ai, "transcribe_to_text", side_effect=ASRNotConfiguredError("未配置")),
|
||||
):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
scripts_ai.extract_from_douyin(request=body, current_user=fake_user, db=mock.MagicMock())
|
||||
assert exc.value.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
|
||||
@@ -131,15 +145,19 @@ def test_asr_not_configured_returns_503(fake_user):
|
||||
def test_asr_failure_returns_502(fake_user):
|
||||
scripts_ai = _import_target()
|
||||
from app.services.script_asr_service import ASRTranscriptionError
|
||||
|
||||
body = scripts_ai.ExtractFromDouyinRequest(url="https://v.douyin.com/abc/")
|
||||
|
||||
class OkYDL(_FakeYDLBase):
|
||||
extract_info_result = {"id":"x","duration":10,"title":"t"}
|
||||
extract_info_result = {"id": "x", "duration": 10, "title": "t"}
|
||||
|
||||
_install_fake_ytdlp(OkYDL)
|
||||
with mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)), \
|
||||
mock.patch.object(scripts_ai.os.path, "isfile", return_value=True), \
|
||||
mock.patch.object(scripts_ai.os.path, "getsize", return_value=1024), \
|
||||
mock.patch.object(scripts_ai, "transcribe_to_text", side_effect=ASRTranscriptionError("识别失败")):
|
||||
with (
|
||||
mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)),
|
||||
mock.patch.object(scripts_ai.os.path, "isfile", return_value=True),
|
||||
mock.patch.object(scripts_ai.os.path, "getsize", return_value=1024),
|
||||
mock.patch.object(scripts_ai, "transcribe_to_text", side_effect=ASRTranscriptionError("识别失败")),
|
||||
):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
scripts_ai.extract_from_douyin(request=body, current_user=fake_user, db=mock.MagicMock())
|
||||
assert exc.value.status_code == status.HTTP_502_BAD_GATEWAY
|
||||
@@ -151,12 +169,15 @@ def test_asr_unexpected_error_returns_502_not_500(fake_user):
|
||||
body = scripts_ai.ExtractFromDouyinRequest(url="https://v.douyin.com/abc/")
|
||||
|
||||
class OkYDL(_FakeYDLBase):
|
||||
extract_info_result = {"id":"x","duration":10,"title":"t"}
|
||||
extract_info_result = {"id": "x", "duration": 10, "title": "t"}
|
||||
|
||||
_install_fake_ytdlp(OkYDL)
|
||||
with mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)), \
|
||||
mock.patch.object(scripts_ai.os.path, "isfile", return_value=True), \
|
||||
mock.patch.object(scripts_ai.os.path, "getsize", return_value=1024), \
|
||||
mock.patch.object(scripts_ai, "transcribe_to_text", side_effect=RuntimeError("ffmpeg crashed")):
|
||||
with (
|
||||
mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)),
|
||||
mock.patch.object(scripts_ai.os.path, "isfile", return_value=True),
|
||||
mock.patch.object(scripts_ai.os.path, "getsize", return_value=1024),
|
||||
mock.patch.object(scripts_ai, "transcribe_to_text", side_effect=RuntimeError("ffmpeg crashed")),
|
||||
):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
scripts_ai.extract_from_douyin(request=body, current_user=fake_user, db=mock.MagicMock())
|
||||
assert exc.value.status_code == status.HTTP_502_BAD_GATEWAY, f"应为502,实际 {exc.value.status_code}"
|
||||
@@ -168,10 +189,13 @@ def test_missing_downloaded_file_returns_502_not_500(fake_user):
|
||||
body = scripts_ai.ExtractFromDouyinRequest(url="https://v.douyin.com/abc/")
|
||||
|
||||
class OkYDL(_FakeYDLBase):
|
||||
extract_info_result = {"id":"x","duration":10,"title":"t"}
|
||||
extract_info_result = {"id": "x", "duration": 10, "title": "t"}
|
||||
|
||||
_install_fake_ytdlp(OkYDL)
|
||||
with mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)), \
|
||||
mock.patch.object(scripts_ai.os.path, "isfile", return_value=False):
|
||||
with (
|
||||
mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)),
|
||||
mock.patch.object(scripts_ai.os.path, "isfile", return_value=False),
|
||||
):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
scripts_ai.extract_from_douyin(request=body, current_user=fake_user, db=mock.MagicMock())
|
||||
assert exc.value.status_code != 500
|
||||
@@ -185,9 +209,11 @@ def test_any_unexpected_error_does_not_return_500_raw(fake_user):
|
||||
|
||||
class BuggyYDL(_FakeYDLBase):
|
||||
def extract_info(self, url, download=True):
|
||||
return {"id":"x","duration":"not_a_number","title":"t"}
|
||||
return {"id": "x", "duration": "not_a_number", "title": "t"}
|
||||
|
||||
def prepare_filename(self, info):
|
||||
raise RuntimeError("some internal bug")
|
||||
|
||||
_install_fake_ytdlp(BuggyYDL)
|
||||
with mock.patch.object(scripts_ai, "get_doubao_client", return_value=mock.MagicMock(is_available=True)):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
|
||||
Reference in New Issue
Block a user