976 lines
33 KiB
TypeScript
976 lines
33 KiB
TypeScript
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 {
|
||
ArrowDown,
|
||
ArrowLeft,
|
||
ArrowUp,
|
||
Bold,
|
||
Check,
|
||
Heading2,
|
||
Heading3,
|
||
Image as ImageIcon,
|
||
Italic,
|
||
Link as LinkIcon,
|
||
List,
|
||
Plus,
|
||
Save,
|
||
Search,
|
||
Trash2,
|
||
Undo2,
|
||
Redo2,
|
||
X,
|
||
} 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 ProductImage = { mediaCode: string; url: string; sortNo: number };
|
||
type MediaItem = {
|
||
mediaCode: string;
|
||
url: string;
|
||
originalFileName: string;
|
||
mediaType: string;
|
||
altText?: string;
|
||
};
|
||
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()];
|
||
}
|
||
|
||
/** 将误存为普通文本的富文本标签恢复为可编辑 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*<pre><code>/i, "")
|
||
.replace(/<\/code><\/pre>(?:<p><\/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 [images, setImages] = useState<ProductImage[]>([]);
|
||
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 [mediaOpen, setMediaOpen] = useState(false);
|
||
const [mediaItems, setMediaItems] = useState<MediaItem[]>([]);
|
||
const [mediaLoading, setMediaLoading] = useState(false);
|
||
const [mediaQuery, setMediaQuery] = useState("");
|
||
const [selectedMedia, setSelectedMedia] = useState<string[]>([]);
|
||
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 || "" });
|
||
setImages(
|
||
d.images?.length
|
||
? d.images
|
||
: d.coverMediaCode && d.coverMediaUrl
|
||
? [{ mediaCode: d.coverMediaCode, url: d.coverMediaUrl, sortNo: 0 }]
|
||
: [],
|
||
);
|
||
setAttributes(d.attributes || []);
|
||
setSpecifications(mergeSpecifications(d.specifications || []));
|
||
editor?.commands.setContent(
|
||
normalizeRichTextHtml(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 (files?: FileList | null) => {
|
||
if (!files?.length) return;
|
||
const selected = [...files];
|
||
if (images.length + selected.length > 12) {
|
||
setNotice("产品图片最多 12 张");
|
||
return;
|
||
}
|
||
if (selected.some((file) => file.size > 10 * 1024 * 1024)) {
|
||
setNotice("单张图片不能超过 10MB");
|
||
return;
|
||
}
|
||
try {
|
||
setUploading(true);
|
||
setNotice("");
|
||
const uploaded: ProductImage[] = [];
|
||
for (const file of selected) {
|
||
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();
|
||
uploaded.push({
|
||
mediaCode: d.mediaCode,
|
||
url: d.url,
|
||
sortNo: images.length + uploaded.length,
|
||
});
|
||
}
|
||
setImages((current) =>
|
||
[...current, ...uploaded].map((image, index) => ({
|
||
...image,
|
||
sortNo: index,
|
||
})),
|
||
);
|
||
setNotice(`成功上传 ${uploaded.length} 张产品图片`);
|
||
} catch (e) {
|
||
setNotice(e instanceof Error ? e.message : "上传失败");
|
||
} finally {
|
||
setUploading(false);
|
||
if (coverInputRef.current) coverInputRef.current.value = "";
|
||
}
|
||
};
|
||
/** 调整产品图片顺序。 */
|
||
const moveImage = (index: number, direction: -1 | 1) => {
|
||
const target = index + direction;
|
||
if (target < 0 || target >= images.length) return;
|
||
const next = [...images];
|
||
[next[index], next[target]] = [next[target], next[index]];
|
||
setImages(next.map((image, position) => ({ ...image, sortNo: position })));
|
||
};
|
||
const openMediaLibrary = async () => {
|
||
setMediaOpen(true);
|
||
setMediaLoading(true);
|
||
try {
|
||
const data = await post("/media/list", {
|
||
siteCode: SITE,
|
||
mediaType: "IMAGE",
|
||
});
|
||
setMediaItems(data.items || []);
|
||
} catch (e) {
|
||
setNotice(e instanceof Error ? e.message : "素材库加载失败");
|
||
} finally {
|
||
setMediaLoading(false);
|
||
}
|
||
};
|
||
const confirmMediaSelection = () => {
|
||
const chosen = mediaItems.filter((item) =>
|
||
selectedMedia.includes(item.mediaCode),
|
||
);
|
||
const room = 12 - images.length;
|
||
if (chosen.length > room) {
|
||
setNotice(`最多还可添加 ${room} 张图片`);
|
||
return;
|
||
}
|
||
setImages((current) => [
|
||
...current,
|
||
...chosen.map((item, index) => ({
|
||
mediaCode: item.mediaCode,
|
||
url: item.url,
|
||
sortNo: current.length + index,
|
||
})),
|
||
]);
|
||
setSelectedMedia([]);
|
||
setMediaOpen(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: images[0]?.mediaCode || "",
|
||
images: images.map((image, index) => ({
|
||
mediaCode: image.mediaCode,
|
||
sortNo: index,
|
||
})),
|
||
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">
|
||
<div className="section-head">
|
||
<h2>产品图片</h2>
|
||
<button type="button" className="gallery-upload-button" onClick={() => void openMediaLibrary()}><Plus size={16} />从素材库添加</button>
|
||
<label
|
||
className={`gallery-upload-button${uploading ? " uploading" : ""}`}
|
||
>
|
||
<Plus size={16} />
|
||
{uploading ? "上传中..." : "添加图片"}
|
||
<input
|
||
ref={coverInputRef}
|
||
multiple
|
||
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)}
|
||
/>
|
||
</label>
|
||
</div>
|
||
<p className="gallery-help">
|
||
最多 12 张,首张作为产品封面;支持 JPG、PNG、WebP、GIF,单张不超过
|
||
10MB。
|
||
</p>
|
||
{images.length ? (
|
||
<div className="product-gallery-editor">
|
||
{images.map((image, index) => (
|
||
<article key={image.mediaCode}>
|
||
<div>
|
||
{index === 0 && <span>封面</span>}
|
||
<img
|
||
src={assetUrl(image.url)}
|
||
alt={`产品图片 ${index + 1}`}
|
||
/>
|
||
</div>
|
||
<footer>
|
||
<button
|
||
type="button"
|
||
title="向前移动"
|
||
disabled={index === 0}
|
||
onClick={() => moveImage(index, -1)}
|
||
>
|
||
<ArrowUp size={16} />
|
||
</button>
|
||
<button
|
||
type="button"
|
||
title="向后移动"
|
||
disabled={index === images.length - 1}
|
||
onClick={() => moveImage(index, 1)}
|
||
>
|
||
<ArrowDown size={16} />
|
||
</button>
|
||
<button
|
||
type="button"
|
||
title="删除图片"
|
||
onClick={() =>
|
||
setImages(
|
||
images
|
||
.filter((_, position) => position !== index)
|
||
.map((item, position) => ({
|
||
...item,
|
||
sortNo: position,
|
||
})),
|
||
)
|
||
}
|
||
>
|
||
<Trash2 size={16} />
|
||
</button>
|
||
</footer>
|
||
</article>
|
||
))}
|
||
</div>
|
||
) : (
|
||
<div className="gallery-empty">
|
||
<ImageIcon size={36} />
|
||
<span>暂未上传产品图片</span>
|
||
</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>
|
||
{mediaOpen && <div className="media-picker-backdrop" onMouseDown={() => setMediaOpen(false)}><section className="media-picker" role="dialog" aria-modal="true" onMouseDown={(event) => event.stopPropagation()}><header><h2>素材库</h2><button type="button" onClick={() => setMediaOpen(false)}><X size={20}/></button></header><div className="media-picker-toolbar"><label><Search size={16}/><input placeholder="搜索图片名称" value={mediaQuery} onChange={(event) => setMediaQuery(event.target.value)}/></label><label className="media-local-upload"><Plus size={16}/>上传本地图片<input ref={coverInputRef} multiple disabled={uploading} type="file" accept=".jpg,.jpeg,.png,.webp,.gif,image/jpeg,image/png,image/webp,image/gif" onChange={(event) => void upload(event.currentTarget.files)}/></label></div><div className="media-picker-grid">{mediaLoading?<div className="media-picker-empty">加载中...</div>:mediaItems.filter(item => !mediaQuery || item.originalFileName.toLowerCase().includes(mediaQuery.toLowerCase())).map(item=><button type="button" className={`media-picker-item${selectedMedia.includes(item.mediaCode)?' selected':''}`} key={item.mediaCode} onClick={() => setSelectedMedia(current => current.includes(item.mediaCode)?current.filter(code => code!==item.mediaCode):[...current,item.mediaCode])}><img src={assetUrl(item.url)} alt={item.originalFileName}/><span>{selectedMedia.includes(item.mediaCode)&&<Check size={15}/>} {item.originalFileName}</span></button>)}</div><footer><button type="button" onClick={() => setMediaOpen(false)}>取消</button><button type="button" className="primary" onClick={confirmMediaSelection}>确定({selectedMedia.length})</button></footer></section></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>
|
||
);
|
||
}
|