账户登录

This commit is contained in:
张锐 committed 2026-11-22 12:49:09 +08:00
1 parent f08dcee83a
commit 8e80e26c91
57 files changed
+1401 -100

No files matched your search

+8 -1
View File
@@ -10,7 +10,8 @@
"dependencies": {
"lucide-react": "0.468.0",
"react": "19.2.0",
"react-dom": "19.2.0"
"react-dom": "19.2.0",
"sa-sdk-javascript": "1.28.2"
},
"devDependencies": {
"@types/react": "19.0.3",
@@ -1109,6 +1110,12 @@
"fsevents": "~2.3.2"
}
},
"node_modules/sa-sdk-javascript": {
"version": "1.28.2",
"resolved": "https://registry.npmjs.org/sa-sdk-javascript/-/sa-sdk-javascript-1.28.2.tgz",
"integrity": "sha512-uPMdaYqaZ4B3VapZnIeR1hBhbyTgG2DgPLojQ2PSoc5o35e/AQDhE2cKEAnO22KX2Zzm7MrkCCrGg0iNfM3D+g==",
"license": "Apache-2.0"
},
"node_modules/scheduler": {
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
+1 -1
View File
@@ -1 +1 @@
{"name":"shoplix-web-site","private":true,"version":"0.1.0","type":"module","scripts":{"dev":"vite","build":"tsc -b && vite build"},"dependencies":{"react":"19.2.0","react-dom":"19.2.0","lucide-react":"0.468.0"},"devDependencies":{"@types/react":"19.0.3","@types/react-dom":"19.0.2","typescript":"5.7.3","vite":"6.4.6"}}
{"name":"shoplix-web-site","private":true,"version":"0.1.0","type":"module","scripts":{"dev":"vite","build":"tsc -b && vite build"},"dependencies":{"lucide-react":"0.468.0","react":"19.2.0","react-dom":"19.2.0","sa-sdk-javascript":"1.28.2"},"devDependencies":{"@types/react":"19.0.3","@types/react-dom":"19.0.2","typescript":"5.7.3","vite":"6.4.6"}}
+164
View File
@@ -0,0 +1,164 @@
import sensors from "sa-sdk-javascript";
const API_BASE = import.meta.env.VITE_SITE_API_BASE || "/api/site/v1";
const SESSION_TIMEOUT = 30 * 60 * 1000;
const VISITOR_KEY = "shoplix_analytics_visitor";
const SESSION_KEY = "shoplix_analytics_session";
const SESSION_TIME_KEY = "shoplix_analytics_session_time";
const LANDING_KEY = "shoplix_analytics_landing";
type EventProperties = Record<string, string | number | boolean | undefined>;
/** 页面访问上下文。 */
export type PageAnalyticsContext = {
pageCode: string;
pageName: string;
targetCode?: string;
scene?: string;
};
let initialized = false;
let pageStartTime = Date.now();
/** 初始化神策Web SDK并将数据发送到项目自建接收端。 */
export function initializeAnalytics(): void {
if (initialized) return;
initialized = true;
const visitor = ensureVisitor();
const session = ensureSession();
sensors.init({
server_url: new URL(`${API_BASE}/analytics/beacon-report-flow`, location.origin).href,
send_type: "ajax",
batch_send: false,
show_log: import.meta.env.DEV,
is_track_single_page: false,
use_client_time: true,
});
sensors.identify(visitor.code, true);
sensors.registerPage({
language: document.documentElement.lang || "en",
session_id: session.code,
is_new_visitor: visitor.isNew ? 1 : 0,
is_session_first: session.isFirst ? 1 : 0,
landing_domain: landing().host,
landing_url: landing().href,
landing_url_body: landing().pathname,
});
}
/** 上报页面访问事件。 */
export function trackPageView(context: PageAnalyticsContext): void {
initializeAnalytics();
pageStartTime = Date.now();
sensors.track("PageView", commonProperties(context));
markSessionVisited();
}
/** 上报页面离开事件及停留时长。 */
export function trackPageLeave(context: PageAnalyticsContext): void {
const now = Date.now();
sensors.track("PageLeave", {
...commonProperties(context),
start_time: pageStartTime,
duration: Math.max(0, Math.round((now - pageStartTime) / 1000)),
});
}
/** 上报询盘提交成功事件。 */
export function trackInquirySubmitted(inquiryCode: string, scene: string): void {
sensors.track("SubmitInquiry", {
...commonProperties({ pageCode: routePageCode(), pageName: document.title, scene }),
event_detail: inquiryCode,
});
}
/** 上报通用点击事件。 */
export function trackClick(detail: string, properties: EventProperties = {}): void {
sensors.track("Click", { ...commonProperties({ pageCode: routePageCode(), pageName: document.title }), event_detail: detail, ...properties });
}
/** 创建当前页面公共属性。 */
function commonProperties(context: PageAnalyticsContext): EventProperties {
const url = new URL(location.href);
const connection = (navigator as Navigator & { connection?: { effectiveType?: string } }).connection;
return {
page_code: context.pageCode,
page_name: context.pageName,
target_code: context.targetCode,
scene: context.scene,
start_time: pageStartTime,
pixel_ratio: String(window.devicePixelRatio || 1),
domain: url.host,
url_args: url.search,
win_height: window.innerHeight,
win_width: window.innerWidth,
network: connection?.effectiveType,
utm_source: url.searchParams.get("utm_source") || undefined,
utm_campaign: url.searchParams.get("utm_campaign") || undefined,
utm_adgroup: url.searchParams.get("utm_adgroup") || undefined,
flow_channel: flowChannel(document.referrer),
social_media_channel: socialChannel(document.referrer),
};
}
/** 获取或创建匿名访客。 */
function ensureVisitor(): { code: string; isNew: boolean } {
const existing = localStorage.getItem(VISITOR_KEY);
if (existing) return { code: existing, isNew: false };
const code = crypto.randomUUID();
localStorage.setItem(VISITOR_KEY, code);
return { code, isNew: true };
}
/** 获取或创建三十分钟有效的会话。 */
function ensureSession(): { code: string; isFirst: boolean } {
const now = Date.now();
const previousTime = Number(sessionStorage.getItem(SESSION_TIME_KEY) || 0);
let code = sessionStorage.getItem(SESSION_KEY);
let isFirst = sessionStorage.getItem(`${SESSION_KEY}_visited`) !== "1";
if (!code || now - previousTime > SESSION_TIMEOUT) {
code = crypto.randomUUID();
sessionStorage.setItem(SESSION_KEY, code);
sessionStorage.removeItem(`${SESSION_KEY}_visited`);
isFirst = true;
}
sessionStorage.setItem(SESSION_TIME_KEY, String(now));
return { code, isFirst };
}
/** 标记当前会话已产生页面访问。 */
function markSessionVisited(): void {
sessionStorage.setItem(`${SESSION_KEY}_visited`, "1");
sessionStorage.setItem(SESSION_TIME_KEY, String(Date.now()));
}
/** 获取首次落地页。 */
function landing(): URL {
const stored = sessionStorage.getItem(LANDING_KEY);
if (stored) return new URL(stored);
sessionStorage.setItem(LANDING_KEY, location.href);
return new URL(location.href);
}
/** 判断流量渠道。 */
function flowChannel(referrer: string): string {
if (!referrer) return "DIRECT";
const host = new URL(referrer).hostname.toLowerCase();
if (/google|bing|yahoo|baidu|yandex/.test(host)) return "ORGANIC_SEARCH";
if (/facebook|instagram|linkedin|twitter|x\.com|youtube|tiktok/.test(host)) return "SOCIAL";
return "REFERRAL";
}
/** 判断社媒来源。 */
function socialChannel(referrer: string): string | undefined {
const match = referrer.toLowerCase().match(/facebook|instagram|linkedin|twitter|youtube|tiktok/);
return match?.[0];
}
/** 根据当前路径识别页面类型。 */
export function routePageCode(): string {
const paths = location.pathname.split("/").filter(Boolean);
if (!paths.length) return "HOME";
const mapping: Record<string, string> = { products: "PRODUCT", news: "NEWS", cases: "CASE", help: "HELP" };
return mapping[paths[0]] ? `${mapping[paths[0]]}_${paths[1] ? "DETAIL" : "CATEGORY"}` : "CUSTOM_PAGE";
}
+105 -9
View File
@@ -2,8 +2,9 @@ import React, { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { ArrowRight, ChevronRight, Mail, Menu, Search } from "lucide-react";
import "./styles.css";
import { initializeAnalytics, routePageCode, trackInquirySubmitted, trackPageLeave, trackPageView } from "./analytics";
const API = "http://localhost:8082/api/site/v1";
const API = import.meta.env.VITE_SITE_API_BASE || "/api/site/v1";
type ContentType = "NEWS" | "CASE" | "HELP";
type Item = {
productCode?: string;
@@ -13,7 +14,7 @@ type Item = {
slug: string;
summary?: string;
model?: string;
publishTime?: string;
publishTime?: number;
coverMediaUrl?: string;
};
type InquiryField = {
@@ -35,6 +36,17 @@ type InquiryFormData = {
successMessage: string;
fields: InquiryField[];
};
type SeoData = {
title: string;
description?: string;
keywords?: string;
canonicalUrl?: string;
robots?: string;
ogTitle?: string;
ogDescription?: string;
ogImageUrl?: string;
structuredData?: string;
};
async function post(path: string, body: unknown) {
const r = await fetch(API + path, {
method: "POST",
@@ -45,6 +57,53 @@ async function post(path: string, body: unknown) {
throw new Error((await r.json()).message || "Unable to load content");
return r.json();
}
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 = [
["Products", "/products"],
["Cases", "/cases"],
@@ -62,13 +121,49 @@ function route() {
}
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 />;
if (r.kind === "home") return <>{runtime}<DecoratedPage pageType={r.previewPage || "HOME"} fallback={<><Header /><main><Home /></main><Footer /></>} /></>;
if (r.kind === "products") return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug ? "PRODUCT_DETAIL" : "PRODUCT_CATEGORY")} fallback={<><Header /><main><Collection title="Products" type="products" slug={r.slug} /></main><Footer /></>} /></>;
if (r.kind === "news") return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug ? "NEWS_DETAIL" : "NEWS_CATEGORY")} fallback={<><Header /><main><Collection title="News" type="NEWS" slug={r.slug} /></main><Footer /></>} /></>;
if (r.kind === "cases") return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug ? "CASE_DETAIL" : "CASE_CATEGORY")} fallback={<><Header /><main><Collection title="Case Studies" type="CASE" slug={r.slug} /></main><Footer /></>} /></>;
if (r.kind === "help") return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug ? "HELP_DETAIL" : "HELP_CATEGORY")} fallback={<><Header /><main><Collection title="Help Center" type="HELP" slug={r.slug} /></main><Footer /></>} /></>;
return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug === "about-us" ? "ABOUT_US" : "CUSTOM_PAGE")} fallback={<><Header /><main><Page slug={r.slug!} /></main><Footer /></>} /></>;
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} /></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} /></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} /></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} /></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()); }, []);
@@ -281,7 +376,7 @@ function Collection({
</div>
<div>
<small>
{item.model || item.publishTime?.slice(0, 10) || "INSIGHT"}
{item.model || (item.publishTime ? new Date(item.publishTime).toLocaleDateString("en-CA") : "INSIGHT")}
</small>
<h2>{item.productName || item.title}</h2>
<p>
@@ -398,6 +493,7 @@ function InquiryForm({
})),
landingUrl: sessionStorage.getItem("landingUrl") || location.href,
});
trackInquirySubmitted(result.inquiryCode, scene);
setNotice(result.successMessage);
} catch (err) {
setNotice(
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/main.tsx","./src/vite-env.d.ts"],"version":"5.7.3"}
{"root":["./src/analytics.ts","./src/main.tsx","./src/vite-env.d.ts"],"version":"5.7.3"}