diff --git a/web-admin/src/DecorationEditor.tsx b/web-admin/src/DecorationEditor.tsx index ae28aeb..e763526 100644 --- a/web-admin/src/DecorationEditor.tsx +++ b/web-admin/src/DecorationEditor.tsx @@ -6,6 +6,7 @@ import { Eye, EyeOff, GripVertical, + Image as ImageIcon, Monitor, Plus, Redo2, @@ -28,6 +29,7 @@ type SectionType = | "HERO" | "RICH_TEXT" | "PRODUCTS" + | "PRODUCT_DETAIL" | "CONTENT" | "INQUIRY" | "FOOTER"; @@ -55,12 +57,14 @@ type Schema = { }; sections: Section[]; }; +type PreviewProduct = {productCode:string;productName:string;model?:string;summary?:string;coverMediaUrl?:string;attributes?:Array<{name:string;value:string;unit?:string}>}; const labels: Record = { ANNOUNCEMENT: "公告栏", HEADER: "导航栏", HERO: "轮播横幅", RICH_TEXT: "富文本", PRODUCTS: "产品展示", + PRODUCT_DETAIL: "产品详情", CONTENT: "内容展示", INQUIRY: "询盘表单", FOOTER: "页脚", @@ -120,6 +124,10 @@ function createSection(type: SectionType): Section { textColor: type === "HEADER" || type === "FOOTER" ? "#ffffff" : "#17211f", }; } +/** 为产品详情页提供可直接发布的基础组件结构。 */ +function productDetailSchema(schema:Schema):Schema{ + return {...schema,sections:[createSection("HEADER"),createSection("PRODUCT_DETAIL"),createSection("FOOTER")]}; +} export default function DecorationEditor({ onBack }: { onBack: () => void }) { const [pageType, setPageType] = useState("HOME"); const [schema, setSchema] = useState(initialSchema); @@ -131,6 +139,7 @@ export default function DecorationEditor({ onBack }: { onBack: () => void }) { const [notice, setNotice] = useState(""); const [status, setStatus] = useState("DRAFT"); const [version, setVersion] = useState(0); + const [previewProduct,setPreviewProduct]=useState(); useEffect(() => { setSelected(null); setGlobalMode(false); @@ -138,12 +147,14 @@ export default function DecorationEditor({ onBack }: { onBack: () => void }) { setFuture([]); post("/decorations/detail", { siteCode: SITE, pageType }) .then((data) => { - setSchema(JSON.parse(data.schema)); + const loaded=JSON.parse(data.schema) as Schema; + setSchema(pageType==="PRODUCT_DETAIL"&&!loaded.sections.length?productDetailSchema(loaded):loaded); setStatus(data.status); setVersion(data.publishedVersion); }) .catch((error) => setNotice(error.message)); }, [pageType]); + useEffect(()=>{if(pageType!=="PRODUCT_DETAIL")return;post("/products/list",{siteCode:SITE}).then(data=>data.items?.[0]?.productCode?post("/products/detail",{siteCode:SITE,productCode:data.items[0].productCode}):undefined).then(data=>{if(data)setPreviewProduct(data)}).catch(()=>setPreviewProduct(undefined))},[pageType]); const commit = (next: Schema) => { setHistory((items) => [...items.slice(-19), schema]); setFuture([]); @@ -389,6 +400,7 @@ export default function DecorationEditor({ onBack }: { onBack: () => void }) { setSelected(item.id); setGlobalMode(false); }} + product={previewProduct} /> )) ) : ( @@ -453,11 +465,13 @@ function PreviewSection({ primary, selected, onSelect, + product, }: { item: Section; primary: string; selected: boolean; onSelect: () => void; + product?:PreviewProduct; }) { const style = { background: item.background, @@ -533,6 +547,7 @@ function PreviewSection({ ); + if(item.type==="PRODUCT_DETAIL")return
{product?.coverMediaUrl?{product.productName}/:}
PRODUCT

{product?.productName||"Product title"}

{product?.model&&Model {product.model}}

{product?.summary||"Product summary and key selling points will be loaded from the selected product."}

{product?.attributes?.length?
{product.attributes.slice(0,4).map(attribute=>
{attribute.name}
{attribute.value} {attribute.unit}
)}
:null}
; if (item.type === "INQUIRY") return (
@@ -658,7 +673,7 @@ function SectionSettings({ return (

{labels[item.type]}设置

- + {item.type!=="PRODUCT_DETAIL"&&<> onChange({ title: e.target.value })} @@ -671,6 +686,7 @@ function SectionSettings({ onChange={(e) => onChange({ subtitle: e.target.value })} /> + } {item.type === "HERO" && ( <> diff --git a/web-admin/src/ProductEditor.tsx b/web-admin/src/ProductEditor.tsx index ba443ae..31d1768 100644 --- a/web-admin/src/ProductEditor.tsx +++ b/web-admin/src/ProductEditor.tsx @@ -38,6 +38,17 @@ function mergeSpecifications(items:Specification[]):Specification[]{ return [...merged.values()]; } +/** 将误存为普通文本的富文本标签恢复为可编辑 HTML,正常富文本保持不变。 */ +function normalizeRichTextHtml(content:string):string{ + if(!content||!/&(?:amp;)?lt;\/?(?:h[1-6]|p|ul|ol|li|blockquote|table|img|a)\b/i.test(content))return content; + const decoder=document.createElement('textarea'); + let decoded=content; + for(let index=0;index<2;index+=1){decoder.innerHTML=decoded;const next=decoder.value;if(next===decoded)break;decoded=next} + decoded=decoded.replace(/^\s*
/i,'').replace(/<\/code><\/pre>(?:

<\/p>)?\s*$/i,''); + if(!/<\/?(?:h[1-6]|p|ul|ol|li|blockquote|table|img|a)\b/i.test(decoded))return content; + const container=document.createElement('div');container.innerHTML=decoded;return container.innerHTML; +} + export default function ProductEditor({productCode,onBack}:Props){ const [form,setForm]=useState({productName:'',slug:'',model:'',summary:'',primaryCategoryCode:'',coverMediaCode:'',coverMediaUrl:'',featured:false,inquiryEnabled:true,sortNo:30,status:'DRAFT'}); const [attributes,setAttributes]=useState([]);const [specifications,setSpecifications]=useState([]);const [categories,setCategories]=useState([]); @@ -47,10 +58,10 @@ export default function ProductEditor({productCode,onBack}:Props){ const [uploading,setUploading]=useState(false);const coverInputRef=useRef(null); const editor=useEditor({extensions:[StarterKit,Link.configure({openOnClick:false}),Image],content:'

'}); useEffect(()=>{let active=true;setCategoriesLoading(true);setCategoriesError('');post('/products/categories/list',{siteCode:SITE}).then(data=>{if(active)setCategories(buildCategoryOptions(data.items||[]))}).catch(error=>{if(active)setCategoriesError(error instanceof Error?error.message:'产品分类加载失败')}).finally(()=>{if(active)setCategoriesLoading(false)});return()=>{active=false}},[]); - useEffect(()=>{if(!productCode)return;post('/products/detail',{siteCode:SITE,productCode}).then(d=>{setForm({...d,coverMediaUrl:d.coverMediaUrl||''});setAttributes(d.attributes||[]);setSpecifications(mergeSpecifications(d.specifications||[]));editor?.commands.setContent(d.productContent||'

')});post('/seo/detail',{siteCode:SITE,pageType:'PRODUCT_DETAIL',targetCode:productCode}).then(d=>{setSeo({title:d.title,description:d.description,keywords:d.keywords||'',h1:d.h1,canonicalUrl:d.canonicalUrl||'',robots:d.robots,ogTitle:d.ogTitle||'',ogDescription:d.ogDescription||'',ogImageUrl:d.ogImageUrl||'',status:d.status});setHeadings(d.headings||[])}).catch(()=>{})},[productCode,editor]); + useEffect(()=>{if(!productCode)return;post('/products/detail',{siteCode:SITE,productCode}).then(d=>{setForm({...d,coverMediaUrl:d.coverMediaUrl||''});setAttributes(d.attributes||[]);setSpecifications(mergeSpecifications(d.specifications||[]));editor?.commands.setContent(normalizeRichTextHtml(d.productContent||'

'))});post('/seo/detail',{siteCode:SITE,pageType:'PRODUCT_DETAIL',targetCode:productCode}).then(d=>{setSeo({title:d.title,description:d.description,keywords:d.keywords||'',h1:d.h1,canonicalUrl:d.canonicalUrl||'',robots:d.robots,ogTitle:d.ogTitle||'',ogDescription:d.ogDescription||'',ogImageUrl:d.ogImageUrl||'',status:d.status});setHeadings(d.headings||[])}).catch(()=>{})},[productCode,editor]); /** 校验并上传产品主图,选择相同文件时也允许重新触发上传。 */ const upload=async(file?:File)=>{if(!file)return;if(file.size>10*1024*1024){setNotice('图片不能超过 10MB');return}try{setUploading(true);setNotice('');const body=new FormData();body.append('siteCode',SITE);body.append('altText',form.productName);body.append('file',file);const r=await fetch(API+'/media/upload-image',{method:'POST',body});if(r.status===413)throw new Error('图片超过服务器上传限制,请联系管理员调整 Nginx 上传上限');if(!r.ok)throw new Error((await r.json().catch(()=>({}))).message||'上传失败');const d=await r.json();setForm(current=>({...current,coverMediaCode:d.mediaCode,coverMediaUrl:d.url}));setNotice('产品主图上传成功')}catch(e){setNotice(e instanceof Error?e.message:'上传失败')}finally{setUploading(false);if(coverInputRef.current)coverInputRef.current.value=''}}; - const save=async()=>{if(!editor)return;try{setSaving(true);setNotice('');const result=await post('/products/save',{productCode,siteCode:SITE,primaryCategoryCode:form.primaryCategoryCode,productName:form.productName,slug:form.slug,model:form.model,summary:form.summary,productContent:editor.getHTML(),coverMediaCode:form.coverMediaCode,featured:form.featured,inquiryEnabled:form.inquiryEnabled,sortNo:form.sortNo,status:form.status,specifications,attributes});await post('/seo/save',{siteCode:SITE,pageType:'PRODUCT_DETAIL',targetCode:result.productCode,title:seo.title||form.productName,description:seo.description||form.summary,keywords:seo.keywords,h1:seo.h1||form.productName,canonicalUrl:seo.canonicalUrl||`/products/${form.slug}`,robots:seo.robots,ogTitle:seo.ogTitle,ogDescription:seo.ogDescription,ogImageUrl:seo.ogImageUrl,structuredData:null,status:form.status,headings});setNotice('产品与 SEO 已保存');if(!productCode)setTimeout(onBack,500)}catch(e){setNotice(e instanceof Error?e.message:'保存失败')}finally{setSaving(false)}}; + const save=async()=>{if(!editor)return;try{setSaving(true);setNotice('');const result=await post('/products/save',{productCode,siteCode:SITE,primaryCategoryCode:form.primaryCategoryCode,productName:form.productName,slug:form.slug,model:form.model,summary:form.summary,productContent:normalizeRichTextHtml(editor.getHTML()),coverMediaCode:form.coverMediaCode,featured:form.featured,inquiryEnabled:form.inquiryEnabled,sortNo:form.sortNo,status:form.status,specifications,attributes});await post('/seo/save',{siteCode:SITE,pageType:'PRODUCT_DETAIL',targetCode:result.productCode,title:seo.title||form.productName,description:seo.description||form.summary,keywords:seo.keywords,h1:seo.h1||form.productName,canonicalUrl:seo.canonicalUrl||`/products/${form.slug}`,robots:seo.robots,ogTitle:seo.ogTitle,ogDescription:seo.ogDescription,ogImageUrl:seo.ogImageUrl,structuredData:null,status:form.status,headings});setNotice('产品与 SEO 已保存');if(!productCode)setTimeout(onBack,500)}catch(e){setNotice(e instanceof Error?e.message:'保存失败')}finally{setSaving(false)}}; const addLink=()=>{const href=window.prompt('请输入链接地址');if(href)editor?.chain().focus().setLink({href}).run()};const addImage=()=>{const src=window.prompt('请输入图片地址');if(src)editor?.chain().focus().setImage({src}).run()}; return
/

{productCode?'编辑产品':'新增产品'}

{notice&&{notice}}

基础信息

setForm({...form,productName:e.target.value})}/>setForm({...form,slug:e.target.value.toLowerCase().replace(/[^a-z0-9-]/g,'-')})}/>setForm({...form,model:e.target.value})}/>setForm({...form,sortNo:Number(e.target.value)})}/>