'use strict'; 'require baseclass'; 'require ui'; 'require rpc'; 'require fs-menutree as tree'; 'require fs-chrome as chrome'; 'require fs-sheets as sheets'; 'require fs-fit as fit'; /* ---- SPA client router ---- * * Kills the full page reload for `view`-type menu nodes — 54 of 74 menu leaves (~73%) on the dev * router; the rest are call/function/template. LuCI already renders every page client-side into * #view; only NAVIGATION is server-dispatched. So intercept link clicks and re-instantiate the * target view in place — what the dispatcher's view.ut does via ui.instantiateView(), minus the * reload. Purely additive: anything that is not a satisfied `view` node (call/function/template/ * alias/firstchild, external, download, cross-origin, modified click) or any error falls through to * a normal navigation, and deep links / F5 keep working because we pushState the real URL. * * Re-instantiation: L.require('view.x') returns a cached SINGLETON whose __init__ (the render) * already ran, so calling it again repaints nothing. Take the class off the instance * (prototype.constructor) and `new v.constructor()` for a fresh __init__ → load()+render(), which is * what a full load does anyway. docs/spa-router.md. * * The path->node half lives in fs-menutree.js (the chrome needs it too); the "has a view poisoned * this document with its CSS?" half in fs-sheets.js. * * `docs/…`, `tools/…` and `tests/…` in these comments name the theme's own repository * (https://github.com/VizzleTF/luci-theme-footstrap), not the tree this file is read in: the * package ships the runtime and nothing else. */ /* --- stray-interval teardown for SPA nav --- * A full load kills every window.setInterval the outgoing page set; SPA nav does not, so a view's * poller keeps firing against a page that is gone. Track view-set ids and clear them on navigation, * keeping L.Poll's own 1 s tick (also a setInterval); L.Poll's queue is flushed in navigate(). * Hooked at module eval, before any view render can set a timer. */ const _viewIntervals = (window.__fsViewIntervals || (window.__fsViewIntervals = new Map())); (function hookIntervals() { if (window.__fsIntervalsHooked) return; window.__fsIntervalsHooked = true; const _si = window.setInterval, _ci = window.clearInterval; /* The id the caller got is the id it keeps, whatever the pause below does underneath: the map is * keyed by that first id and the entry carries `live`, the id armed right now (null while * paused), so a view holding its handle can still stop its own poller after a trip through a * hidden tab. The arguments are kept because a `setInterval` id carries none of them back. */ window.setInterval = function (fn, ms, ...rest) { const id = _si.apply(window, arguments); _viewIntervals.set(id, { fn, ms, rest, live: id }); return id; }; window.clearInterval = function (id) { const spec = _viewIntervals.get(id); _viewIntervals.delete(id); /* a paused timer is already disarmed and its number is the platform's to hand out again, so * clearing it here would stop whatever timer holds it now. Untracked ids fall through: the * hook stays a pass-through for everything it did not arm. */ if (spec) return (spec.live == null) ? undefined : _ci.call(window, spec.live); return _ci.apply(window, arguments); }; /* A hidden tab must not keep calling the router. `wireVisibility()` below stops LuCI's own poll, * which is most of the traffic, but a view is free to run a plain `setInterval` of its own and * those keep hammering ubus for as long as the tab stays open. The registry navigation already * uses to clear them is enough to pause them: disarmed on hide, re-armed on show with the same * callback and period. * * A paused timer stays IN the registry, armed on nothing. Held in a list beside it, the * navigation sweep cannot see it — hide the tab while a navigation is in flight and coming back * re-arms the timers of the page that navigation already replaced. */ document.addEventListener('visibilitychange', () => { if (document.hidden) { /* LuCI's own tick is not ours to pause. `L.Poll.start()` arms it with a plain * `setInterval`, so the hook above catches it like any other id — and pausing it here * re-arms it under an id L.Poll knows nothing about, after which `start()` arms a * second one because `active()` has nothing to see: two ticks per interval after one * hide/show, three after two. * * So the tick is skipped here and wireVisibility() keeps both halves of it. When it * cannot be told apart from a view's timer, NOTHING is paused: a view's poller in a * hidden tab costs a wasted RPC, re-arming LuCI's tick behind its back costs a doubling * that never stops. */ const keep = pollTickId(); if (keep === false) return; for (const [ id, spec ] of _viewIntervals) { if (id === keep || spec.live == null) continue; _ci.call(window, spec.live); spec.live = null; } } else { for (const spec of _viewIntervals.values()) { if (spec.live != null) continue; /* `_si`, not the hook: this timer is already in the registry under the id its * caller holds, and re-registering it would key a second entry to a number nobody * has. The fresh id lives in `spec.live` alone and is never a key. */ spec.live = _si.call(window, spec.fn, spec.ms, ...spec.rest); } } }); })(); /* Which id is LuCI's own tick, asked in one place because both callers — the navigation sweep and * the hidden-tab pause above — pay the same price for getting it wrong. * * `L.Poll.timer` is that id, and it is private state: `add`/`remove`/`start`/`stop`/`active` are the * documented surface, and the whole `L.Poll` alias is already deprecated (`'require poll'` replaces * it, but no supported release ships poll.js yet). `active()` below is called unguarded: this * caller runs from the visibilitychange listener at module eval (:69-81), before CONTRACT_FNS ever * checks anything, so what backs it is the floor, not the boot contract — `L.Poll.active` is * unconditional in every 24.10+ luci.js. Read blind, a renamed `timer` field would make LuCI's tick * look like a view's — cleared on the next navigation, every poll on every later page silently * dead. So a missing field is a reason to do nothing, once, loudly: `active()` says whether the * tick is running, and `timer` is deleted by `stop()`, so an absent field is the ordinary "nothing * to protect" case. The anomaly worth reporting is the pair disagreeing — a tick running while the * id it runs on has no name we know. */ /* -> the tick's id; null when LuCI is not polling; false when the two cannot be told apart, which * every caller reads as "leave every interval alone" */ function pollTickId() { const running = L.Poll.active(); if (running && L.Poll.timer == null) { warnPollUnreadable('footstrap: LuCI is polling but L.Poll.timer is not readable — leaving view ' + 'intervals alone rather than risking its tick. fs-router.js needs updating for this ' + 'luci-base.'); return false; } return running ? L.Poll.timer : null; } function clearViewIntervals() { const keep = pollTickId(); if (keep === false) return; /* Map, not Set: the key is the timer id and the value is what it takes to re-arm it */ _viewIntervals.forEach((spec, id) => { if (id !== keep) window.clearInterval(id); }); } /* The "Refreshing"/"Paused" pill must not outlive the poll it reports on — see the `poll-stop` * listener below, which is the only caller in the shipped file. Exported (fs:probe) too, because * navigate()'s own async chain (require(), staging into a real `.fs-content`) needs more DOM than * tests/lib's fakes give it; this is the one check that actually matters for the ordering bug and is * exercised directly, without the listener's deferral, by tests/poll-status.test.mjs. */ function hidePollIndicatorIfEmpty() { if (!(L.Poll && L.Poll.queue && L.Poll.queue.length === 0)) return; try { ui.hideIndicator('poll-status'); } catch (e) { console.error('footstrap: hideIndicator threw on the poll-status teardown', e); } } /* one line per document: this runs on every navigation, and a router that cannot read L.Poll * cannot read it on the next click either */ let _pollWarned = false; function warnPollUnreadable(msg) { if (_pollWarned) return; _pollWarned = true; console.error(msg); } /* --- uci cache teardown for SPA nav --- * `uci.load()` does not answer "is this config present?" — it answers "which of these packages did * THIS call fetch", skipping every package already in its document-scoped cache. Several shipped * views read that return value as an existence check and abort on an empty array, so under SPA the * SECOND visit renders as "no config found", unstickable short of a reload. * * The apps' reading of `load()` is wrong, but the divergence is ours: a cache that outlives the * page that filled it is state a fresh load does not have, like the poll queue and the intervals * above. So drop it on navigation and let the incoming view fetch what it needs. * * `unload()` is upstream's own idiom for this — `uci.save()` ends with * `self.unload(pkgs); return self.load(pkgs)`. Pending local edits go with it, as they do on a full * load; saved changes are on the server and the Unsaved-changes banner reads them from there. * * Read through `window.L.uci` rather than a `'require uci'` pragma: the class attaches to L's * prototype when the first requirer compiles it, so this sees the instance the pages use, while * requiring it would bind it to our prototypal L (the two-L trap) and pull uci.js onto pages that * never touch uci. * * Returns the refill below as a promise the caller must wait on, or null. It never rejects: a * navigation is not the place to lose a page over a config the incoming view may not read. */ function flushUciCache() { const uci = window.L ? window.L.uci : null; if (!uci || typeof uci.unload !== 'function') return null; /* `state.values` and `loaded` are private, so the L.Poll.timer rule applies: an unrecognised * shape means do nothing, once, loudly. The two hold different halves of the cache (a package * whose load is in flight is in `loaded` alone) and unload() clears both. */ if (!uci.state || typeof uci.state.values !== 'object' || typeof uci.loaded !== 'object') { if (!_uciCacheWarned) { _uciCacheWarned = true; console.error('footstrap: LuCI.uci keeps its cache somewhere this router does not know, so ' + 'it is left alone. An app that reads uci.load()\'s return value as an existence check ' + 'will report a missing config on the second SPA visit. fs-router.js needs updating for ' + 'this luci-base.'); } return null; } const names = Object.keys(uci.state.values).concat(Object.keys(uci.loaded)); if (!names.length) return null; uci.unload(names); /* `state.reorder` is the half unload() does not clear, and is left alone: with `values` gone, * reorderSections() finds no sections, emits no call and clears the map itself on the next * save. */ /* …and put back the three packages luci-base's network.js reads but will never load again. * * initNetworkState() loads `network`, `wireless` and `luci` once and from then on answers every * caller from its own `_state` — but what it answers WITH is the uci cache (`getWifiDevices()` * is `uci.sections('wireless', 'wifi-device')`). So dropping those packages does not make * network.js refetch them, it makes every consumer read an EMPTY config until the next full * load: Channel Analysis with no band tabs, Network -> Switch with no VLAN sections, both * correct again after F5. tools/spa-parity.mjs reproduces it; tools/upstream-contract.mjs * notices if the list of three moves. * * navigate() waits for the refill, because a cached module resolves within a microtask and the * view would read the cache we just emptied. Only when network.js is really in the document. * The ubus half of `_state` stays as stale as upstream leaves it. * * The wait costs one uci `get` in front of the render on a warm navigation (136 -> 159 ms * median). Leaving the three OUT of the unload instead is free and was rejected: a view calling * `network.flushCache()` reloads its ubus half but calls `uci.load()` for the uci half, a no-op * while the package is cached, so Interfaces and Wireless would render fresh device state over * config values from whenever the document first touched them. */ if (!window.L.network) return null; const refill = [ 'network', 'wireless', 'luci' ].filter((p) => names.indexOf(p) !== -1); if (!refill.length) return null; return uci.load(refill).catch((e) => { console.error('footstrap: reloading uci ' + refill.join(', ') + ' after a navigation failed', e); }); } let _uciCacheWarned = false; /* ---- a dead session ends the document, and the router must not browse through it ---- * * luci-base answers an expired session with `notifySessionExpiry()`: `Poll.stop()` plus a modal * whose only button reloads the page, which the dispatcher answers with the login form. Every * navigation of ours does the opposite of both halves (`ui.hideModal()`, `L.Poll.stop()+start()`), * so the first click after the session died dismissed that warning and carried on, leaving the page * on "Loading view…" with every call behind it failing. * * So the router learns that the session is gone and stops claiming navigations; the next click is a * real one and the dispatcher turns it into the login page. Nothing is reset — the flag dies with * the document, as the session did. * * The two signals are luci-base's own decision points (luci.js, `setupDOM`): * * 1. a `403` carrying `X-LuCI-Login-Required: yes` on any `L.Request`; * 2. the `session.access` probe luci-base fires after a `-32002`, when that probe REJECTS. * * `access: false` is deliberately not one of them: the probe is declared `expect: { access: true }`, * so rpc.js resolves it rather than rejecting, and it is an ACL answer — treating it as a dead * session would drop a restricted user out of the SPA over a permission they do not have. * * The probe's rejection is read off the frame the interceptor is handed, since that is all an * interceptor sees: `handleCallReply()` rejects on a frame that is not JSON-RPC 2.0 or on an `error` * carrying both a code and a message. Somebody else's failing `session.access` call would also * match, at a cost of one document of full loads. * * Neither interceptor may throw: luci-base runs both through `Promise.all(...).catch(req.reject)`, * so an exception here would reject the caller's request. Hence the try/catch around each body. */ let _expired = false; let _sessionWired = false; function markExpired() { if (_expired) return; _expired = true; /* once per document, at the least alarming level the house rules allow (eslint no-console * permits warn and error only): nothing is broken, the session simply ended */ console.warn('footstrap: the LuCI session is gone — every navigation from here is a full load.'); } /* The verdict is not a latch. An interceptor sees `msg` only once the transport succeeded and the * body parsed, so a missing frame is not a network flap — but it is a captive portal's page, a * proxy's error body, one truncated reply, any of which would take the router off for the rest of * the document with the session alive throughout. * * A clean `session.access` is the same call the failing one was, so it is evidence the other way. * If the session really has ended no clean one arrives, every ubus call carrying the same dead * sid. */ function markAlive() { if (!_expired) return; _expired = false; console.warn('footstrap: the LuCI session answers again — client navigation is back on.'); } function sessionExpired() { return _expired; } function watchSession() { if (_sessionWired) return; _sessionWired = true; const req = window.L ? window.L.Request : null; if (req && typeof req.addInterceptor === 'function') req.addInterceptor((res) => { try { if (res && res.status === 403 && res.headers && res.headers.get('X-LuCI-Login-Required') === 'yes') markExpired(); } catch (e) { /* see above: an interceptor that throws rejects the caller's request */ } }); if (rpc && typeof rpc.addInterceptor === 'function') rpc.addInterceptor((msg, r) => { try { if (!r || r.object !== 'session' || r.method !== 'access') return; if (!msg || msg.jsonrpc !== '2.0') return; /* an `error` carrying both a code and a message is what handleCallReply() rejects * on, and a rejected session probe is the signal. A frame that is not JSON-RPC 2.0 * is rejected there too, but says nothing about the session. */ if (msg.error && msg.error.code && msg.error.message) { markExpired(); return; } /* Only `access: true` says the session is there. A dead sid does not make this call * fail — `session.access` answers `[0, {access:false}]` with HTTP 200 and no error * frame, the `-32002` arriving on the ordinary call that made luci-base fire the * probe — so "the reply parsed" would read as "the session is back" and clear the * verdict a 403 just reached. `access:false` stays out of both answers, an ACL * denial looking exactly the same. */ if (Array.isArray(msg.result) && msg.result[1] && msg.result[1].access === true) markAlive(); } catch (e) { /* ditto */ } }); } /* ---- throw an element away the way luci-base throws one away ---- * * `dom.data()` does not live on the element: luci.js keeps it in `dom.registry`, keyed by a * `data-idref` attribute, and only `dom.content()` ever deletes an entry. A plain `remove()` * therefore leaves the entry — and through it the element and whatever class instance it held — * reachable for the life of the document. * * `#view` is not affected, the incoming view's own `dom.content()` reaping the outgoing page. What * the router removes by hand is the rest: the siblings a template emitted next to `#view`, and the * runtime notification banners. * * Nothing the sweeps remove carries a `data-idref` on the stands today, and the registry does not * grow across laps (83 entries after the first lap of four pages, 83 after the third), so this * fixes no measurable leak — it closes the class, for the coverage reason the table selector * gives. * * The bin is what makes the element's OWN entry go too: `dom.content()` reaps descendants of the * node it is given, never the node itself, so the element is moved into a detached container first, * which also takes it out of the live tree. Public API only; no reaching into `dom.registry`. */ function discard(el) { try { const bin = document.createElement('div'); bin.appendChild(el); window.L.dom.content(bin, null); } catch (e) { el.remove(); } } /* ---- a page that leaves nodes as direct children of
hands the next page over by full load, * the same way an invasive foreign sheet does (docs/third-party-apps.md, Rule 2 extended from CSS to * the DOM — issue #56) ---- * * luci-app-bandix's render() appends 7 tooltip/modal nodes to document.body on every visit, * unconditionally (reproduced on owrt2512 and owrt2410) — nothing here sweeps them; the reasoning is * docs/spa-router.md, "Foreign view DOM". The recorder is header.ut's first