bug修复
This commit is contained in:
1 parent
b9cc84644c
commit
ec4ca451bb
7 files changed
+176
-35
No files matched your search
@@ -6,6 +6,7 @@ import com.shoplix.admin.modules.page.res.PageDetailAdminRes;
|
||||
import com.shoplix.common.code.enums.BusinessCodePrefixEnum;
|
||||
import com.shoplix.common.exception.BusinessException;
|
||||
import com.shoplix.common.utils.BusinessCodeUtils;
|
||||
import com.shoplix.modules.common.enums.PublishStatusEnum;
|
||||
import com.shoplix.modules.page.repository.entity.PageEntity;
|
||||
import com.shoplix.modules.page.repository.service.PageRepositoryService;
|
||||
import com.shoplix.modules.media.repository.service.MediaAssetRepositoryService;
|
||||
@@ -39,8 +40,12 @@ public class AdminPageService {
|
||||
entity.setSystemPageType(request.systemPageType() == null ? null : request.systemPageType().name());
|
||||
entity.setPageName(request.pageName()); entity.setSlug(request.slug()); entity.setPageContent(request.pageContent());
|
||||
entity.setSummary(request.summary()); entity.setCoverMediaCode(request.coverMediaCode()); entity.setSortNo(request.sortNo());
|
||||
entity.setStatus(request.status().name());
|
||||
if (request.status().name().equals("PUBLISHED") && entity.getPublishTime() == null) entity.setPublishTime(System.currentTimeMillis());
|
||||
PublishStatusEnum publishStatus = request.systemPageType() != null && request.systemPageType().isAlwaysPublished()
|
||||
? PublishStatusEnum.PUBLISHED : request.status();
|
||||
entity.setStatus(publishStatus.name());
|
||||
if (publishStatus == PublishStatusEnum.PUBLISHED && entity.getPublishTime() == null) {
|
||||
entity.setPublishTime(System.currentTimeMillis());
|
||||
}
|
||||
int affected = creating ? repository.insert(entity) : repository.updateByCode(entity);
|
||||
if (affected != 1) throw new BusinessException("PAGE_SAVE_FAILED", "页面保存失败");
|
||||
return entity.getPageCode();
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.shoplix.admin.service;
|
||||
|
||||
import com.shoplix.admin.modules.page.req.SavePageAdminReq;
|
||||
import com.shoplix.common.code.enums.BusinessCodePrefixEnum;
|
||||
import com.shoplix.common.utils.BusinessCodeUtils;
|
||||
import com.shoplix.modules.common.enums.PublishStatusEnum;
|
||||
import com.shoplix.modules.media.repository.service.MediaAssetRepositoryService;
|
||||
import com.shoplix.modules.page.enums.SystemPageTypeEnum;
|
||||
import com.shoplix.modules.page.repository.entity.PageEntity;
|
||||
import com.shoplix.modules.page.repository.service.PageRepositoryService;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** 运营后台页面保存规则测试。 */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminPageServiceTest {
|
||||
@Mock
|
||||
private PageRepositoryService repository;
|
||||
@Mock
|
||||
private BusinessCodeUtils codeUtils;
|
||||
@Mock
|
||||
private MediaAssetRepositoryService mediaRepository;
|
||||
@InjectMocks
|
||||
private AdminPageService service;
|
||||
|
||||
/** 验证协议页即使收到草稿状态也会固定保存为已发布。 */
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = SystemPageTypeEnum.class, names = {
|
||||
"COOKIE_POLICY", "PRIVACY_POLICY", "TERMS_OF_SERVICE"
|
||||
})
|
||||
void shouldForceAgreementPageToPublished(SystemPageTypeEnum systemPageType) {
|
||||
when(codeUtils.generate(BusinessCodePrefixEnum.PAGE)).thenReturn("PAG0000000000001");
|
||||
when(repository.insert(any(PageEntity.class))).thenReturn(1);
|
||||
SavePageAdminReq request = new SavePageAdminReq(null, "SIT0000000000001", "SYSTEM_PAGE",
|
||||
systemPageType, "Agreement", "agreement", "<p>Agreement</p>",
|
||||
"", null, 30, PublishStatusEnum.DRAFT);
|
||||
|
||||
service.save(request);
|
||||
|
||||
ArgumentCaptor<PageEntity> captor = ArgumentCaptor.forClass(PageEntity.class);
|
||||
verify(repository).insert(captor.capture());
|
||||
assertEquals(PublishStatusEnum.PUBLISHED.name(), captor.getValue().getStatus());
|
||||
assertNotNull(captor.getValue().getPublishTime());
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,23 @@ package com.shoplix.modules.page.enums;
|
||||
|
||||
/** 固定系统页面类型。 */
|
||||
public enum SystemPageTypeEnum {
|
||||
ABOUT_US,
|
||||
CONTACT_US,
|
||||
TERMS_OF_SERVICE,
|
||||
PRIVACY_POLICY,
|
||||
COOKIE_POLICY,
|
||||
INQUIRY_SUCCESS
|
||||
ABOUT_US(false),
|
||||
CONTACT_US(false),
|
||||
TERMS_OF_SERVICE(true),
|
||||
PRIVACY_POLICY(true),
|
||||
COOKIE_POLICY(true),
|
||||
INQUIRY_SUCCESS(false);
|
||||
|
||||
/** 是否为始终发布、不可下架的固定页面。 */
|
||||
private final boolean alwaysPublished;
|
||||
|
||||
/** 初始化固定页面的发布规则。 */
|
||||
SystemPageTypeEnum(boolean alwaysPublished) {
|
||||
this.alwaysPublished = alwaysPublished;
|
||||
}
|
||||
|
||||
/** 判断固定页面是否必须保持发布状态。 */
|
||||
public boolean isAlwaysPublished() {
|
||||
return alwaysPublished;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import { Bold, Heading2, Italic, Link as LinkIcon, List, Redo2, Save, Undo2 } from "lucide-react";
|
||||
import { AlertCircle, Bold, CheckCircle2, Heading2, Italic, Link as LinkIcon, List, Redo2, Save, Undo2, X } from "lucide-react";
|
||||
import { EditorContent, useEditor } from "@tiptap/react";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import Link from "@tiptap/extension-link";
|
||||
import { apiPost } from "./api";
|
||||
|
||||
const SITE = "SIT0000000000001";
|
||||
const AGREEMENT_PUBLISH_STATUS = "PUBLISHED";
|
||||
type AgreementKey = "COOKIE_POLICY" | "PRIVACY_POLICY" | "TERMS_OF_SERVICE";
|
||||
type AgreementTab = { key: AgreementKey; label: string; pageName: string; slug: string; seoDescription:string; robots:string };
|
||||
type AgreementSeo={title:string;description:string;canonicalUrl:string;robots:string;h1:string};
|
||||
@@ -23,8 +24,8 @@ export default function AgreementSettingsPage() {
|
||||
const [activeKey, setActiveKey] = useState<AgreementKey>("COOKIE_POLICY");
|
||||
const [pageCodes, setPageCodes] = useState<Partial<Record<AgreementKey, string>>>({});
|
||||
const [title, setTitle] = useState("");
|
||||
const [status, setStatus] = useState("DRAFT");
|
||||
const [notice, setNotice] = useState("");
|
||||
const [noticeType,setNoticeType]=useState<"success"|"error">("success");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [seo,setSeo]=useState<AgreementSeo>(()=>defaultSeo(tabs[0]));
|
||||
const activeTab = useMemo(() => tabs.find((tab) => tab.key === activeKey) || tabs[0], [activeKey]);
|
||||
@@ -33,24 +34,23 @@ export default function AgreementSettingsPage() {
|
||||
useEffect(() => {
|
||||
void loadPages();
|
||||
}, []);
|
||||
useEffect(()=>{if(!notice||noticeType!=="success")return;const timer=window.setTimeout(()=>setNotice(""),3000);return()=>window.clearTimeout(timer)},[notice,noticeType]);
|
||||
useEffect(() => {
|
||||
const code = pageCodes[activeKey];
|
||||
setSeo(defaultSeo(activeTab));
|
||||
if (!code) {
|
||||
setTitle(activeTab.pageName);
|
||||
setStatus("DRAFT");
|
||||
editor?.commands.setContent("<p></p>");
|
||||
return;
|
||||
}
|
||||
void apiPost("/pages/detail", { siteCode: SITE, pageCode: code }).then((data) => {
|
||||
setTitle(data.pageName || activeTab.pageName);
|
||||
setStatus(data.status || "DRAFT");
|
||||
editor?.commands.setContent(data.pageContent || "<p></p>");
|
||||
return apiPost("/seo/detail",{siteCode:SITE,pageType:"SYSTEM_PAGE",targetCode:code}).catch(()=>undefined);
|
||||
}).then((seoData)=>{
|
||||
if(!seoData)return;
|
||||
setSeo({title:seoData.title||defaultSeo(activeTab).title,description:seoData.description||defaultSeo(activeTab).description,canonicalUrl:seoData.canonicalUrl||`/${activeTab.slug}`,robots:seoData.robots||activeTab.robots,h1:seoData.h1||activeTab.pageName});
|
||||
}).catch((error) => setNotice(error instanceof Error ? error.message : "加载失败"));
|
||||
}).catch((error) => {setNoticeType("error");setNotice(error instanceof Error ? error.message : "加载失败")});
|
||||
}, [activeKey, pageCodes, editor, activeTab]);
|
||||
|
||||
async function loadPages() {
|
||||
@@ -62,7 +62,7 @@ export default function AgreementSettingsPage() {
|
||||
});
|
||||
setPageCodes(codes);
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : "加载失败");
|
||||
setNoticeType("error");setNotice(error instanceof Error ? error.message : "加载失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,13 +74,13 @@ export default function AgreementSettingsPage() {
|
||||
const result = await apiPost("/pages/save", {
|
||||
pageCode: pageCodes[activeKey], siteCode: SITE, pageType: "SYSTEM_PAGE", systemPageType: activeKey,
|
||||
pageName: title.trim(), slug: activeTab.slug, pageContent: editor.getHTML(), summary: "", coverMediaCode: null,
|
||||
sortNo: 30, status,
|
||||
sortNo: 30, status: AGREEMENT_PUBLISH_STATUS,
|
||||
});
|
||||
setPageCodes((current) => ({ ...current, [activeKey]: result.pageCode }));
|
||||
await apiPost("/seo/save",{siteCode:SITE,pageType:"SYSTEM_PAGE",targetCode:result.pageCode,title:seo.title.trim()||title.trim(),description:seo.description.trim(),keywords:"",h1:seo.h1.trim()||title.trim(),canonicalUrl:seo.canonicalUrl.trim()||`/${activeTab.slug}`,robots:seo.robots,ogTitle:"",ogDescription:"",ogImageUrl:"",structuredData:null,status,headings:[]});
|
||||
setNotice("协议与 SEO 已保存");
|
||||
await apiPost("/seo/save",{siteCode:SITE,pageType:"SYSTEM_PAGE",targetCode:result.pageCode,title:seo.title.trim()||title.trim(),description:seo.description.trim(),keywords:"",h1:seo.h1.trim()||title.trim(),canonicalUrl:seo.canonicalUrl.trim()||`/${activeTab.slug}`,robots:seo.robots,ogTitle:"",ogDescription:"",ogImageUrl:"",structuredData:null,status:AGREEMENT_PUBLISH_STATUS,headings:[]});
|
||||
setNoticeType("success");setNotice("协议与 SEO 已保存");
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : "保存失败");
|
||||
setNoticeType("error");setNotice(error instanceof Error ? error.message : "保存失败");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -90,11 +90,11 @@ export default function AgreementSettingsPage() {
|
||||
return <div className="agreement-settings">
|
||||
<div className="agreement-top"><div><h1>协议设置</h1><p>维护网站 Cookies、隐私和服务协议内容。</p></div><button className="primary" disabled={saving || !title.trim()} onClick={() => void save()}><Save size={16}/>{saving ? "保存中" : "保存"}</button></div>
|
||||
<div className="agreement-tabs">{tabs.map((tab) => <button key={tab.key} className={tab.key === activeKey ? "active" : ""} onClick={() => setActiveKey(tab.key)}>{tab.label}</button>)}</div>
|
||||
<section className="agreement-card"><div className="agreement-card-head"><h2>{activeTab.label}</h2><select value={status} onChange={(event) => setStatus(event.target.value)}><option value="DRAFT">草稿</option><option value="PUBLISHED">已上架</option><option value="OFFLINE">已下架</option></select></div>
|
||||
<section className="agreement-card"><div className="agreement-card-head"><h2>{activeTab.label}</h2></div>
|
||||
<label className="agreement-title"><span>页面标题</span><input value={title} onChange={(event) => setTitle(event.target.value)} maxLength={100}/></label>
|
||||
<label className="agreement-content"><span>页面详情</span><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="粗体" onClick={() => editor?.chain().focus().toggleBold().run()}><Bold/></Tool><Tool title="斜体" onClick={() => editor?.chain().focus().toggleItalic().run()}><Italic/></Tool><Tool title="二级标题" onClick={() => editor?.chain().focus().toggleHeading({ level: 2 }).run()}><Heading2/></Tool><Tool title="项目列表" onClick={() => editor?.chain().focus().toggleBulletList().run()}><List/></Tool><Tool title="链接" onClick={addLink}><LinkIcon/></Tool></div><EditorContent editor={editor}/></div></label>
|
||||
</section>
|
||||
<section className="agreement-card agreement-seo"><div className="agreement-card-head"><h2>SEO 设置</h2></div><div className="agreement-seo-grid"><label><span>SEO 标题 *</span><input maxLength={70} value={seo.title} onChange={(event)=>setSeo({...seo,title:event.target.value})}/></label><label><span>页面 H1 *</span><input maxLength={120} value={seo.h1} onChange={(event)=>setSeo({...seo,h1:event.target.value})}/></label><label className="wide"><span>SEO 描述 *</span><textarea maxLength={160} rows={3} value={seo.description} onChange={(event)=>setSeo({...seo,description:event.target.value})}/></label><label><span>Canonical *</span><input value={seo.canonicalUrl} onChange={(event)=>setSeo({...seo,canonicalUrl:event.target.value})}/></label><label><span>Robots</span><select value={seo.robots} onChange={(event)=>setSeo({...seo,robots:event.target.value})}><option value="index,follow">允许收录并跟踪链接</option><option value="noindex,follow">不收录但跟踪链接</option></select></label></div></section>{notice && <p className="agreement-notice">{notice}</p>}
|
||||
<section className="agreement-card agreement-seo"><div className="agreement-card-head"><h2>SEO 设置</h2></div><div className="agreement-seo-grid"><label><span>SEO 标题 *</span><input maxLength={70} value={seo.title} onChange={(event)=>setSeo({...seo,title:event.target.value})}/></label><label><span>页面 H1 *</span><input maxLength={120} value={seo.h1} onChange={(event)=>setSeo({...seo,h1:event.target.value})}/></label><label className="wide"><span>SEO 描述 *</span><textarea maxLength={160} rows={3} value={seo.description} onChange={(event)=>setSeo({...seo,description:event.target.value})}/></label><label><span>Canonical *</span><input value={seo.canonicalUrl} onChange={(event)=>setSeo({...seo,canonicalUrl:event.target.value})}/></label><label><span>Robots</span><select value={seo.robots} onChange={(event)=>setSeo({...seo,robots:event.target.value})}><option value="index,follow">允许收录并跟踪链接</option><option value="noindex,follow">不收录但跟踪链接</option></select></label></div></section>{notice && <div className={`agreement-toast ${noticeType}`} role={noticeType==="error"?"alert":"status"}>{noticeType==="success"?<CheckCircle2 size={19}/>:<AlertCircle size={19}/>}<span>{notice}</span><button type="button" title="关闭提示" onClick={()=>setNotice("")}><X size={16}/></button></div>}
|
||||
</div>;
|
||||
}
|
||||
function Tool({ title, onClick, children }: { title: string; onClick: () => void; children: React.ReactElement }) { return <button type="button" title={title} onClick={onClick}>{React.cloneElement(children, { size: 18 } as never)}</button>; }
|
||||
@@ -433,6 +433,7 @@ header p {
|
||||
.category-editor{max-width:1500px;margin:0 auto}.category-editor-layout{display:grid;grid-template-columns:minmax(0,1.4fr) minmax(330px,.6fr);gap:20px;align-items:start}.category-editor .edit-section{background:#fff;border:1px solid #dfe5e9;border-radius:6px;padding:24px;margin-bottom:20px}.category-editor .edit-section h2{font-size:18px;font-weight:500;margin:0 0 20px}.category-editor .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px}.category-editor label{display:grid;gap:7px;margin-bottom:16px}.category-editor label>span{font-size:13px;font-weight:600}.category-editor input,.category-editor textarea,.category-editor select{width:100%;box-sizing:border-box;border:1px solid #d8dee3;border-radius:5px;padding:11px 12px;font:inherit;resize:vertical}.category-editor .wide{grid-column:1/-1}@media(max-width:900px){.category-editor-layout{grid-template-columns:1fr}.category-editor .form-grid{grid-template-columns:1fr}.category-editor .wide{grid-column:auto}}
|
||||
.agreement-settings{max-width:1500px;margin:0 auto;padding:0 0 60px}.agreement-top{display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:22px}.agreement-top h1{margin:0 0 8px;font-size:28px}.agreement-top p{margin:0;color:#71808a}.agreement-top button{border:1px solid #d8dee3;background:#fff;border-radius:5px;padding:10px 16px;display:inline-flex;align-items:center;gap:7px;cursor:pointer}.agreement-top .primary{background:#176b5b;color:#fff}.agreement-tabs{display:flex;gap:28px;background:#fff;border-bottom:1px solid #dde3e7;padding:0 22px}.agreement-tabs button{border:0;background:transparent;padding:16px 2px;color:#71808a;font:inherit;cursor:pointer;border-bottom:3px solid transparent}.agreement-tabs button.active{color:#176b5b;border-bottom-color:#176b5b}.agreement-card{background:#fff;border:1px solid #dde3e7;border-radius:6px;padding:24px;margin-top:20px;display:grid;gap:22px}.agreement-card-head{display:flex;align-items:center;justify-content:space-between}.agreement-card-head h2{margin:0;font-size:18px}.agreement-card-head select,.agreement-title input{border:1px solid #d8dee3;border-radius:5px;padding:10px 12px;font:inherit}.agreement-title,.agreement-content{display:grid;gap:8px}.agreement-title span,.agreement-content>span{font-weight:600;font-size:14px}.agreement-title input{width:100%;box-sizing:border-box}.agreement-content .ProseMirror{min-height:520px}.agreement-notice{color:#176b5b;margin:14px 0 0}
|
||||
.agreement-seo-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px}.agreement-seo-grid label{display:grid;gap:7px}.agreement-seo-grid label>span{font-size:13px;font-weight:600}.agreement-seo-grid input,.agreement-seo-grid textarea,.agreement-seo-grid select{width:100%;box-sizing:border-box;border:1px solid #d8dee3;border-radius:5px;padding:10px 12px;font:inherit;resize:vertical;background:#fff}.agreement-seo-grid .wide{grid-column:1/-1}@media(max-width:760px){.agreement-seo-grid{grid-template-columns:1fr}.agreement-seo-grid .wide{grid-column:auto}}
|
||||
.agreement-toast{position:fixed;right:24px;top:84px;z-index:100;min-width:280px;max-width:min(420px,calc(100vw - 48px));display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:10px;padding:14px 15px;border:1px solid #b9d9d0;border-radius:6px;background:#f0faf7;color:#176b5b;box-shadow:0 12px 36px #20352f26}.agreement-toast.error{border-color:#e7bcbc;background:#fff5f5;color:#a33b3b}.agreement-toast span{font-size:14px;font-weight:600}.agreement-toast button{border:0;background:transparent;color:currentColor;padding:3px;display:grid;place-items:center;cursor:pointer}
|
||||
.cover-upload label.uploading span{background:#71808a;cursor:wait}.cover-upload .upload-notice{display:block;color:#176b5b;font-size:12px;text-align:center}.cover-upload input:disabled+span{cursor:wait}
|
||||
.shell > main > header > div > p,.content-page > header > div > p,.category-heading p,.navigation-editor-title p,.navigation-manager > header p,.account-settings > header p,.seo-settings-heading p,.agreement-top p{display:none}
|
||||
.product-cover-section .cover-upload{min-height:140px;grid-template-columns:120px minmax(0,1fr);grid-template-rows:auto auto auto;align-content:center;justify-content:center;column-gap:18px;row-gap:8px;padding:16px 24px}.product-cover-section .cover-upload>svg,.product-cover-section .cover-upload>img{grid-column:1;grid-row:1/-1;justify-self:center}.product-cover-section .cover-upload>img{width:120px;height:120px;object-fit:contain}.product-cover-section .cover-upload label{grid-column:2;grid-row:1;align-self:end}.product-cover-section .cover-upload p{grid-column:2;grid-row:2}.product-cover-section .cover-upload .upload-notice{grid-column:2;grid-row:3}.product-cover-section .cover-upload label,.product-cover-section .cover-upload p,.product-cover-section .cover-upload .upload-notice{justify-self:start;text-align:left}
|
||||
|
||||
+58
-15
@@ -58,22 +58,64 @@ async function post(path: string, body: unknown) {
|
||||
throw new Error((await r.json()).message || "Unable to load content");
|
||||
return r.json();
|
||||
}
|
||||
/** 兼容历史数据中被转义后保存的富文本标签。 */
|
||||
const RICH_TEXT_ALLOWED_TAGS = new Set([
|
||||
"A", "B", "BLOCKQUOTE", "BR", "CODE", "EM", "H2", "H3", "H4", "HR", "I", "IMG",
|
||||
"LI", "OL", "P", "PRE", "S", "STRONG", "TABLE", "TBODY", "TD", "TH", "THEAD", "TR", "U", "UL",
|
||||
]);
|
||||
const RICH_TEXT_REMOVED_TAGS = new Set(["BUTTON", "EMBED", "FORM", "IFRAME", "INPUT", "OBJECT", "SCRIPT", "STYLE"]);
|
||||
|
||||
/** 判断富文本链接或图片地址是否为可安全输出的站内、HTTP 或 HTTPS 地址。 */
|
||||
function isSafeRichTextUrl(value: string): boolean {
|
||||
const normalized = value.trim().replace(/[\u0000-\u0020]+/g, "").toLowerCase();
|
||||
return normalized.startsWith("/") || normalized.startsWith("#") || normalized.startsWith("http://")
|
||||
|| normalized.startsWith("https://") || normalized.startsWith("mailto:") || normalized.startsWith("tel:");
|
||||
}
|
||||
|
||||
/** 清理富文本节点,仅保留前台展示所需的安全标签和属性。 */
|
||||
function sanitizeRichTextHtml(content: string): string {
|
||||
const container = document.createElement("div");
|
||||
container.innerHTML = content;
|
||||
Array.from(container.querySelectorAll("*")).forEach((element) => {
|
||||
if (RICH_TEXT_REMOVED_TAGS.has(element.tagName)) {
|
||||
element.remove();
|
||||
return;
|
||||
}
|
||||
if (!RICH_TEXT_ALLOWED_TAGS.has(element.tagName)) {
|
||||
element.replaceWith(...Array.from(element.childNodes));
|
||||
return;
|
||||
}
|
||||
Array.from(element.attributes).forEach((attribute) => {
|
||||
const allowed = element.tagName === "A" && ["href", "target", "rel"].includes(attribute.name)
|
||||
|| element.tagName === "IMG" && ["src", "alt", "title"].includes(attribute.name)
|
||||
|| ["TD", "TH"].includes(element.tagName) && ["colspan", "rowspan"].includes(attribute.name);
|
||||
if (!allowed) element.removeAttribute(attribute.name);
|
||||
});
|
||||
if (element instanceof HTMLAnchorElement) {
|
||||
if (!isSafeRichTextUrl(element.getAttribute("href") || "")) element.removeAttribute("href");
|
||||
if (element.target === "_blank") element.rel = "noopener noreferrer";
|
||||
}
|
||||
if (element instanceof HTMLImageElement && !isSafeRichTextUrl(element.getAttribute("src") || "")) {
|
||||
element.removeAttribute("src");
|
||||
}
|
||||
});
|
||||
return container.innerHTML;
|
||||
}
|
||||
|
||||
/** 兼容历史数据中被转义后保存的富文本标签,并统一执行安全清理。 */
|
||||
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 || "";
|
||||
if (!content) return "";
|
||||
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;
|
||||
if (/&(?:amp;)?lt;\/?(?:h[1-6]|p|ul|ol|li|blockquote|table|img|a)\b/i.test(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;
|
||||
return sanitizeRichTextHtml(decoded);
|
||||
}
|
||||
function setMeta(name: string, content?: string) {
|
||||
const selector = `meta[name="${name}"]`;
|
||||
@@ -495,15 +537,16 @@ function ConfiguredPage({ slug }: { slug: string }) {
|
||||
}, [slug]);
|
||||
if (error) return <ErrorState message={error} />;
|
||||
if (!data) return <div className="loading">Loading…</div>;
|
||||
const agreementPage = ["COOKIE_POLICY", "PRIVACY_POLICY", "TERMS_OF_SERVICE"].includes(data.systemPageType);
|
||||
return (
|
||||
<article className="detail">
|
||||
<article className={`detail configured-page${agreementPage ? " legal-page" : ""}`}>
|
||||
<Crumbs current={data.pageName} />
|
||||
<p className="eyebrow">COMPANY INFORMATION</p>
|
||||
<p className="eyebrow">{agreementPage ? "LEGAL INFORMATION" : "COMPANY INFORMATION"}</p>
|
||||
<h1>{data.pageName}</h1>
|
||||
<p className="lead">{data.summary}</p>
|
||||
{data.summary && <p className="lead">{data.summary}</p>}
|
||||
<div
|
||||
className="content"
|
||||
dangerouslySetInnerHTML={{ __html: data.content }}
|
||||
dangerouslySetInnerHTML={{ __html: normalizeRichTextHtml(data.content) }}
|
||||
/>
|
||||
</article>
|
||||
);
|
||||
|
||||
@@ -302,6 +302,29 @@ nav a:hover {
|
||||
font-size: 20px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
.configured-page .content {
|
||||
line-height: 1.75;
|
||||
}
|
||||
.configured-page .content p {
|
||||
color: #4f5d60;
|
||||
margin: 0 0 18px;
|
||||
}
|
||||
.configured-page .content ul,
|
||||
.configured-page .content ol {
|
||||
color: #4f5d60;
|
||||
padding-left: 24px;
|
||||
margin: 12px 0 24px;
|
||||
}
|
||||
.configured-page .content li + li {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.legal-page {
|
||||
max-width: 980px;
|
||||
}
|
||||
.legal-page .content {
|
||||
border-top: 1px solid #d7dfdc;
|
||||
padding-top: 4px;
|
||||
}
|
||||
.specs {
|
||||
margin-top: 55px;
|
||||
border-top: 2px solid #203630;
|
||||
|
||||
Reference in new issue
Block a user