Files
shoplix/web-admin/src/ProductEditor.tsx
T
2026-11-24 15:33:40 +08:00

65 lines
15 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React,{useEffect,useRef,useState} from 'react';
import {EditorContent,useEditor} from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Link from '@tiptap/extension-link';
import Image from '@tiptap/extension-image';
import {ArrowLeft,Bold,Heading2,Heading3,Image as ImageIcon,Italic,Link as LinkIcon,List,Plus,Save,Trash2,Undo2,Redo2} from 'lucide-react';
import {API,assetUrl} from './api';
const SITE='SIT0000000000001';
async function post(path:string,body:unknown){const r=await fetch(API+path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});if(!r.ok)throw new Error((await r.json()).message||'请求失败');return r.json()}
type Attribute={attributeCode?:string;attributeName:string;value:string;unit:string;sortNo:number};
type Specification={groupName:string;name:string;value:string;unit:string;sortNo:number};
type Heading={level:number;text:string;sortNo:number};
type ProductCategory={categoryCode:string;parentCategoryCode:string;categoryName:string;status:string};
type ProductCategoryOption=ProductCategory&{depth:number};
type Props={productCode?:string;onBack:()=>void};
/** 将产品分类转换为带层级深度的下拉选项。 */
function buildCategoryOptions(categories:ProductCategory[]):ProductCategoryOption[]{
const children=new Map<string,ProductCategory[]>();
categories.forEach(category=>{const parentCode=category.parentCategoryCode||'';children.set(parentCode,[...(children.get(parentCode)||[]),category])});
const result:ProductCategoryOption[]=[];
const append=(parentCode:string,depth:number)=>{(children.get(parentCode)||[]).forEach(category=>{result.push({...category,depth});append(category.categoryCode,depth+1)})};
append('',0);
return result;
}
/** 合并名称、分组和单位相同的历史规格,多个规格值使用斜杠分隔展示。 */
function mergeSpecifications(items:Specification[]):Specification[]{
const merged=new Map<string,Specification>();
items.forEach(item=>{
const key=JSON.stringify([item.groupName||'',item.name||'',item.unit||'']);
const current=merged.get(key);
if(!current){merged.set(key,{...item,sortNo:merged.size});return}
const values=[...new Set([...current.value.split('/'),...item.value.split('/')].map(value=>value.trim()).filter(Boolean))];
current.value=values.join(' / ');
});
return [...merged.values()];
}
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<Attribute[]>([]);const [specifications,setSpecifications]=useState<Specification[]>([]);const [categories,setCategories]=useState<ProductCategoryOption[]>([]);
const [categoriesLoading,setCategoriesLoading]=useState(true);const [categoriesError,setCategoriesError]=useState('');
const [seo,setSeo]=useState({title:'',description:'',keywords:'',h1:'',canonicalUrl:'',robots:'index,follow',ogTitle:'',ogDescription:'',ogImageUrl:'',status:'DRAFT'});const [headings,setHeadings]=useState<Heading[]>([]);
const [saving,setSaving]=useState(false);const [notice,setNotice]=useState('');
const [uploading,setUploading]=useState(false);const coverInputRef=useRef<HTMLInputElement>(null);
const editor=useEditor({extensions:[StarterKit,Link.configure({openOnClick:false}),Image],content:'<p></p>'});
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||'<p></p>')});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 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 <div className="product-editor"><div className="editor-top"><div className="breadcrumb-title"><button className="back" onClick={onBack}><ArrowLeft size={17}/>产品管理</button><span>/</span><h1>{productCode?'编辑产品':'新增产品'}</h1>{notice&&<em>{notice}</em>}</div><div className="editor-actions"><button onClick={onBack}>取消</button><button className="primary" disabled={saving||!form.productName||!form.slug} onClick={save}><Save size={16}/>{saving?'保存中':'保存'}</button></div></div><div className="editor-layout"><div className="editor-main">
<section className="edit-section"><h2>基础信息</h2><div className="edit-grid"><Field label="产品标题 *"><input value={form.productName} onChange={e=>setForm({...form,productName:e.target.value})}/></Field><Field label="英文路径 *"><input value={form.slug} onChange={e=>setForm({...form,slug:e.target.value.toLowerCase().replace(/[^a-z0-9-]/g,'-')})}/></Field><Field label="产品分类"><select disabled={categoriesLoading||Boolean(categoriesError)} value={form.primaryCategoryCode} onChange={e=>setForm({...form,primaryCategoryCode:e.target.value})}><option value="">{categoriesLoading?'分类加载中...':categoriesError||'请选择'}</option>{categories.map(category=><option key={category.categoryCode} value={category.categoryCode}>{`${' '.repeat(category.depth)}${category.categoryName}`}</option>)}</select></Field><Field label="产品型号"><input value={form.model||''} onChange={e=>setForm({...form,model:e.target.value})}/></Field><Field label="排序"><input type="number" value={form.sortNo} onChange={e=>setForm({...form,sortNo:Number(e.target.value)})}/></Field><Field wide label="产品简介 *"><textarea rows={4} value={form.summary||''} onChange={e=>setForm({...form,summary:e.target.value})}/></Field></div></section>
<section className="edit-section product-cover-section"><h2>产品主图</h2><div className="cover-upload">{form.coverMediaUrl?<img src={assetUrl(form.coverMediaUrl)} alt="产品主图预览"/>:<ImageIcon size={34}/>}<label className={uploading?'uploading':''}><span>{uploading?'上传中...':'选择图片'}</span><input ref={coverInputRef} disabled={uploading} type="file" accept=".jpg,.jpeg,.png,.webp,.gif,image/jpeg,image/png,image/webp,image/gif" onClick={e=>{e.currentTarget.value=''}} onChange={e=>void upload(e.currentTarget.files?.[0])}/></label><p>支持 JPG、PNG、WebP、GIF,单图不超过 10MB</p>{notice&&<small className="upload-notice">{notice}</small>}</div></section>
<section className="edit-section"><div className="section-head"><h2>产品属性</h2><button onClick={()=>setAttributes([...attributes,{attributeName:'',value:'',unit:'',sortNo:attributes.length}])}><Plus size={16}/>添加属性</button></div>{attributes.map((a,i)=><div className="repeat-row" key={i}><input placeholder="Attribute name" value={a.attributeName} onChange={e=>setAttributes(attributes.map((x,j)=>j===i?{...x,attributeName:e.target.value}:x))}/><input placeholder="Value" value={a.value} onChange={e=>setAttributes(attributes.map((x,j)=>j===i?{...x,value:e.target.value}:x))}/><input placeholder="Unit" value={a.unit||''} onChange={e=>setAttributes(attributes.map((x,j)=>j===i?{...x,unit:e.target.value}:x))}/><button title="删除属性" onClick={()=>setAttributes(attributes.filter((_,j)=>j!==i))}><Trash2 size={17}/></button></div>)}</section>
<section className="edit-section product-specifications"><div className="section-head"><h2>产品规格</h2><button onClick={()=>setSpecifications([...specifications,{groupName:'',name:'',value:'',unit:'',sortNo:specifications.length}])}><Plus size={16}/>添加规格</button></div>{specifications.length===0&&<div className="specification-empty">暂无产品规格</div>}{specifications.map((s,i)=><div className="specification-row" key={i}><label><span>规格名称 *</span><input placeholder="例如 Line diameter" value={s.name} onChange={e=>setSpecifications(specifications.map((x,j)=>j===i?{...x,name:e.target.value}:x))}/></label><label className="specification-values"><span>规格值(多个值使用 / 分隔)*</span><input placeholder="例如 2.0mm / 2.4mm / 2.7mm" value={s.value} onChange={e=>setSpecifications(specifications.map((x,j)=>j===i?{...x,value:e.target.value}:x))}/></label><label><span>分组(可选)</span><input placeholder="例如 Basic" value={s.groupName||''} onChange={e=>setSpecifications(specifications.map((x,j)=>j===i?{...x,groupName:e.target.value}:x))}/></label><label><span>单位(可选)</span><input placeholder="例如 mm" value={s.unit||''} onChange={e=>setSpecifications(specifications.map((x,j)=>j===i?{...x,unit:e.target.value}:x))}/></label><button title="删除规格" onClick={()=>setSpecifications(specifications.filter((_,j)=>j!==i))}><Trash2 size={17}/></button></div>)}</section>
<section className="edit-section"><h2>产品详情 *</h2><div className="rich-editor"><div className="rich-toolbar"><Tool title="撤销" onClick={()=>editor?.chain().focus().undo().run()}><Undo2/></Tool><Tool title="重做" onClick={()=>editor?.chain().focus().redo().run()}><Redo2/></Tool><Tool title="粗体" active={editor?.isActive('bold')} onClick={()=>editor?.chain().focus().toggleBold().run()}><Bold/></Tool><Tool title="斜体" active={editor?.isActive('italic')} onClick={()=>editor?.chain().focus().toggleItalic().run()}><Italic/></Tool><Tool title="二级标题" active={editor?.isActive('heading',{level:2})} onClick={()=>editor?.chain().focus().toggleHeading({level:2}).run()}><Heading2/></Tool><Tool title="三级标题" active={editor?.isActive('heading',{level:3})} onClick={()=>editor?.chain().focus().toggleHeading({level:3}).run()}><Heading3/></Tool><Tool title="项目列表" onClick={()=>editor?.chain().focus().toggleBulletList().run()}><List/></Tool><Tool title="链接" onClick={addLink}><LinkIcon/></Tool><Tool title="插入图片" onClick={addImage}><ImageIcon/></Tool></div><EditorContent editor={editor}/></div></section>
</div><aside className="editor-side"><section className="edit-section"><h2>发布</h2><Field label="状态"><select value={form.status} onChange={e=>setForm({...form,status:e.target.value})}><option value="DRAFT">草稿</option><option value="PUBLISHED">上架</option><option value="OFFLINE">下线</option></select></Field><label className="check"><input type="checkbox" checked={form.inquiryEnabled} onChange={e=>setForm({...form,inquiryEnabled:e.target.checked})}/>启用产品询盘</label><label className="check"><input type="checkbox" checked={form.featured} onChange={e=>setForm({...form,featured:e.target.checked})}/>推荐产品</label></section><section className="edit-section"><h2>搜索引擎优化</h2><Field label="SEO 标题"><input maxLength={70} value={seo.title} onChange={e=>setSeo({...seo,title:e.target.value})}/></Field><Field label="SEO 描述"><textarea maxLength={160} rows={4} value={seo.description} onChange={e=>setSeo({...seo,description:e.target.value})}/></Field><Field label="SEO 关键词"><input value={seo.keywords} onChange={e=>setSeo({...seo,keywords:e.target.value})}/></Field><Field label="H1"><input maxLength={120} value={seo.h1} onChange={e=>setSeo({...seo,h1:e.target.value})}/></Field><Field label="Canonical"><input value={seo.canonicalUrl} placeholder={`/products/${form.slug}`} onChange={e=>setSeo({...seo,canonicalUrl:e.target.value})}/></Field><div className="section-head"><h3>H2 / H3 标签</h3><button onClick={()=>setHeadings([...headings,{level:2,text:'',sortNo:headings.length}])}><Plus size={15}/></button></div>{headings.map((h,i)=><div className="heading-row" key={i}><select value={h.level} onChange={e=>setHeadings(headings.map((x,j)=>j===i?{...x,level:Number(e.target.value)}:x))}><option value={2}>H2</option><option value={3}>H3</option></select><input value={h.text} onChange={e=>setHeadings(headings.map((x,j)=>j===i?{...x,text:e.target.value}:x))}/><button onClick={()=>setHeadings(headings.filter((_,j)=>j!==i))}><Trash2 size={15}/></button></div>)}</section></aside></div></div>
}
function Field({label,wide,children}:{label:string;wide?:boolean;children:React.ReactNode}){return <label className={wide?'wide':''}><span>{label}</span>{children}</label>}
function Tool({title,active,onClick,children}:{title:string;active?:boolean;onClick:()=>void;children:React.ReactElement}){return <button type="button" title={title} className={active?'active':''} onClick={onClick}>{React.cloneElement(children,{size:18} as any)}</button>}