Files
Bkk1234 4f74a509d5 intro-irre: แปลงตำราวิศวกรรมชลประทานเบื้องต้นเป็นเว็บเอกสาร 10 บท
- tools/extract.py: PDF 300 หน้า -> extracted/pages.json + crop ภาพ/ตาราง/สมการ 423 รูป
  (ถอด PUA วรรณยุกต์ไทย, รวมสระอำ, แยกหัวข้อที่ระดับ span)
- tools/build.py: generator หน้า docs แบบ static (สารบัญซ้าย/เนื้อหา/ในหน้านี้)
- index.html + chapters/ch01..10.html + css/docs.css + js/docs.js
  (ธีม K2D, ค้นหาเต็มเล่มผ่าน data/search.json, dark mode, drawer มือถือ)
- README.md: วิธี build และข้อจำกัดที่รู้อยู่
2026-11-19 01:34:49 +07:00

219 lines
7.7 KiB
JavaScript

/* docs.js — theme, sidebar drawer, search modal, scrollspy. No dependencies. */
(() => {
"use strict";
const root = document.body.dataset.root || "";
const html = document.documentElement;
/* ------------------------------------------------------------------ theme */
const THEME_KEY = "irre-docs-theme";
const stored = localStorage.getItem(THEME_KEY);
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
const initial = stored || (prefersDark ? "dark" : "light");
applyTheme(initial);
function applyTheme(mode) {
if (mode === "dark") html.setAttribute("data-theme", "dark");
else html.removeAttribute("data-theme");
const btn = document.getElementById("themeToggle");
if (btn) btn.setAttribute("aria-pressed", String(mode === "dark"));
const meta = document.querySelector('meta[name="theme-color"]');
if (meta) meta.setAttribute("content", mode === "dark" ? "#0b1220" : "#1e3a8a");
}
const themeBtn = document.getElementById("themeToggle");
if (themeBtn) {
themeBtn.addEventListener("click", () => {
const next = html.getAttribute("data-theme") === "dark" ? "light" : "dark";
localStorage.setItem(THEME_KEY, next);
applyTheme(next);
});
}
/* -------------------------------------------------------- sidebar drawer */
const side = document.getElementById("side");
const navToggle = document.getElementById("navToggle");
const scrim = document.getElementById("scrim");
function closeNav() {
if (!side) return;
side.classList.remove("is-open");
if (navToggle) navToggle.setAttribute("aria-expanded", "false");
if (scrim && !document.getElementById("searchModal")?.hidden) return;
if (scrim) scrim.hidden = true;
}
function openNav() {
if (!side) return;
side.classList.add("is-open");
if (navToggle) navToggle.setAttribute("aria-expanded", "true");
if (scrim) scrim.hidden = false;
}
if (navToggle) {
navToggle.addEventListener("click", () => {
side?.classList.contains("is-open") ? closeNav() : openNav();
});
}
if (scrim) scrim.addEventListener("click", () => { closeNav(); closeSearch(); });
/* ----------------------------------------------------------- scrollspy */
const tocLinks = [...document.querySelectorAll(".page-toc a")];
const targets = tocLinks
.map((a) => document.querySelector(a.getAttribute("href")))
.filter(Boolean);
if (targets.length && "IntersectionObserver" in window) {
const visible = new Map();
const spy = new IntersectionObserver(
(entries) => {
entries.forEach((e) => {
if (e.isIntersecting) visible.set(e.target.id, e.boundingClientRect.top);
else visible.delete(e.target.id);
});
if (!visible.size) return;
const [topId] = [...visible.entries()].sort((a, b) => a[1] - b[1])[0];
tocLinks.forEach((a) =>
a.classList.toggle("is-active", a.getAttribute("href") === `#${topId}`)
);
},
{ rootMargin: "-72px 0px -70% 0px", threshold: 0 }
);
targets.forEach((t) => spy.observe(t));
}
/* --------------------------------------------------------------- search */
const modal = document.getElementById("searchModal");
const input = document.getElementById("searchInput");
const results = document.getElementById("searchResults");
const scrimEl = document.getElementById("scrim");
let index = null;
let loading = null;
let active = -1;
let hits = [];
function openSearch() {
if (!modal) return;
modal.hidden = false;
if (scrimEl) scrimEl.hidden = false;
input.value = "";
render([]);
input.focus();
loadIndex();
}
function closeSearch() {
if (!modal || modal.hidden) return;
modal.hidden = true;
if (scrimEl && !side?.classList.contains("is-open")) scrimEl.hidden = true;
active = -1;
}
function loadIndex() {
if (index || loading) return loading;
loading = fetch(`${root}data/search.json`)
.then((r) => r.json())
.then((data) => { index = data; return data; })
.catch(() => { index = []; return []; });
return loading;
}
function esc(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
function highlight(text, q) {
const raw = esc(text);
if (!q) return raw;
const safeQ = esc(q).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return raw.replace(new RegExp(safeQ, "gi"), (m) => `<mark>${m}</mark>`);
}
function render(list) {
active = -1;
hits = list;
if (!list.length) {
results.innerHTML = `<p class="search-hint">${
input.value.trim().length < 2
? "พิมพ์อย่างน้อย 2 ตัวอักษร · ค้นทั้งเล่ม 10 บท"
: "ไม่พบคำที่ค้นหา ลองใช้คำสั้นลงหรือคำอื่น"
}</p>`;
return;
}
results.innerHTML = list
.map(
(h, i) => `<a class="result" href="${root}${h.u}" data-i="${i}">
<span class="r-crumb">${esc(h.c)} · น. ${h.p}</span>
<span class="r-title">${highlight(h.s, input.value.trim())}</span>
<span class="r-text">${highlight(h.x, input.value.trim())}</span>
</a>`
)
.join("");
}
function search(q) {
q = q.trim().toLowerCase();
if (!index || q.length < 2) return render([]);
const scored = [];
for (const row of index) {
const title = row.s.toLowerCase();
const body = row.x.toLowerCase();
const ti = title.indexOf(q);
const bi = body.indexOf(q);
if (ti < 0 && bi < 0) continue;
scored.push({ row, score: (ti >= 0 ? 1000 - ti : 0) + (bi >= 0 ? 100 - Math.min(bi, 90) : 0) });
}
scored.sort((a, b) => b.score - a.score);
render(scored.slice(0, 24).map((s) => s.row));
}
let debounce = 0;
input?.addEventListener("input", (e) => {
clearTimeout(debounce);
const q = e.target.value;
debounce = setTimeout(() => search(q), 90);
});
input?.addEventListener("keydown", (e) => {
const nodes = [...results.querySelectorAll(".result")];
if (e.key === "ArrowDown") {
e.preventDefault();
active = Math.min(active + 1, nodes.length - 1);
nodes.forEach((n, i) => n.classList.toggle("is-cursor", i === active));
nodes[active]?.scrollIntoView({ block: "nearest" });
nodes[active]?.focus({ preventScroll: true });
} else if (e.key === "ArrowUp") {
e.preventDefault();
active = Math.max(active - 1, 0);
nodes.forEach((n, i) => n.classList.toggle("is-cursor", i === active));
nodes[active]?.focus({ preventScroll: true });
} else if (e.key === "Enter") {
const first = nodes[Math.max(active, 0)];
if (first) { e.preventDefault(); window.location.href = first.getAttribute("href"); }
} else if (e.key === "Escape") {
closeSearch();
}
});
document.getElementById("searchOpen")?.addEventListener("click", openSearch);
document.getElementById("searchOpenHero")?.addEventListener("click", openSearch);
document.getElementById("searchClose")?.addEventListener("click", closeSearch);
document.addEventListener("keydown", (e) => {
const typing = /^(input|textarea|select)$/i.test(document.activeElement?.tagName || "");
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
modal?.hidden ? openSearch() : closeSearch();
} else if (e.key === "/" && !typing) {
e.preventDefault();
openSearch();
} else if (e.key === "Escape") {
closeSearch();
closeNav();
}
});
/* clicking a sidebar link on mobile closes the drawer */
side?.querySelectorAll("a").forEach((a) => a.addEventListener("click", closeNav));
})();