statum.js 60 KB

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