996 lines
48 KiB
TypeScript
996 lines
48 KiB
TypeScript
import React, { useEffect, useState } from "react";
|
|
import { createRoot } from "react-dom/client";
|
|
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";
|
|
|
|
const API = import.meta.env.VITE_SITE_API_BASE || "/api/site/v1";
|
|
type ContentType = "NEWS" | "CASE" | "HELP";
|
|
type Item = {
|
|
productCode?: string;
|
|
contentCode?: string;
|
|
productName?: string;
|
|
title?: string;
|
|
slug: string;
|
|
summary?: string;
|
|
model?: string;
|
|
publishTime?: number;
|
|
coverMediaUrl?: string;
|
|
};
|
|
type InquiryField = {
|
|
fieldCode: string;
|
|
fieldKey: string;
|
|
label: string;
|
|
fieldType: string;
|
|
placeholder?: string;
|
|
helpText?: string;
|
|
maxLength?: number;
|
|
required: boolean;
|
|
optionsJson?: string;
|
|
widthType: string;
|
|
};
|
|
type InquiryFormData = {
|
|
formCode: string;
|
|
description?: string;
|
|
submitButtonText: string;
|
|
successMessage: string;
|
|
fields: InquiryField[];
|
|
};
|
|
type SeoData = {
|
|
title: string;
|
|
description?: string;
|
|
keywords?: string;
|
|
canonicalUrl?: string;
|
|
robots?: string;
|
|
ogTitle?: string;
|
|
ogDescription?: string;
|
|
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, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
});
|
|
if (!r.ok)
|
|
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) return "";
|
|
const decoder = document.createElement("textarea");
|
|
let decoded = content;
|
|
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, "");
|
|
return sanitizeRichTextHtml(decoded);
|
|
}
|
|
function setMeta(name: string, content?: string) {
|
|
const selector = `meta[name="${name}"]`;
|
|
let element = document.head.querySelector<HTMLMetaElement>(selector);
|
|
if (!content) { element?.remove(); return; }
|
|
if (!element) { element = document.createElement("meta"); element.name = name; document.head.appendChild(element); }
|
|
element.content = content;
|
|
}
|
|
function setProperty(property: string, content?: string) {
|
|
const selector = `meta[property="${property}"]`;
|
|
let element = document.head.querySelector<HTMLMetaElement>(selector);
|
|
if (!content) { element?.remove(); return; }
|
|
if (!element) { element = document.createElement("meta"); element.setAttribute("property", property); document.head.appendChild(element); }
|
|
element.content = content;
|
|
}
|
|
function applySeo(data?: SeoData) {
|
|
const canonicalValue = data?.canonicalUrl || `${location.origin}${location.pathname}`;
|
|
const canonical = new URL(canonicalValue, location.origin).href;
|
|
if (data?.title) document.title = data.title;
|
|
setMeta("description", data?.description);
|
|
setMeta("keywords", data?.keywords);
|
|
setMeta("robots", data?.robots || "index,follow");
|
|
let link = document.head.querySelector<HTMLLinkElement>('link[rel="canonical"]');
|
|
if (!link) { link = document.createElement("link"); link.rel = "canonical"; document.head.appendChild(link); }
|
|
link.href = canonical;
|
|
setProperty("og:title", data?.ogTitle || data?.title);
|
|
setProperty("og:description", data?.ogDescription || data?.description);
|
|
setProperty("og:image", data?.ogImageUrl ? new URL(data.ogImageUrl, location.origin).href : undefined);
|
|
setProperty("og:url", canonical);
|
|
let structuredData = document.head.querySelector<HTMLScriptElement>('script[data-shoplix-seo="json-ld"]');
|
|
structuredData?.remove();
|
|
if (data?.structuredData) {
|
|
structuredData = document.createElement("script"); structuredData.type = "application/ld+json";
|
|
structuredData.dataset.shoplixSeo = "json-ld"; structuredData.text = data.structuredData;
|
|
document.head.appendChild(structuredData);
|
|
}
|
|
}
|
|
function usePageSeo(pageType: string, targetCode = "") {
|
|
useEffect(() => {
|
|
let active = true;
|
|
applySeo();
|
|
if (!pageType) return () => { active = false; };
|
|
post("/seo/detail", { pageType, targetCode })
|
|
.then((data: SeoData) => { if (active) applySeo(data); })
|
|
.catch(() => undefined);
|
|
return () => { active = false; };
|
|
}, [pageType, targetCode]);
|
|
}
|
|
const nav = [
|
|
["Home", "/"],
|
|
["Products", "/products"],
|
|
["Cases", "/cases"],
|
|
["News", "/news"],
|
|
["Help", "/help"],
|
|
["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[] {
|
|
const fallback = nav.map(([title, url]) => ({ title, url, openType: "CURRENT" as const, children: [] }));
|
|
const [items, setItems] = useState<NavigationItem[]>(fallback);
|
|
useEffect(() => {
|
|
let active = true;
|
|
post("/navigations/detail", { position })
|
|
.then((data) => { if (active && data.items?.length) setItems(data.items); })
|
|
.catch(() => undefined);
|
|
return () => { active = false; };
|
|
}, [position]);
|
|
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"><NavigationLinks items={item.children}/></div>}</div>)}</>;
|
|
}
|
|
function route() {
|
|
const p = location.pathname.split("/").filter(Boolean);
|
|
const parameters = new URLSearchParams(location.search);
|
|
const previewPage = parameters.get("previewPage") || undefined;
|
|
const categoryCode = parameters.get("category") || undefined;
|
|
const query = parameters.get("q") || undefined;
|
|
if (!p.length) return { kind: "home", previewPage, categoryCode };
|
|
if (p[0] === "search") return { kind: "search", previewPage, categoryCode, query };
|
|
if (["products", "news", "cases", "help"].includes(p[0]))
|
|
return { kind: p[0], slug: p[1], previewPage, categoryCode };
|
|
return { kind: "page", slug: p[0], previewPage, categoryCode };
|
|
}
|
|
function App() {
|
|
const r = route();
|
|
useEffect(() => {
|
|
initializeAnalytics();
|
|
const context = { pageCode: routePageCode(), pageName: document.title, scene: r.kind };
|
|
trackPageView(context);
|
|
const leave = () => trackPageLeave(context);
|
|
window.addEventListener("pagehide", leave, { once: true });
|
|
return () => window.removeEventListener("pagehide", leave);
|
|
}, [r.kind, r.slug]);
|
|
const runtime = <CustomCodeRuntime />;
|
|
const seoRuntime = <SeoRuntime current={r} />;
|
|
if (r.kind === "home") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || "HOME"} fallback={<><Header /><main><Home /></main><Footer /></>} /></>;
|
|
if (r.kind === "products") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug ? "PRODUCT_DETAIL" : "PRODUCT_CATEGORY")} fallback={<><Header /><main><Collection title="Products" type="products" slug={r.slug} categoryCode={r.categoryCode} /></main><Footer /></>} /></>;
|
|
if (r.kind === "news") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug ? "NEWS_DETAIL" : "NEWS_CATEGORY")} fallback={<><Header /><main><Collection title="News" type="NEWS" slug={r.slug} categoryCode={r.categoryCode} /></main><Footer /></>} /></>;
|
|
if (r.kind === "cases") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug ? "CASE_DETAIL" : "CASE_CATEGORY")} fallback={<><Header /><main><Collection title="Case Studies" type="CASE" slug={r.slug} categoryCode={r.categoryCode} /></main><Footer /></>} /></>;
|
|
if (r.kind === "help") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug ? "HELP_DETAIL" : "HELP_CATEGORY")} fallback={<><Header /><main><Collection title="Help Center" type="HELP" slug={r.slug} categoryCode={r.categoryCode} /></main><Footer /></>} /></>;
|
|
if (r.kind === "search") return <>{runtime}{seoRuntime}<Header /><main><SearchResults query={r.query || ""} /></main><Footer /></>;
|
|
return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug === "about-us" ? "ABOUT_US" : "CUSTOM_PAGE")} fallback={<><Header /><main><Page slug={r.slug!} /></main><Footer /></>} /></>;
|
|
}
|
|
function SeoRuntime({ current }: { current: ReturnType<typeof route> }) {
|
|
const [target, setTarget] = useState({ pageType: "", targetCode: "" });
|
|
useEffect(() => {
|
|
let active = true;
|
|
const listType = current.kind === "home" ? "HOME"
|
|
: current.kind === "products" && !current.slug ? "PRODUCT_LIST"
|
|
: current.kind === "news" && !current.slug ? "NEWS_LIST"
|
|
: current.kind === "cases" && !current.slug ? "CASE_LIST"
|
|
: current.kind === "help" && !current.slug ? "HELP_CATEGORY_LIST" : "";
|
|
if (listType) { setTarget({ pageType: listType, targetCode: "" }); return () => { active = false; }; }
|
|
setTarget({ pageType: "", targetCode: "" });
|
|
if (["products", "news", "cases", "help"].includes(current.kind) && current.slug) {
|
|
const product = current.kind === "products";
|
|
const contentType = current.kind === "cases" ? "CASE" : current.kind.toUpperCase();
|
|
post(product ? "/products/detail" : "/contents/detail", product ? { slug: current.slug } : { contentType, slug: current.slug })
|
|
.then(data => { if (active) setTarget({ pageType: product ? "PRODUCT_DETAIL" : `${contentType}_DETAIL`, targetCode: data.productCode || data.contentCode || "" }); })
|
|
.catch(() => undefined);
|
|
} else if (current.kind === "page" && current.slug) {
|
|
post("/pages/detail", { slug: current.slug })
|
|
.then(data => { if (active) setTarget({ pageType: data.pageType === "SYSTEM_PAGE" ? "SYSTEM_PAGE" : "CUSTOM_PAGE", targetCode: data.pageCode || "" }); })
|
|
.catch(() => undefined);
|
|
}
|
|
return () => { active = false; };
|
|
}, [current.kind, current.slug]);
|
|
usePageSeo(target.pageType, target.targetCode);
|
|
return null;
|
|
}
|
|
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; 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);
|
|
useEffect(()=>{setLoaded(false);setSchema(null);post("/decorations/detail",{pageType}).then(data=>{if(data.schema)setSchema(JSON.parse(data.schema));setLoaded(true)}).catch(()=>setLoaded(true))},[pageType]);
|
|
if(!loaded) return <div className="site-loading">Loading...</div>;
|
|
if(!schema || !schema.sections?.length) return <>{fallback}</>;
|
|
return <div className="decorated-site" style={{background:schema.global.backgroundColor,color:schema.global.textColor,fontFamily:schema.global.fontFamily,"--brand":schema.global.primaryColor} as React.CSSProperties}>{schema.sections.filter(section=>section.visible).map(section=><LiveSection key={section.id} section={section}/>)}</div>;
|
|
}
|
|
function LiveSection({section}:{section:DecorationSection}) {
|
|
const style={background:section.background,color:section.textColor};
|
|
if(section.type==="ANNOUNCEMENT")return <div className="live-announcement" style={style}>{section.title}</div>;
|
|
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 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({ 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} configuration={configuration}/>;
|
|
}
|
|
/** 装修页面使用的动态页头。 */
|
|
function LiveHeader({ style }: { style: React.CSSProperties }) {
|
|
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);
|
|
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[]>([]);
|
|
useEffect(()=>{const path=section.type==="PRODUCTS"?"/products/list":"/contents/list";const body=section.type==="PRODUCTS"?{}:{contentType:section.sourceType||"CASE"};post(path,body).then(data=>setItems((data.items||[]).slice(0,section.limit||3))).catch(()=>setItems([]))},[section.type,section.sourceType,section.limit]);
|
|
const base=section.type==="PRODUCTS"?"products":(section.sourceType||"CASE").toLowerCase();
|
|
return <section className="live-collection" style={{background:section.background,color:section.textColor}}><p>FEATURED</p><h2>{section.title}</h2><div>{items.map(item=><a href={`/${base}/${item.slug}`} key={item.productCode||item.contentCode}><div>{item.coverMediaUrl&&<img src={assetUrl(item.coverMediaUrl)} alt={item.productName||item.title}/>}</div><span>{section.type==="PRODUCTS"?"PRODUCT":section.sourceType}</span><h3>{item.productName||item.title}</h3><p>{item.summary}</p></a>)}</div></section>;
|
|
}
|
|
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;
|
|
const closeOnEscape = (event: KeyboardEvent) => {
|
|
if (event.key === "Escape") setSearchOpen(false);
|
|
};
|
|
window.addEventListener("keydown", closeOnEscape);
|
|
return () => window.removeEventListener("keydown", closeOnEscape);
|
|
}, [searchOpen]);
|
|
return (
|
|
<header className="site-header">
|
|
<a className="logo" href="/">
|
|
<b>SHOPLIX</b>
|
|
<span>Industrial Solutions</span>
|
|
</a>
|
|
<nav>
|
|
<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)}>
|
|
{searchOpen ? <X size={19}/> : <Search size={19}/>}
|
|
</button>
|
|
<a className="quote" href="/contact-us">
|
|
<Mail size={16} />
|
|
Request a Quote
|
|
</a>
|
|
<Menu className="mobile" />
|
|
</div>
|
|
{searchOpen && <form className="header-search" action="/search" method="get">
|
|
<Search size={18}/>
|
|
<input name="q" type="search" autoFocus required placeholder="Search products, news, cases and help" aria-label="Search keywords"/>
|
|
<button type="submit">Search</button>
|
|
</form>}
|
|
</header>
|
|
);
|
|
}
|
|
function Home() {
|
|
return (
|
|
<>
|
|
<section className="hero">
|
|
<div className="hero-copy">
|
|
<p className="eyebrow">ENGINEERED FOR INDUSTRY</p>
|
|
<h1>Reliable equipment for demanding operations.</h1>
|
|
<p>
|
|
Explore industrial products, application expertise and
|
|
project-proven solutions from a partner built for B2B delivery.
|
|
</p>
|
|
<div>
|
|
<a className="cta" href="/products">
|
|
Explore Products <ArrowRight size={17} />
|
|
</a>
|
|
<a className="text-link" href="/cases">
|
|
View Case Studies
|
|
</a>
|
|
</div>
|
|
</div>
|
|
<div className="hero-visual">
|
|
<div className="metric">
|
|
<strong>16+</strong>
|
|
<span>Industries served</span>
|
|
</div>
|
|
<div className="lines" />
|
|
</div>
|
|
</section>
|
|
<section className="intro">
|
|
<p className="eyebrow">WHAT WE DELIVER</p>
|
|
<h2>From technical selection to project delivery</h2>
|
|
<div className="pillars">
|
|
<article>
|
|
<b>01</b>
|
|
<h3>Product expertise</h3>
|
|
<p>
|
|
Clear technical parameters and application-focused
|
|
recommendations.
|
|
</p>
|
|
</article>
|
|
<article>
|
|
<b>02</b>
|
|
<h3>Proven applications</h3>
|
|
<p>
|
|
Documented case studies for real industrial operating conditions.
|
|
</p>
|
|
</article>
|
|
<article>
|
|
<b>03</b>
|
|
<h3>Responsive support</h3>
|
|
<p>
|
|
Direct inquiry routing and practical help throughout your project.
|
|
</p>
|
|
</article>
|
|
</div>
|
|
</section>
|
|
</>
|
|
);
|
|
}
|
|
function Collection({
|
|
title,
|
|
type,
|
|
slug,
|
|
categoryCode,
|
|
}: {
|
|
title: string;
|
|
type: "products" | ContentType;
|
|
slug?: string;
|
|
categoryCode?: string;
|
|
}) {
|
|
const navigation = useNavigation("HEADER");
|
|
const productCategories = useProductCategoryTree();
|
|
const [data, setData] = useState<Item[] | Record<string, unknown>>([]);
|
|
const [error, setError] = useState("");
|
|
useEffect(() => {
|
|
const run = async () => {
|
|
try {
|
|
if (slug) {
|
|
setData(
|
|
await post(
|
|
type === "products" ? "/products/detail" : "/contents/detail",
|
|
type === "products" ? { slug } : { contentType: type, slug },
|
|
),
|
|
);
|
|
} else {
|
|
const x = await post(
|
|
type === "products" ? "/products/list" : "/contents/list",
|
|
type === "products" ? { categoryCode } : { contentType: type, categoryCode },
|
|
);
|
|
setData(x.items || []);
|
|
}
|
|
} catch (e) {
|
|
setError(e instanceof Error ? e.message : "Unable to load");
|
|
}
|
|
};
|
|
void run();
|
|
}, [type, slug, categoryCode]);
|
|
if (error) return <ErrorState message={error} />;
|
|
if (slug && !Array.isArray(data)) {
|
|
const d = data as Record<string, any>;
|
|
if (type === "products") return <ProductDetailView data={d}/>;
|
|
return (
|
|
<article className="detail">
|
|
<Crumbs current={String(d.productName || d.title || title)} />
|
|
<p className="eyebrow">{title.toUpperCase()}</p>
|
|
<h1>{d.productName || d.title}</h1>
|
|
<p className="lead">{d.summary}</p>
|
|
{d.attributes?.length > 0 && <section className="specs"><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"
|
|
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>
|
|
)}
|
|
</article>
|
|
);
|
|
}
|
|
const basePath = type === "products" ? "/products" : `/${type.toLowerCase()}`;
|
|
const categoryItems = navigation.find((item) => item.url.split("?")[0] === basePath)?.children || [];
|
|
return (
|
|
<section className="listing">
|
|
<Crumbs current={title} />
|
|
<div className="listing-head">
|
|
<div>
|
|
<p className="eyebrow">KNOWLEDGE & SOLUTIONS</p>
|
|
<h1>{title}</h1>
|
|
</div>
|
|
<p>
|
|
Explore our latest {title.toLowerCase()} and find the information you
|
|
need for your next project.
|
|
</p>
|
|
</div>
|
|
<div className="collection-layout">
|
|
<aside className="category-sidebar" aria-label={`${title} categories`}>
|
|
<p>Categories</p>
|
|
<a className={!categoryCode ? "active" : ""} href={basePath}>All {title}</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) => (
|
|
<a
|
|
className="card"
|
|
href={`/${type === "products" ? "products" : type.toLowerCase()}/${item.slug}`}
|
|
key={item.productCode || item.contentCode}
|
|
>
|
|
<div className="thumb">
|
|
{item.coverMediaUrl && (
|
|
<img
|
|
src={assetUrl(item.coverMediaUrl)}
|
|
alt={item.productName || item.title}
|
|
/>
|
|
)}
|
|
<span>{type === "products" ? "PRODUCT" : type}</span>
|
|
</div>
|
|
<div>
|
|
<small>
|
|
{item.model || (item.publishTime ? new Date(item.publishTime).toLocaleDateString("en-CA") : "INSIGHT")}
|
|
</small>
|
|
<h2>{item.productName || item.title}</h2>
|
|
<p>
|
|
{item.summary || "Explore details and technical information."}
|
|
</p>
|
|
<span className="read">
|
|
Read more <ChevronRight size={15} />
|
|
</span>
|
|
</div>
|
|
</a>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</section>
|
|
);
|
|
}
|
|
|
|
/** 递归渲染产品分类侧栏,保留分类层级关系。 */
|
|
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 }>>([]);
|
|
const [loading, setLoading] = useState(Boolean(query.trim()));
|
|
const [error, setError] = useState("");
|
|
useEffect(() => {
|
|
const keyword = query.trim().toLowerCase();
|
|
if (!keyword) { setResults([]); setLoading(false); return; }
|
|
setLoading(true);
|
|
Promise.all([
|
|
post("/products/list", {}).then((data) => ({ items: data.items || [], base: "products", label: "Product" })),
|
|
...(["NEWS", "CASE", "HELP"] as ContentType[]).map((contentType) => post("/contents/list", { contentType }).then((data) => ({ items: data.items || [], base: contentType.toLowerCase(), label: contentType === "CASE" ? "Case" : contentType.charAt(0) + contentType.slice(1).toLowerCase() }))),
|
|
]).then((groups) => {
|
|
const matched = groups.flatMap((group) => group.items.map((item: Item) => ({ item, base: group.base, label: group.label })))
|
|
.filter(({ item }) => [item.productName, item.title, item.summary, item.model].some((value) => value?.toLowerCase().includes(keyword)));
|
|
setResults(matched);
|
|
setError("");
|
|
}).catch((reason) => setError(reason instanceof Error ? reason.message : "Unable to search"))
|
|
.finally(() => setLoading(false));
|
|
}, [query]);
|
|
return <section className="search-page">
|
|
<Crumbs current="Search"/>
|
|
<p className="eyebrow">SITE SEARCH</p>
|
|
<h1>Search</h1>
|
|
<form className="search-page-form" action="/search" method="get"><input name="q" type="search" defaultValue={query} required placeholder="Search products, news, cases and help"/><button type="submit"><Search size={18}/>Search</button></form>
|
|
{loading && <p className="search-status">Searching...</p>}
|
|
{error && <p className="search-status">{error}</p>}
|
|
{!loading && !error && query && <p className="search-status">{results.length} result{results.length === 1 ? "" : "s"} for “{query}”</p>}
|
|
<div className="search-results">{results.map(({ item, base, label }) => <a href={`/${base}/${item.slug}`} key={`${base}-${item.productCode || item.contentCode}`}><span>{label}</span><h2>{item.productName || item.title}</h2><p>{item.summary || "View details"}</p><small>View result <ChevronRight size={14}/></small></a>)}</div>
|
|
</section>;
|
|
}
|
|
/** B2B 商品详情主体,集中展示主图、核心信息、参数、详情和询盘入口。 */
|
|
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;
|
|
const closeOnEscape = (event: KeyboardEvent) => {
|
|
if (event.key === "Escape") setInquiryOpen(false);
|
|
};
|
|
document.body.classList.add("modal-open");
|
|
window.addEventListener("keydown", closeOnEscape);
|
|
return () => {
|
|
document.body.classList.remove("modal-open");
|
|
window.removeEventListener("keydown", closeOnEscape);
|
|
};
|
|
}, [inquiryOpen]);
|
|
return <article className="detail product-detail">
|
|
<Crumbs current={String(d.productName || "Product")}/>
|
|
<section className="product-overview">
|
|
<div className="product-gallery">
|
|
<div className="product-media">
|
|
{productImages[selectedImage]?.url
|
|
? <img src={assetUrl(productImages[selectedImage].url)} alt={`${d.productName || "Product"} ${selectedImage + 1}`}/>
|
|
: <div className="product-image-placeholder"><ImageIcon size={48}/><span>Product image coming soon</span></div>}
|
|
</div>
|
|
{productImages.length>1&&<div className="product-thumbnails">{productImages.map((image:any,index:number)=><button type="button" className={`product-thumbnail${index===selectedImage?' active':''}`} key={image.mediaCode||index} onClick={()=>setSelectedImage(index)}><img src={assetUrl(image.url)} alt={`${d.productName || "Product"} thumbnail ${index+1}`}/></button>)}</div>}
|
|
</div>
|
|
<div className="product-summary">
|
|
<p className="eyebrow">PRODUCT</p>
|
|
<h1>{d.productName}</h1>
|
|
<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>
|
|
<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 && (
|
|
<div className="inquiry-modal-backdrop" role="presentation" onMouseDown={() => setInquiryOpen(false)}>
|
|
<div className="inquiry-modal" role="dialog" aria-modal="true" aria-label="Request a quote" onMouseDown={(event) => event.stopPropagation()}>
|
|
<button className="inquiry-modal-close" type="button" aria-label="Close inquiry form" onClick={() => setInquiryOpen(false)}><X size={22}/></button>
|
|
<InquiryForm scene="PRODUCT" sourceCode={d.productCode}/>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</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 (
|
|
<article className="detail">
|
|
<Crumbs current="Contact Us" />
|
|
<p className="eyebrow">START A CONVERSATION</p>
|
|
<h1>Tell us about your project.</h1>
|
|
<p className="lead">
|
|
Share your requirements and our team will respond with practical next
|
|
steps.
|
|
</p>
|
|
<InquiryForm scene="CONTACT" />
|
|
</article>
|
|
);
|
|
return <ConfiguredPage slug={slug} />;
|
|
}
|
|
function ConfiguredPage({ slug }: { slug: string }) {
|
|
const [data, setData] = useState<any>();
|
|
const [error, setError] = useState("");
|
|
useEffect(() => {
|
|
post("/pages/detail", { slug })
|
|
.then(setData)
|
|
.catch((e) => setError(e.message));
|
|
}, [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 configured-page${agreementPage ? " legal-page" : ""}`}>
|
|
<Crumbs current={data.pageName} />
|
|
<p className="eyebrow">{agreementPage ? "LEGAL INFORMATION" : "COMPANY INFORMATION"}</p>
|
|
<h1>{data.pageName}</h1>
|
|
{data.summary && <p className="lead">{data.summary}</p>}
|
|
<div
|
|
className="content"
|
|
dangerouslySetInnerHTML={{ __html: normalizeRichTextHtml(data.content) }}
|
|
/>
|
|
</article>
|
|
);
|
|
}
|
|
function InquiryForm({
|
|
scene,
|
|
sourceCode,
|
|
}: {
|
|
scene: "PRODUCT" | "CONTACT" | "GENERAL";
|
|
sourceCode?: string;
|
|
}) {
|
|
const [definition, setDefinition] = useState<InquiryFormData>();
|
|
const [form, setForm] = useState({
|
|
name: "",
|
|
email: "",
|
|
phone: "",
|
|
company: "",
|
|
countryCode: "",
|
|
message: "",
|
|
privacyConsent: false,
|
|
website: "",
|
|
});
|
|
const [custom, setCustom] = useState<Record<string, string>>({});
|
|
const [busy, setBusy] = useState(false);
|
|
const [uploadingField, setUploadingField] = useState("");
|
|
const [notice, setNotice] = useState("");
|
|
useEffect(() => {
|
|
post("/inquiries/form-detail", { scene })
|
|
.then(setDefinition)
|
|
.catch((e) => setNotice(e.message));
|
|
}, [scene]);
|
|
const uploadImage = async (fieldCode: string, file?: File) => {
|
|
if (!file) return;
|
|
try {
|
|
setUploadingField(fieldCode);
|
|
setNotice("");
|
|
const body = new FormData();
|
|
body.append("file", file);
|
|
const response = await fetch(`${API}/inquiries/upload-image`, { method: "POST", body });
|
|
if (!response.ok) throw new Error((await response.json()).message || "Unable to upload image");
|
|
const result = await response.json();
|
|
setCustom((values) => ({ ...values, [fieldCode]: result.url }));
|
|
} catch (error) {
|
|
setNotice(error instanceof Error ? error.message : "Unable to upload image");
|
|
} finally {
|
|
setUploadingField("");
|
|
}
|
|
};
|
|
const submit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (!definition) return;
|
|
try {
|
|
setBusy(true);
|
|
setNotice("");
|
|
const configuredValue = (...keys: string[]) => {
|
|
const field = definition.fields.find((item) => keys.includes(item.fieldKey));
|
|
return field ? custom[field.fieldCode] || "" : "";
|
|
};
|
|
const result = await post("/inquiries/submit", {
|
|
formCode: definition.formCode,
|
|
sourceType: scene,
|
|
sourceCode,
|
|
sourceUrl: location.href,
|
|
...form,
|
|
name: configuredValue("name", "customer_name"),
|
|
email: configuredValue("email", "customer_email"),
|
|
phone: configuredValue("phone", "customer_phone"),
|
|
company: configuredValue("company", "company_name"),
|
|
countryCode: configuredValue("country_code", "country"),
|
|
message: configuredValue("message", "requirements"),
|
|
fieldValues: definition.fields.map((x) => ({
|
|
fieldCode: x.fieldCode,
|
|
value: custom[x.fieldCode] || "",
|
|
})),
|
|
landingUrl: sessionStorage.getItem("landingUrl") || location.href,
|
|
});
|
|
trackInquirySubmitted(result.inquiryCode, scene);
|
|
setNotice(result.successMessage);
|
|
} catch (err) {
|
|
setNotice(
|
|
err instanceof Error ? err.message : "Unable to submit inquiry",
|
|
);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
if (!definition)
|
|
return (
|
|
<section className="inquiry-box">
|
|
<h2>Request information</h2>
|
|
<p>{notice || "Loading inquiry form…"}</p>
|
|
</section>
|
|
);
|
|
return (
|
|
<section className="inquiry-box">
|
|
<p className="eyebrow">REQUEST INFORMATION</p>
|
|
<h2>Discuss your requirements</h2>
|
|
{definition.description && <p>{definition.description}</p>}
|
|
<form onSubmit={submit}>
|
|
{definition.fields.map((field) => (
|
|
<label
|
|
className={field.widthType === "FULL" ? "wide" : ""}
|
|
key={field.fieldCode}
|
|
>
|
|
<span>
|
|
{field.label}
|
|
{field.required ? " *" : ""}
|
|
</span>
|
|
{field.fieldType === "IMAGE" ? (
|
|
<div className="inquiry-image-field">
|
|
<input
|
|
type="file"
|
|
accept="image/jpeg,image/png,image/webp,image/gif"
|
|
required={field.required && !custom[field.fieldCode]}
|
|
onChange={(event) => void uploadImage(field.fieldCode, event.target.files?.[0])}
|
|
/>
|
|
{uploadingField === field.fieldCode && <small>Uploading…</small>}
|
|
{custom[field.fieldCode] && (
|
|
<img src={assetUrl(custom[field.fieldCode])} alt={field.label}/>
|
|
)}
|
|
</div>
|
|
) : field.fieldType === "TEXTAREA" ? (
|
|
<textarea
|
|
required={field.required}
|
|
maxLength={field.maxLength}
|
|
placeholder={field.placeholder}
|
|
value={custom[field.fieldCode] || ""}
|
|
onChange={(e) =>
|
|
setCustom({ ...custom, [field.fieldCode]: e.target.value })
|
|
}
|
|
/>
|
|
) : (
|
|
<input
|
|
type={field.fieldType === "EMAIL" ? "email" : field.fieldType === "PHONE" ? "tel" : field.fieldType === "NUMBER" ? "number" : "text"}
|
|
required={field.required}
|
|
maxLength={field.maxLength}
|
|
placeholder={field.placeholder}
|
|
value={custom[field.fieldCode] || ""}
|
|
onChange={(e) =>
|
|
setCustom({ ...custom, [field.fieldCode]: e.target.value })
|
|
}
|
|
/>
|
|
)}
|
|
{field.helpText && <small>{field.helpText}</small>}
|
|
</label>
|
|
))}
|
|
<input
|
|
className="honeypot"
|
|
tabIndex={-1}
|
|
autoComplete="off"
|
|
value={form.website}
|
|
onChange={(e) => setForm({ ...form, website: e.target.value })}
|
|
/>
|
|
<label className="consent wide">
|
|
<input
|
|
type="checkbox"
|
|
required
|
|
checked={form.privacyConsent}
|
|
onChange={(e) =>
|
|
setForm({ ...form, privacyConsent: e.target.checked })
|
|
}
|
|
/>
|
|
<span>
|
|
I agree to the <a href="/privacy-policy">Privacy Policy</a> and
|
|
consent to the processing of my inquiry.
|
|
</span>
|
|
</label>
|
|
<div className="wide">
|
|
<button className="cta" disabled={busy}>
|
|
{busy ? "Submitting…" : definition.submitButtonText}
|
|
</button>
|
|
{notice && <p className="form-notice">{notice}</p>}
|
|
</div>
|
|
</form>
|
|
</section>
|
|
);
|
|
}
|
|
function Crumbs({ current }: { current: string }) {
|
|
return (
|
|
<div className="crumbs">
|
|
<a href="/">Home</a>
|
|
<ChevronRight size={14} />
|
|
<span>{current}</span>
|
|
</div>
|
|
);
|
|
}
|
|
function ErrorState({ message }: { message: string }) {
|
|
return (
|
|
<section className="error">
|
|
<span>CONTENT UNAVAILABLE</span>
|
|
<h1>We could not load this page.</h1>
|
|
<p>{message}</p>
|
|
<a href="/">Return home</a>
|
|
</section>
|
|
);
|
|
}
|
|
function Footer() {
|
|
return (
|
|
<footer>
|
|
<div>
|
|
<b>SHOPLIX</b>
|
|
<p>Industrial products and expertise for global B2B projects.</p>
|
|
</div>
|
|
<div>
|
|
<h3>Company</h3>
|
|
<a href="/about-us">About Us</a>
|
|
<a href="/contact-us">Contact</a>
|
|
</div>
|
|
<div>
|
|
<h3>Legal</h3>
|
|
<a href="/privacy-policy">Privacy Policy</a>
|
|
<a href="/cookie-policy">Cookie Policy</a>
|
|
<a href="/terms-of-service">Terms of Service</a>
|
|
</div>
|
|
<small>© 2026 Shoplix. All rights reserved.</small>
|
|
</footer>
|
|
);
|
|
}
|
|
createRoot(document.getElementById("root")!).render(
|
|
<React.StrictMode>
|
|
<App />
|
|
<SocialFloatingBar />
|
|
</React.StrictMode>,
|
|
);
|