statum.js 74 KB

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