sync from mock: motion, privacy-first search stats, auto-update UX
- frontend/src/lib/ui/motion.ts + components/MotionBoot.tsx: page-enter and scroll reveal per pathname change (ported from mock motion.js); IntersectionObserver plus sweep fallback for jump-scroll/hidden tabs, maps never transformed - frontend/src/lib/ui/analytics.ts: cookie-less local-first search analytics (localStorage at_stats_v1, DNT/GPC + opt-out, term sanitiser, 900ms debounce, caps 300 terms / 200 views / 120 days); optional Umami endpoint via AT_ANALYTICS - /stats page (StatsView + styles/pages/stats.css): KPIs, 14-day chart, top terms, top route/stop pages, no-result terms, JSON export, clear, opt-out - hooks: stops search apply(), stop detail route filter - remove footer visitor counter (lib/ui/visitors.ts, .mu-visitor/.mu-vreset, i18n keys) - remove floating install-app button; PwaBoot keeps SW + guarded version toast (sessionStorage guard, silent reload when tab hidden) - i18n th/en: nav.stats, update.applying, stats.* (public + src/data locales) - version.json + sw VERSION -> 2026.10.24.3; docs/UI-PORT.md section for this round
This commit is contained in:
1 parent
c0b70ff845
commit
4b5a4d33d3
22 files changed
+1473
-453
No files matched your search
@@ -0,0 +1,342 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* StatsView — หน้าสถิติในเครื่อง (ported from web-at-transit-mock #/stats)
|
||||
*
|
||||
* อ่านข้อมูลจาก window.Analytics (lib/ui/analytics.ts) อย่างเดียว
|
||||
* ไม่ยิงเน็ต · ไม่มีคุกกี้ · ตัวเลขเป็นของเบราว์เซอร์นี้เท่านั้น
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { ensureRuntime } from "@/lib/runtime";
|
||||
import "@/styles/pages/stats.css";
|
||||
|
||||
type Row = { term?: string; kind?: string; id?: string; count: number; last: number };
|
||||
type Report = {
|
||||
since: number;
|
||||
totals: { pageviews: number; searches: number; noResult: number; terms: number; views: number };
|
||||
days: { date: string; pageviews: number; searches: number; noResult: number }[];
|
||||
topTerms: Row[];
|
||||
topEmpty: Row[];
|
||||
topViews: Row[];
|
||||
};
|
||||
|
||||
type AnalyticsApi = {
|
||||
report: () => Report;
|
||||
exportJSON: () => string;
|
||||
clear: () => void;
|
||||
optOut: (on: boolean) => void;
|
||||
tracking: () => boolean;
|
||||
};
|
||||
|
||||
const EMPTY: Report = {
|
||||
since: 0,
|
||||
totals: { pageviews: 0, searches: 0, noResult: 0, terms: 0, views: 0 },
|
||||
days: [],
|
||||
topTerms: [],
|
||||
topEmpty: [],
|
||||
topViews: [],
|
||||
};
|
||||
|
||||
/* ข้อความไทย = fallback ถ้า I18N ยังไม่โหลด · คีย์จริงอยู่ใน locales */
|
||||
const FALLBACK: Record<string, string> = {
|
||||
"stats.title": "สถิติการค้นหาในเครื่องนี้",
|
||||
"stats.lead":
|
||||
"เก็บเฉพาะจำนวนครั้งและคำที่ค้น — ไม่มีคุกกี้ ไม่มีรหัสผู้ใช้ ไม่เก็บ IP และไม่ส่งออกนอกเครื่อง",
|
||||
"stats.kpi.views": "ครั้งที่เปิดหน้า",
|
||||
"stats.kpi.searches": "ครั้งที่ค้นหา",
|
||||
"stats.kpi.terms": "คำค้นต่างกัน",
|
||||
"stats.kpi.noResult": "ค้นแล้วไม่พบ",
|
||||
"stats.chart.title": "14 วันล่าสุด",
|
||||
"stats.chart.lead": "แท่งเข้ม = เปิดหน้า · แท่งอ่อน = ค้นหา",
|
||||
"stats.terms.title": "คำที่ค้นมากที่สุด",
|
||||
"stats.terms.lead": "คำถูกทำให้ปลอดภัยแล้ว — ตัดอีเมล เบอร์โทร และเลขยาวออกก่อนบันทึก",
|
||||
"stats.terms.empty": "ยังไม่มีคำค้นในเครื่องนี้ — ลองค้นหาป้ายที่หน้า “ป้ายหยุดรถ” แล้วกลับมาดู",
|
||||
"stats.views.title": "หน้าที่ถูกเปิดบ่อย",
|
||||
"stats.views.lead": "นับเฉพาะรายละเอียดสายรถและรายละเอียดป้าย (ไม่ผูกกับผู้ใช้)",
|
||||
"stats.views.empty": "ยังไม่มีข้อมูล — เปิดรายละเอียดสายหรือป้ายสักครั้ง",
|
||||
"stats.noresult.title": "ค้นแล้วไม่พบ",
|
||||
"stats.noresult.lead": "สัญญาณว่าข้อมูลยังขาด — คำเหล่านี้ควรมีในระบบถ้าเป็นเส้นทางจริง",
|
||||
"stats.privacy.title": "ความเป็นส่วนตัว",
|
||||
"stats.privacy.collect":
|
||||
"เก็บ: จำนวนเปิดหน้า · คำที่ค้น (ตัดข้อมูลส่วนตัวออก) · จำนวนครั้งที่ค้นไม่พบ · เวลาล่าสุด",
|
||||
"stats.privacy.reject":
|
||||
"ไม่เก็บ: IP · User-Agent · ตำแหน่ง · คุกกี้ · รหัสเครื่อง · ประวัติข้ามเว็บ",
|
||||
"stats.privacy.local": "ข้อมูลอยู่ใน localStorage ของเบราว์เซอร์นี้เท่านั้น — ล้างได้ทุกเมื่อ",
|
||||
"stats.privacy.optoutTitle": "ปิดการเก็บสถิติในเครื่องนี้",
|
||||
"stats.privacy.optoutLead":
|
||||
"เปิดสวิตช์นี้ = หยุดบันทึกทันที (ยังดูตัวเลขเดิมได้) · ระบบเคารพ Do Not Track / GPC อยู่แล้ว",
|
||||
"stats.privacy.off": "ปิดการเก็บสถิติแล้ว — ไม่มีการบันทึกใหม่",
|
||||
"stats.privacy.on": "เปิดการเก็บสถิติแล้ว",
|
||||
"stats.btn.export": "ดาวน์โหลดข้อมูล (JSON)",
|
||||
"stats.btn.clear": "ล้างข้อมูลในเครื่อง",
|
||||
"stats.clear.confirm": "ล้างสถิติทั้งหมดในเครื่องนี้? การลบย้อนกลับไม่ได้",
|
||||
"stats.clear.done": "ล้างข้อมูลเรียบร้อย",
|
||||
"stats.export.done": "ดาวน์โหลดไฟล์แล้ว",
|
||||
"stats.since": "เริ่มเก็บเมื่อ",
|
||||
"stats.col.term": "คำค้น",
|
||||
"stats.col.count": "ครั้ง",
|
||||
"stats.col.last": "ล่าสุด",
|
||||
"stats.col.target": "หน้า",
|
||||
"stats.views.stopPrefix": "ป้าย {code}",
|
||||
"stats.views.routePrefix": "สาย {n}",
|
||||
};
|
||||
|
||||
function tr(key: string, vars?: Record<string, string | number>) {
|
||||
let out = FALLBACK[key] || key;
|
||||
if (typeof window !== "undefined") {
|
||||
const w = window as unknown as {
|
||||
I18N?: { t?: (k: string, v?: Record<string, string | number>) => string };
|
||||
};
|
||||
const got = w.I18N?.t?.(key, vars);
|
||||
if (got && got !== key) out = got;
|
||||
}
|
||||
if (vars) {
|
||||
Object.keys(vars).forEach((k) => {
|
||||
out = out.replace(new RegExp(`\\{${k}\\}`, "g"), String(vars[k]));
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
function when(ts: number) {
|
||||
if (!ts) return "—";
|
||||
const d = new Date(ts);
|
||||
const now = new Date();
|
||||
const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
return d.toDateString() === now.toDateString()
|
||||
? hm
|
||||
: `${pad(d.getDate())}/${pad(d.getMonth() + 1)} ${hm}`;
|
||||
}
|
||||
|
||||
const num = (n: number) => {
|
||||
try { return Number(n || 0).toLocaleString("th-TH"); } catch { return String(n || 0); }
|
||||
};
|
||||
|
||||
const short = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
||||
|
||||
export default function StatsView() {
|
||||
const [report, setReport] = useState<Report>(EMPTY);
|
||||
const [tracking, setTracking] = useState(true);
|
||||
const [status, setStatus] = useState("");
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
const api = useCallback((): AnalyticsApi | undefined => {
|
||||
return (window as unknown as { Analytics?: AnalyticsApi }).Analytics;
|
||||
}, []);
|
||||
|
||||
const paint = useCallback(() => {
|
||||
const a = api();
|
||||
if (!a) return;
|
||||
setReport(a.report());
|
||||
setTracking(a.tracking());
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
await ensureRuntime();
|
||||
if (cancelled) return;
|
||||
paint();
|
||||
setReady(true);
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [paint]);
|
||||
|
||||
const onToggle = (on: boolean) => {
|
||||
api()?.optOut(on);
|
||||
setTracking(!on);
|
||||
setStatus(on ? tr("stats.privacy.off") : tr("stats.privacy.on"));
|
||||
};
|
||||
|
||||
const onExport = () => {
|
||||
const a = api();
|
||||
if (!a) return;
|
||||
const d = new Date();
|
||||
const name = `atroute-stats-${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}.json`;
|
||||
const url = URL.createObjectURL(new Blob([a.exportJSON()], { type: "application/json" }));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = name;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1500);
|
||||
setStatus(tr("stats.export.done"));
|
||||
};
|
||||
|
||||
const onClear = () => {
|
||||
if (!window.confirm(tr("stats.clear.confirm"))) return;
|
||||
api()?.clear();
|
||||
paint();
|
||||
setStatus(tr("stats.clear.done"));
|
||||
};
|
||||
|
||||
/* ---------- กราฟ 14 วัน (เติมวันขาดให้ครบ) ---------- */
|
||||
const byDate = new Map(report.days.map((d) => [d.date, d]));
|
||||
const today = new Date();
|
||||
today.setHours(12, 0, 0, 0);
|
||||
const series = Array.from({ length: 14 }, (_, i) => {
|
||||
const d = new Date(today.getTime() - (13 - i) * 86400000);
|
||||
const key = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
const hit = byDate.get(key);
|
||||
return { key, day: d.getDate(), pv: hit?.pageviews || 0, q: hit?.searches || 0 };
|
||||
});
|
||||
const max = Math.max(1, ...series.map((s) => Math.max(s.pv, s.q)));
|
||||
|
||||
return (
|
||||
<main className="mu-page">
|
||||
<div className="st-wrap">
|
||||
<div className="st-hero">
|
||||
<p className="mu-breadcrumb">
|
||||
<a href="/" data-i18n="nav.home">หน้าแรก</a>/ <span data-i18n="nav.stats">สถิติ</span>
|
||||
</p>
|
||||
<h1>{tr("stats.title")}</h1>
|
||||
<p>{tr("stats.lead")}</p>
|
||||
</div>
|
||||
|
||||
<section className="st-kpis" aria-label="summary">
|
||||
<div className="st-kpi"><b>{num(report.totals.pageviews)}</b><span>{tr("stats.kpi.views")}</span></div>
|
||||
<div className="st-kpi"><b>{num(report.totals.searches)}</b><span>{tr("stats.kpi.searches")}</span></div>
|
||||
<div className="st-kpi"><b>{num(report.totals.terms)}</b><span>{tr("stats.kpi.terms")}</span></div>
|
||||
<div className="st-kpi"><b>{num(report.totals.noResult)}</b><span>{tr("stats.kpi.noResult")}</span></div>
|
||||
</section>
|
||||
|
||||
<section className="st-card">
|
||||
<h2>{tr("stats.chart.title")}</h2>
|
||||
<p className="lead">{tr("stats.chart.lead")}</p>
|
||||
<div className="st-chart" role="img" aria-label={tr("stats.chart.title")}>
|
||||
{series.map((s, idx) => (
|
||||
<div className="st-bar" key={s.key} title={`${s.key} · ${num(s.pv)} / ${num(s.q)}`}>
|
||||
<i style={{ height: `${Math.round((s.pv / max) * 92)}px` }} />
|
||||
<u style={{ height: `${Math.round((s.q / max) * 92)}px` }} />
|
||||
<em style={series.length > 8 && idx % 2 === 1 ? { opacity: 0 } : undefined}>{s.day}</em>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="st-legend">
|
||||
<span><b style={{ background: "linear-gradient(180deg,#b694f6,var(--c-brand))" }} />{tr("stats.kpi.views")}</span>
|
||||
<span><b style={{ background: "var(--c-brand-soft)" }} />{tr("stats.kpi.searches")}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="st-grid2">
|
||||
<section className="st-card">
|
||||
<h2>{tr("stats.terms.title")}</h2>
|
||||
<p className="lead">{tr("stats.terms.lead")}</p>
|
||||
<table className="st-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{tr("stats.col.term")}</th>
|
||||
<th className="num">{tr("stats.col.count")}</th>
|
||||
<th>{tr("stats.col.last")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{report.topTerms.map((row) => (
|
||||
<tr key={row.term}>
|
||||
<td className="term" title={row.term}>{short(row.term || "", 42)}</td>
|
||||
<td className="num">{num(row.count)}</td>
|
||||
<td className="when">{when(row.last)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{!report.topTerms.length && <p className="st-empty">{tr("stats.terms.empty")}</p>}
|
||||
</section>
|
||||
|
||||
<section className="st-card">
|
||||
<h2>{tr("stats.views.title")}</h2>
|
||||
<p className="lead">{tr("stats.views.lead")}</p>
|
||||
<table className="st-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{tr("stats.col.target")}</th>
|
||||
<th className="num">{tr("stats.col.count")}</th>
|
||||
<th>{tr("stats.col.last")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{report.topViews.map((row) => (
|
||||
<tr key={`${row.kind}:${row.id}`}>
|
||||
<td>
|
||||
<a href={row.kind === "route" ? `/routes/${row.id}` : `/stops/${row.id}`}>
|
||||
{row.kind === "route"
|
||||
? tr("stats.views.routePrefix", { n: row.id || "" })
|
||||
: tr("stats.views.stopPrefix", { code: row.id || "" })}
|
||||
</a>
|
||||
</td>
|
||||
<td className="num">{num(row.count)}</td>
|
||||
<td className="when">{when(row.last)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{!report.topViews.length && <p className="st-empty">{tr("stats.views.empty")}</p>}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{report.topEmpty.length > 0 && (
|
||||
<section className="st-card">
|
||||
<h2>{tr("stats.noresult.title")}</h2>
|
||||
<p className="lead">{tr("stats.noresult.lead")}</p>
|
||||
<table className="st-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{tr("stats.col.term")}</th>
|
||||
<th className="num">{tr("stats.col.count")}</th>
|
||||
<th>{tr("stats.col.last")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{report.topEmpty.map((row) => (
|
||||
<tr key={row.term}>
|
||||
<td className="term" title={row.term}>{short(row.term || "", 42)}</td>
|
||||
<td className="num">{num(row.count)}</td>
|
||||
<td className="when">{when(row.last)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="st-card">
|
||||
<h2>{tr("stats.privacy.title")}</h2>
|
||||
<ul className="st-list">
|
||||
<li>{tr("stats.privacy.collect")}</li>
|
||||
<li>{tr("stats.privacy.reject")}</li>
|
||||
<li>{tr("stats.privacy.local")}</li>
|
||||
</ul>
|
||||
<label className="st-toggle" htmlFor="st-optout">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="st-optout"
|
||||
checked={!tracking}
|
||||
onChange={(e) => onToggle(e.target.checked)}
|
||||
disabled={!ready}
|
||||
/>
|
||||
<span>
|
||||
<strong>{tr("stats.privacy.optoutTitle")}</strong>
|
||||
<span>{tr("stats.privacy.optoutLead")}</span>
|
||||
</span>
|
||||
</label>
|
||||
<div className="st-actions">
|
||||
<button type="button" className="st-btn is-solid" onClick={onExport} disabled={!ready}>
|
||||
{tr("stats.btn.export")}
|
||||
</button>
|
||||
<button type="button" className="st-btn is-danger" onClick={onClear} disabled={!ready}>
|
||||
{tr("stats.btn.clear")}
|
||||
</button>
|
||||
</div>
|
||||
<p className="st-status" role="status" aria-live="polite">{status}</p>
|
||||
<p className="st-note">
|
||||
{tr("stats.since")}: {report.since ? new Date(report.since).toLocaleDateString("th-TH", { year: "numeric", month: "short", day: "numeric" }) : "—"}
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user