statum.js 63 KB

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