site.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /* lynx-share.com: shared script (language, download links, dates, lightbox). Pages read fine without it.
  2. LYNX_LANGS / LYNX_LANG / LYNX_DICT / LYNX_V come from the inline script in <head>; LYNX_EN holds the English of the
  3. few strings only this script writes. Every other English string is in the page itself (and in i18n/en.json, which
  4. _src/build.py writes from the pages). Other languages: i18n/<id>.json {"ui","featured","insp"}, plus
  5. i18n/<part>/<id>.json for pages that name a part in <html data-dict> (the Updates page), plus the body of a wiki
  6. page, i18n/wiki/<id>/<page>.html, for the languages <html data-wt> lists. */
  7. (() => {
  8. const $ = s => document.querySelector(s), $$ = s => [...document.querySelectorAll(s)];
  9. const html = document.documentElement;
  10. const LANGS = window.LYNX_LANGS || [['en','English']], EN = window.LYNX_EN || {}, V = window.LYNX_V || '';
  11. const SHORT = {'zh-Hans':'简','zh-Hant':'繁','pt-BR':'PT'};
  12. const OGL = {'en':'en_US','zh-Hans':'zh_CN','zh-Hant':'zh_TW','nl':'nl_NL','fr':'fr_FR','de':'de_DE','id':'id_ID','it':'it_IT','ja':'ja_JP','ko':'ko_KR','pl':'pl_PL','pt-BR':'pt_BR','ru':'ru_RU','es':'es_ES','tr':'tr_TR'};
  13. const PART = html.dataset.dict || '';
  14. const BODIES = (html.dataset.wt || '').split(' '), prose = $('#wprose'), proseEn = prose ? prose.innerHTML : '';
  15. const bodyUrl = l => '/i18n/wiki/' + l + location.pathname.replace(/^\/wiki/, '').replace(/\/$/, '') + '.html?v=' + V;
  16. let lang = 'en', D = {}, FEAT = {}, INSP = {}, pristine = true;
  17. // t('dl.for', 'Linux'): the text in the current language (English when missing), {0} {1}... replaced by the arguments
  18. const t = (k, ...a) => { let v = D[k] ?? EN[k] ?? k; a.forEach((x, i) => v = v.split('{' + i + '}').join(x)); return v; };
  19. window.LYNX_T = t;
  20. const cache = window.LYNX_DICT || {};
  21. function fetchDict(l){
  22. const get = u => fetch(u).then(r => r.ok ? r.json() : Promise.reject(r.status));
  23. const body = prose && BODIES.includes(l) ? fetch(bodyUrl(l)).then(r => r.ok ? r.text() : '').catch(() => '') : '';
  24. return Promise.all([get('/i18n/' + l + '.json?v=' + V), PART ? get('/i18n/' + PART + '/' + l + '.json?v=' + V) : {}, body])
  25. .then(([a, b, c]) => ({ui: Object.assign({}, a.ui, b), featured: a.featured || {}, insp: a.insp || {}, body: c}));
  26. }
  27. function loadLang(l){
  28. if (l === 'en' && pristine) return Promise.resolve(null); // the page is already in English
  29. if (window.LYNX_FONT) window.LYNX_FONT(l);
  30. cache[l] = cache[l] || fetchDict(l);
  31. return cache[l].catch(e => { delete cache[l]; throw e; });
  32. }
  33. let seq = 0;
  34. function setLang(l){
  35. const s = ++seq;
  36. return loadLang(l).then(d => { if (s === seq) applyLang(l, d); }, () => { if (s === seq) applyLang('en', null); })
  37. .finally(() => html.classList.remove('i18n-wait'));
  38. }
  39. function pageUrl(l){ return 'https://lynx-share.com' + location.pathname + (l === 'en' ? '' : '?lang=' + (l === 'pt-BR' ? 'pt' : l)); }
  40. function applyLang(l, d){
  41. lang = l; html.lang = l; html.dir = 'ltr';
  42. if (d){
  43. pristine = false; D = d.ui || {}; FEAT = d.featured || {}; INSP = d.insp || {};
  44. if (prose){ // the wiki body in this language, or the English one (with the "English only" note) when there is none
  45. prose.innerHTML = d.body || proseEn; html.classList.toggle('wt', !!d.body);
  46. $$('.toc a:not([data-i18n])').forEach(a => { const h = document.getElementById(a.hash.slice(1)); if (h) a.innerHTML = h.innerHTML; });
  47. }
  48. // a key the dictionary lacks keeps the page's own English (scripts/check-site-i18n.py reports it)
  49. $$('[data-i18n]').forEach(e => {
  50. if (e._en === undefined) e._en = e.innerHTML;
  51. const k = e.dataset.i18n, a = e.dataset.args ? JSON.parse(e.dataset.args) : [];
  52. e.innerHTML = k in D ? t(k, ...a) : e._en;
  53. });
  54. $$('[data-i18n-alt]').forEach(e => { if (e._alt === undefined) e._alt = e.alt; e.alt = D[e.dataset.i18nAlt] || e._alt; });
  55. $$('[data-i18n-ph]').forEach(e => { if (e._ph === undefined) e._ph = e.placeholder; e.placeholder = D[e.dataset.i18nPh] || e._ph; });
  56. $$('[data-i18n-aria]').forEach(e => { if (e._aria === undefined) e._aria = e.getAttribute('aria-label'); e.setAttribute('aria-label', D[e.dataset.i18nAria] || e._aria); });
  57. $$('[data-feat]').forEach(e => { if (FEAT[e.dataset.feat]) e.textContent = FEAT[e.dataset.feat]; else if (e.dataset.en) e.textContent = e.dataset.en; });
  58. $$('[data-insp]').forEach(e => { if (INSP[e.dataset.insp]) e.textContent = INSP[e.dataset.insp]; else if (e.dataset.en) e.textContent = e.dataset.en; });
  59. const h1 = $('[data-i18n-words]');
  60. if (h1 && D[h1.dataset.i18nWords]){ // word by word, as _src/build.py writes the English (site.css animates .w in turn)
  61. const [a, b = ''] = t(h1.dataset.i18nWords).split('|'), ws = a.split(' ');
  62. h1.innerHTML = ws.map((w, i) => '<span class="w" style="--i:' + i + '">' + w + '</span>').join(' ') + (b ? ' <span class="grad w" style="--i:' + ws.length + '">' + b + '</span>' : '');
  63. }
  64. if (D[html.dataset.title]) document.title = D[html.dataset.title] + ('home' in html.dataset ? '' : ' · LYNX SHARE');
  65. const md = $('meta[name=description]'); if (md && D[html.dataset.desc]) md.content = D[html.dataset.desc];
  66. const ot = $('meta[property="og:title"]'); if (ot) ot.content = document.title;
  67. const od = $('meta[property="og:description"]'); if (od && md) od.content = md.content;
  68. }
  69. const can = $('link[rel=canonical]'); if (can) can.href = pageUrl(l);
  70. const ou = $('meta[property="og:url"]'); if (ou) ou.content = pageUrl(l);
  71. const ol = $('meta[property="og:locale"]'); if (ol) ol.content = OGL[l] || 'en_US';
  72. if (sel){ sel.value = l; $('#langCode').textContent = SHORT[l] || l.toUpperCase(); }
  73. renderDates(); renderVer(); renderDownload();
  74. document.dispatchEvent(new CustomEvent('lynx:lang', {detail: lang}));
  75. }
  76. const sel = $('#lang');
  77. if (sel){
  78. sel.innerHTML = LANGS.map(([id, name]) => `<option value="${id}" lang="${id}">${name}</option>`).join('');
  79. sel.value = window.LYNX_LANG || 'en';
  80. sel.onchange = () => {
  81. const l = sel.value;
  82. try { localStorage.setItem('lynx-lang', l); } catch (e) {}
  83. // a ?lang= in the address wins over the saved choice: keep it in step so a reload shows the same language
  84. try { const u = new URL(location.href); if (u.searchParams.has('lang')){ if (l === 'en') u.searchParams.delete('lang'); else u.searchParams.set('lang', l === 'pt-BR' ? 'pt' : l); history.replaceState(null, '', u); } } catch (e) {}
  85. setLang(l);
  86. };
  87. }
  88. /* dates: <time datetime="2026-11-09"> in the reader's language */
  89. function renderDates(){
  90. $$('time[datetime]').forEach(e => { try { e.textContent = new Date(e.dateTime + 'T12:00:00Z').toLocaleDateString(lang, {year:'numeric', month:'long', day:'numeric'}); } catch (x) {} });
  91. }
  92. /* download: the visitor's OS gets the accent; links go straight to the newest matching release file */
  93. const RELEASES = 'https://github.com/Ka1-S/LYNX-SHARE/releases/latest';
  94. const DL = { // main = primary package, alt = second format; tests run on asset names, newest release with a match wins
  95. win: {main: [/setup.*\.exe$/i, /\.exe$/i], alt: [/windows.*\.zip$/i]},
  96. mac: {main: [/macos.*\.dmg$/i, /\.dmg$/i]},
  97. // (x86_64 and arm64 by name: a release from 0.1.31 has both; older ones have only the x86_64 files, so the arm64
  98. // buttons find nothing there and keep the releases page)
  99. linux: {main: [/x86_64\.AppImage$/i], alt: [/linux-x86_64\.tar\.gz$/i], arm: [/aarch64\.AppImage$/i], armalt: [/linux-aarch64\.tar\.gz$/i]}
  100. };
  101. const dlUrl = {};
  102. function detectOS(){
  103. let q = null; try { q = new URLSearchParams(location.search).get('os'); } catch (e) {} // ?os=win|mac|linux|any (testing)
  104. if (q) return DL[q] ? q : '';
  105. const uad = navigator.userAgentData, ua = navigator.userAgent || '';
  106. const p = ((uad && uad.platform) || navigator.platform || '').toLowerCase();
  107. if ((uad && uad.mobile) || /android|iphone|ipad|ipod/i.test(ua) || /android|iphone|ipad|ipod/.test(p)) return '';
  108. if (/mac/.test(p) || /Macintosh|Mac OS X/.test(ua)) return navigator.maxTouchPoints > 1 ? '' : 'mac'; // touch "Mac" = iPadOS
  109. if (/win/.test(p) || /Windows/.test(ua)) return 'win';
  110. if (/cros/.test(p) || /CrOS/.test(ua)) return '';
  111. if (/linux|x11|bsd/.test(p) || /Linux|X11/.test(ua)) return 'linux';
  112. return '';
  113. }
  114. const userOS = detectOS();
  115. // a Linux arm64 visitor (the browser says "Linux aarch64"): the main download link offers the arm64 AppImage
  116. const userArm = userOS === 'linux' && /aarch64|arm64/i.test(((navigator.userAgentData && navigator.userAgentData.platform) || '') + ' ' + (navigator.platform || '') + ' ' + (navigator.userAgent || ''));
  117. function renderDownload(){
  118. $$('[data-dl]').forEach(a => { a.href = dlUrl[a.dataset.dl] || RELEASES; });
  119. $$('[data-os]').forEach(e => {
  120. const you = e.dataset.os === userOS;
  121. e.classList.toggle('you', you);
  122. if (e.classList.contains('btn')){ e.classList.toggle('btn-red', you); e.classList.toggle('btn-ghost', !you); }
  123. const em = e.querySelector('em[data-yours]'); if (em) em.textContent = you ? t('dl.yours') : '';
  124. });
  125. const mainKey = userArm && dlUrl['linux.arm'] ? 'linux.arm' : userOS + '.main';
  126. $$('.dl-link').forEach(a => { if (userOS && dlUrl[mainKey]) a.href = dlUrl[mainKey]; });
  127. const badge = $('#storeBadge'); // Microsoft's own localized badge
  128. if (badge) badge.src = 'https://get.microsoft.com/images/' + ({'en':'en-us','zh-Hans':'zh-cn','zh-Hant':'zh-tw','pt-BR':'pt-br'}[lang] || lang) + '%20light.svg';
  129. }
  130. /* latest release from GitHub (the page already names the version it was built for) */
  131. let rel = null;
  132. function renderVer(){
  133. if (!rel) return;
  134. let d = ''; try { d = rel.at ? ' · ' + new Date(rel.at).toLocaleDateString(lang) : ''; } catch (e) {}
  135. $$('.ver-line').forEach(e => e.textContent = 'v' + rel.v + d);
  136. $$('.ver-tag').forEach(e => e.textContent = rel.v.toUpperCase());
  137. }
  138. if ($('[data-dl]') || $('.ver-line')){
  139. fetch('https://api.github.com/repos/Ka1-S/LYNX-SHARE/releases?per_page=10').then(r => r.ok ? r.json() : null).then(rs => {
  140. if (!Array.isArray(rs)) return;
  141. rs = rs.filter(x => !x.draft); if (!rs.length) return;
  142. rel = {v: rs[0].tag_name.replace(/^v/, ''), at: rs[0].published_at};
  143. Object.keys(DL).forEach(os => Object.keys(DL[os]).forEach(k => {
  144. for (const re of DL[os][k]) for (const r of rs){
  145. const a = (r.assets || []).find(x => re.test(x.name));
  146. if (a){ dlUrl[os + '.' + k] = a.browser_download_url; return; }
  147. }
  148. }));
  149. renderVer(); renderDownload();
  150. }).catch(() => {});
  151. }
  152. /* screenshots open full size */
  153. if ($('a.shot')){
  154. const lb = document.createElement('div'); lb.className = 'lightbox'; lb.innerHTML = '<img alt="">'; document.body.appendChild(lb);
  155. const im = lb.firstChild;
  156. document.addEventListener('click', e => { // delegated: a translated wiki body brings its own links
  157. const a = e.target.closest ? e.target.closest('a.shot') : null; if (!a) return;
  158. e.preventDefault(); im.src = a.href; im.alt = (a.querySelector('img') || {}).alt || ''; lb.classList.add('open');
  159. });
  160. lb.onclick = () => lb.classList.remove('open');
  161. addEventListener('keydown', e => { if (e.key === 'Escape') lb.classList.remove('open'); });
  162. }
  163. setLang(window.LYNX_LANG || 'en');
  164. })();