bug修复

This commit is contained in:
张锐 committed 2026-11-25 20:46:36 +08:00
1 parent 7fed799118
commit eae135ec88
37 files changed
+866 -27

No files matched your search

+143 -15
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { ArrowRight, ChevronRight, Image as ImageIcon, Mail, Menu, Search, X } from "lucide-react";
import { ArrowRight, ChevronRight, Facebook, Image as ImageIcon, Instagram, Linkedin, Mail, Menu, MessageCircle, Music2, Pin, Search, Twitter, Type, X, Youtube } from "lucide-react";
import "./styles.css";
import { initializeAnalytics, routePageCode, trackInquirySubmitted, trackPageLeave, trackPageView } from "./analytics";
@@ -47,6 +47,7 @@ type SeoData = {
ogImageUrl?: string;
structuredData?: string;
};
type SocialChannel = { platform: string; displayName: string; profileUrl: string; shareEnabled: boolean; floatingEnabled: boolean };
function assetUrl(url?: string): string { return url || ""; }
async function post(path: string, body: unknown) {
const r = await fetch(API + path, {
@@ -173,6 +174,8 @@ const nav = [
["About", "/about-us"],
];
type NavigationItem = { title: string; url: string; openType: "CURRENT" | "NEW"; children: NavigationItem[] };
type ProductCategory = { categoryCode: string; parentCategoryCode?: string; categoryName: string; slug: string; sortNo: number };
type ProductCategoryNode = ProductCategory & { children: ProductCategoryNode[] };
/** 读取已发布导航,没有配置时返回既有默认菜单。 */
function useNavigation(position: "HEADER" | "FOOTER"): NavigationItem[] {
@@ -188,9 +191,53 @@ function useNavigation(position: "HEADER" | "FOOTER"): NavigationItem[] {
return items;
}
/** 读取已发布产品分类,并构建稳定的父子分类树。 */
function useProductCategoryTree(): ProductCategoryNode[] {
const [categories, setCategories] = useState<ProductCategory[]>([]);
useEffect(() => {
let active = true;
post("/products/categories/list", {})
.then((data) => { if (active) setCategories(data.items || []); })
.catch(() => undefined);
return () => { active = false; };
}, []);
const children = new Map<string, ProductCategory[]>();
categories.forEach((category) => {
const parentCode = category.parentCategoryCode || "";
children.set(parentCode, [...(children.get(parentCode) || []), category]);
});
const build = (parentCode: string): ProductCategoryNode[] => (children.get(parentCode) || [])
.sort((left, right) => left.sortNo - right.sortNo)
.map((category) => ({ ...category, children: build(category.categoryCode) }));
return build("");
}
/** 读取当前站点已启用的社媒渠道配置。 */
function useSocialChannels(): SocialChannel[] {
const [channels, setChannels] = useState<SocialChannel[]>([]);
useEffect(() => {
let active = true;
post("/social-channels/list", {})
.then((data) => { if (active) setChannels(data.items || []); })
.catch(() => undefined);
return () => { active = false; };
}, []);
return channels;
}
/** 将产品分类树转换成页头导航树。 */
function productCategoryNavigation(categories: ProductCategoryNode[]): NavigationItem[] {
return categories.map((category) => ({
title: category.categoryName,
url: `/products?category=${category.categoryCode}`,
openType: "CURRENT",
children: productCategoryNavigation(category.children),
}));
}
/** 渲染支持二级菜单的前台导航链接。 */
function NavigationLinks({ items }: { items: NavigationItem[] }) {
return <>{items.map((item) => <div className="site-nav-item" key={`${item.title}-${item.url}`}><a href={item.url} target={item.openType === "NEW" ? "_blank" : undefined} rel={item.openType === "NEW" ? "noreferrer" : undefined}>{item.title}</a>{item.children?.length > 0 && <div className="site-subnav">{item.children.map((child) => <a href={child.url} key={`${child.title}-${child.url}`} target={child.openType === "NEW" ? "_blank" : undefined} rel={child.openType === "NEW" ? "noreferrer" : undefined}>{child.title}</a>)}</div>}</div>)}</>;
return <>{items.map((item) => <div className="site-nav-item" key={`${item.title}-${item.url}`}><a href={item.url} target={item.openType === "NEW" ? "_blank" : undefined} rel={item.openType === "NEW" ? "noreferrer" : undefined}>{item.title}</a>{item.children?.length > 0 && <div className="site-subnav"><NavigationLinks items={item.children}/></div>}</div>)}</>;
}
function route() {
const p = location.pathname.split("/").filter(Boolean);
@@ -255,7 +302,15 @@ function CustomCodeRuntime() {
useEffect(() => { let nodes: HTMLElement[] = []; post("/custom-codes/list", { siteCode: "SIT0000000000001" }).then(data => { (data.items || []).forEach((item: { content: string; position: string }) => { const container = item.position === "HEAD" ? document.head : document.body; const wrapper = document.createElement("div"); wrapper.innerHTML = item.content; Array.from(wrapper.children).forEach(child => { let node: HTMLElement = child as HTMLElement; if (child.tagName === "SCRIPT") { const script = document.createElement("script"); Array.from(child.attributes).forEach(attribute => script.setAttribute(attribute.name, attribute.value)); script.text = child.textContent || ""; node = script; } container.insertBefore(node, item.position === "BODY_START" ? container.firstChild : null); nodes.push(node); }); }); }).catch(() => undefined); return () => nodes.forEach(node => node.remove()); }, []);
return null;
}
type DecorationSection = { id:string; type:string; title:string; subtitle:string; imageUrl:string; buttonText:string; buttonUrl:string; sourceType:string; limit:number; visible:boolean; background:string; textColor:string };
type DecorationSection = { id:string; type:string; title:string; subtitle:string; imageUrl:string; buttonText:string; buttonUrl:string; sourceType:string; limit:number; visible:boolean; background:string; textColor:string; showProductInformation?:boolean; productInformationTitle?:string; productInformationLimit?:number };
type ProductDetailConfiguration = {
/** 是否在商品摘要区域展示产品信息。 */
showProductInformation?: boolean;
/** 产品信息区英文标题。 */
productInformationTitle?: string;
/** 产品信息区最多展示的自定义属性数量。 */
productInformationLimit?: number;
};
type DecorationSchema = { global:{primaryColor:string;backgroundColor:string;textColor:string;fontFamily:string;contentWidth:number};sections:DecorationSection[] };
function DecoratedPage({ pageType, fallback }: { pageType: string; fallback: React.ReactNode }) {
const [schema,setSchema]=useState<DecorationSchema|null>(null); const [loaded,setLoaded]=useState(false);
@@ -270,26 +325,30 @@ function LiveSection({section}:{section:DecorationSection}) {
if(section.type==="HEADER")return <LiveHeader style={style}/>;
if(section.type==="HERO")return <section className="live-hero" style={{...style,backgroundImage:section.imageUrl?`linear-gradient(90deg,rgba(0,0,0,.72),rgba(0,0,0,.12)),url(${section.imageUrl})`:undefined}}><div><p>ENGINEERED FOR INDUSTRY</p><h1>{section.title}</h1><span>{section.subtitle}</span>{section.buttonText&&<a href={section.buttonUrl||"#"}>{section.buttonText}<ArrowRight size={17}/></a>}</div></section>;
if(section.type==="RICH_TEXT")return <section className="live-rich" style={style}><h2>{section.title}</h2><p>{section.subtitle}</p></section>;
if(section.type==="PRODUCT_DETAIL")return <RuntimeProductDetail/>;
if(section.type==="PRODUCT_DETAIL")return <RuntimeProductDetail configuration={section}/>;
if(section.type==="PRODUCTS"||section.type==="CONTENT")return <LiveCollection section={section}/>;
if(section.type==="INQUIRY")return <section className="live-inquiry" style={style}><div><p>START A PROJECT</p><h2>{section.title}</h2><span>{section.subtitle}</span></div><InquiryForm scene="GENERAL"/></section>;
if(section.type==="FOOTER")return <footer className="live-footer" style={style}><div><b>SHOPLIX</b><p>Industrial Solutions</p></div><div><b>Explore</b><a href="/products">Products</a><a href="/cases">Cases</a><a href="/news">News</a></div><div><b>Company</b><a href="/about-us">About Us</a><a href="/contact-us">Contact Us</a><a href="/privacy-policy">Privacy Policy</a></div><small>{section.subtitle||"Copyright © 2026. All rights reserved."}</small></footer>;
return null;
}
/** 装修模板中的产品详情组件,按当前访问路径加载真实商品。 */
function RuntimeProductDetail() {
function RuntimeProductDetail({ configuration }: { configuration: ProductDetailConfiguration }) {
const slug = route().slug;
const [product, setProduct] = useState<Record<string, any>>();
const [error, setError] = useState("");
useEffect(() => { if (!slug) return; post("/products/detail", { slug }).then(setProduct).catch((reason) => setError(reason instanceof Error ? reason.message : "Unable to load product")); }, [slug]);
if (error) return <ErrorState message={error}/>;
if (!product) return <div className="loading">Loading product…</div>;
return <ProductDetailView data={product}/>;
return <ProductDetailView data={product} configuration={configuration}/>;
}
/** 装修页面使用的动态页头。 */
function LiveHeader({ style }: { style: React.CSSProperties }) {
const items = useNavigation("HEADER");
return <header className="live-header" style={style}><a href="/" className="live-logo">SHOPLIX</a><nav><NavigationLinks items={items}/></nav><a className="live-quote" href="/contact-us">Get a quote</a></header>;
const productCategories = useProductCategoryTree();
const navigationItems = items.map((item) => productCategories.length > 0 && item.url.split("?")[0] === "/products"
? { ...item, children: productCategoryNavigation(productCategories) }
: item);
return <header className="live-header" style={style}><a href="/" className="live-logo">SHOPLIX</a><nav><NavigationLinks items={navigationItems}/></nav><a className="live-quote" href="/contact-us">Get a quote</a></header>;
}
function LiveCollection({section}:{section:DecorationSection}) {
const [items,setItems]=useState<Item[]>([]);
@@ -299,6 +358,10 @@ function LiveCollection({section}:{section:DecorationSection}) {
}
function Header() {
const items = useNavigation("HEADER");
const productCategories = useProductCategoryTree();
const navigationItems = items.map((item) => productCategories.length > 0 && item.url.split("?")[0] === "/products"
? { ...item, children: productCategoryNavigation(productCategories) }
: item);
const [searchOpen, setSearchOpen] = useState(false);
useEffect(() => {
if (!searchOpen) return;
@@ -315,7 +378,7 @@ function Header() {
<span>Industrial Solutions</span>
</a>
<nav>
<NavigationLinks items={items}/>
<NavigationLinks items={navigationItems}/>
</nav>
<div className="actions">
<button className="search-toggle" type="button" aria-label="Search website" title="Search website" aria-expanded={searchOpen} onClick={() => setSearchOpen((value) => !value)}>
@@ -406,6 +469,7 @@ function Collection({
categoryCode?: string;
}) {
const navigation = useNavigation("HEADER");
const productCategories = useProductCategoryTree();
const [data, setData] = useState<Item[] | Record<string, unknown>>([]);
const [error, setError] = useState("");
useEffect(() => {
@@ -484,10 +548,12 @@ function Collection({
<aside className="category-sidebar" aria-label={`${title} categories`}>
<p>Categories</p>
<a className={!categoryCode ? "active" : ""} href={basePath}>All {title}</a>
{categoryItems.map((item) => {
const itemCategory = new URL(item.url, location.origin).searchParams.get("category");
return <a className={itemCategory === categoryCode ? "active" : ""} href={item.url} key={`${item.title}-${item.url}`}>{item.title}<ChevronRight size={15}/></a>;
})}
{type === "products"
? <ProductCategoryLinks items={productCategories} selectedCategoryCode={categoryCode}/>
: categoryItems.map((item) => {
const itemCategory = new URL(item.url, location.origin).searchParams.get("category");
return <a className={itemCategory === categoryCode ? "active" : ""} href={item.url} key={`${item.title}-${item.url}`}>{item.title}<ChevronRight size={15}/></a>;
})}
</aside>
<div className="cards">
{(data as Item[]).map((item) => (
@@ -525,6 +591,14 @@ function Collection({
);
}
/** 递归渲染产品分类侧栏,保留分类层级关系。 */
function ProductCategoryLinks({ items, selectedCategoryCode, depth = 0 }: { items: ProductCategoryNode[]; selectedCategoryCode?: string; depth?: number }) {
return <>{items.map((item) => <React.Fragment key={item.categoryCode}>
<a className={item.categoryCode === selectedCategoryCode ? "active" : ""} href={`/products?category=${item.categoryCode}`} style={{ "--category-depth": depth } as React.CSSProperties}>{item.categoryName}{item.children.length > 0 && <ChevronRight size={15}/>}</a>
{item.children.length > 0 && <ProductCategoryLinks items={item.children} selectedCategoryCode={selectedCategoryCode} depth={depth + 1}/>}
</React.Fragment>)}</>;
}
/** 搜索产品及内容模块,并在统一结果页中展示。 */
function SearchResults({ query }: { query: string }) {
const [results, setResults] = useState<Array<{ item: Item; base: string; label: string }>>([]);
@@ -557,10 +631,12 @@ function SearchResults({ query }: { query: string }) {
</section>;
}
/** B2B 商品详情主体,集中展示主图、核心信息、参数、详情和询盘入口。 */
function ProductDetailView({ data: d }: { data: Record<string, any> }) {
function ProductDetailView({ data: d, configuration }: { data: Record<string, any>; configuration?: ProductDetailConfiguration }) {
const [inquiryOpen, setInquiryOpen] = useState(false);
const productImages = d.images?.length ? d.images : d.coverMediaUrl ? [{mediaCode:d.coverMediaCode,url:d.coverMediaUrl}] : [];
const [selectedImage, setSelectedImage] = useState(0);
const attributes = (d.attributes || []).slice(0, configuration?.productInformationLimit || d.attributes?.length || 0);
const showProductInformation = configuration?.showProductInformation !== false && (Boolean(d.model) || attributes.length > 0);
useEffect(() => setSelectedImage(0), [d.productCode]);
useEffect(() => {
if (!inquiryOpen) return;
@@ -588,12 +664,18 @@ function ProductDetailView({ data: d }: { data: Record<string, any> }) {
<div className="product-summary">
<p className="eyebrow">PRODUCT</p>
<h1>{d.productName}</h1>
{d.model && <div className="product-model">Model <strong>{d.model}</strong></div>}
<p className="lead">{d.summary}</p>
{showProductInformation && <section className="product-information">
<h2>{configuration?.productInformationTitle || "Product information"}</h2>
<dl>
{d.model && <div><dt>Model</dt><dd>{d.model}</dd></div>}
{attributes.map((attribute:any,index:number)=><div key={`${attribute.name}-${index}`}><dt>{attribute.name}</dt><dd>{attribute.value} {attribute.unit}</dd></div>)}
</dl>
</section>}
{d.inquiryEnabled && <button className="product-inquiry-cta" type="button" onClick={() => setInquiryOpen(true)}><Mail size={18}/>Request a quote</button>}
<SocialShareBar title={String(d.productName || document.title)}/>
</div>
</section>
{d.attributes?.length > 0 && <section className="specs product-attributes"><h2>Product attributes</h2>{d.attributes.map((a:any,i:number)=><div key={i}><span>{a.name}</span><strong>{a.value} {a.unit}</strong></div>)}</section>}
<div className="content product-content" dangerouslySetInnerHTML={{__html:normalizeRichTextHtml(d.content)}}/>
{d.specifications?.length > 0 && <section className="specs"><h2>Technical specifications</h2>{d.specifications.map((s:any,i:number)=><div key={i}><span>{s.groupName&&`${s.groupName} · `}{s.name}</span><strong>{s.value} {s.unit}</strong></div>)}</section>}
{d.inquiryEnabled && inquiryOpen && (
@@ -606,6 +688,51 @@ function ProductDetailView({ data: d }: { data: Record<string, any> }) {
)}
</article>;
}
/** 返回社媒平台对应的图标。 */
function socialPlatformIcon(platform: string): React.ReactNode {
const icons: Record<string, React.ReactNode> = {
FACEBOOK: <Facebook size={17}/>, X: <Twitter size={17}/>, LINKEDIN: <Linkedin size={17}/>,
YOUTUBE: <Youtube size={17}/>, INSTAGRAM: <Instagram size={17}/>, WHATSAPP: <MessageCircle size={17}/>,
PINTEREST: <Pin size={17}/>, TIKTOK: <Music2 size={17}/>, LINE: <MessageCircle size={17}/>,
TUMBLR: <Type size={17}/>, EMAIL: <Mail size={17}/>,
};
return icons[platform] || platform.slice(0, 1);
}
/** 根据平台和当前页面生成分享地址。 */
function socialShareUrl(channel: SocialChannel, title: string): string {
const pageUrl = encodeURIComponent(location.href);
const pageTitle = encodeURIComponent(title);
const links: Record<string, string> = {
FACEBOOK: `https://www.facebook.com/sharer/sharer.php?u=${pageUrl}`,
X: `https://twitter.com/intent/tweet?url=${pageUrl}&text=${pageTitle}`,
LINKEDIN: `https://www.linkedin.com/sharing/share-offsite/?url=${pageUrl}`,
WHATSAPP: `https://wa.me/?text=${pageTitle}%20${pageUrl}`,
PINTEREST: `https://pinterest.com/pin/create/button/?url=${pageUrl}&description=${pageTitle}`,
LINE: `https://social-plugins.line.me/lineit/share?url=${pageUrl}`,
TUMBLR: `https://www.tumblr.com/widgets/share/tool?canonicalUrl=${pageUrl}&title=${pageTitle}`,
EMAIL: `mailto:${channel.profileUrl}?subject=${pageTitle}&body=${pageUrl}`,
};
return links[channel.platform] || channel.profileUrl;
}
/** 展示产品详情中已启用的社媒分享入口。 */
function SocialShareBar({ title }: { title: string }) {
const channels = useSocialChannels().filter((channel) => channel.shareEnabled);
if (channels.length === 0) return null;
return <div className="social-share-bar" aria-label="Share this product">{channels.map((channel) => <a href={socialShareUrl(channel, title)} key={channel.platform} target="_blank" rel="noreferrer" title={`Share on ${channel.displayName}`} aria-label={`Share on ${channel.displayName}`} data-platform={channel.platform}>{socialPlatformIcon(channel.platform)}</a>)}</div>;
}
/** 展示全站右侧已启用的社媒联系悬浮栏。 */
function SocialFloatingBar() {
const channels = useSocialChannels().filter((channel) => channel.floatingEnabled);
if (channels.length === 0) return null;
return <aside className="social-floating-bar" aria-label="Social media channels">{channels.map((channel) => {
const href = channel.platform === "EMAIL" && !channel.profileUrl.startsWith("mailto:") ? `mailto:${channel.profileUrl}` : channel.profileUrl;
return <a href={href} key={channel.platform} target={channel.platform === "EMAIL" ? undefined : "_blank"} rel={channel.platform === "EMAIL" ? undefined : "noreferrer"} title={channel.displayName} aria-label={channel.displayName} data-platform={channel.platform}>{socialPlatformIcon(channel.platform)}</a>;
})}</aside>;
}
function Page({ slug }: { slug: string }) {
if (slug === "contact-us")
return (
@@ -863,5 +990,6 @@ function Footer() {
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
<SocialFloatingBar />
</React.StrictMode>,
);