// pistar.js — WebSocket client, theme switcher, i18n engine 'use strict'; var PiStar = (function() { var ws = null; // The page's strings: its language over English, from /i18n/strings.js // in (loaded before this script, so every string is there // before anything is drawn) var i18nStrings = window.PISTAR_I18N || {}; var _setupComplete = true; // assume configured until API says otherwise // WebSocket client var wsConnected = false; // true after first successful connection function connectWebSocket() { var proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; ws = new WebSocket(proto + '//' + location.host + '/ws'); ws.onopen = function() { if (wsConnected) { // Reconnection after server restart. Only check session // validity if we're on an admin page — public dashboard // doesn't need auth and shouldn't redirect to login. var onAdmin = window.location.pathname.indexOf('/admin') === 0; if (onAdmin) { adminFetch('/admin/api/system/info').then(function(r) { if (r && r.ok) { r.json().then(function(info) { if (info && typeof info.setupComplete !== 'undefined') { setSetupComplete(info.setupComplete); } }); document.dispatchEvent(new CustomEvent('pistar:reconnected')); } }); } else { document.dispatchEvent(new CustomEvent('pistar:reconnected')); } } wsConnected = true; }; ws.onmessage = function(event) { try { var msg = JSON.parse(event.data); if (msg.type === 'features' && msg.features) { applyFeatureVisibility(msg.features); } document.dispatchEvent(new CustomEvent('pistar:message', { detail: msg })); } catch (e) { // Silently discard malformed messages } }; ws.onclose = function() { // Reconnect after 3 seconds setTimeout(connectWebSocket, 3000); }; } // i18n engine // loadTranslations shows the page in another language: the server // picks the language per page (the one picked, else the browser's), // so the page is loaded again in it. function loadTranslations(lang) { setLanguage(lang); return Promise.resolve(); } function applyTranslations() { // Labels screen readers read, and hover titles, are translated too // (data-i18n-aria, data-i18n-title) document.querySelectorAll('[data-i18n-aria]').forEach(function(el) { var s = i18nStrings[el.getAttribute('data-i18n-aria')]; if (s) el.setAttribute('aria-label', s); }); document.querySelectorAll('[data-i18n-title]').forEach(function(el) { var s = i18nStrings[el.getAttribute('data-i18n-title')]; if (s) el.setAttribute('title', s); }); var elements = document.querySelectorAll('[data-i18n]'); elements.forEach(function(el) { var key = el.getAttribute('data-i18n'); if (i18nStrings[key]) { // "{n}" filled from data-i18n-arg ("DMR Network {n}") var arg = el.getAttribute('data-i18n-arg'); el.textContent = arg === null ? i18nStrings[key] : i18nStrings[key].replace('{n}', arg); } }); } function i18n(key, fallback) { return i18nStrings[key] || fallback || key; } // i18nPlural is a count's string in the page's language: the plural // category of n (Intl.PluralRules: one, few, many...) of key // (".few"), else its other, else English's one/other given here. // "{n}" is the number, wherever the language puts it. var pluralRules = null; var PLURAL_LOCALE = { 'pt': 'pt-PT' }; function i18nPlural(key, n, one, other) { var cat = 'other'; try { // pt is European Portuguese here (Intl's plain pt is Brazilian, // where 0 is singular) if (!pluralRules) pluralRules = new Intl.PluralRules(PLURAL_LOCALE[document.documentElement.lang] || document.documentElement.lang || 'en'); cat = pluralRules.select(n); } catch (e) { cat = n === 1 ? 'one' : 'other'; } var s = i18nStrings[key + '.' + cat] || i18nStrings[key + '.other'] || (n === 1 ? one : other) || key; return s.replace(/\{n\}/g, String(n)); } // ── Flags ── // countryName is a flag code's country in the page's language: the // browser names countries (Intl.DisplayNames); the UK's home nations // and Spain's regions are ours. var REGION_NAMES = { 'gb-eng': 'England', 'gb-wls': 'Wales', 'gb-sct': 'Scotland', 'gb-nir': 'Northern Ireland', 'es-ct': 'Catalonia', 'es-ga': 'Galicia', 'es-pv': 'Basque Country' }; var displayNames = null; function countryName(code) { if (!code) return ''; if (REGION_NAMES[code]) return i18n('geo.' + code, REGION_NAMES[code]); try { if (!displayNames) displayNames = new Intl.DisplayNames([document.documentElement.lang || 'en'], { type: 'region' }); return displayNames.of(code.toUpperCase()) || code.toUpperCase(); } catch (e) { return code.toUpperCase(); } } // flagHTML is a flag code's flag (flags.css), named for screen readers // and on hover; '' for no code. function flagHTML(code) { if (!code || !/^[a-z]{2}(-[a-z]{2,3})?$/.test(code)) return ''; var name = escAttr(countryName(code)); return ''; } // ── Look a caller up: their callsign opens a small menu ── // lookupItems: where a caller can be looked up: QRZ.com, RadioID and // aprs.fi by the callsign's base (no /P, -1 or D-Star extension), or // RadioID by the DMR or NXDN ID when there is no callsign. [] when // neither. function lookupItems(callsign, srcId) { var cs = String(callsign || '').toUpperCase().trim().split(/[\/\- ]/)[0]; if (!/^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]{3,8}$/.test(cs)) cs = ''; var id = String(srcId || callsign || ''); if (cs) { return [ { label: 'QRZ.com', url: 'https://www.qrz.com/db/' + encodeURIComponent(cs), title: i18n('lookup.qrz', 'Look up {call} on QRZ.com').replace('{call}', cs) }, { label: 'RadioID', url: 'https://database.radioid.net/database/view?callsign=' + encodeURIComponent(cs), title: i18n('lookup.radioId', 'Look up {call} on RadioID').replace('{call}', cs) }, { label: 'APRS (aprs.fi)', url: 'https://aprs.fi/#!call=' + encodeURIComponent(cs) + '*', title: i18n('lookup.aprs', 'Find {call} on aprs.fi').replace('{call}', cs) } ]; } if (/^[0-9]{1,8}$/.test(id)) { return [{ label: 'RadioID', url: 'https://database.radioid.net/database/view?id=' + encodeURIComponent(id), title: i18n('lookup.radioIdNum', 'Look up ID {id} on RadioID').replace('{id}', id) }]; } return []; } // callButton: a caller's callsign as the button that opens their // look-up menu (the text as given, already HTML); the plain text when // there is nothing to look them up by. function callButton(callsign, srcId, html) { if (!lookupItems(callsign, srcId).length) return html; var name = escAttr(i18n('lookup.menu', 'Look up {call}').replace('{call}', String(callsign || srcId || ''))); return ''; } // The menu: one for the page, opened under the button pressed (above // it when there is no room), closed by Escape, a click elsewhere, a // choice, scrolling or resizing. Arrow keys, Home and End move through // it; Escape gives the focus back to the callsign. var callMenu = null, callMenuFrom = null; function closeCallMenu(refocus) { if (!callMenu || callMenu.hidden) return; callMenu.hidden = true; if (callMenuFrom) { callMenuFrom.setAttribute('aria-expanded', 'false'); // Back to the callsign: the same button, or (the table redrawn // meanwhile) the same caller's var to = callMenuFrom; if (!document.body.contains(to)) { to = null; var call = callMenuFrom.getAttribute('data-call'), id = callMenuFrom.getAttribute('data-id'); Array.prototype.some.call(document.querySelectorAll('.call-menu-btn'), function(b) { if (b.getAttribute('data-call') === call && b.getAttribute('data-id') === id) { to = b; return true; } return false; }); } if (refocus && to) to.focus({ preventScroll: true }); } callMenuFrom = null; } function openCallMenu(btn) { var items = lookupItems(btn.getAttribute('data-call'), btn.getAttribute('data-id')); if (!items.length) return; if (!callMenu) { callMenu = document.createElement('div'); callMenu.id = 'ps-callmenu'; callMenu.className = 'call-menu'; callMenu.setAttribute('role', 'menu'); callMenu.hidden = true; document.body.appendChild(callMenu); callMenu.addEventListener('keydown', function(e) { var links = Array.prototype.slice.call(callMenu.querySelectorAll('a')); var i = links.indexOf(document.activeElement); var to = { ArrowDown: i + 1, ArrowUp: i - 1, Home: 0, End: links.length - 1 }[e.key]; if (e.key === 'Escape') { e.preventDefault(); closeCallMenu(true); return; } if (e.key === 'Tab') { closeCallMenu(false); return; } if (to === undefined) return; e.preventDefault(); links[(to + links.length) % links.length].focus({ preventScroll: true }); }); callMenu.addEventListener('click', function(e) { if (e.target.closest('a')) setTimeout(function() { closeCallMenu(false); }, 0); }); } var who = btn.getAttribute('data-call') || btn.getAttribute('data-id'); callMenu.innerHTML = '' + items.map(function(it) { return '' + '' + escAttr(it.label) + ''; }).join(''); callMenu.setAttribute('aria-label', i18n('lookup.menu', 'Look up {call}').replace('{call}', who)); if (callMenuFrom && callMenuFrom !== btn) callMenuFrom.setAttribute('aria-expanded', 'false'); callMenuFrom = btn; btn.setAttribute('aria-expanded', 'true'); callMenu.hidden = false; // Under the callsign, kept in the window var r = btn.getBoundingClientRect(), mw = callMenu.offsetWidth, mh = callMenu.offsetHeight; var left = Math.max(8, Math.min(r.left, window.innerWidth - mw - 8)); var top = r.bottom + 4; if (top + mh > window.innerHeight - 8 && r.top - mh - 4 > 8) top = r.top - mh - 4; callMenu.style.left = left + 'px'; callMenu.style.top = top + 'px'; callMenu.querySelector('a').focus({ preventScroll: true }); } document.addEventListener('click', function(e) { var btn = e.target.closest && e.target.closest('.call-menu-btn'); // Anywhere in an area holding a callsign's button (Recent // Activity's caller cell) opens it, unless text is being selected if (!btn && e.target.closest) { var area = e.target.closest('.call-menu-area'); var sel = window.getSelection && String(window.getSelection()); if (area && !sel) btn = area.querySelector('.call-menu-btn'); } if (btn) { e.preventDefault(); if (callMenuFrom === btn && callMenu && !callMenu.hidden) closeCallMenu(true); else openCallMenu(btn); return; } if (callMenu && !callMenu.hidden && !callMenu.contains(e.target)) closeCallMenu(false); }); document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && callMenu && !callMenu.hidden) closeCallMenu(true); }); window.addEventListener('resize', function() { closeCallMenu(false); }); // The page scrolled (not the menu itself): the menu would be left // behind window.addEventListener('scroll', function(e) { if (callMenu && (e.target === callMenu || callMenu.contains(e.target))) return; closeCallMenu(false); }, true); // labelFor is a schema field's or group's label, "{n}" filled from // its labelArg; labelAttrs the matching data-i18n attributes. function labelFor(key, fallback, arg) { var s = i18n(key, fallback); return arg ? s.replace('{n}', arg) : s; } function labelAttrs(key, arg) { return 'data-i18n="' + escAttr(key) + '"' + (arg ? ' data-i18n-arg="' + escAttr(arg) + '"' : ''); } // Theme switcher — persists to localStorage function setTheme(theme) { document.documentElement.setAttribute('data-theme', theme); try { localStorage.setItem('pistar-theme', theme); } catch (e) {} snow(theme === 'christmas-dark'); xmasLights(theme === 'christmas-dark'); lightning(theme === 'halloween-dark'); arcade(theme === 'arcade-dark'); speakSpell(theme === 'speakspell-dark'); if (theme === 'vt100-dark') { setTimeout(function() { vtType(true, true); }, 30); woprEvents(); } } // ── VT100: headings type themselves in ── // Each visible section heading is cleared and typed back a character // at a time, the block cursor riding at its end; screen readers have // the whole heading meanwhile (aria-label). When the page loads (and // on switching to the theme) each first types a line of WOPR's from // WarGames, in turn "GREETINGS PROFESSOR FALKEN." and "SHALL WE PLAY // A GAME?", backspaces it away and types its title; a page shown // later just types its title. Not for reduced motion. var typed = typeof WeakSet === 'function' ? new WeakSet() : null; function vtType(intro, again) { if (document.documentElement.getAttribute('data-theme') !== 'vt100-dark') return; if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; // WOPR's own words, as the film's screen shows them var lines = [wopr('greetings'), wopr('game')]; var heads = document.querySelectorAll('.card h2, main h1:not(.sr-only)'); var n = 0; Array.prototype.forEach.call(heads, function(h) { // Only plain-text headings that are on screen, once each if (h.children.length || !h.textContent.trim() || h.offsetParent === null) return; if (typed && typed.has(h) && !again) return; if (typed) typed.add(h); var text = h.textContent; // The steps: [what to show, how long until the next] var steps = []; var i; if (intro) { // The headings take turns: one greets, the next asks var game = lines[n % lines.length]; for (i = 1; i <= game.length; i++) steps.push([game.slice(0, i), 22 + Math.random() * 28]); steps[steps.length - 1][1] = 650; // a beat, for effect for (i = game.length - 1; i >= 0; i--) steps.push([game.slice(0, i), 9]); // backspace steps[steps.length - 1][1] = 180; } for (i = 1; i <= text.length; i++) steps.push([text.slice(0, i), 28 + Math.random() * 40]); var at = 0, shown = ''; h.setAttribute('aria-label', text); h.classList.add('vt-typing'); h.textContent = ''; function done() { if (h.textContent === shown || !h.textContent) h.textContent = text; h.classList.remove('vt-typing'); h.removeAttribute('aria-label'); } setTimeout(function step() { // Translations or a redraw changed it meanwhile: show that if (h.textContent !== shown) { done(); return; } if (at >= steps.length) { done(); return; } shown = steps[at][0]; h.textContent = shown; setTimeout(step, steps[at++][1]); }, 140 * n++); }); } // ── VT100: WOPR has more to say ── // Every minute or two, at random, WOPR takes over the headings on // screen: one of its exchanges from WarGames (or Trinity's, from The // Matrix) typed a line to a heading // in turn (each heading then types its own title back), or a heading // cracks the launch code a character at a time. Screen readers keep // the real headings (aria-label) throughout. Not while the tab is // hidden, and not for reduced motion. var WOPR = { joshua: 'JOSHUA?', logon: 'LOGON: JOSHUA', greetings: 'GREETINGS PROFESSOR FALKEN.', game: 'SHALL WE PLAY A GAME?', preferChess: "WOULDN'T YOU PREFER A GOOD GAME OF CHESS?", gtw: 'GLOBAL THERMONUCLEAR WAR', fine: 'FINE.', real: 'IS IT A GAME, OR IS IT REAL?', difference: "WHAT'S THE DIFFERENCE?", winner: 'WINNER: NONE', strange: 'A STRANGE GAME.', winning: 'THE ONLY WINNING MOVE IS NOT TO PLAY.', chess: 'HOW ABOUT A NICE GAME OF CHESS?', // and, on another green screen, The Matrix's wakeUp: 'Wake up, Neo...', matrixHas: 'The Matrix has you...', whiteRabbit: 'Follow the white rabbit.', knock: 'Knock, knock, Neo.' }; var WOPR_TALKS = [ ['joshua', 'greetings'], ['logon', 'greetings', 'game'], ['preferChess', 'gtw', 'fine'], ['real', 'difference'], ['winner', 'strange', 'winning', 'chess'], ['wakeUp', 'matrixHas', 'whiteRabbit', 'knock'] ]; var WOPR_CODE = 'PISTAR4EVR'; var WOPR_EVERY = [45, 120]; // seconds between WOPR's moments function wopr(k) { return i18n('vt100.' + k, WOPR[k]); } // The plain-text headings wholly on screen, not already being typed function vtOnScreen() { var out = []; Array.prototype.forEach.call(document.querySelectorAll('.card h2, main h1:not(.sr-only)'), function(h) { if (h.children.length || !h.textContent.trim() || h.offsetParent === null || h.classList.contains('vt-typing')) return; var r = h.getBoundingClientRect(); if (r.top >= 0 && r.bottom <= window.innerHeight) out.push(h); }); return out; } // Takes a heading over (its title kept for screen readers) and gives // it back function vtTake(h) { var title = h.textContent; h.setAttribute('aria-label', title); h.classList.add('vt-typing'); return { h: h, title: title, shown: title, // Set the text, unless something else (a translation, a // redraw) has changed it meanwhile: then let go set: function(t) { if (h.textContent !== this.shown) { this.release(); return false; } this.shown = t; h.textContent = t; return true; }, release: function() { if (h.textContent === this.shown) h.textContent = this.title; h.classList.remove('vt-typing'); h.removeAttribute('aria-label'); this.gone = true; } }; } // Plays [text, ms] steps on a taken heading, then calls done function vtPlay(t, steps, done) { var at = 0; (function step() { if (t.gone) return; if (at >= steps.length) { if (done) done(); return; } if (!t.set(steps[at][0])) return; setTimeout(step, steps[at++][1]); })(); } function vtBackspace(from, steps) { for (var i = from.length - 1; i >= 0; i--) steps.push([from.slice(0, i), 9]); return steps; } function vtTypeIn(text, steps, last) { for (var i = 1; i <= text.length; i++) steps.push([text.slice(0, i), 26 + Math.random() * 38]); if (last) steps[steps.length - 1][1] = last; return steps; } // One of WOPR's exchanges, a line to a heading in turn function vtTalk(keys) { var heads = vtOnScreen(); if (!heads.length) return; var taken = [], uses = []; keys.forEach(function(k, i) { var n = i % Math.min(heads.length, keys.length); if (!taken[n]) taken[n] = vtTake(heads[n]); uses[i] = n; }); function say(i) { if (i >= keys.length) return; var t = taken[uses[i]], line = wopr(keys[i]); var steps = vtTypeIn(line, vtBackspace(t.shown, []), 1300); vtPlay(t, steps, function() { // The next line, on the next heading say(i + 1); // This heading's last line: its title back if (uses.lastIndexOf(uses[i]) === i) { setTimeout(function() { vtPlay(t, vtTypeIn(t.title, vtBackspace(t.shown, []), 1), function() { t.release(); }); }, 400); } }); } say(0); } // The launch code: scrambling characters that lock in one by one function vtCrack() { var heads = vtOnScreen(); if (!heads.length) return; var t = vtTake(heads[Math.floor(Math.random() * heads.length)]); var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', locked = [], left = []; for (var i = 0; i < WOPR_CODE.length; i++) { locked.push(false); left.push(i); } vtPlay(t, vtBackspace(t.shown, []), function() { var tick = 0; (function spin() { if (t.gone) return; if (++tick % 6 === 0 && left.length) locked[left.splice(Math.floor(Math.random() * left.length), 1)[0]] = true; var s = ''; for (var j = 0; j < WOPR_CODE.length; j++) { s += locked[j] ? WOPR_CODE.charAt(j) : chars.charAt(Math.floor(Math.random() * chars.length)); } if (!t.set(s)) return; if (left.length || tick % 6) { setTimeout(spin, 55); return; } // Cracked: hold it, then the title back setTimeout(function() { vtPlay(t, vtTypeIn(t.title, vtBackspace(t.shown, []), 1), function() { t.release(); }); }, 1800); })(); }); } var woprTimer = 0; function woprEvents() { if (woprTimer) return; (function next() { var wait = (WOPR_EVERY[0] + Math.random() * (WOPR_EVERY[1] - WOPR_EVERY[0])) * 1000; woprTimer = setTimeout(function() { woprTimer = 0; // Gone from the theme: stop (setting it again starts it) if (document.documentElement.getAttribute('data-theme') !== 'vt100-dark') return; var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; if (!document.hidden && !reduce) { if (Math.random() < 0.25) vtCrack(); else vtTalk(WOPR_TALKS[Math.floor(Math.random() * WOPR_TALKS.length)]); } next(); }, wait); })(); } // ── Speak & Spell: its power-on chirp, and now and then it speaks ── // The chirp is made as it plays (Web Audio); the voice is a clip made // with NiceVoice's Speak & Spell voice generator (credited in the // manual), /static/audio/speakspell-incorrect.mp3. The chirp plays on // choosing the theme only: nothing at all happens as a page opens // (no audio made, no clip fetched), so page loads are not held up. The voice comes about SPEAK_FIRST seconds in, then every SPEAK_EVERY seconds or so, while // the page is shown, spelled out on the VFD as it speaks (the VFD // alone while the browser keeps the page quiet). var SPEAK_VOLUME = 0.12; // the chirp var VOICE_VOLUME = 0.3; // the clip var SPEAK_FIRST = [150, 210]; // the first time: about 3 minutes in var SPEAK_EVERY = [300, 1200]; // then every 5 to 20 minutes var VOICE_URL = '/static/audio/speakspell-incorrect.mp3'; var speakState = null; function speakSpell(on) { if (!on) { if (speakState) { clearTimeout(speakState.timer); clearTimeout(speakState.sleep); if (speakState.gesture) { document.removeEventListener('pointerdown', speakState.gesture, true); document.removeEventListener('keydown', speakState.gesture, true); } if (speakState.ctx) { var c = speakState.ctx.close(); if (c && c.catch) c.catch(function() {}); } if (speakState.say) speakState.say.remove(); speakState = null; } return; } if (speakState) return; var st = speakState = { ctx: null, timer: 0, say: null, gesture: null, voice: null, loading: false }; // The page's sound: made at once (a browser that keeps the page // quiet holds it suspended until a click or key) function audio() { if (!st.ctx) { var AC = window.AudioContext || window.webkitAudioContext; if (!AC) return null; try { st.ctx = new AC(); } catch (e) { return null; } } return st.ctx; } function audible() { return !!(st.ctx && st.ctx.state === 'running'); } // Between sounds the page's audio sleeps (suspended), so the // browser's audio thread is not kept running in silence; woken for // the next one (the page may: it has been clicked, unlocked) function sleepAfter(seconds) { clearTimeout(st.sleep); st.sleep = setTimeout(function() { if (st.ctx && st.ctx.state === 'running') { var r = st.ctx.suspend(); if (r && r.catch) r.catch(function() {}); } }, seconds * 1000); } function wake(play) { // Nothing made until it speaks, and only once the page has been // clicked or a key pressed (else the VFD alone) if (!st.ctx && pageActivated() && audio()) st.unlocked = true; if (!st.ctx || !st.unlocked) return; clearTimeout(st.sleep); if (st.ctx.state === 'running') { play(st.ctx); return; } var r = st.ctx.resume(); if (r && r.then) r.then(function() { if (speakState === st && audible()) play(st.ctx); }, function() {}); } // play(ac) now if the page may make sound, else at the first click // or key press function whenAudible(play) { var ac = audio(); if (!ac) return; if (ac.state === 'running') { st.unlocked = true; play(ac); return; } var done = false; function go() { if (done || speakState !== st || !audible()) return; done = true; st.unlocked = true; if (st.gesture) { document.removeEventListener('pointerdown', st.gesture, true); document.removeEventListener('keydown', st.gesture, true); st.gesture = null; } play(st.ctx); } var r = ac.resume(); if (r && r.then) r.then(go, function() {}); if (!st.gesture) { st.gesture = function() { if (!st.ctx) return; var g = st.ctx.resume(); if (g && g.then) g.then(go, function() {}); else go(); }; document.addEventListener('pointerdown', st.gesture, true); document.addEventListener('keydown', st.gesture, true); } } // The power-on chirp: a quick run of buzzy square-wave notes, each // sliding, through a filter like a small speaker function chirp(ac) { var out = ac.createGain(); out.gain.value = SPEAK_VOLUME; var lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 2600; lp.connect(out); out.connect(ac.destination); var t = ac.currentTime + 0.05; [[392, 523], [523, 466], [659, 784], [784, 1047], [1047, 988]].forEach(function(n, i) { var o = ac.createOscillator(), g = ac.createGain(), at = t + i * 0.085; o.type = 'square'; o.frequency.setValueAtTime(n[0], at); o.frequency.exponentialRampToValueAtTime(n[1], at + 0.07); g.gain.setValueAtTime(0.0001, at); g.gain.exponentialRampToValueAtTime(1, at + 0.008); g.gain.exponentialRampToValueAtTime(0.0001, at + (i === 4 ? 0.32 : 0.08)); o.connect(g); g.connect(lp); o.start(at); o.stop(at + 0.34); }); sleepAfter(1.5); } // The voice clip, fetched and decoded once function loadVoice(then) { if (st.voice) { then(st.voice); return; } if (st.loading || !window.fetch) return; st.loading = true; fetch(VOICE_URL).then(function(r) { return r.ok ? r.arrayBuffer() : Promise.reject(r.status); }).then(function(buf) { if (speakState !== st || !st.ctx) return; // The callback form too (older Safari has no promise) st.ctx.decodeAudioData(buf, function(decoded) { st.voice = decoded; st.loading = false; then(decoded); }, function() { st.loading = false; }); }).catch(function() { st.loading = false; }); } function say(ac) { loadVoice(function(buf) { if (speakState !== st || !audible()) return; var src = ac.createBufferSource(), g = ac.createGain(); src.buffer = buf; g.gain.value = VOICE_VOLUME; src.connect(g); g.connect(ac.destination); src.start(ac.currentTime + 0.05); sleepAfter(buf.duration + 1); }); } // What it says, spelled out on the VFD a letter at a time: over the // LCD panel when it is on the page, else a strip under the top bar function spell(lines, done) { var lcd = document.querySelector('.lcd-screen'); var box = document.createElement('div'); box.className = 'ss-say' + (lcd && lcd.offsetParent ? '' : ' ss-say-strip'); box.setAttribute('role', 'status'); (lcd && lcd.offsetParent ? lcd : document.body).appendChild(box); st.say = box; var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; var li = 0; (function line() { if (st.say !== box) return; if (li >= lines.length) { setTimeout(function() { box.remove(); if (st.say === box) st.say = null; if (done) done(); }, 1600); return; } var text = lines[li++].toUpperCase(), n = reduce ? text.length : 0; (function type() { if (st.say !== box) return; box.textContent = text.slice(0, n); if (n < text.length) { var caret = document.createElement('span'); caret.className = 'ss-caret'; caret.textContent = '_'; box.appendChild(caret); n++; setTimeout(type, 55); } else { setTimeout(line, 1700); } })(); })(); } // The message as two screens of about equal length, split at the // space nearest the middle ("THAT IS INCORRECT. THE CORRECT" / // "PRONUNCIATION OF WPSD IS PI-STAR"); a language written without // spaces keeps its two sentences function screens(a, b) { var all = a + ' ' + b, mid = all.length / 2, best = -1; for (var i = 0; i < all.length; i++) { if (all.charAt(i) === ' ' && (best < 0 || Math.abs(i - mid) < Math.abs(best - mid))) best = i; } if (best < 0 || Math.abs(best - mid) > all.length / 4 || !/ /.test(a)) return [a, b]; return [all.slice(0, best), all.slice(best + 1)]; } function incorrect() { spell(screens(i18n('speakSpell.incorrect', 'That is incorrect.'), i18n('speakSpell.correct', 'The correct pronunciation of WPSD is Pi-Star'))); wake(say); } // Chosen just now in the picker (a click on a page already loaded): // the power-on chirp. Never as a page opens: no sound, no audio and // no clip fetched until the voice first speaks if (window.navigator.userActivation && window.navigator.userActivation.isActive) { whenAudible(function(ac) { chirp(ac); }); } (function next(range) { var wait = (range[0] + Math.random() * (range[1] - range[0])) * 1000; st.timer = setTimeout(function() { if (speakState !== st) return; if (!document.hidden && !st.say) incorrect(); next(SPEAK_EVERY); }, wait); })(SPEAK_FIRST); st.test = incorrect; } // A page shown by the admin sidebar or the manual's contents types // its headings in the first time (the sidebars switch pages without // changing the address) document.addEventListener('click', function(e) { if (e.target.closest && e.target.closest('.sidebar-link, .toc-link')) { setTimeout(function() { vtType(false, false); }, 30); } }); // ── Snow (the Christmas theme) ── // Flakes drawn on one canvas over the page, in the browser (nothing on // the hotspot): paused while the tab is hidden, and never for anyone // whose system asks for reduced motion. var snowState = null; function snow(on) { var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; if (!on || reduce) { if (snowState) { cancelAnimationFrame(snowState.frame); snowState.canvas.remove(); snowState = null; } return; } if (snowState) return; var canvas = document.createElement('canvas'); canvas.id = 'ps-snow'; canvas.setAttribute('aria-hidden', 'true'); document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); var flakes = [], w = 0, h = 0, ratio = Math.min(window.devicePixelRatio || 1, 2); function size() { w = window.innerWidth; h = window.innerHeight; canvas.width = w * ratio; canvas.height = h * ratio; canvas.style.width = w + 'px'; canvas.style.height = h + 'px'; ctx.setTransform(ratio, 0, 0, ratio, 0, 0); // About one flake per 18,000 square pixels: light on a phone var want = Math.max(30, Math.min(140, Math.round(w * h / 18000))); while (flakes.length < want) flakes.push(flake(true)); flakes.length = want; } function flake(anywhere) { return { x: Math.random() * w, y: anywhere ? Math.random() * h : -6, r: 1 + Math.random() * 2.6, v: 0.35 + Math.random() * 0.9, sway: Math.random() * Math.PI * 2, drift: 0.4 + Math.random() * 0.8, a: 0.55 + Math.random() * 0.45 }; } function draw() { ctx.clearRect(0, 0, w, h); for (var i = 0; i < flakes.length; i++) { var f = flakes[i]; f.y += f.v * (0.6 + f.r / 3); f.sway += 0.01 + f.v * 0.01; f.x += Math.sin(f.sway) * f.drift * 0.5; if (f.y > h + 6) { flakes[i] = flake(false); continue; } if (f.x < -6) f.x = w + 6; else if (f.x > w + 6) f.x = -6; ctx.beginPath(); ctx.arc(f.x, f.y, f.r, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255,255,255,' + f.a + ')'; ctx.fill(); } snowState.frame = requestAnimationFrame(draw); } snowState = { canvas: canvas, frame: 0 }; size(); window.addEventListener('resize', function() { if (snowState) size(); }); document.addEventListener('visibilitychange', function() { if (!snowState) return; if (document.hidden) cancelAnimationFrame(snowState.frame); else snowState.frame = requestAnimationFrame(draw); }); snowState.frame = requestAnimationFrame(draw); } // ── Christmas lights along the top bar ── // A bulb every 30px (the wire's dip), each glowing on its own; the // string changes pattern every few seconds: a random twinkle, a chase, // flashing by colour (christmas-dark.css draws them). For reduced // motion the theme's still strip is left as it is. var XMAS_COLOURS = ['#ff3b4e', '#ffd34d', '#3fd16a', '#6fd3ff']; var lightsState = null; function xmasLights(on) { var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; var header = document.querySelector('header[role="banner"]'); if (!on || reduce || !header) { if (lightsState) { clearInterval(lightsState.timer); window.removeEventListener('resize', lightsState.build); lightsState.el.remove(); lightsState.header.classList.remove('ps-lit'); lightsState = null; } return; } if (lightsState) return; var el = document.createElement('div'); el.id = 'ps-lights'; el.setAttribute('aria-hidden', 'true'); el.setAttribute('data-mode', 'twinkle'); function build() { var n = Math.ceil(header.clientWidth / 30), html = ''; for (var i = 0; i < n; i++) { var g = i % XMAS_COLOURS.length; html += ''; } el.innerHTML = html; } build(); header.appendChild(el); header.classList.add('ps-lit'); var modes = ['twinkle', 'chase', 'twinkle', 'flash'], m = 0; lightsState = { el: el, header: header, build: build, timer: setInterval(function() { m = (m + 1) % modes.length; el.setAttribute('data-mode', modes[m]); }, 7000) }; window.addEventListener('resize', build); } // ── Halloween: lightning now and then ── // Every 15 to 40 seconds a jagged bolt, with a branch or two, cracks // down from the top of the window with a double flash, and fades. Two // flashes a strike: well inside three a second (WCAG 2.3.1). Drawn on // one canvas over the page, in the browser; paused while the tab is // hidden; never for anyone whose system asks for reduced motion. // // One strike in a few comes all the way down and hits the ground at // the bottom of the window, 1960s comedy-horror style: it lights up an // old tilted tombstone (RIP Pi-Star DV-Dash, 2014-2026), and a zombie // claws its way up out of the grave, sways, and makes off, until a // second bolt blows it to bits, leaving a smoking shoe. Those two bolts // have a quiet thunder crash; the others are silent. // One strike in this many (at random within) hits the ground var LIGHTNING_GROUND_ONE_IN = [14, 20]; // The zombie (this theme's own pixel art), side on, facing right, arms // out: h hair, s skin, S its shadow, e eye socket, r the eye's glow, // m mouth, t a tooth, j its jacket, J the jacket's shadow, w its shirt, // b gore, o ribs, p trousers, k a shoe, f a bare foot var ZOMBIE_TOP = [ '.......h.hh.......', '......hsssh.......', '.....hssssss......', '.....sssseer......', '.....Sssssss......', '......Ssssmt......', '......SSsmmt......', '.......Ssss.......', '.....jjjjwSs......', '....jjjjjjjjjjjss.', '....jjjjwjJJJJJsss', '....jjjjwjj.....s.', '....jjjjwbj.......', '....jjjjooj.......', '....jjjjwoj.......', '.....jjjwwj.......', '.....jjJ.Jj.......', '.....j.pppj.......', '......pppp........' ]; var ZOMBIE_LEGS = [[ '......pp.pp.......', '.....pp...pp......', '.....pp...pp......', '....pp.....pp.....', '....pp.....pp.....', '....pp......f.....', '...kkk......ff....' ], [ '......pppp........', '......pp.pp.......', '......pp.pp.......', '......pp.pp.......', '......pp..p.......', '......pp..f.......', '.....kkk..ff......' ]]; var ZOMBIE_COLOURS = { h: '#26261c', s: '#8fae7c', S: '#5f7a52', e: '#14140f', r: '#d8ff4a', m: '#3a1414', t: '#ddd6b4', j: '#4a4458', J: '#2e2a38', w: '#a89f80', b: '#7a1f1f', o: '#ddd6b4', p: '#3b3a30', k: '#1e1a16', f: '#8fae7c' }; // The thunder's volume: quiet (under the credits page's music) var THUNDER_VOLUME = 0.1; // Browsers allow sound once the page has been clicked or a key pressed // (at any time: navigator.userActivation knows, where there is one) function pageActivated() { return !window.navigator.userActivation || window.navigator.userActivation.hasBeenActive; } var lightningState = null; function lightning(on) { var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; if (!on || reduce) { if (lightningState) { clearTimeout(lightningState.timer); cancelAnimationFrame(lightningState.frame); lightningState.quiet(); lightningState.canvas.remove(); lightningState = null; } return; } if (lightningState) return; var canvas = document.createElement('canvas'); canvas.id = 'ps-lightning'; canvas.setAttribute('aria-hidden', 'true'); document.body.appendChild(canvas); var ctx = canvas.getContext('2d'), w = 0, h = 0, ratio = Math.min(window.devicePixelRatio || 1, 2); var st = lightningState = { canvas: canvas, timer: 0, frame: 0, strikes: 0, groundAt: pickGround() }; function pickGround() { var lo = LIGHTNING_GROUND_ONE_IN[0], hi = LIGHTNING_GROUND_ONE_IN[1]; return lo + Math.floor(Math.random() * (hi - lo + 1)); } function size() { w = window.innerWidth; h = window.innerHeight; canvas.width = w * ratio; canvas.height = h * ratio; canvas.style.width = w + 'px'; canvas.style.height = h + 'px'; ctx.setTransform(ratio, 0, 0, ratio, 0, 0); } // ── Thunder (the ground strike and the zombie's bolt only): a // crack, then a rumble. Made as it plays (Web Audio), quiet. Silent until the page // has been clicked or a key pressed (before or after the theme // started), as browsers require. var snd = { ctx: null, master: null, noise: null }; function wake() { if (!snd.ctx) { var AC = window.AudioContext || window.webkitAudioContext; if (!AC || !pageActivated()) return null; try { snd.ctx = new AC(); } catch (e) { return null; } snd.master = snd.ctx.createGain(); snd.master.gain.value = THUNDER_VOLUME; snd.master.connect(snd.ctx.destination); } if (snd.ctx.state === 'suspended') { var r = snd.ctx.resume(); if (r && r.catch) r.catch(function() {}); return r; } return null; } // Between claps the sound sleeps (suspended), so the browser's // audio thread is not kept running in silence function rest(seconds) { clearTimeout(snd.sleep); snd.sleep = setTimeout(function() { if (snd.ctx && snd.ctx.state === 'running') { var r = snd.ctx.suspend(); if (r && r.catch) r.catch(function() {}); } }, seconds * 1000); } // A click or key unlocks the sound (browsers require it), which // then sleeps until there is thunder function onGesture() { wake(); rest(1); } document.addEventListener('pointerdown', onGesture, true); document.addEventListener('keydown', onGesture, true); st.quiet = function() { document.removeEventListener('pointerdown', onGesture, true); document.removeEventListener('keydown', onGesture, true); clearTimeout(snd.sleep); if (snd.ctx) { var c = snd.ctx.close(); if (c && c.catch) c.catch(function() {}); } snd.ctx = null; }; // Play now, or as soon as the sound wakes; asleep again once the // rumble has died away function sound(play) { var waking = wake(); if (!snd.ctx) return; var go = function() { clearTimeout(snd.sleep); play(snd.ctx); rest(4); }; if (snd.ctx.state === 'running') go(); else if (waking && waking.then) waking.then(function() { if (snd.ctx && snd.ctx.state === 'running') go(); }); } function thunder(x, ground) { sound(function(ac) { var t = ac.currentTime + 0.12, len = 3; if (!snd.noise) { snd.noise = ac.createBuffer(1, Math.floor(ac.sampleRate * len), ac.sampleRate); var d = snd.noise.getChannelData(0); for (var i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; } var out = snd.master; if (ac.createStereoPanner) { out = ac.createStereoPanner(); out.pan.value = Math.max(-0.7, Math.min(0.7, x / (w || 1) * 2 - 1)); out.connect(snd.master); } function noise(at, dur, type, from, to, peak) { var n = ac.createBufferSource(), f = ac.createBiquadFilter(), g = ac.createGain(); n.buffer = snd.noise; f.type = type; f.frequency.setValueAtTime(from, at); f.frequency.exponentialRampToValueAtTime(to, at + dur); g.gain.setValueAtTime(0.0001, at); g.gain.exponentialRampToValueAtTime(peak, at + Math.min(0.06, dur / 4)); g.gain.exponentialRampToValueAtTime(0.0001, at + dur); n.connect(f); f.connect(g); g.connect(out); n.start(at, Math.random() * 0.5); n.stop(at + dur); } // The crack, its crackle, then the rumble rolling away noise(t, ground ? 0.4 : 0.3, 'highpass', 3000, 1000, ground ? 1 : 0.8); noise(t + 0.03, 0.7, 'bandpass', 1800, 500, 0.7); noise(t + 0.08, 2.6, 'lowpass', 1100, 140, 0.9); noise(t + 0.7 + Math.random() * 0.3, 1.8, 'lowpass', 700, 110, 0.6); if (ground) { var o = ac.createOscillator(), og = ac.createGain(); o.type = 'sine'; o.frequency.setValueAtTime(110, t); o.frequency.exponentialRampToValueAtTime(35, t + 0.6); og.gain.setValueAtTime(0.8, t); og.gain.exponentialRampToValueAtTime(0.0001, t + 0.7); o.connect(og); og.connect(out); o.start(t); o.stop(t + 0.75); } }); } // A bolt: from (x, y) downwards, kinked every few pixels, with // the odd thinner branch forking off function bolt(x, y, len, width, depth, segs) { var pts = [[x, y]], ang = Math.PI / 2 + (Math.random() - 0.5) * 0.4; var step = len / 14; for (var i = 0; i < 14; i++) { ang += (Math.random() - 0.5) * 0.9; ang = Math.max(Math.PI * 0.2, Math.min(Math.PI * 0.8, ang)); x += Math.cos(ang) * step; y += Math.sin(ang) * step; pts.push([x, y]); if (depth < 2 && i > 2 && i < 11 && Math.random() < 0.16) { bolt(x, y, len * (0.25 + Math.random() * 0.25), width * 0.55, depth + 1, segs); } } segs.push({ pts: pts, width: width }); return segs; } // A bolt from the top that ends at (x, y): stretched and moved there function boltTo(top, x, y) { var segs = bolt(x + (Math.random() - 0.5) * w * 0.3, top, (y - top) * 0.7, 2.6, 0, []); var main = segs[segs.length - 1].pts, end = main[main.length - 1]; var k = (y - top) / Math.max(1, end[1] - top), dx = x - end[0]; segs.forEach(function(sg) { sg.pts.forEach(function(p, i) { p[1] = top + (p[1] - top) * k; // Moved more the lower it is, so it starts near where it was p[0] += dx * (p[1] - top) / Math.max(1, y - top); }); }); return segs; } function drawBolt(segs, a) { ctx.save(); ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.shadowColor = 'rgba(179,139,255,0.9)'; ctx.shadowBlur = 18; segs.forEach(function(sg) { ctx.beginPath(); sg.pts.forEach(function(p, i) { if (i) ctx.lineTo(p[0], p[1]); else ctx.moveTo(p[0], p[1]); }); ctx.strokeStyle = 'rgba(235,225,255,' + a.toFixed(3) + ')'; ctx.lineWidth = sg.width; ctx.stroke(); }); ctx.restore(); } // ── The zombie ── function zombieRows(legs) { return ZOMBIE_TOP.concat(ZOMBIE_LEGS[legs]); } function zombieSprite(x, y, p, legs, flip, clipY) { var rows = zombieRows(legs), cols = rows[0].length; for (var r = 0; r < rows.length; r++) { var yy = y + r * p; if (yy >= clipY) break; for (var c = 0; c < cols; c++) { var ch = rows[r].charAt(flip ? cols - 1 - c : c); if (ch === '.') continue; ctx.fillStyle = ZOMBIE_COLOURS[ch]; ctx.fillRect(Math.round(x + c * p), Math.round(yy), Math.ceil(p), Math.ceil(Math.min(p, clipY - yy))); } } } // ── The tombstone: drawn once, old and dirty, then tilted ── function tombstoneArt(p) { var sw = p * 26, sh = p * 34, pad = p * 2; var c = document.createElement('canvas'), g = c.getContext('2d'); c.width = sw + pad * 2; c.height = sh + pad; g.translate(pad, pad); // Its shape: a round top with a chip out of one shoulder function shape() { g.beginPath(); g.moveTo(0, sh); g.lineTo(0, sw / 2); g.arc(sw / 2, sw / 2, sw / 2, Math.PI, Math.PI * 1.62); g.lineTo(sw * 0.66, p * 2.2); g.lineTo(sw * 0.72, p * 3.4); g.arc(sw / 2, sw / 2, sw / 2, Math.PI * 1.8, 0); g.lineTo(sw, sh); g.closePath(); } shape(); var stone = g.createLinearGradient(0, 0, sw, sh); stone.addColorStop(0, '#9c9886'); stone.addColorStop(0.6, '#77735f'); stone.addColorStop(1, '#4a4739'); g.fillStyle = stone; g.fill(); g.save(); g.clip(); // Grime and weather stains, darker towards the ground for (var i = 0; i < 70; i++) { var gx = Math.random() * sw, gy = Math.random() * sh, r = p * (0.6 + Math.random() * 2.6); g.fillStyle = 'rgba(30,26,18,' + (0.08 + 0.22 * gy / sh * Math.random()).toFixed(3) + ')'; g.beginPath(); g.arc(gx, gy, r, 0, Math.PI * 2); g.fill(); } for (var d = 0; d < 6; d++) { var dx = Math.random() * sw; g.fillStyle = 'rgba(30,26,18,0.18)'; g.fillRect(dx, sw * 0.4, p * 0.7, sh * (0.3 + Math.random() * 0.5)); } // Moss, at the foot and on the top for (var m = 0; m < 90; m++) { var low = m < 60; // (clear of the words) var mx = Math.random() * sw, my = low ? sh - Math.random() * sh * 0.24 : Math.random() * sh * 0.1; g.fillStyle = Math.random() < 0.5 ? 'rgba(74,104,44,0.75)' : 'rgba(104,128,58,0.6)'; g.fillRect(Math.round(mx), Math.round(my), Math.ceil(p * (0.6 + Math.random())), Math.ceil(p * (0.6 + Math.random()))); } g.restore(); shape(); g.lineWidth = Math.max(1, p * 0.6); g.strokeStyle = '#2a271e'; g.stroke(); // Cracks g.lineWidth = Math.max(1, p * 0.4); g.beginPath(); g.moveTo(sw * 0.1, sh * 0.72); g.lineTo(sw * 0.2, sh * 0.8); g.lineTo(sw * 0.15, sh * 0.9); g.moveTo(sw * 0.9, sh * 0.62); g.lineTo(sw * 0.78, sh * 0.72); g.lineTo(sw * 0.84, sh * 0.82); g.lineTo(sw * 0.76, sh * 0.95); g.stroke(); // The words, cut in: a dark letter with a lighter edge below function cut(text, size, y) { g.font = 'bold ' + size + 'px Georgia, "Times New Roman", serif'; var tw = g.measureText(text).width, room = sw * 0.86; g.save(); g.translate(sw / 2, y); if (tw > room) g.scale(room / tw, 1); g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillStyle = 'rgba(236,230,206,0.55)'; g.fillText(text, 0, Math.max(1, p * 0.4)); g.fillStyle = '#16140e'; g.fillText(text, 0, 0); g.restore(); } cut('RIP', Math.round(p * 7), sh * 0.26); cut('Pi-Star DV-Dash', Math.round(p * 3.9), sh * 0.47); cut('2014 – 2026', Math.round(p * 3.3), sh * 0.61); return { c: c, sw: sw, sh: sh, pad: pad }; } function drawTombstone(g, floor, p, a) { var art = g.stoneArt; ctx.save(); ctx.globalAlpha = a; // Leaning, and sunk a little into the ground ctx.translate(g.stone, floor + p * 3); ctx.rotate(g.tilt); ctx.drawImage(art.c, -art.sw / 2 - art.pad, -art.sh - art.pad); ctx.restore(); // A mound of earth and some grass at its foot ctx.save(); ctx.globalAlpha = a; ctx.fillStyle = '#2b2116'; ctx.beginPath(); ctx.ellipse(g.stone, floor, art.sw * 0.75, p * 3, 0, Math.PI, 0); ctx.fill(); ctx.fillStyle = '#2f4a22'; for (var gx = g.stone - art.sw * 0.8; gx < g.stone + art.sw * 0.8; gx += p * 1.4) { var tall = (Math.round(gx / p) * 7) % 5; ctx.fillRect(Math.round(gx), floor - p * (1.2 + tall * 0.4), Math.ceil(p * 0.7), p * 3); } ctx.restore(); } function scorch(x, floor, t) { var heat = Math.max(0, 1 - t / 1500), mark = Math.max(0, 1 - t / 7000); if (mark <= 0) return; ctx.save(); ctx.translate(x, floor); ctx.scale(1, 0.28); var grad = ctx.createRadialGradient(0, 0, 0, 0, 0, 70); grad.addColorStop(0, 'rgba(' + Math.round(40 + 215 * heat) + ',' + Math.round(20 + 120 * heat) + ',20,' + (0.75 * mark).toFixed(3) + ')'); grad.addColorStop(1, 'rgba(20,10,5,0)'); ctx.fillStyle = grad; ctx.beginPath(); ctx.arc(0, 0, 70, 0, Math.PI * 2); ctx.fill(); ctx.restore(); } // The zombie in pieces: each of its pixels flung out, and its shoe // left behind, smoking function blowUp(g, p, zw, zh, floor) { var z = g.z, rows = zombieRows(z.frame), cols = rows[0].length; var cx = z.x + zw / 2, cy = floor - zh / 2; for (var r = 0; r < rows.length; r++) { for (var c = 0; c < cols; c++) { var ch = rows[r].charAt(z.dir < 0 ? cols - 1 - c : c); if (ch === '.' || ch === 'k') continue; var x = z.x + c * p, y = floor - zh + r * p, dx = x - cx, dy = y - cy, d = Math.sqrt(dx * dx + dy * dy) || 1; var v = 140 + Math.random() * 320; g.bits.push({ x: x, y: y, vx: dx / d * v + (Math.random() - 0.5) * 80, vy: dy / d * v - 160 - Math.random() * 120, t: 1.6 + Math.random() * 0.8, s: p, c: ZOMBIE_COLOURS[ch] }); } } for (var n = 0; n < 30; n++) { var a = Math.random() * Math.PI * 2, sv = 100 + Math.random() * 300; g.bits.push({ x: cx, y: cy, vx: Math.cos(a) * sv, vy: Math.sin(a) * sv, t: 0.4 + Math.random() * 0.4, s: 2, c: n % 2 ? '#ffd23f' : '#e8e0ff' }); } // Where the shoe was: the bottom row's k pixels var last = rows[rows.length - 1]; var kc = z.dir < 0 ? cols - 1 - last.lastIndexOf('k') : last.indexOf('k'); g.shoe = { x: z.x + kc * p, y: floor - p, w: p * 3, h: p, puff: 0, smoke: [] }; g.z = null; } // The ground strike's after-effects, from the moment it lands (t in // ms). False once it is all over. var ZAP_AT = 4100, STONE_HOLD = 7000, STONE_FADE = 6000; function aftermath(g, t, dt) { var floor = h, p = w < 600 ? 2 : 4; var zw = ZOMBIE_TOP[0].length * p, zh = (ZOMBIE_TOP.length + ZOMBIE_LEGS[0].length) * p; scorch(g.x, floor, t); if (g.zapX !== undefined) scorch(g.zapX, floor, t - ZAP_AT); // The tombstone: lit by the strike, then a long fade var lit = t < STONE_HOLD ? 1 : Math.max(0, 1 - (t - STONE_HOLD) / STONE_FADE); if (lit > 0) drawTombstone(g, floor, p, lit * 0.95); // The zombie: up out of the ground, a sway, then off at a // shamble, until the second bolt var z = g.z; if (z && t > 900) { if (t < 2600) { var up = Math.min(1, (t - 900) / 1500); up = 1 - Math.pow(1 - up, 2); if (Math.random() < 0.35) { g.bits.push({ x: z.x + Math.random() * zw, y: floor - 2, vx: (Math.random() - 0.5) * 120, vy: -60 - Math.random() * 140, t: 0.8, s: p, c: Math.random() < 0.5 ? '#5a4630' : '#3d2f20' }); } zombieSprite(z.x, floor - zh * up + Math.sin(t / 60) * 1.5, p, 1, z.dir < 0, floor); } else if (t < 3300) { // Risen: sways, and looks about var look = Math.floor((t - 2600) / 300) % 2 ? -z.dir : z.dir; zombieSprite(z.x + Math.sin((t - 2600) / 110) * 2, floor - zh, p, 1, look < 0, floor + 1); } else { z.run = Math.min(z.run + 200 * dt, 120); z.x += z.dir * z.run * dt; z.frame = Math.floor(t / 180) % 2; zombieSprite(z.x, floor - zh + (z.frame ? 0 : -p), p, z.frame, z.dir < 0, floor + 1); if (t >= ZAP_AT) { // The second bolt finds it g.zapX = z.x + zw / 2; g.zap = boltTo(g.top, g.zapX, floor - zh * 0.55); thunder(g.zapX, true); blowUp(g, p, zw, zh, floor); } } } // The second bolt: one flash, and the bolt fading if (g.zap) { var zt = t - ZAP_AT; if (zt < 90) { ctx.fillStyle = 'rgba(205,190,255,0.14)'; ctx.fillRect(0, 0, w, h); } if (zt < 500) drawBolt(g.zap, 1 - zt / 500); else g.zap = null; } // The smoking shoe if (g.shoe) { var sh = g.shoe, fade = Math.max(0, Math.min(1, lit * 1.2)); ctx.globalAlpha = fade; ctx.fillStyle = ZOMBIE_COLOURS.k; ctx.fillRect(Math.round(sh.x), Math.round(sh.y), sh.w, sh.h); ctx.fillRect(Math.round(sh.x + (g.dir < 0 ? sh.w - p : 0)), Math.round(sh.y - p), p, p); sh.puff -= dt; if (sh.puff <= 0 && t < STONE_HOLD + STONE_FADE * 0.6) { sh.puff = 0.12; sh.smoke.push({ x: sh.x + sh.w / 2 + (Math.random() - 0.5) * p, y: sh.y - p, r: p * 0.6, t: 1.6 }); } for (var m = sh.smoke.length - 1; m >= 0; m--) { var sm = sh.smoke[m]; sm.t -= dt; sm.y -= 22 * dt; sm.x += Math.sin(sm.t * 4) * 6 * dt; sm.r += p * 1.2 * dt; if (sm.t <= 0) { sh.smoke.splice(m, 1); continue; } ctx.globalAlpha = fade * sm.t / 1.6 * 0.5; ctx.fillStyle = '#b8b4c4'; ctx.beginPath(); ctx.arc(sm.x, sm.y, sm.r, 0, Math.PI * 2); ctx.fill(); } ctx.globalAlpha = 1; } // Sparks, clods of earth and zombie, under gravity for (var i = g.bits.length - 1; i >= 0; i--) { var b = g.bits[i]; b.vy += 900 * dt; b.x += b.vx * dt; b.y += b.vy * dt; b.t -= dt; if (b.y > floor - b.s) { b.y = floor - b.s; b.vy *= -0.25; b.vx *= 0.6; } if (b.t <= 0) { g.bits.splice(i, 1); continue; } ctx.globalAlpha = Math.min(1, b.t * 2); ctx.fillStyle = b.c; ctx.fillRect(Math.round(b.x), Math.round(b.y), b.s, b.s); } ctx.globalAlpha = 1; return t < STONE_HOLD + STONE_FADE; } function strike() { if (document.hidden) { schedule(); return; } var top = (document.querySelector('header[role="banner"]') || { offsetHeight: 56 }).offsetHeight; st.strikes++; var ground = null, segs; if (st.strikes >= st.groundAt) { st.strikes = 0; st.groundAt = pickGround(); var zp = w < 600 ? 2 : 4, x = w * (0.25 + Math.random() * 0.5); var dir = x < w / 2 ? -1 : 1; ground = { x: x, top: top, bits: [], dir: dir, tilt: (Math.random() < 0.5 ? -1 : 1) * (0.12 + Math.random() * 0.08), z: { x: x - ZOMBIE_TOP[0].length * zp / 2, dir: dir, run: 0, frame: 1 } }; // The headstone, on the side the zombie runs from ground.stone = x - dir * zp * 24; ground.stoneArt = tombstoneArt(zp); segs = boltTo(top, x, h); for (var n = 0; n < 34; n++) { var a = -Math.PI * (0.1 + Math.random() * 0.8), v = 120 + Math.random() * 320, spark = n % 3 !== 0; ground.bits.push({ x: x, y: h - 2, vx: Math.cos(a) * v, vy: Math.sin(a) * v, t: spark ? 0.4 + Math.random() * 0.4 : 1.2, s: spark ? 2 : zp, c: spark ? (n % 2 ? '#ffd23f' : '#e8e0ff') : '#5a4630' }); } } else { segs = bolt(w * (0.1 + Math.random() * 0.8), top, h * (0.35 + Math.random() * 0.35), 2.4, 0, []); } // Thunder only for the ground strike (and the bolt that gets the // zombie): the others stay silent if (ground) thunder(ground.x, true); var t0 = performance.now(), clock = 0, last = 0; function draw(now) { // The clock runs on frames, so a hidden tab picks up where it // left off rather than jumping ahead var dt = last ? Math.min((now - last) / 1000, 0.05) : 0; last = now; clock += dt * 1000; var t = ground ? clock : now - t0; ctx.clearRect(0, 0, w, h); // Two flashes: a quick one, a gap, then the bolt with the // second; then the bolt fades var flash = t < 70 ? 0.16 : t < 150 ? 0 : t < 260 ? 0.11 * (1 - (t - 150) / 110) : 0; if (flash > 0) { ctx.fillStyle = 'rgba(205,190,255,' + flash.toFixed(3) + ')'; ctx.fillRect(0, 0, w, h); } var a = t < 150 ? 0 : t < 700 ? 1 - (t - 150) / 550 : 0; if (a > 0) drawBolt(segs, a); // Where it lands, a flash on the ground if (ground && t >= 150 && t < 600) { var gl = ctx.createRadialGradient(ground.x, h, 0, ground.x, h, 90); gl.addColorStop(0, 'rgba(255,240,200,' + (0.8 * (1 - (t - 150) / 450)).toFixed(3) + ')'); gl.addColorStop(1, 'rgba(179,139,255,0)'); ctx.fillStyle = gl; ctx.fillRect(ground.x - 90, h - 90, 180, 90); } var more = ground ? (t < 150 || aftermath(ground, t - 150, dt)) : t < 720; if (more) st.frame = requestAnimationFrame(draw); else { ctx.clearRect(0, 0, w, h); schedule(); } } st.frame = requestAnimationFrame(draw); } function schedule(first) { if (lightningState !== st) return; st.timer = setTimeout(strike, first ? 4000 + Math.random() * 6000 : 15000 + Math.random() * 25000); } size(); window.addEventListener('resize', function() { if (lightningState === st) size(); }); schedule(true); } // ── Arcade: a laser cannon takes shots at a passing saucer ── // Pixel sprites (this theme's own) drawn on one canvas over the page, in // the browser: the cannon slides along the bottom of the window, a saucer // crosses below the top bar now and then, and the cannon leads it and // fires, one shot at a time, so it hits some and misses some. Paused while // the tab is hidden; never for anyone whose system asks for reduced // motion. // // Now and then (one ship in ARCADE_BOSS_ONE_IN) the ship is the WPSD // mothership: bigger, slower, towing a WPSD banner. The cannon holds its // fire, charges, and sends up a guided rocket; the mothership goes up // like a firework whose sparks gather into "Pi-Star" over "Forever" // (the two lines one width), shine, and fall away; then the game goes on. var ARCADE_CANNON = [ '.....#.....', '....###....', '....###....', '.#########.', '###########', '###########', '###########', '##.#####.##', '###########', '.#.#.#.#.#.' ]; var ARCADE_SAUCER = [ '......####......', '...##########...', '..############..', '.##.##.##.##.##.', '################', '..###..##..###..', '...#........#...' ]; // The mothership: # hull, o lights (they blink), d its dome var ARCADE_MOTHERSHIP = [ '.........dddddd.........', '.......dddddddddd.......', '......dddddddddddd......', '...##################...', '.######################.', '##.o.##.o.##.o.##.o.##.#', '########################', '.######################.', '...###...######...###...', '....#......##......#....' ]; var ARCADE_ROCKET = [ '..#..', '.###.', '.###.', '.#o#.', '.###.', '.###.', '##.##', '#...#' ]; // One ship in this many (at random within) is the mothership var ARCADE_BOSS_ONE_IN = [14, 20]; // Each saucer is one of these bright colours, at random var ARCADE_SAUCER_COLOURS = [ '#ff3df0', '#ff2e63', '#ff5cb8', '#ff7a3d', '#ffa53d', '#ffd23f', '#f4ff3d', '#a6ff3d', '#39ff14', '#3dffa8', '#3df0ff', '#3da8ff', '#7b8bff', '#b05cff', '#e8a0ff', '#ffffff' ]; // The mothership's sounds: quiet (well under the credits page's music) var ARCADE_VOLUME = 0.07; var arcadeState = null; function arcade(on) { var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; if (!on || reduce) { if (arcadeState) { cancelAnimationFrame(arcadeState.frame); arcadeState.quiet(); arcadeState.canvas.remove(); arcadeState = null; } return; } if (arcadeState) return; var canvas = document.createElement('canvas'); canvas.id = 'ps-arcade'; canvas.setAttribute('aria-hidden', 'true'); document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); var w = 0, h = 0, px = 3, ratio = Math.min(window.devicePixelRatio || 1, 2); var st = { canvas: canvas, frame: 0, last: 0, clock: 0, cannon: { x: 0, aim: 0, err: 0 }, saucer: null, nextSaucer: 2 + Math.random() * 4, shot: null, cool: 0, bits: [], pops: [], ships: 0, bossAt: pickBoss(), boss: null, rocket: null, smoke: [], show: null, logoPts: null, logoFor: 0 }; arcadeState = st; function pickBoss() { var lo = ARCADE_BOSS_ONE_IN[0], hi = ARCADE_BOSS_ONE_IN[1]; return lo + Math.floor(Math.random() * (hi - lo + 1)); } // The reveal's type (Oxanium, which every page has): loaded now, so // it is ready when the canvas draws it var REVEAL_FONT = '800 100px Oxanium'; if (document.fonts && document.fonts.load) { document.fonts.load(REVEAL_FONT).then(function() { st.logoPts = null; }).catch(function() {}); } function size() { w = window.innerWidth; h = window.innerHeight; canvas.width = w * ratio; canvas.height = h * ratio; canvas.style.width = w + 'px'; canvas.style.height = h + 'px'; ctx.setTransform(ratio, 0, 0, ratio, 0, 0); px = w < 600 ? 2 : 3; if (!st.cannon.x) st.cannon.x = w / 2; st.logoPts = null; } function sprite(rows, x, y, colour, scale, lights) { var p = px * (scale || 1); for (var r = 0; r < rows.length; r++) { for (var c = 0; c < rows[r].length; c++) { var ch = rows[r].charAt(c); if (ch === '.') continue; ctx.fillStyle = ch === '#' ? colour : (lights && lights[ch]) || colour; ctx.fillRect(Math.round(x + c * p), Math.round(y + r * p), Math.ceil(p), Math.ceil(p)); } } } function topY() { // Just below the top bar var bar = document.querySelector('header[role="banner"], nav'); return (bar ? bar.getBoundingClientRect().bottom : 56) + 8; } // ── Sound: the mothership's siren while it crosses, and the kaboom ── // Made as they play (Web Audio). Browsers keep a page quiet until it // has been clicked or a key pressed; until then the show is silent. var sfx = { ctx: null, master: null, siren: null, noise: null }; function unlock() { if (!sfx.ctx) { var AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; try { sfx.ctx = new AC(); } catch (e) { return; } sfx.master = sfx.ctx.createGain(); sfx.master.gain.value = ARCADE_VOLUME; sfx.master.connect(sfx.ctx.destination); } sfx.unlocked = true; if (sfx.ctx.state === 'suspended') { var r = sfx.ctx.resume(); if (r && r.catch) r.catch(function() {}); } rest(1); } document.addEventListener('pointerdown', unlock, true); document.addEventListener('keydown', unlock, true); // Between sounds the sound sleeps (suspended), so the browser's // audio thread is not kept running in silence; never while the // siren sounds function rest(seconds) { clearTimeout(sfx.sleep); sfx.sleep = setTimeout(function() { if (sfx.siren) { rest(2); return; } if (sfx.ctx && sfx.ctx.state === 'running') { var r = sfx.ctx.suspend(); if (r && r.catch) r.catch(function() {}); } }, seconds * 1000); } // Whether the sound is awake now; asleep, it is woken (and ready // a moment later). The page may have been clicked before the theme // started: then the sound can start without another click function audible() { if (!sfx.ctx && pageActivated()) unlock(); if (!sfx.ctx) return false; if (sfx.ctx.state === 'running') return true; if (sfx.unlocked && !sfx.waking) { sfx.waking = true; var r = sfx.ctx.resume(); var done = function() { sfx.waking = false; }; if (r && r.then) r.then(done, done); else done(); } return false; } // Into the mix, placed left to right as x is across the window function outAt(x) { var ac = sfx.ctx; if (!ac.createStereoPanner) return sfx.master; var p = ac.createStereoPanner(); p.pan.value = Math.max(-0.8, Math.min(0.8, x / (w || 1) * 2 - 1)); p.connect(sfx.master); return p; } function sirenStart(x) { if (sfx.siren || !audible()) return; var ac = sfx.ctx, t = ac.currentTime; // A square wave swept up and down several times a second, // softened a little var o = ac.createOscillator(), lfo = ac.createOscillator(), depth = ac.createGain(); var f = ac.createBiquadFilter(), g = ac.createGain(), out = outAt(x); o.type = 'square'; o.frequency.value = 520; lfo.type = 'triangle'; lfo.frequency.value = 6.5; depth.gain.value = 190; lfo.connect(depth); depth.connect(o.frequency); f.type = 'lowpass'; f.frequency.value = 1700; g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(0.32, t + 0.25); o.connect(f); f.connect(g); g.connect(out); o.start(t); lfo.start(t); sfx.siren = { o: o, lfo: lfo, g: g, pan: out === sfx.master ? null : out }; clearTimeout(sfx.sleep); } function sirenMove(x) { var s = sfx.siren; if (s && s.pan) s.pan.pan.value = Math.max(-0.8, Math.min(0.8, x / (w || 1) * 2 - 1)); } function sirenStop() { var s = sfx.siren; if (!s) return; sfx.siren = null; var t = sfx.ctx.currentTime; if (s.g.gain.cancelAndHoldAtTime) s.g.gain.cancelAndHoldAtTime(t); s.g.gain.setTargetAtTime(0, t, 0.05); s.o.stop(t + 0.3); s.lfo.stop(t + 0.3); rest(1); } function kaboom(x) { if (!audible()) { // Asleep: as soon as it wakes if (sfx.ctx && sfx.unlocked) { var r = sfx.ctx.resume(); if (r && r.then) r.then(function() { if (sfx.ctx && sfx.ctx.state === 'running') kaboom(x); }, function() {}); } return; } clearTimeout(sfx.sleep); rest(2.5); var ac = sfx.ctx, t = ac.currentTime, len = 1.6, out = outAt(x); if (!sfx.noise) { sfx.noise = ac.createBuffer(1, Math.floor(ac.sampleRate * len), ac.sampleRate); var d = sfx.noise.getChannelData(0); for (var i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; } // The blast: noise, its top falling away as it dies var n = ac.createBufferSource(), f = ac.createBiquadFilter(), g = ac.createGain(); n.buffer = sfx.noise; f.type = 'lowpass'; f.frequency.setValueAtTime(4200, t); f.frequency.exponentialRampToValueAtTime(80, t + len); g.gain.setValueAtTime(1, t); g.gain.exponentialRampToValueAtTime(0.001, t + len); n.connect(f); f.connect(g); g.connect(out); n.start(t); n.stop(t + len); // The thump under it var o = ac.createOscillator(), og = ac.createGain(); o.type = 'sine'; o.frequency.setValueAtTime(120, t); o.frequency.exponentialRampToValueAtTime(30, t + 0.7); og.gain.setValueAtTime(0.9, t); og.gain.exponentialRampToValueAtTime(0.001, t + 0.8); o.connect(og); og.connect(out); o.start(t); o.stop(t + 0.85); // Crackle, as the sparks burst for (var k = 0; k < 8; k++) { var at = t + 0.3 + Math.random() * 1.2; var c = ac.createBufferSource(), cf = ac.createBiquadFilter(), cg = ac.createGain(); c.buffer = sfx.noise; cf.type = 'highpass'; cf.frequency.value = 2200 + Math.random() * 2500; cg.gain.setValueAtTime(0.35, at); cg.gain.exponentialRampToValueAtTime(0.001, at + 0.06); c.connect(cf); cf.connect(cg); cg.connect(out); c.start(at, Math.random() * (len - 0.2)); c.stop(at + 0.08); } } st.quiet = function() { document.removeEventListener('pointerdown', unlock, true); document.removeEventListener('keydown', unlock, true); sirenStop(); clearTimeout(sfx.sleep); if (sfx.ctx) { var c = sfx.ctx.close(); if (c && c.catch) c.catch(function() {}); } sfx.ctx = null; }; // ── The mothership and its banner ── var BOSS_SCALE = 1.6; // The mothership's hull cycles through the colours as it flies function bossHull() { return 'hsl(' + Math.round(st.clock * 80 % 360) + ',100%,60%)'; } function bossSize() { var p = px * BOSS_SCALE; return { w: ARCADE_MOTHERSHIP[0].length * p, h: ARCADE_MOTHERSHIP.length * p, p: p }; } var bannerArt = null; function bannerCanvas() { // WPSD on a cloth banner, drawn once: sliced into strips that // ripple as it is towed if (bannerArt) return bannerArt; var fh = Math.round(px * 7), bw = Math.round(fh * 4.2), bh = Math.round(fh * 1.5); var c = document.createElement('canvas'); c.width = bw; c.height = bh; var g = c.getContext('2d'); g.fillStyle = '#fff6d8'; g.fillRect(0, 0, bw, bh); g.fillStyle = '#e8d9a8'; for (var y = 0; y < bh; y += 4) g.fillRect(0, y, bw, 1); g.strokeStyle = '#b03a2e'; g.lineWidth = Math.max(2, px); g.strokeRect(g.lineWidth / 2, g.lineWidth / 2, bw - g.lineWidth, bh - g.lineWidth); g.fillStyle = '#b03a2e'; g.font = '900 ' + fh + 'px "Arial Black", Impact, system-ui, sans-serif'; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText('WPSD', bw / 2, bh / 2 + 1); bannerArt = c; return c; } function drawBanner(b, t) { var art = bannerCanvas(), bs = bossSize(); var dir = b.vx > 0 ? 1 : -1; // The tow-rope from the stern, sagging, to the banner's leading edge var sternX = dir > 0 ? b.x : b.x + bs.w, sternY = b.y + bs.h * 0.55; var gap = bs.w * 0.45; var bx = dir > 0 ? sternX - gap - art.width : sternX + gap; var by = sternY - art.height / 2 + Math.sin(t * 1.7) * 3; var leadX = dir > 0 ? bx + art.width : bx; ctx.strokeStyle = '#c9c9c9'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(sternX, sternY); ctx.quadraticCurveTo((sternX + leadX) / 2, Math.max(sternY, by + art.height / 2) + 10, leadX, by + art.height / 2); ctx.stroke(); // Rippling cloth: each strip's height follows a travelling wave, // more towards the trailing edge var strip = 3; for (var sx = 0; sx < art.width; sx += strip) { var fromLead = dir > 0 ? art.width - sx : sx; var amp = 2 + fromLead / art.width * px * 2.2; var off = Math.sin(t * 7 - fromLead * 0.06) * amp; var shade = 0.82 + 0.18 * Math.sin(t * 7 - fromLead * 0.06 + 1.3); ctx.globalAlpha = shade; ctx.drawImage(art, sx, 0, strip, art.height, bx + sx, by + off, strip + 0.5, art.height); } ctx.globalAlpha = 1; b.bannerAt = { x: bx, y: by, w: art.width, h: art.height }; } // ── The reveal: "Pi-Star" over "Forever", as points ── // Each line is sized to the same width (Forever, the shorter word, // a little taller), the pair centred on the window function logoPoints() { if (st.logoPts && st.logoFor === w) return st.logoPts; // About half the window (most of a phone's), 560px at most var tw = w < 600 ? w * 0.7 : Math.min(w * 0.5, 560); var lines = ['Pi-Star', 'Forever'], face = "Oxanium, 'Arial Black', system-ui, sans-serif"; var oc = document.createElement('canvas'), g = oc.getContext('2d'); var sizes = [], heights = [], gap = tw * 0.035, total = 0; for (var i = 0; i < lines.length; i++) { g.font = '800 100px ' + face; var size = 100 * tw / g.measureText(lines[i]).width; sizes.push(size); heights.push(size * 0.78); // cap height and a little: no descenders here total += heights[i] + (i ? gap : 0); } oc.width = Math.ceil(tw); oc.height = Math.ceil(total + 4); g.fillStyle = '#fff'; g.textAlign = 'center'; g.textBaseline = 'alphabetic'; var y = 0; for (var j = 0; j < lines.length; j++) { y += heights[j] + (j ? gap : 0); g.font = '800 ' + sizes[j] + 'px ' + face; g.fillText(lines[j], tw / 2, y); } var data = g.getImageData(0, 0, oc.width, oc.height).data; var step = Math.max(px + 1, Math.round(tw / 95)); var ox = (w - oc.width) / 2, oy = h * 0.45 - oc.height / 2, pts = []; for (var yy = step / 2; yy < oc.height; yy += step) { for (var x = step / 2; x < oc.width; x += step) { if (data[(Math.floor(yy) * oc.width + Math.floor(x)) * 4 + 3] > 120) { pts.push({ x: ox + x, y: oy + yy, f: x / oc.width }); } } } st.logoPts = { pts: pts, step: step }; st.logoFor = w; return st.logoPts; } // ── The firework ── var SPARK_COLOURS = ['#ff3df0', '#ffd23f', '#39ff14', '#3df0ff', '#ffffff', '#ff7a3d']; function explode(cx, cy) { var b = st.boss, bs = bossSize(), hull = bossHull(); var show = { t: 0, cx: cx, cy: cy, sparks: [], logo: [], debris: [], banner: null, ring: 0 }; // A shower of sparks for (var i = 0; i < 160; i++) { var a = Math.random() * Math.PI * 2, v = 80 + Math.random() * 320; show.sparks.push({ x: cx, y: cy, px: cx, py: cy, vx: Math.cos(a) * v, vy: Math.sin(a) * v, t: 0.9 + Math.random() * 0.9, c: SPARK_COLOURS[i % SPARK_COLOURS.length] }); } // The hull in pieces: each of its pixels, tumbling away for (var r = 0; r < ARCADE_MOTHERSHIP.length; r++) { for (var c = 0; c < ARCADE_MOTHERSHIP[r].length; c++) { if (ARCADE_MOTHERSHIP[r].charAt(c) === '.') continue; var dx = b.x + c * bs.p - cx, dy = b.y + r * bs.p - cy, d = Math.sqrt(dx * dx + dy * dy) || 1; var sp = 60 + Math.random() * 160; show.debris.push({ x: cx + dx, y: cy + dy, vx: dx / d * sp, vy: dy / d * sp - 40, t: 1.4 + Math.random() * 0.8, c: ARCADE_MOTHERSHIP[r].charAt(c) === 'd' ? '#9be7ff' : hull }); } } // The banner, its rope gone, flutters down if (b.bannerAt) { show.banner = { x: b.bannerAt.x, y: b.bannerAt.y, vx: b.vx * 0.4, vy: -30, rot: 0, vr: (Math.random() - 0.5) * 1.6, t: 0 }; } // The words: a spark for each of their points, flung out with // the rest, then drawn in to them var lp = logoPoints(); for (var k = 0; k < lp.pts.length; k++) { var q = lp.pts[k], ang = Math.random() * Math.PI * 2, vel = 120 + Math.random() * 260; show.logo.push({ x: cx, y: cy, vx: Math.cos(ang) * vel, vy: Math.sin(ang) * vel, tx: q.x, ty: q.y, f: q.f, delay: 0.25 + Math.random() * 0.35, tw: Math.random() * Math.PI * 2 }); } show.step = lp.step; st.show = show; st.boss = null; sirenStop(); kaboom(cx); st.pops.push({ x: cx, y: cy - 10, t: 1.6, n: 'WPSD DOWN!' }); } function stepShow(dt) { var s = st.show; s.t += dt; s.ring += dt; var g = 260; for (var i = s.sparks.length - 1; i >= 0; i--) { var p = s.sparks[i]; p.px = p.x; p.py = p.y; p.vx *= 0.985; p.vy = p.vy * 0.985 + g * 0.5 * dt; p.x += p.vx * dt; p.y += p.vy * dt; p.t -= dt; if (p.t <= 0) s.sparks.splice(i, 1); } for (var d = s.debris.length - 1; d >= 0; d--) { var q = s.debris[d]; q.vy += g * dt; q.x += q.vx * dt; q.y += q.vy * dt; q.t -= dt; if (q.t <= 0 || q.y > h + 10) s.debris.splice(d, 1); } if (s.banner) { var bn = s.banner; bn.t += dt; bn.vy = Math.min(bn.vy + 90 * dt, 70); bn.vx *= 0.99; bn.x += (bn.vx + Math.sin(bn.t * 2.3) * 25) * dt; bn.y += bn.vy * dt; bn.rot += bn.vr * dt; if (bn.y > h + 40 || bn.t > 5) s.banner = null; } // The logo's sparks: out with the burst, drawn in (a spring), held // shining, then let go to fall var release = 3.9; for (var j = 0; j < s.logo.length; j++) { var l = s.logo[j]; if (s.t < l.delay) { l.vx *= 0.96; l.vy *= 0.96; } else if (s.t < release) { var k = 9, damp = 5.2; l.vx += ((l.tx - l.x) * k - l.vx * damp) * dt; l.vy += ((l.ty - l.y) * k - l.vy * damp) * dt; } else { if (!l.fall) { l.fall = true; l.vx = (Math.random() - 0.5) * 40; l.vy = -Math.random() * 40; } l.vy += g * 0.6 * dt; } l.x += l.vx * dt; l.y += l.vy * dt; } if (s.t > 6) { st.show = null; st.nextSaucer = 3 + Math.random() * 4; } } function drawShow() { var s = st.show; // The flash, gone in a moment if (s.t < 0.3) { ctx.fillStyle = 'rgba(255,240,220,' + (0.32 * (1 - s.t / 0.3)) + ')'; ctx.fillRect(0, 0, w, h); } ctx.save(); ctx.globalCompositeOperation = 'lighter'; // The shockwave if (s.ring < 0.7) { ctx.strokeStyle = 'rgba(255,220,150,' + (0.7 - s.ring) + ')'; ctx.lineWidth = 3 + (0.7 - s.ring) * 6; ctx.beginPath(); ctx.arc(s.cx, s.cy, 20 + s.ring * 420, 0, Math.PI * 2); ctx.stroke(); } // Sparks, with a streak behind each for (var i = 0; i < s.sparks.length; i++) { var p = s.sparks[i]; ctx.globalAlpha = Math.min(1, p.t * 1.4); ctx.strokeStyle = p.c; ctx.lineWidth = px * 0.8; ctx.beginPath(); ctx.moveTo(p.px, p.py); ctx.lineTo(p.x, p.y); ctx.stroke(); } // The words, magenta to cyan, each point twinkling var fade = s.t < 4.3 ? 1 : Math.max(0, 1 - (s.t - 4.3) / 1.6); var dot = Math.max(px, s.step * 0.62); for (var j = 0; j < s.logo.length; j++) { var l = s.logo[j]; var hue = 300 - l.f * 120; var tw = 0.65 + 0.35 * Math.sin(s.t * 9 + l.tw); ctx.globalAlpha = fade * (s.t < l.delay ? 0.55 : tw); ctx.fillStyle = 'hsl(' + hue + ',100%,62%)'; ctx.fillRect(l.x - dot / 2, l.y - dot / 2, dot, dot); // a soft glow round each ctx.globalAlpha *= 0.22; ctx.fillRect(l.x - dot, l.y - dot, dot * 2, dot * 2); } ctx.restore(); ctx.globalAlpha = 1; // The hull's pieces, and the banner falling for (var d = 0; d < s.debris.length; d++) { var q = s.debris[d]; ctx.globalAlpha = Math.min(1, q.t); ctx.fillStyle = q.c; ctx.fillRect(Math.round(q.x), Math.round(q.y), px, px); } ctx.globalAlpha = 1; if (s.banner) { var art = bannerCanvas(), bn = s.banner; ctx.save(); ctx.globalAlpha = Math.max(0, 1 - bn.t / 5); ctx.translate(bn.x + art.width / 2, bn.y + art.height / 2); ctx.rotate(bn.rot); ctx.scale(1, 0.75 + 0.25 * Math.cos(bn.t * 4)); ctx.drawImage(art, -art.width / 2, -art.height / 2); ctx.restore(); } } // ── The rocket ── function launch(c, cw, cy) { st.rocket = { x: c.x + cw / 2, y: cy - 6, vx: 0, vy: -90, speed: 90, puff: 0 }; } function stepRocket(dt) { var r = st.rocket, b = st.boss; if (!b) { st.rocket = null; return; } var bs = bossSize(); var tx = b.x + bs.w / 2, ty = b.y + bs.h / 2; // Faster and faster, turning onto the mothership r.speed = Math.min(r.speed + 520 * dt, 560); var want = Math.atan2(ty - r.y, tx - r.x), have = Math.atan2(r.vy, r.vx); var turn = want - have; while (turn > Math.PI) turn -= Math.PI * 2; while (turn < -Math.PI) turn += Math.PI * 2; have += Math.max(-4 * dt, Math.min(4 * dt, turn)); r.vx = Math.cos(have) * r.speed; r.vy = Math.sin(have) * r.speed; r.x += r.vx * dt; r.y += r.vy * dt; // Smoke behind it r.puff -= dt; if (r.puff <= 0) { r.puff = 0.018; st.smoke.push({ x: r.x - Math.cos(have) * 12, y: r.y - Math.sin(have) * 12, r: 2, t: 0.9 }); } if (Math.abs(r.x - tx) < bs.w * 0.42 && Math.abs(r.y - ty) < bs.h * 0.6) { st.rocket = null; explode(tx, ty); } } function drawRocket() { var r = st.rocket; var ang = Math.atan2(r.vy, r.vx) + Math.PI / 2; ctx.save(); ctx.translate(r.x, r.y); ctx.rotate(ang); // The flame, flickering var fl = (6 + Math.random() * 7) * px / 3; ctx.fillStyle = '#ffd23f'; ctx.fillRect(-px, ARCADE_ROCKET.length * px / 2, px * 2, fl); ctx.fillStyle = '#ff7a3d'; ctx.fillRect(-px / 2, ARCADE_ROCKET.length * px / 2 + fl * 0.4, px, fl * 0.8); sprite(ARCADE_ROCKET, -ARCADE_ROCKET[0].length * px / 2, -ARCADE_ROCKET.length * px / 2, '#e8e8e8', 1, { o: '#ff3df0' }); ctx.restore(); } function step(dt) { st.clock += dt; var cw = ARCADE_CANNON[0].length * px, ch = ARCADE_CANNON.length * px; var sw = ARCADE_SAUCER[0].length * px, sh = ARCADE_SAUCER.length * px; var cy = h - ch - 6; var bs = bossSize(); // A saucer now and then, from either side; one ship in a few // is the mothership. None while the firework is on. if (!st.saucer && !st.boss && !st.show) { st.nextSaucer -= dt; if (st.nextSaucer <= 0) { var left = Math.random() < 0.5; st.ships++; if (st.ships >= st.bossAt) { st.ships = 0; st.bossAt = pickBoss(); var bspeed = 48 + Math.random() * 14; st.boss = { x: left ? -bs.w : w, y0: topY() + 6, y: topY() + 6, vx: left ? bspeed : -bspeed, charge: -1, fired: false }; bannerCanvas(); logoPoints(); } else { var speed = 70 + Math.random() * 60; // A colour of its own, never the last one's var colour; do { colour = ARCADE_SAUCER_COLOURS[Math.floor(Math.random() * ARCADE_SAUCER_COLOURS.length)]; } while (colour === st.lastColour); st.lastColour = colour; st.saucer = { x: left ? -sw : w, y: topY(), vx: left ? speed : -speed, colour: colour }; // How far off this pass the cannon aims: it misses some st.cannon.err = (Math.random() - 0.5) * (Math.random() < 0.6 ? 6 : 60); } } } else if (st.saucer) { var s = st.saucer; s.x += s.vx * dt; if (s.x < -sw - 4 || s.x > w + 4) { st.saucer = null; st.nextSaucer = 5 + Math.random() * 8; } } if (st.boss) { var bo = st.boss; bo.x += bo.vx * dt; bo.y = bo.y0 + Math.sin(st.clock * 2) * 4; // Gone without a rocket (a window too small to line up): it // just leaves if (!bo.fired && (bo.x < -bs.w * 2 - 10 || bo.x > w + bs.w + 10)) { st.boss = null; st.nextSaucer = 4; } } // The cannon leads the saucer (where it will be when the shot // gets there), goes under the mothership, or wanders when there // is none var c = st.cannon, target; if (st.boss) { target = st.boss.x + bs.w / 2 + st.boss.vx * 0.9 - cw / 2; } else if (st.saucer) { var flight = (cy - st.saucer.y) / 420; target = st.saucer.x + sw / 2 + st.saucer.vx * flight + c.err - cw / 2; } else { if (Math.abs(c.aim - c.x) < 2) c.aim = Math.random() * (w - cw); target = c.aim; } var max = (st.saucer || st.boss ? 150 : 45) * dt, d = target - c.x; if (!(st.boss && st.boss.charge >= 0)) c.x += Math.max(-max, Math.min(max, d)); c.x = Math.max(0, Math.min(w - cw, c.x)); // The mothership: once it is well on the screen and the cannon // is under it, charge, then the rocket if (st.boss && !st.boss.fired) { var bc = st.boss.x + bs.w / 2; if (st.boss.charge < 0 && Math.abs(d) < 8 && bc > w * 0.2 && bc < w * 0.8) st.boss.charge = 0; if (st.boss.charge >= 0) { st.boss.charge += dt; if (Math.random() < 0.9) { var a = Math.random() * Math.PI * 2, rr = 26 + Math.random() * 20; st.bits.push({ x: c.x + cw / 2 + Math.cos(a) * rr, y: cy + Math.sin(a) * rr, vx: -Math.cos(a) * rr * 2.6, vy: -Math.sin(a) * rr * 2.6, t: 0.35, k: 1 }); } if (st.boss.charge > 0.9) { st.boss.fired = true; launch(c, cw, cy); } } } if (st.rocket) stepRocket(dt); for (var m = st.smoke.length - 1; m >= 0; m--) { var sm = st.smoke[m]; sm.t -= dt; sm.r += 16 * dt; sm.y += 6 * dt; if (sm.t <= 0) st.smoke.splice(m, 1); } // Fire when lined up: one shot in the air at a time st.cool -= dt; if (st.saucer && !st.shot && st.cool <= 0 && Math.abs(d) < 4 && st.saucer.x > -sw / 2 && st.saucer.x < w - sw / 2) { st.shot = { x: c.x + cw / 2 - 1, y: cy - 10 }; st.cool = 0.4; } if (st.shot) { st.shot.y -= 420 * dt; var sc = st.saucer; if (sc && st.shot.x + 2 > sc.x && st.shot.x < sc.x + sw && st.shot.y < sc.y + sh && st.shot.y + 10 > sc.y) { // A hit: a burst of pixels and the points for (var i = 0; i < 26; i++) { var an = Math.random() * Math.PI * 2, v = 40 + Math.random() * 140; st.bits.push({ x: sc.x + sw / 2, y: sc.y + sh / 2, vx: Math.cos(an) * v, vy: Math.sin(an) * v, t: 0.6 + Math.random() * 0.5 }); } st.pops.push({ x: sc.x + sw / 2, y: sc.y, t: 1.2, n: [50, 100, 150, 300][Math.floor(Math.random() * 4)] }); st.saucer = null; st.shot = null; st.nextSaucer = 6 + Math.random() * 8; } else if (st.shot.y < -12) { st.shot = null; } } for (var b = st.bits.length - 1; b >= 0; b--) { var bit = st.bits[b]; bit.t -= dt; bit.x += bit.vx * dt; bit.y += bit.vy * dt; if (bit.t <= 0) st.bits.splice(b, 1); } for (var p = st.pops.length - 1; p >= 0; p--) { st.pops[p].t -= dt; st.pops[p].y -= 18 * dt; if (st.pops[p].t <= 0) st.pops.splice(p, 1); } if (st.show) stepShow(dt); return cy; } function draw(now) { if (!arcadeState) return; var dt = st.last ? Math.min((now - st.last) / 1000, 0.05) : 0; st.last = now; var cy = step(dt); ctx.clearRect(0, 0, w, h); if (st.saucer) sprite(ARCADE_SAUCER, st.saucer.x, st.saucer.y, st.saucer.colour); // The siren sounds while the mothership is in the window if (st.boss && st.boss.x + bossSize().w > 0 && st.boss.x < w) { sirenStart(st.boss.x + bossSize().w / 2); sirenMove(st.boss.x + bossSize().w / 2); } else { sirenStop(); } if (st.boss) { drawBanner(st.boss, st.clock); var blink = Math.floor(st.clock * 4) % 2; sprite(ARCADE_MOTHERSHIP, st.boss.x, st.boss.y, bossHull(), BOSS_SCALE, { o: blink ? '#ffd23f' : '#3df0ff', d: '#9be7ff' }); } for (var m = 0; m < st.smoke.length; m++) { var sm = st.smoke[m]; ctx.fillStyle = 'rgba(200,200,210,' + (sm.t * 0.35) + ')'; ctx.beginPath(); ctx.arc(sm.x, sm.y, sm.r, 0, Math.PI * 2); ctx.fill(); } if (st.rocket) drawRocket(); if (st.shot) { ctx.fillStyle = '#ffffff'; ctx.fillRect(Math.round(st.shot.x), Math.round(st.shot.y), 2, 10); } for (var i = 0; i < st.bits.length; i++) { ctx.fillStyle = st.bits[i].k ? '#3df0ff' : (i % 2 ? '#ffd23f' : '#ff3df0'); ctx.fillRect(Math.round(st.bits[i].x), Math.round(st.bits[i].y), px, px); } if (st.show) drawShow(); ctx.textAlign = 'center'; for (var p = 0; p < st.pops.length; p++) { var pop = st.pops[p], big = typeof pop.n === 'string'; ctx.font = 'bold ' + (px * (big ? 6 : 4)) + 'px monospace'; ctx.fillStyle = big ? 'rgba(255,210,63,' + Math.min(1, pop.t) + ')' : 'rgba(255,255,255,' + Math.min(1, pop.t) + ')'; ctx.fillText(String(pop.n), pop.x, pop.y); } // The cannon glows while it charges var charging = st.boss && st.boss.charge >= 0 && !st.boss.fired; sprite(ARCADE_CANNON, st.cannon.x, cy, charging && Math.floor(st.clock * 12) % 2 ? '#c8ffb8' : '#39ff14'); st.frame = requestAnimationFrame(draw); } size(); window.addEventListener('resize', function() { if (arcadeState === st) { size(); bannerArt = null; } }); document.addEventListener('visibilitychange', function() { if (arcadeState !== st) return; if (document.hidden) { cancelAnimationFrame(st.frame); sirenStop(); } else { st.last = 0; st.frame = requestAnimationFrame(draw); } }); st.frame = requestAnimationFrame(draw); } // Navigation toggle (mobile) function initNav() { var toggle = document.querySelector('.nav-toggle'); var menu = document.getElementById('nav-menu'); if (toggle && menu) { toggle.addEventListener('click', function() { var expanded = toggle.getAttribute('aria-expanded') === 'true'; toggle.setAttribute('aria-expanded', !expanded); menu.classList.toggle('open'); }); } } // --- Health polling --- var _healthTimer = null; var _prevAlerts = {}; // service → messageKey // Info alerts (why the hotspot rebooted) are news, not problems: each // shows once in a browser, remembered here (the newest few IDs) var SEEN_KEY = 'pistar-notices-seen'; function seenNotices() { try { var v = JSON.parse(localStorage.getItem(SEEN_KEY) || '[]'); return Array.isArray(v) ? v : []; } catch (e) { return []; } } function markNoticeSeen(id) { var seen = seenNotices().filter(function(s) { return s !== id; }); seen.push(id); try { localStorage.setItem(SEEN_KEY, JSON.stringify(seen.slice(-10))); } catch (e) {} } function startHealthPolling() { if (_healthTimer) return; pollHealth(); // immediate first poll _healthTimer = setInterval(pollHealth, 10000); } function pollHealth() { fetch('/api/supervisor/health') .then(function(r) { return r.ok ? r.json() : null; }) .then(function(data) { if (!data) return; processHealthAlerts(data.alerts || []); }) .catch(function() {}); // silent } // alertText fills an alert's {placeholders} (service name, details) // into its translated message. function alertText(a) { var raw = a.params || {}; // A count in the message: its plural form for that number // (".one", ".other"... in the page's language) var n = a.plural ? parseInt(raw[a.plural], 10) : NaN; var text = isNaN(n) ? i18n(a.messageKey, a.fallback) : i18nPlural(a.messageKey, n, a.fallback, a.fallback); var params = {}; Object.keys(raw).forEach(function(k) { params[k] = raw[k]; // A param that is itself translated, with its own // {placeholders} from the params ("DMR Network {n} ({name})") var key = a.paramKeys && a.paramKeys[k]; if (key) { var v = i18n(key, raw[k]); Object.keys(raw).forEach(function(p) { v = v.split('{' + p + '}').join(raw[p]); }); params[k] = v; } }); Object.keys(params).forEach(function(k) { text = text.split('{' + k + '}').join(params[k]); }); return text; } // Each alert is a card that stays until its cause clears: a service // that is down (error), cannot log in to its network, or has modem or // power trouble (warning). Cards have View Log (a service's), and What // to do when the manual has a section for it. A card whose alert has // cleared is removed. A service can have several cards (alert IDs). function processHealthAlerts(alerts) { var current = {}; for (var i = 0; i < alerts.length; i++) { var a = alerts[i]; var id = a.id || a.service; if (a.severity === 'info') { // Already up on this page: leave it until it is closed if (_prevAlerts[id]) { current[id] = _prevAlerts[id]; continue; } if (seenNotices().indexOf(id) !== -1) continue; markNoticeSeen(id); } var text = alertText(a); current[id] = a.messageKey + '|' + text; // New or changed alert? if (_prevAlerts[id] !== current[id]) { var actions = []; if (a.help) { (function(help) { // News (info) has more to read; a problem has what to do var helpLabel = a.severity === 'info' ? i18n('health.learnMore', 'Learn more') : i18n('health.whatToDo', 'What to do'); actions.push({ label: helpLabel, callback: function() { window.open('/manual#' + help, '_blank', 'noopener'); } }); })(a.help); } if (a.ignore) { // Dismiss it (an RF overlap with a neighbour): the // next health poll drops the card (function(id) { actions.push({ label: i18n('health.ignore', 'Ignore'), callback: function() { adminFetch('/admin/api/station/ignored', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: id }) }).then(function() { pollHealth(); }).catch(function() {}); } }); })(a.ignore); } if (a.dismiss) { // Dismiss it for every browser (why the hotspot // rebooted): the toast goes now, and the next health // poll no longer has it. A later reboot's shows. (function(id, url) { actions.push({ label: i18n('health.dismiss', 'Dismiss'), callback: function() { adminFetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: id }) }).then(function(r) { if (!r.ok) return; if (window.pistar && window.pistar.dismissServiceToast) window.pistar.dismissServiceToast(id); pollHealth(); }).catch(function() {}); } }); })(id, a.dismiss); } if (a.service && a.service !== 'system' && !a.noLog) { (function(svc) { actions.push({ label: i18n('health.viewLog', 'View Log'), callback: function() { showServiceLog(svc); } }); })(a.service); } if (window.pistar && window.pistar.toast) { window.pistar.toast(text, { type: a.severity === 'error' ? 'error' : (a.severity === 'info' ? 'info' : 'warning'), duration: 0, serviceKey: id, actions: actions }); } } } Object.keys(_prevAlerts).forEach(function(svc) { if (!current[svc] && window.pistar && window.pistar.dismissServiceToast) { window.pistar.dismissServiceToast(svc); } }); _prevAlerts = current; } function showServiceLog(service) { fetch('/admin/api/supervisor/log/' + encodeURIComponent(service), { headers: { 'X-Requested-With': 'XMLHttpRequest' } }) .then(function(r) { if (r.status === 401) { if (window.pistar && window.pistar.toast) { window.pistar.toast( i18n('health.loginRequired', 'Log in to view service logs'), { type: 'info', action: function() { window.location.href = '/login'; }, actionLabel: i18n('health.login', 'Log In') } ); } return null; } return r.ok ? r.json() : null; }) .then(function(data) { if (data) showLogOverlay(service, data.lines || []); }) .catch(function() {}); } function showLogOverlay(service, lines) { // Remove existing overlay var existing = document.querySelector('.log-overlay'); if (existing) existing.remove(); var overlay = document.createElement('div'); overlay.className = 'log-overlay'; var content = document.createElement('div'); content.className = 'log-overlay-content'; var header = document.createElement('div'); header.className = 'log-overlay-header'; var title = document.createElement('h3'); title.textContent = i18n('health.logTitle', 'Service Log') + ' — ' + service; header.appendChild(title); var closeBtn = document.createElement('button'); closeBtn.type = 'button'; closeBtn.className = 'log-overlay-close'; closeBtn.setAttribute('aria-label', 'Close'); closeBtn.textContent = '\u00D7'; closeBtn.addEventListener('click', function() { overlay.remove(); }); header.appendChild(closeBtn); content.appendChild(header); var body = document.createElement('div'); body.className = 'log-overlay-body'; var pre = document.createElement('pre'); if (lines.length === 0) { pre.textContent = '(no log output)'; } else { // Render each line, highlighting MMDVM/G4KLX error lines (E: prefix) for (var li = 0; li < lines.length; li++) { var span = document.createElement('span'); // Match "E: " anywhere in the line (timestamps may precede it) if (/\bE: /.test(lines[li])) { span.className = 'log-line-error'; } span.textContent = lines[li]; pre.appendChild(span); if (li < lines.length - 1) pre.appendChild(document.createTextNode('\n')); } } body.appendChild(pre); content.appendChild(body); overlay.appendChild(content); // Close on overlay background click overlay.addEventListener('click', function(e) { if (e.target === overlay) overlay.remove(); }); // Close on Escape var escHandler = function(e) { if (e.key === 'Escape') { overlay.remove(); document.removeEventListener('keydown', escHandler); } }; document.addEventListener('keydown', escHandler); document.body.appendChild(overlay); // Scroll to bottom body.scrollTop = body.scrollHeight; } // Feature visibility — hide disabled dashboard modules function applyFeatureVisibility(features) { for (var key in features) { var panel = document.getElementById('module-' + key); if (panel) { panel.style.display = features[key] ? '' : 'none'; } } } function loadFeatureVisibility() { fetch('/api/features') .then(function(r) { return r.ok ? r.json() : null; }) .then(function(features) { if (features) applyFeatureVisibility(features); }) .catch(function() {}); // silent — show all on error } // The top menu's Links item shows while the Link Manager is public // (no admin login needed); MCP announces changes over the WebSocket. function showLinksNav(isPublic) { document.querySelectorAll('.nav-links-item').forEach(function(li) { li.style.display = isPublic ? '' : 'none'; }); } function loadLinksAccess() { fetch('/api/links/access') .then(function(r) { return r.ok ? r.json() : null; }) .then(function(a) { if (a) showLinksNav(!!a.public); }) .catch(function() {}); } document.addEventListener('pistar:message', function(e) { if (e.detail && e.detail.type === 'linksAccess') showLinksNav(!!e.detail.public); }); // Init function init() { initNav(); connectWebSocket(); startHealthPolling(); loadFeatureVisibility(); loadLinksAccess(); // Restore theme from localStorage and sync picker snow(document.documentElement.getAttribute('data-theme') === 'christmas-dark'); xmasLights(document.documentElement.getAttribute('data-theme') === 'christmas-dark'); lightning(document.documentElement.getAttribute('data-theme') === 'halloween-dark'); arcade(document.documentElement.getAttribute('data-theme') === 'arcade-dark'); speakSpell(document.documentElement.getAttribute('data-theme') === 'speakspell-dark'); var savedTheme = null; try { savedTheme = localStorage.getItem('pistar-theme'); } catch (e) {} // A theme this version does not have (one since retired): the // default var picker = document.getElementById('theme-picker'); if (savedTheme && picker && !picker.querySelector('option[value="' + savedTheme.replace(/[^a-z0-9-]/gi, '') + '"]')) { savedTheme = 'default-light'; } if (savedTheme) { setTheme(savedTheme); } var themePicker = document.getElementById('theme-picker'); if (themePicker) { if (savedTheme) { themePicker.value = savedTheme; } themePicker.addEventListener('change', function() { setTheme(this.value); }); } // The theme picker's names are theme. if (themePicker) { Array.prototype.forEach.call(themePicker.options, function(o) { if (!o.hasAttribute('data-i18n')) o.setAttribute('data-i18n', 'theme.' + o.value); }); } applyTranslations(); initLanguage(); // After the strings are in: they are what gets typed setTimeout(function() { vtType(true, false); }, 150); woprEvents(); } // This build's version (pistar.js?v=...), for the cached files asked for var ASSET_V = (function() { var src = document.currentScript && document.currentScript.src; var m = src && /[?&]v=([^&]+)/.exec(src); return m ? m[1] : ''; })(); // ── Language ── // The page comes in the language the viewer picked (the pistar-lang // cookie), else the browser's, else English: the server chooses it. // The picker lists the languages there are packs for; picking one // keeps it (a year, this browser), Automatic follows the browser. var LANG_COOKIE = 'pistar-lang'; function pickedLanguage() { var m = /(?:^|;\s*)pistar-lang=([^;]*)/.exec(document.cookie); return m ? decodeURIComponent(m[1]) : ''; } function setLanguage(lang) { var secure = location.protocol === 'https:' ? '; Secure' : ''; if (lang) { document.cookie = LANG_COOKIE + '=' + encodeURIComponent(lang) + '; Path=/; Max-Age=31536000; SameSite=Lax' + secure; } else { document.cookie = LANG_COOKIE + '=; Path=/; Max-Age=0; SameSite=Lax' + secure; } location.reload(); } function initLanguage() { var picker = document.getElementById('lang-picker'); if (!picker) return; var v = ASSET_V ? '?v=' + encodeURIComponent(ASSET_V) : ''; fetch('/i18n/languages.json' + v) .then(function(r) { return r.ok ? r.json() : []; }) .catch(function() { return []; }) .then(function(available) { if (!available || !available.length) available = [{ code: 'en', name: 'English' }]; var picked = pickedLanguage(); picker.innerHTML = ''; var auto = document.createElement('option'); auto.value = ''; auto.setAttribute('data-i18n', 'lang.auto'); auto.textContent = i18n('lang.auto', 'Language (Auto)'); picker.appendChild(auto); available.forEach(function(l) { var o = document.createElement('option'); o.value = l.code; o.textContent = l.name; o.lang = l.code; picker.appendChild(o); }); picker.value = available.some(function(l) { return l.code === picked; }) ? picked : ''; picker.addEventListener('change', function() { setLanguage(this.value); }); // The compact view's label: the code of the language in // use (the page's, when it follows the browser) var wrap = picker.closest('.lang-select'); if (wrap) { var code = (picker.value || document.documentElement.lang || 'en').toUpperCase(); wrap.setAttribute('data-short', code); wrap.style.setProperty('--short-len', code.length); } }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } // Setup state — gates Advanced Configuration access var _landed = false; function setSetupComplete(complete) { _setupComplete = !!complete; // Admin opens on System (hardware first) until the hotspot is set // up; after that, on the everyday page, the Link Manager (unless // a page was asked for, or the user has moved on already) if (!_landed) { _landed = true; var onSystem = document.querySelector('.sidebar-link.active[href="#system"]'); var links = document.querySelector('.sidebar-link[href="#links"]'); if (_setupComplete && !window.location.hash && onSystem && links) links.click(); } var link = document.querySelector('.sidebar-link[href="#modes"]'); if (link) { if (_setupComplete) { link.classList.remove('disabled'); link.removeAttribute('aria-disabled'); } else { link.classList.add('disabled'); link.setAttribute('aria-disabled', 'true'); } } } function isSetupComplete() { return _setupComplete; } // waitForRestart shows a persistent toast and reloads the page after // a delay, used when MCP is about to restart itself (factory reset, // self-update, etc.). function waitForRestart(message) { if (window.pistar && window.pistar.toast) { window.pistar.toast(message || i18n('system.restarting', 'Restarting...'), { type: 'info', duration: 0 // stays until page reloads }); } setTimeout(function() { window.location.href = '/'; }, 5000); } // --- Power countdown pages --- // Self-contained: replaces entire page so they work after the server goes down. var _countdownCSS = [ 'body{margin:0;padding:0;display:flex;align-items:center;justify-content:center;', 'min-height:100vh;font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;', 'background:var(--ps-bg-primary,#ffffff);color:var(--ps-text-primary,#1a1a1a);text-align:center}', '.cd-wrap{max-width:28rem;padding:2rem}', '.cd-icon{font-size:4rem;margin-bottom:1rem}', '.cd-title{font-size:1.5rem;font-weight:600;margin-bottom:0.5rem}', '.cd-sub{font-size:1rem;color:var(--ps-text-secondary,#555);margin-bottom:2rem}', '.cd-timer{font-size:4rem;font-weight:700;font-variant-numeric:tabular-nums;', 'color:var(--ps-accent,#0066cc);margin-bottom:1rem}', '.cd-bar-track{width:100%;height:0.5rem;background:var(--ps-border,#ddd);border-radius:0.25rem;overflow:hidden;margin-bottom:2rem}', '.cd-bar{height:100%;background:var(--ps-accent,#0066cc);border-radius:0.25rem;', 'transition:width 1s linear}', '.cd-done{display:none;margin-top:1rem}', '.cd-done.visible{display:block}', '.cd-safe{font-size:1.25rem;font-weight:600;color:var(--ps-success,#28a745)}', '.cd-reconnect{font-size:1rem;color:var(--ps-text-secondary,#555)}', '.cd-spinner{display:inline-block;width:1.25rem;height:1.25rem;border:3px solid var(--ps-border,#ddd);', 'border-top-color:var(--ps-accent,#0066cc);border-radius:50%;animation:cd-spin 0.8s linear infinite;', 'vertical-align:middle;margin-right:0.5rem}', '@keyframes cd-spin{to{transform:rotate(360deg)}}', '@media(prefers-reduced-motion:reduce){.cd-bar{transition:none}.cd-spinner{animation:none}}' ].join(''); function _showCountdownPage(opts) { var doc = document; doc.title = opts.title; doc.documentElement.innerHTML = '' + '' + opts.title + '' + '' + '
' + '
' + opts.icon + '
' + '
' + opts.title + '
' + '
' + opts.subtitle + '
' + '
' + opts.seconds + '
' + '
' + '
' + opts.doneHTML + '
' + '
'; var remaining = opts.seconds; var total = opts.seconds; var secsEl = doc.getElementById('cd-secs'); var barEl = doc.getElementById('cd-bar'); var doneEl = doc.getElementById('cd-done'); var timer = setInterval(function() { remaining--; if (remaining <= 0) { clearInterval(timer); secsEl.textContent = '0'; barEl.style.width = '0%'; doneEl.classList.add('visible'); if (opts.onComplete) opts.onComplete(); return; } secsEl.textContent = remaining; barEl.style.width = ((remaining / total) * 100).toFixed(1) + '%'; }, 1000); } function showShutdownCountdown() { _showCountdownPage({ title: i18n('power.shutdown.title', 'Shutting Down'), subtitle: i18n('power.shutdown.wait', 'Please wait before removing power...'), icon: '\u23FB', seconds: 20, doneHTML: '
\u2714 ' + i18n('power.shutdown.safe', 'Safe to remove power') + '
', onComplete: null }); } // showRebootCountdown shows the reboot page, then reconnects. When the // hotspot comes back under a new name (newURL), the old address no // longer resolves and the certificate is new, so the page cannot poll // for it: it links to the new address and goes there after a while. function showRebootCountdown(newURL) { if (newURL) { var host = new URL(newURL).hostname; _showCountdownPage({ title: i18n('power.reboot.title', 'Rebooting'), subtitle: i18n('power.reboot.wait', 'The system is restarting...'), icon: '\u21BB', seconds: 45, doneHTML: '
' + i18n('power.reboot.newName', 'Pi-Star is coming back as') + ' ' + host + '
', onComplete: function() { setTimeout(function() { window.location.href = newURL; }, 20000); } }); return; } _showCountdownPage({ title: i18n('power.reboot.title', 'Rebooting'), subtitle: i18n('power.reboot.wait', 'The system is restarting...'), icon: '\u21BB', seconds: 45, doneHTML: '
' + i18n('power.reboot.reconnecting', 'Reconnecting...') + '
', onComplete: function() { var tries = 0; var maxTries = 30; var check = setInterval(function() { tries++; fetch('/', { method: 'HEAD', cache: 'no-store' }).then(function(r) { if (r.ok) { clearInterval(check); window.location.href = '/'; } }).catch(function() {}); if (tries >= maxTries) { clearInterval(check); var done = document.getElementById('cd-done'); if (done) { done.innerHTML = '
' + i18n('power.reboot.failed', 'Could not reconnect. Please refresh the page manually.') + '
'; } } }, 2000); } }); } // adminFetch wraps fetch() adding the X-Requested-With header required // by the CSRF protection middleware on admin API endpoints. function adminFetch(url, opts) { opts = opts || {}; opts.headers = opts.headers || {}; opts.headers['X-Requested-With'] = 'XMLHttpRequest'; return fetch(url, opts).then(function(r) { if (r.status === 401) { window.location.href = '/login'; return new Promise(function() {}); // never resolves — page is navigating } return r; }); } // ── Locked lists ───────────────────────────────────────────────── // A comma-separated setting (NXDNGateway's static TGs) whose locked // entries, always or while their service is enabled, come first and // cannot be removed. The user edits only their own entries; a hidden // input carries the full list, as the server writes it. function splitList(value) { return String(value || '').split(/[\s,]+/).filter(function(v) { return v !== ''; }); } function lockedListParts(value, locked, isEnabled) { var reserved = {}, fixed = [], extra = [], seen = {}; (locked || []).forEach(function(l) { reserved[l.value] = true; // Once each: a bridge's startup TG may be the always-locked Parrot (10) if ((!l.service || isEnabled(l.service)) && fixed.indexOf(l.value) === -1) fixed.push(l.value); }); splitList(value).forEach(function(v) { if (reserved[v] || seen[v]) return; seen[v] = true; extra.push(v); }); return { fixed: fixed, extra: extra }; } function escAttr(s) { return String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/'; html += ''; html += ''; html += ''; html += ''; return html; } // syncLockedLists rebuilds each widget's fixed part and full value, // e.g. after a service it depends on is toggled. With notify, a // change event fires on the hidden input when its value changes. function syncLockedLists(root, isEnabled, notify) { root.querySelectorAll('.locked-list').forEach(function(w) { var locked = []; try { locked = JSON.parse(w.getAttribute('data-locked')) || []; } catch (e) { /* keep empty */ } var hidden = w.querySelector('.locked-list-value'); var extra = w.querySelector('.locked-list-extra'); var parts = lockedListParts(extra.value, locked, isEnabled); var fixedInput = w.querySelector('.locked-list-fixed'); if (fixedInput) fixedInput.value = parts.fixed.join(','); if (w.classList.contains('tg-list')) { w.setAttribute('data-fixed', parts.fixed.join(',')); renderTGChips(w); } var full = parts.fixed.concat(parts.extra).join(','); if (hidden.value !== full) { hidden.value = full; if (notify) hidden.dispatchEvent(new Event('change', { bubbles: true })); } }); } function bindLockedLists(root, isEnabled) { bindTGLists(root, isEnabled); root.querySelectorAll('.locked-list:not(.tg-list) .locked-list-extra').forEach(function(extra) { extra.addEventListener('change', function() { var w = extra.closest('.locked-list'); var locked = []; try { locked = JSON.parse(w.getAttribute('data-locked')) || []; } catch (e) { /* keep empty */ } // Tidy what was typed: no spaces, no repeats, no locked entries extra.value = lockedListParts(extra.value, locked, isEnabled).extra.join(','); syncLockedLists(w.parentNode, isEnabled, true); }); }); } // ── Host pickers ───────────────────────────────────────────────── // Searchable drop-downs over a host list: NXDN or P25 talkgroups, YSF // reflectors and FCS rooms, or D-Star reflectors. The config holds the // ID (TG number, YSF number, FCS room, reflector name); the list shows // the name and country or type beside it. IDs not in the list can // still be typed in. var hostLists = {}; // A list longer than this is drawn this far, with a line saying how // many more there are (typing narrows it) var HOST_MAX_SHOWN = 3000; function hostList(source) { if (!hostLists[source]) { // Admin pages read the lists from the admin API; the public Link // Manager (/links) through the link API, under its access rule var base = window.location.pathname.indexOf('/admin') === 0 ? '/admin/api/hostfiles/hosts/' : '/api/links/hosts/'; var downloading = false; hostLists[source] = adminFetch(base + encodeURIComponent(source)) .then(function(r) { downloading = r.headers.get('X-Hostfiles-Downloading') === '1'; return r.ok ? r.json() : []; }) .then(function(list) { list = Array.isArray(list) ? list : []; var byId = {}; list.forEach(function(h) { byId[h.id] = h; }); // MCP is still downloading host files: ask again // shortly, so the list fills in when they are in if (downloading) setTimeout(function() { delete hostLists[source]; }, 2500); return { list: list, byId: byId, downloading: downloading }; }) .catch(function() { return { list: [], byId: {}, failed: true }; }); } return hostLists[source]; } function hostName(h) { if (!h) return ''; if (h.kind === 'parrot') return i18n('tg.parrot', 'Parrot'); if (h.kind === 'nxdn2dmr') return i18n('tg.nxdn2dmr', 'NXDN → DMR bridge'); // DMR masters: the network, and where it is if (h.address) return (h.name ? h.name + ' · ' : '') + h.address + ':' + h.port; // XLX reflectors: where, and the module linked by default if (h.module) return (h.name ? h.name + ' · ' : '') + i18n('xlx.module', 'Module') + ' ' + h.module; return h.name || ''; } // The tag beside a name: the country, else FCS or the D-Star type. function hostBadge(h) { if (!h) return ''; // One from the user's own hosts file (NXDN_Custom_Hosts.txt ...) if (h.custom) return i18n('hosts.custom', 'Custom'); if (h.country) return h.country; if (h.kind === 'fcs') return 'FCS'; if (/^(DCS|REF|XRF|XLX)$/.test(h.kind || '')) return h.kind; return ''; } // findHost looks an ID (or a YSF reflector name, as older configs // hold) up in a loaded list. function findHost(data, value) { var v = String(value || '').trim(); if (!v) return null; if (data.byId[v]) return data.byId[v]; var up = v.toUpperCase(); if (data.byId[up]) return data.byId[up]; for (var i = 0; i < data.list.length; i++) { var h = data.list[i]; var n = (h.name || '').toUpperCase(); if ((h.value || '').toUpperCase() === up || n === up || n.indexOf(up + ' \u2013 ') === 0) return h; } return null; } // What a config holds for an entry: its value where the software // takes something other than the ID (YSFGateway's Startup takes the // reflector's name), else the ID. function hostValue(h) { return String(h.value || h.id); } // acceptTyped returns the ID to store for text typed into a picker, // or null if it is not one this list could hold. function acceptTyped(source, typed, data) { var t = String(typed || '').trim(); if (!t) return null; var h = findHost(data, t); if (h) return hostValue(h); switch (source) { case 'nxdn': case 'p25': return /^\d{1,5}$/.test(t) && +t >= 1 && +t <= 65535 ? String(+t) : null; case 'ysf': // A YSF reflector is held by its name, so only listed ones // (found above); an FCS room by its code return /^FCS\d{5}$/i.test(t) ? t.toUpperCase() : null; case 'dstar': return /^(DCS|REF|XRF|XLX)[0-9A-Z]{3}$/i.test(t) ? t.toUpperCase() : null; case 'dmr': // A master not in the list, as address:port var m = /^([A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\]):(\d{1,5})$/.exec(t); return m && +m[2] >= 1 && +m[2] <= 65535 ? t : null; case 'xlx': return /^\d{3}$/.test(t) ? t : null; } return null; } function hostMatches(data, query) { var q = String(query || '').trim().toLowerCase(); if (!q) return data.list.slice(); var starts = [], contains = []; data.list.forEach(function(h) { var id = String(h.id).toLowerCase(); if (id.indexOf(q) === 0) { starts.push(h); return; } var name = hostName(h).toLowerCase(); var value = String(h.value || '').toLowerCase(); if (id.indexOf(q) !== -1 || name.indexOf(q) !== -1 || value.indexOf(q) !== -1 || hostBadge(h).toLowerCase() === q) { contains.push(h); } }); return starts.concat(contains); } function hostItemHTML(h, active, chosen) { var name = hostName(h), badge = hostBadge(h); // IDs too long for the number column (DMR masters are named) go on a line // of their own, the name below. var stacked = String(h.id).length > 8; return '
' + '' + escHTML(h.id) + '' + '' + escHTML(name || (badge ? '' : '—')) + '' + (badge ? '' + escHTML(badge) + '' : '') + '
'; } function escHTML(s) { return String(s).replace(/&/g, '&').replace(//g, '>'); } // showActive scrolls the list (only the list, never the page) to its // highlighted entry: into the middle when the list has just opened. function showActive(dropdown, middle) { var a = dropdown.querySelector('.tg-item-active'); if (!a) return; var d = dropdown.getBoundingClientRect(), r = a.getBoundingClientRect(); var top = r.top - d.top + dropdown.scrollTop; if (middle) dropdown.scrollTop = top - (dropdown.clientHeight - r.height) / 2; else if (r.top < d.top) dropdown.scrollTop = top; else if (r.bottom > d.bottom) dropdown.scrollTop = top - dropdown.clientHeight + r.height; } // listKeys: the keys a drop-down list answers besides typing. Down // (or Alt+Down) opens it; open, Up/Down, Home/End and Page Up/Down // move the highlight. True when the key was used. function listKeys(e, dropdown, active, highlight, openList) { var items = dropdown.hidden ? 0 : dropdown.querySelectorAll('.tg-item').length; var page = Math.max(1, Math.floor(dropdown.clientHeight / 36) - 1); var to = null; switch (e.key) { case 'ArrowDown': e.preventDefault(); if (dropdown.hidden) { openList(); return true; } to = active + 1; break; case 'ArrowUp': if (items) { e.preventDefault(); to = active - 1; } break; case 'PageDown': if (items) { e.preventDefault(); to = active + page; } break; case 'PageUp': if (items) { e.preventDefault(); to = active - page; } break; // Home/End move the cursor in the box until the list is open case 'Home': if (items) { e.preventDefault(); to = 0; } break; case 'End': if (items) { e.preventDefault(); to = items - 1; } break; } if (to === null) return false; highlight(to); return true; } // The search box shared by every picker: an input with a drop-down // arrow and the list below it. function hostSearchBox(o) { return '
' + '' + '' + '' + '
'; } // bindHostSearch wires a search box: onPick(id) when an entry is // chosen (or a valid ID typed and Enter pressed), onBlur on leaving. // current(), when given, is the value chosen now. It works like a // drop-down as well as a search: opened, it shows the whole list with // the current entry highlighted; typing narrows it. function bindHostSearch(box, source, onPick, onBlur, current) { var input = box.querySelector('.tg-search'); var dropdown = box.querySelector('.tg-dropdown'); if (!input || input.disabled) return; var shown = [], active = -1, loaded = { list: [], byId: {} }; var filtering = false, retry = null, seq = 0; function statusRow(text) { dropdown.innerHTML = '
' + '' + escHTML(text) + '
'; } // browse: the whole list (just opened); else what is typed function render(browse) { if (browse) filtering = false; clearTimeout(retry); var mine = ++seq, settled = false; // A list still being fetched says so, rather than nothing setTimeout(function() { if (!settled && mine === seq) { statusRow(i18n('tg.loading', 'Loading the list…')); open(); } }, 150); hostList(source).then(function(data) { settled = true; if (mine !== seq) return; loaded = data; if (!data.list.length && data.downloading) { // MCP is downloading the host files: say so, and look // again until they are in (if the list is still open) shown = []; active = -1; statusRow(i18n('tg.downloading', 'Downloading the host list… it will appear here when it arrives')); open(); retry = setTimeout(function() { if (!dropdown.hidden) render(!filtering); }, 3000); return; } var all = hostMatches(data, filtering ? input.value : ''); shown = all.slice(0, HOST_MAX_SHOWN); active = shown.length ? 0 : -1; var cur = !filtering && current ? String(current() || '') : ''; if (cur) { var ch = findHost(data, cur); var at = ch ? shown.indexOf(ch) : -1; if (at >= 0) active = at; } var html = ''; shown.forEach(function(h, i) { html += hostItemHTML(h, i === active, cur && hostValue(h) === cur); }); if (!shown.length && !data.list.length && !filtering) { html = '
' + escHTML(data.failed ? i18n('tg.loadFailed', 'Could not load the list: check the connection and try again') : i18n('tg.emptyList', 'The list is empty: type an ID and press Enter to use it')) + '
'; } else if (!shown.length) { html = '
' + escHTML(acceptTyped(source, input.value, data) ? i18n('tg.useTyped', 'Not in the list: press Enter to use it') : i18n('tg.noMatch', 'No matches')) + '
'; } else if (all.length > shown.length) { html += '
' + escHTML(i18nPlural('tg.more', all.length - shown.length, '{n} more: keep typing to narrow the list', '{n} more: keep typing to narrow the list')) + '
'; } dropdown.innerHTML = html; open(); showActive(dropdown, !filtering); }); } function open() { dropdown.hidden = false; placeDropdown(box, dropdown); input.setAttribute('aria-expanded', 'true'); box.classList.add('tg-open'); } function close() { seq++; clearTimeout(retry); dropdown.hidden = true; input.setAttribute('aria-expanded', 'false'); box.classList.remove('tg-open'); } function highlight(i) { var items = dropdown.querySelectorAll('.tg-item'); if (!items.length) return; active = Math.max(0, Math.min(i, items.length - 1)); items.forEach(function(el, n) { el.classList.toggle('tg-item-active', n === active); }); showActive(dropdown, false); } function pick(id) { close(); onPick(String(id)); } input.addEventListener('focus', function() { input.select(); render(true); }); // Clicking the box while focused re-opens the list input.addEventListener('click', function() { if (dropdown.hidden) render(true); }); // The arrow opens and shuts it, as a drop-down's does var toggle = box.querySelector('.tg-toggle'); if (toggle) { toggle.addEventListener('mousedown', function(e) { e.preventDefault(); if (document.activeElement !== input) { input.focus(); return; } if (dropdown.hidden) render(true); else close(); }); } input.addEventListener('input', function() { filtering = true; render(false); }); input.addEventListener('blur', function() { close(); if (onBlur) onBlur(loaded); }); input.addEventListener('keydown', function(e) { if (listKeys(e, dropdown, active, highlight, function() { render(true); })) return; if (e.key === 'Escape') { // Back to what was chosen, as a drop-down does if (!dropdown.hidden) e.preventDefault(); close(); if (current) { input.value = String(current() || ''); filtering = false; input.select(); } } else if (e.key === 'Enter') { e.preventDefault(); // The highlighted entry, unless something was typed that // it does not start with and that is itself a valid ID. var typed = input.value.trim(); var hl = active >= 0 ? shown[active] : null; // Nothing typed since the list opened: the highlighted one var own = filtering ? acceptTyped(source, typed, loaded) : null; if (hl && (!own || String(hl.id).toLowerCase().indexOf(typed.toLowerCase()) === 0)) { pick(hostValue(hl)); } else if (own) { pick(own); } } }); dropdown.addEventListener('mousedown', function(e) { var item = e.target.closest('.tg-item'); if (item) { e.preventDefault(); pick(item.getAttribute('data-host')); } }); } // renderHostPicker: one entry from list o.listSource. hiddenAttrs // names the hidden input that carries the ID. function renderHostPicker(o) { return '
' + '' + hostSearchBox({ id: o.id, value: o.value, disabled: o.disabled, placeholder: o.placeholder || i18n('tg.search', 'Search by number or name') }) + '' + '
'; } function bindHostPickers(root) { root.querySelectorAll('.tg-picker:not(.tg-adder)').forEach(function(picker) { if (picker.getAttribute('data-bound')) return; picker.setAttribute('data-bound', '1'); var source = picker.getAttribute('data-list-source'); var hidden = picker.querySelector('.tg-value'); var input = picker.querySelector('.tg-search'); var meta = picker.querySelector('.tg-meta'); function set(id) { if (hidden.value !== id) { hidden.value = id; hidden.dispatchEvent(new Event('change', { bubbles: true })); } } function show() { input.value = hidden.value; hostList(source).then(function(data) { var h = findHost(data, hidden.value); var text = hostName(h), badge = hostBadge(h); if (text && badge) text += ' · ' + badge; else if (!text) text = badge; meta.textContent = text; meta.hidden = !text; }); } picker._pistarShow = show; // re-run when host lists arrive bindHostSearch(picker.querySelector('.tg-box'), source, function(id) { set(id); show(); input.blur(); }, function(data) { // Leaving without picking: keep a valid typed ID, else go back var own = input.value.trim() !== hidden.value ? acceptTyped(source, input.value, data) : null; if (own) set(own); show(); }, function() { return hidden.value; }); show(); }); bindReflectorPickers(root); } // ── D-Star reflector picker: reflector name + module (A-Z) ────── // The config holds "XLX672 E"; hiddenAttrs names the hidden input // carrying that. function renderReflectorPicker(o) { var name = '', module = '', v = String(o.value || ''); var sp = v.lastIndexOf(' '); if (sp > 0 && sp === v.length - 2) { name = v.substring(0, sp); module = v.substring(sp + 1).toUpperCase(); } else { name = v; } var html = '
'; html += ''; html += renderHostPicker({ id: o.id, value: name, listSource: 'dstar', disabled: o.disabled, placeholder: i18n('config.reflector.placeholder', 'Search reflectors') }); html += '
'; return html; } function bindReflectorPickers(root) { root.querySelectorAll('.reflector-picker').forEach(function(rp) { if (rp.getAttribute('data-bound')) return; rp.setAttribute('data-bound', '1'); var combined = rp.querySelector('.reflector-value'); var name = rp.querySelector('.tg-value'); var module = rp.querySelector('.reflector-module'); function update(e) { if (e) e.stopPropagation(); var v = name.value ? (module.value ? name.value + ' ' + module.value : name.value) : ''; if (combined.value !== v) { combined.value = v; combined.dispatchEvent(new Event('change', { bubbles: true })); } } name.addEventListener('change', update); module.addEventListener('change', update); }); } // A talkgroup locked list: the list as tags, the locked ones without // a remove button, and a search box to add more. function renderTGList(o) { var parts = lockedListParts(o.value, o.locked, o.isEnabled); var html = '
'; html += ''; html += ''; html += '
'; if (!o.disabled) { html += '
' + hostSearchBox({ id: o.id, placeholder: i18n('tg.add', 'Add a talkgroup: search by number or name') }) + '
'; } html += '
'; return html; } function renderTGChips(w) { var source = w.getAttribute('data-list-source'); var fixed = splitList(w.getAttribute('data-fixed')); var extra = splitList(w.querySelector('.locked-list-extra').value); var editable = !w.getAttribute('data-disabled'); hostList(source).then(function(data) { var html = ''; function chip(id, locked) { var name = hostName(data.byId[id]); html += '' + '' + escHTML(id) + '' + (name ? '' + escHTML(name) + '' : ''); if (!locked && editable) { html += ''; } html += ''; } fixed.forEach(function(id) { chip(id, true); }); extra.forEach(function(id) { chip(id, false); }); w.querySelector('.tg-chips').innerHTML = html; }); } function bindTGLists(root, isEnabled) { root.querySelectorAll('.tg-list').forEach(function(w) { var extra = w.querySelector('.locked-list-extra'); var setExtra = function(list) { extra.value = list.join(','); syncLockedLists(w.parentNode, isEnabled, true); }; w.querySelector('.tg-chips').addEventListener('click', function(e) { var btn = e.target.closest('.tg-chip-remove'); if (!btn) return; var id = btn.getAttribute('data-tg'); setExtra(splitList(extra.value).filter(function(v) { return v !== id; })); }); var adder = w.querySelector('.tg-adder'); if (adder) { var input = adder.querySelector('.tg-search'); bindHostSearch(adder.querySelector('.tg-box'), w.getAttribute('data-list-source'), function(id) { var list = splitList(extra.value); var fixed = splitList(w.getAttribute('data-fixed')); if (list.indexOf(id) === -1 && fixed.indexOf(id) === -1) list.push(id); input.value = ''; setExtra(list); }, function() { input.value = ''; }); } renderTGChips(w); }); } // ── Station clock ──────────────────────────────────────────────── // Times on the dashboard are the station's: its timezone and its // 12/24-hour choice (Radio Setup, Location), from modem_config. var station = { timezone: '', dateFormat: 'dmy', timeFormat: '24', tempUnit: 'C' }; document.addEventListener('pistar:message', function(e) { var msg = e.detail; if (msg && msg.type === 'modem_config' && msg.config) { station.timezone = msg.config.timezone || ''; station.dateFormat = msg.config.dateFormat || 'dmy'; station.timeFormat = msg.config.timeFormat || '24'; station.tempUnit = msg.config.tempUnit === 'F' ? 'F' : 'C'; document.dispatchEvent(new CustomEvent('pistar:clockformat')); } }); // formatTemperature is a temperature (degrees Celsius, as the system // gives it) in the station's unit (Radio Setup: Celsius, Fahrenheit, // or the callsign's country's), to a tenth: "48.3°C", "118.9°F". function formatTemperature(celsius) { var c = parseFloat(celsius); if (isNaN(c)) return ''; if (station.tempUnit === 'F') return (c * 9 / 5 + 32).toFixed(1) + '\u00b0F'; return c.toFixed(1) + '\u00b0C'; } function clockParts(ts, withDate) { var d = new Date(ts); if (isNaN(d.getTime())) return null; var opts = { hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: station.timeFormat === '12' ? 'h12' : 'h23' }; if (withDate) { opts.day = '2-digit'; opts.month = '2-digit'; opts.year = 'numeric'; } if (station.timezone) opts.timeZone = station.timezone; var parts = {}; try { new Intl.DateTimeFormat('en-GB', opts).formatToParts(d).forEach(function(p) { parts[p.type] = p.value; }); } catch (e) { delete opts.timeZone; // unknown to this browser: its own zone new Intl.DateTimeFormat('en-GB', opts).formatToParts(d).forEach(function(p) { parts[p.type] = p.value; }); } return parts; } // formatTime: "14:05:09" (24-hour, leading zero) or "2:05:09 PM" // (12-hour, none), as on the displays function formatTime(ts) { var p = clockParts(ts, false); if (!p) return ''; if (station.timeFormat === '12') { return String(parseInt(p.hour, 10)) + ':' + p.minute + ':' + p.second + ' ' + String(p.dayPeriod || '').toUpperCase(); } return p.hour + ':' + p.minute + ':' + p.second; } // formatDate: "16/11/26" or "11/16/26", as on the displays function formatDate(ts) { var p = clockParts(ts, true); if (!p) return ''; var yy = String(p.year).slice(-2); return station.dateFormat === 'mdy' ? p.month + '/' + p.day + '/' + yy : p.day + '/' + p.month + '/' + yy; } // formatDay: the day of the week in the page's language and the date, // on the station's clock ("Thu 20/11/26", "Do 20/11/26") function formatDay(ts) { var d = new Date(ts); if (isNaN(d.getTime())) return ''; var opts = { weekday: 'short' }, lang = document.documentElement.lang || 'en', wd = ''; if (station.timezone) opts.timeZone = station.timezone; try { wd = new Intl.DateTimeFormat(lang, opts).format(d); } catch (e) { delete opts.timeZone; try { wd = new Intl.DateTimeFormat(lang, opts).format(d); } catch (e2) { wd = ''; } } return (wd ? wd + ' ' : '') + formatDate(ts); } // timezones lists the IANA zones this browser knows, with current // included even if it does not. function timezones(current) { var zones = []; if (typeof Intl !== 'undefined' && Intl.supportedValuesOf) { try { zones = Intl.supportedValuesOf('timeZone').slice(); } catch (e) { /* fall through */ } } if (!zones.length) { zones = ['UTC', 'Europe/London', 'Europe/Paris', 'Europe/Berlin', 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles', 'Asia/Tokyo', 'Australia/Sydney', 'Pacific/Auckland']; } if (zones.indexOf('UTC') === -1) zones.unshift('UTC'); if (current && zones.indexOf(current) === -1) zones.push(current); return zones; } // ── ID + ESSID ─────────────────────────────────────────────────── // A station value (DMR ID, callsign), fixed, beside a select for an // optional ESSID of o.digits digits (two: 01-99, one: 0-9); a hidden // input carries the combined value. function renderIdEssid(o) { var digits = o.digits || 2; var base = String(o.base || '').toUpperCase(); var cur = String(o.value || '').toUpperCase(); var essid = (base && cur.indexOf(base) === 0 && cur.length === base.length + digits) ? cur.substring(base.length) : ''; var html = '
'; html += ''; html += ''; html += '
'; return html; } function bindIdEssid(root) { root.querySelectorAll('.id-essid-select').forEach(function(sel) { sel.addEventListener('change', function() { var hidden = sel.closest('.id-essid').querySelector('.id-essid-value'); hidden.value = sel.getAttribute('data-base') + sel.value; hidden.dispatchEvent(new Event('change', { bubbles: true })); }); }); } // ── Searchable selects ─────────────────────────────────────────── // Every stays (hidden) and holds the value, so code // reading it, and its change events, work as before. function bindSearchableSelects(root) { root.querySelectorAll('select').forEach(function(sel) { if (sel.getAttribute('data-searchable') || sel.multiple || sel.size > 1) return; sel.setAttribute('data-searchable', '1'); var box = document.createElement('div'); box.className = 'tg-box ss-box'; sel.parentNode.insertBefore(box, sel); box.appendChild(sel); sel.classList.add('ss-native'); sel.tabIndex = -1; sel.setAttribute('aria-hidden', 'true'); box.insertAdjacentHTML('beforeend', '' + '' + ''); var input = box.querySelector('.ss-search'); var toggle = box.querySelector('.tg-toggle'); var dropdown = box.querySelector('.tg-dropdown'); var shown = [], active = -1; // The field's label names the search box, and focuses it if (sel.id) { var lbl = root.querySelector('label[for="' + sel.id + '"]'); if (lbl) { input.setAttribute('aria-label', lbl.textContent.trim()); lbl.addEventListener('click', function(e) { e.preventDefault(); input.focus(); }); } } function optText(o) { return (o.textContent || o.value || '').trim(); } function sync() { var o = sel.options[sel.selectedIndex]; input.value = o ? optText(o) : ''; input.disabled = toggle.disabled = sel.disabled; } function open() { dropdown.hidden = false; placeDropdown(box, dropdown); input.setAttribute('aria-expanded', 'true'); box.classList.add('tg-open'); } function close() { dropdown.hidden = true; input.setAttribute('aria-expanded', 'false'); box.classList.remove('tg-open'); } function render(all) { var q = all ? '' : input.value.trim().toLowerCase(); var starts = [], contains = []; Array.prototype.forEach.call(sel.options, function(o) { if (o.disabled || o.hidden) return; var t = optText(o).toLowerCase(), v = String(o.value).toLowerCase(); if (!q || t.indexOf(q) === 0 || v.indexOf(q) === 0) starts.push(o); else if (t.indexOf(q) !== -1) contains.push(o); }); shown = starts.concat(contains); active = -1; shown.forEach(function(o, i) { if (active < 0 && (q ? i === 0 : o.selected)) active = i; }); if (active < 0 && shown.length) active = 0; var html = ''; shown.forEach(function(o, i) { html += '
' + escHTML(optText(o)) + '
'; }); dropdown.innerHTML = html || '
' + escHTML(i18n('tg.noMatch', 'No matches')) + '
'; open(); showActive(dropdown, !q); } function highlight(i) { var items = dropdown.querySelectorAll('.tg-item'); if (!items.length) return; active = Math.max(0, Math.min(i, items.length - 1)); items.forEach(function(el, n) { el.classList.toggle('tg-item-active', n === active); }); showActive(dropdown, false); } function pick(o) { close(); if (o && sel.value !== o.value) { sel.value = o.value; sel.dispatchEvent(new Event('change', { bubbles: true })); } sync(); input.blur(); } input.addEventListener('focus', function() { input.select(); render(true); }); input.addEventListener('click', function() { if (dropdown.hidden) render(true); }); input.addEventListener('input', function() { render(false); }); input.addEventListener('blur', function() { close(); sync(); }); input.addEventListener('keydown', function(e) { if (listKeys(e, dropdown, active, highlight, function() { render(true); })) return; if (e.key === 'Escape') { if (!dropdown.hidden) e.preventDefault(); close(); sync(); input.select(); } else if (e.key === 'Enter') { e.preventDefault(); if (active >= 0) pick(shown[active]); } }); toggle.addEventListener('mousedown', function(e) { e.preventDefault(); if (document.activeElement !== input) { input.focus(); return; } if (dropdown.hidden) render(true); else close(); }); dropdown.addEventListener('mousedown', function(e) { var item = e.target.closest('.tg-item'); if (item) { e.preventDefault(); pick(shown[+item.getAttribute('data-i')]); } }); // Follow changes made elsewhere (other code, a form reset) sel.addEventListener('change', sync); if (sel.form) sel.form.addEventListener('reset', function() { setTimeout(sync, 0); }); sync(); }); } // ── DMR network Options: hidden while the master is BrandMeister ── // A field rendered in an element with data-options-for="" // shows only while that master is not a BrandMeister one (BM takes // no Options). The master's value is in the input named, or // quick-keyed, by that key. function bindDMROptions(root) { root.querySelectorAll('[data-options-for]').forEach(function(el) { if (el.getAttribute('data-options-bound')) return; el.setAttribute('data-options-bound', '1'); var key = el.getAttribute('data-options-for'); // The master in the same settings (YSF2DMR's and NXDN2DMR's // are both "dmrMaster" on the Modes page) var scope = el.closest('[data-bridge-quick]') || el.closest('form') || root; var master = scope.querySelector('[name="' + key + '"], [data-quick-key="' + key + '"]'); if (!master) return; function apply() { hostList('dmr').then(function(data) { var h = data.byId[master.value]; el.style.display = (h && /^brandmeister$/i.test(h.name || '')) ? 'none' : ''; }); } master.addEventListener('change', apply); apply(); }); } // ── Host files arriving ────────────────────────────────────────── // MCP fetches the host files a mode or bridge needs when it is // switched on (and a new system's at startup). It says when it starts // and when they are in: the lists are then loaded afresh, so pickers // that came up empty work without reloading the page. document.addEventListener('pistar:message', function(e) { var m = e.detail; if (!m || m.type !== 'hostfiles' || !window.pistar || !window.pistar.toast) return; var files = (m.files || []).join(', '); if (m.state === 'downloading') { window.pistar.toast(i18n('hostfiles.downloading', 'Downloading host files: {files}').replace('{files}', files), { type: 'info', duration: 0, serviceKey: 'hostfiles' }); return; } if (m.state !== 'done') return; window.pistar.dismissServiceToast('hostfiles'); hostLists = {}; document.querySelectorAll('.tg-picker[data-bound]').forEach(function(p) { if (p._pistarShow) p._pistarShow(); }); document.querySelectorAll('.tg-list').forEach(function(w) { renderTGChips(w); }); var a = document.activeElement; if (a && a.classList && a.classList.contains('tg-search') && !a.classList.contains('ss-search')) { a.dispatchEvent(new Event('input')); } var failed = (m.results || []).filter(function(r) { return r.status === 'error'; }) .map(function(r) { return r.name; }); if (failed.length) { window.pistar.toast(i18n('hostfiles.failed', 'Could not download: {files}. MCP will try again at the next update.') .replace('{files}', failed.join(', ')), { type: 'warning' }); } else { window.pistar.toast(i18n('hostfiles.ready', 'Host files ready: {files}').replace('{files}', files), { type: 'success' }); } }); // fetchHostFilesFor asks MCP for the host files a mode or service // just switched on (staged) needs and does not have; the toasts and // the pickers' refresh follow over the WebSocket (above). function fetchHostFilesFor(what) { adminFetch('/admin/api/hostfiles/fetch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ modes: what.modes || [], services: what.services || [] }) }).catch(function() {}); } // ── Secret fields: a password input with a show/hide button ───── var EYE_ICON = ''; var EYE_OFF_ICON = ''; // renderSecret wraps an with its show button. function renderSecret(inputHTML) { return '
' + inputHTML + '
'; } document.addEventListener('click', function(e) { var btn = e.target.closest && e.target.closest('.secret-eye-btn'); if (!btn) return; var input = btn.parentNode.querySelector('input'); if (!input) return; var show = input.type === 'password'; input.type = show ? 'text' : 'password'; btn.setAttribute('aria-pressed', show ? 'true' : 'false'); btn.setAttribute('aria-label', show ? i18n('network.hidePassword', 'Hide password') : i18n('network.showPassword', 'Show password')); btn.innerHTML = show ? EYE_OFF_ICON : EYE_ICON; }); // placeDropdown opens a dropdown (shown, absolutely placed under its // box) upwards when there is not room for it below in the window and // there is more above (under the sticky header), so it never runs off // the page or over the footer. Call it each time the dropdown opens. function placeDropdown(box, dropdown) { dropdown.classList.remove('dd-up'); var r = box.getBoundingClientRect(); var header = document.querySelector('header[role="banner"]'); var top = header ? header.getBoundingClientRect().bottom : 0; var below = window.innerHeight - r.bottom; var above = r.top - top; var need = Math.min(dropdown.scrollHeight, parseFloat(getComputedStyle(dropdown).maxHeight) || dropdown.scrollHeight) + 8; if (below < need && above > below) dropdown.classList.add('dd-up'); } // ── Frequencies ── // Kept in Hz; entered however the user writes them (480.3, 480,3 MHz, // 480300 kHz, 480300000) and shown in MHz to three decimal places, // more only when needed (438.800, 438.8125). As svcconfig.ParseFrequency. function parseFrequency(str) { var s = String(str == null ? '' : str).toLowerCase().replace(/\s+/g, '').replace(',', '.'); var scale = 0; var m = s.match(/^(.*?)(mhz|khz|hz)$/); if (m) { s = m[1]; scale = m[2] === 'mhz' ? 1e6 : m[2] === 'khz' ? 1e3 : 1; } if (!/^[0-9]+(\.[0-9]*)?$|^\.[0-9]+$/.test(s)) return 0; var v = parseFloat(s); if (!(v > 0)) return 0; if (!scale) scale = v < 1e4 ? 1e6 : v < 1e7 ? 1e3 : 1; var hz = Math.round(v * scale); return hz >= 1e6 && hz <= 6e9 ? hz : 0; } // Seven-segment digits, the decimal points on their own: the font's // is a speck squeezed between two digits, so each is drawn larger, // in a gap of its own function lcdDigits(cls, digits) { var span = document.createElement('span'); span.className = cls; digits.split('.').forEach(function(d, j) { if (j) { var dp = document.createElement('span'); dp.className = 'lcd-dp'; dp.textContent = '.'; span.appendChild(dp); } if (d) span.appendChild(document.createTextNode(d)); }); return span; } // An LCD readout (Modem Status, System Information): the numbers in // seven-segment digits over their unlit segments, as a real display // shows them, the words and units between them in the panel's text // face. The unlit "8"s are hidden from screen readers. function lcdText(el, text) { if (!el) return; text = text == null ? '' : String(text); if (el.getAttribute('data-lcd') === text) return; el.setAttribute('data-lcd', text); el.textContent = ''; text.split(/([-0-9][-0-9.:]*\u00b0?)/).forEach(function(part, i) { if (!part) return; if (i % 2 === 0) { var u = document.createElement('span'); u.className = 'lcd-unit'; u.textContent = part; el.appendChild(u); return; } var seg = document.createElement('span'); seg.className = 'lcd-seg'; seg.appendChild(lcdDigits('lcd-seg-off', part.replace(/[-0-9]/g, '8'))); seg.appendChild(lcdDigits('lcd-seg-on', part)); seg.firstChild.setAttribute('aria-hidden', 'true'); el.appendChild(seg); }); } function formatFrequency(hz) { var n = typeof hz === 'number' ? hz : parseInt(hz, 10); if (!n) return ''; var s = (n / 1e6).toFixed(6); while (/0$/.test(s) && s.length - s.indexOf('.') > 4) s = s.slice(0, -1); return s; } // Why the modem cannot use hz ('' when it can): its bands come with // the hardware selection (freqBands, freqBlocked). function frequencyError(hz, hw) { if (!hz) return i18n('freq.invalid', 'Enter a frequency, such as 438.800 (MHz)'); if (!hw || !hw.freqBands || !hw.freqBands.length) return ''; var blocked = (hw.freqBlocked || []).filter(function(b) { return hz >= b[0] && hz <= b[1]; })[0]; if (blocked) { return i18n('freq.satellite', '{from}-{to} MHz is a satellite segment: the modem will not use it') .replace('{from}', formatFrequency(blocked[0])).replace('{to}', formatFrequency(blocked[1])); } var ok = hw.freqBands.some(function(b) { return hz >= b[0] && hz < b[1]; }); if (ok) return ''; return i18n('freq.outOfBand', 'The modem cannot use {f} MHz: it works on {bands} MHz') .replace('{f}', formatFrequency(hz)) .replace('{bands}', hw.freqBands.map(function(b) { return String(b[0] / 1e6) + '-' + String(b[1] / 1e6); }).join(', ')); } // Inputs marked data-frequency show MHz, and tidy what was typed when // left (480.3 → 480.300). The value sent may be in any form: the // hotspot keeps it in Hz. function bindFrequencyInputs(container) { (container || document).querySelectorAll('input[data-frequency]').forEach(function(input) { if (input._freqBound) return; input._freqBound = true; input.addEventListener('change', function() { var hz = parseFrequency(input.value); if (hz) input.value = formatFrequency(hz); }); }); } // ── In-page dialog ── // ask({title, message, input: {value, maxlength, placeholder}, // ok, cancel, danger}) resolves to true/false, or to the text // entered (null when cancelled) when there is an input. A page dialog, // not the browser's confirm()/prompt(), which a browser can be told // to block, leaving a button that silently does nothing. function ask(opts) { opts = opts || {}; return new Promise(function(resolve) { var dlg = document.createElement('dialog'); dlg.className = 'ps-dialog'; var html = ''; if (opts.title) html += '

'; if (opts.message) html += '

'; if (opts.input) html += ''; html += '
' + '' + '
'; dlg.innerHTML = html; if (opts.title) dlg.querySelector('.ps-dialog-title').textContent = opts.title; if (opts.message) dlg.querySelector('.ps-dialog-message').textContent = opts.message; dlg.querySelector('.ps-dialog-cancel').textContent = opts.cancel || i18n('common.cancel', 'Cancel'); dlg.querySelector('.ps-dialog-ok').textContent = opts.ok || i18n('common.ok', 'OK'); var input = dlg.querySelector('.ps-dialog-input'); if (input) { input.value = opts.input.value || ''; if (opts.input.maxlength) input.maxLength = opts.input.maxlength; if (opts.input.placeholder) input.placeholder = opts.input.placeholder; } var done = false; function finish(ok) { if (done) return; done = true; var v = input ? (ok ? input.value.trim() : null) : ok; if (dlg.open) dlg.close(); dlg.remove(); resolve(v); } dlg.querySelector('.ps-dialog-ok').addEventListener('click', function() { if (input && !input.value.trim()) { input.focus(); return; } finish(true); }); dlg.querySelector('.ps-dialog-cancel').addEventListener('click', function() { finish(false); }); dlg.addEventListener('cancel', function(e) { e.preventDefault(); finish(false); }); if (input) input.addEventListener('keydown', function(e) { if (e.key === 'Enter') { e.preventDefault(); dlg.querySelector('.ps-dialog-ok').click(); } }); document.body.appendChild(dlg); dlg.showModal(); (input || dlg.querySelector('.ps-dialog-ok')).focus(); }); } return { ask: ask, parseFrequency: parseFrequency, formatFrequency: formatFrequency, lcdText: lcdText, frequencyError: frequencyError, bindFrequencyInputs: bindFrequencyInputs, renderSecret: renderSecret, fetchHostFilesFor: fetchHostFilesFor, labelFor: labelFor, labelAttrs: labelAttrs, bindDMROptions: bindDMROptions, bindSearchableSelects: bindSearchableSelects, placeDropdown: placeDropdown, i18n: i18n, formatTime: formatTime, formatDate: formatDate, formatTemperature: formatTemperature, formatDay: formatDay, timezones: timezones, renderIdEssid: renderIdEssid, bindIdEssid: bindIdEssid, renderLockedList: renderLockedList, syncLockedLists: syncLockedLists, bindLockedLists: bindLockedLists, renderHostPicker: renderHostPicker, bindHostPickers: bindHostPickers, renderReflectorPicker: renderReflectorPicker, setTheme: setTheme, // Speak & Spell: say it now (the theme must be on) speakSpellSay: function() { if (speakState && speakState.test) speakState.test(); }, loadTranslations: loadTranslations, i18nPlural: i18nPlural, flagHTML: flagHTML, countryName: countryName, callButton: callButton, adminFetch: adminFetch, setSetupComplete: setSetupComplete, isSetupComplete: isSetupComplete, showServiceLog: showServiceLog, waitForRestart: waitForRestart, showShutdownCountdown: showShutdownCountdown, showRebootCountdown: showRebootCountdown }; })(); // Global i18n helper for modules function i18n(key, fallback) { return PiStar.i18n(key, fallback); } // Global plural helper: i18nPlural('pending.count', n, '{n} change pending', '{n} changes pending') function i18nPlural(key, n, one, other) { return PiStar.i18nPlural(key, n, one, other); }