diff --git a/docs/UI-PORT.md b/docs/UI-PORT.md index f6c87fa..26b239c 100644 --- a/docs/UI-PORT.md +++ b/docs/UI-PORT.md @@ -84,7 +84,21 @@ npm run dev # http://localhost:3000 ``` - เปิดทุก route: `/`, `/stops`, `/stops/:code`, `/routes`, `/routes/:id`, `/check`, - `/check/:id`, `/blog`, `/blog/:id`, `/about`, `/credits` + `/check/:id`, `/blog`, `/blog/:id`, `/about`, `/credits`, `/stats` - เทียบภาพกับ mock ที่ viewport เดียวกัน (1280×900) — diff ที่วัดได้ 0.7–2.3% (ที่เหลือมาจาก marquee animation / ตัวเลขผู้เข้าชม) - ตรวจว่าไม่มี horizontal scroll และปุ่ม/ลิงก์กดได้จริง + +## รอบล่าสุด — motion, สถิติ, auto-update (พอร์ตจาก mock) + +| ของใน mock | ใน repo นี้ | หมายเหตุ | +|---|---|---| +| `ui/motion.js` (enter · reveal · loading bar) | `src/lib/ui/motion.ts` + `components/MotionBoot.tsx` + CSS ใน `src/styles/_shared.css` | MotionBoot เรียก `Motion.enter(#view)` ทุกครั้งที่ pathname เปลี่ยน (แทน router เดิม) · reveal ใช้ `IntersectionObserver` + sweep (กันค้างตอนกระโดดข้ามหน้า/แท็บถูกซ่อน) | +| `ui/analytics.js` + `#/stats` | `src/lib/ui/analytics.ts` + `app/stats/page.tsx` + `components/views/StatsView.tsx` + `styles/pages/stats.css` | เก็บใน localStorage `at_stats_v1` · ไม่มีคุกกี้/IP/UA · `cleanTerm()` ตัดอีเมล/เบอร์/เลขยาว · debounce 900ms · opt-out + DNT/GPC · ค่าเริ่มต้นไม่ส่งออกเน็ต (จะส่งก็ต่อเมื่อตั้ง `window.AT_ANALYTICS = {endpoint, siteId}`) | +| ปุ่มติดตั้งแอปลอยมุมขวาล่าง | **เอาออก** — `PwaBoot` เหลือ SW + version check | Chrome/Edge ยังมีไอคอนติดตั้งของเบราว์เซอร์เอง | +| ตัวเลขผู้เข้าชม 12,834 ใน footer | **เอาออก** — ลบ `lib/ui/visitors.ts` + CSS `.mu-visitor/.mu-vreset` + คีย์ `visitors.*` | backend มี `/api/visits` (record_visit/visits_summary) แต่ frontend ยังไม่เรียก — ถ้าจะทำสถิติรวมศูนย์ ให้ต่อที่ `lib/api.ts` | +| bump + `version.json` + toast อัปเดต | `PwaBoot` เทียบ `/version.json` กับ `` (อ่านตอน build) → toast + reload ครั้งเดียว/เวอร์ชัน | ต้อง bump `public/version.json` + `public/sw.js` VERSION แล้ว rebuild | + +**ยังไม่พอร์ต (ตั้งใจ):** หน้ารวมศูนย์สถิติจาก backend — backend มีตาราง `visit_daily_stats` +และ API `/visits/summary` แล้ว แต่ยังไม่มี UI/การเรียก; ถ้าจะทำต้องตัดสินใจเรื่อง visitor id +เชิงความเป็นส่วนตัวก่อน (mock ใช้ local-only เพื่อไม่ต้องมี id ถาวร) diff --git a/frontend/public/locales/en.json b/frontend/public/locales/en.json index 60893e8..9bb4623 100644 --- a/frontend/public/locales/en.json +++ b/frontend/public/locales/en.json @@ -131,10 +131,10 @@ "stops.noOffset": "No travel time from the first stop yet", "stops.noBusLine": "No bus line listed", "stops.modeCode": "Search by stop code", - "stops.modeNear": "Near me", + "stops.modeNear": "Near me", "stops.nearCta": "Use my location", "stops.nearHint": "We ask your device for a location, then rank stops by real distance from their coordinates.", -"stops.modePlace": "Search by place name", + "stops.modePlace": "Search by place name", "stops.codePh": "3+000", "stops.codeHint": "Type 4 digits and the + sign is added automatically (e.g. 3000 → 3+000)", "stops.codeHintBox": "Type digits in the boxes — empty boxes are filled with 0 automatically. For 4-digit codes such as 8+591, enter 08+591", @@ -267,5 +267,43 @@ "check.noMoreToday": "No departures left today", "check.stopsCount": "stops", "check.toStopDetail": "View stop detail", - "common.routes": "routes" + "common.routes": "routes", + "nav.stats": "Stats", + "update.applying": "New version — updating…", + "stats.title": "Search statistics on this device", + "stats.lead": "Only counts and search terms are kept — no cookies, no user id, no IP, and nothing leaves this device", + "stats.kpi.views": "Page views", + "stats.kpi.searches": "Searches", + "stats.kpi.terms": "Unique terms", + "stats.kpi.noResult": "No results", + "stats.chart.title": "Last 14 days", + "stats.chart.lead": "Solid bar = page views · light bar = searches", + "stats.terms.title": "Top search terms", + "stats.terms.lead": "Terms are sanitised — emails, phone numbers and long digit runs are stripped before saving", + "stats.terms.empty": "No searches on this device yet — try the stop search page, then come back", + "stats.views.title": "Most opened pages", + "stats.views.lead": "Counts route and stop detail pages only (not tied to any user)", + "stats.views.empty": "No data yet — open a route or stop detail once", + "stats.views.stopPrefix": "Stop {code}", + "stats.views.routePrefix": "Route {n}", + "stats.noresult.title": "Searched, nothing found", + "stats.noresult.lead": "A signal that data is missing — these terms should exist if they are real routes", + "stats.privacy.title": "Privacy", + "stats.privacy.collect": "Stored: page-view counts · sanitised search terms · no-result counts · last-used time", + "stats.privacy.reject": "Not stored: IP · User-Agent · location · cookies · device id · cross-site history", + "stats.privacy.local": "Data lives in this browser's localStorage only — clear it anytime", + "stats.privacy.optoutTitle": "Turn off stats on this device", + "stats.privacy.optoutLead": "Switching this on stops recording immediately (existing numbers stay visible). Do Not Track / GPC are respected anyway.", + "stats.privacy.off": "Stats turned off — nothing new is recorded", + "stats.privacy.on": "Stats turned on", + "stats.btn.export": "Download data (JSON)", + "stats.btn.clear": "Clear data on this device", + "stats.clear.confirm": "Clear all stats on this device? This cannot be undone.", + "stats.clear.done": "Data cleared", + "stats.export.done": "File downloaded", + "stats.since": "Collecting since", + "stats.col.term": "Term", + "stats.col.count": "Hits", + "stats.col.last": "Last", + "stats.col.target": "Page" } diff --git a/frontend/public/locales/th.json b/frontend/public/locales/th.json index 70f825d..5eded9b 100644 --- a/frontend/public/locales/th.json +++ b/frontend/public/locales/th.json @@ -131,10 +131,10 @@ "stops.noOffset": "ยังไม่ระบุเวลาเดินทางจากจุดแรก", "stops.noBusLine": "ยังไม่ระบุสายรถ", "stops.modeCode": "ค้นหาด้วยรหัสป้าย", - "stops.modeNear": "ป้ายใกล้ฉัน", + "stops.modeNear": "ป้ายใกล้ฉัน", "stops.nearCta": "ขอพิกัดและหาป้ายใกล้ฉัน", "stops.nearHint": "ระบบจะขอตำแหน่งจากเครื่อง แล้วคำนวณระยะจากพิกัดป้าย/ศาลารถ เรียงจากใกล้ไปไกล", -"stops.modePlace": "ค้นหาด้วยชื่อสถานที่", + "stops.modePlace": "ค้นหาด้วยชื่อสถานที่", "stops.codePh": "3+000", "stops.codeHint": "พิมพ์ตัวเลข 4 หลัก ระบบจะเติมเครื่องหมาย + ให้อัตโนมัติ (เช่น 3000 → 3+000)", "stops.codeHintBox": "พิมพ์ตัวเลขในช่อง ระบบจะเติม 0 ให้อัตโนมัติเมื่อเว้นว่าง และถ้าเจอรหัส 4 หลัก เช่น 8+591 ให้กรอก 08+591", @@ -267,5 +267,43 @@ "check.noMoreToday": "ไม่มีรถเหลือในวันนี้แล้ว", "check.stopsCount": "จุดจอด", "check.toStopDetail": "ไปหน้ารายละเอียดจุดจอด", - "common.routes": "เส้นทาง" + "common.routes": "เส้นทาง", + "nav.stats": "สถิติ", + "update.applying": "มีเวอร์ชันใหม่ — กำลังอัปเดต…", + "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.views.stopPrefix": "ป้าย {code}", + "stats.views.routePrefix": "สาย {n}", + "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": "หน้า" } diff --git a/frontend/public/sw.js b/frontend/public/sw.js index edbffc3..69440b6 100644 --- a/frontend/public/sw.js +++ b/frontend/public/sw.js @@ -15,7 +15,7 @@ - SW ใหม่ → skipWaiting + clients.claim + แจ้งหน้าเว็บ ============================================================ */ -const VERSION = "2026.10.24.2"; /* bump เมื่อแก้ UI เพื่อบังคับให้ cache เก่าถูกทิ้ง */ +const VERSION = "2026.10.24.3"; /* bump เมื่อแก้ UI เพื่อบังคับให้ cache เก่าถูกทิ้ง */ const CACHE = `atroute-${VERSION}`; const OFFLINE_URL = "/offline.html"; const VERSION_URL = "/version.json"; diff --git a/frontend/public/version.json b/frontend/public/version.json index 88f3c99..358417e 100644 --- a/frontend/public/version.json +++ b/frontend/public/version.json @@ -1,6 +1,6 @@ { "app": "Atroute", - "version": "2026.10.24.2", - "builtAt": "2026-10-24T00:33:20", + "version": "2026.10.24.3", + "builtAt": "2026-11-04T00:51:02", "pwa": true } diff --git a/frontend/src/app/layout.tsx b/frontend/src/app/layout.tsx index b1118c6..f65e9e2 100644 --- a/frontend/src/app/layout.tsx +++ b/frontend/src/app/layout.tsx @@ -18,6 +18,7 @@ const APP_VERSION = readAppVersion(); import IconSprite from "@/components/IconSprite"; import PwaBoot from "@/components/PwaBoot"; import SiteBoot from "@/components/SiteBoot"; +import MotionBoot from "@/components/MotionBoot"; import SiteFooter from "@/components/SiteFooter"; import SiteHeader from "@/components/SiteHeader"; @@ -144,6 +145,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
{children}
+ diff --git a/frontend/src/app/stats/page.tsx b/frontend/src/app/stats/page.tsx new file mode 100644 index 0000000..cda4e90 --- /dev/null +++ b/frontend/src/app/stats/page.tsx @@ -0,0 +1,13 @@ +import StatsView from "@/components/views/StatsView"; + +export const metadata = { + title: "สถิติการค้นหา", + description: + "สถิติการค้นหาและหน้าเว็บที่ถูกเปิด — เก็บในเบราว์เซอร์นี้เท่านั้น ไม่มีคุกกี้ ไม่ระบุตัวตน", + alternates: { canonical: "/stats" }, + robots: { index: false, follow: true }, +}; + +export default function Page() { + return ; +} diff --git a/frontend/src/components/MotionBoot.tsx b/frontend/src/components/MotionBoot.tsx new file mode 100644 index 0000000..89dd561 --- /dev/null +++ b/frontend/src/components/MotionBoot.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { useEffect } from "react"; +import { usePathname } from "next/navigation"; +import { ensureRuntime } from "@/lib/runtime"; + +/** + * MotionBoot — อนิเมชันเข้าหน้า + สถิติการเปิดหน้า (ต่อจาก mock's router) + * + * mock: router.js เรียก `Motion.enter(viewEl)` หลัง inject partial ทุกครั้ง + * Next: App Router เปลี่ยน pathname → เรียกเองตรงนี้ (ผลลัพธ์เดียวกัน) + * + * ทำ 3 อย่างต่อการเปลี่ยนหน้า + * 1. Analytics.pageview(pathname) → นับครั้งเปิดหน้าแบบไม่ระบุตัวตน + * 2. Motion.enter(#view) → หน้าใหม่ค่อย ๆ โผล่ + เริ่ม scan reveal + * 3. Motion.scan() → เก็บการ์ดที่ hydrate ทีหลัง (MutationObserver ช่วยอีกแรง) + */ +export default function MotionBoot() { + const pathname = usePathname(); + + useEffect(() => { + let cancelled = false; + + (async () => { + await ensureRuntime(); + if (cancelled) return; + + const w = window as unknown as { + Analytics?: { pageview?: (p: string) => void }; + Motion?: { enter?: (el: Element | null) => void; scan?: () => void }; + }; + + w.Analytics?.pageview?.(pathname || "/"); + + const view = document.getElementById("view"); + w.Motion?.enter?.(view); + w.Motion?.scan?.(); + })(); + + return () => { + cancelled = true; + }; + }, [pathname]); + + return null; +} diff --git a/frontend/src/components/PwaBoot.tsx b/frontend/src/components/PwaBoot.tsx index 10286e7..834d912 100644 --- a/frontend/src/components/PwaBoot.tsx +++ b/frontend/src/components/PwaBoot.tsx @@ -2,41 +2,132 @@ * Atroute — PWA bootstrap (Next.js client component) * * ทำ 3 อย่าง - * 1. ลงทะเบียน /sw.js → ทำให้ Chrome/Samsung Internet ยอมให้ "ติดตั้งเป็นแอป" - * 2. จับ beforeinstallprompt → แสดงปุ่ม "ติดตั้งแอป" ของเราเอง - * (Android/Chrome/Edge/Samsung — iOS ไม่มี event นี้) - * 3. iOS/iPadOS → แสดงคำใบ้ "แชร์ → เพิ่มไปยังหน้าจอโฮม" แทนปุ่ม + * 1. ลงทะเบียน /sw.js + reg.update() ทุกครั้งที่เปิดหน้า และทุก 30 นาที + * 2. เทียบ /version.json กับ (เปิดหน้า · ทุก 5 นาที · + * กลับมาที่แท็บ · เน็ตกลับมา) → ต่างกัน = ขึ้น toast + รีโหลดเองครั้งเดียว + * (guard ด้วย sessionStorage: กันลูปเมื่อเซิร์ฟเวอร์ลงไฟล์ไม่ครบ) + * 3. วาดเลขรุ่นที่ footer ([data-app-ver]) * - * หมายเหตุความปลอดภัย: เบราว์เซอร์จะไม่ให้ติดตั้งถ้าไม่ใช่ HTTPS - * component นี้จะไม่แสดงปุ่มและไม่ error ถ้าเงื่อนไขไม่ครบ + * ผู้ใช้ไม่ต้องกด Ctrl+Shift+R ทั้งคอมและมือถือ + * + * หมายเหตุ: ไม่มีปุ่ม "ติดตั้งแอป" ลอยมุมขวาล่างแล้ว (เอาออกตามคำขอ) + * — Chrome/Edge ยังมีไอคอนติดตั้งของเบราว์เซอร์เองตามปกติ */ "use client"; -import { useEffect, useState } from "react"; +import { useEffect } from "react"; -type InstallPromptEvent = Event & { - prompt: () => Promise; - userChoice: Promise<{ outcome: "accepted" | "dismissed" }>; -}; +const CHECK_INTERVAL_MS = 5 * 60 * 1000; // version.json +const SW_INTERVAL_MS = 30 * 60 * 1000; // sw.js +const RELOAD_GUARD = "at_reloaded_for"; // sessionStorage — กันรีโหลดวน -const isStandalone = () => - typeof window !== "undefined" && - (window.matchMedia("(display-mode: standalone)").matches || - // iOS - (window.navigator as unknown as { standalone?: boolean }).standalone === true); +function localVersion(): string { + return document.documentElement.dataset.appVersion || ""; +} + +function alreadyReloaded(ver: string): boolean { + try { + return sessionStorage.getItem(RELOAD_GUARD) === ver; + } catch { + return false; + } +} + +function reloadOnce(ver: string) { + try { + if (alreadyReloaded(ver)) return; + sessionStorage.setItem(RELOAD_GUARD, ver); + } catch { + /* โหมดส่วนตัว: ยอมให้รีโหลดได้ */ + } + window.location.reload(); +} + +function t(key: string, fallback: string): string { + const w = window as unknown as { I18N?: { t?: (k: string) => string } }; + const got = w.I18N?.t?.(key); + return !got || got === key ? fallback : got; +} + +/* ---------- toast เล็ก ๆ ล่างจอ (ไม่บล็อกการใช้งาน) ---------- */ +function showToast(message: string) { + if (document.querySelector(".mu-update-toast")) return; + const el = document.createElement("div"); + el.className = "mu-update-toast"; + el.setAttribute("role", "status"); + el.setAttribute("aria-live", "polite"); + + const dot = document.createElement("span"); + dot.className = "mu-update-dot"; + dot.setAttribute("aria-hidden", "true"); + + const text = document.createElement("span"); + text.textContent = message; + + el.appendChild(dot); + el.appendChild(text); + document.body.appendChild(el); + setTimeout(() => el.classList.add("is-in"), 20); +} + +function applyUpdate(nextVersion: string) { + /* รีโหลดเพื่อเวอร์ชันนี้ไปแล้วแต่ยังไม่ตรง (เซิร์ฟเวอร์ยังไม่ลงไฟล์ครบ) + → หยุดเงียบ ๆ ไม่เด้ง toast ซ้ำให้รำคาญ */ + if (alreadyReloaded(nextVersion)) return; + + showToast(t("update.applying", "มีเวอร์ชันใหม่ — กำลังอัปเดต…")); + + /* แท็บถูกซ่อน = รีโหลดเลย ไม่รบกวน */ + if (document.hidden) { + reloadOnce(nextVersion); + return; + } + + let done = false; + const finish = () => { + if (done) return; + done = true; + reloadOnce(nextVersion); + }; + + if (navigator.serviceWorker) { + navigator.serviceWorker.addEventListener("controllerchange", finish, { once: true }); + navigator.serviceWorker + .getRegistration() + .then((reg) => reg?.update()) + .catch(() => undefined); + } + /* ไม่ว่า SW จะทันหรือไม่ ภายใน 2.5 วิ รีโหลดเพื่อรับ HTML/JS ใหม่ */ + setTimeout(finish, 2500); +} + +function paintVersion() { + const v = localVersion(); + if (!v) return; + document.querySelectorAll("[data-app-ver]").forEach((el) => { + el.textContent = "v" + v; + }); +} export default function PwaBoot() { - const [deferred, setDeferred] = useState(null); - const [showIosHint, setShowIosHint] = useState(false); - const [installed, setInstalled] = useState(false); - useEffect(() => { if (typeof window === "undefined") return; - if (process.env.NODE_ENV !== "production") { - // dev server ไม่มี HTTPS/scope ที่ถูก → ไม่ต้องรบกวน - } + paintVersion(); - setInstalled(isStandalone()); + /* เทียบรุ่นที่โหลดอยู่ กับ /version.json บนเซิร์ฟเวอร์ + — ต่างกัน = deploy รุ่นใหม่แล้ว → toast + รีโหลด (กันลูปด้วย guard) */ + const checkVersion = () => { + if (!localVersion()) return; + fetch("/version.json?t=" + Date.now(), { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : null)) + .then((data: { version?: string } | null) => { + const remote = String(data?.version || ""); + const local = localVersion(); + paintVersion(); + if (remote && local && remote !== local) applyUpdate(remote); + }) + .catch(() => undefined); + }; /* ---------- 1) service worker ---------- */ if ("serviceWorker" in navigator) { @@ -45,145 +136,32 @@ export default function PwaBoot() { .register("/sw.js", { scope: "/", updateViaCache: "none" }) .then((reg) => { reg.update().catch(() => undefined); - // ตรวจอัปเดตซ้ำทุก 30 นาที (จอที่เปิดค้าง) - setInterval(() => reg.update().catch(() => undefined), 30 * 60 * 1000); + // ตรวจอัปเดต SW ซ้ำทุก 30 นาที (จอที่เปิดค้าง) + setInterval(() => reg.update().catch(() => undefined), SW_INTERVAL_MS); }) .catch(() => undefined); }; if (document.readyState === "complete") register(); else window.addEventListener("load", register, { once: true }); - /* SW ใหม่เข้าควบคุม → โหลดใหม่เงียบ ๆ (ผู้ใช้ไม่ต้องล้างแคช) */ - navigator.serviceWorker.addEventListener("message", (e) => { - if (e.data?.type === "SW_ACTIVATED") { - // กัน reload วนซ้ำ: ทำได้ครั้งเดียวต่อการเปิดหน้า - const w = window as unknown as { __swReloaded?: boolean }; - if (w.__swReloaded) return; - w.__swReloaded = true; - window.location.reload(); - } + /* SW ใหม่เข้าควบคุม → รับเวอร์ชันใหม่ (ครั้งเดียวต่อเวอร์ชัน) */ + navigator.serviceWorker.addEventListener("controllerchange", () => { + reloadOnce(localVersion() || "sw"); }); - - /* เทียบรุ่นที่โหลดอยู่ กับ /version.json บนเซิร์ฟเวอร์ - — ถ้าต่างกัน แปลว่า deploy รุ่นใหม่แล้ว แต่หน้านี้ยังเป็นของเก่า → โหลดใหม่ */ - /* แสดงรุ่นที่โหลดอยู่บนหน้าเว็บ (footer) */ - const paintVersion = () => { - const v = document.documentElement.dataset.appVersion || ""; - if (!v) return; - document.querySelectorAll("[data-app-ver]").forEach((el) => { - el.textContent = "v" + v; - }); - }; - paintVersion(); - - const checkVersion = () => { - fetch("/version.json", { cache: "no-store" }) - .then((r) => (r.ok ? r.json() : null)) - .then((v) => { - const remote = String(v?.version || ""); - const local = document.documentElement.dataset.appVersion || ""; - paintVersion(); - if (remote && local && remote !== local) { - const w = window as unknown as { __verReloaded?: boolean }; - if (w.__verReloaded) return; - w.__verReloaded = true; - window.location.reload(); - } - }) - .catch(() => undefined); - }; - setTimeout(checkVersion, 1500); - setInterval(checkVersion, 5 * 60 * 1000); } - /* ---------- 2) install prompt (Android) ---------- */ - const onPrompt = (e: Event) => { - e.preventDefault(); - setDeferred(e as InstallPromptEvent); - }; - const onInstalled = () => { - setInstalled(true); - setDeferred(null); - }; - window.addEventListener("beforeinstallprompt", onPrompt); - window.addEventListener("appinstalled", onInstalled); + /* ---------- 2) ตรวจ version.json ---------- */ + checkVersion(); + setInterval(checkVersion, CHECK_INTERVAL_MS); - /* ---------- 3) iOS/iPadOS hint ---------- */ - const ua = navigator.userAgent; - const isIos = - /iPad|iPhone|iPod/.test(ua) || - (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1); - // Samsung Internet ก็ไม่ยิง beforeinstallprompt เหมือนกันในบางเวอร์ชัน - const isSamsung = /SamsungBrowser/i.test(ua); - if ((isIos || isSamsung) && !isStandalone()) setShowIosHint(true); - - return () => { - window.removeEventListener("beforeinstallprompt", onPrompt); - window.removeEventListener("appinstalled", onInstalled); + /* กลับมาที่แท็บ/สลับแอปกลับมา (มือถือ) · เน็ตกลับมา → ตรวจทันที */ + const onVisible = () => { + if (document.visibilityState === "visible") checkVersion(); }; + const onOnline = () => checkVersion(); + document.addEventListener("visibilitychange", onVisible); + window.addEventListener("online", onOnline); }, []); - if (installed) return null; - if (!deferred && !showIosHint) return null; - - const btn: React.CSSProperties = { - position: "fixed", - insetInlineEnd: 16, - bottom: 16, - zIndex: 2000, - display: "inline-flex", - alignItems: "center", - gap: 8, - minHeight: 44, - padding: "10px 18px", - border: 0, - borderRadius: 999, - background: "#7a4cc0", - color: "#fff", - font: "inherit", - fontSize: 14, - fontWeight: 600, - cursor: "pointer", - boxShadow: "0 2px 10px rgba(0,0,0,.18)", - }; - - if (showIosHint && !deferred) { - return ( -
- - แชร์ → เพิ่มไปยังหน้าจอโฮม -
- ); - } - - return ( - - ); + return null; } diff --git a/frontend/src/components/SiteFooter.tsx b/frontend/src/components/SiteFooter.tsx index 3fc4142..eda38ec 100644 --- a/frontend/src/components/SiteFooter.tsx +++ b/frontend/src/components/SiteFooter.tsx @@ -86,6 +86,11 @@ export default function SiteFooter() { เครดิต +
  • + + สถิติ + +
  • @@ -122,22 +127,6 @@ export default function SiteFooter() { v—

    - - - ผู้เข้าชม - 12,834 - diff --git a/frontend/src/components/views/StatsView.tsx b/frontend/src/components/views/StatsView.tsx new file mode 100644 index 0000000..94e58f7 --- /dev/null +++ b/frontend/src/components/views/StatsView.tsx @@ -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 = { + "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) { + let out = FALLBACK[key] || key; + if (typeof window !== "undefined") { + const w = window as unknown as { + I18N?: { t?: (k: string, v?: Record) => 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(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 ( +
    +
    +
    +

    + หน้าแรก/ สถิติ +

    +

    {tr("stats.title")}

    +

    {tr("stats.lead")}

    +
    + +
    +
    {num(report.totals.pageviews)}{tr("stats.kpi.views")}
    +
    {num(report.totals.searches)}{tr("stats.kpi.searches")}
    +
    {num(report.totals.terms)}{tr("stats.kpi.terms")}
    +
    {num(report.totals.noResult)}{tr("stats.kpi.noResult")}
    +
    + +
    +

    {tr("stats.chart.title")}

    +

    {tr("stats.chart.lead")}

    +
    + {series.map((s, idx) => ( +
    + + + 8 && idx % 2 === 1 ? { opacity: 0 } : undefined}>{s.day} +
    + ))} +
    +
    + {tr("stats.kpi.views")} + {tr("stats.kpi.searches")} +
    +
    + +
    +
    +

    {tr("stats.terms.title")}

    +

    {tr("stats.terms.lead")}

    + + + + + + + + + + {report.topTerms.map((row) => ( + + + + + + ))} + +
    {tr("stats.col.term")}{tr("stats.col.count")}{tr("stats.col.last")}
    {short(row.term || "", 42)}{num(row.count)}{when(row.last)}
    + {!report.topTerms.length &&

    {tr("stats.terms.empty")}

    } +
    + +
    +

    {tr("stats.views.title")}

    +

    {tr("stats.views.lead")}

    + + + + + + + + + + {report.topViews.map((row) => ( + + + + + + ))} + +
    {tr("stats.col.target")}{tr("stats.col.count")}{tr("stats.col.last")}
    + + {row.kind === "route" + ? tr("stats.views.routePrefix", { n: row.id || "" }) + : tr("stats.views.stopPrefix", { code: row.id || "" })} + + {num(row.count)}{when(row.last)}
    + {!report.topViews.length &&

    {tr("stats.views.empty")}

    } +
    +
    + + {report.topEmpty.length > 0 && ( +
    +

    {tr("stats.noresult.title")}

    +

    {tr("stats.noresult.lead")}

    + + + + + + + + + + {report.topEmpty.map((row) => ( + + + + + + ))} + +
    {tr("stats.col.term")}{tr("stats.col.count")}{tr("stats.col.last")}
    {short(row.term || "", 42)}{num(row.count)}{when(row.last)}
    +
    + )} + +
    +

    {tr("stats.privacy.title")}

    +
      +
    • {tr("stats.privacy.collect")}
    • +
    • {tr("stats.privacy.reject")}
    • +
    • {tr("stats.privacy.local")}
    • +
    + +
    + + +
    +

    {status}

    +

    + {tr("stats.since")}: {report.since ? new Date(report.since).toLocaleDateString("th-TH", { year: "numeric", month: "short", day: "numeric" }) : "—"} +

    +
    +
    +
    + ); +} diff --git a/frontend/src/data/locales/en.json b/frontend/src/data/locales/en.json index 2b06d64..7f40b21 100644 --- a/frontend/src/data/locales/en.json +++ b/frontend/src/data/locales/en.json @@ -352,5 +352,43 @@ "credits.osmCredit": "OpenStreetMap © contributors (ODbL)", "credits.facebookGroup": "Facebook group (web.facebook.com)", "credits.from": "from", - "credits.routeN": "Route {n}" + "credits.routeN": "Route {n}", + "nav.stats": "Stats", + "update.applying": "New version — updating…", + "stats.title": "Search statistics on this device", + "stats.lead": "Only counts and search terms are kept — no cookies, no user id, no IP, and nothing leaves this device", + "stats.kpi.views": "Page views", + "stats.kpi.searches": "Searches", + "stats.kpi.terms": "Unique terms", + "stats.kpi.noResult": "No results", + "stats.chart.title": "Last 14 days", + "stats.chart.lead": "Solid bar = page views · light bar = searches", + "stats.terms.title": "Top search terms", + "stats.terms.lead": "Terms are sanitised — emails, phone numbers and long digit runs are stripped before saving", + "stats.terms.empty": "No searches on this device yet — try the stop search page, then come back", + "stats.views.title": "Most opened pages", + "stats.views.lead": "Counts route and stop detail pages only (not tied to any user)", + "stats.views.empty": "No data yet — open a route or stop detail once", + "stats.views.stopPrefix": "Stop {code}", + "stats.views.routePrefix": "Route {n}", + "stats.noresult.title": "Searched, nothing found", + "stats.noresult.lead": "A signal that data is missing — these terms should exist if they are real routes", + "stats.privacy.title": "Privacy", + "stats.privacy.collect": "Stored: page-view counts · sanitised search terms · no-result counts · last-used time", + "stats.privacy.reject": "Not stored: IP · User-Agent · location · cookies · device id · cross-site history", + "stats.privacy.local": "Data lives in this browser's localStorage only — clear it anytime", + "stats.privacy.optoutTitle": "Turn off stats on this device", + "stats.privacy.optoutLead": "Switching this on stops recording immediately (existing numbers stay visible). Do Not Track / GPC are respected anyway.", + "stats.privacy.off": "Stats turned off — nothing new is recorded", + "stats.privacy.on": "Stats turned on", + "stats.btn.export": "Download data (JSON)", + "stats.btn.clear": "Clear data on this device", + "stats.clear.confirm": "Clear all stats on this device? This cannot be undone.", + "stats.clear.done": "Data cleared", + "stats.export.done": "File downloaded", + "stats.since": "Collecting since", + "stats.col.term": "Term", + "stats.col.count": "Hits", + "stats.col.last": "Last", + "stats.col.target": "Page" } diff --git a/frontend/src/data/locales/th.json b/frontend/src/data/locales/th.json index 6d45d8c..930207b 100644 --- a/frontend/src/data/locales/th.json +++ b/frontend/src/data/locales/th.json @@ -352,5 +352,43 @@ "credits.osmCredit": "OpenStreetMap © ผู้มีส่วนร่วม (ODbL)", "credits.facebookGroup": "กลุ่ม Facebook (web.facebook.com)", "credits.from": "จาก", - "credits.routeN": "สาย {n}" + "credits.routeN": "สาย {n}", + "nav.stats": "สถิติ", + "update.applying": "มีเวอร์ชันใหม่ — กำลังอัปเดต…", + "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.views.stopPrefix": "ป้าย {code}", + "stats.views.routePrefix": "สาย {n}", + "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": "หน้า" } diff --git a/frontend/src/lib/runtime.ts b/frontend/src/lib/runtime.ts index 1f4158f..3c5fa3a 100644 --- a/frontend/src/lib/runtime.ts +++ b/frontend/src/lib/runtime.ts @@ -24,7 +24,8 @@ export function ensureRuntime(): Promise { await import("./ui/imageurl"); await import("./ui/i18n"); await import("./ui/popular"); - await import("./ui/visitors"); + await import("./ui/analytics"); + await import("./ui/motion"); await import("./ui/map"); await import("./ui/schedules"); await import("./ui/otherStop"); diff --git a/frontend/src/lib/ui/analytics.ts b/frontend/src/lib/ui/analytics.ts new file mode 100644 index 0000000..5fcb5c0 --- /dev/null +++ b/frontend/src/lib/ui/analytics.ts @@ -0,0 +1,302 @@ +// @ts-nocheck +/** + * analytics.ts — สถิติการค้นหา/เปิดหน้า แบบไม่ระบุตัวตน (ported from + * web-at-transit-mock/ui/analytics.js) + * + * หลักความเป็นส่วนตัว (เหมือนต้นแบบ): + * - ไม่มีคุกกี้ · ไม่มี fingerprint · ไม่เก็บ IP/UA/พิกัด + * - session id สุ่มต่อแท็บ (sessionStorage) — ใช้แค่กันนับซ้ำ + * - เคารพ Do Not Track + Global Privacy Control + สวิตช์ opt-out + * - เก็บรวมในเครื่อง (localStorage at_stats_v1) — ค่าเริ่มต้นไม่ส่งออกเน็ต + * - ถ้าตั้ง window.AT_ANALYTICS = { endpoint, siteId } จึง POST สเปก Umami + * + * API: window.Analytics.search({q,scope,results}) · pageview(path) · view(kind,id) + * report() · exportJSON() · clear() · optOut(bool) · isOptedOut() · cleanTerm() + */ +(function () { + 'use strict'; + + var KEY = 'at_stats_v1'; + var OPTOUT_KEY = 'at_stats_optout'; + var SESSION_KEY = 'at_stats_sid'; + + var MAX_TERMS = 300; + var MAX_VIEWS = 200; + var MAX_DAYS = 120; + var TERM_MAX_LEN = 60; + var DEBOUNCE_MS = 900; + var DAY_MS = 86400000; + + function cfg() { + return (typeof window !== 'undefined' && window.AT_ANALYTICS) || {}; + } + + function dntOn() { + var d = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack; + if (d === '1' || d === 'yes' || d === 'on') return true; + if (navigator.globalPrivacyControl === true) return true; + return false; + } + + function optedOut() { + try { return localStorage.getItem(OPTOUT_KEY) === '1'; } + catch (e) { return true; } + } + + function tracking() { return !dntOn() && !optedOut(); } + + function now() { return Date.now(); } + + function dayKey(ts) { + var d = new Date(ts); + var m = ('0' + (d.getMonth() + 1)).slice(-2); + var day = ('0' + d.getDate()).slice(-2); + return d.getFullYear() + '-' + m + '-' + day; + } + + /** ตัดข้อมูลส่วนตัวออกจากคำค้นก่อนบันทึกเสมอ */ + function cleanTerm(q) { + var s = String(q == null ? '' : q).replace(/\s+/g, ' ').trim(); + if (!s) return ''; + s = s + .replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g, ' ') + .replace(/@[\w.]+/g, ' ') + .replace(/\d{5,}/g, ' ') + .replace(/\s+/g, ' ') + .trim() + .toLowerCase(); + if (s.length > TERM_MAX_LEN) s = s.slice(0, TERM_MAX_LEN); + return s; + } + + function blank() { + return { v: 1, since: now(), days: {}, terms: {}, empty: {}, views: {} }; + } + + function read() { + try { + var raw = localStorage.getItem(KEY); + if (!raw) return blank(); + var d = JSON.parse(raw); + if (!d || typeof d !== 'object' || d.v !== 1) return blank(); + d.days = d.days || {}; d.terms = d.terms || {}; d.empty = d.empty || {}; d.views = d.views || {}; + return d; + } catch (e) { return blank(); } + } + + function write(d) { + try { localStorage.setItem(KEY, JSON.stringify(d)); } catch (e) { /* เงียบ */ } + } + + function cap(map, max) { + var keys = Object.keys(map); + if (keys.length <= max) return false; + keys.sort(function (a, b) { return ((map[a] && map[a][1]) || 0) - ((map[b] && map[b][1]) || 0); }); + var cut = keys.length - max; + for (var i = 0; i < cut; i++) delete map[keys[i]]; + return true; + } + + function bump(map, key, ts, max) { + if (!key) return; + var e = map[key]; + map[key] = [(e && Number(e[0])) || 0, ts]; + map[key][0] += 1; + cap(map, max); + } + + function pruneDays(d, ts) { + var cut = dayKey(ts - (MAX_DAYS - 1) * DAY_MS); + Object.keys(d.days).forEach(function (k) { if (k < cut) delete d.days[k]; }); + } + + function day(d, ts) { + var k = dayKey(ts); + if (!d.days[k]) d.days[k] = { pv: 0, q: 0, nores: 0 }; + return d.days[k]; + } + + /* ---------- ส่งออก Umami (เฉพาะเมื่อเจ้าของเว็บตั้งค่า) ---------- */ + var sid = null; + function sessionId() { + if (sid) return sid; + try { + sid = sessionStorage.getItem(SESSION_KEY); + if (!sid) { + sid = Math.random().toString(36).slice(2) + now().toString(36); + sessionStorage.setItem(SESSION_KEY, sid); + } + } catch (e) { sid = 'anon'; } + return sid; + } + + function send(name, data) { + var c = cfg(); + if (!c || !c.endpoint || !c.siteId) return; + var body = { + type: 'event', + payload: { + website: c.siteId, + hostname: location.hostname, + url: location.pathname + location.search, + referrer: document.referrer || '', + title: document.title || '', + language: navigator.language || '', + screen: (screen.width || 0) + 'x' + (screen.height || 0), + event_name: name, + event_data: data || {} + } + }; + var url = String(c.endpoint).replace(/\/+$/, '') + '/api/send'; + try { + var blob = new Blob([JSON.stringify(body)], { type: 'application/json' }); + if (navigator.sendBeacon && navigator.sendBeacon(url, blob)) return; + fetch(url, { + method: 'POST', body: JSON.stringify(body), keepalive: true, + headers: { 'Content-Type': 'application/json' } + }).catch(function () {}); + } catch (e) { /* analytics ต้องไม่ทำให้หน้าเว็บพัง */ } + } + + /* ---------- บันทึก ---------- */ + var pending = null; + var lastPV = { key: '', ts: 0 }; + var lastView = { key: '', ts: 0 }; + + function recordSearch(q, scope, results) { + var term = cleanTerm(q); + if (!term || term.replace(/\s/g, '').length < 2) return; + var ts = now(); + var d = read(); + var bucket = day(d, ts); + bucket.q += 1; + if (results === 0) { bucket.nores += 1; bump(d.empty, term, ts, MAX_TERMS); } + else bump(d.terms, term, ts, MAX_TERMS); + pruneDays(d, ts); + write(d); + if (tracking()) send('search', { term: term, scope: scope || '', results: results }); + } + + function flush() { + if (!pending) return; + var p = pending; + pending = null; + clearTimeout(p.timer); + recordSearch(p.q, p.scope, p.results); + } + + function trackViewOnce(kind, id) { + if (!id) return; + var key = kind + ':' + id; + var ts = now(); + if (lastView.key === key && ts - lastView.ts < 1200) return; + lastView = { key: key, ts: ts }; + var d = read(); + bump(d.views, key, ts, MAX_VIEWS); + write(d); + if (tracking()) send('view', { kind: kind, id: String(id) }); + } + + var Analytics = { + /** นับการเปิดหน้า — เรียกจาก MotionBoot ตอน pathname เปลี่ยน */ + pageview: function (path) { + if (!tracking()) { flush(); return; } + var key = String(path || (typeof location !== 'undefined' ? location.pathname : '/')); + var ts = now(); + if (lastPV.key === key && ts - lastPV.ts < 1200) return; + lastPV = { key: key, ts: ts }; + + var d = read(); + day(d, ts).pv += 1; + pruneDays(d, ts); + write(d); + + var seg = key.split('/').filter(Boolean); + if (seg[0] === 'routes' && seg[1]) trackViewOnce('route', decodeURIComponent(seg[1])); + else if (seg[0] === 'stops' && seg[1]) trackViewOnce('stop', decodeURIComponent(seg[1])); + + if (tracking()) send('pageview', { path: key }); + }, + + /** เรียกได้ทุกครั้งที่ผลค้นเปลี่ยน — debounce 900ms ในตัว */ + search: function (opts) { + if (!tracking()) return; + var o = opts || {}; + var q = String(o.q == null ? '' : o.q); + if (!cleanTerm(q) || cleanTerm(q).replace(/\s/g, '').length < 2) return; + + if (pending) clearTimeout(pending.timer); + pending = { + q: q, + scope: o.scope || '', + results: (typeof o.results === 'number') ? o.results : null, + timer: setTimeout(flush, DEBOUNCE_MS) + }; + }, + + view: function (kind, id) { if (tracking()) trackViewOnce(kind, id); }, + + /* ---------- รายงานสำหรับหน้า /stats ---------- */ + report: function () { + var d = read(); + var ts = now(); + + function rows(map, n, fn) { + var arr = Object.keys(map).map(function (k) { + var e = map[k] || []; + return fn(k, Number(e[0]) || 0, Number(e[1]) || 0); + }).filter(function (r) { return r.count > 0; }); + arr.sort(function (a, b) { return b.count - a.count || b.last - a.last; }); + return arr.slice(0, n || 10); + } + + var days = Object.keys(d.days).sort().slice(-14).map(function (k) { + var v = d.days[k]; + return { date: k, pageviews: v.pv || 0, searches: v.q || 0, noResult: v.nores || 0 }; + }); + + var pv = 0, q = 0, nores = 0; + Object.keys(d.days).forEach(function (k) { + pv += d.days[k].pv || 0; q += d.days[k].q || 0; nores += d.days[k].nores || 0; + }); + + return { + since: d.since || ts, + totals: { + pageviews: pv, searches: q, noResult: nores, + terms: Object.keys(d.terms).length, views: Object.keys(d.views).length + }, + days: days, + topTerms: rows(d.terms, 12, function (k, c, l) { return { term: k, count: c, last: l }; }), + topEmpty: rows(d.empty, 8, function (k, c, l) { return { term: k, count: c, last: l }; }), + topViews: rows(d.views, 12, function (k, c, l) { + var at = k.indexOf(':'); + return { kind: k.slice(0, at), id: k.slice(at + 1), count: c, last: l }; + }) + }; + }, + + exportJSON: function () { return JSON.stringify(read(), null, 2); }, + + clear: function () { + try { localStorage.removeItem(KEY); } catch (e) {} + pending = null; + lastPV = { key: '', ts: 0 }; + lastView = { key: '', ts: 0 }; + }, + + optOut: function (on) { + if (pending) { clearTimeout(pending.timer); pending = null; } + try { localStorage.setItem(OPTOUT_KEY, on ? '1' : '0'); } catch (e) {} + }, + + isOptedOut: function () { return optedOut() || dntOn(); }, + tracking: tracking, + cleanTerm: cleanTerm, + _key: KEY + }; + + window.Analytics = Analytics; +})(); + +export {}; diff --git a/frontend/src/lib/ui/motion.ts b/frontend/src/lib/ui/motion.ts new file mode 100644 index 0000000..0b730f2 --- /dev/null +++ b/frontend/src/lib/ui/motion.ts @@ -0,0 +1,205 @@ +// @ts-nocheck +/** + * motion.ts — อนิเมชันร่วมทุกหน้า (ported from web-at-transit-mock/ui/motion.js) + * + * window.Motion.enter(#view) ← MotionBoot เรียกทุกครั้งที่ pathname เปลี่ยน + * window.Motion.scan() ← สแกนการ์ดที่จะค่อย ๆ โผล่ตอนเลื่อน + * window.Motion.loading(bool) ← แถบโหลดบางบนสุด + * + * หลักการเดียวกับต้นแบบ: + * - แตะเฉพาะ opacity + transform (ไม่เกิด CLS) · ใช้ของที่ยังไม่เห็นบนจอเท่านั้น + * - เคลียร์ class/transform หลังจบ → hover เดิมของแต่ละหน้าไม่ถูกทับ + * - ไม่แตะของที่ครอบแผนที่ (Leaflet) · prefers-reduced-motion = ปิดทั้งหมด + */ +(function () { + 'use strict'; + + var mqReduce = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null; + function reduced() { return !!(mqReduce && mqReduce.matches); } + + /* ---------------------------------------------------------- + 1) แถบโหลดด้านบน + ---------------------------------------------------------- */ + var bar = null, barFill = null, growTimer = null, outTimer = null; + + function ensureBar() { + if (bar && document.body.contains(bar)) return; + bar = document.createElement('div'); + bar.className = 'mu-loadbar'; + bar.setAttribute('aria-hidden', 'true'); + barFill = document.createElement('div'); + barFill.className = 'mu-loadbar-fill'; + bar.appendChild(barFill); + document.body.appendChild(bar); + } + + function setProgress(p) { + if (!barFill) return; + barFill.style.transition = 'transform .4s cubic-bezier(.22,.61,.36,1)'; + barFill.style.transform = 'scaleX(' + p + ')'; + } + + function loading(on) { + if (reduced() || !document.body) return; + ensureBar(); + clearTimeout(growTimer); + clearTimeout(outTimer); + + if (on) { + bar.classList.add('is-on'); + barFill.style.transition = 'none'; + barFill.style.transform = 'scaleX(0)'; + void barFill.offsetWidth; + setProgress(0.18); + growTimer = setTimeout(function () { setProgress(0.5); }, 200); + growTimer = setTimeout(function () { setProgress(0.78); }, 700); + return; + } + + setProgress(1); + outTimer = setTimeout(function () { + bar.classList.remove('is-on'); + outTimer = setTimeout(function () { + if (!barFill) return; + barFill.style.transition = 'none'; + barFill.style.transform = 'scaleX(0)'; + }, 260); + }, 180); + } + + /* ---------------------------------------------------------- + 2) เข้าหน้า + ---------------------------------------------------------- */ + function enter(el) { + if (!el || reduced()) { firstPass = false; return; } + el.classList.remove('mu-view-in'); + void el.offsetWidth; + el.classList.add('mu-view-in'); + firstPass = true; + scan(el); + setTimeout(function () { firstPass = false; scan(el); }, 400); + } + + /* ---------------------------------------------------------- + 3) เลื่อนแล้วค่อยโผล่ + ---------------------------------------------------------- */ + var SELECTOR = [ + '.mu-zone', '.mu-card', '.mu-stop-card', '.mu-blog-card', '.mu-blog-row', + '.mu-credit-section', '.mu-summary', '.mu-stat', '.mu-zone-head', + '.mu-sponsor-head', '.mu-schedule', '.mu-kpi', '.mu-post-figure', + '.mu-nearby', '.mu-route-tools', '.st-card', '.st-kpi' + ].join(','); + + var SKIP_INSIDE = '.leaflet-container, .at-map, .blog-mapx, [data-no-reveal]'; + + var io = ('IntersectionObserver' in window) + ? new IntersectionObserver(onIntersect, { rootMargin: '0px 0px -8% 0px', threshold: 0.05 }) + : null; + + var firstPass = false; + var pending = []; + + function reveal(el) { + if (!el || el.classList.contains('is-in')) return; + var at = pending.indexOf(el); + if (at !== -1) pending.splice(at, 1); + io.unobserve(el); + el.classList.add('is-in'); + var d = parseFloat(el.style.getPropertyValue('--mu-d')) || 0; + setTimeout(function () { + el.classList.remove('mu-reveal', 'is-in'); + el.style.removeProperty('--mu-d'); + }, 700 + d); + } + + function onIntersect(entries) { + for (var i = 0; i < entries.length; i++) { + if (entries[i].isIntersecting) reveal(entries[i].target); + } + sweep(); + } + + function sweep() { + if (!pending.length) return; + var vh = window.innerHeight || document.documentElement.clientHeight; + for (var i = pending.length - 1; i >= 0; i--) { + var el = pending[i]; + if (!el.isConnected) { pending.splice(i, 1); io.unobserve(el); continue; } + if (el.getBoundingClientRect().top < vh) reveal(el); + } + } + + var sweepQueued = 0; + function queueSweep() { + if (sweepQueued) return; + sweepQueued = 1; + setTimeout(function () { sweepQueued = 0; sweep(); }, 90); + } + + function scan(root) { + if (!io || reduced()) return; + root = root || document.getElementById('view'); + if (!root) return; + + var nodes = root.querySelectorAll(SELECTOR); + if (!nodes.length) return; + + pending = pending.filter(function (el) { return el.isConnected; }); + + var vh = window.innerHeight || document.documentElement.clientHeight; + var idx = 0; + + for (var i = 0; i < nodes.length; i++) { + var el = nodes[i]; + if (el.classList.contains('mu-reveal') || el.classList.contains('is-in')) continue; + if (el.closest(SKIP_INSIDE)) continue; + if (el.parentElement && el.parentElement.closest(SELECTOR) && root.contains(el.parentElement.closest(SELECTOR))) continue; + + var rect = el.getBoundingClientRect(); + if (rect.width === 0 && rect.height === 0) continue; + if (firstPass && rect.top < vh) continue; + + el.style.setProperty('--mu-d', (Math.min(idx, 4) * 45) + 'ms'); + el.classList.add('mu-reveal'); + pending.push(el); + idx++; + io.observe(el); + } + + if (idx) setTimeout(sweep, 300); + } + + window.addEventListener('scroll', queueSweep, { passive: true }); + window.addEventListener('resize', queueSweep); + document.addEventListener('visibilitychange', function () { + if (document.visibilityState === 'visible') queueSweep(); + }); + window.addEventListener('beforeprint', function () { + var rest = pending.slice(); + for (var i = 0; i < rest.length; i++) reveal(rest[i]); + }); + + /* การ์ดที่ JS สร้างทีหลัง (fetch JSON / กรอง / เปลี่ยนภาษา) → สแกนซ้ำให้เอง */ + var scanTimer = 0; + function scheduleScan() { + if (scanTimer) return; + scanTimer = setTimeout(function () { scanTimer = 0; scan(); }, 80); + } + + function watch() { + var host = document.getElementById('view'); + if (!host || !window.MutationObserver) return; + new MutationObserver(function (list) { + for (var i = 0; i < list.length; i++) { + if (list[i].addedNodes && list[i].addedNodes.length) { scheduleScan(); return; } + } + }).observe(host, { childList: true, subtree: true }); + } + + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watch); + else watch(); + + window.Motion = { enter: enter, scan: scan, loading: loading, reduced: reduced }; +})(); + +export {}; diff --git a/frontend/src/lib/ui/stop.init.ts b/frontend/src/lib/ui/stop.init.ts index 8243007..f73c3d7 100644 --- a/frontend/src/lib/ui/stop.init.ts +++ b/frontend/src/lib/ui/stop.init.ts @@ -341,6 +341,11 @@ function nm(o: any, base: string): string { if (ok) shown++; }); setCount(shown, items.length); + + /* สถิติคำค้นในหน้ารายละเอียดป้าย (debounce อยู่ใน Analytics) */ + if (kw.length >= 2 && (window as any).Analytics) { + (window as any).Analytics.search({ q: kw, scope: 'stop', results: shown }); + } } function setupFilter() { var input = $('mu-route-filter'); diff --git a/frontend/src/lib/ui/stops.search.ts b/frontend/src/lib/ui/stops.search.ts index 261c866..bf22dd2 100644 --- a/frontend/src/lib/ui/stops.search.ts +++ b/frontend/src/lib/ui/stops.search.ts @@ -159,6 +159,15 @@ /* จำกัด 6 ใบเมื่อ "ไม่ได้กรองอะไร" (เปิดหน้าปกติ) · ค้นหา/กรอง = แสดงผลทั้งหมดที่เจอ */ var searching = !!f.value; + + /* สถิติคำค้น (เฉพาะตอนมีคำจริง · Analytics ทำ debounce 900ms ให้เอง) */ + if (searching && (window as any).Analytics) { + (window as any).Analytics.search({ + q: f.value, + scope: state.mode === MODE_CODE ? 'code' : 'place', + results: filtered.length + }); + } var limit = (searching || state.showAll) ? filtered.length : PREVIEW_LIMIT; var cards = [].filter.call(host.children, function (el) { return el.tagName === 'LI' && el.hasAttribute('data-idx'); }); diff --git a/frontend/src/lib/ui/visitors.ts b/frontend/src/lib/ui/visitors.ts deleted file mode 100644 index 3614ebf..0000000 --- a/frontend/src/lib/ui/visitors.ts +++ /dev/null @@ -1,227 +0,0 @@ -// @ts-nocheck -/* Ported from web-at-transit-mock/ui/visitors.js — logic unchanged. */ -/* visitors.js — นับผู้เข้าชมจริง (ฝั่งเบราว์เซอร์ ไม่มี backend) + รีเซ็ตด้วยรหัส - - แนวคิด - แสดงผล = ฐาน + จำนวนผู้เข้าชมจริง (unique) - ฐานเริ่มต้น = 12,834 (แสดงเมื่อยังไม่เคยรีเซ็ต) - รีเซ็ต (รหัส) = ล้างฐานทิ้งด้วย → เริ่มนับใหม่จาก 0 - - กันจำนวนเฟ้อ 3 ชั้น - 1. sessionStorage → 1 รอบการเข้าชม (เปิดแท็บใหม่) นับ 1 · กด F5 ไม่นับ - 2. localStorage → 1 ครั้ง/วัน/เครื่อง (วันเดียวกันนับครั้งเดียว) - 3. dayKey กำกับ → ล้าง session/incognito เปิดซ้ำวันเดิม = ไม่นับ (เพดาน/วัน) - - ประหยัดพื้นที่ - เก็บแค่ {"v": <จำนวนจริง>, "d": <วัน YYYY-MM-DD>} ≈ 35 ไบต์ · ไม่เก็บ log/IP/UA - - รีเซ็ต - กดที่ตัวเลขผู้เข้าชม 5 ครั้งติด → เปิดช่องกรอกรหัส (ซ่อน ไม่มีปุ่มให้คนอื่นกด) - รหัสตรวจแบบ SHA-256 (ไม่เก็บรหัสจริงในโค้ด — เปิด view-source ไม่เจอ) -*/ -(function () { - 'use strict'; - - var KEY = 'at_visitors'; /* { v: จำนวนจริง, d: 'YYYY-MM-DD' } */ - var SESSION_KEY = 'at_visitors_seen'; - var BASE = 12834; /* ฐานตั้งต้น — รีเซ็ตแล้วกลับมาที่นี่ */ - var TAPS = 5; /* จำนวนครั้งที่ต้องกดตัวเลข */ - var TAP_WINDOW = 2000; /* ต้องกดรัวภายใน 2 วิต่อครั้ง */ - - /* SHA-256 ของรหัสรีเซ็ต — เก็บเฉพาะ hash (ไม่เก็บรหัสจริงในไฟล์นี้) */ - var PASS_HASH = '4f23cd6ac8e7da56b92974cd0cf146eee9d995208a6645ed17eba91813c1d323'; - - function today() { - var d = new Date(); - var m = String(d.getMonth() + 1); - var day = String(d.getDate()); - if (m.length < 2) m = '0' + m; - if (day.length < 2) day = '0' + day; - return d.getFullYear() + '-' + m + '-' + day; - } - - function read() { - try { - var raw = localStorage.getItem(KEY); - var d = raw ? JSON.parse(raw) : null; - if (!d || typeof d !== 'object') return { b: null, v: 0, d: '' }; - return { - b: (d.b === undefined || d.b === null) ? null : Math.max(0, Number(d.b) || 0), - v: Math.max(0, Number(d.v) || 0), - d: String(d.d || '') - }; - } catch (e) { return { b: null, v: 0, d: '' }; } - } - - function write(d) { - try { localStorage.setItem(KEY, JSON.stringify(d)); } catch (e) { /* เงียบ */ } - } - - /* ตรวจว่ารอบการเข้าชมนี้ "ควรนับ" — ผ่านครบ 3 ชั้น */ - function shouldCount(store) { - /* ชั้น 1: sessionStorage — รอบนี้เคยนับแล้ว? (F5 ไม่นับ) */ - var seen = null; - try { seen = sessionStorage.getItem(SESSION_KEY); } catch (e) { /* เงียบ */ } - if (seen) return false; - - /* ชั้น 2+3: วันเดียวกันห้ามเพิ่ม (แม้ sessionStorage ถูกล้าง) */ - if (store.d === today()) return false; - return true; - } - - function fmt(n) { return Number(n).toLocaleString('en-US'); } - - /* ── รหัส: SHA-256 ผ่าน SubtleCrypto (มีในทุกเบราว์เซอร์สมัยใหม่) ── */ - function hash(text, cb) { - if (window.crypto && crypto.subtle && crypto.subtle.digest) { - crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)) - .then(function (buf) { - var b = new Uint8Array(buf), s = ''; - for (var i = 0; i < b.length; i++) s += ('0' + b[i].toString(16)).slice(-2); - cb(s); - }) - .catch(function () { cb(null); }); - } else { - cb(null); /* เบราว์เซอร์เก่า/ไม่มี https → กรุณาใช้ http://localhost */ - } - } - - /* เทียบแบบ constant-time (กัน timing attack) */ - function safeEqual(a, b) { - if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false; - var diff = 0; - for (var i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); - return diff === 0; - } - - var Visitors = { - BASE: BASE, /* ฐานตั้งต้น (ค่าคงที่) — ดู Visitors._base สำหรับฐานที่ใช้จริง */ - _base: BASE, - - /* เรียกครั้งเดียวตอนโหลดหน้า — นับ (ถ้าควรนับ) แล้วคืนค่าที่จะแสดง */ - init: function () { - var store = read(); - if (shouldCount(store)) { - store.v = (Number(store.v) || 0) + 1; - store.d = today(); - write(store); - try { sessionStorage.setItem(SESSION_KEY, '1'); } catch (e) { /* เงียบ */ } - } - /* ฐาน: ยังไม่เคยรีเซ็ต → BASE · เคยรีเซ็ต → ค่าที่บันทึกไว้ (0) */ - var base = (store.b === null) ? BASE : store.b; - var el = document.getElementById('visitor-count'); - if (el) el.textContent = fmt(base + store.v); - Visitors._base = base; - Visitors._store = store; - return base + store.v; - }, - - /* จำนวนจริง (ไม่รวม BASE) */ - actual: function () { return read().v; }, - - /* รีเซ็ต: ล้างฐานทิ้งด้วย → เริ่มนับใหม่จาก 0 (ตามที่เลือก) */ - reset: function () { - write({ b: 0, v: 0, d: today() }); - /* ไม่ล้าง sessionStorage — กันการนับซ้ำทันทีหลังรีเซ็ตในรอบเดียวกัน */ - Visitors._base = 0; - var el = document.getElementById('visitor-count'); - if (el) el.textContent = fmt(0); - return 0; - }, - - /* ตรวจรหัสแล้วรีเซ็ต (async — SHA-256) */ - resetWith: function (pass, done) { - hash(String(pass == null ? '' : pass), function (h) { - if (!h) { done(false, 'unsupported'); return; } - if (!safeEqual(h, PASS_HASH)) { done(false, 'wrong'); return; } - Visitors.reset(); - done(true, 'ok'); - }); - }, - - _hash: hash, - _key: KEY - }; - - window.Visitors = Visitors; - - /* ── ช่องทางลับ: กดที่ตัวเลข 5 ครั้งติด → เปิดช่องกรอกรหัส ── */ - function mountTap() { - var el = document.getElementById('visitor-count'); - if (!el) return; - - var taps = 0, timer = null; - el.style.cursor = 'pointer'; - el.addEventListener('click', function () { - taps++; - if (timer) clearTimeout(timer); - timer = setTimeout(function () { taps = 0; }, TAP_WINDOW); - if (taps >= TAPS) { - taps = 0; - clearTimeout(timer); - openDialog(); - } - }); - } - - function openDialog() { - if (document.querySelector('.mu-vreset')) return; - - var wrap = document.createElement('div'); - wrap.className = 'mu-vreset'; - wrap.innerHTML = - ''; - - var input = wrap.querySelector('#vreset-pass'); - var msg = wrap.querySelector('.mu-vreset-msg'); - - function close() { wrap.remove(); } - function submit() { - msg.textContent = ''; - Visitors.resetWith(input.value, function (ok, why) { - if (ok) { - msg.className = 'mu-vreset-msg is-ok'; - msg.textContent = 'รีเซ็ตแล้ว — เริ่มนับใหม่จาก 0'; - input.value = ''; - setTimeout(close, 1200); - } else if (why === 'unsupported') { - msg.textContent = 'เบราว์เซอร์ไม่รองรับ — ต้องเปิดผ่าน https หรือ localhost'; - } else { - msg.className = 'mu-vreset-msg is-bad'; - msg.textContent = 'รหัสไม่ถูกต้อง'; - input.value = ''; - input.focus(); - } - }); - } - - wrap.querySelector('.mu-vreset-ok').addEventListener('click', submit); - wrap.querySelector('.mu-vreset-cancel').addEventListener('click', close); - wrap.addEventListener('click', function (e) { if (e.target === wrap) close(); }); - input.addEventListener('keydown', function (e) { - if (e.key === 'Enter') submit(); - if (e.key === 'Escape') close(); - }); - - document.body.appendChild(wrap); - input.focus(); - } - - /* ── nับตอนโหลด + ติดช่องทางลับ ── */ - function boot() { - Visitors.init(); - mountTap(); - } - if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); - else boot(); -})(); -export {}; diff --git a/frontend/src/styles/_shared.css b/frontend/src/styles/_shared.css index 700e677..b013e3f 100644 --- a/frontend/src/styles/_shared.css +++ b/frontend/src/styles/_shared.css @@ -720,3 +720,99 @@ body:has(.mu-site-footer) .mu-footer { display: none; } color: var(--c-ink-2); opacity: .85; } + +/* ========================================================= + Motion (ported from web-at-transit-mock/ui/motion.js) + --------------------------------------------------------- + โทเคนเดียวทั้งเว็บ: --mu-ease (deceleration) · 420ms เข้าหน้า + 520ms reveal · 45ms/ชิ้น · แถบโหลดออกเร็วกว่าเข้า + ========================================================= */ +:root { --mu-ease: cubic-bezier(.22, .61, .36, 1); } + +/* ---------- แถบโหลดบาง ๆ บนสุด (ตอนเปลี่ยนหน้า) ---------- */ +.mu-loadbar { + position: fixed; + top: 0; + left: 0; + right: 0; + height: 3px; + z-index: 1200; + pointer-events: none; + opacity: 0; + transition: opacity .25s ease; +} +.mu-loadbar.is-on { opacity: 1; } +.mu-loadbar-fill { + height: 100%; + width: 100%; + transform: scaleX(0); + transform-origin: 0 50%; + border-radius: 0 2px 2px 0; + background: linear-gradient(90deg, var(--c-brand), #b694f6); + box-shadow: 0 0 8px color-mix(in srgb, var(--c-brand) 45%, transparent); +} + +@media (prefers-reduced-motion: no-preference) { + #view.mu-view-in { animation: muViewIn .42s var(--mu-ease) both; } + @keyframes muViewIn { + from { opacity: 0; transform: translate3d(0, 10px, 0); } + to { opacity: 1; transform: none; } + } + + .mu-reveal { + opacity: 0; + transform: translate3d(0, 18px, 0); + transition: opacity .52s var(--mu-ease), transform .52s var(--mu-ease); + transition-delay: var(--mu-d, 0ms); + } + .mu-reveal.is-in { opacity: 1; transform: none; } +} + +@media (prefers-reduced-motion: reduce) { + #view.mu-view-in { animation: none; } + .mu-reveal { opacity: 1; transform: none; transition: none; } + .mu-loadbar { display: none; } +} + +/* ========================================================= + Toast แจ้งอัปเดตเวอร์ชัน (สร้างจาก PwaBoot) + ========================================================= */ +.mu-update-toast { + position: fixed; + left: 50%; + bottom: calc(20px + env(safe-area-inset-bottom, 0px)); + z-index: 1300; + display: inline-flex; + align-items: center; + gap: 10px; + max-width: calc(100vw - 32px); + padding: 10px 16px; + border-radius: 999px; + background: var(--c-ink); + color: var(--c-surface); + font-size: .82rem; + font-weight: 600; + line-height: 1.35; + box-shadow: 0 10px 24px var(--c-shadow); + transform: translate(-50%, 12px); + opacity: 0; + pointer-events: none; + transition: opacity .25s ease, transform .25s ease; +} +.mu-update-toast.is-in { opacity: 1; transform: translate(-50%, 0); } +.mu-update-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: #b694f6; + flex: none; + animation: muUpdatePulse 1.1s ease-in-out infinite; +} +@keyframes muUpdatePulse { + 0%, 100% { opacity: .35; transform: scale(.85); } + 50% { opacity: 1; transform: scale(1); } +} +@media (prefers-reduced-motion: reduce) { + .mu-update-toast { transition: none; } + .mu-update-dot { animation: none; } +} diff --git a/frontend/src/styles/pages/stats.css b/frontend/src/styles/pages/stats.css new file mode 100644 index 0000000..127a3aa --- /dev/null +++ b/frontend/src/styles/pages/stats.css @@ -0,0 +1,137 @@ +/* Ported from web-at-transit-mock/ui/partials/stats.html — ใช้โทเคนของ target */ +.mu-page { background: linear-gradient(180deg, var(--c-surface) 0%, var(--c-bg) 100%); } +.st-wrap { max-width: 62rem; margin: 0 auto; padding: 32px 20px 64px; } +.st-hero { margin-bottom: 22px; } +.st-hero h1 { + margin: 0 0 8px; + font-size: clamp(1.5rem, 1.2rem + 1.4vw, 1.9rem); + color: var(--c-ink); + letter-spacing: -.01em; +} +.st-hero p { + margin: 0; + max-width: 62ch; + color: var(--c-ink-2); + font-size: .92rem; + line-height: 1.65; +} + +.st-kpis { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } +.st-kpi { + min-width: 0; + padding: 14px 16px; + border: 1px solid var(--c-border); + border-radius: var(--radius); + background: var(--c-surface); +} +.st-kpi b { + display: block; + font-size: 1.55rem; + line-height: 1.2; + color: var(--c-ink); + font-variant-numeric: tabular-nums; +} +.st-kpi span { + display: block; + margin-top: 4px; + font-size: .76rem; + font-weight: 700; + color: var(--c-ink-2); + letter-spacing: .01em; +} + +.st-card { + margin-top: 16px; + padding: 18px 20px; + border: 1px solid var(--c-border); + border-radius: var(--radius); + background: var(--c-surface); +} +.st-card h2 { margin: 0 0 4px; font-size: 1rem; color: var(--c-ink); } +.st-card .lead { margin: 0 0 14px; color: var(--c-ink-2); font-size: .84rem; line-height: 1.6; } +.st-grid2 { display: grid; gap: 16px; margin-top: 16px; } +.st-grid2 > .st-card { margin-top: 0; } + +/* กราฟแท่ง 14 วัน — CSS ล้วน */ +.st-chart { display: flex; align-items: flex-end; gap: 5px; height: 128px; padding-top: 10px; } +.st-bar { flex: 1 1 0; min-width: 0; display: flex; flex-direction: column; justify-content: flex-end; gap: 2px; } +.st-bar i, .st-bar u { display: block; border-radius: 4px 4px 0 0; min-height: 2px; } +.st-bar i { background: linear-gradient(180deg, #b694f6, var(--c-brand)); } +.st-bar u { background: var(--c-brand-soft); } +.st-bar em { + margin-top: 4px; + font-style: normal; + font-size: .6rem; + color: var(--c-ink-3); + text-align: center; + white-space: nowrap; +} +.st-legend { display: flex; flex-wrap: wrap; gap: 16px; margin-top: 12px; font-size: .76rem; color: var(--c-ink-2); } +.st-legend b { display: inline-block; width: 10px; height: 10px; margin-right: 6px; border-radius: 3px; vertical-align: -1px; } + +.st-table { width: 100%; border-collapse: collapse; font-size: .88rem; } +.st-table th { + padding: 0 8px 6px 0; + text-align: left; + font-size: .7rem; + font-weight: 800; + letter-spacing: .04em; + text-transform: uppercase; + color: var(--c-ink-3); + border-bottom: 1px solid var(--c-border); +} +.st-table td { padding: 8px 8px 8px 0; border-bottom: 1px solid var(--c-border-2); color: var(--c-ink); vertical-align: top; } +.st-table tr:last-child td { border-bottom: 0; } +.st-table .num { width: 3.5rem; text-align: right; font-variant-numeric: tabular-nums; font-weight: 800; } +.st-table .when { color: var(--c-ink-3); font-size: .74rem; white-space: nowrap; } +.st-table .term { font-weight: 700; word-break: break-word; } +.st-table a { color: var(--c-brand-ink); text-decoration: none; font-weight: 600; } +.st-table a:hover { text-decoration: underline; } + +.st-empty { margin: 0; padding: 14px 0 4px; color: var(--c-ink-3); font-size: .86rem; } + +.st-list { margin: 0 0 14px; padding-left: 1.15rem; color: var(--c-ink); font-size: .88rem; line-height: 1.75; } +.st-toggle { + display: flex; + gap: 10px; + align-items: flex-start; + padding: 12px 14px; + border: 1px solid var(--c-border); + border-radius: var(--radius); + background: var(--c-brand-soft); + font-size: .88rem; + color: var(--c-ink); + cursor: pointer; +} +.st-toggle input { width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--c-brand); flex: none; } +.st-toggle strong { display: block; margin-bottom: 2px; font-size: .9rem; color: var(--c-ink); } +.st-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; } +.st-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 40px; + padding: 9px 16px; + border: 1px solid var(--c-border); + border-radius: var(--radius); + background: var(--c-surface); + color: var(--c-brand-ink); + font: inherit; + font-size: .86rem; + font-weight: 700; + cursor: pointer; +} +.st-btn:hover { background: var(--c-surface-2); } +.st-btn.is-solid { background: var(--c-brand); border-color: var(--c-brand); color: var(--c-on-brand); } +.st-btn.is-solid:hover { background: #6a3fb0; } +.st-btn.is-danger { border-color: var(--c-border); color: var(--c-danger); } +.st-btn.is-danger:hover { background: var(--c-surface-2); } +.st-note { margin: 12px 0 0; font-size: .78rem; color: var(--c-ink-3); } +.st-status { margin: 10px 0 0; min-height: 18px; font-size: .82rem; color: var(--c-ok); } + +@media (min-width: 520px) { .st-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); } } +@media (min-width: 768px) { + .st-grid2 { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } + .st-wrap { padding: 40px 28px 72px; } +} diff --git a/frontend/src/styles/shell.css b/frontend/src/styles/shell.css index 89952f8..158b136 100644 --- a/frontend/src/styles/shell.css +++ b/frontend/src/styles/shell.css @@ -221,52 +221,8 @@ .mu-stat.tag-purple { background: var(--c-tint-purple); } .mu-stat.tag-mint { background: var(--c-tint-green); } - /* ===== Visitor counter (footer bottom bar) ===== */ + /* ===== Footer bottom bar ===== */ .mu-footer-bottom { display: flex; align-items: center; justify-content: center; gap: 14px; flex-wrap: wrap; } - .mu-visitor { - display: inline-flex; - align-items: center; - gap: 7px; - margin: 0; - padding: 5px 12px; - border-radius: var(--radius-pill); - background: rgba(255,255,255,.06); - border: 1px solid rgba(255,255,255,.1); - color: #b6bdda; - font-size: .78rem; - font-weight: 600; - letter-spacing: .01em; - line-height: 1; - } - .mu-visitor svg { width: 14px; height: 14px; color: var(--c-brand-ink); flex: none; } - .mu-visitor strong { color: #fff; font-weight: 700; font-variant-numeric: tabular-nums; } - /* ปุ่ม/ช่องรีเซ็ตผู้เข้าชม (ซ่อน — กดตัวเลข 5 ครั้ง) */ - #visitor-count { cursor: pointer; } - .mu-vreset { - position: fixed; inset: 0; z-index: 3000; display: flex; align-items: center; justify-content: center; - padding: 20px; background: rgba(15, 23, 42, .55); backdrop-filter: blur(3px); - } - .mu-vreset-card { - width: 100%; max-width: 340px; background: var(--c-surface); border-radius: var(--radius); padding: 20px; - box-shadow: 0 18px 50px rgba(15, 23, 42, .28); - } - .mu-vreset-card h4 { margin: 0 0 12px; font-size: 1rem; color: var(--c-ink); } - .mu-vreset-card label { display: block; font-size: 0.78rem; color: var(--c-ink-2); margin-bottom: 6px; } - .mu-vreset-card input { - width: 100%; box-sizing: border-box; padding: 10px 12px; font-size: .95rem; - border: 1px solid var(--c-border); border-radius: var(--radius); color: var(--c-ink); background: var(--c-surface-2); - } - .mu-vreset-card input:focus { outline: 2px solid var(--c-brand-ink); outline-offset: 2px; border-color: #7a4cc0; } - .mu-vreset-msg { margin: 10px 0 0; min-height: 18px; font-size: 0.78rem; color: var(--c-danger); } - .mu-vreset-msg.is-ok { color: var(--c-ok); } - .mu-vreset-row { display: flex; gap: 8px; margin-top: 16px; justify-content: flex-end; } - .mu-vreset-row button { - padding: 9px 16px; font-size: .85rem; font-weight: 700; border-radius: var(--radius); cursor: pointer; - border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-info); - } - .mu-vreset-row button:hover { background: var(--c-surface-2); } - .mu-vreset-ok { border-color: #7a4cc0 !important; background: var(--c-brand) !important; color: #fff !important; } - .mu-vreset-ok:hover { background: #6a3fb0 !important; } /* ===== Sponsor marquee (between hero and main) ===== */ .mu-sponsor-marquee { padding: 26px 0 6px; background: var(--c-surface); border-bottom: 1px solid var(--c-border); }