fix(cover): 修复AI数字人封面打开崩溃 Cannot read properties of undefined (reading 'text') (#2036)
CI/CD Pipeline / Check push changed paths (pull_request) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (pull_request) Successful in 1s
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 0s
CI/CD Pipeline / Unit Tests (pull_request) Has been skipped
CI/CD Pipeline / Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / PR Build API Image (pull_request) Has been skipped
CI/CD Pipeline / PR Build Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
CI/CD Pipeline / Frontend Lint (pull_request) Failing after 1m3s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 1m8s
Preview Deploy / Deploy Preview Environment (pull_request) Successful in 1m47s
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 1m54s
CI/CD Pipeline / Frontend Unit Tests (pull_request) Successful in 1m57s
CI/CD Pipeline / Validate - Style (pull_request) Successful in 2m50s
CI/CD Pipeline / Validate - Python (mypy + alembic) (pull_request) Successful in 3m5s
CI/CD Pipeline / Build Production API Image (pull_request) Has been cancelled
CI/CD Pipeline / Build Production Web Image (pull_request) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been cancelled
CI/CD Pipeline / Deploy Production (pull_request) Has been cancelled
CI/CD Pipeline / Production Browser E2E (pull_request) Has been cancelled
CI/CD Pipeline / Canary Release to Production (pull_request) Has been cancelled
CI/CD Pipeline / CI Gate (pull_request) Has been cancelled
CI/CD Pipeline / Validate - Security (pull_request) Has been cancelled
AI Code Review / AI Code Review (pull_request) Has been cancelled
PR Automation / Auto Merge on CI Green + Approved (pull_request) Has been cancelled

根因:后端 /cover-templates 返回的模板如果 config 字段缺失或只有部分字段(title/subtitle 对象为 undefined),
CoverEditorModal 用浅拷贝 {...template?.config} 初始化 state,导致 cfg.title/cfg.subtitle 为 undefined,
后续渲染时访问 tc.text 触发崩溃。useSharedCover 在拉取模板后未做 config 字段归一化,首次打开时传入
缺少字段的模板对象给 CoverEditorModal 也会触发。

修复:
- CoverEditorModal 新增 mergeEditorConfig 深合并工具:缺失字段用 DEFAULT_EDITOR_CONFIG 补齐,
  对 title/subtitle/shadows/background/position 等嵌套对象做深拷贝,避免共享引用
- 初始化 cfg 与 open 时重置 state 都改用 mergeEditorConfig
- renderTextStyle/renderTextLines/TextStylePanel 增加 null/undefined 防御
- 画布渲染处 cfg.title && cfg.subtitle && 条件渲染
- useSharedCover 的 reloadTemplates 兼容 {items:[]} 与直接数组两种响应格式,并确保每个模板都带 config 字段

tsc/eslint/prettier 全过,构建产物 bundle 检查无不安全的 .text 访问。
This commit is contained in:
xiaoxia
2026-09-25 18:03:52 +08:00
parent 751f8ad84e
commit 0d8b03ca1f
2 changed files with 53 additions and 13 deletions
@@ -76,8 +76,16 @@ export function useSharedCover(opts: UseSharedCoverOptions): UseSharedCoverRetur
setTemplatesLoading(true)
setTemplatesError(null)
try {
const res = await fetchCoverTemplates()
setTemplates(res.items || [])
const res: any = await fetchCoverTemplates()
// 兼容两种响应:{items:[...]} 或直接数组
const list = Array.isArray(res) ? res : res?.items || []
// 过滤掉后端可能返回的没有 config 的模板(避免编辑器打开时访问 .title.text 崩溃)
setTemplates(
list.map((t: any) => ({
...t,
config: t.config || undefined,
})),
)
} catch (err) {
console.error("[SharedCover] 加载封面模板失败:", err)
setTemplatesError("加载模板失败,请稍后重试")
@@ -12,6 +12,31 @@ import Modal from "@/components/ui/Modal"
import Button from "@/components/ui/Button"
import "@/components/cover/cover.css"
/** 安全合并模板 config 与默认配置(深拷贝 title/subtitle/shadows/background 等嵌套对象,避免共享引用 & 字段缺失) */
const mergeEditorConfig = (partial?: Partial<CoverEditorConfig> | null): CoverEditorConfig => {
const def = DEFAULT_EDITOR_CONFIG
const src = partial || {}
const mergeText = (
base: TextStyleConfig,
patch?: Partial<TextStyleConfig> | null,
): TextStyleConfig => ({
...base,
...(patch || {}),
position: { ...base.position, ...(patch?.position || {}) },
background: { ...base.background, ...(patch?.background || {}) },
shadows: Array.isArray(patch?.shadows) ? [...patch!.shadows] : [...base.shadows],
})
return {
...def,
...src,
title: mergeText(def.title, src.title),
subtitle: mergeText(def.subtitle, src.subtitle),
portraitPosition: { ...def.portraitPosition, ...(src.portraitPosition || {}) },
backgroundPosition: { ...def.backgroundPosition, ...(src.backgroundPosition || {}) },
maskPosition: { ...def.maskPosition, ...(src.maskPosition || {}) },
}
}
/* ── Props ── */
interface CoverEditorModalProps {
open: boolean
@@ -98,10 +123,11 @@ const getFontFamily = (name: string): string => {
/* ── Text style panel (shared between title & subtitle) ── */
const TextStylePanel: React.FC<{
config: TextStyleConfig
config: TextStyleConfig | undefined | null
onChange: (c: TextStyleConfig) => void
placeholder: string
}> = ({ config, onChange, placeholder }) => {
if (!config) return null
const upd = <K extends keyof TextStyleConfig>(key: K, val: TextStyleConfig[K]) =>
onChange({ ...config, [key]: val })
return (
@@ -274,9 +300,9 @@ const TextStylePanel: React.FC<{
/* ══════════════ Main Component ══════════════ */
const CoverEditorModal: React.FC<CoverEditorModalProps> = ({ open, onClose, template, onSave }) => {
const initCfg = template?.config ?? DEFAULT_EDITOR_CONFIG
const initCfg = mergeEditorConfig(template?.config)
const [name, setName] = useState(template?.name ?? "")
const [cfg, setCfg] = useState<CoverEditorConfig>(() => ({ ...initCfg }))
const [cfg, setCfg] = useState<CoverEditorConfig>(() => mergeEditorConfig(template?.config))
const [sections, setSections] = useState<Record<SectionKey, boolean>>({
basic: true,
portrait: false,
@@ -294,8 +320,8 @@ const CoverEditorModal: React.FC<CoverEditorModalProps> = ({ open, onClose, temp
// reset state when modal opens with a new template
useEffect(() => {
if (open) {
const c = template?.config ?? DEFAULT_EDITOR_CONFIG
setCfg({ ...c })
const c = mergeEditorConfig(template?.config)
setCfg(c)
setName(template?.name ?? "")
setBgImageUrl(c.backgroundImage || "")
setPortraitImageUrl(c.portraitImage || "")
@@ -366,7 +392,8 @@ const CoverEditorModal: React.FC<CoverEditorModalProps> = ({ open, onClose, temp
const s = (px: number) => Math.round(px * SCALE * 100) / 100
const renderTextStyle = (tc: TextStyleConfig): React.CSSProperties => {
const renderTextStyle = (tc: TextStyleConfig | undefined | null): React.CSSProperties => {
if (!tc) return {}
// wrap text by charsPerLine
const rawText = tc.text || ""
const lines: string[] = []
@@ -407,7 +434,8 @@ const CoverEditorModal: React.FC<CoverEditorModalProps> = ({ open, onClose, temp
return style
}
const renderTextLines = (tc: TextStyleConfig) => {
const renderTextLines = (tc: TextStyleConfig | undefined | null): string => {
if (!tc) return ""
const raw = tc.text || ""
if (tc.direction === "vertical") return raw
const per = Math.max(1, tc.charsPerLine)
@@ -608,7 +636,7 @@ const CoverEditorModal: React.FC<CoverEditorModalProps> = ({ open, onClose, temp
{sections.title && (
<div className="xx-ce-section-body">
<TextStylePanel
config={cfg.title}
config={cfg.title || DEFAULT_EDITOR_CONFIG.title}
onChange={updTitle}
placeholder="输入主标题文字"
/>
@@ -625,7 +653,7 @@ const CoverEditorModal: React.FC<CoverEditorModalProps> = ({ open, onClose, temp
{sections.subtitle && (
<div className="xx-ce-section-body">
<TextStylePanel
config={cfg.subtitle}
config={cfg.subtitle || DEFAULT_EDITOR_CONFIG.subtitle}
onChange={updSubtitle}
placeholder="输入副标题文字"
/>
@@ -887,10 +915,14 @@ const CoverEditorModal: React.FC<CoverEditorModalProps> = ({ open, onClose, temp
)}
{/* Title */}
<div style={renderTextStyle(cfg.title)}>{renderTextLines(cfg.title)}</div>
{cfg.title && (
<div style={renderTextStyle(cfg.title)}>{renderTextLines(cfg.title)}</div>
)}
{/* Subtitle */}
<div style={renderTextStyle(cfg.subtitle)}>{renderTextLines(cfg.subtitle)}</div>
{cfg.subtitle && (
<div style={renderTextStyle(cfg.subtitle)}>{renderTextLines(cfg.subtitle)}</div>
)}
{/* Mask overlay */}
{cfg.maskEnabled && (