Files
Bkk1234 c00bc62272 feat: hobby project landing page (PWA + SPA) with admin backoffice
- landing page: welcome hero, live search, project card grid (10 projects from owner list)
- warm brown/white theme (fastwork-inspired layout), embedded K2D Thai font
- PWA: manifest, PIL-generated icons, versioned service worker with auto-update
- backoffice at #/admin: edit name/description/url, reorder, delete, publish
- server/publish.mjs: zero-dependency static server + PUT api/projects with
  validation, JSON write, git commit and push; loopback-only unless ADMIN_TOKEN
- docs: README, DESIGN.md (color/type contract), AGENTS.md
2026-11-19 01:03:13 +07:00

65 lines
1.9 KiB
JavaScript

/* router.js — hash router จิ๋ว (ไม่มี build step, ใช้ได้กับ static hosting ทุกแบบ) */
const listeners = new Set();
let routes = {};
let fallback = null;
let currentPath = null;
export function defineRoutes(map, fallbackRoute) {
routes = map;
fallback = fallbackRoute || Object.keys(map)[0];
}
export function currentRoute() {
return parseHash();
}
function parseHash() {
const raw = window.location.hash.replace(/^#/, "");
const path = raw.split("?")[0] || "/";
const query = new URLSearchParams(raw.split("?")[1] || "");
return { path: path.startsWith("/") ? path : `/${path}`, query };
}
export function navigate(path) {
if (window.location.hash === `#${path}`) {
handleRoute(true);
return;
}
window.location.hash = `#${path}`;
}
export function onRouteChange(callback) {
listeners.add(callback);
return () => listeners.delete(callback);
}
function handleRoute(force = false) {
const route = parseHash();
const key = route.path;
const resolved = routes[key] ? key : fallback;
if (!routes[resolved]) return;
if (!force && currentPath === resolved) return;
currentPath = resolved;
const view = routes[resolved];
listeners.forEach((fn) => fn({ ...route, path: resolved, view }));
}
export function startRouter() {
window.addEventListener("hashchange", () => handleRoute());
if (!window.location.hash) {
window.location.replace("#/");
}
handleRoute(true);
}
export function markActiveNav(path) {
document.querySelectorAll("[data-nav]").forEach((link) => {
const target = link.getAttribute("data-nav");
const isHome = path === "/" && (target === "home" || target === "home-link");
const isAdmin = path === "/admin" && target.startsWith("admin");
if (isHome || isAdmin) link.setAttribute("aria-current", "page");
else link.removeAttribute("aria-current");
});
}