/* * 轻量 i18n:中文为源文案,英文通过 zh→en 字典(i18n-en.js)映射。 * - 静态/动态文案统一在 DOM 层翻译(MutationObserver 覆盖后插入的节点) * - JS 里需要提前拿到译文时用 PL.t('中文') * - 语言解析优先级:?lang= > localStorage > navigator */ (function (w, d) { 'use strict'; var LS_KEY = 'pouchlab.lang'; var SUPPORTED = ['zh', 'en']; var EN = w.PLI18N_EN || {}; var dict = EN.dict || {}; var rules = EN.rules || []; var SKIP = 'svg,canvas,script,style,noscript,textarea,[data-no-i18n]'; var ATTRS = ['placeholder', 'title', 'aria-label', 'alt']; var lang = 'zh'; var observer = null; var booted = false; function norm(s) { return String(s).replace(/\s+/g, ' ').trim(); } function resolveLang() { try { var q = new URLSearchParams(w.location.search).get('lang'); if (q && SUPPORTED.indexOf(q) >= 0) { try { localStorage.setItem(LS_KEY, q); } catch (e) {} return q; } var saved = localStorage.getItem(LS_KEY); if (saved && SUPPORTED.indexOf(saved) >= 0) return saved; } catch (e) {} var n = (navigator.language || 'zh').toLowerCase(); return n.indexOf('zh') === 0 ? 'zh' : 'en'; } function translate(key) { if (lang === 'zh' || !key) return null; var v = dict[key]; if (v != null) return v; for (var i = 0; i < rules.length; i++) { var r = rules[i]; if (!r || !r[0] || !r[1]) continue; var m = key.match(r[0]); if (m) return r[1](m); } return null; } function applyTextNode(node) { var p = node.parentElement; if (!p) return; // SVG 默认跳过(画布内是用户设计内容);仅翻译带 data-ui="1" 的界面标注 if (p.closest('svg') ? !p.closest('[data-ui="1"]') : p.closest(SKIP)) return; var raw = node.nodeValue; if (!raw || !/\S/.test(raw)) return; if (node.__pliSrc === undefined) node.__pliSrc = raw; else if (node.__pliOut !== undefined && raw !== node.__pliOut) { // 应用层主动改写了文本(React/JS 重渲染),重新记录源文案 node.__pliSrc = raw; node.__pliOut = undefined; } if (lang === 'zh') { if (raw !== node.__pliSrc) { node.__pliOut = undefined; node.nodeValue = node.__pliSrc; } return; } var out = translate(norm(node.__pliSrc)); if (out == null) return; var src = String(node.__pliSrc); var lead = (src.match(/^\s*/) || [''])[0]; var trail = (src.match(/\s*$/) || [''])[0]; var val = lead + out + trail; if (raw !== val) { node.__pliOut = val; node.nodeValue = val; } else { node.__pliOut = val; } } function applyAttrs(el) { if (!el.getAttribute || !el.closest || el.closest('[data-no-i18n]')) return; if (!el.__pliAttr) el.__pliAttr = {}; for (var i = 0; i < ATTRS.length; i++) { var a = ATTRS[i]; var v = el.getAttribute(a); if (v == null || !v) continue; if (el.__pliAttr[a] === undefined) el.__pliAttr[a] = v; var src = el.__pliAttr[a]; var next = src; if (lang !== 'zh') { var out = translate(norm(src)); if (out != null) next = out; } if (v !== next) el.setAttribute(a, next); } if (el.tagName === 'INPUT' && /^(button|submit|reset)$/i.test(el.type || '')) { if (el.__pliVal === undefined) el.__pliVal = el.value; var want = el.__pliVal; if (lang !== 'zh') { var o = translate(norm(el.__pliVal)); if (o != null) want = o; } if (el.value !== want) el.value = want; } } function walk(root) { if (!root) return; if (root.nodeType === 3) { applyTextNode(root); return; } if (root.nodeType !== 1 && root.nodeType !== 9 && root.nodeType !== 11) return; if (root.nodeType === 1) applyAttrs(root); var tw = d.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null); var n; while ((n = tw.nextNode())) { if (n.nodeType === 3) applyTextNode(n); else applyAttrs(n); } } function applyHead() { var title = d.querySelector('title'); if (title) { if (!title.__pliSrc) title.__pliSrc = title.textContent; var tv = title.__pliSrc; if (lang !== 'zh') { var to = translate(norm(tv)); if (to != null) tv = to; } if (title.textContent !== tv) title.textContent = tv; } var meta = d.querySelector('meta[name="description"]'); if (meta) { if (!meta.__pliSrc) meta.__pliSrc = meta.getAttribute('content') || ''; var cv = meta.__pliSrc; if (lang !== 'zh') { var co = translate(norm(cv)); if (co != null) cv = co; } if (meta.getAttribute('content') !== cv) meta.setAttribute('content', cv); } if (d.documentElement.lang !== (lang === 'zh' ? 'zh-CN' : 'en')) { d.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'; } } function refresh() { walk(d.body || d.documentElement); applyHead(); } function onMutations(list) { if (lang === 'zh') return; for (var i = 0; i < list.length; i++) { var m = list[i]; if (m.type === 'characterData') applyTextNode(m.target); else if (m.type === 'attributes') { if (m.target && m.target.nodeType === 1) applyAttrs(m.target); } else if (m.type === 'childList') { for (var j = 0; j < m.addedNodes.length; j++) walk(m.addedNodes[j]); } } } function syncObserver() { if (!w.MutationObserver) return; if (lang === 'en') { if (!observer) { observer = new MutationObserver(onMutations); observer.observe(d.body || d.documentElement, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ATTRS }); } } else if (observer) { observer.disconnect(); observer = null; } } function buildSwitcher() { var box = d.createElement('div'); box.className = 'pli-switch'; box.setAttribute('data-no-i18n', ''); box.setAttribute('role', 'group'); box.setAttribute('aria-label', 'Language'); SUPPORTED.forEach(function (code) { var b = d.createElement('button'); b.type = 'button'; b.setAttribute('data-lang', code); b.textContent = code === 'zh' ? '中文' : 'EN'; b.setAttribute('aria-pressed', String(code === lang)); b.addEventListener('click', function () { setLang(code); }); box.appendChild(b); }); return box; } function mountSwitcher() { if (d.querySelector('.pli-switch')) return; var el = buildSwitcher(); var slot = d.querySelector('[data-lang-slot]'); if (slot) { slot.appendChild(el); } else { el.classList.add('pli-switch--float'); (d.body || d.documentElement).appendChild(el); } } function updateSwitcher() { var box = d.querySelector('.pli-switch'); if (!box) return; Array.prototype.forEach.call(box.querySelectorAll('button'), function (b) { b.setAttribute('aria-pressed', String(b.getAttribute('data-lang') === lang)); }); } function setLang(code) { if (SUPPORTED.indexOf(code) < 0) return; if (code === lang) return; lang = code; try { localStorage.setItem(LS_KEY, code); } catch (e) {} // 先还原中文再整体应用译文,避免残留 var prev = lang; lang = 'zh'; refresh(); lang = prev; refresh(); syncObserver(); updateSwitcher(); try { if (w.dayjs && w.dayjs.locale) w.dayjs.locale(code === 'zh' ? 'zh-cn' : 'en'); } catch (e) {} if (w.PL && w.PL.ui && w.PL.ui.retheme) { try { w.PL.ui.retheme(); } catch (e) {} } d.dispatchEvent(new CustomEvent('pl:langchange', { detail: { lang: lang } })); // 应用层可能在语言切换时重绘(如 React/SVG),重绘后再整体校正一次 refresh(); } function injectStyle() { if (d.getElementById('pli-style')) return; var s = d.createElement('style'); s.id = 'pli-style'; s.textContent = [ '.pli-switch{display:inline-flex;align-items:center;gap:2px;padding:2px;border:1px solid #e2dacb;background:#fffdf8;border-radius:999px;font:600 12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}', '.pli-switch button{border:0;background:transparent;color:#7d7466;border-radius:999px;padding:5px 9px;cursor:pointer;font:inherit;line-height:1}', '.pli-switch button[aria-pressed="true"]{background:#17140f;color:#fff}', '.pli-switch--float{position:fixed;right:16px;bottom:16px;z-index:9999;box-shadow:0 6px 20px rgba(23,20,15,.14)}' ].join(''); (d.head || d.documentElement).appendChild(s); } function boot() { if (booted) return; booted = true; injectStyle(); refresh(); mountSwitcher(); syncObserver(); updateSwitcher(); try { if (w.dayjs && w.dayjs.locale) w.dayjs.locale(lang === 'zh' ? 'zh-cn' : 'en'); } catch (e) {} } lang = resolveLang(); var api = { getLang: function () { return lang; }, setLang: setLang, toggle: function () { setLang(lang === 'zh' ? 'en' : 'zh'); }, t: function (s, vars) { if (lang === 'zh' || s == null) return s; var out = translate(norm(s)); if (out == null) return s; if (vars) out = out.replace(/\{(\w+)\}/g, function (_, k) { return vars[k] != null ? vars[k] : '{' + k + '}'; }); return out; }, refresh: refresh, translate: translate, register: function (extra) { if (!extra) return; if (extra.dict) for (var k in extra.dict) dict[k] = extra.dict[k]; if (extra.rules) rules = rules.concat(extra.rules); if (booted) refresh(); }, mounted: false }; w.PL = w.PL || {}; w.PL.i18n = api; w.PL.t = api.t; w.t = w.t || api.t; if (d.readyState === 'loading') d.addEventListener('DOMContentLoaded', boot); else boot(); w.addEventListener('storage', function (e) { if (e.key === LS_KEY && e.newValue && e.newValue !== lang && SUPPORTED.indexOf(e.newValue) >= 0) setLang(e.newValue); }); })(window, document);