// The last few script errors, kept where a smoke test or a bug report can // read them back (window.__zimiErrors): a desktop window has no console a // person can open, and "the page stayed blank" is not a report. window.__zimiErrors = []; window.addEventListener('error', function(e) { var where = (e.filename || '').split('/').pop() + ':' + (e.lineno || 0); window.__zimiErrors.push(where + ' ' + (e.message || String(e.error || e))); if (window.__zimiErrors.length > 20) window.__zimiErrors.shift(); }); window.addEventListener('unhandledrejection', function(e) { window.__zimiErrors.push('promise: ' + String((e.reason && (e.reason.message || e.reason)) || e)); if (window.__zimiErrors.length > 20) window.__zimiErrors.shift(); }); // A pinch zooms; nothing else does (Eric, 2026-10-01: "Maybe I still did want // pinch to zoom just not text or any auto"): no double-tap zoom // (touch-action: manipulation) and no zoom into a focused field (16px fields // on touch screens), both in app.css. // Storage that is always there. WebKitGTK hands a private-mode window a // null localStorage, and one unguarded read of it at load killed the whole // script: the desktop window on Linux stayed a bare shell (issue #81). A // window with no storage gets an in-memory one and forgets on close, which // is what private mode means; it does not get a dead page. (function _ensureStorage() { function memory() { var m = {}; return { getItem: function(k) { return Object.prototype.hasOwnProperty.call(m, k) ? m[k] : null; }, setItem: function(k, v) { m[k] = String(v); }, removeItem: function(k) { delete m[k]; }, clear: function() { m = {}; }, key: function(i) { return Object.keys(m)[i] || null; }, get length() { return Object.keys(m).length; } }; } ['localStorage', 'sessionStorage'].forEach(function(name) { var ok = false; try { ok = !!window[name] && typeof window[name].getItem === 'function'; } catch (e) { ok = false; } if (!ok) { try { Object.defineProperty(window, name, { configurable: true, value: memory() }); } catch (e) {} } }); })(); // ── Config (injected by server via inline script) ── var _cfg = window.__ZIMI_CONFIG || {}; var _i18nVer = _cfg.i18nHash || '0'; // A /static data file's address with the version of the file: the server sends /static as immutable for a year, so a file whose // content changed under the same name (the 3D view's models and maps did, from 1.15 to 1.16) is only fetched afresh when its address // changes. The server gives the page each data file's content hash (__ZIMI_CONFIG.assets, by path under static/); a file it does not // list takes the build's. A query on the address is replaced by it; the Almanac inside its own ZIM has no // config and keeps its relative paths as they are. function _almAsset(path) { var base = String(path).replace(/[?#].*$/, ''), c = window.__ZIMI_CONFIG || {}; var rel = base.replace(/^\/?static\//, ''), v = (c.assets && c.assets[rel]) || c.build || ''; return v ? base + '?v=' + encodeURIComponent(v) : base; } // ── Storage Keys ── var SK = { UI_LANG: 'zimi_ui_lang', HIDE_DISCOVER: 'zimi_hide_discover', // The Almanac's chosen place, kept on this device (read with // _almChosenPlace); ALMANAC_LOC is the session key older builds used. ALMANAC_PLACE: 'zimi_almanac_place', ALMANAC_LOC: 'zimi_almanac_location', ALMANAC_HL: 'zimi_almanac_highlights', HIDE_LANG_CHOOSER: 'zimi_hide_lang_chooser', LANG_LIST_OPEN: 'zimi_lang_list_open', // Settings > Languages, unfolded // Last KNOWN answer to "may this browser create ZIMs?" — a boot-time hint so // the + can be drawn before the manage probe lands, never an authority. See // _createCanShow for why optimism here is safe in one direction only. CAN_CREATE: 'zimi_can_create', HIDE_XZIM_LINKS: 'zimi_hide_cross_zim_links', // Links that leave the library (#99): absent = mark them, 'hide' = plain text. EXT_LINKS: 'zimi_external_links', // Search results open in their app (absent = yes, '0' = the ZIM's own page). OPEN_IN_APPS: 'zimi_open_in_apps', // When set, ZIM article HTML is run through the server-side a11y // rewriter (alt="" on images, h1 promotion, html lang). Off by // default to keep ZIM content byte-identical for purist users. LIBRARY_TAB: 'zimi_library_tab', // Home library layout: 'list' (default full cards) | 'tiles' (compact grid). LIBRARY_VIEW: 'zimi_library_view', // Home's width on a wide screen: 'compact' (the narrow centred column) | default wide. // How the home screen orders the ZIMs inside a category. Alphabetical by // default (#67): it matches Settings > Library, and it is the order you can // predict when you are looking for a title you already know. Article count // was the old default and rewards big files rather than the one you want. LIBRARY_SORT: 'zimi_library_sort', // Everything kept (1.12): items, lists, memberships, highlights and their // tombstones, one JSON value (see Saved); where you were (positions and // theirs) under SAVED_POS, written on its own as you read. Signed out it // is these keys; an account's own copy is each + ':' + its name. SAVED: 'zimi_saved', SAVED_POS: 'zimi_saved_pos', // The accounts already asked whether to add this browser's pre-1.12 // bookmarks to them (a JSON list of names). SAVED_LEGACY_ASKED: 'zimi_saved_legacy_asked', // Before 1.12: bookmarks, and their folders ({id,name,parent,order}). // Read into the signed-out SAVED when it is first used (an account's only // when its person asks), and left in place for one release so an older // Zimi still finds them. BOOKMARKS: 'zimi_bookmarks', BM_FOLDERS: 'zimi_bm_folders', // Per-device UI state: ids of collapsed folders in the bookmarks tree. BM_COLLAPSED: 'zimi_bm_collapsed', // Highlights, per device: the colour last chosen, and the highlights a // page opened here did not have ({id: 1}), for the panel to say so. Never // synced: another device may hold another build of the ZIM. HL_COLOR: 'zimi_hl_color', HL_MISSING: 'zimi_hl_missing', // The admin's session token. Never the password: that used to be kept here // in plain text under the key zimi_manage_pw, which _purgeStoredPassword // removes wherever an older version left it. MANAGE_PW: 'zimi_manage_token', // Optional management username (v1.8) — a plain identifier, stored next to // the token so a remembered session keeps sending its X-Zimi-User header. MANAGE_USER: 'zimi_manage_user', PREF_LANGUAGES: 'zimi_pref_languages', PREF_FLAVOR: 'zimi_pref_flavor', // The person's voices ({voice: Say's last pick, off: [engines]}): // Settings > Voices; dictionary.html reads it under this same name. VOICE_PREFS: 'zimi_voice_prefs', // Hear's sample words, {lang: [words]}: SESSION-scoped, the same all session. VOICE_SAMPLE: 'zimi_voice_sample', // Read aloud: server engines that could not keep up with reading on this // server ([engines]), tried last from then on. TTS_SLOW: 'zimi_tts_slow', // Read aloud: how quick this device's own voice is, as Test voice speed // timed it here ({first_s, cold_s, gaps}); the server's are the server's. TTS_DEVICE_TIMES: 'zimi_tts_device_times', // Read aloud: when it was last used (ms), so a Reader View opened within a // week of it gets the voice list and the engine warmed ahead of the tap. TTS_LAST_USE: 'zimi_tts_last_use', // Read aloud: engines already suggested as a faster choice ([engines]), // each said once. TTS_SUGGESTED: 'zimi_tts_suggested', // Read aloud: how fast it reads (_TTS_RATE_MIN to _TTS_RATE_MAX), set in the reading bar. TTS_RATE: 'zimi_tts_rate', // Reader font scale (percent, one of READER_FONT_LEVELS), applied as a `zoom` // on the iframe body and reapplied on every article load. READER_FONT: 'zimi_reader_font_scale', // Reader View settings palette (persisted — a real palette implies persistence, // unlike the session-only v1 toggle). Family: 'serif'|'sans'. Theme: // 'dark'|'light'|'sepia'. Auto: '1' opens every article straight into Reader View. READER_FAMILY: 'zimi_reader_family', READER_THEME: 'zimi_reader_theme', READER_AUTO: 'zimi_reader_auto', // One-shot: set once the "tap again for reading settings" coachmark has been // shown, so the hint never nags a returning reader. READER_COACH: 'zimi_reader_settings_coach', // Last-rendered SHARING rows (Server pane) — restored synchronously on // pane open so the section doesn't pop in after the status fetches. SHARE_ROWS: 'zimi_share_rows', // Last-active manage settings section (library|preferences|server|users). // Session-scoped so a reload (or re-entering Manage) lands on the same tab. MANAGE_SECTION: 'zimi_manage_section', // Video resume ledger: {"\n#": {t, d, ts}} — playback position // per video, restored on reopen and dropped once watched to completion. VIDEO_RESUME: 'zimi_video_resume', // Before 1.12, where you were in each book: {"\n": {f, c, ts, // id, title, author, cover}}. Read once into SAVED's positions, like the // bookmarks, and left in place for one release. BOOK_PLACES: 'zimi_book_places', // How books are read in this browser: {mode: 'scroll'|'pages', size (px), // lh and margin (indexes into _READING_LEADINGS / _READING_MARGINS)}. BOOK_PREFS: 'zimi_book_prefs', // How Zimipedia's reader reads articles in this browser: {size (px), lh and // margin (indexes into _READING_LEADINGS / _READING_MARGINS)}. WIKI_PREFS: 'zimi_wiki_prefs', // Zimipedia's trails: this tab's (SESSION-scoped: the articles you came // through, one link at a time) and the recent ones in this browser, which // its front door lists (_wikiTrailsKept, _wikiTrailResume). WIKI_TRAIL: 'zimi_wiki_trail', WIKI_TRAILS: 'zimi_wiki_trails', // Whole-app theme: 'auto' (follow prefers-color-scheme, dark fallback) | // 'dark' | 'light' | 'red' (night vision: deep red on black everywhere). Default auto. Read/written via _appTheme/_setAppTheme; // the head bootstrap in index.html stamps the resolved value pre-paint. APP_THEME: 'zimi_app_theme', // What Red replaced, so switching Red off (the sky's and the Field Guide's // switches do) puts the person back where they were rather than on Auto. APP_THEME_BEFORE_RED: 'zimi_app_theme_before_red', // Auto-darken raw (non-Reader-View) ZIM articles when the app is dark, so a // blinding-white ZIM page doesn't break dark mode. Tri-state: unset = follow // the app theme (on when dark); '1'/'0' = explicit override once toggled. // Kept its 1.x name: the key stores whether to SIMULATE a dark mode on // articles that have none. It used to decide darkness outright. DARKEN_ARTICLES: 'zimi_darken_articles', ARTICLE_THEME: 'zimi_article_theme', // The language welcome card's x: {lang: 1} for each language it was dismissed in. WELCOME_DISMISSED: 'zimi_welcome_dismissed', // Which source Catalog > Maps lists: 'kiwix' (absent) | 'streetzim'. MAPS_SOURCE: 'zimi_maps_source', // The Almanac's choices (almanac*.js read and write them under these names; the // ZIM build shares SK). Place: {lat, lon, name}; clocks: [IANA zone]; clocks view: // 'all'|'saved'; units: 'ft'|'m'; sky: {skin, lines, size, dial}; orbits: // 'always' (on) or absent (off); landmarks and HD-later: '1'; spin faces: '1'|'0' (absent: on in full screen only); tried: {hint: 1}. ALM_CLOCKS: 'zimi_almanac_clocks', ALM_CLOCKS_VIEW: 'zimi_almanac_clocks_view', ALM_UNITS: 'zimi_almanac_units', ALM_SKY: 'zimi_sky_settings', ALM_ORBITS: 'zimi_ae_orbits', ALM_SATS_ALL: 'zimi_ae_sats_all', ALM_LANDMARKS: 'zimi_alm_landmarks', ALM_SPIN_FACES: 'zimi_alm_spin_faces', ALM_HINT_CONTROLS: 'zimi_alm_hint_controls', // sessionStorage: the 3D view's "tap to show or hide controls" line, said once ALM_HD_LATER: 'zimi_alm_hd_later', ALM_ORRERY_TRIED: 'zimi_orrery_tried', // The app pages' choices (apps.js prefWrite, pdfreader.js): they cannot read SK // from inside their frames, so they spell these names themselves. WIKI_VIEW: 'zimi_wiki_view', WIKI_LANG: 'zimi_wiki_lang', PDF_DARK: 'zimi_pdf_dark', PDF_SPREAD: 'zimi_pdf_spread', PDF_VIEW: 'zimi_pdf_view', TUBE_SORT: 'zimitube_sort', TUBE_AUTOPLAY: 'zimitube_autoplay', TUBE_THEATER: 'zimitube_theater', REDDOT_FOLLOW: 'reddot_follow', // Settings sync's state in this browser: {owner: the account it follows, or // null; pending: {key: 1} changed here while signed in to it and not yet // taken by it; seeded: this browser has followed an account before, so its // settings are no longer the ones it had before sync}. apps.js marks a // page's change pending under this same name. PREF_SYNC: 'zimi_pref_sync', // Whose ZimiGames this browser keeps for (owner), what changed here and has // not gone up (pending), and one who left without it going (aside). GAMES_SYNC: 'zimi_games_sync', // The signed-in player's display name, for the games pages to show, and // whether a player is signed in at all (the games' boards are theirs). GAMES_PERSON: 'zimi_games_person', GAMES_SIGNED: 'zimi_games_signed', }; // What a person sets for themselves: carried by My data, and while signed in // kept by the account and followed in every browser (Eric, 2026-10-21: // "Things a user changes while signed in should sync to all sessions all // browsers"). Not here: what belongs to this device or this server (timed // voices, a highlight's colour, window sizes, caches), or to this tab. var _PREF_KEYS = [ SK.UI_LANG, SK.HIDE_DISCOVER, SK.HIDE_LANG_CHOOSER, SK.HIDE_XZIM_LINKS, SK.LIBRARY_VIEW, SK.PREF_LANGUAGES, SK.VOICE_PREFS, SK.PREF_FLAVOR, SK.READER_FONT, SK.READER_FAMILY, SK.READER_THEME, SK.READER_AUTO, SK.EXT_LINKS, SK.OPEN_IN_APPS, SK.APP_THEME, SK.APP_THEME_BEFORE_RED, SK.ARTICLE_THEME, SK.DARKEN_ARTICLES, SK.LIBRARY_SORT, SK.TTS_RATE, SK.BOOK_PREFS, SK.WIKI_PREFS, SK.READER_COACH, SK.TTS_SUGGESTED, SK.WELCOME_DISMISSED, SK.MAPS_SOURCE, SK.ALMANAC_PLACE, SK.ALM_CLOCKS, SK.ALM_CLOCKS_VIEW, SK.ALM_UNITS, SK.ALM_SKY, SK.ALM_ORBITS, SK.ALM_SATS_ALL, SK.ALM_LANDMARKS, SK.ALM_SPIN_FACES, SK.ALM_HD_LATER, SK.ALM_ORRERY_TRIED, SK.WIKI_VIEW, SK.WIKI_LANG, SK.PDF_DARK, SK.PDF_SPREAD, SK.PDF_VIEW, SK.TUBE_SORT, SK.TUBE_AUTOPLAY, SK.TUBE_THEATER, SK.REDDOT_FOLLOW, ]; function _isPrefKey(k) { return _PREF_KEYS.indexOf(k) >= 0; } function _rawGet(k) { try { return localStorage.getItem(k); } catch (e) { return null; } } // An account-synced store's state in this browser (settings, games): whose it // follows, what is pending, what the account refused, and ``flags`` of its own // ({name: 'bool' | 'object'}). function _syncState(key, flags) { var st = _getStorageJSON(key, null); if (!st || typeof st !== 'object' || Array.isArray(st)) st = {}; var obj = function (v) { return v && typeof v === 'object' && !Array.isArray(v) ? v : {}; }; var out = { owner: typeof st.owner === 'string' && st.owner ? st.owner : null, pending: obj(st.pending), refused: obj(st.refused) }; Object.keys(flags || {}).forEach(function (f) { out[f] = flags[f] === 'bool' ? !!st[f] : obj(st[f]); }); return out; } function _syncSaveState(key, st) { try { localStorage.setItem(key, JSON.stringify(st)); } catch (e) {} } function _prefState() { return _syncState(SK.PREF_SYNC, { seeded: 'bool' }); } function _prefSaveState(st) { _syncSaveState(SK.PREF_SYNC, st); } // One of them changed here (``before``: its raw value a moment ago). Signed // in, it is the account's to take: pending, and sent soon. Signed out, it is // this browser's alone (users.py's convention). The same value is no change. function _prefChanged(k, before) { if (!_isPrefKey(k) || _rawGet(k) === before) return; var st = _prefState(); if (!_accountId || st.owner !== _accountId) return; st.pending[k] = 1; _prefSaveState(st); _prefPushSoon(); } // Every write of one of _PREF_KEYS: ``v`` a string, or null for the default. function _prefWrite(k, v) { var before = _rawGet(k); try { if (v == null) localStorage.removeItem(k); else localStorage.setItem(k, String(v)); } catch (e) {} _prefChanged(k, before); } // ── Storage Helpers ── function _getStorageJSON(key, fallback, session) { try { var v = (session ? sessionStorage : localStorage).getItem(key); return v ? JSON.parse(v) : fallback; } catch(e) { return fallback; } } // Read for keys that live in sessionStorage rather than localStorage. function _getSessionJSON(key, fallback) { return _getStorageJSON(key, fallback, true); } // The Almanac's chosen place ({lat, lon, name}) or null: kept on this device, // with the session copy older builds wrote as the fallback. function _almChosenPlace() { return _getStorageJSON(SK.ALMANAC_PLACE, null) || _getSessionJSON(SK.ALMANAC_LOC, null); } // Which hemisphere the Almanac's sky is drawn for: the chosen place, else the // device's time zone (zone-places.js, the table the sky uses), else null: the // sky does not know, so nothing season-shaped is said. The table is fetched // on first need and the Discover row drawn again when it lands. var _zonePlacesLoading = false, _discoverDrawn = null; function _almHemisphere() { var p = _almChosenPlace(); if (p) return p.lat < 0 ? 'south' : 'north'; if (typeof _skyZonePlace !== 'function') { if (!_zonePlacesLoading) { _zonePlacesLoading = true; var sc = document.createElement('script'); sc.src = '/static/zone-places.js?v=45'; sc.onload = function() { var d = _discoverDrawn; if (d && d.el.isConnected) _renderDiscover(d.el, d.items); }; document.head.appendChild(sc); } return null; } var tz = null; try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone; } catch(e) {} var z = _skyZonePlace(tz); return z ? (z[0] < 0 ? 'south' : 'north') : null; } // "Spring 41%": the season the Today card names and how far through it is, // from the hemisphere the sky is drawn for. Null hemisphere (the place is not // known): no season, rather than the wrong one. var _SEASONS_NORTH = ['winter', 'spring', 'summer', 'autumn', 'winter']; var _SEASONS_SOUTH = ['summer', 'autumn', 'winter', 'spring', 'summer']; function _todaySeason(now, hemi) { if (!hemi) return ''; var y = now.getFullYear(), keys = hemi === 'south' ? _SEASONS_SOUTH : _SEASONS_NORTH; var bounds = [ { k: 0, s: new Date(y - 1, 11, 21), e: new Date(y, 2, 20) }, { k: 1, s: new Date(y, 2, 20), e: new Date(y, 5, 21) }, { k: 2, s: new Date(y, 5, 21), e: new Date(y, 8, 22) }, { k: 3, s: new Date(y, 8, 22), e: new Date(y, 11, 21) }, { k: 4, s: new Date(y, 11, 21), e: new Date(y + 1, 2, 20) } ]; for (var i = 0; i < bounds.length; i++) { if (now >= bounds[i].s && now < bounds[i].e) return t('season_' + keys[bounds[i].k]) + ' ' + fmtPct((now - bounds[i].s) / (bounds[i].e - bounds[i].s) * 100); } return ''; } function _setStorageJSON(key, value) { if (_isPrefKey(key)) { _prefWrite(key, JSON.stringify(value)); return; } try { localStorage.setItem(key, JSON.stringify(value)); } catch(e) {} } function _getStorageFlag(key) { return localStorage.getItem(key) === '1'; } // ── Whole-app theme (Auto / Dark / Light / Red) ── // The token palette in app.css is driven by data-theme on . Auto mode // resolves the OS preference to a concrete 'dark'|'light' and stamps the SAME // attribute, so the CSS has one code path (no reliance on prefers-color-scheme // in the stylesheet). The head bootstrap sets it pre-paint; this re-applies on // load and, in Auto, live-tracks the media query. // // Red is a theme like the others, kept under the same key: it is Dark with the // night-red class on , which app.css / apps.css turn into deep red on // black so looking at the phone does not cost night vision. Every view reads // that one class; the sky's and the Field Guide's switches are shortcuts that // choose this theme (_nightSet). var APP_THEMES = ['auto', 'dark', 'light', 'red']; var APP_THEME_RED = 'red', NIGHT_CLASS = 'night-red'; // The browser's own chrome (address bar, status area) follows this while Red is on. var NIGHT_THEME_COLOR = '#000000'; function _appTheme() { var v = localStorage.getItem(SK.APP_THEME); return APP_THEMES.indexOf(v) >= 0 ? v : 'auto'; } function _nightRedOn() { return _appTheme() === APP_THEME_RED; } function _prefersLight() { return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches); } // Resolve a stored mode to the concrete theme actually painted. Auto → the OS // preference, dark fallback (matches the index.html bootstrap exactly). Red is // dark underneath: every dark-only rule still holds, then night-red recolours. function _resolveAppTheme(mode) { mode = mode || _appTheme(); if (mode === 'light') return 'light'; if (mode === 'dark' || mode === APP_THEME_RED) return 'dark'; return _prefersLight() ? 'light' : 'dark'; } function _appThemeIsDark() { return _resolveAppTheme() === 'dark'; } // The colour the browser paints behind the notch and the status bar: black in // Red, and while a PDF is read the colour of its top bar (the reader's own // --bg), so the band under the notch is the bar's and stays so. Otherwise none. function _themeColorNow() { if (_nightRedOn()) return NIGHT_THEME_COLOR; if (typeof _pdfReading !== 'undefined' && _pdfReading) return getComputedStyle(document.documentElement).getPropertyValue('--bg').trim() || null; return null; } function _syncThemeColor() { var c = _themeColorNow(); var meta = document.querySelector('meta[name="theme-color"]'); if (c && !meta) { meta = document.createElement('meta'); meta.name = 'theme-color'; document.head.appendChild(meta); } if (meta) { if (c) meta.content = c; else meta.remove(); } } function _applyAppTheme() { var t = _resolveAppTheme(); var el = document.documentElement; var red = _nightRedOn(); el.setAttribute('data-theme', t); // Keep the UA surface (scrollbars, form controls, Safari's tab backdrop) in // sync with the app theme — this is what prevents the dark compositor flash // on tab re-activation. Mirrors the head bootstrap. el.style.colorScheme = t; el.classList.toggle(NIGHT_CLASS, red); _syncThemeColor(); var btn = document.getElementById('night-btn'); if (btn) btn.setAttribute('aria-pressed', red ? 'true' : 'false'); _syncFrameNight(null); } // The sky's, the Field Guide's and the header's switch: Red on, or back to what // it replaced. The one door a switch uses, so there is one key and one apply. function _nightSet(on) { var back = localStorage.getItem(SK.APP_THEME_BEFORE_RED); _setAppTheme(on ? APP_THEME_RED : (APP_THEMES.indexOf(back) >= 0 && back !== APP_THEME_RED ? back : 'auto')); } function _nightToggle() { _nightSet(!_nightRedOn()); } function _setAppTheme(mode) { if (APP_THEMES.indexOf(mode) < 0) mode = 'auto'; var cur = _appTheme(); if (mode === APP_THEME_RED && cur !== APP_THEME_RED) _prefWrite(SK.APP_THEME_BEFORE_RED, cur); _prefWrite(SK.APP_THEME, mode === 'auto' ? null : mode); _appThemeChanged(); } // Everything that follows a theme change, whoever made it (the selector here, // a switch in an app page's frame, another tab: the storage event below). function _appThemeChanged() { _applyAppTheme(); // Repaint the segmented control's active state in place, and re-apply the // article appearance: on Match Zimi, this is the setting it matches. var seg = document.getElementById('app-theme-seg'); if (seg) seg.innerHTML = _appThemeSegInner(); var hint = document.getElementById('app-theme-hint'); if (hint) hint.innerHTML = _appThemeHintHtml(); try { _applyArticleDarken(_readerFrameDoc()); } catch (e) {} _reapplyReaderThemeIfAuto(); } window.addEventListener('storage', function(e) { if (e.key === SK.APP_THEME || e.key === null) _appThemeChanged(); }); // When the reader theme is set to Auto, it follows the app theme — so an app // theme change (manual or OS flip) must re-stamp an open reader. Hoisted, so it // can be called from the app-theme handlers above the reader definitions. function _reapplyReaderThemeIfAuto() { if (typeof _readerThemeMode !== 'function' || _readerThemeMode() !== 'auto') return; try { var d = _readerFrameDoc(); if (d && _readerViewOn) _applyReaderTheme(d); } catch (e) {} try { _tintReaderChrome(); } catch (e) {} } // Install once: when in Auto, a live OS light/dark flip re-resolves the theme. var _appThemeMediaBound = false; function _bindAppThemeMedia() { if (_appThemeMediaBound || !window.matchMedia) return; _appThemeMediaBound = true; var mq = window.matchMedia('(prefers-color-scheme: dark)'); var onFlip = function() { if (_appTheme() !== 'auto') return; // explicit choice ignores the OS _applyAppTheme(); try { _applyArticleDarken(_readerFrameDoc()); } catch (e) {} _reapplyReaderThemeIfAuto(); }; if (mq.addEventListener) mq.addEventListener('change', onFlip); else if (mq.addListener) mq.addListener(onFlip); // Safari <14 } // ── Article appearance ── // Two settings, and they answer different questions. // // Article theme WHEN articles are dark. Match Zimi (the default), or // pinned dark/light regardless. // Simulate dark WHAT to do about an article that has no dark mode of its // own — invert it, or leave it light. // // The chain is OS -> Zimi -> articles. Zimi may follow the system; articles // follow ZIMI. That middle link is the part that used to be missing: an // article with its own dark mode read prefers-color-scheme, which is the // SYSTEM's answer, so a dark Zimi on a light Mac served light articles. var ARTICLE_THEMES = ['match', 'dark', 'light']; function _articleTheme() { var v = localStorage.getItem(SK.ARTICLE_THEME); return ARTICLE_THEMES.indexOf(v) < 0 ? 'match' : v; } function _articlesAreDark() { if (_nightRedOn()) return true; // no white page anywhere in Red, whatever was pinned var m = _articleTheme(); return m === 'match' ? _appThemeIsDark() : m === 'dark'; } function _setArticleTheme(mode) { if (ARTICLE_THEMES.indexOf(mode) < 0) mode = 'match'; _prefWrite(SK.ARTICLE_THEME, mode === 'match' ? null : mode); var seg = document.getElementById('article-theme-seg'); if (seg) seg.innerHTML = _articleThemeSegInner(); try { _applyArticleDarken(_readerFrameDoc()); } catch (e) {} _reapplyReaderThemeIfAuto(); } // Default on. Most ZIMs have no dark mode, so off would mean switching Zimi to // dark leaves the whole library blazing white — which is the complaint this // setting exists to answer. function _darkenArticlesOn() { return localStorage.getItem(SK.DARKEN_ARTICLES) !== '0'; } // Whether the person TICKED the box, as opposed to leaving it at its default. // The difference matters for a captured site: left alone, a capture keeps the // design it was captured with; ticked, the person has asked for dark and gets // it. Before this, a ticked box did nothing on a capture (#65), which on a // library of captures reads as a checkbox that does nothing at all. function _darkenArticlesExplicit() { return localStorage.getItem(SK.DARKEN_ARTICLES) === '1'; } // What to ask the page to paint. Pure, so the table below can be a test. // // 'dark' / 'light' push the scheme: articles follow Zimi, not the system // '' hands the page back its own judgement // // Reader View and the viewers we ship under /static/ are ours and own their // themes; pushing a scheme at them would fight their own control. function _articleScheme(readerViewOn, loc, articlesDark) { if (readerViewOn) return ''; if ((loc || '').indexOf('/static/') === 0) return ''; return articlesDark ? 'dark' : 'light'; } // And whether to simulate one. Only ever reached for a page that was ASKED for // dark and came back light — `paintsDark` is measured after the ask, not // guessed from the markup, because "has a dark mode" is not something a // document reliably declares. function _shouldSimulateDark(articlesDark, simulate, explicit, readerViewOn, loc, isCapture, paintsDark) { if (!articlesDark) return false; if (_articleScheme(readerViewOn, loc, articlesDark) === '') return false; if (paintsDark) return false; // it has its own; nothing to fake if (!simulate) return false; if (isCapture && !explicit) return false; // a capture keeps its own design return true; } function _setDarkenArticles(on) { _prefWrite(SK.DARKEN_ARTICLES, on ? '1' : '0'); try { _applyArticleDarken(_readerFrameDoc()); } catch (e) {} } // ── App-theme segmented control (Display settings) ── // Auto / Dark / Light / Red, matching the reader palette's control language (pills). var _APP_THEME_ICONS = { auto: '', dark: '', light: '', // An eye adjusted to the dark: Red is for night vision. red: '' }; // A segmented control's buttons: one per value, the current one on. `setter` // is the global each button calls with its value; `keyPrefix` + value is its // label. Every such control in Settings is this one shape. function _segButtonsHtml(values, cur, icons, setter, keyPrefix) { return values.map(function(m) { var on = m === cur; return ''; }).join(''); } function _segHtml(id, labelKey, inner) { return '
' + inner + '
'; } function _appThemeSegInner() { return _segButtonsHtml(APP_THEMES, _appTheme(), _APP_THEME_ICONS, '_setAppTheme', 'theme_'); } // Article theme reuses the app-theme control's icons and chrome — same shape, // same language, one row below it — with `match` in the slot where the app // control says `auto`. Both answer "follow something else, or pin it". var _ARTICLE_THEME_ICONS = { match: _APP_THEME_ICONS.auto, dark: _APP_THEME_ICONS.dark, light: _APP_THEME_ICONS.light }; function _articleThemeSegInner() { return _segButtonsHtml(ARTICLE_THEMES, _articleTheme(), _ARTICLE_THEME_ICONS, '_setArticleTheme', 'article_theme_'); } function _articleThemeSegHtml() { return _segHtml('article-theme-seg', 'article_theme', _articleThemeSegInner()); } // What the choice means, in the person's words: Auto's line by default, Red's while Red is on. function _appThemeHintHtml() { return tH(_nightRedOn() ? 'app_theme_hint_red' : 'app_theme_hint'); } function _appThemeSegHtml() { return _segHtml('app-theme-seg', 'app_theme', _appThemeSegInner()); } // ── Article dark adaptation (raw / non-Reader-View pages) ── var _ARTICLE_DARKEN_STYLE_ID = 'zimi-article-darken'; // The invert-based adaptation. invert(1) hue-rotate(180deg) on the root flips the // page to dark while roughly preserving hue; media + math + anything painting its // own background image is counter-inverted so photos/diagrams/formulas stay true. // A slightly-off-white root background gives the invert a clean white to flip to // pure near-black, so transparent pages don't leave a grey haze. // In Red a white picture would be the brightest thing on the screen: media is dimmed before it is flipped // back (the root's flip then turns the dimming into dimming, not into a brighter page). var _NIGHT_MEDIA_DIM = 'brightness(.5) '; // And on a page that was not flipped (it has a dark of its own, or is Reader View). var _NIGHT_MEDIA_CSS = 'img,video,canvas{filter:brightness(.5) !important}'; function _articleDarkenCss(dimMedia) { var flipBack = (dimMedia ? _NIGHT_MEDIA_DIM : '') + 'invert(1) hue-rotate(180deg)'; return [ 'html{background:#ffffff !important;filter:invert(1) hue-rotate(180deg) !important;', '-webkit-filter:invert(1) hue-rotate(180deg) !important}', // Counter-invert media + anything painting its own image so photos, diagrams, // maps and icons keep true colour under the root flip. Filters COMPOUND down // the tree: a counter-inverted holding a counter-inverted // flipped the photo back to a negative — apple.com's portraits on Eric's // phone (2026-09-03). So is not in the list (its is what // paints), and nothing inside a counter-inverted element is filtered again. // Elements whose STYLESHEET paints a picture (a hero as a class background) // are marked by _applyArticleDarken, since a selector cannot see computed // style. 'img,video,canvas,svg,image,embed,object,iframe,', '[style*="background-image"],[data-zimi-bgimg]{filter:' + flipBack + ' !important;', '-webkit-filter:' + flipBack + ' !important}', '[style*="background-image"] img,[style*="background-image"] video,[style*="background-image"] svg,', '[style*="background-image"] canvas,[data-zimi-bgimg] img,[data-zimi-bgimg] video,', '[data-zimi-bgimg] svg,[data-zimi-bgimg] canvas,[data-zimi-bgimg] [data-zimi-bgimg],', '[style*="background-image"] [style*="background-image"]{filter:none !important;-webkit-filter:none !important}', // MediaWiki math is black line-art on a TRANSPARENT ground — an fallback // (caught by the img rule above) or an inline . It must invert WITH the // page like text, NOT be counter-inverted, or the glyphs stay black on the dark // page and vanish. filter:none here leaves only the root flip → white glyphs. // Outranks the generic img/svg counter-invert by class specificity. '.mwe-math-element,.mwe-math-element img,.mwe-math-element svg,', '.mwe-math-fallback-image-inline,.mwe-math-fallback-image-display{', 'filter:none !important;-webkit-filter:none !important}' ].join(''); } // A page "declares its own dark scheme" (so we must NOT invert it, or we'd flip it // back to blinding white) when it opts into dark via // or its body already paints a dark background. // The page's own background decides. With none (body and root both // transparent) the browser paints the canvas, which follows the color-scheme // _askArticleFor just set, and draws default text to match: then the text // colour is the honest answer. Inverting such a page turned its white text // black on a canvas the filter cannot reach (black on black). var _DARK_BG_MAX_LUM = 0.4, _LIGHT_TEXT_MIN_LUM = 0.6, _OPAQUE_MIN_ALPHA = 0.5; function _cssColorLum(css) { var m = css && css.match(/rgba?\(([^)]+)\)/); if (!m) return null; var p = m[1].split(',').map(parseFloat); return { lum: (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) / 255, alpha: p.length > 3 ? p[3] : 1 }; } function _articleHasNoBackground(doc) { try { var win = doc.defaultView; var body = _cssColorLum(win.getComputedStyle(doc.body).backgroundColor); var root = _cssColorLum(win.getComputedStyle(doc.documentElement).backgroundColor); return !(body && body.alpha >= _OPAQUE_MIN_ALPHA) && !(root && root.alpha >= _OPAQUE_MIN_ALPHA); } catch (e) { return false; } } function _setCanvasBackground(doc) { var html = doc.documentElement; html.style.backgroundColor = 'Canvas'; html.dataset.zimiCanvasBg = '1'; } // A page's own dark mode turns its text light but cannot reach a colour // written on an element (a MediaWiki template's style="background-color: // #FEC2DC"): light text on a light box, unreadable in Dark and in Red (#119, // the LGBTQIA+ Wiki). Such a box keeps its hue and goes dark like the page's // own surfaces; its colour comes back with the light face. var _ISLAND_DARK_L = 0.2; // the box's lightness (HSL) once dark function _darkenLightIslands(doc) { var win = doc.defaultView; doc.querySelectorAll('body [style*="background"]').forEach(function(el) { var cs = win.getComputedStyle(el), bg = _cssColorLum(cs.backgroundColor), text = _cssColorLum(cs.color); if (!bg || !text || bg.alpha < _OPAQUE_MIN_ALPHA || bg.lum < _DARK_BG_MAX_LUM || text.lum < _DARK_BG_MAX_LUM) return; el.dataset.zimiBg = el.style.backgroundColor; el.style.setProperty('background-color', _cssColorWithLightness(cs.backgroundColor, _ISLAND_DARK_L), 'important'); }); } function _restoreLightIslands(doc) { if (!doc || !doc.querySelectorAll) return; doc.querySelectorAll('[data-zimi-bg]').forEach(function(el) { el.style.removeProperty('background-color'); if (el.dataset.zimiBg) el.style.backgroundColor = el.dataset.zimiBg; delete el.dataset.zimiBg; }); } // An rgb()/rgba() colour, its hue and saturation kept, at lightness ``l`` (0-1). function _cssColorWithLightness(css, l) { var p = css.match(/rgba?\(([^)]+)\)/)[1].split(',').map(parseFloat); var r = p[0] / 255, g = p[1] / 255, b = p[2] / 255, max = Math.max(r, g, b), min = Math.min(r, g, b); var L = (max + min) / 2, d = max - min, s = d ? d / (1 - Math.abs(2 * L - 1)) : 0, h = 0; if (d) h = max === r ? ((g - b) / d + 6) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4; var c = (1 - Math.abs(2 * l - 1)) * s, x = c * (1 - Math.abs(h % 2 - 1)), m = l - c / 2; var rgb = [[c, x, 0], [x, c, 0], [0, c, x], [0, x, c], [x, 0, c], [c, 0, x]][Math.floor(h) % 6]; return 'rgb(' + rgb.map(function(v) { return Math.round((v + m) * 255); }).join(', ') + ')'; } function _dropCanvasBackground(doc) { var html = doc && doc.documentElement; if (!html || !html.dataset.zimiCanvasBg) return; html.style.backgroundColor = ''; delete html.dataset.zimiCanvasBg; } function _articleDeclaresDark(doc) { try { var meta = doc.querySelector('meta[name="color-scheme"]'); if (meta && /dark/i.test(meta.getAttribute('content') || '')) return true; } catch (e) {} try { var win = doc.defaultView; var bodyBg = _cssColorLum(win.getComputedStyle(doc.body).backgroundColor); if (bodyBg && bodyBg.alpha >= _OPAQUE_MIN_ALPHA) return bodyBg.lum < _DARK_BG_MAX_LUM; var rootBg = _cssColorLum(win.getComputedStyle(doc.documentElement).backgroundColor); if (rootBg && rootBg.alpha >= _OPAQUE_MIN_ALPHA) return rootBg.lum < _DARK_BG_MAX_LUM; var text = _cssColorLum(win.getComputedStyle(doc.body).color); if (text) return text.lum > _LIGHT_TEXT_MIN_LUM; } catch (e) {} return false; } // A picture painted by a stylesheet rule (apple.com's hero is a class with a // background image) is invisible to the counter-invert selector, which can // only see inline style. Mark such elements so the stylesheet rule can find // them. Bounded walk; a gradient is not a picture. var _BGIMG_SCAN_MAX = 4000; function _markStylesheetPictures(doc) { try { var win = doc.defaultView; var all = doc.body ? doc.body.getElementsByTagName('*') : []; for (var i = 0; i < all.length && i < _BGIMG_SCAN_MAX; i++) { var el = all[i]; if (el.hasAttribute('data-zimi-bgimg')) continue; var st = el.getAttribute('style') || ''; if (st.indexOf('background-image') !== -1) continue; // the selector sees it var bg = win.getComputedStyle(el).backgroundImage; if (bg && bg !== 'none' && bg.indexOf('url(') !== -1) el.setAttribute('data-zimi-bgimg', '1'); } } catch (e) {} } // Apply or remove the dark adaptation on a raw article document. No-op for // Reader View (it owns its themes), PDF/static viewer pages, and pages that ship // their own dark scheme. Idempotent — safe to call on any frame.onload or toggle. // A website Zimi captured is a designed page, not an article to adapt: cnn.com // and apple.com on Eric's phone in dark mode (2026-09-03) came out as a black // page with no pictures and a hero with negative portraits, after a gate in // light mode had passed them. The invert is for wiki-style article ZIMs whose // pages have no design of their own. Created ZIMs and bookmark exports keep // their colours; the app chrome around them stays dark. // A capture may hold both of the site's faces. Open the one that matches the // theme the person is reading in, so a captured site behaves the way the live // one did rather than always showing whichever face the capture was taken in. function _facePathFor(zimName, path) { try { var info = _zimInfo(zimName); var faces = info && info.faces; if (!faces || !faces.other || !faces.other.path) return path; // Only the entry the ZIM opens on has a counterpart; a link deeper into // the capture is left exactly as it was asked for. var main = info.main_path || 'A/index'; if (path !== main) return path; // The article theme, not the app theme: this is the article. Identical on // Match Zimi, which is everyone who has not pinned it. var want = _articlesAreDark() ? 'dark' : 'light'; if (faces.other.scheme === want) return faces.other.path; return path; } catch (e) { return path; } } function _articleIsWebCapture() { try { var z = currentArticle && _zimsByName && _zimsByName.get(currentArticle.zim); return !!(z && (z.category === 'Created' || z.zimi_export)); } catch (e) { return false; } } function _dropArticleDarken(doc) { var existing = doc.getElementById(_ARTICLE_DARKEN_STYLE_ID); if (existing && existing.parentNode) existing.parentNode.removeChild(existing); } function _applyArticleDarken(doc) { if (!doc || !doc.documentElement) return; var loc = ''; try { loc = doc.defaultView.location.pathname; } catch (e) {} var dark = _articlesAreDark(); var scheme = _articleScheme(_readerViewOn, loc, dark); // Our own invert would answer the question we are about to ask, so it comes // off first. Nothing repaints between here and the end of this function — // the browser paints between tasks, not inside one. _dropArticleDarken(doc); _dropCanvasBackground(doc); _restoreLightIslands(doc); _askArticleFor(doc, scheme); // Asked for dark and STILL painting light: this page has no dark mode of its // own. Measured rather than assumed — an unstyled ZIM article, a MediaWiki // one and a captured site are indistinguishable from the outside until you // ask them. var paintsDark = _articleDeclaresDark(doc); // A page with no background of its own that follows the scheme (its text // turned light) would show the reader frame's white through it: white on // white. It gets the scheme's own page colour instead. if (scheme === 'dark' && paintsDark && _articleHasNoBackground(doc)) _setCanvasBackground(doc); if (scheme === 'dark' && paintsDark) _darkenLightIslands(doc); // Red is for night vision: a page that has no dark mode is darkened whatever // the setting says, a captured site included, and its pictures are dimmed. var red = _nightRedOn() && loc.indexOf('/static/') !== 0 && !_docIsOurOwnPage(doc) && !_docBroughtRed(doc); var simulate = _shouldSimulateDark(dark, _darkenArticlesOn() || red, _darkenArticlesExplicit() || red, _readerViewOn, loc, _articleIsWebCapture(), paintsDark); if (doc.head && (simulate || red)) { var st = doc.createElement('style'); st.id = _ARTICLE_DARKEN_STYLE_ID; st.textContent = simulate ? _articleDarkenCss(red) : _NIGHT_MEDIA_CSS; doc.head.appendChild(st); } if (simulate) _markStylesheetPictures(doc); } // Ask the page itself for a face. Passing '' hands it back its own judgement. // // Three mechanisms, because a page can carry any of them: // // 1. `color-scheme` on the root. This governs the UA surface inside the // document — scrollbars, form controls, the canvas behind a transparent // body — and nothing else. It does NOT decide how prefers-color-scheme // resolves. The comment that used to sit here said it did; measured in // Chromium (2026-09-13), setting it on the article root, on the iframe // element, and on the embedder all leave the query answering the OS. // So the light-face half of #65 only ever worked on MediaWiki, whose // theming is a class. On a captured site with a media-query dark mode it // did nothing at all, silently. // // 2. The media queries themselves, rewritten in the page's own stylesheets. // prefers-color-scheme cannot be overridden from outside, so the // condition is edited instead — see _retuneColorSchemeQueries. // // 3. MediaWiki's theme class. Vector 2022 stamps `skin-theme-clientpref-os` // on and its CSS reads the class, no query involved. That covers // every Wikipedia-family ZIM, which is most of a typical library. // // A page can also switch by script and answer to none of these — that is the // second face the CAPTURE stores, chosen at read time by _faceForTheme. // // Rewriting somebody's media query is a liberty, so it is surgical: the // prefers-color-scheme term alone is swapped for one that is always or never // true, and the rest of the condition (a width, a print target) is left // standing. `not all` on the whole rule would have thrown those away. var _PCS_ALWAYS = '(min-width: 0px)'; var _PCS_NEVER = '(min-width: 999999px)'; var _PCS_DARK_RE = /\(\s*prefers-color-scheme\s*:\s*dark\s*\)/gi; var _PCS_LIGHT_RE = /\(\s*prefers-color-scheme\s*:\s*light\s*\)/gi; var _PCS_ANY_RE = /prefers-color-scheme/i; // Pure, so the table of conditions can be a test. function _retunedQuery(original, mode) { if (!mode) return original; return original .replace(_PCS_DARK_RE, mode === 'dark' ? _PCS_ALWAYS : _PCS_NEVER) .replace(_PCS_LIGHT_RE, mode === 'light' ? _PCS_ALWAYS : _PCS_NEVER); } // The original condition text, so handing the page back restores it rather // than leaving whichever face we last chose. Keyed by the rule, so it is // collected with the document. var _pcsOriginal = new WeakMap(); // Bounded like the picture scan, but generously: running out part-way is the // expensive failure, not the cheap one. A dark block left un-rewritten means // the page answers "light" when asked for dark, and then gets inverted on top // of the dark mode it already had. Measured at 8ms cold and 1-2ms warm over a // 12,060-rule sheet, once per article load and off the first paint, so the // ceiling is here for pathology rather than for ordinary pages. var _PCS_SCAN_MAX = 50000; // A dark block is not always at the top of a sheet: @layer and @supports both // nest, and a modern build tool emits @layer around nearly everything. Depth // is capped anyway — a query buried five levels down is not a theme. var _PCS_MAX_DEPTH = 4; function _retuneColorSchemeQueries(doc, mode) { var sheets; try { sheets = doc.styleSheets; } catch (e) { return; } var budget = {left: _PCS_SCAN_MAX}; for (var i = 0; i < sheets.length && budget.left > 0; i++) { var rules; try { rules = sheets[i].cssRules; } catch (e) { continue; } // cross-origin _retuneRuleList(rules, mode, budget, 0); } } function _retuneRuleList(rules, mode, budget, depth) { if (!rules || depth > _PCS_MAX_DEPTH) return; for (var j = 0; j < rules.length && budget.left > 0; j++) { budget.left--; var rule = rules[j]; if (!rule) continue; if (rule.media) { var original = _pcsOriginal.get(rule); if (original === undefined && _PCS_ANY_RE.test(rule.media.mediaText || '')) { original = rule.media.mediaText; _pcsOriginal.set(rule, original); } if (original !== undefined) { var want = _retunedQuery(original, mode); if (rule.media.mediaText !== want) { try { rule.media.mediaText = want; } catch (e) {} } } } // Grouping rules carry their own list. Reading it can throw on a rule type // the browser exposes without children, so it is asked for, not assumed. var inner = null; try { inner = rule.cssRules; } catch (e) {} if (inner && inner.length) _retuneRuleList(inner, mode, budget, depth + 1); } } var _MW_THEME_RE = /\bskin-theme-clientpref-\S+/; var _MW_THEME_CLASS = {light: 'skin-theme-clientpref-day', dark: 'skin-theme-clientpref-night'}; function _askArticleFor(doc, mode) { try { var html = doc.documentElement; html.style.colorScheme = mode || ''; _retuneColorSchemeQueries(doc, mode); if (!_MW_THEME_RE.test(html.className)) return; var want = _MW_THEME_CLASS[mode]; if (want) { // Remember what the ZIM shipped, once, so handing the page back to // itself later restores `-os` rather than whichever face we last chose. if (!html.dataset.zimiMwTheme) { html.dataset.zimiMwTheme = html.className.match(_MW_THEME_RE)[0]; } html.className = html.className.replace(_MW_THEME_RE, want); } else if (html.dataset.zimiMwTheme) { html.className = html.className.replace(_MW_THEME_RE, html.dataset.zimiMwTheme); delete html.dataset.zimiMwTheme; } } catch (e) {} } // Shared "dismiss on outside interaction" for menus/popovers. Registers a // capture-phase click listener on BOTH the parent document AND the reader iframe // document. The iframe half is the crucial bit: the reader content is iframed, // so a tap inside the article never bubbles to the parent — without listening on // the frame doc, an open palette/menu would stay stuck when you tap the article. // `keepEls` are elements whose interior clicks must NOT dismiss (the menu itself // and, usually, its trigger so a second tap toggles cleanly instead of // double-firing). `onDismiss` runs on the first outside interaction; if it // returns false the dismissal is vetoed and the listener keeps watching (e.g. a // transient locked state). Returns a detach fn; also auto-detaches once it fires. function _dismissOnOutside(keepEls, onDismiss) { keepEls = (Array.isArray(keepEls) ? keepEls : [keepEls]).filter(Boolean); function inside(target) { return keepEls.some(function(el) { return el.contains && el.contains(target); }); } var detached = false; function detach() { if (detached) return; detached = true; document.removeEventListener('click', handler, true); var f = _readerFrameDoc(); if (f) { try { f.removeEventListener('click', handler, true); } catch (_) {} } } function handler(e) { if (e && e.target && inside(e.target)) return; if (onDismiss() === false) return; detach(); } // Defer a tick so the click that opened the menu doesn't instantly dismiss it. setTimeout(function() { document.addEventListener('click', handler, true); var f = _readerFrameDoc(); if (f) { try { f.addEventListener('click', handler, true); } catch (_) {} } }, 0); return detach; } // A password an older version stored (zimi_manage_pw) is deleted on load; // that browser signs in once more and keeps a session token instead. (function _purgeStoredPassword() { try { localStorage.removeItem('zimi_manage_pw'); } catch (e) {} try { sessionStorage.removeItem('zimi_manage_pw'); } catch (e) {} })(); // ── Manage token storage ── // localStorage = persistent ("Remember me" checked). // sessionStorage = current-tab-only (default). Read both, prefer persistent. function _readManageToken() { return localStorage.getItem(SK.MANAGE_PW) || sessionStorage.getItem(SK.MANAGE_PW) || ''; } function _saveManageToken(token, remember) { // Clear both first so toggling "remember me" never leaves stale copies. localStorage.removeItem(SK.MANAGE_PW); sessionStorage.removeItem(SK.MANAGE_PW); localStorage.removeItem(SK.MANAGE_USER); sessionStorage.removeItem(SK.MANAGE_USER); if (!token) return; var store = remember ? localStorage : sessionStorage; store.setItem(SK.MANAGE_PW, token); if (typeof _accountRefresh === 'function') _accountRefresh(); // Persist the username alongside so it rides with the same remember scope. if (_manageUser) store.setItem(SK.MANAGE_USER, _manageUser); } function _readManageUser() { return localStorage.getItem(SK.MANAGE_USER) || sessionStorage.getItem(SK.MANAGE_USER) || ''; } function _clearManageToken() { localStorage.removeItem(SK.MANAGE_PW); sessionStorage.removeItem(SK.MANAGE_PW); localStorage.removeItem(SK.MANAGE_USER); sessionStorage.removeItem(SK.MANAGE_USER); } // Auth headers for every manage request: Bearer token + optional username. // One builder so the two dozen call sites can't drift out of sync. function _authHeaders(token) { token = token || _manageToken; var h = {}; if (token) { h['Authorization'] = 'Bearer ' + token; if (_manageUser) h['X-Zimi-User'] = _manageUser; } return h; } function _hasStoredManageToken() { return !!_readManageToken(); } // Your languages (Settings > Languages): the interface languages checked // under Show languages. Eric, 2026-10-05: "show languages dropdown under // show languages is a checklist of languages that can be enabled in the // UI". Checked ones are the top bar's language menu, and what already has a // language notion reads them: the catalog's filter (_zimMatchesLang), // search's language pills (_applyPreferredLanguages), the library's language // pills (yours first), Discover's picks (_featuredZimFor), the Dictionary's // languages and their order, and Zimipedia's language. Nothing stored: every // one checked, and nothing filtered. Zimi's own language is always among // them. A language beyond the ten (a Swahili ZIM) is the catalog's own pill. function _getPrefLanguages() { var v = _getStorageJSON(SK.PREF_LANGUAGES, []); v = Array.isArray(v) ? v.map(_normLang).filter(_isUiLang) : []; var ui = _uiLangPrimary(); if (v.length && v.indexOf(ui) < 0) v.unshift(ui); return v; } function _setPrefLanguages(langs) { if (langs.length && langs.length < _AVAILABLE_LANGS.length) _setStorageJSON(SK.PREF_LANGUAGES, langs); else _prefWrite(SK.PREF_LANGUAGES, null); } // Where your languages rank a language: its place among them, or after them. function _prefLangRank(code) { var prefs = _getPrefLanguages(), i = prefs.indexOf(_normLang(code)); return i < 0 ? prefs.length : i; } function _uiLangPrimary() { return String(_currentLang || 'en').split('-')[0]; } function _langPrimary(tag) { return String(tag || '').split('-')[0]; } function _isUiLang(c) { return _AVAILABLE_LANGS.some(function(l) { return l.code === c; }); } function _langChecked(c) { var p = _getPrefLanguages(); return !p.length || p.indexOf(c) >= 0; } // The interface languages the top bar's menu offers. function _offeredUiLangs() { return _AVAILABLE_LANGS.filter(function(l) { return _langChecked(l.code); }); } // Zimi switched to a language (the top bar, Zimipedia): checked from then on. function _keepUiLangChecked(lang) { var p = _getStorageJSON(SK.PREF_LANGUAGES, []); p = Array.isArray(p) ? p.map(_normLang).filter(_isUiLang) : []; if (p.length && p.indexOf(lang) < 0) { p.push(lang); _setPrefLanguages(p); } } // Settings > Languages: Show languages, and under it (while on) one folded // line, "Languages: English, Español", that opens to the ten, each a check, // its own name and Zimi's name for it. Zimi's own is checked and locked. var _LANG_LIST_ID = 'ms-lang-list'; var _WIKTIONARY_LANG_RE = /^wiktionary_([a-z]{2,3})(?:_|$)/; var _CHECK_ICON = ''; function _langsShown() { return !_getStorageFlag(SK.HIDE_LANG_CHOOSER); } function _langListOpen() { return _getStorageFlag(SK.LANG_LIST_OPEN); } function _toggleLangList() { _setStorageFlag(SK.LANG_LIST_OPEN, !_langListOpen()); _paintLangPrefs(); } // A language in itself (Français, עברית), as a reader finds their own. function _langOwnName(c) { return _langEndonym(c, _NATIVE_LANG_NAMES[c], _langDisplayName(c)); } function _langPrefSummary() { var mine = _getPrefLanguages(); return mine.length ? t('languages_line', { langs: mine.map(_langOwnName).join(', ') }) : t('languages_every'); } function _togglePrefLanguage(code) { if (code === _uiLangPrimary()) return; var current = _offeredUiLangs().map(function(l) { return l.code; }), i = current.indexOf(code); if (i >= 0) current.splice(i, 1); else current.push(code); _setPrefLanguages(current); _paintLangPrefs(); _paintVoices(); } function _setShowLangFilters(on) { _setStorageFlag(SK.HIDE_LANG_CHOOSER, !on); if (window.updateTopbar) updateTopbar(); _paintLangPrefs(); _paintVoices(); } // Show languages off hides the top bar's language button and the menu's // Language too (Eric, 2026-10-05): Zimi stays in the language it is in. // Where this viewer cannot open Settings (Manage off, locked, or behind a // password they do not hold) the button stays: a Zimipedia that switched // Zimi to Hebrew must always leave a way back. function _langSettingsReachable() { return manageEnabled && !_managePublicLocked && !_needsSignIn(); } function _langMenuHidden() { return !_langsShown() && _langSettingsReachable(); } function _langRowHtml(l) { var c = l.code, on = _langChecked(c), cur = c === _uiLangPrimary(), named = _langDisplayName(c) || c; return ''; } // The fold's line, and the list under it while it is open; nothing of // either while languages are not shown. function _paintLangPrefs() { var shown = _langsShown(), open = shown && _langListOpen(); var sum = document.getElementById('ms-lang-summary'); if (sum) sum.textContent = _langPrefSummary(); var fold = document.getElementById('ms-lang-fold'); if (fold) { fold.hidden = !shown; fold.setAttribute('aria-expanded', open); } var hint = document.getElementById('ms-lang-hint'); if (hint) hint.hidden = !open; var el = document.getElementById(_LANG_LIST_ID); if (!el) return; el.hidden = !open; el.innerHTML = open ? _AVAILABLE_LANGS.map(_langRowHtml).join('') : ''; } function _languagesCardHtml() { // No heading: the tab already says Language. The empty anchor keeps #languages. return '
' + '' + ''; } // ── Voices (Settings > Preferences > Voices) ── // One row per engine: its name, how many languages it says here and its // version, Hear, and a switch. Natural (Kokoro), one download for its // languages, is Got and Removed on its row. Say remembers the voice last // picked in the Dictionary's menu; nothing to prefer or remember here. Eric, // 2026-10-03: "We could actually drop both preferred and remember toggle by // just remembering... one for dictionary and one for reader views". // Kept in this browser and carried by My data: {voice: Say's last pick, // off: [engines switched off]}. The Dictionary reads and writes the same key. // Everyone sees what is here (Eric, 2026-10-03: "All users see all available // only admins can add"); an admin alone downloads and removes. var _VOICE_ENGINES = ['kokoro', 'piper', 'say', 'espeak', 'device']; // the server's order, then this browser's var _DEVICE_VOICE = 'device'; var _VOICES_WRAP_ID = 'ms-voices-wrap'; var _VOICES_MODE_ID = 'voices-mode'; var _VOICES_POLL_MS = 1000; // a download's bar moves while it is watched var _VOICE_BYTES_PER_MB = 1000 * 1000; // as fmtBytes counts, and the Dictionary's line var _VOICE_CONFIRM_MS = 4000; // as long as a ZIM's Redownload? waits for its second tap var _voicesTimer = null; // /dictionary/voices?all=1 for Settings, or null before (or without) it. var _voicesHere = null; // The shape before, a voice per language, was never released: dropped. try { localStorage.removeItem('zimi_voice_choices'); } catch (e) {} function _voiceMb(bytes) { return Math.round(bytes / _VOICE_BYTES_PER_MB); } function _voicePrefs() { var p = _getStorageJSON(SK.VOICE_PREFS, {}); p = p && typeof p === 'object' ? p : {}; var out = { voice: typeof p.voice === 'string' ? p.voice : '', off: Array.isArray(p.off) ? p.off.filter(function(e) { return _VOICE_ENGINES.indexOf(e) >= 0; }) : [] }; if (p.quiet === true) out.quiet = true; // kept only when it says something if (typeof p.read === 'string' && p.read) out.read = p.read; // Read aloud's own voice; absent = Automatic if (p.wait === true) out.wait = true; // Read aloud waits for a slow voice to get ahead (readaloud.js _ttsWaits) return out; } // Speaking, Settings > Voices' first switch (Eric, 2026-10-06: "a Speaking // toggle or something to turn all this off and hide it ... Some way that // hides it from everywhere even reader view"). Off: no Say, no voice menus, // no Discover speaker, no Read aloud, in this browser. The Dictionary reads // the same key. function _speakingOn() { return !_voicePrefs().quiet; } function _setSpeaking(on) { // A Remove waiting for its second tap would keep the panel from redrawing. var wrap = document.getElementById(_VOICES_WRAP_ID); if (wrap) wrap.querySelectorAll('.confirming').forEach(function(b) { b.classList.remove('confirming'); }); if (!on) { _ttsStop(); if (_discAudio) { try { _discAudio.pause(); } catch (e) {} } } _setVoicePrefs({ quiet: !on }); _markSpeaking(); updateTopbar(); } // Discover's speakers hide by a class: the cards are not drawn again for it. function _markSpeaking() { document.documentElement.classList.toggle('zimi-quiet', !_speakingOn()); } _markSpeaking(); function _setVoicePrefs(change) { var p = Object.assign(_voicePrefs(), change); if (p.voice && p.off.indexOf(p.voice) >= 0) p.voice = ''; if (p.read && p.off.indexOf(p.read) >= 0) p.read = ''; if (!p.quiet) delete p.quiet; if (!p.read) delete p.read; if (!p.wait) delete p.wait; if (!p.voice && !p.off.length && !p.quiet && !p.read && !p.wait) _prefWrite(SK.VOICE_PREFS, null); else _setStorageJSON(SK.VOICE_PREFS, p); _voicesTellDictionary(); _paintVoices(); } // 1.13.0's first builds kept {remember: false} to stop Say's menu from // remembering. Remembering is all there is now: the old switch is dropped. (function() { var p = _getStorageJSON(SK.VOICE_PREFS, null); if (p && typeof p === 'object' && 'remember' in p) _setStorageJSON(SK.VOICE_PREFS, _voicePrefs()); })(); function _setVoiceEngineOn(engine, on) { var off = _voicePrefs().off.filter(function(e) { return e !== engine; }); if (!on) off.push(engine); _setVoicePrefs({ off: off }); } function _voiceEngineName(e) { return e === _DEVICE_VOICE ? t('dictionary_voice_device') : t('voices_engine_' + e); } function _voicesDl() { return (_voicesHere && _voicesHere.downloading) || {}; } function _voiceRowFor(lang) { return ((_voicesHere && _voicesHere.langs) || []).filter(function(r) { return r.lang === lang; })[0] || null; } // System (the server's macOS `say`) and Device (this browser's own voices) // are the same voices when the page runs on the server's own Mac: the // desktop app, or a browser on localhost. Eric, 2026-10-05: "Wouldn't // System on a Mac and Device be the same!? Why two?" There, System alone. var _LOCAL_HOST_RE = /^(localhost|127\.0\.0\.1|\[::1\])$/; function _voiceSameMachine() { var says = ((_voicesHere && _voicesHere.langs) || []).some(function(r) { return (r.engines || []).indexOf('say') >= 0; }); return says && (!!window.pywebview || _LOCAL_HOST_RE.test(location.hostname)); } // The languages this browser's own voices say (none where System is them). function _deviceVoiceLangs() { var vs = [], out = []; if (_voiceSameMachine()) return out; try { vs = window.speechSynthesis ? window.speechSynthesis.getVoices() : []; } catch (e) {} vs.forEach(function(v) { var l = String(v.lang || '').toLowerCase().split(/[-_]/)[0]; if (l && out.indexOf(l) < 0) out.push(l); }); return out; } // Natural voices: the one download (Kokoro) that says several languages. function _voiceNatural() { return ((_voicesHere && _voicesHere.voices) || []).filter(function(v) { return v.langs; })[0] || null; } function _naturalLangs(v) { var out = []; (v ? v.langs : []).forEach(function(tag) { var p = _langPrimary(tag); if (out.indexOf(p) < 0) out.push(p); }); return out; } // May this viewer fetch a voice now: an admin, and the setting not Never // (ZIMI_OFFLINE is Never). function _voicesMayFetch() { var d = _voicesHere; return !!(d && d.can_change && d.setting && d.setting.mode !== 'never'); } // The engines here, each with the languages it says: the server's from its // answer, this browser's from its own voices. function _voiceEnginesHere() { var by = {}; ((_voicesHere && _voicesHere.langs) || []).forEach(function(row) { (row.engines || []).forEach(function(e) { (by[e] = by[e] || []).push(row.lang); }); }); var dev = _deviceVoiceLangs(); if (dev.length) by[_DEVICE_VOICE] = dev; return _VOICE_ENGINES.filter(function(e) { return by[e]; }).map(function(e) { return { engine: e, langs: by[e] }; }); } var _HEAR_ICON = ''; function _voiceAction(path, tag, label, extra) { return ''; } function _voiceRemoveHtml(tag, extra) { return _voiceAction('/manage/voices/remove', tag, tH('voices_remove'), ' data-confirm="' + escAttr(t('voices_remove_confirm')) + '"' + (extra || '')); } // A download's bar; _paintKept fills in how far it is, in place. function _voiceBarHtml() { return '
' + '
'; } // Languages by their own names, in their alphabet. function _langNamesSorted(codes) { return codes.map(_langOwnName).sort(cmpText); } // An engine's "N languages" lists them: in its title (a hover), and on a // tap as a line under the row (a phone has no hover). var _voiceCountOpen = {}; function _toggleVoiceCount(e) { _voiceCountOpen[e] = !_voiceCountOpen[e]; _paintVoices(); } function _voiceRowHtml(x, isOn, last) { var e = x.engine, js = JSON.stringify(e), nat = e === 'kokoro' ? _voiceNatural() : null; var dl = _voicesDl(), admin = !!(_voicesHere && _voicesHere.can_change); var busy = !!nat && dl.tag === nat.tag, here = !x.absent, open = !!_voiceCountOpen[e]; var v = _voicesHere && _voicesHere.versions && _voicesHere.versions[e]; var names = _langNamesSorted(x.langs).join(', '); var meta = '' + (v ? ' · ' + esc(v) : ''); // What each is, and how quick against how natural, in plain words (Eric, // 2026-10-05: "gently suggest which are faster or slower for their quality"). // One word for speed (Eric: "one word each ... instant fast slow"); System // and Device add what tells them apart. var what = ''; // Natural, an admin's: Remove (a second tap) when it is here, Get when it // is not (or a newer one is out), Cancel while it comes. var act = ''; if (nat && admin && here && !dl.tag) meta += ' · ' + _voiceRemoveHtml(nat.tag, ' data-quiet'); if (busy && admin) act += _voiceAction('/manage/voices/cancel', nat.tag, tH('cancel')); else if (nat && (!here || nat.newer) && _voicesMayFetch() && nat.runnable) { act += _voiceAction('/manage/voices/download', nat.tag, !dl.tag && dl.error === nat.tag ? tH('retry') : tH(nat.needs_setup ? 'voices_set_up_mb' : 'voices_get_mb', { mb: _voiceMb(nat.bytes) }), ' data-primary' + (dl.tag ? ' disabled' : '')); } // Clear: Get for the language Zimi is in, and a ▾ for any other checked // one, or all of them (Eric, 2026-10-06: "default to current language // there with dropdown showing all enabled languages, footer row All N // languages"). Fetched one after another. var pick = ''; // Once a Clear voice is here and on, the grid below gets the rest (Eric, // 2026-10-06: "No get other button after one is there and it's on"). if (e === 'piper' && admin && _voicesMayFetch() && !(here && isOn)) { var offers = _clearOffers(), clearBusy = _clearQueue.length || offers.some(function(o) { return o.tag === dl.tag; }); if (clearBusy) act += _voiceAction('/manage/voices/cancel', dl.tag || '', tH('cancel'), ' data-clear-cancel'); else if (offers.length) { var dis = dl.tag ? ' disabled' : ''; var first = offers.filter(function(o) { return o.lang === _uiLangPrimary(); })[0] || offers[0]; // One line, as Natural's Get: the language a quieter word beside the size. var split = '' + (offers.length > 1 ? '' : '') + ''; // Where Natural's sits; its own line only beside Hear and the switch, where it would wrap. if (here) pick += '
' + split + '
'; else act += split; if (_clearPickOpen && offers.length > 1) { var all = offers.map(function(o) { return o.tag; }); pick += '
' + offers.filter(function(o) { return o !== first; }).map(function(o) { return ''; }).join('') + '
'; } } } if (here) { act += '' + ''; } return ''; } // The downloads setting, an admin's, one quiet line under the voices. // A foot row of Settings > Voices: its label, then a few short choices (the segmented selector, not a menu). // opts: [{ v, label }]; `call` is the JS each button runs with its value. function _voiceFootSegHtml(id, labelKey, opts, cur, call, disabled) { return '
' + tH(labelKey) + '
' + opts.map(function(o) { var on = o.v === cur; return ''; }).join('') + '
'; } function _voicesModeHtml(s) { var opts = (s.choices || ['ask', 'auto', 'never']).map(function(m) { return { v: m, label: t('alm_earth_sat_' + m) }; }); var note = s.locked ? (s.locked === 'offline' ? t('net_offline') : t('env_controlled', { v: s.env || 'ZIMI_VOICE_DOWNLOADS' })) : ''; return _voiceFootSegHtml(_VOICES_MODE_ID, 'voices_mode', opts, s.mode, '_voicesSetMode', !!s.locked) + (note ? '
' + esc(note) + '
' : ''); } // Cache voices for faster playback: how much said audio is kept; Off keeps // it in memory only (nothing written to the data folder, a kindness to an SD card). function _voiceCacheHtml(c) { var opts = (c.choices || []).map(function(mb) { return { v: mb, label: mb ? mb + ' MB' : t('net_state_off') }; }); return _voiceFootSegHtml('voices-cache', 'voices_cache', opts, c.mb, '_voicesSetCache', !!c.env) + (c.mb && typeof c.used === 'number' ? '
' + esc(t('voices_cache_used', { used: fmtBytes(c.used), cap: c.mb + ' MB' })) + '
' : '') + '
' + esc(c.env ? t('env_controlled', { v: 'ZIMI_VOICE_CACHE_DIR' }) : t('voices_cache_desc')) + '
'; } // Under the engines, which flavor says which language here (Eric, // 2026-10-05: "a languages list with like dots representing the coverage // for each language across all four voice flavors"). A row per language, a // column per flavor here. A cell is one of: on (it says it now: downloaded, // or built in), rm (on, and a Clear voice downloaded for this language // alone: ✕ removes it), get (an admin may download it here), busy (coming) // or none. Natural is one shared download: removed on its engine row only. var _VG_GET_ICON = ''; var _HOVER_MQ = '(hover: hover)'; var _vgAllOpen = false; // All languages, open until the pane is drawn again function _toggleVgAll() { _vgAllOpen = !_vgAllOpen; _paintVoices(); } function _voiceCell(lang, e) { if (e === _DEVICE_VOICE) return { s: _deviceVoiceLangs().indexOf(lang) >= 0 ? 'on' : 'none' }; var dl = _voicesDl(), row = _voiceRowFor(lang); if (row && (row.engines || []).indexOf(e) >= 0) { if (e === 'piper' && row.remove && _voicesHere.can_change && !dl.tag) return { s: 'rm', tag: row.remove }; // Natural, one shared download, goes the same way (Eric, 2026-10-05: // "Maybe we allow also removing natural the same way"); its question // says every language goes with it. var shared = e === 'kokoro' && _voiceNatural(); if (shared && shared.installed && _voicesHere.can_change && !dl.tag) return { s: 'rm', tag: shared.tag, shared: true }; return { s: 'on' }; } var offer = null, nat = e === 'kokoro' && _voiceNatural(); if (nat && nat.runnable && (!nat.installed || nat.needs_setup) && _naturalLangs(nat).indexOf(lang) >= 0) offer = nat; if (e === 'piper' && row && row.piper && !row.piper.newer) offer = row.piper; if (offer && dl.tag === offer.tag) return { s: 'busy', tag: offer.tag }; if (offer && _voicesMayFetch()) return { s: 'get', tag: offer.tag, bytes: offer.bytes }; return { s: 'none' }; } function _vgCovered(lang, flavors) { return flavors.some(function(e) { return _voiceCell(lang, e).s !== 'none'; }); } // Every language a flavor here says (or could, downloaded). function _vgAllLangs() { var out = []; var add = function(c) { if (c && out.indexOf(c) < 0) out.push(c); }; ((_voicesHere && _voicesHere.langs) || []).forEach(function(r) { add(r.lang); }); _naturalLangs(_voiceNatural()).forEach(add); _deviceVoiceLangs().forEach(add); return out; } // The rows shown first: Zimi's language and the others checked under Show // languages, any language with a Clear voice downloaded for it, and the // library's languages (its Wiktionaries' among them) that a voice here says. // Eric, 2026-10-05: "Filter the voices list to the checked list above." function _vgMainLangs(flavors) { var zimi = [_uiLangPrimary()]; if (_langsShown()) _offeredUiLangs().forEach(function(l) { if (zimi.indexOf(l.code) < 0) zimi.push(l.code); }); return zimi; } function _vgByName(codes) { return codes.slice().sort(function(a, b) { return cmpText(_langDisplayName(a) || a, _langDisplayName(b) || b); }); } function _vgCellHtml(lang, e, name) { var x = _voiceCell(lang, e), off = _voicePrefs().off.indexOf(e) >= 0; var label = escAttr(t('voices_cell_' + x.s, { lang: name, voice: _voiceEngineName(e), mb: x.bytes ? _voiceMb(x.bytes) : '' })); var a = ' aria-label="' + label + '" title="' + label + '"', inner; if (x.s === 'get') { inner = ''; } else if (x.s === 'rm') { inner = ''; } else { inner = ''; } return '' + inner + ''; } // A language with more than one accent (English: United States, United // Kingdom) lets an admin pick which says it; one not here is fetched on the pick. function _regionName(r) { try { return new Intl.DisplayNames([_currentLang || 'en'], { type: 'region' }).of(r) || r; } catch (e) { return r; } } function _vgRegionHtml(lang) { var row = _voiceRowFor(lang), opts = (row && row.regions) || []; if (opts.length < 2 || !_voicesHere.can_change) return ''; var cur = row.region || opts[0].region, busy = _voicesDl().tag, label = escAttr(t('voices_region')); var curOpt = opts.filter(function(o) { return o.region === cur; })[0]; // The region's two letters, its name and what it costs on hover; each says only the voices that have it. var seg = '
' + opts.map(function(o) { var mb = o.tag && _voicesMayFetch() ? ' (' + _voiceMb(o.bytes) + ' MB)' : ''; var on = o.region === cur, title = escAttr(_regionName(o.region) + mb); return ''; }).join('') + '
'; // Which voices the accent reaches, when more than one says this language: the rest keep their own. var by = curOpt && curOpt.engines || []; var note = (row.engines || []).length > 1 && by.length ? '' + esc(t('voices_accent_in', { voices: by.map(_voiceEngineName).join(', ') })) + '' : ''; return '' + seg + note + ''; } function _voiceRegionPick(lang, region) { var o = (((_voiceRowFor(lang) || {}).regions) || []).filter(function(x) { return x.region === region; })[0]; _voicesSend('/manage/voices/choose', { lang: lang, region: region }, t('voices_failed')).then(function() { if (o && o.tag) _voicesSend('/manage/voices/download', { lang: o.tag }, t('voices_failed')); }); } // A row; the first row with a download coming carries its bar and Cancel. function _vgRowHtml(lang, flavors, state) { var own = _langOwnName(lang), named = _langDisplayName(lang) || lang, dl = _voicesDl(); var busy = !state.bar && dl.tag && flavors.some(function(e) { return _voiceCell(lang, e).s === 'busy'; }); if (busy) state.bar = true; return '
' + // In Zimi's language, the language's own name small after it (Eric, // 2026-10-05: "You know my language"). '' + esc(named) + '' + (named !== own ? '' + esc(own) + '' : '') + _vgRegionHtml(lang) + '' + flavors.map(function(e) { return _vgCellHtml(lang, e, named); }).join('') + '
' + (busy ? '
' + _voiceBarHtml() + (_voicesHere && _voicesHere.can_change ? _voiceAction('/manage/voices/cancel', dl.tag, tH('cancel')) : '') + '
' : ''); } function _voiceGridHtml() { var all = _vgAllLangs(); var flavors = _VOICE_ENGINES.filter(function(e) { return all.some(function(c) { return _voiceCell(c, e).s !== 'none'; }); }); if (!flavors.length) return ''; var main = _vgMainLangs(flavors); var rest = _vgByName(all.filter(function(c) { return main.indexOf(c) < 0 && _vgCovered(c, flavors); })); var state = {}; var head = '
' + flavors.map(function(e) { var n = escAttr(_voiceEngineName(e)); return '' + n + ''; }).join('') + '
'; var rows = function(codes) { return codes.map(function(c) { return _vgRowHtml(c, flavors, state); }).join(''); }; return '' + _voiceTestHtml(); } // How quick each voice is on this server, under its name in the table (Eric, // 2026-10-19: "show time to first word and all that? Set expectations but // also understand ourselves based on the hardware"; "add to the table"): // first words, first words after a rest (the model loading), and the // fastest speed it reads at without pausing. Measured by Test all voices and // by every reading; a release, an engine or a machine change clears them. // While a Test runs, the voice it is timing turns, and numbers from before it // stay dimmed until their voice's new ones come (Eric, 2026-10-20: "a // spinner on the ones currently being gathered ... old values dimmed"). function _vgTimingRowsHtml(flavors) { var tm = _voiceTimings(_voicesHere && _voicesHere.timings), run = (_voicesHere && _voicesHere.testing) || {}; if (!run.engine && !_voiceDeviceTesting && !flavors.some(function(e) { return tm[e]; })) return ''; var state = function(e) { if (e === _DEVICE_VOICE) return _voiceDeviceTesting ? 'busy' : ''; if (!run.engine) return ''; if (e === run.engine) return 'busy'; return tm[e] && tm[e].tested >= run.started ? '' : 'stale'; }; var row = function(label, cell) { return '
' + tH(label) + '' + flavors.map(function(e) { var st = state(e); return '' + (st === 'busy' ? '' : esc(tm[e] ? cell(tm[e], e) || '–' : '–')) + ''; }).join('') + '
'; }; var secs = function(s) { return typeof s === 'number' ? t('voices_secs', { s: _voiceSecs(s) }) : ''; }; return row('voices_t_cold', function(x) { return secs(x.cold_s); }) + row('voices_t_warm', function(x) { return secs(x.first_s); }) + row('voices_t_top', function(x, e) { if (!x.gaps && !x.rtf) return ''; var top = _TTS_GAP_RATES.filter(function(r) { return r >= 1 && _ttsKeepsUp(e, r, tm); }).pop(); return top ? _ttsRateLabel(top) : '<' + _ttsRateLabel(1); }); } function _voiceSecs(s) { if (s < _VOICE_SECS_MIN) return '<' + _voiceSecs(_VOICE_SECS_MIN); try { return s.toLocaleString(_currentLang || undefined, { maximumFractionDigits: s < 10 ? 1 : 0 }); } catch (e) { return String(Math.round(s)); } } // The one word, from what was measured here once it was (Eric, 2026-10-20: // "when we have the data ... still use relative terms? It's hard data to // convey"): how soon the first words come, or that it cannot keep up with a // reading at 1×. Before then, the word each engine usually earns. var _VOICE_PACES = [[0.5, 'instant'], [2, 'fast'], [5, 'slow'], [Infinity, 'slower']]; // first words up to (s), the word function _voicePaceKey(e) { var tm = _voiceTimings(_voicesHere && _voicesHere.timings); if (!tm[e] || typeof tm[e].first_s !== 'number') return 'voices_speed_' + e; if (_ttsKeepsUp(e, 1, tm) === false) return 'voices_pace_behind'; return 'voices_pace_' + _VOICE_PACES.filter(function(p) { return tm[e].first_s <= p[0]; })[0][1]; } // One button tests every voice as a reading uses it: after a rest, warm, // then a page back to back. An admin's; it runs on the server, the pane asks // how far it is. function _voiceTestHtml() { if (!_voicesHere || !_voicesHere.can_change) return ''; var run = _voicesHere.testing || {}, tm = _voiceTimings(_voicesHere.timings); // When it was last tested, beside the button (Eric, 2026-10-20); the table // shows how far a Test is. var last = Object.keys(tm).reduce(function(n, e) { return Math.max(n, tm[e].tested || 0); }, 0); var note = run.error ? '' + tH('voices_test_failed') + '' : !run.engine && last ? '' : ''; return '
' + note + '
'; } function _voiceTestedDate(sec) { var d = new Date(sec * 1000), o = { month: 'short', day: 'numeric' }; if (d.getFullYear() !== new Date().getFullYear()) o.year = 'numeric'; try { return d.toLocaleDateString(_currentLang || undefined, o); } catch (e) { return d.toDateString(); } } // A reading's paragraph, with what makes speech slow (numbers, units, a // name, an abbreviation), cut as Read aloud cuts an article (readaloud.js). function _voiceTestAll() { _ttsLoad().then(function(ok) { if (!ok) { _showToast(t('tts_unavailable_offline')); return; } var chunks = _ttsChunkText(t('voices_test_reading'), _TTS_CHUNK_MAX, _TTS_FIRST_CHUNK_MAX, _currentLang || 'en'); _voiceTestDevice(chunks.length - 1); _voicesSend('/manage/voices/test', { lang: _langPrimary(_currentLang || 'en'), chunks: chunks }, t('voices_test_failed')); }); } var _VOICE_SECS_MIN = 0.1; // quicker than this reads as "<0.1 s", never "0 s" var _voiceDeviceTesting = false; // this device's voice is being timed var _VOICE_DEVICE_TEST_MS = 10000; // two words take a second or two; past this the device has no voice to give // This device's own voice, timed in the same tap while the server tests its // voices: one word, then another queued behind it, at no volume (iOS may say // them anyway). The first is after a rest; the wait between the two is both // its first words warm and each pause a reading's chunks would have. It // speaks as it goes, so those pauses (``joins`` of them, where the Test's // reading meets its next chunk) are all that could slow it, at any speed. function _voiceTestDevice(joins) { var synth = _TTS_AVAILABLE && window.speechSynthesis; if (!synth) return; synth.cancel(); _voiceDeviceTesting = true; var asked = performance.now(), ended = 0, cold = 0; // No voice for the language, or the browser refusing to speak: the column // stops spinning instead of spinning until a reload. function giveUp() { if (!_voiceDeviceTesting) return; _voiceDeviceTesting = false; synth.cancel(); _paintVoices(); } var limit = setTimeout(giveUp, _VOICE_DEVICE_TEST_MS); [0, 1].forEach(function(i) { var u = new SpeechSynthesisUtterance('Zimi'); u.lang = _langPrimary(_currentLang || 'en'); u.volume = 0; u.onstart = function() { var now = performance.now(); if (!i) { cold = (now - asked) / 1000; return; } var warm = Math.max(0, (now - ended) / 1000), gaps = {}; _TTS_GAP_RATES.forEach(function(r) { gaps[String(r)] = Math.round(warm * joins * 10) / 10; }); _setStorageJSON(SK.TTS_DEVICE_TIMES, { first_s: warm, cold_s: cold, gaps: gaps, tested: Math.round(Date.now() / 1000) }); clearTimeout(limit); _voiceDeviceTesting = false; _paintVoices(); }; if (!i) u.onend = function() { ended = performance.now(); }; u.onerror = function() { clearTimeout(limit); giveUp(); }; synth.speak(u); }); } // The server's timings, with this device's own voice as this browser timed it. function _voiceTimings(server) { var tm = Object.assign({}, server || {}), own = _getStorageJSON(SK.TTS_DEVICE_TIMES, null); if (own && own.first_s !== undefined) tm[_DEVICE_VOICE] = own; return tm; } // ✕ on a Clear voice: a pointer's hover showed it, a touch's first tap (or a // long press) shows it; then once asked, it goes. function _vgRemove(btn, tag, question) { if (!btn.classList.contains('show-x') && !window.matchMedia(_HOVER_MQ).matches) { btn.classList.add('show-x'); return; } _appConfirm(question, t('voices_remove')).then(function(ok) { btn.classList.remove('show-x'); if (ok) _voicesSend('/manage/voices/remove', { lang: tag }, t('voices_remove_failed')); }); } // Clear voices to fetch for your languages: each checked language whose Clear // cell offers one. A queue, since the server fetches one at a time. var _clearQueue = []; function _clearOffers() { var out = []; _vgMainLangs().forEach(function(lang) { var c = _voiceCell(lang, 'piper'); if ((c.s === 'get' || c.s === 'busy') && c.tag && !out.some(function(o) { return o.tag === c.tag; })) out.push({ tag: c.tag, bytes: c.bytes || 0, lang: lang }); }); return out; } function _clearNext() { if (_voicesDl().tag || !_clearQueue.length) return; _voicesSend('/manage/voices/download', { lang: _clearQueue.shift() }, t('voices_failed')); } var _clearPickOpen = false; function _toggleClearPick() { _clearPickOpen = !_clearPickOpen; _paintVoices(); } function _clearGet(btn, tags) { if (btn) btn.disabled = true; _clearPickOpen = false; _clearQueue = tags.slice(); _clearNext(); } // The voice Zimi says things in first, wherever there is no menu to pick // one (a Discover card) and wherever Say has not been told otherwise (Eric, // 2026-10-06: "a selector under voices to choose which is the default used // first throughout zimi ... showing only available options"). Automatic is // the server's choice per language; a voice that cannot say a language // gives way to it there. Picking in the Dictionary's Say menu sets it too. function _voiceDefaultHtml(on) { return _voicePickHtml(on, 'voices_default', _voicePrefs().voice, 'voice', 'voice-default'); } // Read aloud's own voice, beside it: Automatic follows the default above. // Under it, always, Patience: a reading keeps a voice that may not keep up // (Natural, or one measured too slow) and waits for it to get ahead instead // of giving way (Eric, 2026-10-23: "a Patience toggle ... when I want the // good audio but need patience to get it" and "No hidden toggle in voices // always show it"). function _voiceReadHtml(on) { return _voicePickHtml(on, 'tts_speak', _voicePrefs().read || '', 'read', 'voice-read', true) + _voiceSwitchRow('voices_wait', 'voices-wait', !!_voicePrefs().wait, '_setVoicePrefs({ wait: this.checked })'); } // A switch row of Settings > Voices: its title, what it covers, the switch. function _voiceSwitchRow(key, id, on, onchange) { return ''; } // One row of voice choices: Automatic and every voice here, ``cur`` marked, // a pick saved as prefs[field]. // ``reads``: a voice measured too slow at Read aloud's speed is dimmed and says so. function _voicePickHtml(on, labelKey, cur, field, cls, reads) { if (on.length < 2) return ''; if (cur && !on.some(function(x) { return x.engine === cur; })) cur = ''; var opt = function(e, label) { var sel = e === cur, change = {}; var slow = reads && e && !_voicePrefs().wait && _ttsKeepsUp(e, _ttsRate(), _voiceTimings(_voicesHere && _voicesHere.timings)) === false; change[field] = e; return ''; }; // A row of the card, as every Settings section draws one: its title, then the choices under it. return ''; } // The Speaking switch, and with it off, the voices downloaded here offered // for removal (an admin's): nothing else of Voices shows. function _speakingHtml() { var on = _speakingOn(); var h = ''; } function _voicePrefsHtml() { if (!_speakingOn()) return _speakingHtml(); var off = _voicePrefs().off, here = _voiceEnginesHere(), nat = _voiceNatural(), dl = _voicesDl(); // Clear not here yet but fetchable for your languages: its row, with Get. if (!here.some(function(x) { return x.engine === 'piper'; }) && _voicesHere && _voicesHere.can_change && _voicesMayFetch()) { var offers = _clearOffers(); if (offers.length || _clearQueue.length) { here.push({ engine: 'piper', absent: true, langs: _vgMainLangs().filter(function(c) { var x = _voiceCell(c, 'piper').s; return x === 'get' || x === 'busy'; }) }); } } // Natural not here yet: its row, for an admin to Get it from (or to watch // it come). if (nat && !here.some(function(x) { return x.engine === 'kokoro'; }) && ((nat.runnable && _voicesMayFetch()) || dl.tag === nat.tag)) { here.unshift({ engine: 'kokoro', langs: _naturalLangs(nat), absent: true }); } here.sort(function(a, b) { return _VOICE_ENGINES.indexOf(a.engine) - _VOICE_ENGINES.indexOf(b.engine); }); var on = here.filter(function(x) { return !x.absent && off.indexOf(x.engine) < 0; }); // One row per engine here; the last one on stays on. var h = _speakingHtml() + '' + _voiceGridHtml(); // Why a voice is not offered, or why the last download failed, in the server's words. var why = _voicesHere && (_voicesHere.problem || (_voicesHere.downloading && _voicesHere.downloading.reason)); if (why) h += ''; if (_voicesHere && _voicesHere.can_change && _voicesHere.setting) h += _voicesModeHtml(_voicesHere.setting); if (_voicesHere && _voicesHere.can_change && _voicesHere.cache) h += _voiceCacheHtml(_voicesHere.cache); return h + '
' + tH('voices_say_remembers') + '
'; } // Drawn again only when something in it changed: the browser names its voices // (voiceschanged) when it pleases, a download's poll comes every second, and // a repaint under a finger swallows the tap. A download's bar moves in place; // a Remove waiting for its second tap is not redrawn from under it. function _paintKept(el, html) { if (!el) return; if (el._painted !== html && !el.querySelector('.confirming, .show-x')) { if (_voiceSample && el.contains(_voiceSample.btn)) _stopVoiceSample(); el.innerHTML = el._painted = html; } var dl = _voicesDl(), p = Math.floor(100 * (dl.done || 0) / (dl.total || 1)); el.querySelectorAll('.voice-dl').forEach(function(b) { // The first voice on a Python install sets the engines up before it // downloads: no measure of that, so the bar sweeps. var bar = b.querySelector('.dl-progress'); b.querySelector('.voice-progress').textContent = dl.setup ? t('voices_setup') : t('voices_downloading', { p: p }); bar.classList.toggle('dl-indeterminate', !!dl.setup); b.querySelector('.dl-progress-bar').style.width = dl.setup ? '' : p + '%'; if (dl.setup) bar.removeAttribute('aria-valuenow'); else bar.setAttribute('aria-valuenow', p); }); } function _paintVoices() { // The next Clear voice in line, once the last one is done. if (_clearQueue.length && !_voicesDl().tag) _clearNext(); _paintKept(document.getElementById(_VOICES_WRAP_ID), _voicePrefsHtml()); // A download in flight: ask how it is going until it is done. clearTimeout(_voicesTimer); var testing = _voicesHere && _voicesHere.testing && _voicesHere.testing.engine; if ((_voicesDl().tag || testing) && document.getElementById(_VOICES_WRAP_ID)) _voicesTimer = setTimeout(_renderVoicePrefs, _VOICES_POLL_MS); } var _voicesHeard = false; function _renderVoicePrefs() { if (!document.getElementById(_VOICES_WRAP_ID)) return; // This browser may name its voices a moment after the page loads. if (!_voicesHeard && window.speechSynthesis && window.speechSynthesis.addEventListener) { _voicesHeard = true; try { window.speechSynthesis.addEventListener('voiceschanged', _paintVoices); } catch (e) {} } authedFetch('/dictionary/voices?all=1').then(function(r) { return r.ok ? r.json() : null; }).catch(function() { return null; }).then(function(d) { _voicesHere = d; _paintVoices(); }); } // The Dictionary hears of every change, so its Say uses the new voice. function _voicesTellDictionary() { var f = document.getElementById('reader-frame'); try { if (f && f.contentWindow) f.contentWindow.postMessage({ zimi: 'voices-changed' }, location.origin); } catch (e) {} } // Every answer is painted from the server's truth; a refusal says so in the // words the caller names. function _voicesSend(path, body, failText) { return manageFetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(function(r) { return r.json(); }).then(function(d) { if (d && d.error) _showToast(d.detail || failText); if (d && d.voices) { d.can_change = !!(_voicesHere && _voicesHere.can_change); _voicesHere = d; _paintVoices(); } else _renderVoicePrefs(); _voicesTellDictionary(); }).catch(function() { _showToast(failText); _renderVoicePrefs(); }); } // A button that asks first (Natural's Remove) is armed by one tap and acts // on the next, as Delete and Redownload do; the voice is a download away // again. function _voicesArm(btn) { var label = btn.textContent; btn.classList.add('confirming'); btn.textContent = btn.getAttribute('data-confirm'); setTimeout(function() { if (!btn.classList.contains('confirming')) return; btn.classList.remove('confirming'); btn.textContent = label; }, _VOICE_CONFIRM_MS); } function _voicesPost(path, tag, btn) { if (btn && btn.hasAttribute('data-clear-cancel')) _clearQueue = []; if (btn && btn.getAttribute('data-confirm') && !btn.classList.contains('confirming')) { _voicesArm(btn); return; } if (btn) { btn.disabled = true; btn.classList.remove('confirming'); } // Several tags, space-separated (Speaking off removes every voice here): one after another. var fail = t(/remove$/.test(path) ? 'voices_remove_failed' : 'voices_failed'); return String(tag).split(' ').reduce(function(done, one) { return done.then(function() { return _voicesSend(path, { lang: one }, fail); }); }, Promise.resolve()); } function _voicesSetCache(mb) { _voicesSend('/manage/voices/cache', { mb: mb }, t('voices_failed')); } function _voicesSetMode(mode) { _voicesSend('/manage/voices', { mode: mode }, t('env_controlled', { v: 'ZIMI_VOICE_DOWNLOADS' })); } // Settings > Languages, at Voices or Languages, from elsewhere: the // Dictionary's Voices… and its front's speaker, /?manage=languages#voices // (or #languages; Preferences' old address too), the network list's row. var _msScrollTo = null; var _MS_HASH_TARGETS = { '#voices': 'ms-voices', '#languages': 'ms-languages' }; function _openSettingsAt(id) { _msScrollTo = id; if (mode === 'manage') switchMs('languages'); else enterManage(null, 'languages'); } // The boot's own address changes drop the fragment before Settings draws. if (_MS_HASH_TARGETS[location.hash] && ['preferences', 'languages'].indexOf(new URLSearchParams(location.search).get('manage')) >= 0) { _msScrollTo = _MS_HASH_TARGETS[location.hash]; } function _msScrollPending() { var id = _msScrollTo; _msScrollTo = null; var el = id && document.getElementById(id); if (el) el.scrollIntoView({ block: 'start' }); } // Hear: "Some dictionary words are: X, Y, Z." in Zimi's language, the words // random ones from the library's Wiktionary in that language, the same for // the session; in another language, its words alone. An engine that cannot // say Zimi's language says words of one it can. The button works (a pulse) // from the tap until the audio starts, then plays until it ends; a second // tap stops it. var _voiceSample = null; // {btn, audio} while one is working or playing function _voiceSampleWords(lang) { var kept = _getSessionJSON(SK.VOICE_SAMPLE, {}) || {}; if (Array.isArray(kept[lang])) return Promise.resolve(kept[lang]); return authedFetch('/dictionary/sample?lang=' + encodeURIComponent(lang)) .then(function(r) { return r.ok ? r.json() : null; }).catch(function() { return null; }) .then(function(d) { var words = (d && Array.isArray(d.words)) ? d.words : []; kept[lang] = words; try { sessionStorage.setItem(SK.VOICE_SAMPLE, JSON.stringify(kept)); } catch (e) {} return words; }); } function _listText(words, lang) { try { return new Intl.ListFormat(lang, { type: 'conjunction' }).format(words); } catch (e) { return words.join(', '); } } // The sentence in a language: Zimi's own says it in full. function _voiceSampleIn(lang) { var own = lang === _uiLangPrimary(); return _voiceSampleWords(lang).then(function(words) { var text = own ? (words.length ? t('voices_sample', { words: _listText(words, lang) }) : t('voices_sample_none')) : (words.length ? _listText(words, lang) : _langOwnName(lang)); return { lang: lang, text: text }; }); } function _voiceHearState(btn, state) { if (!btn) return; btn.classList.toggle('working', state === 'working'); btn.classList.toggle('playing', state === 'playing'); if (state) btn.setAttribute('aria-busy', state === 'working' ? 'true' : 'false'); else btn.removeAttribute('aria-busy'); } function _stopVoiceSample() { var s = _voiceSample; _voiceSample = null; if (!s) return; if (s.audio) { try { s.audio.onplaying = s.audio.onended = s.audio.onerror = null; s.audio.pause(); } catch (e) {} } if (s.device) { try { window.speechSynthesis.cancel(); } catch (e) {} } _voiceHearState(s.btn, ''); } // An engine's row: Zimi's language when it says it, else the first it says. function _hearVoice(engine, btn) { var x = _voiceEnginesHere().filter(function(r) { return r.engine === engine; })[0]; var langs = x ? x.langs : [], ui = _uiLangPrimary(); _playSample(btn, engine, !langs.length || langs.indexOf(ui) >= 0 ? ui : langs[0]); } function _playSample(btn, engine, lang) { var again = _voiceSample && _voiceSample.btn === btn; _stopVoiceSample(); if (again || !engine) return; var mine = _voiceSample = { btn: btn }; _voiceHearState(btn, 'working'); var done = function(failed) { if (_voiceSample !== mine) return; _voiceSample = null; _voiceHearState(btn, ''); if (failed) _showToast(t('voices_hear_failed')); }; _voiceSampleIn(lang).then(function(s) { if (_voiceSample !== mine) return; if (engine === _DEVICE_VOICE) { try { var u = new SpeechSynthesisUtterance(s.text); u.lang = s.lang; u.onstart = function() { if (_voiceSample === mine) _voiceHearState(btn, 'playing'); }; u.onend = function() { done(false); }; u.onerror = function() { done(true); }; mine.device = true; window.speechSynthesis.cancel(); window.speechSynthesis.speak(u); } catch (x) { done(true); } return; } var a = mine.audio = new Audio('/dictionary/speak?sample=1&text=' + encodeURIComponent(s.text) + '&lang=' + encodeURIComponent(s.lang) + '&engine=' + encodeURIComponent(engine)); a.onplaying = function() { if (_voiceSample === mine) _voiceHearState(btn, 'playing'); }; a.onended = function() { done(false); }; a.onerror = function() { done(true); }; var pr = a.play(); if (pr && pr.catch) pr.catch(function(x) { if (!(x && x.name === 'AbortError')) done(true); }); }); } // A sheet stands on the bottom of the layout viewport, which an iPhone's // keyboard covers: while the keyboard is up, the sheet stands on top of it // instead and fits above it. Returns the function that stops the fitting. // The Almanac's sheets use it too. var SHEET_KEYBOARD_GAP_PX = 8; function _sheetAboveKeyboard(el) { var vv = window.visualViewport; if (!vv) return function() {}; function fit() { if (!el.isConnected) return; var covered = Math.max(0, window.innerHeight - (vv.offsetTop + vv.height)); el.style.bottom = covered ? covered + 'px' : ''; el.style.maxHeight = covered ? (vv.height - SHEET_KEYBOARD_GAP_PX) + 'px' : ''; el.style.setProperty('--sheet-room', (vv.height - SHEET_KEYBOARD_GAP_PX) + 'px'); // what a sheet inside may fill } vv.addEventListener('resize', fit); vv.addEventListener('scroll', fit); fit(); return function() { vv.removeEventListener('resize', fit); vv.removeEventListener('scroll', fit); el.style.removeProperty('--sheet-room'); }; } // Preferred download flavor: "full" (with images), "nopic", or "mini". // Used to sort variant pickers so the user's default lands at the top. function _getPrefFlavor() { try { return localStorage.getItem(SK.PREF_FLAVOR) || 'full'; } catch (e) { return 'full'; } } var PREF_FLAVORS = ['full', 'nopic', 'mini']; var _NO_ICONS = { full: '', nopic: '', mini: '' }; function _setPrefFlavor(f) { _prefWrite(SK.PREF_FLAVOR, f); var seg = document.getElementById('ms-flavor-seg'); if (seg) seg.innerHTML = _flavorSegInner(); } // Settings' selector row for it (Full / No images / Mini). function _flavorSegInner() { return _segButtonsHtml(PREF_FLAVORS, _getPrefFlavor(), _NO_ICONS, '_setPrefFlavor', 'flavor_'); } // ── State ── let mode = 'home'; // 'home' | 'source' | 'search' | 'manage' let currentSource = null; let readerOpen = false; let _readerTimeout = null; let readerSource = null; // ZIM name of what's in reader (for topbar badge when no explicit source) let sourceAutoReader = false; // true when enterSource auto-opened the reader (non-zimgit homepage) let _popstateNoAutoReader = false; // suppress auto-reader on popstate navigation let articleHistory = []; // [{zim, path, title, timestamp}] — max 50 entries let currentArticle = null; // {zim, path} — what's currently in the reader let _domainZimMap = {}; // {domain: zim_name} — for cross-ZIM link classification let _resolveCache = {}; // {url: {found, zim, path}} — cached batch resolve results let zimsCache = null; let _zimsByName = new Map(); function _rebuildZimsMap() { _zimsByName = new Map((zimsCache || []).map(z => [z.name, z])); _keepOwnForget(); } function _zimInfo(name) { return _zimsByName.get(name) || null; } let manageEnabled = false; let _managePwRequired = false; // server is password-protected and we have no token yet // Passwordless instance reached over a non-private hop: management is LAN-only // and there is no password to enter, so we explain instead of prompting (#36). let _managePublicLocked = false; let _manageNeedsSetupKey = false; let _manageSetupKeyIssued = true; // A password exists but settings stay inside the network, and this browser // is outside it: nothing to enter, so the page explains. let _manageOutside = false; // Who may change settings (/manage/has-password's access): password, lan // (anyone directly on the network), open, or unset (first run). let _manageAccess = ''; let _manageUnlocked = true; // manage is always available (auth via env var only) // May we hit ambient /manage/* endpoints (activity bar, peer discovery)? // Yes when we hold a token, or when the server isn't password-protected. // Avoids a stream of 401s/403s (and console noise) before the operator logs in. function _canPollManage() { return !!_manageToken || (!_managePwRequired && !_managePublicLocked); } let activeCategories = new Set(); let activeSourceFilters = new Set(); let allResults = {}; let searchController = null; let _searchSeq = 0; // doSearch calls, newest last let searchTimer = null; let suggestTimer = null; let suggestItems = []; let suggestIndex = -1; let snippetController = null; let collectionsCache = null; // {version, favorites, collections} let _expandedCollection = null; // which collection is expanded for ZIM picking // #37 home section order: array of "cat:"/"col:"/"other" keys. // Populated by _fetchList from /list?layout=1; drives renderHome section ordering. let _sectionOrder = []; // #37 user-declared empty sections (category names with no ZIM yet). Offered as // Move-to targets and reorder rows so a section can be created before it holds // anything. Populated by _fetchList; written via _saveLibraryLayout({sections}). let _declaredSections = []; // The reserved category VALUE stored as an override to force a ZIM into the // uncategorized "Other" bucket, and the client-internal group key that bucket // uses. The heuristic never emits it, so its only source is an explicit move. const OTHER_CAT = '__other__'; // The reserved section-order key for the Other section (server mirrors it). const OTHER_KEY = 'other'; // Which ms-nav section to jump to after the (async) manage view mounts. let _pendingMsSection = null; // Single reader of /list — normalizes the additive ?layout=1 envelope // ({zims, section_order}) back to the bare ZIM array every caller expects, and // stashes the section order as a side effect. Older/plain array responses still // work (section order simply stays empty). // Folders another program owns (Project NOMAD): `{label, incoming_files, // incoming_bytes}`, from /list. The words for an empty library and for a // download that is still arriving there. let _libFolders = []; function _libFoldersNoteHtml() { var parts = _libFolders.filter(function(f) { return f.incoming_files > 0; }).map(function(f) { return tPluralH('ext_folder_incoming', f.incoming_files, { label: f.label, size: fmtBytes(f.incoming_bytes) }); }); return parts.length ? '
' + parts.join('
') + '
' : ''; } // The empty library, said for the folder it is waiting on when there is one. function _emptyLibraryHtml() { var f = _libFolders[0]; var what = f ? '

' + tH('ext_folder_empty', { label: f.label }) + '

' + tH('ext_folder_empty_hint') + '

' : '

' + tH('no_sources_found') + '

' + tH('add_zims') + '

'; return what + _libFoldersNoteHtml(); } async function _fetchList() { const r = await serverFetch('/list?layout=1'); const data = await r.json(); if (Array.isArray(data)) { _sectionOrder = []; _declaredSections = []; _libFolders = []; return data; } _libFolders = Array.isArray(data.folders) ? data.folders : []; _sectionOrder = Array.isArray(data.section_order) ? data.section_order : []; _declaredSections = Array.isArray(data.sections) ? data.sections : []; return Array.isArray(data.zims) ? data.zims : []; } let homeScope = null; // {type:'favorites'|'category'|'collection'|'apps', label, zimNames:[]} // Library language filter: a Set of ZIM language codes. Empty = all languages. // Transient view state — reset when leaving/entering a scope, never persisted, // so a reload always lands on the full library. Multi-select toggle, matching // the search-results lang pills. let homeLangFilter = new Set(); // Home language filter pills live in the search dropdown, where the // user picks a filter (see showHistoryDropdown). On home itself the pills row is // hidden by default (clean home) and only appears above the content while a // filter is actively applied, so its un-filter controls stay reachable. // True only while pillsBar currently holds the home filter pills (vs the // search-results source/language pills, which are always shown). Gates the // visibility toggle so it never touches the search-results pills. Transient. let _pillsAreHomeFilters = false; // Cached recency+language pills HTML, rebuilt each renderHome, so the search // dropdown can render the same pills at its top without recomputing. let _homeFilterRowsHtml = ''; function _updateHomeFiltersVisibility() { if (!_pillsAreHomeFilters || !pillsBar.innerHTML) return; const filterActive = homeLangFilter.size > 0; pillsBar.style.display = filterActive ? '' : 'none'; } // ── Language filter ── let activeLanguageFilters = new Set(); // Whether the language filter is the one preferred languages chose (and so // follows each new search) rather than one the person picked; and the query // it was chosen for. let _langFilterIsAuto = false; let _langAutoQuery = null; const RESULTS_PER_PAGE = 20; let visibleResultCount = RESULTS_PER_PAGE; // ── i18n ── const _AVAILABLE_LANGS = [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' }, { code: 'de', name: 'Deutsch' }, { code: 'es', name: 'Español' }, { code: 'pt', name: 'Português' }, { code: 'ru', name: 'Русский' }, { code: 'zh', name: '中文' }, { code: 'ar', name: 'العربية' }, { code: 'hi', name: 'हिन्दी' }, { code: 'he', name: 'עברית' }, ]; const _RTL_LANGS = new Set(['ar', 'he', 'fa', 'ur']); let _i18n = {}; // current language strings let _i18nFallback = {}; // English fallback let _currentLang = 'en'; function t(key, vars) { var s = _i18n[key] || _i18nFallback[key] || key; if (vars) for (var k in vars) s = s.replaceAll('{' + k + '}', vars[k]); return s; } // HTML-escaped version of t() for use in innerHTML/attribute contexts function tH(key, vars) { return t(key, vars).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); } // The string as HTML with each of `vars` already HTML (a around a // name the person typed, say): the string escaped, the values not. function tHtml(key, vars) { let s = tH(key); for (const k in vars) s = s.split('{' + k + '}').join(vars[k]); return s; } // Zimi's language, not the phone's: a German Zimi on an English phone reads // 20.10.2026 and 1.234 everywhere, so every number, date and sorted list goes // through these. Each Intl object is kept per language and options: building // one costs more than using it, and lists call these once a row. // The locale is Zimi's language in the phone's region when the phone speaks // that language (en-GB: 20/10/2026, weeks from Monday), else the language. function _uiLocale() { var lang = _uiLangPrimary(), phone = (typeof navigator !== 'undefined' && navigator.language) || ''; return _langPrimary(phone).toLowerCase() === lang ? phone : lang; } var _intlKept = {}; function _intl(kind, opts) { var lang = _uiLocale(), key = kind + ' ' + lang + ' ' + JSON.stringify(opts || {}); if (!_intlKept[key]) { try { _intlKept[key] = new Intl[kind](lang, opts); } catch (e) { _intlKept[key] = new Intl[kind]('en', opts); } } return _intlKept[key]; } function fmtNum(n, opts) { return _intl('NumberFormat', opts).format(Number(n) || 0); } // A share of 100 as the language writes one (73,6 %, %73). function fmtPct(of100, digits) { return fmtNum((Number(of100) || 0) / 100, { style: 'percent', maximumFractionDigits: digits || 0 }); } // A date as the language writes it; with no options, the short numeric date. function fmtDate(d, opts) { if (!(d instanceof Date)) d = new Date(d); return isNaN(d.getTime()) ? '' : _intl('DateTimeFormat', opts).format(d); } // Text in the order a reader of the language expects, numbers by value // ("Part 2" before "Part 10"). var _COLLATE_OPTS = { numeric: true }; var _collators = {}; function cmpText(a, b) { var lang = _uiLocale(); var c = _collators[lang] || (_collators[lang] = _intl('Collator', _COLLATE_OPTS)); return c.compare(a == null ? '' : String(a), b == null ? '' : String(b)); } // A library's things by their title, or their name where they have none. function cmpTitle(a, b) { return cmpText(a.title || a.name, b.title || b.name); } // The first day of the week, 0 = Sunday, for _uiLocale (en-GB starts on // Monday, en-US on Sunday, a bare language in its usual region). Intl's week // info where the browser has it (not Firefox yet), CLDR's table where not. var _WEEK_SUN = /^(AG|AS|BD|BR|BS|BT|BW|BZ|CA|CO|DM|DO|ET|GT|GU|HK|HN|ID|IL|IN|JM|JP|KE|KH|KR|LA|MH|MM|MO|MT|MX|MZ|NI|NP|PA|PE|PH|PK|PR|PT|PY|SA|SG|SV|TH|TT|TW|UM|US|VE|VI|WS|YE|ZA|ZW)$/; var _WEEK_SAT = /^(AE|AF|BH|DJ|DZ|EG|IQ|IR|JO|KW|LY|OM|QA|SD|SY)$/; var _LANG_HOME_REGION = { en: 'US', ar: 'EG', he: 'IL', hi: 'IN', pt: 'BR', zh: 'CN' }; function _weekFirstDay() { var lang = _uiLangPrimary(), tag = _uiLocale(); try { var loc = new Intl.Locale(tag), wi = loc.getWeekInfo ? loc.getWeekInfo() : loc.weekInfo; if (wi && wi.firstDay) return wi.firstDay % 7; } catch (e) {} var m = /[-_]([A-Za-z]{2})\b/.exec(tag), region = m ? m[1].toUpperCase() : (_LANG_HOME_REGION[lang] || ''); return _WEEK_SUN.test(region) ? 0 : _WEEK_SAT.test(region) ? 6 : 1; } // Localized pluralization: picks "_" via Intl.PluralRules for // the active UI language, falling back to "_other" when that category // key does not exist. Locale files currently ship only _one/_other; languages // with richer plural categories (ru few/many, ar, he...) resolve to _other // until per-category keys are added. {n} is injected automatically, written // as the language writes numbers (1.234 in German). function tPlural(base, n, vars) { var cat = 'other'; try { cat = _intl('PluralRules').select(Number(n) || 0); } catch (e) {} var key = base + '_' + cat; if (_i18n[key] === undefined && _i18nFallback[key] === undefined) key = base + '_other'; var v = { n: typeof n === 'number' ? fmtNum(n) : n }; if (vars) for (var k in vars) v[k] = vars[k]; return t(key, v); } function tPluralH(base, n, vars) { return tPlural(base, n, vars).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); } function _loadingHtml(key) { return '
' + tH(key || 'loading') + '
'; } // In-app confirmation — replaces window.confirm everywhere (Eric: "Delete // confirmation should be in app ui"). Reuses the password overlay's shell so // it themes correctly on both palettes. Resolves true only on the primary // button; overlay tap, Cancel, and Escape all resolve false. // A third button (altLabel) answers 'alt'; Cancel and Escape answer false. function _appConfirm(message, okLabel, altLabel) { return new Promise(function(resolve) { var overlay = document.createElement('div'); overlay.className = 'pw-overlay open pw-confirm'; overlay.innerHTML = '
' + '

' + esc(message) + '

' + '
' + '' + (altLabel ? '' : '') + '' + '
' + '
'; function done(answer) { overlay.remove(); document.removeEventListener('keydown', onKey, true); resolve(answer); } function onKey(e) { if (e.key === 'Escape') { e.stopPropagation(); done(false); } } overlay.addEventListener('click', function(e) { if (e.target === overlay) done(false); }); document.addEventListener('keydown', onKey, true); document.body.appendChild(overlay); overlay.querySelector('#ac-cancel').onclick = function() { done(false); }; var alt = overlay.querySelector('#ac-alt'); if (alt) alt.onclick = function() { done('alt'); }; var ok = overlay.querySelector('#ac-ok'); ok.onclick = function() { done(true); }; ok.focus(); }); } // A language's words, kept on this device from the last time they loaded: // a fetch that fails (offline after a deploy changed the address, a // sign-in in front of the server answering with its own page) falls back // to them instead of leaving every label its key (Eric, 2026-10-03: the // Dictionary and the search box read "dictionary_say", "search"). var _I18N_KEPT = 'zimi_i18n_kept_'; // dir: '' for Home's words, I18N_ALMANAC_DIR for the Almanac's (its own file, so Home does not download them). var I18N_ALMANAC_DIR = 'almanac/'; async function _i18nFetch(lang, dir) { dir = dir || ''; try { var res = await fetch('/static/i18n/' + dir + lang + '.json?v=' + _i18nVer); if (res.ok) { var words = await res.json(); if (words && typeof words === 'object' && Object.keys(words).length) { try { localStorage.setItem(_I18N_KEPT + dir + lang, JSON.stringify(words)); } catch (e) {} return words; } } } catch (e) {} try { var kept = JSON.parse(localStorage.getItem(_I18N_KEPT + dir + lang) || 'null'); if (kept) return kept; } catch (e) {} return null; } // The Almanac's words (alm_, tb_, ref_), asked for with the first thing of the Almanac's that runs and from then on // with every language load. One load per language, however many ask; dropped when it fails so the next ask tries again. var _almWordsWanted = false; var _almWordsLoading = null; async function _mergeAlmanacWords(lang) { var got = await Promise.all([_i18nFetch('en', I18N_ALMANAC_DIR), lang === 'en' ? null : _i18nFetch(lang, I18N_ALMANAC_DIR)]); if (got[0]) Object.assign(_i18nFallback, got[0]); if (got[1] && _i18n !== _i18nFallback) Object.assign(_i18n, got[1]); return !!got[0]; } function _loadAlmanacWords() { _almWordsWanted = true; if (!_almWordsLoading) { var lang = _currentLang; _almWordsLoading = _mergeAlmanacWords(lang).then(function(ok) { if (!ok) _almWordsLoading = null; else if (lang !== _currentLang) { _almWordsLoading = null; return _loadAlmanacWords(); } }, function() { _almWordsLoading = null; }); } return _almWordsLoading; } async function _loadI18n(lang) { // English is every language's fallback; the language itself alongside it. var got = await Promise.all([_i18nFetch('en'), lang === 'en' ? null : _i18nFetch(lang)]); if (got[0]) _i18nFallback = got[0]; _i18n = (lang !== 'en' && got[1]) || _i18nFallback; // The Almanac's words were in the language that was left: bring them in the new one. if (_almWordsWanted) { _almWordsLoading = null; await _loadAlmanacWords(); } } function _detectLanguage() { // Check localStorage first, then browser language var saved = localStorage.getItem(SK.UI_LANG); if (saved && _AVAILABLE_LANGS.some(l => l.code === saved)) return saved; var nav = (navigator.language || '').split('-')[0].toLowerCase(); if (_AVAILABLE_LANGS.some(l => l.code === nav)) return nav; return 'en'; } function _applyRTL(lang) { if (_RTL_LANGS.has(lang)) { document.documentElement.setAttribute('dir', 'rtl'); document.documentElement.lang = lang; } else { document.documentElement.removeAttribute('dir'); document.documentElement.lang = lang; } } var _langLoadId = 0; // Guard against race conditions on rapid language switching async function setLanguage(lang) { _currentLang = lang; _prefWrite(SK.UI_LANG, lang); _keepUiLangChecked(lang); var myId = ++_langLoadId; await _loadI18n(lang); if (_langLoadId !== myId) return; // Superseded by a newer setLanguage call _applyRTL(lang); _applyI18nToDOM(); _renderLangDropdown(); // Re-render current view so all dynamic strings update // Skip re-rendering when reader is open — renderSource auto-opens the ZIM homepage, // which would overwrite the article the user is reading. if (readerOpen) { // Just update topbar/labels — reader iframe content stays put } else if (mode === 'manage') { // Drawn again in the new language on the same section, where it was: // Settings > Languages switches Zimi's language without leaving it. var _msY = window.scrollY; _pendingMsSection = _msSection; renderManage().then(function() { window.scrollTo(0, _msY); }); } else if (mode === 'source' && currentSource) { renderSource(currentSource); } else { renderHome(); } updateTopbar(); _refreshLibraryPanelIfOpen(); // If reading an article, re-check language banner in reader context if (readerOpen && currentArticle) _checkReaderLangBanner(); // The PDF viewer speaks the shell's language too: reopened with the new // locale on the same file (Eric: "changing language with PDF up doesn't // change language of the text in the PDF player"). if (_isPdfPage()) { try { var _pf = document.getElementById('reader-frame'); var _pw = _pf.contentWindow; var _pm = /[?&]file=([^#&]*)/.exec(_pw.location.href); if (_pm) { // The locale rides in the #fragment, and replacing a URL with one that // differs only there is a scroll, not a load: the viewer kept its old // language for every switch but the one to English (no fragment). var _next = _pdfViewerUrl(_pm[1]); var _onlyHash = _pw.location.href.split('#')[0] === new URL(_next, _pw.location.href).href.split('#')[0]; _pw.location.replace(_next); if (_onlyHash) _pw.location.reload(); } } catch (e) {} } if (_isDictPage()) _dictFollowLanguage(lang); else _appFollowLanguage(); // Sync almanac: re-render all content with new translations if (typeof _onGlobalLanguageChanged === 'function') _onGlobalLanguageChanged(lang); if (_almanacOpen && typeof _renderAlmanacContent === 'function') _renderAlmanacContent(); } // Remove any stale language banner (actual banner logic lives in _renderLangDropdown) function _checkReaderLangBanner() { var old = document.getElementById('lang-banner'); if (old) old.remove(); } // Legacy download-count badge shim. The topbar activity badge (.topbar-badge, // see _applyActivityBadge) is now the single source of truth for the gear count // — it already surfaces downloads plus indexing/seeding. Painting a second // `.manage-badge` here stacked two badges on the same gear (double-badge bug), // so this now just nudges the activity poll for immediate feedback on a // download start/stop and lets that one badge own the gear. Kept as a named // function so the download call sites read intentionally. function _showManageBadge(show, count) { // Drop any stale `.manage-badge` left by an older cached app.js, then defer to // the activity badge. var btn = document.getElementById('manage-btn'); var stale = btn && btn.querySelector('.manage-badge'); if (stale) stale.remove(); if (window._nudgeActivityPoll) window._nudgeActivityPoll(); } function _langBannerDownload(lang, catMatch) { // Fallback for welcome card — drill into catalog var banner = document.getElementById('lang-banner'); if (banner) { banner.remove(); } closeReader(); manageTab = 'browse'; var prefix = (catMatch === 'wikipedia' || !catMatch) ? 'wikipedia_' + lang + '_all' : null; _pendingDrill = { catKey: catMatch || 'wikipedia', lang: lang, namePrefix: prefix }; enterManage(); } function _applyI18nToDOM() { // Update static elements with data-i18n attributes document.querySelectorAll('[data-i18n]').forEach(function(el) { el.textContent = t(el.dataset.i18n); }); document.querySelectorAll('[data-i18n-placeholder]').forEach(function(el) { if (el === q) return; // the search box's words are fitted to its room below, never set whole and then cut a frame later el.placeholder = t(el.dataset.i18nPlaceholder); }); document.querySelectorAll('[data-i18n-title]').forEach(function(el) { el.title = t(el.dataset.i18nTitle); }); document.querySelectorAll('[data-i18n-aria]').forEach(function(el) { el.setAttribute('aria-label', t(el.dataset.i18nAria)); }); // Update search placeholder based on current context _updateSearchPlaceholder(); } // On an app's page the box asks the app's question, short enough for a // phone's box: "Where to?", "Find a video", "Ask a question". function _appPlaceholder() { if (_isWikiPage()) return t('wiki_search_placeholder'); if (_isBooksPage()) return t('books_search_placeholder'); if (_isDictPage()) return t('dictionary_search_placeholder'); if (_isGameShelf()) return t('games_search_placeholder'); if (_isFieldguidePage()) return t('fieldguide_search_placeholder'); if (_isReddotPage()) return t('reddot_search_placeholder'); if (_isExchangePage()) return t('exchange_search_placeholder'); if (_isTubePage()) return t('tube_search_placeholder'); if (_isMapPage()) return t('maps_search_placeholder'); return ''; } // What the box does on the Manage page: filters the installed list on // the Library tab, searches the catalog (or the open category) everywhere // else. One answer, so the two places that write the placeholder agree. function _managePlaceholder() { if (manageTab === 'installed') return t('filter_installed'); if (manageCategoryFilter) { var catMeta = BROWSE_CATEGORIES.find(function(c) { return c.key === manageCategoryFilter; }); return t('search_in', {source: catMeta ? t(catMeta.i18n) : manageCategoryFilter}); } return t('search_catalog'); } // What the box asks, wherever you are: one answer for the header and for a // language change (which used to write its own, and said "Search in // Wikipedia…" where the header said "Wikipedia"). function _searchPlaceholderText() { if (_createOpen) { // Same treatment as the Almanac below: the box stays and takes the page's // name. It used to fall through to the ZIM underneath, so the header on // the page where you make a NEW ZIM read "Lit Docs". return t('create_zim'); } if (_almanacOpen) return t('almanac'); if (_appPlaceholder()) return _appPlaceholder(); // In one ZIM, or reading one: the box searches that ZIM, and says so. var scoped = _searchScopeSource(); if (scoped) return t('search_in', {source: _zimTitle(scoped)}); if (mode === 'manage') return _managePlaceholder(); if (homeScope) return t('search_in', {source: homeScope.label}); return t('search_placeholder'); } // A prompt cut off mid-word ("Search books ar") is half a sentence: where // the whole one does not fit the box (a phone, the ? beside it), the box // says Search. Measured, not guessed: the words, the language and the box // decide. var _placeholderFull = ''; var _placeholderCanvas = null; // Measured once a frame, just before the paint that lays the page out anyway. // Measuring on every call forced a layout each time, several times over while // the home page was still being built (~40 ms of a phone's first paint). var _placeholderRaf = 0; function _fitSearchPlaceholder(text) { if (!q) return; if (text != null) _placeholderFull = text; if (_placeholderRaf) return; _placeholderRaf = requestAnimationFrame(_fitSearchPlaceholderNow); } function _fitSearchPlaceholderNow() { _placeholderRaf = 0; var full = _placeholderFull, room = q.clientWidth; if (!full || !room) { q.placeholder = full; return; } var cs = getComputedStyle(q); room -= (parseFloat(cs.paddingLeft) || 0) + (parseFloat(cs.paddingRight) || 0); _placeholderCanvas = _placeholderCanvas || document.createElement('canvas'); var ctx = _placeholderCanvas.getContext('2d'); if (!ctx) { q.placeholder = full; return; } ctx.font = cs.fontStyle + ' ' + cs.fontWeight + ' ' + cs.fontSize + ' ' + cs.fontFamily; var fits = function(s) { return ctx.measureText(s).width <= room; }; // "Search in Wikipedia…" too long for a phone's box: the ZIM's name alone, // which still says where the search goes, before the bare "Search". var scoped = _searchScopeSource(), name = scoped ? _zimTitle(scoped) : ''; q.placeholder = fits(full) ? full : (name && full.indexOf(name) >= 0 && fits(name)) ? name : t('search'); } // The one ZIM the box searches: the one open, or the one being read. function _searchScopeSource() { return currentSource || (readerOpen && readerSource && !_isAppPage() && !_isMapPage() ? readerSource : null); } function _updateSearchPlaceholder() { if (!q) return; _fitSearchPlaceholder(_searchPlaceholderText()); } // Sizes are DECIMAL, everywhere, and this is the only place that says so. // // The app used to divide by 1024 and print "GB" — a GiB wearing the wrong // name — in five separate hand-rolled formatters that did not even agree with // each other. At these file sizes the gap is not academic: // wikipedia_en_all_maxi is 123,980,647,016 bytes, which Zimi called 115 GB // while the NAS, Finder, df and Kiwix's own library page all called it 124 GB. // Nine gigabytes of disagreement, on the screen whose job is answering "will // this fit". // // The Python side's format_bytes() is this same function, thresholds and // decimal places included, and tests/test_size_units.py holds the two to one // table of expected strings so they cannot drift apart again. var BYTES_PER_KB = 1000; var BYTES_PER_MB = 1000 * 1000; var BYTES_PER_GB = 1000 * 1000 * 1000; // Where GB stops carrying a decimal: below ten a tenth says something about a // ZIM, above it "115 GB" reads better than "115.5 GB" down a list. var GB_WHOLE_FROM = 10; // MB likewise: from a hundred, "285 MB" says all a list needs and "285.0 MB" only adds a zero. var MB_WHOLE_FROM = 100; // Biggest unit first. English keeps the units Finder and the server print // (KB, not CLDR's kB); every other language takes its own (1,5 Go, 1,5 ГБ). var _SIZE_UNITS = [ { per: BYTES_PER_GB, unit: 'gigabyte', en: 'GB' }, { per: BYTES_PER_MB, unit: 'megabyte', en: 'MB' }, { per: BYTES_PER_KB, unit: 'kilobyte', en: 'KB' }, { per: 1, unit: 'byte', en: 'B' }]; var _SIZE_NUMBER_PART = /^(integer|decimal|fraction|minusSign)$/; function fmtBytes(bytes, html) { var b = Math.max(0, Number(bytes) || 0); var u = _SIZE_UNITS.filter(function(x) { return b >= x.per; })[0] || _SIZE_UNITS[_SIZE_UNITS.length - 1]; var v = b / u.per; var tenths = u.per === 1 || (u.per === BYTES_PER_GB && v >= GB_WHOLE_FROM) || (u.per === BYTES_PER_MB && v >= MB_WHOLE_FROM) ? 0 : 1; var en = String(_currentLang || 'en').split('-')[0] === 'en'; var parts = _intl('NumberFormat', { style: 'unit', unit: u.unit, minimumFractionDigits: tenths, maximumFractionDigits: tenths, useGrouping: false }).formatToParts(v); var out = '', num = ''; var flush = function() { if (num) out += html ? '' + num + '' : num; num = ''; }; parts.forEach(function(p) { if (_SIZE_NUMBER_PART.test(p.type)) { num += p.value; return; } flush(); out += !en ? p.value : p.type === 'unit' ? u.en : ' '; }); flush(); return out; } // The same size, for the callers that only ever held a GB figure (the API's // size_gb, which is now decimal GB computed from the same constant). One // entry point too many, but zero implementations too many: it lands in // fmtBytes like everything else, so nothing can quote a different number. function fmtSize(gb, html) { return fmtBytes((Number(gb) || 0) * BYTES_PER_GB, html); } // Localized count line for a ZIM's card/info panel. Prefers the real article // count (libzim `article_count`, added by the metadata cache) and falls back to // the raw entry count for stale caches that predate the field. Empty string // when neither is a number (e.g. an unreadable ZIM whose entries is '?'). function _zimCountHtml(z) { const n = _zimCount(z); // tPlural, not t: this line read "1 entries" on the home screen for every // single-article library — a 67MB medical collection announcing itself with // a grammar mistake. The helper has been here the whole time and this was // the one count that did not use it. return typeof n === 'number' ? tPlural('n_entries', n, {n: fmtNum(n)}) : ''; } // How many things a ZIM holds, as a person would count them. // // `article_count` is libzim's, and libzim only counts what the ZIM declares an // ARTICLE. That is right for an encyclopedia and wrong for a document // collection: every zimgit library — food preparation, knots, medicine, // post-disaster, water — declares ONE article, its index, and keeps its // hundreds of PDFs as ordinary entries. So the home screen introduced a 645MB // survival library as "1 entry". // // A Zimi-made capture is the case where 1 is the truth: one page, plus the // images and stylesheets that page needs. Those are marked, so they keep the // article count and everything else falls back to entries when the article // count is obviously not describing the ZIM. function _zimCount(z) { if (!z) return undefined; const articles = typeof z.article_count === 'number' ? z.article_count : undefined; const entries = typeof z.entries === 'number' ? z.entries : undefined; // A capture counted its own pages. libzim's article count cannot know // that: for a whole crawl it reported two, one a vendor feedback widget. if (z.capture && z.capture.pages) return z.capture.pages; if (articles === undefined) return entries; if (z.zimi_export) return articles; // a capture really is one page if (articles <= 1 && entries > 1) return entries; return articles; } // True for ZIMs Zimi itself exported (bookmark exports). Server flags them // from Creator metadata; the description sniff covers caches built before the // flag existed. Their cards show the full creation date — for an export, // "when did I make this" is the date that matters. function _isZimiExport(z) { return !!(z && (z.zimi_export || /exported by Zimi/.test(z.description || ''))); } // ── DOM refs ── const q = document.getElementById('q'); const output = document.getElementById('output'); // Delegated click for the "Did you mean" correction link. The suggestion // derives from third-party ZIM title words, so the anchor carries it in an // HTML-attribute-encoded data-sugg (no inline onclick — a JS-string escape // alone doesn't survive a double-quote in attribute position). output.addEventListener('click', function(e) { var link = e.target.closest('.did-you-mean a[data-sugg]'); if (link) { e.preventDefault(); applyDidYouMean(link.getAttribute('data-sugg')); return; } var typed = e.target.closest('.did-you-mean a[data-typed]'); if (typed) { e.preventDefault(); searchTypedInstead(typed.getAttribute('data-typed')); } }); const mainView = document.getElementById('main-view'); const statsBar = document.getElementById('stats-bar'); const pillsBar = document.getElementById('pills-bar'); const sourceHeaderEl = document.getElementById('source-header'); const searchMeta = document.getElementById('search-meta'); const logoEl = document.getElementById('logo'); const backBtn = document.getElementById('back-btn'); const bcSep = document.getElementById('bc-sep'); const bcIcon = document.getElementById('bc-icon'); const randomBtn = document.getElementById('random-btn'); const manageBtnEl = document.getElementById('manage-btn'); const _gearSvg = manageBtnEl.innerHTML; // capture gear icon for toggle const newtabBtn = document.getElementById('newtab-btn'); const suggestDropdown = document.getElementById('suggest-dropdown'); const footerEl = document.getElementById('footer'); // ── Manage password ── let _manageToken = ''; // Optional management username (v1.8). '' = none; when set it rides along in // the X-Zimi-User header (see _authHeaders). Restored from storage on load. let _manageUser = _readManageUser(); let _manageSavedReader = null; // saved reader state when entering manage let _pwResolve = null; let _pwReject = null; // Manage calls that got a 401 while a manage sign-in was already open. Each is // retried with the token once the call that opened the prompt is accepted, and // rejected if it is cancelled. Two 401s at once (the Library pane and the // Creator prefetch) used to replace one resolver with the other, and the first // call waited forever: Manage stuck on "Loading…" after a correct password. let _pwQueued = []; let _pwQueueOwner = null; function _pwDropQueue(err) { var q = _pwQueued; _pwQueued = []; _pwQueueOwner = null; q.forEach(function(w) { w.reject(err || new Error('auth_cancelled')); }); } // ── Multi-user session (v1.8) ── // A logged-in NAMED USER (not admin). The session cookie does the actual // server-side filtering; this just shapes the client chrome (hide the admin // gear, show name + logout). null = admin or anonymous. // {name, restricted, canCreate} — canCreate mirrors the account's per-user // create permission (/whoami can_create); the server gates regardless. let _userSession = null; // When true, the password modal is in "sign in" mode (POST /login: user OR // admin) rather than the admin-only manage-retry flow. let _pwLoginMode = false; var _ACCT_ICON = ''; // Open the shared modal in sign-in mode (reachable by anyone, incl. a kid on a // password-protected instance who can't open manage). function openLoginModal() { _pwLoginMode = true; _pwResolve = null; _pwReject = null; openPwModal(t('sign_in')); } function _showPwError(msg) { var el = document.getElementById('pw-error'); if (el) { el.textContent = msg; el.style.display = 'block'; } var inp = document.getElementById('pw-input'); if (inp) { inp.value = ''; inp.focus(); } } // POST /login → {status, j}. Cookie (if a user) is set by the server. function doLogin(username, password, remember) { return fetch('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ username: username, password: password, remember: remember }) }).then(function(r) { return r.json().then(function(j) { return { status: r.status, j: j }; }); }); } // Apply a user session to the UI. Server-side filtering is already live via the // cookie; here we hide manage and reload the (now restricted) library view. function _applyUserSession(name, canCreate) { _userSession = { name: name, restricted: true, canCreate: !!canCreate }; // A user is never admin — drop any admin token so ambient manage polls stop. _manageToken = ''; _clearManageToken(); if (manageBtnEl) manageBtnEl.style.display = 'none'; _accountSet(name); _gamesFollow(name); _accountRecheck(); // the display name this person goes by (/whoami) _refreshAfterAuthChange(); } function userLogout() { // A change still waiting to go to the account goes before the session does; // once the account has everything, its copy leaves this browser (a shared // screen keeps nothing of it, highlights and notes included). One that // could not go stays, to go up at the next sign-in. _accountLeave().then(function() { return fetch('/logout', { method: 'POST', credentials: 'same-origin' }); }).catch(function(){}).then(function() { _userSession = null; // Reboot at the ROOT so the boot gate re-runs from a clean anonymous state. // In private mode it re-shows the non-dismissible login gate (never a stale // library); in open/limited it reboots into the anonymous/filtered view. We // navigate to '/' (not reload the current URL): the user may be on a /w/ // article that, reloaded anonymous in private mode, renders raw 401 JSON // instead of the gate. An in-place refetch would strand a private instance // on an empty home with no gate. location.replace('/'); }); } // Reload the library after a login/logout so the filtered view is reflected. async function _refreshAfterAuthChange() { try { zimsCache = await _fetchList(); _rebuildZimsMap(); _libraryKnown = true; } catch (e) { zimsCache = []; _libraryKnown = false; _noteConnFailure(e); _renderConnBanner(); } // goHome() on a clean home page only scrolls to the top, so a sign-in made while home was already // drawn (the gate opens over it) kept the anonymous library on screen until a reload: draw it again. if (mode === 'home' && !readerOpen && !currentSource && !homeScope && typeof renderHome === 'function') renderHome(); else if (typeof goHome === 'function') goHome(); else route(false); } // Who is asking: asked at the start of the boot, beside the words and the password probe, and read by _bootAuthGate. var _bootWho = null; function _fetchWhoami() { // Present any stored admin token so whoami can authenticate a token-admin. if (!_manageToken) { var saved = _readManageToken(); if (saved) _manageToken = saved; } return serverFetch('/whoami', { credentials: 'same-origin', headers: _manageToken ? _authHeaders() : {}, }).then(function(r) { return r.json(); }); } // Boot-time auth probe + gate. Runs BEFORE the library renders so a private // instance paints the login form as its FIRST frame (no empty-chrome flash), // and a token-authed admin is recognised without a spurious re-gate on reload. // Returns true when the login gate was shown — the caller then skips the whole // library boot; a successful sign-in reloads into a clean, authorised boot. // // Why whoami must carry the admin token: the admin's credential is a Bearer // token kept in client storage, NOT the session cookie the named-user path // rides on. A bare whoami (cookie only) can't see the admin, answers // `anonymous + login_required`, and used to bounce a just-signed-in admin // straight back to the login screen ("login wouldn't stick"). async function _bootAuthGate() { var j; try { j = await (_bootWho || _fetchWhoami()); } catch (e) { // Unreachable server: we cannot know whether this instance is private, so // we do NOT gate. Fall through to the normal boot, where /list will fail // the same way and the offline state (not a fake empty library) paints. return false; } // The apps the server offers now: the shell's stamp can be older than the // setting (Chrome's Back shows a kept shell without asking), and nothing // has drawn yet (#98). if (j && 'apps' in j) _setAppsStamp(j.apps); // First-login hint: the server only sends this when the default username // ("admin") applies (no custom username, no named users). The login modal // reads it to show "Default username: admin". _defaultUsernameHint = (j && j.default_username) || ''; // Whose account this browser follows, from the server's word only: the // account's own saved things and settings, from the browser's copy of them // (the account's arrives in the background once the page is up: _savedStart). _accountSet(j && j.account, true); _gamesWhoami(j, true); if (j && j.role === 'user') { _userSession = { name: j.name, restricted: !!j.restricted, canCreate: !!j.can_create }; if (manageBtnEl) manageBtnEl.style.display = 'none'; _loadUserPrefs(); return false; } if (j && j.role === 'admin') { return false; // token-authed admin — proceed to the full library. } // Private public-access mode: an anonymous visitor (no valid cookie or token) // sees nothing but the login screen. The server already 401s every read; the // gate makes the CLIENT match with an opaque, non-dismissible login overlay // rendered as the first frame, instead of a half-populated home whose fetches // all fail in the background. if (j && j.login_required) { // A stored token that didn't authenticate above is stale — drop it so the // gate isn't skipped on the next reload. if (_manageToken) { _manageToken = ''; _clearManageToken(); } _applyI18nToDOM(); // localise the modal's static labels before it shows _enterLoginGate(); return true; } return false; } // '' unless the server says the default username applies (see _bootAuthGate). var _defaultUsernameHint = ''; // ── Login gate (private public-access mode) ── // True while an anonymous visitor is held at the forced login screen. var _loginRequired = false; function _enterLoginGate() { _loginRequired = true; document.body.classList.add('login-gate'); var help = document.getElementById('pw-helpnow'); if (help) { help.innerHTML = _gateHelpHtml(); help.hidden = !help.innerHTML; } openLoginModal(); } function _exitLoginGate() { _loginRequired = false; document.body.classList.remove('login-gate'); var help = document.getElementById('pw-helpnow'); if (help) help.hidden = true; } // Token-adding fetch for *ambient* /manage/* calls (activity bar, peer // discovery, status/mirror polls). Sends the manage token when we have one // so these work on password-protected servers, but never prompts for a // password on 401 — background polling must fail silently, unlike the // interactive manageFetch below. // 429 responses surface as a typed error so callers keep their last-known // content and reschedule, instead of rendering the error JSON as an empty // state (the downloads panel used to blank itself this way, #30). function _throwIfRateLimited(res) { if (res.status === 429) { var err = new Error('rate_limited'); err.rateLimited = true; err.retryAfter = parseInt(res.headers.get('Retry-After') || '5', 10) || 5; throw err; } return res; } function authedFetch(url, opts) { opts = opts || {}; if (_manageToken) { opts.headers = Object.assign({}, opts.headers, _authHeaders()); } return fetch(url, opts).then(_throwIfRateLimited); } function manageFetch(url, opts) { opts = opts || {}; if (_manageToken) { opts.headers = Object.assign({}, opts.headers, _authHeaders()); } return fetch(url, opts).then(_throwIfRateLimited).then(function(res) { if (res.status === 401) { return new Promise(function(resolve, reject) { var retryWith = function(token) { var o = Object.assign({}, opts); o.headers = Object.assign({}, o.headers, _authHeaders(token)); return fetch(url, o); }; if (_pwResolve && _pwResolve === _pwQueueOwner) { _pwQueued.push({ retry: retryWith, resolve: resolve, reject: reject }); return; } // Single auth door: any unauthorized manage call opens the UNIFIED // sign-in modal (there is no separate "Sign in" entry). It accepts a // named user (→ their filtered library) OR the admin (→ full manage); // submitPw routes /login by role. For the admin case it calls the // resolver below, which verifies the token by retrying THIS request. _pwLoginMode = true; var rejectFn = function() { // User cancelled — leave manage view _pwDropQueue(); goHome(); reject(new Error('auth_cancelled')); }; _pwResolve = function(token) { // Verify password (and username, if any) before accepting it. // submitPw has already set _manageUser from the modal field, so // _authHeaders folds in the X-Zimi-User header. retryWith(token).then(function(retryRes) { if (retryRes.status === 401) { // Wrong password — show error, restore reject handler, keep modal open document.getElementById('pw-error').textContent = t('wrong_password'); document.getElementById('pw-error').style.display = 'block'; document.getElementById('pw-input').value = ''; document.getElementById('pw-input').focus(); _pwReject = rejectFn; return; } // Correct password _manageToken = token; _saveManageToken(token, document.getElementById('pw-remember').checked); var queued = _pwQueued; _pwQueued = []; _pwQueueOwner = null; closePwModal(); resolve(retryRes); queued.forEach(function(w) { w.retry(token).then(w.resolve, w.reject); }); }); }; _pwQueueOwner = _pwResolve; _pwQueued = []; _pwReject = rejectFn; openPwModal(t('sign_in')); }); } return res; }); } function manageLogout() { // The admin's account leaves this browser the way a user's does (userLogout): // what it has not had goes up first, then its copy goes. _accountLeave().then(_manageLogoutNow, _manageLogoutNow); } function _manageLogoutNow() { _manageToken = ''; _clearManageToken(); // Drop any server-side session too — a SECONDARY admin authenticates to a // session cookie, not just the client-held token — then reboot at the ROOT so // the boot gate re-runs anonymous. Without the reboot the admin keeps the full // library they already loaded on screen: in private mode that reads as "logged // out but still see everything" even though the server now 401s every // anonymous read. We navigate to '/' (not reload the current URL): an admin // can now open articles in private mode, so the current URL may be a /w/ // article that, reloaded anonymous, renders raw 401 JSON instead of the gate. fetch('/logout', { method: 'POST', credentials: 'same-origin' }) .catch(function(){}) .then(function() { location.replace('/'); }); } // Element that had focus before the modal opened; we restore focus // here on close so keyboard users don't lose their place. let _pwPreviousFocus = null; function openPwModal(title, opts) { document.getElementById('pw-title').textContent = title || t('enter_password'); // Prefill: the session's known username (change-password continuity), else the // server-flagged default. The default is 'admin' ONLY when the sole account is // the primary admin (server sends default_username then — see _bootAuthGate); // once named users exist the field starts blank so a user types their own name // rather than a misleading 'admin'. var uEl = document.getElementById('pw-username'); // What is already in the fields stays: the private-mode gate is on screen (and typed // into) a moment before the boot gets round to opening the modal, and wiping it then // sent a name that was no longer there. The fields are emptied when the modal closes. if (uEl && !uEl.value) uEl.value = _manageUser || _defaultUsernameHint || ''; // First-login hint ("Default username: admin") — only in sign-in mode and // only when the server says the default applies (no custom username/users). var hintEl = document.getElementById('pw-username-hint'); if (hintEl) { var showHint = _pwLoginMode && !!_defaultUsernameHint; hintEl.style.display = showHint ? 'block' : 'none'; if (showHint) hintEl.textContent = t('default_username_hint').replace('{name}', _defaultUsernameHint); } // The password starts empty every time the sheet opens (a change-password flow reopens it for the // new one), except under the private-mode gate, where it may already be being typed into. if (!_loginRequired) document.getElementById('pw-input').value = ''; document.getElementById('pw-input').placeholder = (opts && opts.placeholder) || t('password'); document.getElementById('pw-input').autocomplete = (opts && opts.hideRemember) ? 'new-password' : 'current-password'; document.getElementById('pw-error').style.display = 'none'; document.getElementById('pw-remember-row').style.display = (opts && opts.hideRemember) ? 'none' : 'flex'; document.getElementById('pw-remove-btn').style.display = 'none'; // The private-mode login gate is non-dismissible (closePwModal no-ops while // _loginRequired), so hide the Cancel button there — an inert Cancel just // reads as broken. It shows in every other (dismissible) use of the modal. var pwCancel = document.getElementById('pw-cancel'); if (pwCancel) pwCancel.style.display = _loginRequired ? 'none' : ''; _pwPreviousFocus = document.activeElement; const overlay = document.getElementById('pw-overlay'); overlay.classList.add('open'); document.addEventListener('keydown', _pwKeyHandler); // Focus the password, unless a field in the sheet already has it: the private-mode gate is typed into // as it opens, and taking focus here sent the name just typed into the password field. setTimeout(function() { var at = document.activeElement; if (at && at !== overlay && overlay.contains(at)) return; document.getElementById('pw-input').focus(); }, 50); } function closePwModal() { // The private-mode login gate is non-dismissible: Cancel / Esc / any close // path is a no-op, since there is nothing behind it but 401s. Only a // successful sign-in (which calls _exitLoginGate) can leave. if (_loginRequired) return; document.getElementById('pw-input').value = ''; var uClear = document.getElementById('pw-username'); if (uClear) uClear.value = ''; document.getElementById('pw-overlay').classList.remove('open'); document.removeEventListener('keydown', _pwKeyHandler); if (_pwReject) { _pwReject(); _pwReject = null; } _pwResolve = null; _pwLoginMode = false; // never leave sign-in mode armed for the next opener // Restore focus to where the user was before we hijacked it. if (_pwPreviousFocus && typeof _pwPreviousFocus.focus === 'function') { try { _pwPreviousFocus.focus(); } catch (_) {} } _pwPreviousFocus = null; } function _pwKeyHandler(e) { // Esc closes the modal — standard a11y pattern for dialogs. Exception: the // login gate (private mode) is non-dismissible — there is nothing behind it // to reveal, so Esc is swallowed. if (e.key === 'Escape') { e.preventDefault(); if (!_loginRequired) closePwModal(); return; } // Tab focus-trap: cycle within the modal so keyboard users can't // accidentally escape to the background page. if (e.key !== 'Tab') return; const overlay = document.getElementById('pw-overlay'); if (!overlay || !overlay.classList.contains('open')) return; const focusables = overlay.querySelectorAll( 'input:not([type=hidden]):not([disabled]), button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])' ); if (!focusables.length) return; const first = focusables[0]; const last = focusables[focusables.length - 1]; if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } } function submitPw() { const pw = document.getElementById('pw-input').value.trim(); if (!pw) return; // Capture the optional username so _authHeaders sends X-Zimi-User on the // verify/retry. Blank field → 'admin' (matches the passwordless keychain UX // and the server's any-value-passes rule when no username is configured). const uEl = document.getElementById('pw-username'); const uname = (uEl && uEl.value.trim()) || 'admin'; _manageUser = uname; // Sign-in mode: unified /login (a named user OR the admin account). if (_pwLoginMode) { const remember = document.getElementById('pw-remember').checked; doLogin(uname, pw, remember).then(function(res) { if (res.status === 403 && res.j.error === 'outside_network') { _showPwError(t('outside_locked_body')); return; } if (res.status !== 200) { _showPwError(t('wrong_password')); return; } if (res.j.role === 'user') { // Named user: no manage powers. Abandon any pending manage request // (it's admin-only — retrying would just 401 again) and switch to the // filtered library. Their account state lives in Manage → Users. _pwResolve = null; _pwReject = null; _pwDropQueue(); _pwLoginMode = false; // Leaving the private-mode gate: reload into a clean authenticated // state so the whole app boots with the session's filtered view. if (_loginRequired) { _exitLoginGate(); location.reload(); return; } closePwModal(); _applyUserSession(res.j.name, !!res.j.can_create); return; } // Admin via the sign-in modal. A SECONDARY admin authenticates to a // session token (res.j.token); the PRIMARY admin's token is the password. var tok = res.j.token || pw; if (res.j.secondary && res.j.name) _manageUser = res.j.name; _pwLoginMode = false; if (_pwResolve) { // Opened from a manage 401: hand the token to the resolver, which // verifies it by retrying the original request, persists it, closes the // modal, and resolves so the in-flight manage view paints in place. var resolver = _pwResolve; _pwResolve = null; _pwReject = null; resolver(tok); } else if (_loginRequired) { // Admin signing in from the private-mode gate: persist the token and // reload into a clean, fully authorized boot (whoami → admin, no gate). _manageToken = tok; _saveManageToken(tok, remember); _exitLoginGate(); location.reload(); } else { // Opened directly (no pending request): store the token and enter // manage deterministically (enterManage, never toggleManage — the // latter would toggle OFF when opened from within manage). _manageToken = tok; _saveManageToken(tok, remember); _msPrefetch = {}; // whatever was fetched before the password is stale closePwModal(); if (typeof enterManage === 'function') enterManage(); } }); return; } if (_pwResolve) { _pwReject = null; // prevent cancel on close document.getElementById('pw-error').style.display = 'none'; _pwResolve(pw); // Don't close modal here — manageFetch closes it after verifying the password works } } // Breadcrumb identity for the Almanac — a calendar-with-a-star glyph, sized to // match a ZIM's 22px icon, tinted by the chrome via currentColor. // Breadcrumb identity for the Create page — the + that opens it, at a ZIM // icon's 22px. Same reason the Almanac has one: it opens over whatever you // were looking at, and without an identity of its own that view's icon shows // through as if you were still in it. var _CREATE_BC_ICON = ''; // Where a page was opened from, when that is a place of its own rather than // a step through the reader: the Almanac, a search, the home page (Discover), // or an app. Stamped on the page's history entry as it is pushed, so the // header's arrow and the browser's Back go to the same place, and named on // the arrow ("Almanac", "Search"). Read from the entry being left. var _FROM_APPS = ['tube', 'exchange', 'reddot', 'wiki', 'books', 'fieldguide', 'dictionary']; function _openedFrom() { var s = history.state || {}; if (s.mode === 'almanac' || s.mode === 'search') return s.mode; if (s.mode === 'home' && !s.scope) return 'home'; if (s.mode === 'reader') { for (var i = 0; i < _FROM_APPS.length; i++) if (s[_FROM_APPS[i]]) return _FROM_APPS[i]; } return null; } // `st`, about to be pushed, marked with where it was opened from (not an // app's own step: Zimipedia to Zimipedia is the app's business). function _stampFrom(st) { var from = _openedFrom(); if (from && !st[from]) st.from = from; return st; } // `st`, about to replace the entry on screen with the same page (Back or // Forward landing on it, a reload), keeping where that page was opened from. function _keepFrom(st) { var s = history.state || {}; var same = s.mode === st.mode && (st.zim ? s.zim === st.zim && s.path === st.path : _FROM_APPS.some(function(k) { return st[k] && s[k]; })); if (same && s.from) st.from = s.from; return st; } // What the arrow returns to, named for screen readers and the tooltip (the // arrow itself carries no text): the place the page was opened from, or the // source of the page before it when that was another ZIM. null for a step // back through the reader's own pages. function _backLabel() { if (typeof _aeIsOpen !== 'undefined' && _aeIsOpen) return _aeBackLabel(); // the Almanac's 3D view if (!readerOpen) return null; var prev = articleHistory[articleHistory.length - 1]; if (prev && !prev.app) { return currentArticle && prev.zim !== currentArticle.zim ? _zimTitle(prev.zim) : null; } // Home is not named: the logo beside the arrow already is the way there, // and on a phone "← Home" took the room the search box needs. Back and // Escape still return to Discover as it was left (history.state.from). var from = (history.state || {}).from; return from && from !== 'home' ? t(from) : null; } // ── Topbar ── function updateTopbar() { const activeSource = currentSource || readerSource; // Back button: show when user has navigated deep enough that the breadcrumb // icons (Zimi logo = home, source icon = ZIM top-level) aren't sufficient. // That means: article history exists (stepped into articles), scoped home // view, or search results. NOT shown for basic reader-open-from-source // (back = click source icon or Escape). // On an app page the arrow is always there: a step back inside the app // (a video, a question, a post, a list), and from its home, out. const backTo = _backLabel(); // Offline an app's page may not be here at all (the worker answers with its own "You're offline" page, which never // tells the topbar it is at the app's top or not): the arrow stays so there is always a way back to where you were. const showBack = !!backTo || (typeof _aeIsOpen !== 'undefined' && _aeIsOpen) || articleHistory.length > 0 || mode === 'search' || homeScope || (_isAppPage() && (!_appTop || _connState !== CONN_OK)) || _gameHasShelfBehind(); backBtn.style.display = showBack ? 'flex' : 'none'; var nightBtn = document.getElementById('night-btn'); // The red night light where it is used in the dark: the Field Guide and the Almanac's sky. if (nightBtn) nightBtn.style.display = _isFieldguidePage() || _almanacOpen ? 'flex' : 'none'; backBtn.setAttribute('aria-label', backTo ? t('back_to', {place: backTo}) : t('go_back')); backBtn.title = backTo ? t('back_to', {place: backTo}) : ''; // Breadcrumb: Zimi / [icon] — search bar shows source name as placeholder. // The Almanac opens as an overlay over the home/ZIM view but is its own // destination, so it shows its OWN identity here (icon + "Almanac"), mirroring // how entering a ZIM does — never the underlying ZIM's icon bleeding through. if (_createOpen) { // Was showing the last-opened ZIM's icon, and the search box its name — // "Lit Docs", on the page where you make a NEW one. Both were the view // underneath showing through. bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; bcIcon.title = t('create_zim'); bcIcon.innerHTML = _CREATE_BC_ICON; bcIcon.removeAttribute('href'); } else if (_almanacOpen) { bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; bcIcon.title = t('almanac'); bcIcon.innerHTML = _ALMANAC_SVG.replace('width="26" height="26"', 'width="20" height="20"'); // Identity only — no destination behind it, so no link affordance either. bcIcon.removeAttribute('href'); } else if (_isWikiPage() || _isBooksPage() || _isDictPage()) { var hashApp = _isWikiPage() ? 'wiki' : _isBooksPage() ? 'books' : 'dictionary'; bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; bcIcon.title = t(hashApp); bcIcon.innerHTML = _appIcon(hashApp).replace('width="26" height="26"', 'width="20" height="20"'); bcIcon.setAttribute('href', '/#' + hashApp); } else if (_isFieldguidePage()) { bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; bcIcon.title = t('fieldguide'); bcIcon.innerHTML = _FIELDGUIDE_SVG.replace('width="26" height="26"', 'width="20" height="20"'); bcIcon.setAttribute('href', '/#fieldguide'); } else if (_isReddotPage()) { bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; bcIcon.title = t('reddot'); bcIcon.innerHTML = _REDDOT_SVG.replace('width="26" height="26"', 'width="20" height="20"'); bcIcon.setAttribute('href', '/#reddot'); } else if (_isExchangePage()) { bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; bcIcon.title = t('exchange'); bcIcon.innerHTML = _EXCHANGE_SVG.replace('width="26" height="26"', 'width="20" height="20"'); bcIcon.setAttribute('href', '/#exchange'); } else if (_isTubePage()) { bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; bcIcon.title = t('tube'); bcIcon.innerHTML = _TUBE_PLAY_SVG.replace('width="26" height="26"', 'width="20" height="20"'); bcIcon.setAttribute('href', '/#tube'); } else if (_isMapPage()) { // Zimi Maps: the surface is the identity, whichever map is open. bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; bcIcon.title = t('cat_maps'); bcIcon.innerHTML = _MAPS_SVG.replace('width="26" height="26"', 'width="20" height="20"'); bcIcon.setAttribute('href', '/#maps'); } else if (activeSource) { bcSep.style.display = 'inline'; bcIcon.style.display = 'inline-flex'; const info = _zimInfo(activeSource); const title = _zimTitle(activeSource); bcIcon.title = title; // Real link (#49): the source view has a true URL, so right/middle/ // modifier clicks can open it in a new tab; bcClick keeps plain clicks SPA. bcIcon.setAttribute('href', '/w/' + encodeURIComponent(activeSource)); if (activeSource === _GAMES_ZIM) { bcIcon.innerHTML = _GAMES_SVG.replace('width="26" height="26"', 'width="20" height="20"'); } else if (info && info.has_icon) { bcIcon.innerHTML = ''; } else { bcIcon.innerHTML = '' + (esc(title)[0] || 'Z').toUpperCase() + ''; } } else { bcSep.style.display = 'none'; bcIcon.style.display = 'none'; bcIcon.title = ''; bcIcon.removeAttribute('href'); } // Manage/Almanac: gear → X close. Reader open: gear → X close reader. // Always show this button so topbar has a stable 4-icon layout. var _closeSvg = ''; // Every "this slot is now a close X" case differs only in what the click does // and whether the button is highlighted, so they share one setter. var _setCloseBtn = function(onclick, highlighted) { manageBtnEl.innerHTML = _closeSvg; manageBtnEl.title = t('close'); manageBtnEl.style.color = highlighted ? 'var(--amber)' : ''; manageBtnEl.style.borderColor = highlighted ? 'var(--amber-border)' : ''; manageBtnEl.style.background = highlighted ? 'var(--amber-glow)' : ''; manageBtnEl.onclick = onclick; }; if (mode === 'manage') { manageBtnEl.style.display = 'flex'; _setCloseBtn(function(e) { toggleManage(e); }, true); } else if (_createOpen) { manageBtnEl.style.display = 'flex'; _setCloseBtn(closeCreate, false); } else if (_almanacOpen || readerOpen) { // Hide X when another button takes the 4th slot (save on desktop, pop-out on // web). On mobile .manage-btn is hidden anyway (close is the back-btn / // breadcrumb) and the pop-out now lives in the ... menu, so this only affects // desktop-web where the inline pop-out still shows. var hasSaveBtn = !_almanacOpen && IS_DESKTOP && currentArticle && /\.(pdf|epub)$/i.test(currentArticle.path || ''); // Pop-out (open in browser) only makes sense from an installed/standalone // PWA — in a plain browser tab you're already in a browser, so it's hidden // (the close X takes the slot back). var hasNewtab = !_almanacOpen && readerOpen && _isStandalonePWA(); // On a phone the Almanac's way out is the Zimi crumb (and the arrow, one step back), as in every other world: the X would be a // second door. var phoneAlmanac = _almanacOpen && _isNarrow(); manageBtnEl.style.display = (hasSaveBtn || hasNewtab || phoneAlmanac) ? 'none' : 'flex'; _setCloseBtn(_almanacOpen ? closeAlmanac : function() { closeReader(); goHome(); }, false); } else { manageBtnEl.style.display = 'flex'; manageBtnEl.innerHTML = _gearSvg; manageBtnEl.title = t('library_manager'); manageBtnEl.style.color = ''; manageBtnEl.style.borderColor = ''; manageBtnEl.style.background = ''; manageBtnEl.onclick = function(e) { toggleManage(e); }; } newtabBtn.style.display = (readerOpen && !_almanacOpen && _isStandalonePWA()) ? 'flex' : 'none'; // Reader-only controls: font scale (always when reading) + read-aloud (only // when the browser exposes the offline Web Speech API). Hidden when the // reader isn't the active surface — and read-aloud never appears at all // when unsupported, so no dead button. var _readingArticle = readerOpen && !_almanacOpen && !_createOpen; // On a phone the reader topbar was carrying nine controls. Font size and // Read aloud are the two least-reached, and both already live in the ⋯ // menu's reader group — so on a narrow viewport they fold there and leave // the inline row to the essentials (Eric: reconsider what's behind ⋯, we // have a lot going on). Desktop keeps them inline; the space is there. var _foldReaderExtras = _readingArticle && _isNarrow(); // A map is read with the eyes and the hands: no type size, no read-aloud, // no Reader View. _syncReaderViewBtn and the ⋯ menu know the same rule. var _readingText = _readingArticle && !_isMapPage() && !_isAppPage() && !_isPdfPage() && !_isGamePage(); var fontBtn = document.getElementById('font-btn'); if (fontBtn) fontBtn.style.display = (_readingText && !_foldReaderExtras) ? 'flex' : 'none'; // Places and maps: the places kept, and the same place on another map. var mapSrcBtn = document.getElementById('map-source-btn'); if (mapSrcBtn) { // A map page carries one more button (the picker) than any other page, // and on a phone that squeezed the box to a third of its placeholder. // The bookmarks button steps aside there: the history button's panel // holds the bookmarks too. document.body.classList.toggle('map-page', !!(_readingArticle && currentArticle && _isMapZim(currentArticle.zim))); // An app page is not an article: nothing on it to bookmark as one. document.body.classList.toggle('app-page', _isAppPage()); document.body.classList.toggle('app-noitem', _isAppPage() && !_appItem); // Places and maps: on every map page, since it is where a place is saved. var showMapSrc = !!(_readingArticle && currentArticle && _isMapZim(currentArticle.zim)); mapSrcBtn.style.display = showMapSrc ? 'flex' : 'none'; if (!showMapSrc) _closeMapSourceDropdown(); } var ttsBtn = document.getElementById('tts-btn'); if (ttsBtn) ttsBtn.style.display = (_readingText && _ttsOffered() && !_foldReaderExtras) ? 'flex' : 'none'; // The dice on a map roll a place, and say so. var randomLabel = t(_isMapPage() ? 'random_place' : 'random_article'); randomBtn.title = randomLabel; randomBtn.setAttribute('aria-label', randomLabel); _syncReaderViewBtn(); // book/reader-view glyph — gated on extractable content // Desktop: show save button when viewing a downloadable file (PDF, EPUB) var saveBtn = document.getElementById('save-btn'); if (saveBtn) { var showSave = IS_DESKTOP && readerOpen && currentArticle && /\.(pdf|epub)$/i.test(currentArticle.path || ''); saveBtn.style.display = showSave ? 'flex' : 'none'; } // Library chrome is for moving around a library. Manage, Almanac and Create // are all places you went deliberately, and none of them is a ZIM — Random, // the library/bookmark button and the history trail have nothing to act on // in any of them. // // Create was briefly excluded from this, because hiding them left a wide // desktop window with three controls and a ⋯, which read as a broken toolbar // rather than as focus (#68). The ⋯ is what made it read that way, and it is // gone now; what is left is Language and the X, which is the whole job. var libraryChromeOff = mode === 'manage' || _almanacOpen || _createOpen; randomBtn.style.display = libraryChromeOff ? 'none' : 'flex'; // Zimipedia's reader saves from its own bar: the header's save toggle // would be a second bookmark for the same article. Saved stays one tap // away (bm-panel-btn). document.getElementById('library-btn').style.display = (libraryChromeOff || (readerOpen && _wikiReading)) ? 'none' : 'flex'; // History and Saved are two panels with two openers (Eric: "both under the // clock is weird"). The clock opens History: library-btn off the reader, // history-btn in it, where library-btn is the save toggle. The bookmarks // mark opens Saved, wherever the library chrome shows. Neither folds into // the ⋯ menu: what you read and what you kept stay one tap away. document.getElementById('history-btn').style.display = (readerOpen && !libraryChromeOff) ? 'flex' : 'none'; document.getElementById('bm-panel-btn').style.display = libraryChromeOff ? 'none' : 'flex'; // Create-a-ZIM lives in the ⋯ menu at every width — creation is an // occasional, deliberate act, so it stays out of the primary topbar. The ⋯ // trigger is CSS-hidden on a wide viewport at rest, so reveal it (inline // style; the mobile !important rules still win) whenever the menu would // carry the Create row. See _buildTopbarMenuHtml. _createRememberCanShow(); // Except on the Create page, which has no ⋯ at all (#68). Everything it // offered there was either already inline a few pixels to the left (Random, // Language) or one tap away behind the X that closes the page (Manage) — // and if an article happened to be open behind Create, the reader group came // with it: Reader View and Read aloud, on a page with no article. Five rows, // two duplicated and two inert. // body.creating, not an inline style: the mobile rule that shows ⋯ is // !important, which no inline display can outrank. document.body.classList.toggle('creating', !!_createOpen); _syncTopbarMore(); // On a phone the language lives in the ⋯ menu (the Almanac too: one header in every world). document.getElementById('lang-selector-btn').style.display = (_langMenuHidden() || (_almanacOpen && _isNarrow())) ? 'none' : ''; _updateLibraryBtnIcon(); _syncGameHead(); // Search placeholder: fitted once the ? has taken (or given back) its room. _syncSearchHelp(); _updateSearchPlaceholder(); // Footer updateFooter(); // Batch-download bar only belongs to the Catalog tab — hide elsewhere, // keeping the selection so it reappears when the user returns. _renderSelectionBar(); document.body.classList.toggle('in-manage', mode === 'manage'); // Home's grids take the room the screen has (up to --pick-max); search, a source and Manage keep their column. document.body.classList.toggle('on-home', mode === 'home'); // Reading an article: the inline Reader View / font / read-aloud controls fold // into the ⋯ menu (desktop too, matching mobile), and CSS `order` pins the // close X to the far right with ⋯ just before it. No DOM is moved — display // and flex order only — so repeated opens can't duplicate any button. document.body.classList.toggle('reading', _readingArticle); // Re-attach the background-activity badge: this function rewrites the gear's // innerHTML above (wiping any child badge), and Manage mode suppresses it // (that view surfaces downloads in its own tabs). Safe no-op before the first // poll (badge state defaults to inactive). _applyActivityBadge(); } function bcClick(e) { // Clicking the icon in the breadcrumb goes to the source view if (e.target.closest && e.target.closest('#logo')) return; // the logo's own handler navigates if (_anchorNativeClick(e)) return; // bc-icon is a real link (#49) — new-tab gestures stay native e.preventDefault(); if (_almanacOpen) { // Over the Almanac, its icon is the way back to it: the 3D view closes, as its back arrow does (Eric 2026-11-08). // On the Almanac itself it is identity only, no nav into the ZIM behind it. if (typeof _aeIsOpen !== 'undefined' && _aeIsOpen && e.target.closest && e.target.closest('#bc-icon')) goBack(); return; } // An app's icon is the way to its front page, from anywhere inside it. if (_isAppPage()) { _appEntryHome(); return; } // In ZimiGames the icon is the way to every game: the shelf, from any game (a Discover card or a link lands mid-shelf). if (_isGamesZimOpen()) { openArticle(_GAMES_ZIM, 'index.html', t('app_games')); return; } if (currentSource && (readerOpen || mode === 'search')) { if (readerOpen) closeReader(); enterSource(currentSource, false); } } function updateFooter() { if (readerOpen) { footerEl.style.display = 'none'; } else { footerEl.style.display = ''; } } // ── Connection state ── // // Absence of data is not data. The PWA shell is service-worker cached, so it // boots perfectly well with a dead backend; before this, every data fetch that // failed fell into the same `catch { zimsCache = [] }` as a server that // genuinely answered "you have zero ZIMs", and home rendered a confident "No // knowledge sources found". That reads as "my library was wiped". // // Every server exchange is classified into exactly one of three states: // 'online' — the server answered. ANY HTTP status counts, including 401/403 // /404/500: an answer is an answer, and the auth gate owns 401. // 'offline' — the request never reached the server: fetch threw at the // network layer, or the service worker returned its synthetic // offline response (X-Zimi-Offline) in place of one. // 'error' — the server answered but the payload was unusable (malformed // JSON, unexpected shape). Rare, and still not "you own nothing". // Auth-gating is deliberately NOT a connection state: _bootAuthGate owns it. const CONN_OK = 'online', CONN_OFFLINE = 'offline', CONN_ERROR = 'error'; // Reconnect probe backoff, ms. Capped so a long outage settles into a cheap // 30s heartbeat rather than hammering a server that may be mid-restart. const CONN_PROBE_STEPS = [3000, 5000, 10000, 20000, 30000]; let _connState = CONN_OK; // Why we are offline, so the words say what is true: 'nonet' (this device has no // connection), 'server' (it has one and the server does not answer) or // 'restarting' (a proxy in front of the server answered for it). Only // meaningful while _connState is not online. const WHY_NONET = 'nonet', WHY_SERVER = 'server', WHY_RESTARTING = 'restarting'; let _connWhy = WHY_SERVER; // False once an attempt to load /list failed for ANY reason. Gates every // "no ZIMs" claim in the UI: we only assert an empty library when the server // actually told us it was empty. let _libraryKnown = true; let _connProbeTimer = null; let _connProbeStep = 0; let _connProbeSeq = 0; let _connRecovering = false; // Tagged error meaning "never reached the server". Thrown by serverFetch so // callers can branch on cause without re-sniffing the failure. function _offlineError(why) { const e = new Error('zimi-offline'); e.zimiOffline = true; e.why = why; return e; } function _isOfflineError(e) { return !!(e && e.zimiOffline); } // The service worker's stand-in for an answer, not an answer from the server. function _isOfflineResponse(res) { if (!res) return false; try { if (res.headers.get('X-Zimi-Offline') === '1') return true; // Older cached SW without the header: its offline page is the only 503 that // returns HTML from an endpoint the app only ever asks for JSON. return res.status === 503 && (res.headers.get('Content-Type') || '').indexOf('text/html') === 0; } catch (e) { return false; } } // A proxy or tunnel answering for a server that is down or restarting (its own // 502/503/504 page, never the app's JSON): the server did not speak. function _isGatewayDown(res) { try { return (res.status === 502 || res.status === 503 || res.status === 504) && (res.headers.get('Content-Type') || '').indexOf('json') < 0; } catch (e) { return false; } } // Mirrors sw.js NETWORK_ONLY_PREFIXES. A 200 from any OTHER route may have come // out of the service worker's cache, which proves nothing about the server being // up — it is exactly how a dead backend came to look reachable. Only these // routes (and the cache-busted /health probe) can promote the state to online. const _LIVE_PROOF_PREFIXES = ['/whoami', '/login', '/logout', '/list', '/search', '/suggest', '/random']; function _isLiveProof(url) { const p = String(url).split('?')[0]; for (let i = 0; i < _LIVE_PROOF_PREFIXES.length; i++) { const pre = _LIVE_PROOF_PREFIXES[i]; if (p === pre || p.indexOf(pre + '/') === 0) return true; } return String(url).indexOf('/health?ping=') === 0; } // The single front door for anything that talks to the Zimi server. Classifies // the outcome (updating the banner as a side effect) and throws a tagged // offline error rather than letting an unreachable server masquerade as data. // // The classification is deliberately asymmetric: a failure ALWAYS proves the // server is unreachable (nothing else produces the SW's offline response), but a // success only proves it when the route could not have been served from cache. async function serverFetch(url, opts) { let res; try { res = await fetch(url, opts); } catch (e) { _noteConn(CONN_OFFLINE); throw _offlineError(); } if (_isOfflineResponse(res)) { _noteConn(CONN_OFFLINE); throw _offlineError(); } // A kept answer the worker gave because the server did not answer in time: // good to draw from, and proof of nothing about the server. if (res.headers.get('X-Zimi-Stale') === '1') { _noteConn(CONN_OFFLINE); return res; } if (_isGatewayDown(res)) { _noteConn(CONN_OFFLINE, WHY_RESTARTING); throw _offlineError(WHY_RESTARTING); } if (_isLiveProof(url)) _noteConn(CONN_OK); return res; } // Record the outcome of a server exchange. Transitions drive the banner and, // on a fall to offline, start the reconnect probe. // A failed exchange, from the error it threw: never reached the server (and, // when it says, why), or reached it and could not use the answer. function _noteConnFailure(e) { if (_isOfflineError(e)) _noteConn(CONN_OFFLINE, e.why); else _noteConn(CONN_ERROR); } function _noteConn(state, why) { if (state !== CONN_OK) { const was = _connWhy; _connWhy = why || (navigator.onLine === false ? WHY_NONET : WHY_SERVER); if (state === _connState && was !== _connWhy) { _renderConnBanner(); _renderOfflineHome(); return; } } if (state === _connState) { // Still online and the library is stale-unknown from an earlier outage // (e.g. only /list failed): keep probing until the library is back. if (state === CONN_OK && !_libraryKnown && !_connProbeTimer) _scheduleConnProbe(); return; } _connState = state; if (state === CONN_OK) { _stopConnProbe(); _renderConnBanner(); } else { _renderConnBanner(); _scheduleConnProbe(); } } // ── Connection banner ── // Calm, persistent, non-blocking. Sits between the topbar and the content (it // pushes rather than overlays, so cached articles and the almanac stay fully // readable) and offers an explicit Retry alongside the automatic probe. function _renderConnBanner() { // Offline is a mode, not a fault: a small neutral pill by the logo, no Retry // (the check is automatic and silent). Tapping it says what is shown and // offers a manual check. It leaves, quietly, when the server is back. const away = _connState !== CONN_OK || !_libraryKnown; document.documentElement.classList.toggle('conn-away', _connState !== CONN_OK); document.documentElement.style.setProperty('--conn-h', '0px'); if (_isAppPage()) updateTopbar(); // an app's back arrow depends on the connection const el = document.getElementById('conn-pill'); if (!el) return; if (!away) { el.hidden = true; return; } const key = _connState === CONN_OFFLINE ? (_connWhy === WHY_NONET ? 'nonet' : 'server') : 'error'; el.dataset.why = key; el.querySelector('.conn-pill-text').textContent = t('conn_pill_' + key); // Icon-only where there is no room for words: the words ride the label. el.setAttribute('aria-label', t('conn_pill_' + key)); el.title = t('conn_pill_' + key); el.hidden = false; } function _connPillTap(e) { e.preventDefault(); e.stopPropagation(); const el = document.getElementById('conn-pill'), r = el.getBoundingClientRect(); window._openMenuAt('
' + tH('conn_pill_' + el.dataset.why + '_hint') + '
' + '
' + tH('conn_check') + '
', r.left, r.bottom + 4, function() { _connProbeStep = 0; _connProbeNow(); }); } // The banner's height was content-dependent; the pill takes no room. function _syncConnBannerHeight() { document.documentElement.style.setProperty('--conn-h', '0px'); } function _connRetryClick(btn) { if (btn) { btn.disabled = true; btn.textContent = t('conn_retrying'); } _connProbeStep = 0; _connProbeNow(); } function _stopConnProbe() { if (_connProbeTimer) { clearTimeout(_connProbeTimer); _connProbeTimer = null; } _connProbeStep = 0; } function _scheduleConnProbe() { if (_connProbeTimer) return; const delay = CONN_PROBE_STEPS[Math.min(_connProbeStep, CONN_PROBE_STEPS.length - 1)]; _connProbeTimer = setTimeout(function() { _connProbeTimer = null; _connProbeStep++; _connProbeNow(); }, delay); } // /health, read once for everyone who asks within HEALTH_SHARE_MS (the footer's version and the build check both come in the // first moments: one request, not two). Resolves to the answer, or null when it did not come. var _healthInFlight = null, _healthAt = 0, HEALTH_SHARE_MS = 5000; function _healthOnce(share) { // `share`: the first moments' asks, which take an answer a few seconds old; coming back to the front asks afresh if (!share || !_healthInFlight || performance.now() - _healthAt > HEALTH_SHARE_MS) { _healthAt = performance.now(); _healthInFlight = fetch('/health', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }); } return _healthInFlight; } // One reachability check. The cache-busting query is deliberate: /health is a // network-first route, so a plain request could be answered from the SW cache // and report a dead server as alive. async function _connProbeNow() { if (_connRecovering) return; const seq = ++_connProbeSeq; _connRecovering = true; let reachable = false; try { await serverFetch('/health?ping=' + Date.now(), { cache: 'no-store' }); reachable = true; } catch (e) { reachable = false; } _connRecovering = false; if (seq !== _connProbeSeq) return; // superseded by a newer probe if (!reachable) { _renderConnBanner(); _scheduleConnProbe(); return; } await _connRecover(); } // The server is back. Reload the library and repaint whatever the user is // looking at, so recovery needs no manual reload. async function _connRecover() { const hadLibrary = _libraryKnown; try { zimsCache = await _fetchList(); _rebuildZimsMap(); _libraryKnown = true; } catch (e) { _noteConnFailure(e); _scheduleConnProbe(); return; } _stopConnProbe(); _renderConnBanner(); if (!hadLibrary) { // Only announce when something actually changed on screen. if (mode === 'manage') renderInstalled(); else if (!readerOpen && !currentSource && !readerSource) renderHome(); } } // Browser-level connectivity events are a hint, not the truth (a laptop can be // on Wi-Fi with the Zimi server down, or offline-flagged yet reachable on LAN), // so a regain triggers a probe rather than clearing the banner outright. function _bindConnEvents() { window.addEventListener('online', function() { _connProbeStep = 0; _connProbeNow(); }); window.addEventListener('offline', function() { _noteConn(CONN_OFFLINE); }); document.addEventListener('visibilitychange', function() { if (!document.hidden && (_connState !== CONN_OK || !_libraryKnown)) { _connProbeStep = 0; _connProbeNow(); } }); window.addEventListener('resize', _syncConnBannerHeight); // The box's room changes with the window: the placeholder is fitted again // (on the next frame, once however many resizes come before it). window.addEventListener('resize', function() { _fitSearchPlaceholder(); var g = document.getElementById('game-title'); if (g && document.body.classList.contains('game-page')) _fitGameTitle(g); }); } // Shared honest-empty markup for any surface that would otherwise assert "no // ZIMs" while _libraryKnown is false. function _libraryUnavailableHtml() { // Cannot reach the server (not "it answered and the library would not // load"): that is a mode, not a fault. Lead with what is on the phone. const unreachable = _connState === CONN_OFFLINE; if (unreachable) { return '
' + tH('keep_kept') + '
' + '
'; } return '
' + '

' + tH('library_unavailable') + '

' + '

' + tH('library_unavailable_hint') + '

' + '' + '
'; } // What this device can do with no server, from what it actually holds: the // Almanac when its scripts are kept, Help now when the page and the guide's // own copy are, and the saved pages whose text is kept. Asked of the cache, not // assumed, so the list is true (an app opened once with no connection has none). async function _offlineWorks() { const kept = async function(url, bare) { try { return !!(await caches.match(url, bare ? { ignoreSearch: true } : undefined)); } catch (e) { return false; } }; const works = { carried: await _keepLocalList(), almanac: await kept(_ALMANAC_MODULES[_ALMANAC_MODULES.length - 1]), help: _fieldguideOn() && (await kept(_FIELDGUIDE_PAGE)) && (await kept(_FIELDGUIDE_OFFLINE_URL)), saved: 0 }; const items = Saved.all().filter(function(it) { return it.kind === 'article' && !it.app; }); const hits = await Promise.all(items.map(function(it) { return kept(_articleUrl(it.zim, it.path), true); })); works.saved = hits.filter(Boolean).length; return works; } // The panel's list, filled in once the cache has answered (only when the panel // is on screen). async function _renderOfflineHome() { const box = document.getElementById('offline-works'); if (!box) return; const w = await _offlineWorks(); if (!document.getElementById('offline-works')) return; w.carried.forEach(function(m) { _keepMetas[m.name] = m; }); _keepNames = new Set(w.carried.map(function(m) { return m.name; })); // The ZIMs on this phone as the library draws them: tiles, with their icons. const tiles = w.carried.map(function(m) { return { name: m.name, title: m.title || m.name, size_gb: (m.size || 0) / BYTES_PER_GB, has_icon: !!m.icon, description: '', entries: '' }; }); const noCount = function() { return ''; }; const saved = w.saved ? '' + '
\u2605
' + esc(t('saved_tab')) + '
' + '
' + esc(t('offline_works_saved_n', { n: w.saved })) + '
' : ''; _keepWarmWhenIdle(w.carried); box.innerHTML = '
' + _keepFilesBtnHtml() + '
' + renderCardGrid(tiles, false, false, noCount, ((w.almanac || w.help) ? _keepSurvivalTiles() : '') + saved); const none = document.getElementById('offline-none'); if (none) none.hidden = tiles.length > 0; } // ── Init ── async function init() { // Re-apply the app theme (the head bootstrap already stamped it pre-paint) and // start live-tracking the OS preference when in Auto mode. _applyAppTheme(); _bindAppThemeMedia(); // bfcache restore (Safari back/forward) re-runs no other script — re-assert // the theme so a restored page can't paint with a stale scheme. window.addEventListener('pageshow', function(e) { if (e.persisted) _applyAppTheme(); }); // Initialize i18n before anything else _currentLang = _detectLanguage(); _applyRTL(_currentLang); _bootHasPw = _fetchHasPw(); _bootWho = _fetchWhoami(); _bootWho.catch(function() {}); // read (and its failure handled) by _bootAuthGate, which a fresh install never reaches // Booting into the Almanac, its files come down while the words and the answers below are on their way. if (_ALM_BOOT_HASH.test(location.hash)) _almPreloadFiles(); await _loadI18n(_currentLang); // A fresh install opens once its owner says who can change settings. var _hp = await _bootHasPw; if (_hp.ok && _hp.j.setup) { _openSetup(_hp.j); return; } // Decide auth BEFORE any library chrome paints. On a private instance an // anonymous visitor gets the login form as the first frame (no empty flash), // and a token-authed admin is recognised so a reload never re-gates them. A // shown gate reloads the page on successful sign-in, so we stop the boot here. if (await _bootAuthGate()) return; // Learn manage-auth state in parallel with /list. /manage/has-password is a // cheap, lock-free endpoint, so this resolves long before /list on a large // library — the gear is then live the moment the library paints instead of // dead until the whole boot finishes (#44). _initSecondary reuses this probe. _manageProbe = _probeManageAuth(); _bindConnEvents(); // Paint the topbar BEFORE blocking on /list. The shell is fully interactive // from here on — the ⋯ menu (Create rides the remembered hint), search — so a // tap during a slow library load reaches a live control instead of landing on // a button that has not been drawn yet. updateTopbar runs again with real // authority once /list and the manage probe land, and corrects anything the // hint got wrong. updateTopbar(); // Late: a library that answers at once goes from nothing to Home, with no message blinking in between. output.innerHTML = '
' + tH('loading_library') + '
'; // Only block on /list — everything else loads in background. // A failure here must NOT collapse into "the library is empty": zimsCache // stays a safe [] for the hundreds of call sites that iterate it, but // _libraryKnown records that the emptiness is our ignorance, not a fact. // Booting into the Almanac, it does not wait for the library: it is on its way before the list is asked for, and home // is drawn behind it once the Almanac's page has run (the list is the slowest thing on a big library). var bootAlmanac = _ALM_BOOT_HASH.test(location.hash); var listing = _fetchList(); if (bootAlmanac) _openAlmanacFromAddress(); try { zimsCache = await listing; _libraryKnown = true; } catch(e) { zimsCache = []; _libraryKnown = false; _noteConnFailure(e); _renderConnBanner(); } _rebuildZimsMap(); _keepProbeStorage(); _keepRefreshNames().then(function() { if (_keepNames.size) _keepPrimeOffline(); }); // A new deploy's worker takes over with an empty cache (the Almanac it // carries itself): what a kept ZIM needs offline comes again. if ('serviceWorker' in navigator) { navigator.serviceWorker.addEventListener('controllerchange', function() { if (_keepNames.size) _keepPrimeOffline(); }); } // A kept answer marked the connection offline while the words were still // loading: say it again now they are here. if (_connState !== CONN_OK) _renderConnBanner(); // Render immediately with what we have if (!history.state) history.replaceState({ mode: 'home' }, '', location.href); _applyI18nToDOM(); // The shell is live during the load: a search or Manage opened meanwhile // is what is on screen now, and drawing the address's page would wipe it. // Nor the Almanac, open or on its way: route() would open it a second time // and rewrite its history entry, dropping a step Look had pushed on top. if (bootAlmanac) { Promise.resolve(_almanacModulesLoading).catch(function() {}).then(function() { setTimeout(function() { if (mode === 'home') renderHome(); }, 0); // drawn, not entered: the person may be in the 3D view by now }); } else if (mode === 'home' && !_almanacOpen && !_almanacModulesLoading) route(false); _desktopCheckOnboarding(); // Register service worker if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/static/sw.js', { scope: '/' }).catch(function() { _swPrimed = true; }); _keepOwnAheadWhenIdle(); // The first visit's answers went by before the worker was in charge: ask // for the ones the next start cannot do without once it is, so that start // can draw the library from the phone when the server does not answer. // Only then: a start the worker already controls kept them on the way in, // and asking again would cost every start three requests for nothing. // _swPrimed says when that is done (tests wait for the boot to go quiet). if (!navigator.serviceWorker.controller) { navigator.serviceWorker.addEventListener('controllerchange', function() { Promise.all(['/list?layout=1', '/whoami', '/manage/has-password'].map(function(u) { return fetch(u, { credentials: 'same-origin', headers: _manageToken ? _authHeaders() : {} }).catch(function() {}); })).then(function() { _swPrimed = true; }); }, { once: true }); } else { _swPrimed = true; } } // Fetch secondary data in parallel, update UI as each arrives _initSecondary(); _savedStart(); } // Resolves once we know whether the server wants a password. Ambient // pollers await this so they never fire an unauthenticated request (a 401 // resource error in the console) during the bootstrap race. let _manageProbe = null; // True once _probeManageAuth has finished at least once — lets enterManage // tell "manage genuinely disabled" (bail) apart from "state not known yet" // (open on demand). See #44. let _manageProbed = false; // The first visit's kept answers are asked for once the worker is in charge (boot). let _swPrimed = !('serviceWorker' in navigator); async function _probeManageAuth() { try { // Public pre-auth endpoint — learns password state without a 401 probe. var boot = _bootHasPw; _bootHasPw = null; const hres = await (boot || _fetchHasPw()); if (!hres.ok) { manageEnabled = false; return; } // 404 = manage disabled // Enabled only once the password answer is read: in between, a Manage // link saw manageEnabled with no password required and opened Manage // unasked (a slow CI runner caught the gap). const h = hres.j; manageEnabled = true; _setupState = h; _manageAccess = h.access || ''; const saved = _readManageToken(); if (saved) _manageToken = saved; if (h.has_password && !_manageToken) { _managePwRequired = true; // protected + not yet authenticated return; } const mres = await authedFetch('/manage/status'); if (mres.ok) { const mdata = await mres.json(); manageEnabled = !!mdata.manage_enabled; } else if (mres.status === 403) { // Passwordless instance, non-private client: no password exists to enter, // so surface an explanation instead of a bogus prompt (#36). manage stays // "enabled" so the tab is reachable and renders the locked banner. _managePublicLocked = true; // Bootstrap-from-remote: the server has no password AND we are not on the // host, so the door is the setup key it printed to its log, not a // password (GHSA-5mw2-53vv-9pw6). Remember which locked state this is so // the banner asks for the right thing. try { var _ld = await mres.clone().json(); _manageOutside = !!(_ld && _ld.error === 'outside_network'); _manageNeedsSetupKey = !!(_ld && _ld.needs_setup_key); _manageSetupKeyIssued = !(_ld && _ld.setup_key_issued === false); } catch (e) { _manageNeedsSetupKey = false; } } else if (mres.status === 401) { // Stored token went stale — drop BOTH copies (leaving the persisted // one meant every future load retried it, 401'd, and re-prompted). _manageToken = ''; _clearManageToken(); _managePwRequired = true; } } catch (e) {} finally { _manageProbed = true; whenQuiet(_warmManage, { key: 'manage-js', priority: QUIET_PRI_POLISH }); } } // The running server's version (/health), for the footer and what Zimi makes. var _zimiVersion = ''; async function _initSecondary() { var needsRerender = false; // Reuse the probe init() already kicked off in parallel with /list; only // start one here if that didn't run (e.g. a code path that skips init()). if (!_manageProbe) _manageProbe = _probeManageAuth(); var _probeDone = _manageProbe.then(() => { needsRerender = true; }); await Promise.allSettled([ _probeDone, // Collections/favorites fetch('/collections').then(async cres => { if (cres.ok) { collectionsCache = await cres.json(); needsRerender = true; } }).catch(function(){}), // Version for footer _healthOnce(true).then(hdata => { if (hdata) { if (hdata.version) { _zimiVersion = hdata.version; document.getElementById('footer-version').textContent = hdata.version + ' '; } _extServerOffline = !!hdata.offline; } }).catch(function(){}), // Domain→ZIM map for cross-ZIM links. A page read before it arrived // marked a link to an installed site as the web; now it knows better. fetch('/resolve?domains=1').then(async dres => { if (dres.ok) { _domainZimMap = await dres.json(); _extRemarkOpen(); } }).catch(function(){}) ]); // Always update topbar after secondary data (manage status determines gear visibility) updateTopbar(); // Create was opened before we could know whether this client may create — // either from a cold /#create load or from a tap during the library fetch. // Now we know. If the answer is no, leave rather than sit on a page whose // every button the server will refuse. if (_createOpen && !_canCreate()) { closeCreate(); _showToast(t('create_needs_admin')); } // Re-check URL for ?manage now that manageEnabled is known (route() ran before this resolved) var params = new URLSearchParams(location.search); if (params.get('manage') !== null && manageEnabled && mode !== 'manage') { enterManage(null, _validMsSection(params.get('manage'))); return; } // Re-render homepage if manage/collections changed (adds collection sections, // manage button). Not while manage is open: on a slow library the gear can be // used long before this resolves, and painting home over it leaves the manage // chrome (X button, catalog placeholder) on top of the home view. if (needsRerender) _renderHomeSoon(); } var _ALM_BOOT_HASH = /^#almanac(\?|$)/; function _openAlmanacFromAddress() { openAlmanac(true); // Backstop: if the almanac never comes up (a module error mid-parse slips // past the loader's onerror), drop the boot gate so the library isn't left // permanently hidden behind an empty shell. setTimeout(function () { if (!_almanacOpen) { document.documentElement.classList.remove('almanac-boot'); _almFirstFrameOff(); } }, 8000); } function route(push) { const path = location.pathname; const search = location.search; const params = new URLSearchParams(search); // Restore Almanac on reload if #almanac hash is present. The head bootstrap // already stamped html.almanac-boot, so the home render below stays invisible // and the dark almanac shell is what the first paint shows. // #almanac, or #almanac?... (the address almanac.js keeps up to date as the person moves; it is read there). if (_ALM_BOOT_HASH.test(location.hash)) { enterHome(false); _openAlmanacFromAddress(); return; } // Same for the Create page (#create). Opened optimistically: whether this // client may create is not known until the manage probe lands, and every // /manage/create* route is admin-gated server-side anyway — so the page // opens now and _initSecondary closes it if the answer comes back no. The // alternative, waiting, is the home-then-switch flash Eric asked us to kill. // The query form of an app address: /?tube=