/* ============================================================ * 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'; 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 = ''; var MOON_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'; (function initLang() { var saved = null; try { saved = localStorage.getItem('wto.site.lang'); } catch (e) { /* noop */ } if (saved === 'zh' || saved === 'en') { currentLang = saved; } else { var navLang = (navigator.language || '').toLowerCase(); currentLang = navLang.indexOf('zh') === 0 ? 'zh' : 'en'; } applyLang(currentLang); document.addEventListener('click', function (e) { var btn = e.target.closest('[data-lang-toggle]'); if (!btn) return; currentLang = currentLang === 'zh' ? 'en' : 'zh'; applyLang(currentLang); try { localStorage.setItem('wto.site.lang', currentLang); } catch (err) { /* noop */ } if (docRefreshHook) docRefreshHook(); }); })(); function applyLang(lang) { document.body.setAttribute('data-lang', lang); document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'; if (pageKind === 'releases') { document.title = lang === 'zh' ? 'WTOffline · 全部版本下载' : 'WTOffline · All Releases'; } else if (pageKind === 'dev-docs') { document.title = lang === 'zh' ? 'WTOffline · 开发者文档与 PR 规范' : 'WTOffline · Developer Docs & PR Standards'; } else if (pageKind === 'mod-docs') { document.title = lang === 'zh' ? 'WTOffline · 模组制作文档' : 'WTOffline · Mod Authoring Documentation'; } else { document.title = lang === 'zh' ? '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) ---- (function initTheme() { var root = document.documentElement; var saved = null; try { saved = localStorage.getItem('wto.site.mode'); } catch (e) { /* noop */ } var mode = saved === 'light' || saved === 'dark' ? saved : 'dark'; 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'; setMode(next); try { localStorage.setItem('wto.site.mode', next); } catch (err) { /* noop */ } }); })(); // ---- Opening shutter cleanup ---- (function initShutter() { var el = document.getElementById('blink'); if (!el) return; if (reduce) { el.remove(); return; } el.addEventListener('animationend', function () { el.remove(); }); setTimeout(function () { if (el.parentNode) el.remove(); }, 1500); })(); // ---- Rotating public-domain military backdrop (underneath .grid) ---- (function initBackdrop() { var bg = document.querySelector('.bg'); if (!bg) return; var slides = [ 'assets/bg/air-daylight.jpg', 'assets/bg/ground-abrams.jpg', 'assets/bg/naval-iowa.jpg', 'assets/bg/air-vapor.jpg' ]; var stage = document.createElement('div'); stage.className = 'bg-stage'; stage.setAttribute('aria-hidden', 'true'); var nodes = slides.map(function (src, idx) { var div = document.createElement('div'); div.className = 'bg-slide'; if (idx === 0) { div.style.backgroundImage = 'url("' + src + '")'; div.setAttribute('data-loaded', '1'); } stage.appendChild(div); return div; }); bg.insertAdjacentElement('afterend', stage); function ensureLoaded(index) { var node = nodes[index]; if (!node || node.getAttribute('data-loaded') === '1') return; var img = new Image(); img.onload = function () { node.style.backgroundImage = 'url("' + slides[index] + '")'; node.setAttribute('data-loaded', '1'); }; img.src = slides[index]; } requestAnimationFrame(function () { nodes[0].classList.add('active'); }); if (reduce || slides.length < 2) return; var current = 0; ensureLoaded(1); setInterval(function () { if (document.hidden) return; var next = (current + 1) % slides.length; ensureLoaded(next); ensureLoaded((next + 1) % slides.length); nodes[current].classList.remove('active'); nodes[next].classList.add('active'); current = next; }, 11000); })(); // ---- Scroll-triggered reveal ---- (function initReveal() { var items = document.querySelectorAll('.reveal'); if (!items.length) return; if (reduce || !('IntersectionObserver' in window)) { items.forEach(function (n) { n.classList.add('in'); }); return; } var io = new IntersectionObserver(function (entries) { entries.forEach(function (entry) { if (!entry.isIntersecting) return; var index = +(entry.target.getAttribute('data-i') || 0); setTimeout(function () { entry.target.classList.add('in'); }, index * 85); io.unobserve(entry.target); }); }, { rootMargin: '0px 0px -8% 0px' }); items.forEach(function (n) { io.observe(n); }); })(); // ---- Pointer spotlight on cards ---- (function initSpotlight() { if (reduce) return; document.addEventListener('mousemove', function (e) { var card = e.target.closest('.card'); if (!card) return; var rect = card.getBoundingClientRect(); card.style.setProperty('--mx', (e.clientX - rect.left) + 'px'); card.style.setProperty('--my', (e.clientY - rect.top) + 'px'); }); })(); // ---- Sticky header border ---- (function initStickyNav() { var nav = document.querySelector('.nav'); if (!nav) return; var update = function () { nav.classList.toggle('stuck', window.scrollY > 8); }; update(); 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() { document.addEventListener('click', function (e) { var a = e.target.closest('a'); 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 = resolved; }, 240); }); })(); // ---- 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(); } }); 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 }); }); }); if (!hits.length) { resultsBox.innerHTML = '
$1')
.replace(/\*\*([^*]+)\*\*/g, '$1');
}
function renderMd(src) {
var out = [];
var inList = false;
String(src || '').split(/\r?\n/).forEach(function (raw) {
var line = raw.trim();
var heading = /^(#{2,3})\s+(.*)$/.exec(line);
var bullet = /^[-*]\s+(.*)$/.exec(line);
if (heading) {
if (inList) { out.push(''); inList = false; }
out.push('' + inlineMd(line) + '
'); } }); if (inList) out.push(''); return out.join(''); } function parseSemver(tag) { var m = /^v(\d+)\.(\d+)\.(\d+)$/.exec(tag || ''); return m ? [+m[1], +m[2], +m[3]] : null; } function compareSemverDesc(a, b) { var va = parseSemver(a.tag_name) || [0, 0, 0]; var vb = parseSemver(b.tag_name) || [0, 0, 0]; for (var i = 0; i < 3; i++) { if (vb[i] !== va[i]) return vb[i] - va[i]; } return 0; } function parsePackVer(tag) { var m = /^patches-(\d{4})\.(\d{2})\.(\d{2})(?:\.(\d+))?$/.exec(tag || ''); return m ? [+m[1], +m[2], +m[3], m[4] ? +m[4] : 1] : null; } function comparePackDesc(a, b) { var va = parsePackVer(a.tag_name) || [0, 0, 0, 0]; var vb = parsePackVer(b.tag_name) || [0, 0, 0, 0]; for (var i = 0; i < 4; i++) { if (vb[i] !== va[i]) return vb[i] - va[i]; } return 0; } function classifyReleases(list) { var launchers = list.filter(function (r) { return r && !r.draft && !r.prerelease && parseSemver(r.tag_name) !== null; }).sort(compareSemverDesc); var packs = list.filter(function (r) { return r && !r.draft && parsePackVer(r.tag_name) !== null; }).sort(comparePackDesc); return { launchers: launchers, packs: packs }; } function fetchReleaseFeed() { function load(url, headers) { return fetch(url, headers ? { headers: headers } : undefined).then(function (res) { if (!res.ok) throw new Error('HTTP ' + res.status); return res.json(); }).then(function (data) { if (!Array.isArray(data) || !data.length) throw new Error('Empty feed'); return data; }); } return load(PRIMARY_FEED).catch(function () { return load(FALLBACK_FEED, { Accept: 'application/vnd.github+json' }); }); } // ---- Home page latest release card (#release) ---- (function initHomeRelease() { var host = document.getElementById('release'); if (!host) return; function render(list) { var groups = classifyReleases(list); var latest = groups.launchers[0]; var latestPack = groups.packs[0] || null; if (!latest) { renderFallback(); return; } var assets = Array.isArray(latest.assets) ? latest.assets : []; var installer = assets.filter(function (a) { return /\.exe$/i.test(a.name || ''); })[0]; var portable = assets.filter(function (a) { return /-portable\.zip$/i.test(a.name || ''); })[0]; var dateStr = latest.published_at ? String(latest.published_at).slice(0, 10) : ''; var buttons = ''; if (installer) { buttons += '' + DL_ICON + '下载安装版(推荐)' + 'Download Installer' + (installer.size ? '' + esc(formatSize(installer.size)) + '' : '') + ''; } if (portable) { buttons += '' + DL_ICON + '便携压缩包' + 'Portable Archive' + (portable.size ? '' + esc(formatSize(portable.size)) + '' : '') + ''; } buttons += '' + '查看全部版本' + 'All Releases' + ''; var packHtml = ''; if (latestPack) { var games = Array.isArray(latestPack.game_versions) && latestPack.game_versions.length ? latestPack.game_versions.join(', ') : ''; packHtml = '' + esc(latestPack.tag_name) + '' +
(games ? '已核对客户端:Verified clients: ' + esc(games) + '' : '') +
'' + '当前未能实时拉取版本清单,可打开全部版本页或前往 GitHub Releases 获取安装包。' + 'Could not load the live release feed right now. Open the All Releases page or visit GitHub Releases for downloads.' + '
' + '' + '' + esc(games) + '');
}
if (minApp) {
metaRows.push('最低启动器版本:Min launcher: ' + esc(minApp) + '');
}
var hashHtml = zip && zip.sha256
? '' + '未能加载实时版本清单,请稍后刷新或前往 GitHub Releases 下载。' + 'Could not load the release catalog right now. Please refresh or visit GitHub Releases.' + '
' + '