statum.js 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  1. /*!
  2. * Statum - client-side state library.
  3. *
  4. * An HTMX-inspired state layer. The library manages signed "snapshots" of
  5. * application state (one per slot type), keeps them fresh via the server's
  6. * `transmit_after` / `invalid_after` timestamps, and binds them to the DOM
  7. * through `stm-*` attributes. See model.md for the full specification.
  8. *
  9. * Distribution: a single IIFE that attaches `window.statum` (no dependencies,
  10. * no build step). Targets modern evergreen browsers (uses fetch,
  11. * BroadcastChannel, queueMicrotask, URLSearchParams, FormData).
  12. */
  13. (function () {
  14. 'use strict';
  15. /** Content-Type used by every Statum directive response. */
  16. var STATUM_CONTENT_TYPE = 'application/vnd.statum+json';
  17. /** Request/response header carrying one slot's reference (or base64 frame). */
  18. var SLOT_HEADER = 'X-Statum-Slot';
  19. /** Request header carrying an action's opaque `private` blob. */
  20. var PRIVATE_HEADER = 'X-Statum-Private';
  21. /** Session-cookie marker used to detect a fresh browser session. */
  22. var SESSION_COOKIE = '_statum_sdc';
  23. /** BroadcastChannel name used to sync session/device state across tabs. */
  24. var CHANNEL_NAME = 'statum';
  25. /** localStorage / sessionStorage key prefix for persisted frames. */
  26. var STORAGE_PREFIX = 'statum:';
  27. // ---------------------------------------------------------------------------
  28. // Configuration
  29. // ---------------------------------------------------------------------------
  30. /**
  31. * Endpoint URLs. These defaults may be overridden per-page with the
  32. * `stm-entrypoint` and `stm-slots` attributes on the `<body>` element.
  33. *
  34. * @type {{entrypointUrl: string, slotsUrl: string}}
  35. */
  36. var config = {
  37. entrypointUrl: '/_statum/entrypoint',
  38. slotsUrl: '/_statum/slots',
  39. channelUrl: '/_statum/channel',
  40. workerUrl: '/_statum/worker.js'
  41. };
  42. // ---------------------------------------------------------------------------
  43. // State store
  44. // ---------------------------------------------------------------------------
  45. /**
  46. * In-memory store, keyed by slot type. Each value is `{frame, snapshot}`
  47. * where `snapshot` is the parsed `frame.content`. This map is the single
  48. * source of truth for rendering; persistent backends merely hydrate it.
  49. *
  50. * @type {Map<string, {frame: object, snapshot: object}>}
  51. */
  52. var store = new Map();
  53. /** Listeners, keyed by type name. @type {Map<string, Set<Function>>} */
  54. var listeners = new Map();
  55. /**
  56. * Idempotency tracking: slot key -> last-applied frame `signature`. Held in
  57. * memory only (per tab), so a frame already persisted by another tab still
  58. * re-draws a tab whose tracking lags. Entries are dropped on clear so a
  59. * replayed frame re-applies.
  60. * @type {Map<string, string>}
  61. */
  62. var signatures = new Map();
  63. /** Optional UI handlers (set via `statum.on*Handler`). */
  64. var handlers = { onConfirm: null, onNotify: null, onError: null };
  65. /** @type {BroadcastChannel|null} */
  66. var channel = null;
  67. /** Whether {@link init} has already run. */
  68. var initialized = false;
  69. // ---------------------------------------------------------------------------
  70. // Small utilities
  71. // ---------------------------------------------------------------------------
  72. /**
  73. * Parse an ISO 8601 timestamp to epoch millis, or `undefined`.
  74. * @param {string|undefined} s
  75. * @returns {number|undefined}
  76. */
  77. function parseTime(s) {
  78. if (!s) return undefined;
  79. var t = new Date(s).getTime();
  80. return isNaN(t) ? undefined : t;
  81. }
  82. /**
  83. * Base64-encode a UTF-8 string (safe for frames containing non-Latin1 data).
  84. * @param {string} str
  85. * @returns {string}
  86. */
  87. function b64encode(str) {
  88. var bytes = new TextEncoder().encode(str);
  89. var bin = '';
  90. var chunk = 0x8000;
  91. for (var i = 0; i < bytes.length; i += chunk) {
  92. bin += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
  93. }
  94. return btoa(bin);
  95. }
  96. /** Read a cookie value, or `null` if absent. @param {string} name */
  97. function getCookie(name) {
  98. var escaped = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
  99. var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
  100. return match ? decodeURIComponent(match[1]) : null;
  101. }
  102. /** Set a session cookie (no expiry => cleared when the browser closes). */
  103. function setCookie(name, value) {
  104. document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; SameSite=Lax';
  105. }
  106. // ---------------------------------------------------------------------------
  107. // Expression evaluation
  108. // ---------------------------------------------------------------------------
  109. /**
  110. * Compiled-expression cache. Expressions are evaluated as JavaScript against
  111. * a scope object (the page's HTML is trusted, per the model).
  112. * @type {Map<string, Function>}
  113. */
  114. var exprCache = new Map();
  115. /**
  116. * Compile (and cache) an expression string into a function of `scope`.
  117. * Uses `with` so that arbitrary type names and loop variables are resolved
  118. * as bare identifiers. Returns a function that yields `undefined` on any
  119. * runtime or compile error.
  120. * @param {string} expr
  121. * @returns {Function}
  122. */
  123. function compileExpr(expr) {
  124. var cached = exprCache.get(expr);
  125. if (cached !== undefined) return cached;
  126. var fn;
  127. try {
  128. // Function-constructor bodies are non-strict by default, so `with` is
  129. // permitted. The inner try/catch turns reference errors into `undefined`
  130. // so a missing path simply yields no value.
  131. fn = new Function('scope', 'with(scope){try{return (' + expr + ');}catch(e){return undefined;}}');
  132. } catch (e) {
  133. fn = function () { return undefined; };
  134. }
  135. exprCache.set(expr, fn);
  136. return fn;
  137. }
  138. /**
  139. * Evaluate an expression against a scope.
  140. * @param {string} expr
  141. * @param {object} [scope]
  142. * @returns {*} `undefined` if the expression is empty or fails.
  143. */
  144. function evalExpr(expr, scope) {
  145. if (expr == null || expr === '') return undefined;
  146. try {
  147. return compileExpr(expr)(scope || {});
  148. } catch (e) {
  149. return undefined;
  150. }
  151. }
  152. /**
  153. * Build a child scope that inherits the parent (so type bindings remain
  154. * visible) and adds one own loop variable.
  155. * @param {object} parent
  156. * @param {string} name
  157. * @param {*} value
  158. * @returns {object}
  159. */
  160. function childScope(parent, name, value) {
  161. var scope = Object.create(parent || null);
  162. scope[name] = value;
  163. return scope;
  164. }
  165. // ---------------------------------------------------------------------------
  166. // StatumError
  167. // ---------------------------------------------------------------------------
  168. /**
  169. * Error type thrown for HTTP failures and `error` directives.
  170. * @param {string} [message]
  171. * @param {string} [code]
  172. * @param {object} [data]
  173. */
  174. function StatumError(message, code, data) {
  175. this.name = 'StatumError';
  176. this.message = message || '';
  177. this.code = code || undefined;
  178. this.data = data || undefined;
  179. }
  180. StatumError.prototype = Object.create(Error.prototype);
  181. // ---------------------------------------------------------------------------
  182. // UI handlers (confirm / notify / error)
  183. // ---------------------------------------------------------------------------
  184. /**
  185. * Run the `notify` directive's default behaviour or the custom
  186. * `statum.onNotifyHandler`. The default surfaces the message via `alert()`.
  187. * @param {string} [kind] Application-defined category (freeform).
  188. * @param {string} [message]
  189. */
  190. function triggerNotify(kind, message) {
  191. var fn = handlers.onNotify;
  192. try {
  193. if (fn) fn(kind, message);
  194. else if (message != null) window.alert(message);
  195. } catch (e) { console.error('[statum] notify handler error', e); }
  196. }
  197. /**
  198. * Run the `stm-confirm` gate: the custom `statum.onConfirmHandler` if set,
  199. * otherwise `window.confirm`. Supports async handlers (custom modals).
  200. * @param {string} message
  201. * @param {HTMLElement} element
  202. * @returns {Promise<boolean>} truthy if the action should proceed.
  203. */
  204. async function triggerConfirm(message, element) {
  205. var fn = handlers.onConfirm;
  206. try {
  207. if (fn) return !!(await fn(message, element));
  208. return !!window.confirm(message);
  209. } catch (e) {
  210. console.error('[statum] confirm handler error', e);
  211. return false;
  212. }
  213. }
  214. /**
  215. * Run the custom `statum.onErrorHandler`, if set. Returns whether the default
  216. * behaviour (promise rejection + `stm-on-error` classes) should proceed: the
  217. * handler suppresses the default by returning (or resolving) `false`.
  218. * @param {StatumError} error
  219. * @param {HTMLElement|null} element
  220. * @returns {Promise<boolean>}
  221. */
  222. async function triggerError(error, element) {
  223. var fn = handlers.onError;
  224. if (!fn) return true;
  225. try {
  226. var suppress = await fn(error, element);
  227. return suppress !== false;
  228. } catch (e) {
  229. console.error('[statum] error handler error', e);
  230. return true;
  231. }
  232. }
  233. /**
  234. * Surface a failure: run `triggerError`, and if the default is not
  235. * suppressed, apply `stm-on-error` classes (when an origin element exists)
  236. * and re-throw so the originating promise rejects.
  237. * @param {StatumError} error
  238. * @param {HTMLElement|null} element
  239. */
  240. async function reportFailure(error, element) {
  241. if (await triggerError(error, element)) {
  242. if (element) applyErrorClasses(element, true);
  243. throw error;
  244. }
  245. }
  246. // ---------------------------------------------------------------------------
  247. // Persistence
  248. // ---------------------------------------------------------------------------
  249. /**
  250. * Pick the storage backend for a scope.
  251. * @param {string} scope
  252. * @returns {Storage|null} `null` for in-memory scopes.
  253. */
  254. function storageFor(scope) {
  255. if (scope === 'device' || scope === 'session') return localStorage;
  256. if (scope === 'flow') return sessionStorage;
  257. return null; // page / transient
  258. }
  259. /**
  260. * Persist a slot's frame to the backend matching its scope, removing any
  261. * stale copy from the other backend first (in case the scope changed).
  262. * @param {string} type
  263. * @param {{frame: object, snapshot: object}} entry
  264. */
  265. function persistEntry(type, entry) {
  266. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  267. removePersisted(type);
  268. var storage = storageFor(scope);
  269. if (!storage) return;
  270. try {
  271. storage.setItem(STORAGE_PREFIX + type, JSON.stringify(entry.frame));
  272. } catch (e) {
  273. /* storage full or unavailable; remain in-memory only */
  274. }
  275. }
  276. /** Remove a persisted frame from both backends. @param {string} type */
  277. function removePersisted(type) {
  278. try { localStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  279. try { sessionStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  280. }
  281. /** Load every persisted frame from a backend into the in-memory store. */
  282. function loadFrom(storage) {
  283. for (var i = 0; i < storage.length; i++) {
  284. var key = storage.key(i);
  285. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  286. try {
  287. var frame = JSON.parse(storage.getItem(key));
  288. var snapshot = JSON.parse(frame.content);
  289. var type = snapshot.slot && snapshot.slot.type;
  290. if (type && !store.has(type)) store.set(type, { frame: frame, snapshot: snapshot });
  291. } catch (e) {
  292. /* corrupt entry: ignore */
  293. }
  294. }
  295. }
  296. /** Hydrate the store from localStorage and sessionStorage. */
  297. function hydrate() {
  298. try { loadFrom(localStorage); } catch (e) {}
  299. try { loadFrom(sessionStorage); } catch (e) {}
  300. }
  301. // ---------------------------------------------------------------------------
  302. // Session-cookie initialization
  303. // ---------------------------------------------------------------------------
  304. /**
  305. * Detect a fresh browser session using the `_statum_sdc` session cookie.
  306. * On a fresh session, clear all `session`-scoped persisted frames, then set
  307. * the marker. Session cookies are shared across tabs, so a tab opened
  308. * mid-session sees the marker and leaves session data intact.
  309. */
  310. function initSession() {
  311. if (getCookie(SESSION_COOKIE) !== null) return;
  312. clearSessionSlotsFromStorage();
  313. setCookie(SESSION_COOKIE, '1');
  314. }
  315. /** Remove all `session`-scoped frames from localStorage. */
  316. function clearSessionSlotsFromStorage() {
  317. var toRemove = [];
  318. for (var i = 0; i < localStorage.length; i++) {
  319. var key = localStorage.key(i);
  320. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  321. try {
  322. var frame = JSON.parse(localStorage.getItem(key));
  323. var snapshot = JSON.parse(frame.content);
  324. if (snapshot.slot && snapshot.slot.scope === 'session') toRemove.push(key);
  325. } catch (e) {}
  326. }
  327. for (var j = 0; j < toRemove.length; j++) localStorage.removeItem(toRemove[j]);
  328. }
  329. // ---------------------------------------------------------------------------
  330. // Listeners & cross-tab broadcast
  331. // ---------------------------------------------------------------------------
  332. /**
  333. * Fire all listeners for a type. (Renamed from `notify` to avoid confusion
  334. * with the `notify` directive.)
  335. * @param {string} type
  336. * @param {object|null} frame
  337. * @param {object|null} snapshot
  338. */
  339. function fireListeners(type, frame, snapshot) {
  340. var set = listeners.get(type);
  341. if (!set) return;
  342. var event = { type: type, frame: frame, snapshot: snapshot };
  343. set.forEach(function (cb) {
  344. try { cb(event); } catch (e) { console.error('[statum] listener error', e); }
  345. });
  346. }
  347. /**
  348. * Broadcast a state change to other tabs. Only `session`/`device` scopes are
  349. * shared (flow/page/transient are per-tab).
  350. * @param {object} message
  351. * @param {string} [scope]
  352. */
  353. function broadcast(message, scope) {
  354. if (!channel) return;
  355. if (scope !== 'session' && scope !== 'device') return;
  356. try { channel.postMessage(message); } catch (e) {}
  357. }
  358. /**
  359. * Broadcast a message to other tabs regardless of slot scope. Used to relay
  360. * realtime (live) events so they reach every tab, not just session/device
  361. * ones.
  362. */
  363. function broadcastAlways(message) {
  364. if (!channel) return;
  365. try { channel.postMessage(message); } catch (e) {}
  366. }
  367. /** Open the BroadcastChannel and wire inbound messages. */
  368. function setupChannel() {
  369. if (typeof BroadcastChannel === 'undefined') return;
  370. try {
  371. channel = new BroadcastChannel(CHANNEL_NAME);
  372. } catch (e) {
  373. channel = null;
  374. return;
  375. }
  376. channel.onmessage = function (ev) {
  377. var msg = ev.data;
  378. if (!msg) return;
  379. if (msg.kind === 'set' && msg.frame) {
  380. try {
  381. var snapshot = JSON.parse(msg.frame.content);
  382. var type = snapshot.slot && snapshot.slot.type;
  383. if (type && commitSet(msg.frame, snapshot, type, false)) renderAll();
  384. } catch (e) { /* ignore malformed */ }
  385. } else if (msg.kind === 'clear') {
  386. var t = msg.type;
  387. if (!t && msg.key != null) {
  388. store.forEach(function (entry, type) {
  389. if (entry.snapshot.slot && entry.snapshot.slot.key === msg.key) t = type;
  390. });
  391. }
  392. if (t) clearType(t, { broadcast: false });
  393. else if (msg.key != null) signatures.delete(msg.key);
  394. renderAll();
  395. }
  396. };
  397. }
  398. // ---------------------------------------------------------------------------
  399. // State mutation
  400. // ---------------------------------------------------------------------------
  401. /**
  402. * Remove a type from the store, un-persist it, drop its idempotency entry,
  403. * fire listeners, and (optionally) broadcast the clear to other tabs.
  404. * @param {string} type
  405. * @param {{broadcast?: boolean}} [opts]
  406. */
  407. function clearType(type, opts) {
  408. var entry = store.get(type);
  409. if (!entry) return;
  410. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  411. var key = entry.snapshot.slot && entry.snapshot.slot.key;
  412. store.delete(type);
  413. removePersisted(type);
  414. if (key) signatures.delete(key);
  415. fireListeners(type, null, null);
  416. if (opts && opts.broadcast) broadcast({ kind: 'clear', key: key, type: type }, scope);
  417. }
  418. /**
  419. * Resolve a slot key to its type and clear it. Used by the `clear` directive
  420. * (keyed) and by live `clear` events.
  421. * @param {string} key
  422. * @param {boolean} [broadcast]
  423. */
  424. function clearByKey(key, broadcast) {
  425. var typeToRemove = null;
  426. store.forEach(function (entry, type) {
  427. if (entry.snapshot.slot && entry.snapshot.slot.key === key) typeToRemove = type;
  428. });
  429. if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
  430. else if (key) signatures.delete(key);
  431. }
  432. /**
  433. * Commit a `set` to the in-memory store, persist it, and fire listeners.
  434. * Idempotent: if the frame's `signature` matches the last-applied signature
  435. * for this slot (tracked in {@link signatures}), nothing happens and `false`
  436. * is returned. When `doBroadcast` is true the set is forwarded to other tabs
  437. * via the scope-gated broadcast (session/device only).
  438. * @param {object} frame
  439. * @param {object} snapshot
  440. * @param {string} type
  441. * @param {boolean} doBroadcast
  442. * @returns {boolean} `true` if state changed.
  443. */
  444. function commitSet(frame, snapshot, type, doBroadcast) {
  445. var key = snapshot.slot && snapshot.slot.key;
  446. var sig = frame.signature;
  447. if (key && sig !== undefined && signatures.get(key) === sig) return false;
  448. var entry = { frame: frame, snapshot: snapshot };
  449. store.set(type, entry);
  450. persistEntry(type, entry);
  451. fireListeners(type, frame, snapshot);
  452. if (key && sig !== undefined) signatures.set(key, sig);
  453. if (doBroadcast) {
  454. var scope = snapshot.slot && snapshot.slot.scope;
  455. broadcast({ kind: 'set', frame: frame }, scope);
  456. }
  457. return true;
  458. }
  459. /**
  460. * Apply a `set` directive: store/refresh a slot's snapshot (idempotently),
  461. * broadcasting to other tabs.
  462. * @param {object} directive `{ snapshot_frame }`
  463. */
  464. function applySet(directive) {
  465. var frame = directive.snapshot_frame;
  466. if (!frame || !frame.content) return;
  467. var snapshot;
  468. try { snapshot = JSON.parse(frame.content); } catch (e) { return; }
  469. var type = snapshot.slot && snapshot.slot.type;
  470. if (!type) return;
  471. commitSet(frame, snapshot, type, true);
  472. }
  473. /**
  474. * Apply a `clear` directive. The directive carries a slot key, so the type
  475. * holding that key is resolved and removed.
  476. * @param {object} directive `{ key }`
  477. */
  478. function applyClear(directive) {
  479. if (directive.key == null) return;
  480. clearByKey(directive.key, true);
  481. }
  482. /**
  483. * Apply a live `set` event received over the realtime channel. The frame is
  484. * committed (idempotently) and, when new, broadcast to sibling tabs via the
  485. * scope-agnostic {@link broadcastAlways} so every tab sees it regardless of
  486. * which (or how many) tabs hold a subscription.
  487. * @param {object} frame
  488. */
  489. function applyRemoteSet(frame) {
  490. try {
  491. var snapshot = JSON.parse(frame.content);
  492. var type = snapshot.slot && snapshot.slot.type;
  493. if (!type) return;
  494. if (commitSet(frame, snapshot, type, false)) {
  495. broadcastAlways({ kind: 'set', frame: frame });
  496. renderAll();
  497. }
  498. } catch (e) { /* malformed frame */ }
  499. }
  500. /** Apply a live `clear` event received over the realtime channel. */
  501. function applyRemoteClear(key) {
  502. if (key == null) return;
  503. signatures.delete(key);
  504. clearByKey(key, false);
  505. broadcastAlways({ kind: 'clear', key: key });
  506. renderAll();
  507. }
  508. // ---------------------------------------------------------------------------
  509. // Snapshot freshness & request headers
  510. // ---------------------------------------------------------------------------
  511. /**
  512. * Categorize a held snapshot relative to the current time.
  513. * @returns {'silent'|'always'|'invalid'|'stale'|'fresh'}
  514. * - `silent`: unidirectional (`transmit_after` undefined) - never sent.
  515. * - `always`: `transmit_after === as_at` - send the base64 frame each time.
  516. * - `invalid`: past `invalid_after` - drop and refetch.
  517. * - `stale`: past `transmit_after` but not yet invalid - pre-flight first.
  518. * - `fresh`: still cached server-side - send the `as_at` reference.
  519. */
  520. function entryCategory(entry) {
  521. var snap = entry.snapshot;
  522. var transmit = snap.transmit_after;
  523. if (transmit === undefined || transmit === null) return 'silent';
  524. if (transmit === snap.as_at) return 'always';
  525. var now = Date.now();
  526. var invalidAt = parseTime(snap.invalid_after);
  527. var transmitAt = parseTime(transmit);
  528. if (invalidAt !== undefined && now >= invalidAt) return 'invalid';
  529. if (transmitAt !== undefined && now >= transmitAt) return 'stale';
  530. return 'fresh';
  531. }
  532. /**
  533. * Drop locally-invalid snapshots and pre-flight any stale ones. Pre-flighting
  534. * posts the stale frames to the slot endpoint and applies the returned `set`
  535. * directives, refreshing their `as_at` values before the real request runs.
  536. *
  537. * Single-flight: concurrent callers share one in-flight preparation.
  538. * @returns {Promise<void>}
  539. */
  540. var preparePromise = null;
  541. function prepareSlots() {
  542. if (preparePromise) return preparePromise;
  543. preparePromise = doPrepareSlots().then(function () {
  544. preparePromise = null;
  545. }, function () {
  546. preparePromise = null;
  547. });
  548. return preparePromise;
  549. }
  550. async function doPrepareSlots() {
  551. var stale = [];
  552. store.forEach(function (entry, type) {
  553. var cat = entryCategory(entry);
  554. if (cat === 'invalid') {
  555. clearType(type, { broadcast: false });
  556. } else if (cat === 'stale') {
  557. stale.push(entry.frame);
  558. }
  559. });
  560. if (stale.length) {
  561. var directives = await postSlots(stale);
  562. var pfResult = applyDirectives(directives, { originElement: null });
  563. executeTerminal(pfResult);
  564. }
  565. }
  566. /**
  567. * Build the `X-Statum-Slot` header values for every held slot, using the
  568. * freshness rules. Assumes {@link prepareSlots} has just run.
  569. * @returns {string[]}
  570. */
  571. function buildSlotHeaders() {
  572. var headers = [];
  573. store.forEach(function (entry) {
  574. var snap = entry.snapshot;
  575. var cat = entryCategory(entry);
  576. if (cat === 'silent' || cat === 'invalid') return;
  577. if (cat === 'always') {
  578. headers.push(b64encode(JSON.stringify(entry.frame)));
  579. } else {
  580. headers.push('key=' + snap.slot.key + '; as_at=' + snap.as_at);
  581. }
  582. });
  583. return headers;
  584. }
  585. /**
  586. * Collect the current frames held for the given slot keys, in the order the
  587. * keys are first supplied. Used by the `transmit` directive (which forces a
  588. * slot's frame to be posted as if its `transmit_after` had elapsed). Keys the
  589. * client does not currently hold are skipped.
  590. * @param {string[]} keys
  591. * @returns {object[]}
  592. */
  593. function collectFramesForKeys(keys) {
  594. var keySet = Object.create(null);
  595. for (var i = 0; i < keys.length; i++) keySet[keys[i]] = true;
  596. var frames = [];
  597. store.forEach(function (entry) {
  598. var key = entry.snapshot.slot && entry.snapshot.slot.key;
  599. if (key && keySet[key]) {
  600. frames.push(entry.frame);
  601. delete keySet[key];
  602. }
  603. });
  604. return frames;
  605. }
  606. // ---------------------------------------------------------------------------
  607. // HTTP helpers
  608. // ---------------------------------------------------------------------------
  609. /** True if a response is a Statum directive response. */
  610. function isStatum(res) {
  611. return (res.headers.get('Content-Type') || '').indexOf(STATUM_CONTENT_TYPE) !== -1;
  612. }
  613. /**
  614. * POST an array of frames to the slot endpoint (the pre-flight target) and
  615. * return its directive array. This request intentionally carries no slot
  616. * headers (it is itself the refresh).
  617. * @param {object[]} frames
  618. * @returns {Promise<object[]>}
  619. */
  620. async function postSlots(frames) {
  621. var headers = new Headers();
  622. headers.set('Accept', STATUM_CONTENT_TYPE);
  623. headers.set('Content-Type', 'application/json');
  624. var res = await fetch(config.slotsUrl, {
  625. method: 'POST',
  626. headers: headers,
  627. body: JSON.stringify(frames),
  628. credentials: 'same-origin'
  629. });
  630. if (!isStatum(res)) return [];
  631. try { return await res.json(); } catch (e) { return []; }
  632. }
  633. /**
  634. * Apply the non-terminal directives from a response (set/clear/subscribe/
  635. * unsubscribe/notify/transmit-collection), then `render`.
  636. *
  637. * Terminal directives (`navigate`, `post`), error directives, and any
  638. * transmit/retry intent are collected on the returned result rather than
  639. * executed here: {@link handleResponse} performs the asynchronous
  640. * transmission (and optional retry) and then runs terminal navigation, so
  641. * that a `transmit` with `retry` can re-issue the request before the page is
  642. * navigated away.
  643. * @param {object[]} directives
  644. * @param {{originElement?: HTMLElement}} [ctx]
  645. * @returns {{errors: StatumError[], transmitKeys: string[], retry: boolean, navigate: object|null, post: object|null}}
  646. */
  647. function applyDirectives(directives, ctx) {
  648. var result = { errors: [], transmitKeys: [], retry: false, navigate: null, post: null };
  649. var list = Array.isArray(directives) ? directives : [];
  650. for (var i = 0; i < list.length; i++) {
  651. var d = list[i];
  652. if (!d || typeof d !== 'object') continue;
  653. switch (d.type) {
  654. case 'set': applySet(d); break;
  655. case 'clear': applyClear(d); break;
  656. case 'subscribe': channelSubscribe(d.key); break;
  657. case 'unsubscribe': channelUnsubscribe(d.key); break;
  658. case 'notify': triggerNotify(d.kind, d.message); break;
  659. case 'transmit':
  660. if (d.key != null) {
  661. if (result.transmitKeys.indexOf(d.key) === -1) result.transmitKeys.push(d.key);
  662. if (d.retry) result.retry = true;
  663. }
  664. break;
  665. case 'error': result.errors.push(new StatumError(d.message, d.code, d.data)); break;
  666. case 'navigate': result.navigate = d; break;
  667. case 'post': result.post = d; break;
  668. }
  669. }
  670. renderAll();
  671. return result;
  672. }
  673. /** Execute the terminal navigation directives collected by {@link applyDirectives}. */
  674. function executeTerminal(result) {
  675. if (result.navigate) doNavigate(result.navigate);
  676. if (result.post) doPost(result.post);
  677. }
  678. /** Execute a `navigate` directive as a full page load. */
  679. function doNavigate(d) {
  680. if (d.uri) window.location.href = d.uri;
  681. }
  682. /** Execute a `post` directive as a real (navigating) form POST. */
  683. function doPost(d) {
  684. if (!d.uri) return;
  685. var form = document.createElement('form');
  686. form.method = 'POST';
  687. form.action = d.uri;
  688. form.style.display = 'none';
  689. var data = d.data || {};
  690. Object.keys(data).forEach(function (name) {
  691. var input = document.createElement('input');
  692. input.type = 'hidden';
  693. input.name = name;
  694. input.value = data[name] == null ? '' : String(data[name]);
  695. form.appendChild(input);
  696. });
  697. document.body.appendChild(form);
  698. form.submit();
  699. }
  700. /**
  701. * Handle a fetch response: if it is a Statum response, apply its directives;
  702. * otherwise throw on HTTP errors and no-op on other successful responses.
  703. *
  704. * Directive ordering: non-terminal directives are applied and the page
  705. * rendered; then any `transmit` directives force their slot frames to be
  706. * posted (applying the directives the slot endpoint returns); then, if a
  707. * transmit requested a retry, the originating request (`ctx.retry`) is
  708. * re-issued and this response's terminal directives and errors are skipped.
  709. * Otherwise terminal navigation runs, then error directives are surfaced.
  710. * @param {Response} res
  711. * @param {{originElement?: HTMLElement, retry?: Function}} [ctx]
  712. */
  713. async function handleResponse(res, ctx) {
  714. var el = ctx && ctx.originElement;
  715. if (!isStatum(res)) {
  716. if (!res.ok) await reportFailure(new StatumError('HTTP ' + res.status), el);
  717. return;
  718. }
  719. var directives;
  720. try { directives = await res.json(); } catch (e) { directives = []; }
  721. var result = applyDirectives(directives, ctx);
  722. if (result.transmitKeys && result.transmitKeys.length) {
  723. var frames = collectFramesForKeys(result.transmitKeys);
  724. if (frames.length) {
  725. var txDirectives = await postSlots(frames);
  726. applyDirectives(txDirectives, { originElement: el });
  727. }
  728. }
  729. if (result.retry && ctx && typeof ctx.retry === 'function') {
  730. await ctx.retry();
  731. return;
  732. }
  733. executeTerminal(result);
  734. var errors = result.errors || [];
  735. for (var i = 0; i < errors.length; i++) {
  736. await reportFailure(errors[i], el);
  737. }
  738. }
  739. // ---------------------------------------------------------------------------
  740. // Entrypoint & action requests
  741. // ---------------------------------------------------------------------------
  742. /**
  743. * Fetch the entrypoint for the current URL, applying its directives. Carries
  744. * slot headers (and pre-flights) like any other request. The request is
  745. * wrapped in an `attempt` closure passed as the response `retry` callback, so
  746. * a `transmit` directive with `retry` can re-issue it after transmission.
  747. * @returns {Promise<void>}
  748. */
  749. function loadEntrypoint() {
  750. var attempt = async function () {
  751. await prepareSlots();
  752. var headers = new Headers();
  753. headers.set('Accept', STATUM_CONTENT_TYPE);
  754. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  755. var url = config.entrypointUrl + '?uri=' + encodeURIComponent(window.location.href);
  756. var res = await fetch(url, { headers: headers, credentials: 'same-origin' });
  757. await handleResponse(res, { originElement: null, retry: attempt });
  758. };
  759. return attempt();
  760. }
  761. /**
  762. * Perform an action request.
  763. *
  764. * The request is wrapped in an `attempt` closure passed as the response
  765. * `retry` callback, so a `transmit` directive with `retry` can re-issue the
  766. * same action after the transmission (rebuilding headers from current state).
  767. *
  768. * @param {object} action `{ uri, method, private }`
  769. * @param {object} [data] Key/value parameters. Encoded as query string for
  770. * GET/HEAD, otherwise as `application/x-www-form-urlencoded`.
  771. * @param {HTMLElement} [originElement] Element that triggered the action, so
  772. * that `stm-on-error` classes can be applied on an `error` directive.
  773. * @returns {Promise<void>} Resolves once the request completes and its
  774. * directives have run; rejects on HTTP failure or an `error` directive.
  775. */
  776. function performAction(action, data, originElement) {
  777. var attempt = async function () {
  778. await prepareSlots();
  779. var headers = new Headers();
  780. headers.set('Accept', STATUM_CONTENT_TYPE);
  781. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  782. if (action.private) headers.set(PRIVATE_HEADER, action.private);
  783. var method = (action.method || 'GET').toUpperCase();
  784. var params = data || {};
  785. var init = { method: method, headers: headers, credentials: 'same-origin' };
  786. var url = action.uri;
  787. if (method === 'GET' || method === 'HEAD') {
  788. var qs = new URLSearchParams(params).toString();
  789. if (qs) url += (url.indexOf('?') !== -1 ? '&' : '?') + qs;
  790. } else {
  791. init.body = new URLSearchParams(params).toString();
  792. headers.set('Content-Type', 'application/x-www-form-urlencoded');
  793. }
  794. var res;
  795. try {
  796. res = await fetch(url, init);
  797. } catch (networkErr) {
  798. await reportFailure(new StatumError('Network error'), originElement);
  799. return;
  800. }
  801. await handleResponse(res, { originElement: originElement, retry: attempt });
  802. };
  803. return attempt();
  804. }
  805. // ---------------------------------------------------------------------------
  806. // Realtime channel (subscribe/unsubscribe directives)
  807. // ---------------------------------------------------------------------------
  808. /**
  809. * Per-tab fallback engine, used when `SharedWorker` is unavailable. Owns an
  810. * `EventSource`, reads the channel id from the first `event: channel`,
  811. * reference-counts slot keys within this tab, PATCHes subscription changes,
  812. * applies incoming set/clear events (broadcasting them to siblings), and
  813. * closes the stream once it has no subscriptions.
  814. */
  815. function createFallbackEngine() {
  816. var es = null;
  817. var channelId = null;
  818. var refs = new Map(); // slotKey -> count
  819. var pending = { subscribe: [], unsubscribe: [] };
  820. var patchScheduled = false;
  821. function openStream() {
  822. if (es) return;
  823. try { es = new EventSource(config.channelUrl); }
  824. catch (e) { es = null; return; }
  825. es.addEventListener('channel', function (ev) { channelId = ev.data; flushPatch(); });
  826. es.addEventListener('set', function (ev) {
  827. try { applyRemoteSet(JSON.parse(ev.data)); } catch (e) {}
  828. });
  829. es.addEventListener('clear', function (ev) { applyRemoteClear(ev.data); });
  830. es.onerror = function () { /* EventSource auto-reconnects */ };
  831. }
  832. function closeStream() {
  833. if (es) { try { es.close(); } catch (e) {} es = null; }
  834. channelId = null;
  835. }
  836. function schedulePatch() {
  837. if (patchScheduled) return;
  838. patchScheduled = true;
  839. Promise.resolve().then(function () { patchScheduled = false; flushPatch(); });
  840. }
  841. function flushPatch() {
  842. if (!channelId) return;
  843. var sub = pending.subscribe, uns = pending.unsubscribe;
  844. if (!sub.length && !uns.length) return;
  845. pending = { subscribe: [], unsubscribe: [] };
  846. var body = {};
  847. if (sub.length) body.subscribe = sub;
  848. if (uns.length) body.unsubscribe = uns;
  849. try {
  850. fetch(config.channelUrl + '/' + encodeURIComponent(channelId), {
  851. method: 'PATCH',
  852. headers: { 'Content-Type': 'application/json' },
  853. credentials: 'same-origin',
  854. body: JSON.stringify(body)
  855. }).catch(function () {});
  856. } catch (e) {}
  857. }
  858. return {
  859. subscribe: function (key) {
  860. var c = refs.get(key) || 0;
  861. refs.set(key, c + 1);
  862. if (c === 0) { openStream(); pending.subscribe.push(key); schedulePatch(); }
  863. },
  864. unsubscribe: function (key) {
  865. var c = refs.get(key) || 0;
  866. if (c <= 0) return;
  867. if (c - 1 <= 0) {
  868. refs.delete(key);
  869. pending.unsubscribe.push(key);
  870. schedulePatch();
  871. if (refs.size === 0) setTimeout(function () { if (refs.size === 0) closeStream(); }, 0);
  872. } else {
  873. refs.set(key, c - 1);
  874. }
  875. }
  876. };
  877. }
  878. /**
  879. * Channel manager. Prefers a `SharedWorker` (which owns the single SSE
  880. * connection, reference-counts subscriptions across tabs, and relays events
  881. * through the cross-tab `BroadcastChannel`); falls back to a per-tab
  882. * `EventSource` engine when `SharedWorker` is unavailable or the worker
  883. * script fails to load. Tracks the true per-slot subscription count so it can
  884. * replay active subscriptions into the fallback on a mid-session switch.
  885. */
  886. function createChannelManager() {
  887. var port = null;
  888. var workerObj = null;
  889. var fallback = null;
  890. var mode = null; // 'worker' | 'fallback' | null
  891. var counts = new Map(); // slotKey -> count (true subscription state)
  892. function switchToFallback() {
  893. if (mode === 'fallback') return;
  894. mode = 'fallback';
  895. port = null;
  896. workerObj = null;
  897. fallback = createFallbackEngine();
  898. counts.forEach(function (c, key) {
  899. for (var i = 0; i < c; i++) fallback.subscribe(key);
  900. });
  901. }
  902. function ensure() {
  903. if (mode !== null) return;
  904. if (typeof SharedWorker !== 'undefined') {
  905. try {
  906. workerObj = new SharedWorker(config.workerUrl);
  907. port = workerObj.port;
  908. port.start();
  909. port.postMessage({ op: 'init', url: config.channelUrl });
  910. // The worker delivers events via the BroadcastChannel, so nothing is
  911. // required on this port beyond command messages.
  912. port.onmessage = function () {};
  913. workerObj.onerror = function () {
  914. console.warn('[statum] realtime worker failed; falling back to per-tab channel');
  915. switchToFallback();
  916. };
  917. window.addEventListener('pagehide', function () {
  918. if (mode === 'worker' && port) {
  919. try { port.postMessage({ op: 'disconnect' }); } catch (e) {}
  920. }
  921. });
  922. mode = 'worker';
  923. return;
  924. } catch (e) { workerObj = null; port = null; }
  925. }
  926. switchToFallback();
  927. }
  928. return {
  929. subscribe: function (key) {
  930. if (key == null) return;
  931. ensure();
  932. counts.set(key, (counts.get(key) || 0) + 1);
  933. if (mode === 'worker') { try { port.postMessage({ op: 'subscribe', key: key }); } catch (e) {} }
  934. else fallback.subscribe(key);
  935. },
  936. unsubscribe: function (key) {
  937. if (key == null) return;
  938. var c = (counts.get(key) || 0) - 1;
  939. if (c <= 0) counts.delete(key); else counts.set(key, c);
  940. ensure();
  941. if (mode === 'worker') { try { port.postMessage({ op: 'unsubscribe', key: key }); } catch (e) {} }
  942. else fallback.unsubscribe(key);
  943. }
  944. };
  945. }
  946. var channelManager = createChannelManager();
  947. function channelSubscribe(key) { channelManager.subscribe(key); }
  948. function channelUnsubscribe(key) { channelManager.unsubscribe(key); }
  949. // ---------------------------------------------------------------------------
  950. // Rendering: loops, conditionals, bindings
  951. // ---------------------------------------------------------------------------
  952. /** Templates captured from loop holders. @type {WeakMap<Element, Element>} */
  953. var templates = new WeakMap();
  954. /** Instance nodes managed by a loop holder. @type {WeakMap<Element, Element[]>} */
  955. var instancesByHolder = new WeakMap();
  956. /** Loop instance nodes; skipped by the render walk (owned by their holder). */
  957. var instanceNodes = new WeakSet();
  958. /** Elements whose `stm-action` has been wired, to avoid double-binding. */
  959. var wired = new WeakSet();
  960. /**
  961. * Find a `stm-for-{name}-in` attribute on an element.
  962. * @returns {{varName: string, expr: string}|null}
  963. */
  964. function getStmFor(el) {
  965. var attrs = el.attributes;
  966. for (var i = 0; i < attrs.length; i++) {
  967. var match = attrs[i].name.match(/^stm-for-(.+)-in$/);
  968. if (match) return { varName: match[1], expr: attrs[i].value };
  969. }
  970. return null;
  971. }
  972. /** Remove any `stm-for-*` and `stm-key` attributes from an element. */
  973. function stripLoopAttrs(el) {
  974. var toRemove = [];
  975. for (var i = 0; i < el.attributes.length; i++) {
  976. var name = el.attributes[i].name;
  977. if (/^stm-for-(.+)-in$/.test(name) || name === 'stm-key') toRemove.push(name);
  978. }
  979. toRemove.forEach(function (n) { el.removeAttribute(n); });
  980. }
  981. /**
  982. * Evaluate an `stm-if` / `stm-else-if` / `stm-else` chain beginning at `el`,
  983. * showing the matching branch and hiding the rest.
  984. *
  985. * Branches are toggled with the `hidden` attribute rather than detached, so
  986. * every branch stays in the DOM and is re-evaluated on each render. (Detaching
  987. * the `stm-if` element would remove it from the render walk, leaving an
  988. * already-attached `stm-else` branch skipped and never refreshed.)
  989. * @returns {Element|null} The active branch element (or `null`).
  990. */
  991. function handleIfChain(el, scope) {
  992. var branches = [{ el: el, expr: el.getAttribute('stm-if') }];
  993. var cur = el.nextElementSibling;
  994. while (cur) {
  995. if (cur.hasAttribute('stm-else-if')) {
  996. branches.push({ el: cur, expr: cur.getAttribute('stm-else-if') });
  997. cur = cur.nextElementSibling;
  998. } else if (cur.hasAttribute('stm-else')) {
  999. branches.push({ el: cur, expr: null });
  1000. break;
  1001. } else {
  1002. break;
  1003. }
  1004. }
  1005. var activeEl = null;
  1006. for (var i = 0; i < branches.length; i++) {
  1007. var b = branches[i];
  1008. if (b.expr === null || !!evalExpr(b.expr, scope)) { activeEl = b.el; break; }
  1009. }
  1010. branches.forEach(function (b) {
  1011. if (b.el === activeEl) b.el.removeAttribute('hidden');
  1012. else b.el.setAttribute('hidden', '');
  1013. });
  1014. return activeEl;
  1015. }
  1016. /** Toggle `stm-class.{name}` classes from their predicate expressions. */
  1017. function handleClass(el, scope) {
  1018. var attrs = el.attributes;
  1019. for (var i = 0; i < attrs.length; i++) {
  1020. var attr = attrs[i];
  1021. if (attr.name.indexOf('stm-class.') === 0) {
  1022. var cls = attr.name.slice('stm-class.'.length);
  1023. if (cls && !!evalExpr(attr.value, scope)) el.classList.add(cls);
  1024. else el.classList.remove(cls);
  1025. }
  1026. }
  1027. }
  1028. /**
  1029. * Bind `stm-attribute.{name}`: a boolean result toggles the attribute, any
  1030. * other defined value sets it, and `undefined` removes it.
  1031. *
  1032. * For booleans, prefer the element's IDL property when one exists (e.g.
  1033. * `checked`, `disabled`, `hidden`) — setting the content attribute is
  1034. * unreliable for these once the control is "dirty".
  1035. */
  1036. function handleAttribute(el, scope) {
  1037. var attrs = el.attributes;
  1038. for (var i = 0; i < attrs.length; i++) {
  1039. var attr = attrs[i];
  1040. if (attr.name.indexOf('stm-attribute.') === 0) {
  1041. var name = attr.name.slice('stm-attribute.'.length);
  1042. if (!name) continue;
  1043. var value = evalExpr(attr.value, scope);
  1044. if (value === undefined) {
  1045. el.removeAttribute(name);
  1046. } else if (typeof value === 'boolean') {
  1047. if (name in el && typeof el[name] === 'boolean') el[name] = value;
  1048. else if (value) el.setAttribute(name, '');
  1049. else el.removeAttribute(name);
  1050. } else {
  1051. el.setAttribute(name, value === null ? '' : String(value));
  1052. }
  1053. }
  1054. }
  1055. }
  1056. /**
  1057. * Apply `stm-disabled`: when the predicate is truthy, disable the element and
  1058. * its descendant form controls; otherwise enable them.
  1059. */
  1060. function handleDisabled(el, scope) {
  1061. if (!el.hasAttribute('stm-disabled')) return;
  1062. setDisabledCascade(el, !!evalExpr(el.getAttribute('stm-disabled'), scope));
  1063. }
  1064. /** Set the `disabled` attribute on an element and its descendant controls. */
  1065. function setDisabledCascade(el, on) {
  1066. var nodes = [el].concat(Array.prototype.slice.call(
  1067. el.querySelectorAll('button,input,select,textarea,fieldset')));
  1068. nodes.forEach(function (n) {
  1069. if (on) n.setAttribute('disabled', ''); else n.removeAttribute('disabled');
  1070. });
  1071. }
  1072. /**
  1073. * Bind `stm-text` / `stm-html`. Per the "leave original DOM content" policy,
  1074. * an unresolved value (`undefined`) leaves the element untouched; otherwise
  1075. * the value is stringified (`null` becomes the empty string).
  1076. */
  1077. function handleTextHtml(el, scope) {
  1078. if (el.hasAttribute('stm-text')) {
  1079. var text = evalExpr(el.getAttribute('stm-text'), scope);
  1080. if (text !== undefined) el.textContent = text === null ? '' : String(text);
  1081. }
  1082. if (el.hasAttribute('stm-html')) {
  1083. var html = evalExpr(el.getAttribute('stm-html'), scope);
  1084. if (html !== undefined) el.innerHTML = html === null ? '' : String(html);
  1085. }
  1086. }
  1087. /**
  1088. * Expand a loop holder: reconcile its instances against the current array.
  1089. * Keyed loops (`stm-key`) reuse DOM nodes for unchanged keys to preserve
  1090. * focus/selection/input state; unkeyed loops rebuild wholesale.
  1091. */
  1092. function handleLoop(el, scope) {
  1093. var info = getStmFor(el);
  1094. if (!info) return;
  1095. var template = templates.get(el);
  1096. if (!template) {
  1097. template = el.cloneNode(true);
  1098. stripLoopAttrs(template);
  1099. templates.set(el, template);
  1100. }
  1101. var raw = evalExpr(info.expr, scope);
  1102. if (raw === undefined) {
  1103. // No value for the source path yet: clear instances and restore the
  1104. // server-rendered holder content (progressive enhancement).
  1105. var prev = instancesByHolder.get(el) || [];
  1106. prev.forEach(function (n) { n.remove(); });
  1107. instancesByHolder.set(el, []);
  1108. if (el.getAttribute('data-stm-active') === '1') {
  1109. el.removeAttribute('data-stm-active');
  1110. el.removeAttribute('hidden');
  1111. }
  1112. return;
  1113. }
  1114. var arr = Array.isArray(raw) ? raw : [];
  1115. // Activate: hide the holder so only rendered instances are visible.
  1116. if (el.getAttribute('data-stm-active') !== '1') {
  1117. el.setAttribute('data-stm-active', '1');
  1118. el.setAttribute('hidden', '');
  1119. }
  1120. var keyExpr = el.getAttribute('stm-key');
  1121. var next = [];
  1122. if (keyExpr) {
  1123. var oldByKey = new Map();
  1124. (instancesByHolder.get(el) || []).forEach(function (n) {
  1125. if (n.__stmKey !== undefined) oldByKey.set(n.__stmKey, n);
  1126. });
  1127. var used = new Set();
  1128. arr.forEach(function (item) {
  1129. var child = childScope(scope, info.varName, item);
  1130. var key = evalExpr(keyExpr, child);
  1131. var node = (key !== undefined && !used.has(key)) ? oldByKey.get(key) : undefined;
  1132. if (node) {
  1133. used.add(key);
  1134. processElement(node, child);
  1135. } else {
  1136. node = template.cloneNode(true);
  1137. node.__stmKey = key;
  1138. instanceNodes.add(node);
  1139. processElement(node, child);
  1140. }
  1141. next.push(node);
  1142. });
  1143. oldByKey.forEach(function (n, key) { if (!used.has(key)) n.remove(); });
  1144. } else {
  1145. (instancesByHolder.get(el) || []).forEach(function (n) { n.remove(); });
  1146. arr.forEach(function (item) {
  1147. var child = childScope(scope, info.varName, item);
  1148. var node = template.cloneNode(true);
  1149. instanceNodes.add(node);
  1150. processElement(node, child);
  1151. next.push(node);
  1152. });
  1153. }
  1154. // Place instances in order, immediately after the holder.
  1155. var ref = el;
  1156. next.forEach(function (node) {
  1157. if (node !== ref.nextSibling) ref.parentNode.insertBefore(node, ref.nextSibling);
  1158. ref = node;
  1159. });
  1160. instancesByHolder.set(el, next);
  1161. }
  1162. /**
  1163. * Process one element's bindings (and recurse). Loop holders are handled by
  1164. * {@link handleLoop}; `stm-else-if` / `stm-else` are owned by their `stm-if`.
  1165. */
  1166. function processElement(el, scope) {
  1167. if (getStmFor(el)) { handleLoop(el, scope); return; }
  1168. if (el.hasAttribute('stm-else-if') || el.hasAttribute('stm-else')) return;
  1169. if (el.hasAttribute('stm-if')) {
  1170. var active = handleIfChain(el, scope);
  1171. if (active) processInner(active, scope);
  1172. return;
  1173. }
  1174. processInner(el, scope);
  1175. }
  1176. /**
  1177. * Collect `stm-def-{name}-as` attributes on an element into a child scope.
  1178. * Each expression is evaluated against the incoming scope (so the new
  1179. * variables cannot reference each other within the same element), and the
  1180. * results are added to a child scope visible to the element and its
  1181. * descendants. Multiple defs on one element are supported. If there are no
  1182. * defs, the original scope is returned unchanged.
  1183. * @param {Element} el
  1184. * @param {object} scope
  1185. * @returns {object}
  1186. */
  1187. function applyDefs(el, scope) {
  1188. var attrs = el.attributes;
  1189. var child = null;
  1190. for (var i = 0; i < attrs.length; i++) {
  1191. var name = attrs[i].name;
  1192. if (name.indexOf('stm-def-') === 0 && name.slice(-3) === '-as') {
  1193. var varName = name.slice(8, -3);
  1194. if (!varName) continue;
  1195. if (!child) child = Object.create(scope || null);
  1196. child[varName] = evalExpr(attrs[i].value, scope);
  1197. }
  1198. }
  1199. return child || scope;
  1200. }
  1201. /** Bind the non-control-flow attributes and recurse into children. */
  1202. function processInner(el, scope) {
  1203. var s = applyDefs(el, scope); // local definitions: element + descendants
  1204. el.__stmScope = s; // latest scope, used when an action fires
  1205. handleClass(el, s);
  1206. handleAttribute(el, s);
  1207. handleDisabled(el, s);
  1208. handleTextHtml(el, s);
  1209. wireAction(el);
  1210. render(el, s);
  1211. }
  1212. /**
  1213. * Walk an element's children, processing each. Loop instance nodes are
  1214. * skipped here (they are owned and processed by their holder).
  1215. */
  1216. function render(root, scope) {
  1217. if (!root || !root.children) return;
  1218. // Snapshot the children: processing mutates the DOM (detaching branches,
  1219. // inserting loop instances) and a live HTMLCollection would shift indices.
  1220. var children = Array.prototype.slice.call(root.children);
  1221. for (var i = 0; i < children.length; i++) {
  1222. var el = children[i];
  1223. if (instanceNodes.has(el)) continue;
  1224. processElement(el, scope);
  1225. }
  1226. }
  1227. /** Re-render the whole document against the current state. */
  1228. function renderAll() {
  1229. try { render(document.body, stateScope()); }
  1230. catch (e) { console.error('[statum] render error', e); }
  1231. }
  1232. // ---------------------------------------------------------------------------
  1233. // HTML API: actions
  1234. // ---------------------------------------------------------------------------
  1235. /**
  1236. * Collect data for an action trigger: `stm-data-{key}` attributes plus, for a
  1237. * form, its named inputs.
  1238. * @param {HTMLElement} el
  1239. * @returns {object}
  1240. */
  1241. function collectData(el) {
  1242. var data = {};
  1243. var attrs = el.attributes;
  1244. for (var i = 0; i < attrs.length; i++) {
  1245. var name = attrs[i].name;
  1246. if (name.indexOf('stm-data-') === 0) data[name.slice('stm-data-'.length)] = attrs[i].value;
  1247. }
  1248. if (el.tagName === 'FORM') {
  1249. var fd = new FormData(el);
  1250. fd.forEach(function (value, key) {
  1251. data[key] = value instanceof File ? value.name : String(value);
  1252. });
  1253. }
  1254. return data;
  1255. }
  1256. /**
  1257. * Toggle the busy state of an action element: disables the element and its
  1258. * descendant form controls and applies `stm-busy-class` classes while busy.
  1259. *
  1260. * On un-busy the disabled state is not "restored" to a captured snapshot
  1261. * (that would clobber a `stm-disabled` value that `renderAll` applied during
  1262. * the response); instead the nodes are re-enabled and `stm-disabled` is
  1263. * re-evaluated, which re-disables any that should remain disabled.
  1264. */
  1265. function setBusyState(el, busy) {
  1266. var nodes = [el].concat(Array.prototype.slice.call(
  1267. el.querySelectorAll('button,input,select,textarea,fieldset')));
  1268. var busyClasses = (el.getAttribute('stm-busy-class') || '').split(/\s+/).filter(Boolean);
  1269. if (busy) {
  1270. nodes.forEach(function (n) { n.setAttribute('disabled', ''); });
  1271. busyClasses.forEach(function (c) { el.classList.add(c); });
  1272. } else {
  1273. nodes.forEach(function (n) { n.removeAttribute('disabled'); });
  1274. busyClasses.forEach(function (c) { el.classList.remove(c); });
  1275. reapplyDisabled(el);
  1276. }
  1277. }
  1278. /** Re-apply `stm-disabled` to an element and any descendants that carry it. */
  1279. function reapplyDisabled(el) {
  1280. var scope = el.__stmScope || stateScope();
  1281. if (el.hasAttribute('stm-disabled')) handleDisabled(el, scope);
  1282. var scoped = el.querySelectorAll('[stm-disabled]');
  1283. Array.prototype.forEach.call(scoped, function (n) {
  1284. handleDisabled(n, n.__stmScope || scope);
  1285. });
  1286. }
  1287. /** Apply or remove `stm-on-error` classes on an action element. */
  1288. function applyErrorClasses(el, on) {
  1289. if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
  1290. var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
  1291. classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
  1292. }
  1293. /**
  1294. * Wire an element's primary action once. The listener resolves the action
  1295. * object against the element's latest render scope, so loop instances bind to
  1296. * their own item.
  1297. */
  1298. function wireAction(el) {
  1299. if (!el.hasAttribute('stm-action') || wired.has(el)) return;
  1300. wired.add(el);
  1301. var eventName = el.tagName === 'FORM' ? 'submit' : 'click';
  1302. el.addEventListener(eventName, function (event) {
  1303. event.preventDefault();
  1304. runElementAction(el);
  1305. });
  1306. }
  1307. /**
  1308. * Resolve and perform the action attached to an element, managing busy and
  1309. * error-state classes around the request.
  1310. * @param {HTMLElement} el
  1311. */
  1312. async function runElementAction(el) {
  1313. var scope = el.__stmScope || stateScope();
  1314. var action = evalExpr(el.getAttribute('stm-action'), scope);
  1315. if (!action || typeof action.uri !== 'string') return;
  1316. // stm-confirm: gate the action behind the confirm handler (async-capable,
  1317. // so custom modals are supported).
  1318. if (el.hasAttribute('stm-confirm')) {
  1319. var confirmed = await triggerConfirm(el.getAttribute('stm-confirm'), el);
  1320. if (!confirmed) return;
  1321. }
  1322. applyErrorClasses(el, false); // clear error state on a new attempt
  1323. var data = collectData(el);
  1324. setBusyState(el, true);
  1325. try {
  1326. await performAction(action, data, el);
  1327. } catch (err) {
  1328. // Already handled: stm-on-error classes and the onErrorHandler run inside
  1329. // performAction/reportFailure. Swallow so an HTML-triggered action does
  1330. // not surface as an unhandled rejection.
  1331. } finally {
  1332. setBusyState(el, false);
  1333. }
  1334. }
  1335. // ---------------------------------------------------------------------------
  1336. // Boot visibility (stm-preloader / stm-content)
  1337. // ---------------------------------------------------------------------------
  1338. /**
  1339. * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
  1340. * loading, `stm-preloader` elements are shown and `stm-content` elements
  1341. * hidden; once ready, the reverse.
  1342. *
  1343. * To avoid a flash of un-bound template before the script runs, authors may
  1344. * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
  1345. * `<div stm-content hidden>`); the library removes it once ready. The library
  1346. * also sets `hidden` itself during loading as a fallback for authors who do
  1347. * not pre-set it.
  1348. * @param {boolean} ready
  1349. */
  1350. function setBootState(ready) {
  1351. var preloaders = document.querySelectorAll('[stm-preloader]');
  1352. var contents = document.querySelectorAll('[stm-content]');
  1353. for (var i = 0; i < preloaders.length; i++) {
  1354. ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
  1355. }
  1356. for (var j = 0; j < contents.length; j++) {
  1357. ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
  1358. }
  1359. }
  1360. // ---------------------------------------------------------------------------
  1361. // Public state accessors
  1362. // ---------------------------------------------------------------------------
  1363. /** Build the scope used for expression evaluation: `{ typeName: public }`. */
  1364. function stateScope() {
  1365. var scope = {};
  1366. store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
  1367. return scope;
  1368. }
  1369. /** Read a type's `public` data (what the attributes bind to). */
  1370. function read(type) {
  1371. var entry = store.get(type);
  1372. return entry ? entry.snapshot.public : undefined;
  1373. }
  1374. /** Read a type's full snapshot object. */
  1375. function getSnapshot(type) {
  1376. var entry = store.get(type);
  1377. return entry ? entry.snapshot : undefined;
  1378. }
  1379. /** Read the frame wrapping a type's snapshot. */
  1380. function getFrame(type) {
  1381. var entry = store.get(type);
  1382. return entry ? entry.frame : undefined;
  1383. }
  1384. /** Build an object of `{ typeName: public }` for every held type. */
  1385. function state() {
  1386. var result = {};
  1387. store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
  1388. return result;
  1389. }
  1390. /**
  1391. * Clear state. With a type argument, clears that type only; without, clears
  1392. * all held state.
  1393. * @param {string} [type]
  1394. */
  1395. function clear(type) {
  1396. if (type === undefined) {
  1397. Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
  1398. } else {
  1399. clearType(type, { broadcast: true });
  1400. }
  1401. renderAll();
  1402. }
  1403. /**
  1404. * Perform an action. `action` may be an action object or a string path that
  1405. * resolves to an action object within the current state.
  1406. * @param {object|string} action
  1407. * @param {object} [data]
  1408. * @returns {Promise<void>}
  1409. */
  1410. function act(action, data) {
  1411. var resolved = action;
  1412. if (typeof action === 'string') resolved = evalExpr(action, stateScope());
  1413. if (!resolved || typeof resolved.uri !== 'string') {
  1414. return Promise.reject(new StatumError('Invalid action'));
  1415. }
  1416. return performAction(resolved, data, null);
  1417. }
  1418. /** Attach a state listener for a type. */
  1419. function addStateListener(type, callback) {
  1420. if (typeof callback !== 'function') return;
  1421. if (!listeners.has(type)) listeners.set(type, new Set());
  1422. listeners.get(type).add(callback);
  1423. }
  1424. /** Remove a previously-attached state listener. */
  1425. function removeStateListener(type, callback) {
  1426. var set = listeners.get(type);
  1427. if (!set) return;
  1428. set.delete(callback);
  1429. if (set.size === 0) listeners.delete(type);
  1430. }
  1431. // ---------------------------------------------------------------------------
  1432. // Initialization
  1433. // ---------------------------------------------------------------------------
  1434. /**
  1435. * Scan the document for `pstm-*` attributes and `<pstm-*>` elements, which
  1436. * are intended for server-side pre-rendering and should never reach the
  1437. * browser. Emits a single `console.warn` summarizing them.
  1438. */
  1439. function warnServerSideMarkup() {
  1440. var found = [];
  1441. var els = document.querySelectorAll('*');
  1442. for (var i = 0; i < els.length; i++) {
  1443. var el = els[i];
  1444. var tag = el.tagName.toLowerCase();
  1445. if (tag.indexOf('pstm-') === 0) found.push('<' + tag + '>');
  1446. var attrs = el.attributes;
  1447. for (var j = 0; j < attrs.length; j++) {
  1448. var name = attrs[j].name;
  1449. if (name.indexOf('pstm-') === 0) found.push('<' + tag + '> ' + name);
  1450. }
  1451. }
  1452. if (found.length) {
  1453. console.warn('[statum] ' + found.length + ' server-side pstm-* attribute/element(s) ' +
  1454. 'found in the DOM; they should have been resolved during pre-rendering: ' +
  1455. found.slice(0, 10).join(', ') + (found.length > 10 ? ' …' : ''));
  1456. }
  1457. }
  1458. /**
  1459. * Initialize Statum: read URL overrides, run the session-cookie check,
  1460. * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
  1461. * and render. Safe to call multiple times.
  1462. * @returns {Promise<void>}
  1463. */
  1464. async function init() {
  1465. if (initialized) return;
  1466. initialized = true;
  1467. var body = document.body;
  1468. if (body) {
  1469. if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
  1470. if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
  1471. if (body.hasAttribute('stm-channel')) config.channelUrl = body.getAttribute('stm-channel');
  1472. if (body.hasAttribute('stm-worker')) config.workerUrl = body.getAttribute('stm-worker');
  1473. }
  1474. try { warnServerSideMarkup(); } catch (e) {}
  1475. try { initSession(); } catch (e) {}
  1476. try { hydrate(); } catch (e) {}
  1477. setupChannel();
  1478. setBootState(false);
  1479. renderAll(); // bind against any persisted/hydrated state immediately
  1480. try {
  1481. await loadEntrypoint();
  1482. } catch (err) {
  1483. console.error('[statum] entrypoint load failed', err);
  1484. } finally {
  1485. setBootState(true);
  1486. }
  1487. }
  1488. function autoInit() {
  1489. if (document.readyState === 'loading') {
  1490. document.addEventListener('DOMContentLoaded', init);
  1491. } else {
  1492. init();
  1493. }
  1494. }
  1495. // ---------------------------------------------------------------------------
  1496. // Public API
  1497. // ---------------------------------------------------------------------------
  1498. /** @namespace statum */
  1499. window.statum = {
  1500. /** Library version. */
  1501. version: '0.1.0',
  1502. /** Mutable endpoint configuration. */
  1503. config: config,
  1504. /** (Re)initialize the library. Usually runs automatically on load. */
  1505. init: init,
  1506. /** Read a type's `public` data. */
  1507. read: read,
  1508. /** Read a type's full snapshot object. */
  1509. getSnapshot: getSnapshot,
  1510. /** Read the frame wrapping a type's snapshot. */
  1511. getFrame: getFrame,
  1512. /** Build `{ typeName: public }` for every held type. */
  1513. state: state,
  1514. /** Clear one type (`clear("x")`) or all state (`clear()`). */
  1515. clear: clear,
  1516. /** Perform an action object or named action. */
  1517. act: act,
  1518. /** Attach a state-changed listener for a type. */
  1519. addStateListener: addStateListener,
  1520. /** Remove a previously-attached listener. */
  1521. removeStateListener: removeStateListener,
  1522. /** The Statum error type (thrown by `act` and surfaced to handlers). */
  1523. Error: StatumError,
  1524. get onConfirmHandler() { return handlers.onConfirm; },
  1525. set onConfirmHandler(v) { handlers.onConfirm = typeof v === 'function' ? v : null; },
  1526. get onNotifyHandler() { return handlers.onNotify; },
  1527. set onNotifyHandler(v) { handlers.onNotify = typeof v === 'function' ? v : null; },
  1528. get onErrorHandler() { return handlers.onError; },
  1529. set onErrorHandler(v) { handlers.onError = typeof v === 'function' ? v : null; }
  1530. };
  1531. autoInit();
  1532. })();