Files
xiaoxia-saas/apps/web/src/pages/scripts/ScriptLibrary.tsx
T
xiaoxia b2ba78c16c
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 2s
CI/CD Pipeline / Check push changed paths (push) Successful in 2s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / Build Staging API Image (push) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m22s
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (push) Successful in 18s
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Successful in 19s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 53s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 2m52s
CI/CD Pipeline / Integration Tests (push) Successful in 3m42s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m51s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 4m44s
CI/CD Pipeline / Validate - Style (push) Successful in 5m3s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m15s
CI/CD Pipeline / Staging E2E Tests (push) Successful in 3m17s
CI/CD Pipeline / Validate - Security (push) Successful in 9m41s
CI/CD Pipeline / Unit Tests (push) Successful in 10m40s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
fix(ux): #1894 抖音提取前端不再拦截非http开头文本,透传后端400错误 (#1972)
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-17 10:01:31 +08:00

661 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 文案库页面 — Issue #1811#1894 方向修正后)
* 功能:
* - 列表页:卡片列表,搜索(标题/正文)、分类标签筛选、分页
* 每条卡片展示:title(标题)、content 前 100 字摘要、分类 Tag、tags、使用次数、时间
* 操作:编辑 / 删除 / 复制 / 使用(跳创作页预填)
* - 新建/编辑弹窗:标题(原"名称")、正文(含 AI 改写)、分类、标签
* - #1893/#1894 AI 能力:
* - 顶部「🎬 从抖音提取」按钮 → 粘贴分享文案/链接(后端自动提取URL) → ASR 提取文案 → 自动填充到新建弹窗
* - 正文下方「✨ AI 改写」按钮 → 点击直接执行(美化 loading spinner + "正在改写..."),
* 成功自动替换正文并 toast「改写成功」1s 自动关闭;失败 toast 错误
* - 标题旁「✨ AI 生成标题」按钮 → 候选列表一键填入
* - 删除确认(Popconfirm
* - 对接 api/scripts CRUDmock 阶段 SCRIPTS_API_MOCK=trueAI 接口始终走真实 API
*/
import React, { useCallback, useEffect, useState } from "react"
import {
Button,
Card,
Empty,
Form,
Input,
Modal,
Pagination,
Popconfirm,
Select,
Space,
Spin,
Tag,
Tooltip,
Typography,
message,
} from "antd"
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
CopyOutlined,
PlayCircleOutlined,
SearchOutlined,
TagsOutlined,
VideoCameraOutlined,
RobotOutlined,
BulbOutlined,
} from "@ant-design/icons"
import { useNavigate } from "react-router-dom"
import {
getScripts,
createScript,
updateScript,
deleteScript,
duplicateScript,
extractScriptFromDouyin,
aiRewriteScript,
aiGenerateTitles,
REWRITE_STYLE_OPTIONS,
} from "@/api/scripts"
import type { ScriptItem, ScriptCategory, ScriptUpsertRequest, RewriteStyle } from "@/api/scripts"
import { SCRIPT_CATEGORY_LABEL } from "@/api/scripts"
import "./scripts.css"
const { TextArea } = Input
const { Paragraph, Text } = Typography
const PAGE_SIZE = 12
const CATEGORY_OPTIONS: { value: ScriptCategory | "all"; label: string }[] = [
{ value: "all", label: "全部分类" },
...Object.entries(SCRIPT_CATEGORY_LABEL).map(([value, label]) => ({
value: value as ScriptCategory,
label,
})),
]
/** 提取后端返回的错误 detail(全局拦截器可能已弹 toast,但这里再兜一层) */
function extractErrMsg(err: unknown, fallback: string): string {
const e = err as {
response?: { data?: { detail?: string | { message?: string }; message?: string } }
message?: string
}
const data = e?.response?.data
if (data?.detail) {
if (typeof data.detail === "string") return data.detail
if (typeof data.detail.message === "string") return data.detail.message
}
if (data?.message && typeof data.message === "string") return data.message
if (e?.message) return e.message
return fallback
}
const ScriptLibrary: React.FC = () => {
const navigate = useNavigate()
const [items, setItems] = useState<ScriptItem[]>([])
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [loading, setLoading] = useState(false)
const [keyword, setKeyword] = useState("")
const [category, setCategory] = useState<ScriptCategory | "all">("all")
// 主弹窗状态
const [modalOpen, setModalOpen] = useState(false)
const [editing, setEditing] = useState<ScriptItem | null>(null)
const [submitting, setSubmitting] = useState(false)
const [form] = Form.useForm<ScriptUpsertRequest & { tags_text?: string }>()
// ── #1893 AI 能力状态 ──
// 抖音提取
const [douyinModalOpen, setDouyinModalOpen] = useState(false)
const [douyinUrl, setDouyinUrl] = useState("")
const [douyinLoading, setDouyinLoading] = useState(false)
// AI 改写(#1894: 点击直接执行,美化 loading + 1s 自动关闭 toast,不弹确认弹窗)
const [rewriteStyle, setRewriteStyle] = useState<RewriteStyle>("口语化")
const [rewriteLoading, setRewriteLoading] = useState(false)
// AI 生成标题
const [titleGenLoading, setTitleGenLoading] = useState(false)
const [titleCandidates, setTitleCandidates] = useState<string[]>([])
const load = useCallback(async () => {
setLoading(true)
try {
const res = await getScripts({
page,
page_size: PAGE_SIZE,
keyword: keyword.trim() || undefined,
category,
})
if (Array.isArray(res)) {
setItems(res)
setTotal(res.length)
} else {
setItems(res.items ?? [])
setTotal(res.total ?? 0)
}
} catch (err) {
message.error(extractErrMsg(err, "加载文案列表失败"))
} finally {
setLoading(false)
}
}, [page, keyword, category])
useEffect(() => {
load()
}, [load])
const resetCreateForm = () => {
form.resetFields()
form.setFieldsValue({
title: "",
content: "",
segments: [],
tags: [],
title_category: "other",
})
setTitleCandidates([])
}
const openCreate = () => {
setEditing(null)
resetCreateForm()
setModalOpen(true)
}
const openEdit = (item: ScriptItem) => {
setEditing(item)
form.setFieldsValue({
title: item.title,
content: item.content,
segments: item.segments ?? item.content.split(/\n\n+/).filter(Boolean),
tags: item.tags ?? [],
title_category: item.title_category ?? "other",
})
setTitleCandidates([])
setModalOpen(true)
}
const closeModal = () => {
setModalOpen(false)
setEditing(null)
setTitleCandidates([])
}
/** 提交新建/编辑 */
const handleSubmit = async () => {
try {
const values = await form.validateFields()
setSubmitting(true)
const payload: ScriptUpsertRequest = {
title: values.title.trim(),
content: values.content,
segments: values.segments?.filter(Boolean) ?? values.content.split(/\n\n+/).filter(Boolean),
tags: values.tags ?? [],
title_category: values.title_category,
// #1894: 配套标题 / 标题样式配置字段已从 UI 移除,后端即将删除,不再传
}
if (editing) {
await updateScript(editing.id, payload)
message.success("文案已更新")
} else {
await createScript(payload)
message.success("文案已创建")
}
closeModal()
await load()
} catch (err) {
if ((err as { errorFields?: unknown })?.errorFields) return
message.error(extractErrMsg(err, "保存失败"))
} finally {
setSubmitting(false)
}
}
const handleDelete = async (id: string) => {
try {
await deleteScript(id)
message.success("文案已删除")
if (items.length === 1 && page > 1) {
setPage(page - 1)
} else {
await load()
}
} catch (err) {
message.error(extractErrMsg(err, "删除失败"))
}
}
const handleDuplicate = async (id: string) => {
try {
await duplicateScript(id)
message.success("已复制")
setPage(1)
await load()
} catch (err) {
message.error(extractErrMsg(err, "复制失败"))
}
}
/** 使用:跳创作页,query 带 scriptId 预填 */
const handleUse = (item: ScriptItem) => {
navigate(`/app/generate?scriptId=${encodeURIComponent(item.id)}`)
}
const preview = (content: string) => {
const text = content.replace(/\s+/g, " ").trim()
if (text.length <= 100) return text || "(空)"
return `${text.slice(0, 100)}…`
}
const formatTime = (iso?: string) => {
if (!iso) return "-"
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return iso
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())}`
}
const categoryColor: Record<ScriptCategory, string> = {
promo: "red",
vlog: "blue",
knowledge: "green",
story: "purple",
emotion: "magenta",
other: "default",
}
// ── #1893 AI 操作 ──
/** 打开抖音提取弹窗 */
const openDouyinModal = () => {
setDouyinUrl("")
setDouyinModalOpen(true)
}
/** #1894:执行抖音提取。前端不再做 URL 前缀校验,直接把用户粘贴的原文(含分享文案+链接)交给后端 _extract_url_from_text 自动提取。后端 400 错误(未找到链接/非抖音域名等)直接透传给用户。 */
const handleDouyinExtract = async () => {
const raw = douyinUrl.trim()
if (!raw) {
message.warning("请粘贴抖音视频链接或分享文案")
return
}
setDouyinLoading(true)
try {
const res = await extractScriptFromDouyin({ url: raw })
message.success(`提取成功${res.duration_seconds ? `(时长 ${res.duration_seconds}s` : ""}`)
setDouyinModalOpen(false)
setDouyinUrl("")
// 关闭抖音弹窗,打开新建弹窗预填 content
setEditing(null)
resetCreateForm()
form.setFieldsValue({
title: "",
content: res.text,
tags: [],
title_category: "other",
})
setModalOpen(true)
} catch (err) {
// 后端 400(未找到有效链接/仅支持抖音域名等)直接透传错误信息
message.error(extractErrMsg(err, "抖音文案提取失败"))
} finally {
setDouyinLoading(false)
}
}
/** #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)
try {
const res = await aiRewriteScript({ content, style })
form.setFieldsValue({ content: res.rewritten })
message.success({ content: "改写成功", duration: 1 })
} catch (err) {
message.error(extractErrMsg(err, "AI 改写失败"))
} finally {
setRewriteLoading(false)
}
}
/** 执行 AI 生成标题,生成候选 */
const handleGenerateTitles = async () => {
const content = form.getFieldValue("content") as string | undefined
if (!content || !content.trim()) {
message.warning("请先填写文案内容")
return
}
setTitleGenLoading(true)
setTitleCandidates([])
try {
const res = await aiGenerateTitles({ content, count: 3 })
if (!res.titles || res.titles.length === 0) {
message.info("AI 未返回可用标题,请稍后再试")
return
}
setTitleCandidates(res.titles)
} catch (err) {
message.error(extractErrMsg(err, "AI 生成标题失败"))
} finally {
setTitleGenLoading(false)
}
}
/** 点击候选标题直接填入 title 字段 */
const pickTitle = (t: string) => {
form.setFieldsValue({ title: t })
}
// 监听 content 字段,用于禁用生成标题按钮(content 为空时)
const watchedContent = Form.useWatch("content", form)
const contentEmpty = !watchedContent || !String(watchedContent).trim()
return (
<div className="xx-scripts-page">
<div className="xx-scripts-layout">
{/* 顶部筛选栏 */}
<div className="xx-scripts-filters">
<Space wrap size={12} className="xx-scripts-filters-left">
<Input
prefix={<SearchOutlined />}
placeholder="搜索标题或正文"
value={keyword}
onChange={(e) => {
setKeyword(e.target.value)
setPage(1)
}}
allowClear
style={{ width: 260 }}
/>
<Select
value={category}
onChange={(v) => {
setCategory(v)
setPage(1)
}}
style={{ width: 140 }}
options={CATEGORY_OPTIONS}
/>
</Space>
<div className="xx-scripts-filters-right">
<Button icon={<VideoCameraOutlined />} onClick={openDouyinModal}>
🎬 从抖音提取
</Button>
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
新建文案
</Button>
</div>
</div>
{/* 列表 */}
{loading ? (
<div className="xx-scripts-loading">加载中…</div>
) : items.length === 0 ? (
<Empty
description={
keyword || category !== "all"
? "没有匹配的文案"
: "暂无文案,点击右上角「新建文案」或「🎬 从抖音提取」开始创作"
}
/>
) : (
<>
<div className="xx-scripts-list">
{items.map((s) => (
<Card key={s.id} className="xx-script-card" hoverable size="small">
<div className="xx-script-card-header">
<div className="xx-script-title-row">
<span className="xx-script-title">{s.title}</span>
{s.title_category && (
<Tag color={categoryColor[s.title_category] ?? "default"}>
{SCRIPT_CATEGORY_LABEL[s.title_category]}
</Tag>
)}
</div>
<Space size={4} className="xx-script-actions">
<Button
size="small"
type="text"
icon={<PlayCircleOutlined />}
onClick={() => handleUse(s)}
>
使用
</Button>
<Button
size="small"
type="text"
icon={<CopyOutlined />}
onClick={() => handleDuplicate(s.id)}
>
复制
</Button>
<Button
size="small"
type="text"
icon={<EditOutlined />}
onClick={() => openEdit(s)}
>
编辑
</Button>
<Popconfirm
title="确认删除此文案?"
description="删除后不可恢复"
okText="删除"
cancelText="取消"
okButtonProps={{ danger: true }}
onConfirm={() => handleDelete(s.id)}
>
<Button size="small" type="text" danger icon={<DeleteOutlined />}>
删除
</Button>
</Popconfirm>
</Space>
</div>
<div className="xx-script-preview">{preview(s.content)}</div>
{s.tags && s.tags.length > 0 && (
<div className="xx-script-tags">
<TagsOutlined
style={{ color: "var(--text-tertiary, #999)", marginRight: 4 }}
/>
{s.tags.map((t, i) => (
<Tag key={`${t}-${i}`} color="blue">
{t}
</Tag>
))}
</div>
)}
<div className="xx-script-meta">
<span>{s.char_count ?? s.content.length} </span>
<span className="xx-script-meta-sep">·</span>
<span>使用 {s.use_count ?? 0} </span>
<span className="xx-script-meta-sep">·</span>
<span>{formatTime(s.updated_at ?? s.created_at)}</span>
</div>
</Card>
))}
</div>
{total > PAGE_SIZE && (
<div className="xx-scripts-pagination">
<Pagination
current={page}
pageSize={PAGE_SIZE}
total={total}
onChange={(p) => setPage(p)}
showSizeChanger={false}
/>
</div>
)}
</>
)}
</div>
{/* 新建/编辑弹窗 */}
<Modal
title={editing ? "编辑文案" : "新建文案"}
open={modalOpen}
onCancel={closeModal}
onOk={handleSubmit}
confirmLoading={submitting}
destroyOnClose
okText={editing ? "保存" : "创建"}
cancelText="取消"
width={680}
>
<Form
form={form}
layout="vertical"
initialValues={{
title_category: "other",
}}
>
<Form.Item
name="title"
label={
<span>
标题
{/* #1893 UX: disabled 时原生 title 在 antd Button 上不触发,
用 Tooltip + span 包裹保证提示可见 */}
<Tooltip
title={contentEmpty ? "请先填写文案内容" : "基于正文 AI 生成 3 个候选标题"}
>
<span style={{ display: "inline-flex", marginLeft: 4 }}>
<Button
type="link"
size="small"
icon={<BulbOutlined />}
loading={titleGenLoading}
disabled={contentEmpty}
onClick={handleGenerateTitles}
style={{ padding: "0 4px", height: 22 }}
>
AI 生成标题
</Button>
</span>
</Tooltip>
</span>
}
rules={[{ required: true, message: "请填写视频标题" }, { max: 200 }]}
>
<Input placeholder="输入视频标题" maxLength={200} />
</Form.Item>
{/* AI 生成标题候选列表 */}
{titleCandidates.length > 0 && (
<div className="xx-ai-title-candidates">
<Text type="secondary" style={{ fontSize: 12 }}>
点击候选直接填入:
</Text>
<div className="xx-ai-title-list">
{titleCandidates.map((t, i) => (
<Tag
key={`${t}-${i}`}
color="purple"
className="xx-ai-title-tag"
onClick={() => pickTitle(t)}
>
{t}
</Tag>
))}
</div>
</div>
)}
<Form.Item
name="content"
label="正文"
rules={[{ required: true, message: "请填写正文" }]}
extra="段落间用空行分隔,保存时会自动按空行切分为 segments。"
>
<TextArea placeholder="在这里输入文案正文…" rows={6} maxLength={10000} />
</Form.Item>
{/* AI 改写工具条(#1894 UX:点击直接执行,自定义渐变圆环 loading) */}
<div className="xx-ai-rewrite-bar">
<Space size={8} wrap align="center">
<Select
value={rewriteStyle}
onChange={setRewriteStyle}
options={REWRITE_STYLE_OPTIONS}
style={{ width: 110 }}
size="small"
disabled={rewriteLoading}
/>
<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>
)}
</Space>
</div>
<Form.Item name="segments" hidden>
<Input />
</Form.Item>
<Form.Item name="tags" label="标签" style={{ marginTop: 12 }}>
<Select
mode="tags"
placeholder="输入标签后回车添加"
tokenSeparators={[",", ""]}
style={{ width: "100%" }}
/>
</Form.Item>
</Form>
</Modal>
{/* 抖音提取弹窗 */}
<Modal
title="🎬 从抖音视频提取文案"
open={douyinModalOpen}
onCancel={() => !douyinLoading && setDouyinModalOpen(false)}
onOk={handleDouyinExtract}
confirmLoading={douyinLoading}
okText="开始提取"
cancelText="取消"
maskClosable={!douyinLoading}
closable={!douyinLoading}
destroyOnClose
>
<Paragraph type="secondary" style={{ marginBottom: 12, fontSize: 13 }}>
粘贴抖音分享文案或链接即可,系统会自动从文本中识别链接(支持 v.douyin.com 短链、
www.douyin.com/video/ 长链,以及 App「复制链接」带的分享文案)。AI
将自动下载音频并识别文案, 首次识别可能需要 5-15 秒。
</Paragraph>
<Input.TextArea
placeholder="直接粘贴 App「复制链接」的全部内容即可,例如:8.88 复制打开抖音... https://v.douyin.com/xxxxx/"
value={douyinUrl}
onChange={(e) => setDouyinUrl(e.target.value)}
rows={2}
autoSize={{ minRows: 2, maxRows: 4 }}
disabled={douyinLoading}
/>
{douyinLoading && (
<div className="xx-ai-loading-hint">
<Spin size="small" style={{ marginRight: 8 }} />
提取中,正在下载视频并识别文案,可能需要数秒,请稍候…
</div>
)}
</Modal>
</div>
)
}
export default ScriptLibrary