feat(site): upgrade documentation reader with full-book handbooks and search

Compile unabridged bilingual Developer Handbook and Mod Authoring Handbook from repository Markdown with nested list and ordered-list continuation fixes, fix primary button text contrast inside doc sections, and add full-book search, expand-all Ctrl+F mode, active chapter sub-TOC, pushState history, and local file:// link fallback.
This commit is contained in:
N0VAN0M4LY committed 2026-12-03 11:26:11 +08:00
1 parent c265ccbb61
commit fa05f36584
5 files changed
+3794 -594

No files matched your search

+298 -36
View File
@@ -1,22 +1,66 @@
/* ============================================================
* WTOffline Project Homepage & All-Releases Script
* Classic non-module script so opening HTML files directly via
* file:// works without a local server.
* Handles: language toggle, color theme toggle, opening shutter,
* scroll reveal, pointer spotlight, sticky header, internal page
* transition, and live release catalog rendering.
* WTOffline Website & Documentation Reader Script
* Zero-dependency classic script supporting:
* - Bilingual toggle (zh-CN / EN) and dark/light theme toggle
* - Rotating public-domain daylight military backdrop
* - Smooth internal navigation (with automatic file:// fallback
* so local preview clicks on /dev-docs, /mod-docs, /releases work)
* - Multi-chapter documentation reader with pushState history,
* sub-heading deep links, active chapter sub-TOC, live full-book
* search, expand-all mode (for native Ctrl+F), and clipboard fallback
* - Dynamic release catalog rendering (R2 primary -> GitHub fallback)
* ============================================================ */
(function () {
'use strict';
// Primary release feed is served via edge object storage to keep origin server load low;
// falls back to GitHub Releases API when unavailable.
var PRIMARY_FEED = 'https://dl.wto-project.net/releases';
var FALLBACK_FEED = 'https://api.github.com/repos/N0VAN0M4LY/WT-Offline/releases?per_page=30';
var GH_RELEASES = 'https://github.com/N0VAN0M4LY/WT-Offline/releases';
var SUN_SVG =
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
'<circle cx="12" cy="12" r="4"/>' +
'<path d="M12 2.5v2.2M12 19.3v2.2M21.5 12h-2.2M4.7 12H2.5M18.7 5.3l-1.5 1.5M6.8 17.2l-1.5 1.5M18.7 18.7l-1.5-1.5M6.8 6.8 5.3 5.3"/>' +
'</svg>';
var MOON_SVG =
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M21 12.8A8.5 8.5 0 1 1 11.2 3a6.8 6.8 0 0 0 9.8 9.8z"/>' +
'</svg>';
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var pageKind = document.body.getAttribute('data-page') || 'home';
var docRefreshHook = null;
// ---- Copy text helper with non-HTTPS / file:// fallback ----
function copyText(text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(text).catch(function () {
return legacyCopy(text);
});
}
return legacyCopy(text);
}
function legacyCopy(text) {
return new Promise(function (resolve, reject) {
try {
var ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.opacity = '0';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.select();
var ok = document.execCommand('copy');
document.body.removeChild(ta);
if (ok) resolve();
else reject(new Error('copy failed'));
} catch (err) {
reject(err);
}
});
}
// ---- Language (zh / en) ----
var currentLang = 'zh';
@@ -37,6 +81,7 @@
currentLang = currentLang === 'zh' ? 'en' : 'zh';
applyLang(currentLang);
try { localStorage.setItem('wto.site.lang', currentLang); } catch (err) { /* noop */ }
if (docRefreshHook) docRefreshHook();
});
})();
@@ -60,6 +105,10 @@
? 'WTOffline · 战争雷霆本地单机离线项目'
: 'WTOffline · Local Single-Player Offline Project for War Thunder';
}
var searchInput = document.querySelector('[data-doc-search]');
if (searchInput) {
searchInput.placeholder = lang === 'zh' ? '搜索全书关键词…' : 'Search all chapters…';
}
}
// ---- Color mode (dark default / light optional) ----
@@ -68,13 +117,20 @@
var saved = null;
try { saved = localStorage.getItem('wto.site.mode'); } catch (e) { /* noop */ }
var mode = saved === 'light' || saved === 'dark' ? saved : 'dark';
root.setAttribute('data-mode', mode);
setMode(mode);
function setMode(m) {
root.setAttribute('data-mode', m);
document.querySelectorAll('[data-mode-toggle]').forEach(function (btn) {
btn.innerHTML = m === 'dark' ? SUN_SVG : MOON_SVG;
});
}
document.addEventListener('click', function (e) {
var btn = e.target.closest('[data-mode-toggle]');
if (!btn) return;
var next = root.getAttribute('data-mode') === 'dark' ? 'light' : 'dark';
root.setAttribute('data-mode', next);
setMode(next);
try { localStorage.setItem('wto.site.mode', next); } catch (err) { /* noop */ }
});
})();
@@ -128,7 +184,6 @@
img.src = slides[index];
}
// Activate initial slide on next frame so Ken Burns scale eases in
requestAnimationFrame(function () {
nodes[0].classList.add('active');
});
@@ -189,53 +244,260 @@
window.addEventListener('scroll', update, { passive: true });
})();
// ---- Resolve extensionless routes cleanly when previewed via file:// ----
function resolveInternalHref(href) {
if (location.protocol !== 'file:') return href;
var m = /^\/(|releases|dev-docs|mod-docs)(#.*)?$/.exec(href);
if (!m) return href;
var page = m[1] ? m[1] + '.html' : 'index.html';
return page + (m[2] || '');
}
// ---- Smooth internal page navigation ----
(function initLeaveTransition() {
if (reduce) return;
if (document.startViewTransition) return;
document.addEventListener('click', function (e) {
var a = e.target.closest('a');
if (!a) return;
if (!a || a.hasAttribute('data-chapter') || a.hasAttribute('data-doc-jump')) return;
var href = a.getAttribute('href') || '';
if (a.target === '_blank' || a.hasAttribute('download')) return;
if (!href || href.charAt(0) === '#' || /^(https?:)?\/\//.test(href)) return;
if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
var resolved = resolveInternalHref(href);
if (reduce || (document.startViewTransition && location.protocol !== 'file:')) {
if (resolved !== href) {
e.preventDefault();
location.href = resolved;
}
return;
}
e.preventDefault();
document.body.classList.add('leaving');
setTimeout(function () { location.href = href; }, 260);
setTimeout(function () { location.href = resolved; }, 240);
});
})();
// ---- Documentation TOC active section highlight & code copy ----
(function initDocHelpers() {
var tocLinks = document.querySelectorAll('.doc-toc a[href^="#"]');
if (tocLinks.length && 'IntersectionObserver' in window) {
var sections = [];
tocLinks.forEach(function (link) {
var target = document.querySelector(link.getAttribute('href'));
if (target) sections.push({ el: target, link: link });
// ---- Multi-chapter documentation reader, sub-TOC, search & expand-all ----
(function initDocReader() {
var chapters = Array.prototype.slice.call(document.querySelectorAll('.doc-chapter'));
var chapterLinks = Array.prototype.slice.call(document.querySelectorAll('.doc-toc a[data-chapter]'));
if (chapters.length && chapterLinks.length) {
var activeChapterId = chapters[0].id;
var subTocEl = document.createElement('div');
subTocEl.className = 'doc-subtoc';
function rebuildSubToc() {
if (subTocEl.parentNode) subTocEl.parentNode.removeChild(subTocEl);
subTocEl.innerHTML = '';
if (document.body.classList.contains('doc-expand-all')) return;
var activeChap = document.getElementById(activeChapterId);
var activeLink = chapterLinks.filter(function (a) {
return a.getAttribute('data-chapter') === activeChapterId;
})[0];
if (!activeChap || !activeLink) return;
var lang = document.body.getAttribute('data-lang') || 'zh';
var scope = activeChap.querySelector('.lang-' + lang) || activeChap;
var headings = scope.querySelectorAll('h3[id]');
if (!headings.length) return;
headings.forEach(function (h) {
var sub = document.createElement('a');
sub.href = '#' + h.id;
sub.setAttribute('data-doc-jump', h.id);
sub.textContent = h.textContent || '';
subTocEl.appendChild(sub);
});
activeLink.insertAdjacentElement('afterend', subTocEl);
}
function findChapterContaining(targetId) {
if (!targetId) return null;
var direct = chapters.filter(function (c) { return c.id === targetId; })[0];
if (direct) return { chapter: direct, anchor: null };
var el = document.getElementById(targetId);
if (!el) return null;
var parentChap = el.closest('.doc-chapter');
return parentChap ? { chapter: parentChap, anchor: el } : null;
}
function activateTarget(rawId, scrollBehavior, historyMode) {
var resolved = findChapterContaining(rawId) || { chapter: chapters[0], anchor: null };
activeChapterId = resolved.chapter.id;
chapters.forEach(function (c) {
c.classList.toggle('active', c.id === activeChapterId);
});
chapterLinks.forEach(function (a) {
var on = a.getAttribute('data-chapter') === activeChapterId;
a.classList.toggle('active', on);
a.setAttribute('aria-current', on ? 'page' : 'false');
});
rebuildSubToc();
var hashVal = resolved.anchor ? '#' + resolved.anchor.id : '#' + activeChapterId;
if (historyMode === 'push' && history.pushState && location.hash !== hashVal) {
history.pushState(null, '', hashVal);
} else if (historyMode === 'replace' && history.replaceState) {
history.replaceState(null, '', hashVal);
}
if (scrollBehavior) {
requestAnimationFrame(function () {
if (resolved.anchor) {
resolved.anchor.scrollIntoView({ behavior: reduce ? 'auto' : 'smooth', block: 'start' });
} else {
var layout = document.querySelector('.doc-layout');
if (layout) {
var top = layout.getBoundingClientRect().top + window.scrollY - 76;
window.scrollTo({ top: Math.max(0, top), behavior: reduce ? 'auto' : 'smooth' });
}
}
});
}
}
var initialHash = decodeURIComponent((location.hash || '').replace(/^#/, ''));
activateTarget(initialHash || chapters[0].id, Boolean(initialHash && initialHash !== chapters[0].id), 'none');
document.addEventListener('click', function (e) {
var chapBtn = e.target.closest('[data-chapter]');
if (chapBtn) {
e.preventDefault();
var cid = chapBtn.getAttribute('data-chapter');
if (cid) activateTarget(cid, true, 'push');
return;
}
var jumpBtn = e.target.closest('[data-doc-jump]');
if (jumpBtn) {
e.preventDefault();
var jid = jumpBtn.getAttribute('data-doc-jump');
var resultsBox = document.querySelector('.doc-search-results');
if (resultsBox) resultsBox.classList.remove('open');
if (jid) activateTarget(jid, true, 'push');
return;
}
// Intercept internal #anchor links inside doc body
var inDocLink = e.target.closest('.doc-body a[href^="#"]');
if (inDocLink) {
var hid = decodeURIComponent((inDocLink.getAttribute('href') || '').slice(1));
if (hid && findChapterContaining(hid)) {
e.preventDefault();
activateTarget(hid, true, 'push');
}
return;
}
var expandBtn = e.target.closest('[data-expand-all]');
if (expandBtn) {
var expanded = document.body.classList.toggle('doc-expand-all');
expandBtn.classList.toggle('active', expanded);
expandBtn.setAttribute('aria-pressed', expanded ? 'true' : 'false');
rebuildSubToc();
}
});
if (sections.length) {
sections[0].link.classList.add('active');
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (!entry.isIntersecting) return;
sections.forEach(function (s) {
s.link.classList.toggle('active', s.el === entry.target);
window.addEventListener('popstate', function () {
var h = decodeURIComponent((location.hash || '').replace(/^#/, ''));
activateTarget(h || chapters[0].id, true, 'none');
});
// Full-book instant search
var searchInput = document.querySelector('[data-doc-search]');
var resultsBox = document.querySelector('.doc-search-results');
function runSearch() {
if (!searchInput || !resultsBox) return;
var q = (searchInput.value || '').trim().toLowerCase();
if (!q) {
resultsBox.classList.remove('open');
resultsBox.innerHTML = '';
return;
}
var lang = document.body.getAttribute('data-lang') || 'zh';
var hits = [];
chapters.forEach(function (chap) {
var linkEl = chapterLinks.filter(function (a) { return a.getAttribute('data-chapter') === chap.id; })[0];
var chapTitle = linkEl ? (linkEl.querySelector('.lang-' + lang) || linkEl).textContent : chap.id;
var scope = chap.querySelector('.lang-' + lang) || chap;
var blocks = scope.querySelectorAll('h2, h3, h4, h5, p, li, td, pre');
var lastHeadingId = chap.id;
var lastHeadingTitle = chapTitle;
blocks.forEach(function (node) {
if (/^H[2-5]$/.test(node.tagName)) {
if (node.id) lastHeadingId = node.id;
lastHeadingTitle = node.textContent || chapTitle;
}
if (hits.length >= 12) return;
var txt = (node.textContent || '').replace(/\s+/g, ' ').trim();
var pos = txt.toLowerCase().indexOf(q);
if (pos === -1) return;
// Deduplicate consecutive hits pointing to the same target anchor
if (hits.length && hits[hits.length - 1].targetId === lastHeadingId) return;
var start = Math.max(0, pos - 24);
var snip = (start > 0 ? '…' : '') + txt.slice(start, pos + q.length + 46) + (pos + q.length + 46 < txt.length ? '…' : '');
hits.push({
targetId: lastHeadingId,
chapTitle: chapTitle,
secTitle: lastHeadingTitle,
snippet: snip
});
});
}, { rootMargin: '-18% 0px -68% 0px' });
sections.forEach(function (s) { io.observe(s.el); });
});
if (!hits.length) {
resultsBox.innerHTML = '<div class="doc-search-empty">' +
(lang === 'zh' ? '未找到匹配内容' : 'No matching sections found') +
'</div>';
} else {
resultsBox.innerHTML = hits.map(function (h) {
return '<a class="doc-search-item" href="#' + esc(h.targetId) + '" data-doc-jump="' + esc(h.targetId) + '">' +
'<span class="doc-search-item-chap">' + esc(h.chapTitle) + '</span>' +
'<span class="doc-search-item-head">' + esc(h.secTitle) + '</span>' +
'<span class="doc-search-item-snip">' + esc(h.snippet) + '</span>' +
'</a>';
}).join('');
}
resultsBox.classList.add('open');
}
if (searchInput && resultsBox) {
searchInput.addEventListener('input', runSearch);
searchInput.addEventListener('focus', function () {
if ((searchInput.value || '').trim()) runSearch();
});
document.addEventListener('click', function (e) {
if (!e.target.closest('.doc-search')) {
resultsBox.classList.remove('open');
}
});
}
docRefreshHook = function () {
applyLang(currentLang);
rebuildSubToc();
if (searchInput && (searchInput.value || '').trim()) runSearch();
};
}
// Code block copy button
document.addEventListener('click', function (e) {
var btn = e.target.closest('[data-copy-code]');
if (!btn || !navigator.clipboard) return;
if (!btn) return;
var box = btn.closest('.doc-pre');
var codeEl = box && box.querySelector('pre code');
if (!codeEl) return;
navigator.clipboard.writeText(codeEl.textContent || '').then(function () {
var lang = document.body.getAttribute('data-lang') || 'zh';
var scoped = codeEl.querySelector('.lang-' + lang);
var text = (scoped || codeEl).textContent || '';
copyText(text).then(function () {
btn.innerHTML = '<span class="lang-zh">已复制</span><span class="lang-en">Copied</span>';
setTimeout(function () {
btn.innerHTML = '<span class="lang-zh">复制</span><span class="lang-en">Copy</span>';
@@ -606,9 +868,9 @@
}
var copyBtn = e.target.closest('[data-copy]');
if (copyBtn && navigator.clipboard) {
if (copyBtn) {
var val = copyBtn.getAttribute('data-copy') || '';
navigator.clipboard.writeText(val).then(function () {
copyText(val).then(function () {
copyBtn.innerHTML = '<span class="lang-zh">已复制</span><span class="lang-en">Copied</span>';
setTimeout(function () {
copyBtn.innerHTML = '<span class="lang-zh">复制</span><span class="lang-en">Copy</span>';