Files

206 lines
8.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 도움말의 제목·본문에서 검색하고 해당 소제목으로 이동한다. DB/API 불필요. */
(function () {
"use strict";
const root = document.querySelector(".pjh");
if (!root) return;
const input = document.getElementById("pjh-query");
const form = document.getElementById("pjh-search-form");
const results = document.getElementById("pjh-results");
const status = document.getElementById("pjh-search-status");
const clear = document.getElementById("pjh-search-clear");
const chapters = Array.from(root.querySelectorAll(".pjh-sec"));
const index = [];
let composing = false;
function plain(node) {
const copy = node.cloneNode(true);
copy.querySelectorAll(".pjh-num, .material-symbols-outlined").forEach(function (n) { n.remove(); });
return copy.textContent.replace(/\s+/g, " ").trim();
}
// 본문 자체에서 색인을 만든다. 도움말을 고치면 검색 결과도 함께 바뀐다.
chapters.forEach(function (chapter) {
const title = plain(chapter.querySelector("h2"));
let block = { chapter: chapter, title: title, heading: chapter.querySelector("h2"), nodes: [], order: index.length };
block.heading.id = block.heading.id || chapter.id + "-intro";
let ordinal = 0;
function finish() {
block.text = block.nodes.map(plain).join(" ");
block.search = (block.title + " " + block.text).toLowerCase();
index.push(block);
}
Array.from(chapter.children).forEach(function (node) {
if (node.tagName === "H2") return;
if (node.tagName === "H3") {
finish();
ordinal++;
node.id = node.id || chapter.id + "-" + ordinal;
block = { chapter: chapter, title: title + " › " + plain(node), heading: node, nodes: [], order: index.length };
} else block.nodes.push(node);
});
finish();
});
function words(query) {
return Array.from(new Set(query.trim().toLowerCase().split(/\s+/).filter(Boolean)));
}
// 검색어는 HTML이나 정규식으로 해석하지 않는다.
function marked(text, terms) {
const fragment = document.createDocumentFragment();
const lower = text.toLowerCase();
let pos = 0;
while (pos < text.length) {
let start = -1, length = 0;
terms.forEach(function (term) {
const found = lower.indexOf(term, pos);
if (found !== -1 && (start === -1 || found < start || (found === start && term.length > length))) {
start = found; length = term.length;
}
});
if (start === -1) { fragment.appendChild(document.createTextNode(text.slice(pos))); break; }
fragment.appendChild(document.createTextNode(text.slice(pos, start)));
const mark = document.createElement("mark");
mark.className = "pjh-match";
mark.textContent = text.slice(start, start + length);
fragment.appendChild(mark);
pos = start + length;
}
return fragment;
}
function highlight(terms) {
chapters.forEach(function (chapter) {
chapter.querySelectorAll("mark.pjh-match").forEach(function (mark) {
mark.replaceWith(document.createTextNode(mark.textContent));
});
chapter.normalize();
if (!terms.length) return;
const walker = document.createTreeWalker(chapter, NodeFilter.SHOW_TEXT);
const nodes = [];
let node;
while ((node = walker.nextNode())) {
if (!node.parentElement.closest(".material-symbols-outlined, .pjh-num") &&
terms.some(function (term) { return node.nodeValue.toLowerCase().includes(term); })) nodes.push(node);
}
nodes.forEach(function (n) { n.replaceWith(marked(n.nodeValue, terms)); });
});
}
function snippet(text, terms) {
const lower = text.toLowerCase();
const hits = terms.map(function (term) { return lower.indexOf(term); }).filter(function (n) { return n >= 0; });
const start = hits.length ? Math.max(0, Math.min.apply(null, hits) - 35) : 0;
return (start ? "…" : "") + text.slice(start, start + 155) + (text.length > start + 155 ? "…" : "");
}
function saveQuery(query) {
const url = new URL(window.location.href);
if (query.trim()) url.searchParams.set("q", query.trim());
else url.searchParams.delete("q");
window.history.replaceState(null, "", url);
}
function search(updateUrl) {
const query = input.value.slice(0, 160);
const terms = words(query);
results.replaceChildren();
clear.hidden = !query;
results.hidden = !terms.length;
highlight(terms);
if (updateUrl) saveQuery(query);
if (!terms.length) { status.textContent = ""; return; }
const matches = index.filter(function (entry) {
return terms.every(function (term) { return entry.search.includes(term); });
});
// 제목에 모든 단어가 있으면 먼저, 나머지는 문서 순서대로.
matches.sort(function (a, b) {
function score(entry) { return terms.every(function (term) { return entry.title.toLowerCase().includes(term); }) ? 1 : 0; }
return score(b) - score(a) || a.order - b.order;
});
status.textContent = matches.length
? "검색 결과 " + matches.length + "개 · 결과를 누르거나 Enter로 첫 설명에 이동하세요."
: "검색 결과가 없습니다. 다른 단어를 쓰거나 검색어를 줄여 보세요.";
matches.forEach(function (entry) {
const li = document.createElement("li");
const link = document.createElement("a");
link.href = "#" + entry.heading.id;
const title = document.createElement("strong");
title.appendChild(marked(entry.title, terms));
const preview = document.createElement("span");
preview.appendChild(marked(snippet(entry.text, terms), terms));
link.append(title, preview);
li.appendChild(link);
results.appendChild(li);
});
}
const tocLinks = Array.from(root.querySelectorAll(".pjh-toc a"));
function activate(chapter) {
tocLinks.forEach(function (link) {
const active = link.getAttribute("href") === "#" + chapter.id;
link.classList.toggle("is-active", active);
if (active) link.setAttribute("aria-current", "location");
else link.removeAttribute("aria-current");
});
}
function jump(id) {
const target = document.getElementById(id);
if (!target || !root.contains(target)) return;
target.setAttribute("tabindex", "-1");
target.focus({ preventScroll: true });
target.scrollIntoView({ block: "start" });
const chapter = target.closest(".pjh-sec");
if (chapter) activate(chapter);
}
root.addEventListener("click", function (event) {
const link = event.target.closest('a[href^="#"]');
if (!link || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
const id = link.getAttribute("href").slice(1);
if (!document.getElementById(id)) return;
event.preventDefault();
if (window.location.hash !== "#" + id) window.history.pushState(null, "", "#" + id);
jump(id);
});
input.maxLength = 160;
input.addEventListener("compositionstart", function () { composing = true; });
input.addEventListener("compositionend", function () { composing = false; search(true); });
input.addEventListener("input", function () { if (!composing) search(true); });
form.addEventListener("submit", function (event) {
event.preventDefault();
if (composing) return;
search(true);
const first = results.querySelector("a");
if (first) first.click();
});
function reset() { input.value = ""; search(true); input.focus(); }
clear.addEventListener("click", reset);
input.addEventListener("keydown", function (event) {
if (composing || event.isComposing || event.keyCode === 229) return;
if (event.key === "Escape") { event.preventDefault(); reset(); }
});
document.addEventListener("keydown", function (event) {
if (event.key !== "/" || event.isComposing || event.ctrlKey || event.metaKey || event.altKey ||
event.target.closest("input, textarea, select, [contenteditable='true']")) return;
event.preventDefault();
input.focus();
input.scrollIntoView({ block: "center" });
});
function restore() {
input.value = (new URL(window.location.href).searchParams.get("q") || "").slice(0, 160);
search(false);
if (window.location.hash) jump(window.location.hash.slice(1));
}
window.addEventListener("popstate", restore);
window.addEventListener("hashchange", function () { if (window.location.hash) jump(window.location.hash.slice(1)); });
document.getElementById("pjh-search").hidden = false;
restore();
if ("IntersectionObserver" in window) {
const observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) { if (entry.isIntersecting) activate(entry.target); });
}, { rootMargin: "-10% 0px -75% 0px" });
chapters.forEach(function (chapter) { observer.observe(chapter); });
}
})();