statum.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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. };
  40. // ---------------------------------------------------------------------------
  41. // State store
  42. // ---------------------------------------------------------------------------
  43. /**
  44. * In-memory store, keyed by slot type. Each value is `{frame, snapshot}`
  45. * where `snapshot` is the parsed `frame.content`. This map is the single
  46. * source of truth for rendering; persistent backends merely hydrate it.
  47. *
  48. * @type {Map<string, {frame: object, snapshot: object}>}
  49. */
  50. var store = new Map();
  51. /** Listeners, keyed by type name. @type {Map<string, Set<Function>>} */
  52. var listeners = new Map();
  53. /** @type {BroadcastChannel|null} */
  54. var channel = null;
  55. /** Whether {@link init} has already run. */
  56. var initialized = false;
  57. // ---------------------------------------------------------------------------
  58. // Small utilities
  59. // ---------------------------------------------------------------------------
  60. /**
  61. * Parse an ISO 8601 timestamp to epoch millis, or `undefined`.
  62. * @param {string|undefined} s
  63. * @returns {number|undefined}
  64. */
  65. function parseTime(s) {
  66. if (!s) return undefined;
  67. var t = new Date(s).getTime();
  68. return isNaN(t) ? undefined : t;
  69. }
  70. /**
  71. * Base64-encode a UTF-8 string (safe for frames containing non-Latin1 data).
  72. * @param {string} str
  73. * @returns {string}
  74. */
  75. function b64encode(str) {
  76. var bytes = new TextEncoder().encode(str);
  77. var bin = '';
  78. var chunk = 0x8000;
  79. for (var i = 0; i < bytes.length; i += chunk) {
  80. bin += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
  81. }
  82. return btoa(bin);
  83. }
  84. /** Read a cookie value, or `null` if absent. @param {string} name */
  85. function getCookie(name) {
  86. var escaped = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
  87. var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
  88. return match ? decodeURIComponent(match[1]) : null;
  89. }
  90. /** Set a session cookie (no expiry => cleared when the browser closes). */
  91. function setCookie(name, value) {
  92. document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; SameSite=Lax';
  93. }
  94. // ---------------------------------------------------------------------------
  95. // Expression evaluation
  96. // ---------------------------------------------------------------------------
  97. /**
  98. * Compiled-expression cache. Expressions are evaluated as JavaScript against
  99. * a scope object (the page's HTML is trusted, per the model).
  100. * @type {Map<string, Function>}
  101. */
  102. var exprCache = new Map();
  103. /**
  104. * Compile (and cache) an expression string into a function of `scope`.
  105. * Uses `with` so that arbitrary type names and loop variables are resolved
  106. * as bare identifiers. Returns a function that yields `undefined` on any
  107. * runtime or compile error.
  108. * @param {string} expr
  109. * @returns {Function}
  110. */
  111. function compileExpr(expr) {
  112. var cached = exprCache.get(expr);
  113. if (cached !== undefined) return cached;
  114. var fn;
  115. try {
  116. // Function-constructor bodies are non-strict by default, so `with` is
  117. // permitted. The inner try/catch turns reference errors into `undefined`
  118. // so a missing path simply yields no value.
  119. fn = new Function('scope', 'with(scope){try{return (' + expr + ');}catch(e){return undefined;}}');
  120. } catch (e) {
  121. fn = function () { return undefined; };
  122. }
  123. exprCache.set(expr, fn);
  124. return fn;
  125. }
  126. /**
  127. * Evaluate an expression against a scope.
  128. * @param {string} expr
  129. * @param {object} [scope]
  130. * @returns {*} `undefined` if the expression is empty or fails.
  131. */
  132. function evalExpr(expr, scope) {
  133. if (expr == null || expr === '') return undefined;
  134. try {
  135. return compileExpr(expr)(scope || {});
  136. } catch (e) {
  137. return undefined;
  138. }
  139. }
  140. /**
  141. * Build a child scope that inherits the parent (so type bindings remain
  142. * visible) and adds one own loop variable.
  143. * @param {object} parent
  144. * @param {string} name
  145. * @param {*} value
  146. * @returns {object}
  147. */
  148. function childScope(parent, name, value) {
  149. var scope = Object.create(parent || null);
  150. scope[name] = value;
  151. return scope;
  152. }
  153. // ---------------------------------------------------------------------------
  154. // StatumError
  155. // ---------------------------------------------------------------------------
  156. /**
  157. * Error type thrown for HTTP failures and `error` directives.
  158. * @param {string} [message]
  159. * @param {string} [code]
  160. * @param {object} [data]
  161. */
  162. function StatumError(message, code, data) {
  163. this.name = 'StatumError';
  164. this.message = message || '';
  165. this.code = code || undefined;
  166. this.data = data || undefined;
  167. }
  168. StatumError.prototype = Object.create(Error.prototype);
  169. // ---------------------------------------------------------------------------
  170. // Persistence
  171. // ---------------------------------------------------------------------------
  172. /**
  173. * Pick the storage backend for a scope.
  174. * @param {string} scope
  175. * @returns {Storage|null} `null` for in-memory scopes.
  176. */
  177. function storageFor(scope) {
  178. if (scope === 'device' || scope === 'session') return localStorage;
  179. if (scope === 'flow') return sessionStorage;
  180. return null; // page / transient
  181. }
  182. /**
  183. * Persist a slot's frame to the backend matching its scope, removing any
  184. * stale copy from the other backend first (in case the scope changed).
  185. * @param {string} type
  186. * @param {{frame: object, snapshot: object}} entry
  187. */
  188. function persistEntry(type, entry) {
  189. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  190. removePersisted(type);
  191. var storage = storageFor(scope);
  192. if (!storage) return;
  193. try {
  194. storage.setItem(STORAGE_PREFIX + type, JSON.stringify(entry.frame));
  195. } catch (e) {
  196. /* storage full or unavailable; remain in-memory only */
  197. }
  198. }
  199. /** Remove a persisted frame from both backends. @param {string} type */
  200. function removePersisted(type) {
  201. try { localStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  202. try { sessionStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  203. }
  204. /** Load every persisted frame from a backend into the in-memory store. */
  205. function loadFrom(storage) {
  206. for (var i = 0; i < storage.length; i++) {
  207. var key = storage.key(i);
  208. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  209. try {
  210. var frame = JSON.parse(storage.getItem(key));
  211. var snapshot = JSON.parse(frame.content);
  212. var type = snapshot.slot && snapshot.slot.type;
  213. if (type && !store.has(type)) store.set(type, { frame: frame, snapshot: snapshot });
  214. } catch (e) {
  215. /* corrupt entry: ignore */
  216. }
  217. }
  218. }
  219. /** Hydrate the store from localStorage and sessionStorage. */
  220. function hydrate() {
  221. try { loadFrom(localStorage); } catch (e) {}
  222. try { loadFrom(sessionStorage); } catch (e) {}
  223. }
  224. // ---------------------------------------------------------------------------
  225. // Session-cookie initialization
  226. // ---------------------------------------------------------------------------
  227. /**
  228. * Detect a fresh browser session using the `_statum_sdc` session cookie.
  229. * On a fresh session, clear all `session`-scoped persisted frames, then set
  230. * the marker. Session cookies are shared across tabs, so a tab opened
  231. * mid-session sees the marker and leaves session data intact.
  232. */
  233. function initSession() {
  234. if (getCookie(SESSION_COOKIE) !== null) return;
  235. clearSessionSlotsFromStorage();
  236. setCookie(SESSION_COOKIE, '1');
  237. }
  238. /** Remove all `session`-scoped frames from localStorage. */
  239. function clearSessionSlotsFromStorage() {
  240. var toRemove = [];
  241. for (var i = 0; i < localStorage.length; i++) {
  242. var key = localStorage.key(i);
  243. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  244. try {
  245. var frame = JSON.parse(localStorage.getItem(key));
  246. var snapshot = JSON.parse(frame.content);
  247. if (snapshot.slot && snapshot.slot.scope === 'session') toRemove.push(key);
  248. } catch (e) {}
  249. }
  250. for (var j = 0; j < toRemove.length; j++) localStorage.removeItem(toRemove[j]);
  251. }
  252. // ---------------------------------------------------------------------------
  253. // Listeners & cross-tab broadcast
  254. // ---------------------------------------------------------------------------
  255. /**
  256. * Fire all listeners for a type.
  257. * @param {string} type
  258. * @param {object|null} frame
  259. * @param {object|null} snapshot
  260. */
  261. function notify(type, frame, snapshot) {
  262. var set = listeners.get(type);
  263. if (!set) return;
  264. var event = { type: type, frame: frame, snapshot: snapshot };
  265. set.forEach(function (cb) {
  266. try { cb(event); } catch (e) { console.error('[statum] listener error', e); }
  267. });
  268. }
  269. /**
  270. * Broadcast a state change to other tabs. Only `session`/`device` scopes are
  271. * shared (flow/page/transient are per-tab).
  272. * @param {object} message
  273. * @param {string} [scope]
  274. */
  275. function broadcast(message, scope) {
  276. if (!channel) return;
  277. if (scope !== 'session' && scope !== 'device') return;
  278. try { channel.postMessage(message); } catch (e) {}
  279. }
  280. /** Open the BroadcastChannel and wire inbound messages. */
  281. function setupChannel() {
  282. if (typeof BroadcastChannel === 'undefined') return;
  283. try {
  284. channel = new BroadcastChannel(CHANNEL_NAME);
  285. } catch (e) {
  286. channel = null;
  287. return;
  288. }
  289. channel.onmessage = function (ev) {
  290. var msg = ev.data;
  291. if (!msg || msg.kind !== 'set' && msg.kind !== 'clear') return;
  292. if (msg.kind === 'set' && msg.frame) {
  293. try {
  294. var snapshot = JSON.parse(msg.frame.content);
  295. var type = snapshot.slot && snapshot.slot.type;
  296. if (type) {
  297. var entry = { frame: msg.frame, snapshot: snapshot };
  298. store.set(type, entry);
  299. persistEntry(type, entry);
  300. notify(type, msg.frame, snapshot);
  301. renderAll();
  302. }
  303. } catch (e) { /* ignore malformed */ }
  304. } else if (msg.kind === 'clear' && msg.type) {
  305. clearType(msg.type, { broadcast: false });
  306. renderAll();
  307. }
  308. };
  309. }
  310. // ---------------------------------------------------------------------------
  311. // State mutation
  312. // ---------------------------------------------------------------------------
  313. /**
  314. * Remove a type from the store, un-persist it, fire listeners, and
  315. * (optionally) broadcast the clear to other tabs.
  316. * @param {string} type
  317. * @param {{broadcast?: boolean}} [opts]
  318. */
  319. function clearType(type, opts) {
  320. var entry = store.get(type);
  321. if (!entry) return;
  322. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  323. store.delete(type);
  324. removePersisted(type);
  325. notify(type, null, null);
  326. if (opts && opts.broadcast) broadcast({ kind: 'clear', type: type }, scope);
  327. }
  328. /**
  329. * Apply a `set` directive: store/refresh a slot's snapshot.
  330. * @param {object} directive `{ snapshot_frame }`
  331. */
  332. function applySet(directive) {
  333. var frame = directive.snapshot_frame;
  334. if (!frame || !frame.content) return;
  335. var snapshot;
  336. try { snapshot = JSON.parse(frame.content); } catch (e) { return; }
  337. var type = snapshot.slot && snapshot.slot.type;
  338. if (!type) return;
  339. var entry = { frame: frame, snapshot: snapshot };
  340. store.set(type, entry);
  341. persistEntry(type, entry);
  342. notify(type, frame, snapshot);
  343. var scope = snapshot.slot && snapshot.slot.scope;
  344. broadcast({ kind: 'set', frame: frame }, scope);
  345. }
  346. /**
  347. * Apply a `clear` directive. The directive carries a slot key, so the type
  348. * holding that key is resolved and removed.
  349. * @param {object} directive `{ key }`
  350. */
  351. function applyClear(directive) {
  352. var key = directive.key;
  353. var typeToRemove = null;
  354. store.forEach(function (entry, type) {
  355. if (entry.snapshot.slot && entry.snapshot.slot.key === key) typeToRemove = type;
  356. });
  357. if (typeToRemove) clearType(typeToRemove, { broadcast: true });
  358. }
  359. // ---------------------------------------------------------------------------
  360. // Snapshot freshness & request headers
  361. // ---------------------------------------------------------------------------
  362. /**
  363. * Categorize a held snapshot relative to the current time.
  364. * @returns {'silent'|'always'|'invalid'|'stale'|'fresh'}
  365. * - `silent`: unidirectional (`transmit_after` undefined) - never sent.
  366. * - `always`: `transmit_after === as_at` - send the base64 frame each time.
  367. * - `invalid`: past `invalid_after` - drop and refetch.
  368. * - `stale`: past `transmit_after` but not yet invalid - pre-flight first.
  369. * - `fresh`: still cached server-side - send the `as_at` reference.
  370. */
  371. function entryCategory(entry) {
  372. var snap = entry.snapshot;
  373. var transmit = snap.transmit_after;
  374. if (transmit === undefined || transmit === null) return 'silent';
  375. if (transmit === snap.as_at) return 'always';
  376. var now = Date.now();
  377. var invalidAt = parseTime(snap.invalid_after);
  378. var transmitAt = parseTime(transmit);
  379. if (invalidAt !== undefined && now >= invalidAt) return 'invalid';
  380. if (transmitAt !== undefined && now >= transmitAt) return 'stale';
  381. return 'fresh';
  382. }
  383. /**
  384. * Drop locally-invalid snapshots and pre-flight any stale ones. Pre-flighting
  385. * posts the stale frames to the slot endpoint and applies the returned `set`
  386. * directives, refreshing their `as_at` values before the real request runs.
  387. *
  388. * Single-flight: concurrent callers share one in-flight preparation.
  389. * @returns {Promise<void>}
  390. */
  391. var preparePromise = null;
  392. function prepareSlots() {
  393. if (preparePromise) return preparePromise;
  394. preparePromise = doPrepareSlots().then(function () {
  395. preparePromise = null;
  396. }, function () {
  397. preparePromise = null;
  398. });
  399. return preparePromise;
  400. }
  401. async function doPrepareSlots() {
  402. var stale = [];
  403. store.forEach(function (entry, type) {
  404. var cat = entryCategory(entry);
  405. if (cat === 'invalid') {
  406. clearType(type, { broadcast: false });
  407. } else if (cat === 'stale') {
  408. stale.push(entry.frame);
  409. }
  410. });
  411. if (stale.length) {
  412. var directives = await postSlots(stale);
  413. applyDirectives(directives, { originElement: null });
  414. }
  415. }
  416. /**
  417. * Build the `X-Statum-Slot` header values for every held slot, using the
  418. * freshness rules. Assumes {@link prepareSlots} has just run.
  419. * @returns {string[]}
  420. */
  421. function buildSlotHeaders() {
  422. var headers = [];
  423. store.forEach(function (entry) {
  424. var snap = entry.snapshot;
  425. var cat = entryCategory(entry);
  426. if (cat === 'silent' || cat === 'invalid') return;
  427. if (cat === 'always') {
  428. headers.push(b64encode(JSON.stringify(entry.frame)));
  429. } else {
  430. headers.push('key=' + snap.slot.key + '; as_at=' + snap.as_at);
  431. }
  432. });
  433. return headers;
  434. }
  435. // ---------------------------------------------------------------------------
  436. // HTTP helpers
  437. // ---------------------------------------------------------------------------
  438. /** True if a response is a Statum directive response. */
  439. function isStatum(res) {
  440. return (res.headers.get('Content-Type') || '').indexOf(STATUM_CONTENT_TYPE) !== -1;
  441. }
  442. /**
  443. * POST an array of frames to the slot endpoint (the pre-flight target) and
  444. * return its directive array. This request intentionally carries no slot
  445. * headers (it is itself the refresh).
  446. * @param {object[]} frames
  447. * @returns {Promise<object[]>}
  448. */
  449. async function postSlots(frames) {
  450. var headers = new Headers();
  451. headers.set('Accept', STATUM_CONTENT_TYPE);
  452. headers.set('Content-Type', 'application/json');
  453. var res = await fetch(config.slotsUrl, {
  454. method: 'POST',
  455. headers: headers,
  456. body: JSON.stringify(frames),
  457. credentials: 'same-origin'
  458. });
  459. if (!isStatum(res)) return [];
  460. try { return await res.json(); } catch (e) { return []; }
  461. }
  462. /**
  463. * Apply the directives from a response. Set/clear run first, then `render`,
  464. * then terminal navigation (`navigate`, then `post`). Returns any error
  465. * directive encountered without throwing, so callers can decide.
  466. * @param {object[]} directives
  467. * @param {{originElement?: HTMLElement}} [ctx]
  468. * @returns {{error?: StatumError}}
  469. */
  470. function applyDirectives(directives, ctx) {
  471. var result = { error: undefined };
  472. var list = Array.isArray(directives) ? directives : [];
  473. var navigateDirective = null;
  474. var postDirective = null;
  475. for (var i = 0; i < list.length; i++) {
  476. var d = list[i];
  477. if (!d || typeof d !== 'object') continue;
  478. switch (d.type) {
  479. case 'set': applySet(d); break;
  480. case 'clear': applyClear(d); break;
  481. case 'error':
  482. result.error = new StatumError(d.message, d.code, d.data);
  483. if (ctx && ctx.originElement) applyErrorClasses(ctx.originElement, true);
  484. break;
  485. case 'navigate': navigateDirective = d; break;
  486. case 'post': postDirective = d; break;
  487. }
  488. }
  489. renderAll();
  490. if (navigateDirective) doNavigate(navigateDirective);
  491. if (postDirective) doPost(postDirective);
  492. return result;
  493. }
  494. /** Execute a `navigate` directive as a full page load. */
  495. function doNavigate(d) {
  496. if (d.uri) window.location.href = d.uri;
  497. }
  498. /** Execute a `post` directive as a real (navigating) form POST. */
  499. function doPost(d) {
  500. if (!d.uri) return;
  501. var form = document.createElement('form');
  502. form.method = 'POST';
  503. form.action = d.uri;
  504. form.style.display = 'none';
  505. var data = d.data || {};
  506. Object.keys(data).forEach(function (name) {
  507. var input = document.createElement('input');
  508. input.type = 'hidden';
  509. input.name = name;
  510. input.value = data[name] == null ? '' : String(data[name]);
  511. form.appendChild(input);
  512. });
  513. document.body.appendChild(form);
  514. form.submit();
  515. }
  516. /**
  517. * Handle a fetch response: if it is a Statum response, apply its directives;
  518. * otherwise throw on HTTP errors and no-op on other successful responses.
  519. * @param {Response} res
  520. * @param {{originElement?: HTMLElement}} [ctx]
  521. */
  522. async function handleResponse(res, ctx) {
  523. if (!isStatum(res)) {
  524. if (!res.ok) throw new StatumError('HTTP ' + res.status);
  525. return;
  526. }
  527. var directives;
  528. try { directives = await res.json(); } catch (e) { directives = []; }
  529. var result = applyDirectives(directives, ctx);
  530. if (result.error) throw result.error;
  531. }
  532. // ---------------------------------------------------------------------------
  533. // Entrypoint & action requests
  534. // ---------------------------------------------------------------------------
  535. /**
  536. * Fetch the entrypoint for the current URL, applying its directives. Carries
  537. * slot headers (and pre-flights) like any other request.
  538. * @returns {Promise<void>}
  539. */
  540. async function loadEntrypoint() {
  541. await prepareSlots();
  542. var headers = new Headers();
  543. headers.set('Accept', STATUM_CONTENT_TYPE);
  544. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  545. var url = config.entrypointUrl + '?uri=' + encodeURIComponent(window.location.href);
  546. var res = await fetch(url, { headers: headers, credentials: 'same-origin' });
  547. await handleResponse(res, { originElement: null });
  548. }
  549. /**
  550. * Perform an action request.
  551. *
  552. * @param {object} action `{ uri, method, private }`
  553. * @param {object} [data] Key/value parameters. Encoded as query string for
  554. * GET/HEAD, otherwise as `application/x-www-form-urlencoded`.
  555. * @param {HTMLElement} [originElement] Element that triggered the action, so
  556. * that `stm-on-error` classes can be applied on an `error` directive.
  557. * @returns {Promise<void>} Resolves once the request completes and its
  558. * directives have run; rejects on HTTP failure or an `error` directive.
  559. */
  560. async function performAction(action, data, originElement) {
  561. await prepareSlots();
  562. var headers = new Headers();
  563. headers.set('Accept', STATUM_CONTENT_TYPE);
  564. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  565. if (action.private) headers.set(PRIVATE_HEADER, action.private);
  566. var method = (action.method || 'GET').toUpperCase();
  567. var params = data || {};
  568. var init = { method: method, headers: headers, credentials: 'same-origin' };
  569. var url = action.uri;
  570. if (method === 'GET' || method === 'HEAD') {
  571. var qs = new URLSearchParams(params).toString();
  572. if (qs) url += (url.indexOf('?') !== -1 ? '&' : '?') + qs;
  573. } else {
  574. init.body = new URLSearchParams(params).toString();
  575. headers.set('Content-Type', 'application/x-www-form-urlencoded');
  576. }
  577. var res = await fetch(url, init);
  578. await handleResponse(res, { originElement: originElement });
  579. }
  580. // ---------------------------------------------------------------------------
  581. // Rendering: loops, conditionals, bindings
  582. // ---------------------------------------------------------------------------
  583. /** Templates captured from loop holders. @type {WeakMap<Element, Element>} */
  584. var templates = new WeakMap();
  585. /** Instance nodes managed by a loop holder. @type {WeakMap<Element, Element[]>} */
  586. var instancesByHolder = new WeakMap();
  587. /** Loop instance nodes; skipped by the render walk (owned by their holder). */
  588. var instanceNodes = new WeakSet();
  589. /** If-chain anchors for detached branches. @type {WeakMap<Element, Comment>} */
  590. var ifAnchors = new WeakMap();
  591. /** Elements whose `stm-action` has been wired, to avoid double-binding. */
  592. var wired = new WeakSet();
  593. /**
  594. * Find a `stm-for-{name}-in` attribute on an element.
  595. * @returns {{varName: string, expr: string}|null}
  596. */
  597. function getStmFor(el) {
  598. var attrs = el.attributes;
  599. for (var i = 0; i < attrs.length; i++) {
  600. var match = attrs[i].name.match(/^stm-for-(.+)-in$/);
  601. if (match) return { varName: match[1], expr: attrs[i].value };
  602. }
  603. return null;
  604. }
  605. /** Remove any `stm-for-*` and `stm-key` attributes from an element. */
  606. function stripLoopAttrs(el) {
  607. var toRemove = [];
  608. for (var i = 0; i < el.attributes.length; i++) {
  609. var name = el.attributes[i].name;
  610. if (/^stm-for-(.+)-in$/.test(name) || name === 'stm-key') toRemove.push(name);
  611. }
  612. toRemove.forEach(function (n) { el.removeAttribute(n); });
  613. }
  614. /** Ensure an element is in the DOM (reattaching at its remembered anchor). */
  615. function ensureAttached(el) {
  616. var anchor = ifAnchors.get(el);
  617. if (anchor && anchor.parentNode) {
  618. anchor.parentNode.insertBefore(el, anchor);
  619. anchor.parentNode.removeChild(anchor);
  620. ifAnchors.delete(el);
  621. }
  622. }
  623. /** Detach an element, remembering its position with a comment anchor. */
  624. function ensureDetached(el) {
  625. if (!el.parentNode) return;
  626. if (!ifAnchors.has(el)) {
  627. var anchor = document.createComment('#stm-if');
  628. el.parentNode.insertBefore(anchor, el);
  629. ifAnchors.set(el, anchor);
  630. }
  631. el.parentNode.removeChild(el);
  632. }
  633. /**
  634. * Evaluate an `stm-if` / `stm-else-if` / `stm-else` chain beginning at `el`,
  635. * attaching the matching branch and detaching the rest.
  636. * @returns {Element|null} The active branch element (or `null`).
  637. */
  638. function handleIfChain(el, scope) {
  639. var branches = [{ el: el, expr: el.getAttribute('stm-if') }];
  640. var cur = el.nextElementSibling;
  641. while (cur) {
  642. if (cur.hasAttribute('stm-else-if')) {
  643. branches.push({ el: cur, expr: cur.getAttribute('stm-else-if') });
  644. cur = cur.nextElementSibling;
  645. } else if (cur.hasAttribute('stm-else')) {
  646. branches.push({ el: cur, expr: null });
  647. break;
  648. } else {
  649. break;
  650. }
  651. }
  652. var activeEl = null;
  653. for (var i = 0; i < branches.length; i++) {
  654. var b = branches[i];
  655. if (b.expr === null || !!evalExpr(b.expr, scope)) { activeEl = b.el; break; }
  656. }
  657. branches.forEach(function (b) {
  658. if (b.el === activeEl) ensureAttached(b.el);
  659. else ensureDetached(b.el);
  660. });
  661. return activeEl;
  662. }
  663. /** Toggle `stm-class.{name}` classes from their predicate expressions. */
  664. function handleClass(el, scope) {
  665. var attrs = el.attributes;
  666. for (var i = 0; i < attrs.length; i++) {
  667. var attr = attrs[i];
  668. if (attr.name.indexOf('stm-class.') === 0) {
  669. var cls = attr.name.slice('stm-class.'.length);
  670. if (cls && !!evalExpr(attr.value, scope)) el.classList.add(cls);
  671. else el.classList.remove(cls);
  672. }
  673. }
  674. }
  675. /**
  676. * Bind `stm-text` / `stm-html`. Per the "leave original DOM content" policy,
  677. * an unresolved value (`undefined`) leaves the element untouched; otherwise
  678. * the value is stringified (`null` becomes the empty string).
  679. */
  680. function handleTextHtml(el, scope) {
  681. if (el.hasAttribute('stm-text')) {
  682. var text = evalExpr(el.getAttribute('stm-text'), scope);
  683. if (text !== undefined) el.innerText = text === null ? '' : String(text);
  684. }
  685. if (el.hasAttribute('stm-html')) {
  686. var html = evalExpr(el.getAttribute('stm-html'), scope);
  687. if (html !== undefined) el.innerHTML = html === null ? '' : String(html);
  688. }
  689. }
  690. /**
  691. * Expand a loop holder: reconcile its instances against the current array.
  692. * Keyed loops (`stm-key`) reuse DOM nodes for unchanged keys to preserve
  693. * focus/selection/input state; unkeyed loops rebuild wholesale.
  694. */
  695. function handleLoop(el, scope) {
  696. var info = getStmFor(el);
  697. if (!info) return;
  698. var template = templates.get(el);
  699. if (!template) {
  700. template = el.cloneNode(true);
  701. stripLoopAttrs(template);
  702. templates.set(el, template);
  703. }
  704. var raw = evalExpr(info.expr, scope);
  705. if (raw === undefined) {
  706. // No value for the source path yet: clear instances and restore the
  707. // server-rendered holder content (progressive enhancement).
  708. var prev = instancesByHolder.get(el) || [];
  709. prev.forEach(function (n) { n.remove(); });
  710. instancesByHolder.set(el, []);
  711. if (el.getAttribute('data-stm-active') === '1') {
  712. el.removeAttribute('data-stm-active');
  713. el.removeAttribute('hidden');
  714. }
  715. return;
  716. }
  717. var arr = Array.isArray(raw) ? raw : [];
  718. // Activate: hide the holder so only rendered instances are visible.
  719. if (el.getAttribute('data-stm-active') !== '1') {
  720. el.setAttribute('data-stm-active', '1');
  721. el.setAttribute('hidden', '');
  722. }
  723. var keyExpr = el.getAttribute('stm-key');
  724. var next = [];
  725. if (keyExpr) {
  726. var oldByKey = new Map();
  727. (instancesByHolder.get(el) || []).forEach(function (n) {
  728. if (n.__stmKey !== undefined) oldByKey.set(n.__stmKey, n);
  729. });
  730. var used = new Set();
  731. arr.forEach(function (item) {
  732. var child = childScope(scope, info.varName, item);
  733. var key = evalExpr(keyExpr, child);
  734. var node = (key !== undefined && !used.has(key)) ? oldByKey.get(key) : undefined;
  735. if (node) {
  736. used.add(key);
  737. processElement(node, child);
  738. } else {
  739. node = template.cloneNode(true);
  740. node.__stmKey = key;
  741. instanceNodes.add(node);
  742. processElement(node, child);
  743. }
  744. next.push(node);
  745. });
  746. oldByKey.forEach(function (n, key) { if (!used.has(key)) n.remove(); });
  747. } else {
  748. (instancesByHolder.get(el) || []).forEach(function (n) { n.remove(); });
  749. arr.forEach(function (item) {
  750. var child = childScope(scope, info.varName, item);
  751. var node = template.cloneNode(true);
  752. instanceNodes.add(node);
  753. processElement(node, child);
  754. next.push(node);
  755. });
  756. }
  757. // Place instances in order, immediately after the holder.
  758. var ref = el;
  759. next.forEach(function (node) {
  760. if (node !== ref.nextSibling) ref.parentNode.insertBefore(node, ref.nextSibling);
  761. ref = node;
  762. });
  763. instancesByHolder.set(el, next);
  764. }
  765. /**
  766. * Process one element's bindings (and recurse). Loop holders are handled by
  767. * {@link handleLoop}; `stm-else-if` / `stm-else` are owned by their `stm-if`.
  768. */
  769. function processElement(el, scope) {
  770. if (getStmFor(el)) { handleLoop(el, scope); return; }
  771. if (el.hasAttribute('stm-else-if') || el.hasAttribute('stm-else')) return;
  772. if (el.hasAttribute('stm-if')) {
  773. var active = handleIfChain(el, scope);
  774. if (active) processInner(active, scope);
  775. return;
  776. }
  777. processInner(el, scope);
  778. }
  779. /** Bind the non-control-flow attributes and recurse into children. */
  780. function processInner(el, scope) {
  781. el.__stmScope = scope; // latest scope, used when an action fires
  782. handleClass(el, scope);
  783. handleTextHtml(el, scope);
  784. wireAction(el);
  785. render(el, scope);
  786. }
  787. /**
  788. * Walk an element's children, processing each. Loop instance nodes are
  789. * skipped here (they are owned and processed by their holder).
  790. */
  791. function render(root, scope) {
  792. if (!root || !root.children) return;
  793. // Snapshot the children: processing mutates the DOM (detaching branches,
  794. // inserting loop instances) and a live HTMLCollection would shift indices.
  795. var children = Array.prototype.slice.call(root.children);
  796. for (var i = 0; i < children.length; i++) {
  797. var el = children[i];
  798. if (instanceNodes.has(el)) continue;
  799. processElement(el, scope);
  800. }
  801. }
  802. /** Re-render the whole document against the current state. */
  803. function renderAll() {
  804. try { render(document.body, stateScope()); }
  805. catch (e) { console.error('[statum] render error', e); }
  806. }
  807. // ---------------------------------------------------------------------------
  808. // HTML API: actions
  809. // ---------------------------------------------------------------------------
  810. /**
  811. * Collect data for an action trigger: `stm-data-{key}` attributes plus, for a
  812. * form, its named inputs.
  813. * @param {HTMLElement} el
  814. * @returns {object}
  815. */
  816. function collectData(el) {
  817. var data = {};
  818. var attrs = el.attributes;
  819. for (var i = 0; i < attrs.length; i++) {
  820. var name = attrs[i].name;
  821. if (name.indexOf('stm-data-') === 0) data[name.slice('stm-data-'.length)] = attrs[i].value;
  822. }
  823. if (el.tagName === 'FORM') {
  824. var fd = new FormData(el);
  825. fd.forEach(function (value, key) {
  826. data[key] = value instanceof File ? value.name : String(value);
  827. });
  828. }
  829. return data;
  830. }
  831. /**
  832. * Toggle the busy state of an action element: disables the element and its
  833. * descendant form controls and applies `stm-busy-class` classes while busy,
  834. * restoring prior state when not.
  835. */
  836. function setBusyState(el, busy) {
  837. var nodes = [el].concat(Array.prototype.slice.call(
  838. el.querySelectorAll('button,input,select,textarea,fieldset')));
  839. var busyClasses = (el.getAttribute('stm-busy-class') || '').split(/\s+/).filter(Boolean);
  840. if (busy) {
  841. el.__stmDisabled = [];
  842. nodes.forEach(function (n) {
  843. if (!('disabled' in n)) return;
  844. el.__stmDisabled.push([n, n.disabled]);
  845. n.disabled = true;
  846. });
  847. busyClasses.forEach(function (c) { el.classList.add(c); });
  848. } else {
  849. (el.__stmDisabled || []).forEach(function (pair) { pair[0].disabled = pair[1]; });
  850. el.__stmDisabled = [];
  851. busyClasses.forEach(function (c) { el.classList.remove(c); });
  852. }
  853. }
  854. /** Apply or remove `stm-on-error` classes on an action element. */
  855. function applyErrorClasses(el, on) {
  856. if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
  857. var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
  858. classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
  859. }
  860. /**
  861. * Wire an element's primary action once. The listener resolves the action
  862. * object against the element's latest render scope, so loop instances bind to
  863. * their own item.
  864. */
  865. function wireAction(el) {
  866. if (!el.hasAttribute('stm-action') || wired.has(el)) return;
  867. wired.add(el);
  868. var eventName = el.tagName === 'FORM' ? 'submit' : 'click';
  869. el.addEventListener(eventName, function (event) {
  870. event.preventDefault();
  871. runElementAction(el);
  872. });
  873. }
  874. /**
  875. * Resolve and perform the action attached to an element, managing busy and
  876. * error-state classes around the request.
  877. * @param {HTMLElement} el
  878. */
  879. async function runElementAction(el) {
  880. var scope = el.__stmScope || stateScope();
  881. var action = evalExpr(el.getAttribute('stm-action'), scope);
  882. if (!action || typeof action.uri !== 'string') return;
  883. applyErrorClasses(el, false); // clear error state on a new attempt
  884. var data = collectData(el);
  885. setBusyState(el, true);
  886. try {
  887. await performAction(action, data, el);
  888. } catch (err) {
  889. // stm-on-error is applied by the directive path for `error` directives;
  890. // ensure it is also applied for other failures (network, HTTP).
  891. applyErrorClasses(el, true);
  892. } finally {
  893. setBusyState(el, false);
  894. }
  895. }
  896. // ---------------------------------------------------------------------------
  897. // Boot visibility (stm-preloader / stm-content)
  898. // ---------------------------------------------------------------------------
  899. /**
  900. * Toggle pre/post-entrypoint visibility. While loading, `stm-preloader`
  901. * elements are shown and `stm-content` elements hidden; once ready, the
  902. * reverse. Uses the `hidden` attribute so it does not fight inline styles.
  903. * @param {boolean} ready
  904. */
  905. function setBootState(ready) {
  906. var preloaders = document.querySelectorAll('[stm-preloader]');
  907. var contents = document.querySelectorAll('[stm-content]');
  908. for (var i = 0; i < preloaders.length; i++) {
  909. ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
  910. }
  911. for (var j = 0; j < contents.length; j++) {
  912. ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
  913. }
  914. }
  915. // ---------------------------------------------------------------------------
  916. // Public state accessors
  917. // ---------------------------------------------------------------------------
  918. /** Build the scope used for expression evaluation: `{ typeName: public }`. */
  919. function stateScope() {
  920. var scope = {};
  921. store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
  922. return scope;
  923. }
  924. /** Read a type's `public` data (what the attributes bind to). */
  925. function read(type) {
  926. var entry = store.get(type);
  927. return entry ? entry.snapshot.public : undefined;
  928. }
  929. /** Read a type's full snapshot object. */
  930. function getSnapshot(type) {
  931. var entry = store.get(type);
  932. return entry ? entry.snapshot : undefined;
  933. }
  934. /** Read the frame wrapping a type's snapshot. */
  935. function getFrame(type) {
  936. var entry = store.get(type);
  937. return entry ? entry.frame : undefined;
  938. }
  939. /** Build an object of `{ typeName: public }` for every held type. */
  940. function state() {
  941. var result = {};
  942. store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
  943. return result;
  944. }
  945. /**
  946. * Clear state. With a type argument, clears that type only; without, clears
  947. * all held state.
  948. * @param {string} [type]
  949. */
  950. function clear(type) {
  951. if (type === undefined) {
  952. Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
  953. } else {
  954. clearType(type, { broadcast: true });
  955. }
  956. renderAll();
  957. }
  958. /**
  959. * Perform an action. `action` may be an action object or a string path that
  960. * resolves to an action object within the current state.
  961. * @param {object|string} action
  962. * @param {object} [data]
  963. * @returns {Promise<void>}
  964. */
  965. function act(action, data) {
  966. var resolved = action;
  967. if (typeof action === 'string') resolved = evalExpr(action, stateScope());
  968. if (!resolved || typeof resolved.uri !== 'string') {
  969. return Promise.reject(new StatumError('Invalid action'));
  970. }
  971. return performAction(resolved, data, null);
  972. }
  973. /** Attach a state listener for a type. */
  974. function addStateListener(type, callback) {
  975. if (typeof callback !== 'function') return;
  976. if (!listeners.has(type)) listeners.set(type, new Set());
  977. listeners.get(type).add(callback);
  978. }
  979. /** Remove a previously-attached state listener. */
  980. function removeStateListener(type, callback) {
  981. var set = listeners.get(type);
  982. if (!set) return;
  983. set.delete(callback);
  984. if (set.size === 0) listeners.delete(type);
  985. }
  986. // ---------------------------------------------------------------------------
  987. // Initialization
  988. // ---------------------------------------------------------------------------
  989. /**
  990. * Initialize Statum: read URL overrides, run the session-cookie check,
  991. * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
  992. * and render. Safe to call multiple times.
  993. * @returns {Promise<void>}
  994. */
  995. async function init() {
  996. if (initialized) return;
  997. initialized = true;
  998. var body = document.body;
  999. if (body) {
  1000. if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
  1001. if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
  1002. }
  1003. try { initSession(); } catch (e) {}
  1004. try { hydrate(); } catch (e) {}
  1005. setupChannel();
  1006. setBootState(false);
  1007. renderAll(); // bind against any persisted/hydrated state immediately
  1008. try {
  1009. await loadEntrypoint();
  1010. } catch (err) {
  1011. console.error('[statum] entrypoint load failed', err);
  1012. } finally {
  1013. setBootState(true);
  1014. }
  1015. }
  1016. function autoInit() {
  1017. if (document.readyState === 'loading') {
  1018. document.addEventListener('DOMContentLoaded', init);
  1019. } else {
  1020. init();
  1021. }
  1022. }
  1023. // ---------------------------------------------------------------------------
  1024. // Public API
  1025. // ---------------------------------------------------------------------------
  1026. /** @namespace statum */
  1027. window.statum = {
  1028. /** Library version. */
  1029. version: '0.1.0',
  1030. /** Mutable endpoint configuration. */
  1031. config: config,
  1032. /** (Re)initialize the library. Usually runs automatically on load. */
  1033. init: init,
  1034. /** Read a type's `public` data. */
  1035. read: read,
  1036. /** Read a type's full snapshot object. */
  1037. getSnapshot: getSnapshot,
  1038. /** Read the frame wrapping a type's snapshot. */
  1039. getFrame: getFrame,
  1040. /** Build `{ typeName: public }` for every held type. */
  1041. state: state,
  1042. /** Clear one type (`clear("x")`) or all state (`clear()`). */
  1043. clear: clear,
  1044. /** Perform an action object or named action. */
  1045. act: act,
  1046. /** Attach a state-changed listener for a type. */
  1047. addStateListener: addStateListener,
  1048. /** Remove a previously-attached listener. */
  1049. removeStateListener: removeStateListener
  1050. };
  1051. autoInit();
  1052. })();