statum.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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-attribute.{name}`: a boolean result toggles the attribute, any
  661. * other defined value sets it, and `undefined` removes it.
  662. *
  663. * For booleans, prefer the element's IDL property when one exists (e.g.
  664. * `checked`, `disabled`, `hidden`) — setting the content attribute is
  665. * unreliable for these once the control is "dirty".
  666. */
  667. function handleAttribute(el, scope) {
  668. var attrs = el.attributes;
  669. for (var i = 0; i < attrs.length; i++) {
  670. var attr = attrs[i];
  671. if (attr.name.indexOf('stm-attribute.') === 0) {
  672. var name = attr.name.slice('stm-attribute.'.length);
  673. if (!name) continue;
  674. var value = evalExpr(attr.value, scope);
  675. if (value === undefined) {
  676. el.removeAttribute(name);
  677. } else if (typeof value === 'boolean') {
  678. if (name in el && typeof el[name] === 'boolean') el[name] = value;
  679. else if (value) el.setAttribute(name, '');
  680. else el.removeAttribute(name);
  681. } else {
  682. el.setAttribute(name, value === null ? '' : String(value));
  683. }
  684. }
  685. }
  686. }
  687. /**
  688. * Apply `stm-disabled`: when the predicate is truthy, disable the element and
  689. * its descendant form controls; otherwise enable them.
  690. */
  691. function handleDisabled(el, scope) {
  692. if (!el.hasAttribute('stm-disabled')) return;
  693. setDisabledCascade(el, !!evalExpr(el.getAttribute('stm-disabled'), scope));
  694. }
  695. /** Set the `disabled` attribute on an element and its descendant controls. */
  696. function setDisabledCascade(el, on) {
  697. var nodes = [el].concat(Array.prototype.slice.call(
  698. el.querySelectorAll('button,input,select,textarea,fieldset')));
  699. nodes.forEach(function (n) {
  700. if (on) n.setAttribute('disabled', ''); else n.removeAttribute('disabled');
  701. });
  702. }
  703. /**
  704. * Bind `stm-text` / `stm-html`. Per the "leave original DOM content" policy,
  705. * an unresolved value (`undefined`) leaves the element untouched; otherwise
  706. * the value is stringified (`null` becomes the empty string).
  707. */
  708. function handleTextHtml(el, scope) {
  709. if (el.hasAttribute('stm-text')) {
  710. var text = evalExpr(el.getAttribute('stm-text'), scope);
  711. if (text !== undefined) el.textContent = text === null ? '' : String(text);
  712. }
  713. if (el.hasAttribute('stm-html')) {
  714. var html = evalExpr(el.getAttribute('stm-html'), scope);
  715. if (html !== undefined) el.innerHTML = html === null ? '' : String(html);
  716. }
  717. }
  718. /**
  719. * Expand a loop holder: reconcile its instances against the current array.
  720. * Keyed loops (`stm-key`) reuse DOM nodes for unchanged keys to preserve
  721. * focus/selection/input state; unkeyed loops rebuild wholesale.
  722. */
  723. function handleLoop(el, scope) {
  724. var info = getStmFor(el);
  725. if (!info) return;
  726. var template = templates.get(el);
  727. if (!template) {
  728. template = el.cloneNode(true);
  729. stripLoopAttrs(template);
  730. templates.set(el, template);
  731. }
  732. var raw = evalExpr(info.expr, scope);
  733. if (raw === undefined) {
  734. // No value for the source path yet: clear instances and restore the
  735. // server-rendered holder content (progressive enhancement).
  736. var prev = instancesByHolder.get(el) || [];
  737. prev.forEach(function (n) { n.remove(); });
  738. instancesByHolder.set(el, []);
  739. if (el.getAttribute('data-stm-active') === '1') {
  740. el.removeAttribute('data-stm-active');
  741. el.removeAttribute('hidden');
  742. }
  743. return;
  744. }
  745. var arr = Array.isArray(raw) ? raw : [];
  746. // Activate: hide the holder so only rendered instances are visible.
  747. if (el.getAttribute('data-stm-active') !== '1') {
  748. el.setAttribute('data-stm-active', '1');
  749. el.setAttribute('hidden', '');
  750. }
  751. var keyExpr = el.getAttribute('stm-key');
  752. var next = [];
  753. if (keyExpr) {
  754. var oldByKey = new Map();
  755. (instancesByHolder.get(el) || []).forEach(function (n) {
  756. if (n.__stmKey !== undefined) oldByKey.set(n.__stmKey, n);
  757. });
  758. var used = new Set();
  759. arr.forEach(function (item) {
  760. var child = childScope(scope, info.varName, item);
  761. var key = evalExpr(keyExpr, child);
  762. var node = (key !== undefined && !used.has(key)) ? oldByKey.get(key) : undefined;
  763. if (node) {
  764. used.add(key);
  765. processElement(node, child);
  766. } else {
  767. node = template.cloneNode(true);
  768. node.__stmKey = key;
  769. instanceNodes.add(node);
  770. processElement(node, child);
  771. }
  772. next.push(node);
  773. });
  774. oldByKey.forEach(function (n, key) { if (!used.has(key)) n.remove(); });
  775. } else {
  776. (instancesByHolder.get(el) || []).forEach(function (n) { n.remove(); });
  777. arr.forEach(function (item) {
  778. var child = childScope(scope, info.varName, item);
  779. var node = template.cloneNode(true);
  780. instanceNodes.add(node);
  781. processElement(node, child);
  782. next.push(node);
  783. });
  784. }
  785. // Place instances in order, immediately after the holder.
  786. var ref = el;
  787. next.forEach(function (node) {
  788. if (node !== ref.nextSibling) ref.parentNode.insertBefore(node, ref.nextSibling);
  789. ref = node;
  790. });
  791. instancesByHolder.set(el, next);
  792. }
  793. /**
  794. * Process one element's bindings (and recurse). Loop holders are handled by
  795. * {@link handleLoop}; `stm-else-if` / `stm-else` are owned by their `stm-if`.
  796. */
  797. function processElement(el, scope) {
  798. if (getStmFor(el)) { handleLoop(el, scope); return; }
  799. if (el.hasAttribute('stm-else-if') || el.hasAttribute('stm-else')) return;
  800. if (el.hasAttribute('stm-if')) {
  801. var active = handleIfChain(el, scope);
  802. if (active) processInner(active, scope);
  803. return;
  804. }
  805. processInner(el, scope);
  806. }
  807. /** Bind the non-control-flow attributes and recurse into children. */
  808. function processInner(el, scope) {
  809. el.__stmScope = scope; // latest scope, used when an action fires
  810. handleClass(el, scope);
  811. handleAttribute(el, scope);
  812. handleDisabled(el, scope);
  813. handleTextHtml(el, scope);
  814. wireAction(el);
  815. render(el, scope);
  816. }
  817. /**
  818. * Walk an element's children, processing each. Loop instance nodes are
  819. * skipped here (they are owned and processed by their holder).
  820. */
  821. function render(root, scope) {
  822. if (!root || !root.children) return;
  823. // Snapshot the children: processing mutates the DOM (detaching branches,
  824. // inserting loop instances) and a live HTMLCollection would shift indices.
  825. var children = Array.prototype.slice.call(root.children);
  826. for (var i = 0; i < children.length; i++) {
  827. var el = children[i];
  828. if (instanceNodes.has(el)) continue;
  829. processElement(el, scope);
  830. }
  831. }
  832. /** Re-render the whole document against the current state. */
  833. function renderAll() {
  834. try { render(document.body, stateScope()); }
  835. catch (e) { console.error('[statum] render error', e); }
  836. }
  837. // ---------------------------------------------------------------------------
  838. // HTML API: actions
  839. // ---------------------------------------------------------------------------
  840. /**
  841. * Collect data for an action trigger: `stm-data-{key}` attributes plus, for a
  842. * form, its named inputs.
  843. * @param {HTMLElement} el
  844. * @returns {object}
  845. */
  846. function collectData(el) {
  847. var data = {};
  848. var attrs = el.attributes;
  849. for (var i = 0; i < attrs.length; i++) {
  850. var name = attrs[i].name;
  851. if (name.indexOf('stm-data-') === 0) data[name.slice('stm-data-'.length)] = attrs[i].value;
  852. }
  853. if (el.tagName === 'FORM') {
  854. var fd = new FormData(el);
  855. fd.forEach(function (value, key) {
  856. data[key] = value instanceof File ? value.name : String(value);
  857. });
  858. }
  859. return data;
  860. }
  861. /**
  862. * Toggle the busy state of an action element: disables the element and its
  863. * descendant form controls and applies `stm-busy-class` classes while busy.
  864. *
  865. * On un-busy the disabled state is not "restored" to a captured snapshot
  866. * (that would clobber a `stm-disabled` value that `renderAll` applied during
  867. * the response); instead the nodes are re-enabled and `stm-disabled` is
  868. * re-evaluated, which re-disables any that should remain disabled.
  869. */
  870. function setBusyState(el, busy) {
  871. var nodes = [el].concat(Array.prototype.slice.call(
  872. el.querySelectorAll('button,input,select,textarea,fieldset')));
  873. var busyClasses = (el.getAttribute('stm-busy-class') || '').split(/\s+/).filter(Boolean);
  874. if (busy) {
  875. nodes.forEach(function (n) { n.setAttribute('disabled', ''); });
  876. busyClasses.forEach(function (c) { el.classList.add(c); });
  877. } else {
  878. nodes.forEach(function (n) { n.removeAttribute('disabled'); });
  879. busyClasses.forEach(function (c) { el.classList.remove(c); });
  880. reapplyDisabled(el);
  881. }
  882. }
  883. /** Re-apply `stm-disabled` to an element and any descendants that carry it. */
  884. function reapplyDisabled(el) {
  885. var scope = el.__stmScope || stateScope();
  886. if (el.hasAttribute('stm-disabled')) handleDisabled(el, scope);
  887. var scoped = el.querySelectorAll('[stm-disabled]');
  888. Array.prototype.forEach.call(scoped, function (n) {
  889. handleDisabled(n, n.__stmScope || scope);
  890. });
  891. }
  892. /** Apply or remove `stm-on-error` classes on an action element. */
  893. function applyErrorClasses(el, on) {
  894. if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
  895. var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
  896. classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
  897. }
  898. /**
  899. * Wire an element's primary action once. The listener resolves the action
  900. * object against the element's latest render scope, so loop instances bind to
  901. * their own item.
  902. */
  903. function wireAction(el) {
  904. if (!el.hasAttribute('stm-action') || wired.has(el)) return;
  905. wired.add(el);
  906. var eventName = el.tagName === 'FORM' ? 'submit' : 'click';
  907. el.addEventListener(eventName, function (event) {
  908. event.preventDefault();
  909. runElementAction(el);
  910. });
  911. }
  912. /**
  913. * Resolve and perform the action attached to an element, managing busy and
  914. * error-state classes around the request.
  915. * @param {HTMLElement} el
  916. */
  917. async function runElementAction(el) {
  918. var scope = el.__stmScope || stateScope();
  919. var action = evalExpr(el.getAttribute('stm-action'), scope);
  920. if (!action || typeof action.uri !== 'string') return;
  921. // stm-confirm: gate the action behind a confirm() dialog (literal message).
  922. if (el.hasAttribute('stm-confirm') && !window.confirm(el.getAttribute('stm-confirm'))) return;
  923. applyErrorClasses(el, false); // clear error state on a new attempt
  924. var data = collectData(el);
  925. setBusyState(el, true);
  926. try {
  927. await performAction(action, data, el);
  928. } catch (err) {
  929. // stm-on-error is applied by the directive path for `error` directives;
  930. // ensure it is also applied for other failures (network, HTTP).
  931. applyErrorClasses(el, true);
  932. } finally {
  933. setBusyState(el, false);
  934. }
  935. }
  936. // ---------------------------------------------------------------------------
  937. // Boot visibility (stm-preloader / stm-content)
  938. // ---------------------------------------------------------------------------
  939. /**
  940. * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
  941. * loading, `stm-preloader` elements are shown and `stm-content` elements
  942. * hidden; once ready, the reverse.
  943. *
  944. * To avoid a flash of un-bound template before the script runs, authors may
  945. * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
  946. * `<div stm-content hidden>`); the library removes it once ready. The library
  947. * also sets `hidden` itself during loading as a fallback for authors who do
  948. * not pre-set it.
  949. * @param {boolean} ready
  950. */
  951. function setBootState(ready) {
  952. var preloaders = document.querySelectorAll('[stm-preloader]');
  953. var contents = document.querySelectorAll('[stm-content]');
  954. for (var i = 0; i < preloaders.length; i++) {
  955. ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
  956. }
  957. for (var j = 0; j < contents.length; j++) {
  958. ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
  959. }
  960. }
  961. // ---------------------------------------------------------------------------
  962. // Public state accessors
  963. // ---------------------------------------------------------------------------
  964. /** Build the scope used for expression evaluation: `{ typeName: public }`. */
  965. function stateScope() {
  966. var scope = {};
  967. store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
  968. return scope;
  969. }
  970. /** Read a type's `public` data (what the attributes bind to). */
  971. function read(type) {
  972. var entry = store.get(type);
  973. return entry ? entry.snapshot.public : undefined;
  974. }
  975. /** Read a type's full snapshot object. */
  976. function getSnapshot(type) {
  977. var entry = store.get(type);
  978. return entry ? entry.snapshot : undefined;
  979. }
  980. /** Read the frame wrapping a type's snapshot. */
  981. function getFrame(type) {
  982. var entry = store.get(type);
  983. return entry ? entry.frame : undefined;
  984. }
  985. /** Build an object of `{ typeName: public }` for every held type. */
  986. function state() {
  987. var result = {};
  988. store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
  989. return result;
  990. }
  991. /**
  992. * Clear state. With a type argument, clears that type only; without, clears
  993. * all held state.
  994. * @param {string} [type]
  995. */
  996. function clear(type) {
  997. if (type === undefined) {
  998. Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
  999. } else {
  1000. clearType(type, { broadcast: true });
  1001. }
  1002. renderAll();
  1003. }
  1004. /**
  1005. * Perform an action. `action` may be an action object or a string path that
  1006. * resolves to an action object within the current state.
  1007. * @param {object|string} action
  1008. * @param {object} [data]
  1009. * @returns {Promise<void>}
  1010. */
  1011. function act(action, data) {
  1012. var resolved = action;
  1013. if (typeof action === 'string') resolved = evalExpr(action, stateScope());
  1014. if (!resolved || typeof resolved.uri !== 'string') {
  1015. return Promise.reject(new StatumError('Invalid action'));
  1016. }
  1017. return performAction(resolved, data, null);
  1018. }
  1019. /** Attach a state listener for a type. */
  1020. function addStateListener(type, callback) {
  1021. if (typeof callback !== 'function') return;
  1022. if (!listeners.has(type)) listeners.set(type, new Set());
  1023. listeners.get(type).add(callback);
  1024. }
  1025. /** Remove a previously-attached state listener. */
  1026. function removeStateListener(type, callback) {
  1027. var set = listeners.get(type);
  1028. if (!set) return;
  1029. set.delete(callback);
  1030. if (set.size === 0) listeners.delete(type);
  1031. }
  1032. // ---------------------------------------------------------------------------
  1033. // Initialization
  1034. // ---------------------------------------------------------------------------
  1035. /**
  1036. * Initialize Statum: read URL overrides, run the session-cookie check,
  1037. * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
  1038. * and render. Safe to call multiple times.
  1039. * @returns {Promise<void>}
  1040. */
  1041. async function init() {
  1042. if (initialized) return;
  1043. initialized = true;
  1044. var body = document.body;
  1045. if (body) {
  1046. if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
  1047. if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
  1048. }
  1049. try { initSession(); } catch (e) {}
  1050. try { hydrate(); } catch (e) {}
  1051. setupChannel();
  1052. setBootState(false);
  1053. renderAll(); // bind against any persisted/hydrated state immediately
  1054. try {
  1055. await loadEntrypoint();
  1056. } catch (err) {
  1057. console.error('[statum] entrypoint load failed', err);
  1058. } finally {
  1059. setBootState(true);
  1060. }
  1061. }
  1062. function autoInit() {
  1063. if (document.readyState === 'loading') {
  1064. document.addEventListener('DOMContentLoaded', init);
  1065. } else {
  1066. init();
  1067. }
  1068. }
  1069. // ---------------------------------------------------------------------------
  1070. // Public API
  1071. // ---------------------------------------------------------------------------
  1072. /** @namespace statum */
  1073. window.statum = {
  1074. /** Library version. */
  1075. version: '0.1.0',
  1076. /** Mutable endpoint configuration. */
  1077. config: config,
  1078. /** (Re)initialize the library. Usually runs automatically on load. */
  1079. init: init,
  1080. /** Read a type's `public` data. */
  1081. read: read,
  1082. /** Read a type's full snapshot object. */
  1083. getSnapshot: getSnapshot,
  1084. /** Read the frame wrapping a type's snapshot. */
  1085. getFrame: getFrame,
  1086. /** Build `{ typeName: public }` for every held type. */
  1087. state: state,
  1088. /** Clear one type (`clear("x")`) or all state (`clear()`). */
  1089. clear: clear,
  1090. /** Perform an action object or named action. */
  1091. act: act,
  1092. /** Attach a state-changed listener for a type. */
  1093. addStateListener: addStateListener,
  1094. /** Remove a previously-attached listener. */
  1095. removeStateListener: removeStateListener
  1096. };
  1097. autoInit();
  1098. })();