statum.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  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. applyDirectives(directives, { originElement: null });
  563. }
  564. }
  565. /**
  566. * Build the `X-Statum-Slot` header values for every held slot, using the
  567. * freshness rules. Assumes {@link prepareSlots} has just run.
  568. * @returns {string[]}
  569. */
  570. function buildSlotHeaders() {
  571. var headers = [];
  572. store.forEach(function (entry) {
  573. var snap = entry.snapshot;
  574. var cat = entryCategory(entry);
  575. if (cat === 'silent' || cat === 'invalid') return;
  576. if (cat === 'always') {
  577. headers.push(b64encode(JSON.stringify(entry.frame)));
  578. } else {
  579. headers.push('key=' + snap.slot.key + '; as_at=' + snap.as_at);
  580. }
  581. });
  582. return headers;
  583. }
  584. // ---------------------------------------------------------------------------
  585. // HTTP helpers
  586. // ---------------------------------------------------------------------------
  587. /** True if a response is a Statum directive response. */
  588. function isStatum(res) {
  589. return (res.headers.get('Content-Type') || '').indexOf(STATUM_CONTENT_TYPE) !== -1;
  590. }
  591. /**
  592. * POST an array of frames to the slot endpoint (the pre-flight target) and
  593. * return its directive array. This request intentionally carries no slot
  594. * headers (it is itself the refresh).
  595. * @param {object[]} frames
  596. * @returns {Promise<object[]>}
  597. */
  598. async function postSlots(frames) {
  599. var headers = new Headers();
  600. headers.set('Accept', STATUM_CONTENT_TYPE);
  601. headers.set('Content-Type', 'application/json');
  602. var res = await fetch(config.slotsUrl, {
  603. method: 'POST',
  604. headers: headers,
  605. body: JSON.stringify(frames),
  606. credentials: 'same-origin'
  607. });
  608. if (!isStatum(res)) return [];
  609. try { return await res.json(); } catch (e) { return []; }
  610. }
  611. /**
  612. * Apply the directives from a response. set/clear/subscribe/unsubscribe/notify
  613. * run first, then `render`, then terminal navigation (`navigate`, then `post`).
  614. * Error directives are collected (not thrown) so the caller can route them
  615. * through `reportFailure` (and thus `onErrorHandler`).
  616. * @param {object[]} directives
  617. * @param {{originElement?: HTMLElement}} [ctx]
  618. * @returns {{errors: StatumError[]}}
  619. */
  620. function applyDirectives(directives, ctx) {
  621. var result = { errors: [] };
  622. var list = Array.isArray(directives) ? directives : [];
  623. var navigateDirective = null;
  624. var postDirective = null;
  625. for (var i = 0; i < list.length; i++) {
  626. var d = list[i];
  627. if (!d || typeof d !== 'object') continue;
  628. switch (d.type) {
  629. case 'set': applySet(d); break;
  630. case 'clear': applyClear(d); break;
  631. case 'subscribe': channelSubscribe(d.key); break;
  632. case 'unsubscribe': channelUnsubscribe(d.key); break;
  633. case 'notify': triggerNotify(d.kind, d.message); break;
  634. case 'error': result.errors.push(new StatumError(d.message, d.code, d.data)); break;
  635. case 'navigate': navigateDirective = d; break;
  636. case 'post': postDirective = d; break;
  637. }
  638. }
  639. renderAll();
  640. if (navigateDirective) doNavigate(navigateDirective);
  641. if (postDirective) doPost(postDirective);
  642. return result;
  643. }
  644. /** Execute a `navigate` directive as a full page load. */
  645. function doNavigate(d) {
  646. if (d.uri) window.location.href = d.uri;
  647. }
  648. /** Execute a `post` directive as a real (navigating) form POST. */
  649. function doPost(d) {
  650. if (!d.uri) return;
  651. var form = document.createElement('form');
  652. form.method = 'POST';
  653. form.action = d.uri;
  654. form.style.display = 'none';
  655. var data = d.data || {};
  656. Object.keys(data).forEach(function (name) {
  657. var input = document.createElement('input');
  658. input.type = 'hidden';
  659. input.name = name;
  660. input.value = data[name] == null ? '' : String(data[name]);
  661. form.appendChild(input);
  662. });
  663. document.body.appendChild(form);
  664. form.submit();
  665. }
  666. /**
  667. * Handle a fetch response: if it is a Statum response, apply its directives;
  668. * otherwise throw on HTTP errors and no-op on other successful responses.
  669. * @param {Response} res
  670. * @param {{originElement?: HTMLElement}} [ctx]
  671. */
  672. async function handleResponse(res, ctx) {
  673. var el = ctx && ctx.originElement;
  674. if (!isStatum(res)) {
  675. if (!res.ok) await reportFailure(new StatumError('HTTP ' + res.status), el);
  676. return;
  677. }
  678. var directives;
  679. try { directives = await res.json(); } catch (e) { directives = []; }
  680. var result = applyDirectives(directives, ctx);
  681. var errors = result.errors || [];
  682. for (var i = 0; i < errors.length; i++) {
  683. await reportFailure(errors[i], el);
  684. }
  685. }
  686. // ---------------------------------------------------------------------------
  687. // Entrypoint & action requests
  688. // ---------------------------------------------------------------------------
  689. /**
  690. * Fetch the entrypoint for the current URL, applying its directives. Carries
  691. * slot headers (and pre-flights) like any other request.
  692. * @returns {Promise<void>}
  693. */
  694. async function loadEntrypoint() {
  695. await prepareSlots();
  696. var headers = new Headers();
  697. headers.set('Accept', STATUM_CONTENT_TYPE);
  698. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  699. var url = config.entrypointUrl + '?uri=' + encodeURIComponent(window.location.href);
  700. var res = await fetch(url, { headers: headers, credentials: 'same-origin' });
  701. await handleResponse(res, { originElement: null });
  702. }
  703. /**
  704. * Perform an action request.
  705. *
  706. * @param {object} action `{ uri, method, private }`
  707. * @param {object} [data] Key/value parameters. Encoded as query string for
  708. * GET/HEAD, otherwise as `application/x-www-form-urlencoded`.
  709. * @param {HTMLElement} [originElement] Element that triggered the action, so
  710. * that `stm-on-error` classes can be applied on an `error` directive.
  711. * @returns {Promise<void>} Resolves once the request completes and its
  712. * directives have run; rejects on HTTP failure or an `error` directive.
  713. */
  714. async function performAction(action, data, originElement) {
  715. await prepareSlots();
  716. var headers = new Headers();
  717. headers.set('Accept', STATUM_CONTENT_TYPE);
  718. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  719. if (action.private) headers.set(PRIVATE_HEADER, action.private);
  720. var method = (action.method || 'GET').toUpperCase();
  721. var params = data || {};
  722. var init = { method: method, headers: headers, credentials: 'same-origin' };
  723. var url = action.uri;
  724. if (method === 'GET' || method === 'HEAD') {
  725. var qs = new URLSearchParams(params).toString();
  726. if (qs) url += (url.indexOf('?') !== -1 ? '&' : '?') + qs;
  727. } else {
  728. init.body = new URLSearchParams(params).toString();
  729. headers.set('Content-Type', 'application/x-www-form-urlencoded');
  730. }
  731. var res;
  732. try {
  733. res = await fetch(url, init);
  734. } catch (networkErr) {
  735. await reportFailure(new StatumError('Network error'), originElement);
  736. return;
  737. }
  738. await handleResponse(res, { originElement: originElement });
  739. }
  740. // ---------------------------------------------------------------------------
  741. // Realtime channel (subscribe/unsubscribe directives)
  742. // ---------------------------------------------------------------------------
  743. /**
  744. * Per-tab fallback engine, used when `SharedWorker` is unavailable. Owns an
  745. * `EventSource`, reads the channel id from the first `event: channel`,
  746. * reference-counts slot keys within this tab, PATCHes subscription changes,
  747. * applies incoming set/clear events (broadcasting them to siblings), and
  748. * closes the stream once it has no subscriptions.
  749. */
  750. function createFallbackEngine() {
  751. var es = null;
  752. var channelId = null;
  753. var refs = new Map(); // slotKey -> count
  754. var pending = { subscribe: [], unsubscribe: [] };
  755. var patchScheduled = false;
  756. function openStream() {
  757. if (es) return;
  758. try { es = new EventSource(config.channelUrl); }
  759. catch (e) { es = null; return; }
  760. es.addEventListener('channel', function (ev) { channelId = ev.data; flushPatch(); });
  761. es.addEventListener('set', function (ev) {
  762. try { applyRemoteSet(JSON.parse(ev.data)); } catch (e) {}
  763. });
  764. es.addEventListener('clear', function (ev) { applyRemoteClear(ev.data); });
  765. es.onerror = function () { /* EventSource auto-reconnects */ };
  766. }
  767. function closeStream() {
  768. if (es) { try { es.close(); } catch (e) {} es = null; }
  769. channelId = null;
  770. }
  771. function schedulePatch() {
  772. if (patchScheduled) return;
  773. patchScheduled = true;
  774. Promise.resolve().then(function () { patchScheduled = false; flushPatch(); });
  775. }
  776. function flushPatch() {
  777. if (!channelId) return;
  778. var sub = pending.subscribe, uns = pending.unsubscribe;
  779. if (!sub.length && !uns.length) return;
  780. pending = { subscribe: [], unsubscribe: [] };
  781. var body = {};
  782. if (sub.length) body.subscribe = sub;
  783. if (uns.length) body.unsubscribe = uns;
  784. try {
  785. fetch(config.channelUrl + '/' + encodeURIComponent(channelId), {
  786. method: 'PATCH',
  787. headers: { 'Content-Type': 'application/json' },
  788. credentials: 'same-origin',
  789. body: JSON.stringify(body)
  790. }).catch(function () {});
  791. } catch (e) {}
  792. }
  793. return {
  794. subscribe: function (key) {
  795. var c = refs.get(key) || 0;
  796. refs.set(key, c + 1);
  797. if (c === 0) { openStream(); pending.subscribe.push(key); schedulePatch(); }
  798. },
  799. unsubscribe: function (key) {
  800. var c = refs.get(key) || 0;
  801. if (c <= 0) return;
  802. if (c - 1 <= 0) {
  803. refs.delete(key);
  804. pending.unsubscribe.push(key);
  805. schedulePatch();
  806. if (refs.size === 0) setTimeout(function () { if (refs.size === 0) closeStream(); }, 0);
  807. } else {
  808. refs.set(key, c - 1);
  809. }
  810. }
  811. };
  812. }
  813. /**
  814. * Channel manager. Prefers a `SharedWorker` (which owns the single SSE
  815. * connection, reference-counts subscriptions across tabs, and relays events
  816. * through the cross-tab `BroadcastChannel`); falls back to a per-tab
  817. * `EventSource` engine when `SharedWorker` is unavailable or the worker
  818. * script fails to load. Tracks the true per-slot subscription count so it can
  819. * replay active subscriptions into the fallback on a mid-session switch.
  820. */
  821. function createChannelManager() {
  822. var port = null;
  823. var workerObj = null;
  824. var fallback = null;
  825. var mode = null; // 'worker' | 'fallback' | null
  826. var counts = new Map(); // slotKey -> count (true subscription state)
  827. function switchToFallback() {
  828. if (mode === 'fallback') return;
  829. mode = 'fallback';
  830. port = null;
  831. workerObj = null;
  832. fallback = createFallbackEngine();
  833. counts.forEach(function (c, key) {
  834. for (var i = 0; i < c; i++) fallback.subscribe(key);
  835. });
  836. }
  837. function ensure() {
  838. if (mode !== null) return;
  839. if (typeof SharedWorker !== 'undefined') {
  840. try {
  841. workerObj = new SharedWorker(config.workerUrl);
  842. port = workerObj.port;
  843. port.start();
  844. port.postMessage({ op: 'init', url: config.channelUrl });
  845. // The worker delivers events via the BroadcastChannel, so nothing is
  846. // required on this port beyond command messages.
  847. port.onmessage = function () {};
  848. workerObj.onerror = function () {
  849. console.warn('[statum] realtime worker failed; falling back to per-tab channel');
  850. switchToFallback();
  851. };
  852. window.addEventListener('pagehide', function () {
  853. if (mode === 'worker' && port) {
  854. try { port.postMessage({ op: 'disconnect' }); } catch (e) {}
  855. }
  856. });
  857. mode = 'worker';
  858. return;
  859. } catch (e) { workerObj = null; port = null; }
  860. }
  861. switchToFallback();
  862. }
  863. return {
  864. subscribe: function (key) {
  865. if (key == null) return;
  866. ensure();
  867. counts.set(key, (counts.get(key) || 0) + 1);
  868. if (mode === 'worker') { try { port.postMessage({ op: 'subscribe', key: key }); } catch (e) {} }
  869. else fallback.subscribe(key);
  870. },
  871. unsubscribe: function (key) {
  872. if (key == null) return;
  873. var c = (counts.get(key) || 0) - 1;
  874. if (c <= 0) counts.delete(key); else counts.set(key, c);
  875. ensure();
  876. if (mode === 'worker') { try { port.postMessage({ op: 'unsubscribe', key: key }); } catch (e) {} }
  877. else fallback.unsubscribe(key);
  878. }
  879. };
  880. }
  881. var channelManager = createChannelManager();
  882. function channelSubscribe(key) { channelManager.subscribe(key); }
  883. function channelUnsubscribe(key) { channelManager.unsubscribe(key); }
  884. // ---------------------------------------------------------------------------
  885. // Rendering: loops, conditionals, bindings
  886. // ---------------------------------------------------------------------------
  887. /** Templates captured from loop holders. @type {WeakMap<Element, Element>} */
  888. var templates = new WeakMap();
  889. /** Instance nodes managed by a loop holder. @type {WeakMap<Element, Element[]>} */
  890. var instancesByHolder = new WeakMap();
  891. /** Loop instance nodes; skipped by the render walk (owned by their holder). */
  892. var instanceNodes = new WeakSet();
  893. /** Elements whose `stm-action` has been wired, to avoid double-binding. */
  894. var wired = new WeakSet();
  895. /**
  896. * Find a `stm-for-{name}-in` attribute on an element.
  897. * @returns {{varName: string, expr: string}|null}
  898. */
  899. function getStmFor(el) {
  900. var attrs = el.attributes;
  901. for (var i = 0; i < attrs.length; i++) {
  902. var match = attrs[i].name.match(/^stm-for-(.+)-in$/);
  903. if (match) return { varName: match[1], expr: attrs[i].value };
  904. }
  905. return null;
  906. }
  907. /** Remove any `stm-for-*` and `stm-key` attributes from an element. */
  908. function stripLoopAttrs(el) {
  909. var toRemove = [];
  910. for (var i = 0; i < el.attributes.length; i++) {
  911. var name = el.attributes[i].name;
  912. if (/^stm-for-(.+)-in$/.test(name) || name === 'stm-key') toRemove.push(name);
  913. }
  914. toRemove.forEach(function (n) { el.removeAttribute(n); });
  915. }
  916. /**
  917. * Evaluate an `stm-if` / `stm-else-if` / `stm-else` chain beginning at `el`,
  918. * showing the matching branch and hiding the rest.
  919. *
  920. * Branches are toggled with the `hidden` attribute rather than detached, so
  921. * every branch stays in the DOM and is re-evaluated on each render. (Detaching
  922. * the `stm-if` element would remove it from the render walk, leaving an
  923. * already-attached `stm-else` branch skipped and never refreshed.)
  924. * @returns {Element|null} The active branch element (or `null`).
  925. */
  926. function handleIfChain(el, scope) {
  927. var branches = [{ el: el, expr: el.getAttribute('stm-if') }];
  928. var cur = el.nextElementSibling;
  929. while (cur) {
  930. if (cur.hasAttribute('stm-else-if')) {
  931. branches.push({ el: cur, expr: cur.getAttribute('stm-else-if') });
  932. cur = cur.nextElementSibling;
  933. } else if (cur.hasAttribute('stm-else')) {
  934. branches.push({ el: cur, expr: null });
  935. break;
  936. } else {
  937. break;
  938. }
  939. }
  940. var activeEl = null;
  941. for (var i = 0; i < branches.length; i++) {
  942. var b = branches[i];
  943. if (b.expr === null || !!evalExpr(b.expr, scope)) { activeEl = b.el; break; }
  944. }
  945. branches.forEach(function (b) {
  946. if (b.el === activeEl) b.el.removeAttribute('hidden');
  947. else b.el.setAttribute('hidden', '');
  948. });
  949. return activeEl;
  950. }
  951. /** Toggle `stm-class.{name}` classes from their predicate expressions. */
  952. function handleClass(el, scope) {
  953. var attrs = el.attributes;
  954. for (var i = 0; i < attrs.length; i++) {
  955. var attr = attrs[i];
  956. if (attr.name.indexOf('stm-class.') === 0) {
  957. var cls = attr.name.slice('stm-class.'.length);
  958. if (cls && !!evalExpr(attr.value, scope)) el.classList.add(cls);
  959. else el.classList.remove(cls);
  960. }
  961. }
  962. }
  963. /**
  964. * Bind `stm-attribute.{name}`: a boolean result toggles the attribute, any
  965. * other defined value sets it, and `undefined` removes it.
  966. *
  967. * For booleans, prefer the element's IDL property when one exists (e.g.
  968. * `checked`, `disabled`, `hidden`) — setting the content attribute is
  969. * unreliable for these once the control is "dirty".
  970. */
  971. function handleAttribute(el, scope) {
  972. var attrs = el.attributes;
  973. for (var i = 0; i < attrs.length; i++) {
  974. var attr = attrs[i];
  975. if (attr.name.indexOf('stm-attribute.') === 0) {
  976. var name = attr.name.slice('stm-attribute.'.length);
  977. if (!name) continue;
  978. var value = evalExpr(attr.value, scope);
  979. if (value === undefined) {
  980. el.removeAttribute(name);
  981. } else if (typeof value === 'boolean') {
  982. if (name in el && typeof el[name] === 'boolean') el[name] = value;
  983. else if (value) el.setAttribute(name, '');
  984. else el.removeAttribute(name);
  985. } else {
  986. el.setAttribute(name, value === null ? '' : String(value));
  987. }
  988. }
  989. }
  990. }
  991. /**
  992. * Apply `stm-disabled`: when the predicate is truthy, disable the element and
  993. * its descendant form controls; otherwise enable them.
  994. */
  995. function handleDisabled(el, scope) {
  996. if (!el.hasAttribute('stm-disabled')) return;
  997. setDisabledCascade(el, !!evalExpr(el.getAttribute('stm-disabled'), scope));
  998. }
  999. /** Set the `disabled` attribute on an element and its descendant controls. */
  1000. function setDisabledCascade(el, on) {
  1001. var nodes = [el].concat(Array.prototype.slice.call(
  1002. el.querySelectorAll('button,input,select,textarea,fieldset')));
  1003. nodes.forEach(function (n) {
  1004. if (on) n.setAttribute('disabled', ''); else n.removeAttribute('disabled');
  1005. });
  1006. }
  1007. /**
  1008. * Bind `stm-text` / `stm-html`. Per the "leave original DOM content" policy,
  1009. * an unresolved value (`undefined`) leaves the element untouched; otherwise
  1010. * the value is stringified (`null` becomes the empty string).
  1011. */
  1012. function handleTextHtml(el, scope) {
  1013. if (el.hasAttribute('stm-text')) {
  1014. var text = evalExpr(el.getAttribute('stm-text'), scope);
  1015. if (text !== undefined) el.textContent = text === null ? '' : String(text);
  1016. }
  1017. if (el.hasAttribute('stm-html')) {
  1018. var html = evalExpr(el.getAttribute('stm-html'), scope);
  1019. if (html !== undefined) el.innerHTML = html === null ? '' : String(html);
  1020. }
  1021. }
  1022. /**
  1023. * Expand a loop holder: reconcile its instances against the current array.
  1024. * Keyed loops (`stm-key`) reuse DOM nodes for unchanged keys to preserve
  1025. * focus/selection/input state; unkeyed loops rebuild wholesale.
  1026. */
  1027. function handleLoop(el, scope) {
  1028. var info = getStmFor(el);
  1029. if (!info) return;
  1030. var template = templates.get(el);
  1031. if (!template) {
  1032. template = el.cloneNode(true);
  1033. stripLoopAttrs(template);
  1034. templates.set(el, template);
  1035. }
  1036. var raw = evalExpr(info.expr, scope);
  1037. if (raw === undefined) {
  1038. // No value for the source path yet: clear instances and restore the
  1039. // server-rendered holder content (progressive enhancement).
  1040. var prev = instancesByHolder.get(el) || [];
  1041. prev.forEach(function (n) { n.remove(); });
  1042. instancesByHolder.set(el, []);
  1043. if (el.getAttribute('data-stm-active') === '1') {
  1044. el.removeAttribute('data-stm-active');
  1045. el.removeAttribute('hidden');
  1046. }
  1047. return;
  1048. }
  1049. var arr = Array.isArray(raw) ? raw : [];
  1050. // Activate: hide the holder so only rendered instances are visible.
  1051. if (el.getAttribute('data-stm-active') !== '1') {
  1052. el.setAttribute('data-stm-active', '1');
  1053. el.setAttribute('hidden', '');
  1054. }
  1055. var keyExpr = el.getAttribute('stm-key');
  1056. var next = [];
  1057. if (keyExpr) {
  1058. var oldByKey = new Map();
  1059. (instancesByHolder.get(el) || []).forEach(function (n) {
  1060. if (n.__stmKey !== undefined) oldByKey.set(n.__stmKey, n);
  1061. });
  1062. var used = new Set();
  1063. arr.forEach(function (item) {
  1064. var child = childScope(scope, info.varName, item);
  1065. var key = evalExpr(keyExpr, child);
  1066. var node = (key !== undefined && !used.has(key)) ? oldByKey.get(key) : undefined;
  1067. if (node) {
  1068. used.add(key);
  1069. processElement(node, child);
  1070. } else {
  1071. node = template.cloneNode(true);
  1072. node.__stmKey = key;
  1073. instanceNodes.add(node);
  1074. processElement(node, child);
  1075. }
  1076. next.push(node);
  1077. });
  1078. oldByKey.forEach(function (n, key) { if (!used.has(key)) n.remove(); });
  1079. } else {
  1080. (instancesByHolder.get(el) || []).forEach(function (n) { n.remove(); });
  1081. arr.forEach(function (item) {
  1082. var child = childScope(scope, info.varName, item);
  1083. var node = template.cloneNode(true);
  1084. instanceNodes.add(node);
  1085. processElement(node, child);
  1086. next.push(node);
  1087. });
  1088. }
  1089. // Place instances in order, immediately after the holder.
  1090. var ref = el;
  1091. next.forEach(function (node) {
  1092. if (node !== ref.nextSibling) ref.parentNode.insertBefore(node, ref.nextSibling);
  1093. ref = node;
  1094. });
  1095. instancesByHolder.set(el, next);
  1096. }
  1097. /**
  1098. * Process one element's bindings (and recurse). Loop holders are handled by
  1099. * {@link handleLoop}; `stm-else-if` / `stm-else` are owned by their `stm-if`.
  1100. */
  1101. function processElement(el, scope) {
  1102. if (getStmFor(el)) { handleLoop(el, scope); return; }
  1103. if (el.hasAttribute('stm-else-if') || el.hasAttribute('stm-else')) return;
  1104. if (el.hasAttribute('stm-if')) {
  1105. var active = handleIfChain(el, scope);
  1106. if (active) processInner(active, scope);
  1107. return;
  1108. }
  1109. processInner(el, scope);
  1110. }
  1111. /**
  1112. * Collect `stm-def-{name}-as` attributes on an element into a child scope.
  1113. * Each expression is evaluated against the incoming scope (so the new
  1114. * variables cannot reference each other within the same element), and the
  1115. * results are added to a child scope visible to the element and its
  1116. * descendants. Multiple defs on one element are supported. If there are no
  1117. * defs, the original scope is returned unchanged.
  1118. * @param {Element} el
  1119. * @param {object} scope
  1120. * @returns {object}
  1121. */
  1122. function applyDefs(el, scope) {
  1123. var attrs = el.attributes;
  1124. var child = null;
  1125. for (var i = 0; i < attrs.length; i++) {
  1126. var name = attrs[i].name;
  1127. if (name.indexOf('stm-def-') === 0 && name.slice(-3) === '-as') {
  1128. var varName = name.slice(8, -3);
  1129. if (!varName) continue;
  1130. if (!child) child = Object.create(scope || null);
  1131. child[varName] = evalExpr(attrs[i].value, scope);
  1132. }
  1133. }
  1134. return child || scope;
  1135. }
  1136. /** Bind the non-control-flow attributes and recurse into children. */
  1137. function processInner(el, scope) {
  1138. var s = applyDefs(el, scope); // local definitions: element + descendants
  1139. el.__stmScope = s; // latest scope, used when an action fires
  1140. handleClass(el, s);
  1141. handleAttribute(el, s);
  1142. handleDisabled(el, s);
  1143. handleTextHtml(el, s);
  1144. wireAction(el);
  1145. render(el, s);
  1146. }
  1147. /**
  1148. * Walk an element's children, processing each. Loop instance nodes are
  1149. * skipped here (they are owned and processed by their holder).
  1150. */
  1151. function render(root, scope) {
  1152. if (!root || !root.children) return;
  1153. // Snapshot the children: processing mutates the DOM (detaching branches,
  1154. // inserting loop instances) and a live HTMLCollection would shift indices.
  1155. var children = Array.prototype.slice.call(root.children);
  1156. for (var i = 0; i < children.length; i++) {
  1157. var el = children[i];
  1158. if (instanceNodes.has(el)) continue;
  1159. processElement(el, scope);
  1160. }
  1161. }
  1162. /** Re-render the whole document against the current state. */
  1163. function renderAll() {
  1164. try { render(document.body, stateScope()); }
  1165. catch (e) { console.error('[statum] render error', e); }
  1166. }
  1167. // ---------------------------------------------------------------------------
  1168. // HTML API: actions
  1169. // ---------------------------------------------------------------------------
  1170. /**
  1171. * Collect data for an action trigger: `stm-data-{key}` attributes plus, for a
  1172. * form, its named inputs.
  1173. * @param {HTMLElement} el
  1174. * @returns {object}
  1175. */
  1176. function collectData(el) {
  1177. var data = {};
  1178. var attrs = el.attributes;
  1179. for (var i = 0; i < attrs.length; i++) {
  1180. var name = attrs[i].name;
  1181. if (name.indexOf('stm-data-') === 0) data[name.slice('stm-data-'.length)] = attrs[i].value;
  1182. }
  1183. if (el.tagName === 'FORM') {
  1184. var fd = new FormData(el);
  1185. fd.forEach(function (value, key) {
  1186. data[key] = value instanceof File ? value.name : String(value);
  1187. });
  1188. }
  1189. return data;
  1190. }
  1191. /**
  1192. * Toggle the busy state of an action element: disables the element and its
  1193. * descendant form controls and applies `stm-busy-class` classes while busy.
  1194. *
  1195. * On un-busy the disabled state is not "restored" to a captured snapshot
  1196. * (that would clobber a `stm-disabled` value that `renderAll` applied during
  1197. * the response); instead the nodes are re-enabled and `stm-disabled` is
  1198. * re-evaluated, which re-disables any that should remain disabled.
  1199. */
  1200. function setBusyState(el, busy) {
  1201. var nodes = [el].concat(Array.prototype.slice.call(
  1202. el.querySelectorAll('button,input,select,textarea,fieldset')));
  1203. var busyClasses = (el.getAttribute('stm-busy-class') || '').split(/\s+/).filter(Boolean);
  1204. if (busy) {
  1205. nodes.forEach(function (n) { n.setAttribute('disabled', ''); });
  1206. busyClasses.forEach(function (c) { el.classList.add(c); });
  1207. } else {
  1208. nodes.forEach(function (n) { n.removeAttribute('disabled'); });
  1209. busyClasses.forEach(function (c) { el.classList.remove(c); });
  1210. reapplyDisabled(el);
  1211. }
  1212. }
  1213. /** Re-apply `stm-disabled` to an element and any descendants that carry it. */
  1214. function reapplyDisabled(el) {
  1215. var scope = el.__stmScope || stateScope();
  1216. if (el.hasAttribute('stm-disabled')) handleDisabled(el, scope);
  1217. var scoped = el.querySelectorAll('[stm-disabled]');
  1218. Array.prototype.forEach.call(scoped, function (n) {
  1219. handleDisabled(n, n.__stmScope || scope);
  1220. });
  1221. }
  1222. /** Apply or remove `stm-on-error` classes on an action element. */
  1223. function applyErrorClasses(el, on) {
  1224. if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
  1225. var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
  1226. classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
  1227. }
  1228. /**
  1229. * Wire an element's primary action once. The listener resolves the action
  1230. * object against the element's latest render scope, so loop instances bind to
  1231. * their own item.
  1232. */
  1233. function wireAction(el) {
  1234. if (!el.hasAttribute('stm-action') || wired.has(el)) return;
  1235. wired.add(el);
  1236. var eventName = el.tagName === 'FORM' ? 'submit' : 'click';
  1237. el.addEventListener(eventName, function (event) {
  1238. event.preventDefault();
  1239. runElementAction(el);
  1240. });
  1241. }
  1242. /**
  1243. * Resolve and perform the action attached to an element, managing busy and
  1244. * error-state classes around the request.
  1245. * @param {HTMLElement} el
  1246. */
  1247. async function runElementAction(el) {
  1248. var scope = el.__stmScope || stateScope();
  1249. var action = evalExpr(el.getAttribute('stm-action'), scope);
  1250. if (!action || typeof action.uri !== 'string') return;
  1251. // stm-confirm: gate the action behind the confirm handler (async-capable,
  1252. // so custom modals are supported).
  1253. if (el.hasAttribute('stm-confirm')) {
  1254. var confirmed = await triggerConfirm(el.getAttribute('stm-confirm'), el);
  1255. if (!confirmed) return;
  1256. }
  1257. applyErrorClasses(el, false); // clear error state on a new attempt
  1258. var data = collectData(el);
  1259. setBusyState(el, true);
  1260. try {
  1261. await performAction(action, data, el);
  1262. } catch (err) {
  1263. // Already handled: stm-on-error classes and the onErrorHandler run inside
  1264. // performAction/reportFailure. Swallow so an HTML-triggered action does
  1265. // not surface as an unhandled rejection.
  1266. } finally {
  1267. setBusyState(el, false);
  1268. }
  1269. }
  1270. // ---------------------------------------------------------------------------
  1271. // Boot visibility (stm-preloader / stm-content)
  1272. // ---------------------------------------------------------------------------
  1273. /**
  1274. * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
  1275. * loading, `stm-preloader` elements are shown and `stm-content` elements
  1276. * hidden; once ready, the reverse.
  1277. *
  1278. * To avoid a flash of un-bound template before the script runs, authors may
  1279. * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
  1280. * `<div stm-content hidden>`); the library removes it once ready. The library
  1281. * also sets `hidden` itself during loading as a fallback for authors who do
  1282. * not pre-set it.
  1283. * @param {boolean} ready
  1284. */
  1285. function setBootState(ready) {
  1286. var preloaders = document.querySelectorAll('[stm-preloader]');
  1287. var contents = document.querySelectorAll('[stm-content]');
  1288. for (var i = 0; i < preloaders.length; i++) {
  1289. ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
  1290. }
  1291. for (var j = 0; j < contents.length; j++) {
  1292. ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
  1293. }
  1294. }
  1295. // ---------------------------------------------------------------------------
  1296. // Public state accessors
  1297. // ---------------------------------------------------------------------------
  1298. /** Build the scope used for expression evaluation: `{ typeName: public }`. */
  1299. function stateScope() {
  1300. var scope = {};
  1301. store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
  1302. return scope;
  1303. }
  1304. /** Read a type's `public` data (what the attributes bind to). */
  1305. function read(type) {
  1306. var entry = store.get(type);
  1307. return entry ? entry.snapshot.public : undefined;
  1308. }
  1309. /** Read a type's full snapshot object. */
  1310. function getSnapshot(type) {
  1311. var entry = store.get(type);
  1312. return entry ? entry.snapshot : undefined;
  1313. }
  1314. /** Read the frame wrapping a type's snapshot. */
  1315. function getFrame(type) {
  1316. var entry = store.get(type);
  1317. return entry ? entry.frame : undefined;
  1318. }
  1319. /** Build an object of `{ typeName: public }` for every held type. */
  1320. function state() {
  1321. var result = {};
  1322. store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
  1323. return result;
  1324. }
  1325. /**
  1326. * Clear state. With a type argument, clears that type only; without, clears
  1327. * all held state.
  1328. * @param {string} [type]
  1329. */
  1330. function clear(type) {
  1331. if (type === undefined) {
  1332. Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
  1333. } else {
  1334. clearType(type, { broadcast: true });
  1335. }
  1336. renderAll();
  1337. }
  1338. /**
  1339. * Perform an action. `action` may be an action object or a string path that
  1340. * resolves to an action object within the current state.
  1341. * @param {object|string} action
  1342. * @param {object} [data]
  1343. * @returns {Promise<void>}
  1344. */
  1345. function act(action, data) {
  1346. var resolved = action;
  1347. if (typeof action === 'string') resolved = evalExpr(action, stateScope());
  1348. if (!resolved || typeof resolved.uri !== 'string') {
  1349. return Promise.reject(new StatumError('Invalid action'));
  1350. }
  1351. return performAction(resolved, data, null);
  1352. }
  1353. /** Attach a state listener for a type. */
  1354. function addStateListener(type, callback) {
  1355. if (typeof callback !== 'function') return;
  1356. if (!listeners.has(type)) listeners.set(type, new Set());
  1357. listeners.get(type).add(callback);
  1358. }
  1359. /** Remove a previously-attached state listener. */
  1360. function removeStateListener(type, callback) {
  1361. var set = listeners.get(type);
  1362. if (!set) return;
  1363. set.delete(callback);
  1364. if (set.size === 0) listeners.delete(type);
  1365. }
  1366. // ---------------------------------------------------------------------------
  1367. // Initialization
  1368. // ---------------------------------------------------------------------------
  1369. /**
  1370. * Scan the document for `pstm-*` attributes and `<pstm-*>` elements, which
  1371. * are intended for server-side pre-rendering and should never reach the
  1372. * browser. Emits a single `console.warn` summarizing them.
  1373. */
  1374. function warnServerSideMarkup() {
  1375. var found = [];
  1376. var els = document.querySelectorAll('*');
  1377. for (var i = 0; i < els.length; i++) {
  1378. var el = els[i];
  1379. var tag = el.tagName.toLowerCase();
  1380. if (tag.indexOf('pstm-') === 0) found.push('<' + tag + '>');
  1381. var attrs = el.attributes;
  1382. for (var j = 0; j < attrs.length; j++) {
  1383. var name = attrs[j].name;
  1384. if (name.indexOf('pstm-') === 0) found.push('<' + tag + '> ' + name);
  1385. }
  1386. }
  1387. if (found.length) {
  1388. console.warn('[statum] ' + found.length + ' server-side pstm-* attribute/element(s) ' +
  1389. 'found in the DOM; they should have been resolved during pre-rendering: ' +
  1390. found.slice(0, 10).join(', ') + (found.length > 10 ? ' …' : ''));
  1391. }
  1392. }
  1393. /**
  1394. * Initialize Statum: read URL overrides, run the session-cookie check,
  1395. * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
  1396. * and render. Safe to call multiple times.
  1397. * @returns {Promise<void>}
  1398. */
  1399. async function init() {
  1400. if (initialized) return;
  1401. initialized = true;
  1402. var body = document.body;
  1403. if (body) {
  1404. if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
  1405. if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
  1406. if (body.hasAttribute('stm-channel')) config.channelUrl = body.getAttribute('stm-channel');
  1407. if (body.hasAttribute('stm-worker')) config.workerUrl = body.getAttribute('stm-worker');
  1408. }
  1409. try { warnServerSideMarkup(); } catch (e) {}
  1410. try { initSession(); } catch (e) {}
  1411. try { hydrate(); } catch (e) {}
  1412. setupChannel();
  1413. setBootState(false);
  1414. renderAll(); // bind against any persisted/hydrated state immediately
  1415. try {
  1416. await loadEntrypoint();
  1417. } catch (err) {
  1418. console.error('[statum] entrypoint load failed', err);
  1419. } finally {
  1420. setBootState(true);
  1421. }
  1422. }
  1423. function autoInit() {
  1424. if (document.readyState === 'loading') {
  1425. document.addEventListener('DOMContentLoaded', init);
  1426. } else {
  1427. init();
  1428. }
  1429. }
  1430. // ---------------------------------------------------------------------------
  1431. // Public API
  1432. // ---------------------------------------------------------------------------
  1433. /** @namespace statum */
  1434. window.statum = {
  1435. /** Library version. */
  1436. version: '0.1.0',
  1437. /** Mutable endpoint configuration. */
  1438. config: config,
  1439. /** (Re)initialize the library. Usually runs automatically on load. */
  1440. init: init,
  1441. /** Read a type's `public` data. */
  1442. read: read,
  1443. /** Read a type's full snapshot object. */
  1444. getSnapshot: getSnapshot,
  1445. /** Read the frame wrapping a type's snapshot. */
  1446. getFrame: getFrame,
  1447. /** Build `{ typeName: public }` for every held type. */
  1448. state: state,
  1449. /** Clear one type (`clear("x")`) or all state (`clear()`). */
  1450. clear: clear,
  1451. /** Perform an action object or named action. */
  1452. act: act,
  1453. /** Attach a state-changed listener for a type. */
  1454. addStateListener: addStateListener,
  1455. /** Remove a previously-attached listener. */
  1456. removeStateListener: removeStateListener,
  1457. /** The Statum error type (thrown by `act` and surfaced to handlers). */
  1458. Error: StatumError,
  1459. get onConfirmHandler() { return handlers.onConfirm; },
  1460. set onConfirmHandler(v) { handlers.onConfirm = typeof v === 'function' ? v : null; },
  1461. get onNotifyHandler() { return handlers.onNotify; },
  1462. set onNotifyHandler(v) { handlers.onNotify = typeof v === 'function' ? v : null; },
  1463. get onErrorHandler() { return handlers.onError; },
  1464. set onErrorHandler(v) { handlers.onError = typeof v === 'function' ? v : null; }
  1465. };
  1466. autoInit();
  1467. })();