statum.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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. /** Elements whose `stm-action` has been wired, to avoid double-binding. */
  590. var wired = new WeakSet();
  591. /**
  592. * Find a `stm-for-{name}-in` attribute on an element.
  593. * @returns {{varName: string, expr: string}|null}
  594. */
  595. function getStmFor(el) {
  596. var attrs = el.attributes;
  597. for (var i = 0; i < attrs.length; i++) {
  598. var match = attrs[i].name.match(/^stm-for-(.+)-in$/);
  599. if (match) return { varName: match[1], expr: attrs[i].value };
  600. }
  601. return null;
  602. }
  603. /** Remove any `stm-for-*` and `stm-key` attributes from an element. */
  604. function stripLoopAttrs(el) {
  605. var toRemove = [];
  606. for (var i = 0; i < el.attributes.length; i++) {
  607. var name = el.attributes[i].name;
  608. if (/^stm-for-(.+)-in$/.test(name) || name === 'stm-key') toRemove.push(name);
  609. }
  610. toRemove.forEach(function (n) { el.removeAttribute(n); });
  611. }
  612. /**
  613. * Evaluate an `stm-if` / `stm-else-if` / `stm-else` chain beginning at `el`,
  614. * showing the matching branch and hiding the rest.
  615. *
  616. * Branches are toggled with the `hidden` attribute rather than detached, so
  617. * every branch stays in the DOM and is re-evaluated on each render. (Detaching
  618. * the `stm-if` element would remove it from the render walk, leaving an
  619. * already-attached `stm-else` branch skipped and never refreshed.)
  620. * @returns {Element|null} The active branch element (or `null`).
  621. */
  622. function handleIfChain(el, scope) {
  623. var branches = [{ el: el, expr: el.getAttribute('stm-if') }];
  624. var cur = el.nextElementSibling;
  625. while (cur) {
  626. if (cur.hasAttribute('stm-else-if')) {
  627. branches.push({ el: cur, expr: cur.getAttribute('stm-else-if') });
  628. cur = cur.nextElementSibling;
  629. } else if (cur.hasAttribute('stm-else')) {
  630. branches.push({ el: cur, expr: null });
  631. break;
  632. } else {
  633. break;
  634. }
  635. }
  636. var activeEl = null;
  637. for (var i = 0; i < branches.length; i++) {
  638. var b = branches[i];
  639. if (b.expr === null || !!evalExpr(b.expr, scope)) { activeEl = b.el; break; }
  640. }
  641. branches.forEach(function (b) {
  642. if (b.el === activeEl) b.el.removeAttribute('hidden');
  643. else b.el.setAttribute('hidden', '');
  644. });
  645. return activeEl;
  646. }
  647. /** Toggle `stm-class.{name}` classes from their predicate expressions. */
  648. function handleClass(el, scope) {
  649. var attrs = el.attributes;
  650. for (var i = 0; i < attrs.length; i++) {
  651. var attr = attrs[i];
  652. if (attr.name.indexOf('stm-class.') === 0) {
  653. var cls = attr.name.slice('stm-class.'.length);
  654. if (cls && !!evalExpr(attr.value, scope)) el.classList.add(cls);
  655. else el.classList.remove(cls);
  656. }
  657. }
  658. }
  659. /**
  660. * Bind `stm-text` / `stm-html`. Per the "leave original DOM content" policy,
  661. * an unresolved value (`undefined`) leaves the element untouched; otherwise
  662. * the value is stringified (`null` becomes the empty string).
  663. */
  664. function handleTextHtml(el, scope) {
  665. if (el.hasAttribute('stm-text')) {
  666. var text = evalExpr(el.getAttribute('stm-text'), scope);
  667. if (text !== undefined) el.textContent = text === null ? '' : String(text);
  668. }
  669. if (el.hasAttribute('stm-html')) {
  670. var html = evalExpr(el.getAttribute('stm-html'), scope);
  671. if (html !== undefined) el.innerHTML = html === null ? '' : String(html);
  672. }
  673. }
  674. /**
  675. * Expand a loop holder: reconcile its instances against the current array.
  676. * Keyed loops (`stm-key`) reuse DOM nodes for unchanged keys to preserve
  677. * focus/selection/input state; unkeyed loops rebuild wholesale.
  678. */
  679. function handleLoop(el, scope) {
  680. var info = getStmFor(el);
  681. if (!info) return;
  682. var template = templates.get(el);
  683. if (!template) {
  684. template = el.cloneNode(true);
  685. stripLoopAttrs(template);
  686. templates.set(el, template);
  687. }
  688. var raw = evalExpr(info.expr, scope);
  689. if (raw === undefined) {
  690. // No value for the source path yet: clear instances and restore the
  691. // server-rendered holder content (progressive enhancement).
  692. var prev = instancesByHolder.get(el) || [];
  693. prev.forEach(function (n) { n.remove(); });
  694. instancesByHolder.set(el, []);
  695. if (el.getAttribute('data-stm-active') === '1') {
  696. el.removeAttribute('data-stm-active');
  697. el.removeAttribute('hidden');
  698. }
  699. return;
  700. }
  701. var arr = Array.isArray(raw) ? raw : [];
  702. // Activate: hide the holder so only rendered instances are visible.
  703. if (el.getAttribute('data-stm-active') !== '1') {
  704. el.setAttribute('data-stm-active', '1');
  705. el.setAttribute('hidden', '');
  706. }
  707. var keyExpr = el.getAttribute('stm-key');
  708. var next = [];
  709. if (keyExpr) {
  710. var oldByKey = new Map();
  711. (instancesByHolder.get(el) || []).forEach(function (n) {
  712. if (n.__stmKey !== undefined) oldByKey.set(n.__stmKey, n);
  713. });
  714. var used = new Set();
  715. arr.forEach(function (item) {
  716. var child = childScope(scope, info.varName, item);
  717. var key = evalExpr(keyExpr, child);
  718. var node = (key !== undefined && !used.has(key)) ? oldByKey.get(key) : undefined;
  719. if (node) {
  720. used.add(key);
  721. processElement(node, child);
  722. } else {
  723. node = template.cloneNode(true);
  724. node.__stmKey = key;
  725. instanceNodes.add(node);
  726. processElement(node, child);
  727. }
  728. next.push(node);
  729. });
  730. oldByKey.forEach(function (n, key) { if (!used.has(key)) n.remove(); });
  731. } else {
  732. (instancesByHolder.get(el) || []).forEach(function (n) { n.remove(); });
  733. arr.forEach(function (item) {
  734. var child = childScope(scope, info.varName, item);
  735. var node = template.cloneNode(true);
  736. instanceNodes.add(node);
  737. processElement(node, child);
  738. next.push(node);
  739. });
  740. }
  741. // Place instances in order, immediately after the holder.
  742. var ref = el;
  743. next.forEach(function (node) {
  744. if (node !== ref.nextSibling) ref.parentNode.insertBefore(node, ref.nextSibling);
  745. ref = node;
  746. });
  747. instancesByHolder.set(el, next);
  748. }
  749. /**
  750. * Process one element's bindings (and recurse). Loop holders are handled by
  751. * {@link handleLoop}; `stm-else-if` / `stm-else` are owned by their `stm-if`.
  752. */
  753. function processElement(el, scope) {
  754. if (getStmFor(el)) { handleLoop(el, scope); return; }
  755. if (el.hasAttribute('stm-else-if') || el.hasAttribute('stm-else')) return;
  756. if (el.hasAttribute('stm-if')) {
  757. var active = handleIfChain(el, scope);
  758. if (active) processInner(active, scope);
  759. return;
  760. }
  761. processInner(el, scope);
  762. }
  763. /** Bind the non-control-flow attributes and recurse into children. */
  764. function processInner(el, scope) {
  765. el.__stmScope = scope; // latest scope, used when an action fires
  766. handleClass(el, scope);
  767. handleTextHtml(el, scope);
  768. wireAction(el);
  769. render(el, scope);
  770. }
  771. /**
  772. * Walk an element's children, processing each. Loop instance nodes are
  773. * skipped here (they are owned and processed by their holder).
  774. */
  775. function render(root, scope) {
  776. if (!root || !root.children) return;
  777. // Snapshot the children: processing mutates the DOM (detaching branches,
  778. // inserting loop instances) and a live HTMLCollection would shift indices.
  779. var children = Array.prototype.slice.call(root.children);
  780. for (var i = 0; i < children.length; i++) {
  781. var el = children[i];
  782. if (instanceNodes.has(el)) continue;
  783. processElement(el, scope);
  784. }
  785. }
  786. /** Re-render the whole document against the current state. */
  787. function renderAll() {
  788. try { render(document.body, stateScope()); }
  789. catch (e) { console.error('[statum] render error', e); }
  790. }
  791. // ---------------------------------------------------------------------------
  792. // HTML API: actions
  793. // ---------------------------------------------------------------------------
  794. /**
  795. * Collect data for an action trigger: `stm-data-{key}` attributes plus, for a
  796. * form, its named inputs.
  797. * @param {HTMLElement} el
  798. * @returns {object}
  799. */
  800. function collectData(el) {
  801. var data = {};
  802. var attrs = el.attributes;
  803. for (var i = 0; i < attrs.length; i++) {
  804. var name = attrs[i].name;
  805. if (name.indexOf('stm-data-') === 0) data[name.slice('stm-data-'.length)] = attrs[i].value;
  806. }
  807. if (el.tagName === 'FORM') {
  808. var fd = new FormData(el);
  809. fd.forEach(function (value, key) {
  810. data[key] = value instanceof File ? value.name : String(value);
  811. });
  812. }
  813. return data;
  814. }
  815. /**
  816. * Toggle the busy state of an action element: disables the element and its
  817. * descendant form controls and applies `stm-busy-class` classes while busy,
  818. * restoring prior state when not.
  819. */
  820. function setBusyState(el, busy) {
  821. var nodes = [el].concat(Array.prototype.slice.call(
  822. el.querySelectorAll('button,input,select,textarea,fieldset')));
  823. var busyClasses = (el.getAttribute('stm-busy-class') || '').split(/\s+/).filter(Boolean);
  824. if (busy) {
  825. el.__stmDisabled = [];
  826. nodes.forEach(function (n) {
  827. if (!('disabled' in n)) return;
  828. el.__stmDisabled.push([n, n.disabled]);
  829. n.disabled = true;
  830. });
  831. busyClasses.forEach(function (c) { el.classList.add(c); });
  832. } else {
  833. (el.__stmDisabled || []).forEach(function (pair) { pair[0].disabled = pair[1]; });
  834. el.__stmDisabled = [];
  835. busyClasses.forEach(function (c) { el.classList.remove(c); });
  836. }
  837. }
  838. /** Apply or remove `stm-on-error` classes on an action element. */
  839. function applyErrorClasses(el, on) {
  840. if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
  841. var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
  842. classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
  843. }
  844. /**
  845. * Wire an element's primary action once. The listener resolves the action
  846. * object against the element's latest render scope, so loop instances bind to
  847. * their own item.
  848. */
  849. function wireAction(el) {
  850. if (!el.hasAttribute('stm-action') || wired.has(el)) return;
  851. wired.add(el);
  852. var eventName = el.tagName === 'FORM' ? 'submit' : 'click';
  853. el.addEventListener(eventName, function (event) {
  854. event.preventDefault();
  855. runElementAction(el);
  856. });
  857. }
  858. /**
  859. * Resolve and perform the action attached to an element, managing busy and
  860. * error-state classes around the request.
  861. * @param {HTMLElement} el
  862. */
  863. async function runElementAction(el) {
  864. var scope = el.__stmScope || stateScope();
  865. var action = evalExpr(el.getAttribute('stm-action'), scope);
  866. if (!action || typeof action.uri !== 'string') return;
  867. applyErrorClasses(el, false); // clear error state on a new attempt
  868. var data = collectData(el);
  869. setBusyState(el, true);
  870. try {
  871. await performAction(action, data, el);
  872. } catch (err) {
  873. // stm-on-error is applied by the directive path for `error` directives;
  874. // ensure it is also applied for other failures (network, HTTP).
  875. applyErrorClasses(el, true);
  876. } finally {
  877. setBusyState(el, false);
  878. }
  879. }
  880. // ---------------------------------------------------------------------------
  881. // Boot visibility (stm-preloader / stm-content)
  882. // ---------------------------------------------------------------------------
  883. /**
  884. * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
  885. * loading, `stm-preloader` elements are shown and `stm-content` elements
  886. * hidden; once ready, the reverse.
  887. *
  888. * To avoid a flash of un-bound template before the script runs, authors may
  889. * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
  890. * `<div stm-content hidden>`); the library removes it once ready. The library
  891. * also sets `hidden` itself during loading as a fallback for authors who do
  892. * not pre-set it.
  893. * @param {boolean} ready
  894. */
  895. function setBootState(ready) {
  896. var preloaders = document.querySelectorAll('[stm-preloader]');
  897. var contents = document.querySelectorAll('[stm-content]');
  898. for (var i = 0; i < preloaders.length; i++) {
  899. ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
  900. }
  901. for (var j = 0; j < contents.length; j++) {
  902. ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
  903. }
  904. }
  905. // ---------------------------------------------------------------------------
  906. // Public state accessors
  907. // ---------------------------------------------------------------------------
  908. /** Build the scope used for expression evaluation: `{ typeName: public }`. */
  909. function stateScope() {
  910. var scope = {};
  911. store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
  912. return scope;
  913. }
  914. /** Read a type's `public` data (what the attributes bind to). */
  915. function read(type) {
  916. var entry = store.get(type);
  917. return entry ? entry.snapshot.public : undefined;
  918. }
  919. /** Read a type's full snapshot object. */
  920. function getSnapshot(type) {
  921. var entry = store.get(type);
  922. return entry ? entry.snapshot : undefined;
  923. }
  924. /** Read the frame wrapping a type's snapshot. */
  925. function getFrame(type) {
  926. var entry = store.get(type);
  927. return entry ? entry.frame : undefined;
  928. }
  929. /** Build an object of `{ typeName: public }` for every held type. */
  930. function state() {
  931. var result = {};
  932. store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
  933. return result;
  934. }
  935. /**
  936. * Clear state. With a type argument, clears that type only; without, clears
  937. * all held state.
  938. * @param {string} [type]
  939. */
  940. function clear(type) {
  941. if (type === undefined) {
  942. Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
  943. } else {
  944. clearType(type, { broadcast: true });
  945. }
  946. renderAll();
  947. }
  948. /**
  949. * Perform an action. `action` may be an action object or a string path that
  950. * resolves to an action object within the current state.
  951. * @param {object|string} action
  952. * @param {object} [data]
  953. * @returns {Promise<void>}
  954. */
  955. function act(action, data) {
  956. var resolved = action;
  957. if (typeof action === 'string') resolved = evalExpr(action, stateScope());
  958. if (!resolved || typeof resolved.uri !== 'string') {
  959. return Promise.reject(new StatumError('Invalid action'));
  960. }
  961. return performAction(resolved, data, null);
  962. }
  963. /** Attach a state listener for a type. */
  964. function addStateListener(type, callback) {
  965. if (typeof callback !== 'function') return;
  966. if (!listeners.has(type)) listeners.set(type, new Set());
  967. listeners.get(type).add(callback);
  968. }
  969. /** Remove a previously-attached state listener. */
  970. function removeStateListener(type, callback) {
  971. var set = listeners.get(type);
  972. if (!set) return;
  973. set.delete(callback);
  974. if (set.size === 0) listeners.delete(type);
  975. }
  976. // ---------------------------------------------------------------------------
  977. // Initialization
  978. // ---------------------------------------------------------------------------
  979. /**
  980. * Initialize Statum: read URL overrides, run the session-cookie check,
  981. * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
  982. * and render. Safe to call multiple times.
  983. * @returns {Promise<void>}
  984. */
  985. async function init() {
  986. if (initialized) return;
  987. initialized = true;
  988. var body = document.body;
  989. if (body) {
  990. if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
  991. if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
  992. }
  993. try { initSession(); } catch (e) {}
  994. try { hydrate(); } catch (e) {}
  995. setupChannel();
  996. setBootState(false);
  997. renderAll(); // bind against any persisted/hydrated state immediately
  998. try {
  999. await loadEntrypoint();
  1000. } catch (err) {
  1001. console.error('[statum] entrypoint load failed', err);
  1002. } finally {
  1003. setBootState(true);
  1004. }
  1005. }
  1006. function autoInit() {
  1007. if (document.readyState === 'loading') {
  1008. document.addEventListener('DOMContentLoaded', init);
  1009. } else {
  1010. init();
  1011. }
  1012. }
  1013. // ---------------------------------------------------------------------------
  1014. // Public API
  1015. // ---------------------------------------------------------------------------
  1016. /** @namespace statum */
  1017. window.statum = {
  1018. /** Library version. */
  1019. version: '0.1.0',
  1020. /** Mutable endpoint configuration. */
  1021. config: config,
  1022. /** (Re)initialize the library. Usually runs automatically on load. */
  1023. init: init,
  1024. /** Read a type's `public` data. */
  1025. read: read,
  1026. /** Read a type's full snapshot object. */
  1027. getSnapshot: getSnapshot,
  1028. /** Read the frame wrapping a type's snapshot. */
  1029. getFrame: getFrame,
  1030. /** Build `{ typeName: public }` for every held type. */
  1031. state: state,
  1032. /** Clear one type (`clear("x")`) or all state (`clear()`). */
  1033. clear: clear,
  1034. /** Perform an action object or named action. */
  1035. act: act,
  1036. /** Attach a state-changed listener for a type. */
  1037. addStateListener: addStateListener,
  1038. /** Remove a previously-attached listener. */
  1039. removeStateListener: removeStateListener
  1040. };
  1041. autoInit();
  1042. })();