statum-binding.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /**
  2. * statum-binding.js — client-side variables for Statum pages.
  3. *
  4. * Load position: after statum-core.js and statum-document.js. This module
  5. * and statum-markdown.js are order-independent and need not co-exist.
  6. *
  7. * ES5-style, zero dependencies, guarded IIFE. Attributes:
  8. *
  9. * stm-global-{name}="expr" page-wide variable, usable in any
  10. * expression anywhere on the page
  11. * stm-global-{name}-from-{attribute} page-wide variable sourced from an
  12. * element attribute; changes to that
  13. * attribute trigger a redraw
  14. * stm-local-{name}="expr" subtree-scoped variable (element +
  15. * descendants); supersedes
  16. * stm-def-{name}-as (kept as an
  17. * obsolescent alias, see below)
  18. * stm-local-{name}-from-{attribute} subtree-scoped attribute-sourced
  19. * variable; changes trigger a redraw
  20. * stm-declare-{name} declares {name} for a subtree so a
  21. * descendant can bind it and SIBLINGS
  22. * of that binder can read it
  23. *
  24. * The legacy `stm-def-{name}-as="expr"` spelling (the pre-binding-module
  25. * form, still emitted by older templates) is accepted as an exact alias of
  26. * `stm-local-{name}` and logs a one-time obsolescence warning per element.
  27. *
  28. * Semantics (operator-confirmed):
  29. * - LAZY-CACHED: a binding's expression evaluates at most once per render
  30. * pass, only when something reads the variable; the result is cached for
  31. * the pass and the cache resets each pass.
  32. * - CYCLES are an error, not a crash: re-entrant evaluation of the SAME
  33. * binding logs '[statum] variable cycle: a → b → a' (variable names) and
  34. * the variable reads as undefined for that pass. Distinct bindings that
  35. * shadow a name are not cycles (an inner `x` may reference an outer `x`).
  36. * - `from-value` / `from-checked` on input/select/textarea read the live
  37. * PROPERTY (not the attribute): an input/change listener updates the
  38. * variable and calls renderAll() directly, per keystroke. Every other
  39. * attribute name, and every non-form-control element, uses a
  40. * MutationObserver.
  41. * - Redraw guard: an observed attribute change only redraws when the
  42. * variable's derived value actually changed — the walk itself writes
  43. * attributes (stm-attribute.*, hidden, data-stm-active) and a naive
  44. * observer would loop forever.
  45. * - A stm-global is visible page-wide on the FIRST pass it is declared in,
  46. * even at elements that precede its declaring element in document order
  47. * (the pass-start sweep exposes lazy getters; each reader resolves the
  48. * binding on demand, at most once per pass).
  49. * - Shadowing: a variable shadows slot types and outer variables with the
  50. * same name inside its scope. Duplicate stm-global-{name}: last in
  51. * document order wins, one console.warn per pass.
  52. */
  53. (function () {
  54. if (!window.statum || !window.statum._bridge) {
  55. console.error('[statum] statum-binding.js requires statum-core.js');
  56. return;
  57. }
  58. if (!window.statum.registerAttribute) {
  59. console.error('[statum] statum-binding.js requires statum-document.js');
  60. return;
  61. }
  62. var bridge = window.statum._bridge;
  63. var evalExpr = bridge.evalExpr;
  64. var renderAll = bridge.renderAll;
  65. // Scope-chain marker for declared slots. Expressions evaluate through the
  66. // evalScope proxy, whose `with` semantics only surface string keys, so
  67. // this key is invisible to page code.
  68. var DECLARED = '__stmDeclared';
  69. /** Per-pass cache: binding key -> value. Reset at every pass start. */
  70. var passCache = {};
  71. /** Evaluation stack for cycle detection: {key, name}, innermost last. */
  72. var evalStack = [];
  73. /**
  74. * Per-(element, source) plumbing registries: which property listeners /
  75. * attribute observers are already attached, so several bindings may share
  76. * one element without one starving the other (review finding V1).
  77. * @type {WeakMap} element -> { source: true }
  78. */
  79. var propBound = new WeakMap();
  80. var observed = new WeakMap();
  81. /** Variables bound to each (element, property): element -> { name: prop }. */
  82. var propNames = new WeakMap();
  83. /** Live property values: element -> { varName: value }. @type {WeakMap} */
  84. var liveProps = new WeakMap();
  85. /** Stable per-element identity for cache keys. @type {WeakMap} */
  86. var elIds = new WeakMap();
  87. var elSeq = 0;
  88. /** Elements already warned for legacy stm-def usage. @type {WeakSet} */
  89. var legacyWarned = new WeakSet();
  90. function elId(el) {
  91. var id = elIds.get(el);
  92. if (id === undefined) { id = ++elSeq; elIds.set(el, id); }
  93. return id;
  94. }
  95. /**
  96. * Resolve one binding for this pass: evaluate at most once, cache, and
  97. * detect re-entrant evaluation of the SAME binding (a cycle).
  98. * @param {string} key unique per binding site (stable across passes)
  99. * @param {string} name variable name, for diagnostics
  100. * @param {Function} compute () => value
  101. */
  102. function resolve(key, name, compute) {
  103. if (Object.prototype.hasOwnProperty.call(passCache, key)) {
  104. return passCache[key];
  105. }
  106. for (var i = 0; i < evalStack.length; i++) {
  107. if (evalStack[i].key === key) {
  108. var chain = [];
  109. for (var j = i; j < evalStack.length; j++) chain.push(evalStack[j].name);
  110. console.error('[statum] variable cycle: ' + chain.concat(name).join(' → '));
  111. return undefined;
  112. }
  113. }
  114. evalStack.push({ key: key, name: name });
  115. try {
  116. var value = compute();
  117. passCache[key] = value;
  118. return value;
  119. } finally {
  120. evalStack.pop();
  121. }
  122. }
  123. /**
  124. * Parse a binding attribute name into {kind, name, source, attr};
  125. * source is the attribute/property name for -from- forms, else null.
  126. * `stm-def-{name}-as` (the pre-binding spelling) parses as a LOCAL
  127. * expression binding with legacy=true: identical semantics, plus an
  128. * obsolescence warning at bind time.
  129. * @param {string} attr
  130. */
  131. function parseBinding(attr) {
  132. var m;
  133. if ((m = attr.match(/^stm-global-([A-Za-z_$][\w$]*)-from-(.+)$/)))
  134. return { kind: 'global', name: m[1], source: m[2], attr: attr };
  135. if ((m = attr.match(/^stm-global-([A-Za-z_$][\w$]*)$/)))
  136. return { kind: 'global', name: m[1], source: null, attr: attr };
  137. if ((m = attr.match(/^stm-local-([A-Za-z_$][\w$]*)-from-(.+)$/)))
  138. return { kind: 'local', name: m[1], source: m[2], attr: attr };
  139. if ((m = attr.match(/^stm-local-([A-Za-z_$][\w$]*)$/)))
  140. return { kind: 'local', name: m[1], source: null, attr: attr };
  141. if ((m = attr.match(/^stm-def-([A-Za-z_$][\w$]*)-as$/)))
  142. return { kind: 'local', name: m[1], source: null, attr: attr, legacy: true };
  143. return null;
  144. }
  145. /** Live-property form: from-value/from-checked on a form control. */
  146. function isPropSource(el, source) {
  147. if (source !== 'value' && source !== 'checked') return false;
  148. var tag = el.tagName;
  149. return tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA';
  150. }
  151. /**
  152. * Attach the redraw plumbing for one -from- binding. The listener/observer
  153. * is attached ONCE per (element, source); the VARIABLE registration
  154. * (propNames + seed) happens for every binding — several variables may
  155. * bind the same source, and each must see updates (review finding V1).
  156. */
  157. function bindSource(el, binding) {
  158. var propKey = binding.source;
  159. if (isPropSource(el, propKey)) {
  160. // Register this variable against the property (always).
  161. var names = propNames.get(el) || {};
  162. names[binding.name] = propKey;
  163. propNames.set(el, names);
  164. var seed = liveProps.get(el) || {};
  165. if (!Object.prototype.hasOwnProperty.call(seed, binding.name)) {
  166. seed[binding.name] = el[propKey];
  167. liveProps.set(el, seed);
  168. }
  169. // Attach the shared listener once per (element, property).
  170. var bound = propBound.get(el);
  171. if (bound && bound[propKey]) return;
  172. if (!bound) bound = {};
  173. bound[propKey] = true;
  174. propBound.set(el, bound);
  175. var onChange = function () {
  176. var n = propNames.get(el);
  177. if (!n) return;
  178. var changed = false;
  179. var store = liveProps.get(el) || {};
  180. for (var name in n) {
  181. var key = n[name];
  182. if (store[name] !== el[key]) {
  183. store[name] = el[key];
  184. changed = true;
  185. }
  186. }
  187. if (changed) liveProps.set(el, store);
  188. if (changed) renderAll();
  189. };
  190. el.addEventListener('input', onChange);
  191. el.addEventListener('change', onChange);
  192. return;
  193. }
  194. var seen = observed.get(el);
  195. if (seen && seen[propKey]) return;
  196. if (typeof MutationObserver !== 'function') return;
  197. if (!seen) seen = {};
  198. seen[propKey] = true;
  199. observed.set(el, seen);
  200. var last = el.getAttribute(propKey);
  201. new MutationObserver(function () {
  202. var now = el.getAttribute(propKey);
  203. if (now === last) return; // same-value write: never redraw
  204. last = now;
  205. renderAll();
  206. }).observe(el, { attributes: true, attributeFilter: [propKey] });
  207. }
  208. /**
  209. * Build one binding's value computation. Expression forms evaluate
  210. * against the PARENT scope (a binding cannot reference itself or a
  211. * same-element sibling, matching the stm-def semantics this replaces).
  212. * -from- forms read their live source (attaching plumbing on first use).
  213. */
  214. function makeCompute(el, binding, parentScope) {
  215. if (binding.source === null) {
  216. return function () {
  217. return evalExpr(el.getAttribute(binding.attr), parentScope);
  218. };
  219. }
  220. return function () {
  221. bindSource(el, binding);
  222. if (isPropSource(el, binding.source)) {
  223. var store = liveProps.get(el);
  224. if (store && Object.prototype.hasOwnProperty.call(store, binding.name)) {
  225. return store[binding.name];
  226. }
  227. }
  228. return el.getAttribute(binding.source);
  229. };
  230. }
  231. /**
  232. * Expose a lazily-resolved variable on a scope. `slot`, when present, is
  233. * a declared slot (see buildScope): resolution goes through the slot so
  234. * the NEWEST binder in the subtree supplies the value, and the cache key
  235. * is the SLOT's (one evaluation per pass no matter which getter is read).
  236. */
  237. function defineVar(scope, name, key, compute, slot) {
  238. if (slot) slot.compute = compute;
  239. Object.defineProperty(scope, name, {
  240. configurable: true,
  241. enumerable: true,
  242. get: function () {
  243. if (slot) return resolve(key, name, slot.compute);
  244. return resolve(key, name, compute);
  245. },
  246. set: function (v) { // expressions never assign; escape hatch only
  247. Object.defineProperty(scope, name, {
  248. configurable: true, writable: true, value: v
  249. });
  250. }
  251. });
  252. }
  253. /**
  254. * Walk UP a scope chain for a declared slot named `name`.
  255. * @returns {{key: string, compute: Function}|null}
  256. */
  257. function findDeclared(scope, name) {
  258. var s = scope;
  259. while (s) {
  260. if (Object.prototype.hasOwnProperty.call(s, DECLARED) && s[DECLARED][name]) {
  261. return s[DECLARED][name];
  262. }
  263. s = Object.getPrototypeOf(s);
  264. }
  265. return null;
  266. }
  267. /**
  268. * Scope construction seam (document's walk calls this for every element;
  269. * core defaults to identity). Elements carrying stm-local-* or
  270. * stm-declare-* get a child scope with lazy getters; others pass through
  271. * unchanged.
  272. */
  273. function buildScope(el, scope) {
  274. var attrs = el.attributes;
  275. var child = null;
  276. var declaredHere = null;
  277. for (var i = 0; i < attrs.length; i++) {
  278. var attrName = attrs[i].name;
  279. var binding = parseBinding(attrName);
  280. if (binding && binding.kind === 'local') {
  281. if (!child) child = Object.create(scope || null);
  282. if (binding.legacy && !legacyWarned.has(el)) {
  283. legacyWarned.add(el);
  284. console.warn('[statum] stm-def-' + binding.name + '-as is obsolescent; ' +
  285. 'use stm-local-' + binding.name + ' (same semantics)');
  286. }
  287. // If an ancestor declared this name, bind into its slot so the
  288. // declarer's whole subtree (including siblings of this element)
  289. // reads this binding.
  290. var slot = findDeclared(child, binding.name);
  291. var key = slot ? slot.key
  292. : 'local:' + binding.name + ':' + elId(el) + ':' + attrName;
  293. defineVar(child, binding.name, key,
  294. makeCompute(el, binding, scope), slot);
  295. } else if (attrName.indexOf('stm-declare-') === 0) {
  296. var dName = attrName.slice('stm-declare-'.length);
  297. if (!dName) continue;
  298. if (!child) child = Object.create(scope || null);
  299. if (!declaredHere) {
  300. declaredHere = {};
  301. Object.defineProperty(child, DECLARED, { value: declaredHere });
  302. }
  303. if (!declaredHere[dName]) {
  304. var dSlot = { key: 'declare:' + dName + ':' + elId(el),
  305. compute: function () { return undefined; } };
  306. declaredHere[dName] = dSlot;
  307. defineVar(child, dName, dSlot.key, dSlot.compute, dSlot);
  308. }
  309. }
  310. }
  311. return child || scope;
  312. }
  313. /**
  314. * Pass start (document's walk driver calls this with the root scope):
  315. * reset the per-pass cache and expose every stm-global-* on the root
  316. * scope so they are visible page-wide. Later declarations overwrite
  317. * earlier ones (getters redefine); duplicates warn once per pass.
  318. */
  319. function passStart(rootScope) {
  320. passCache = {};
  321. var seenByName = {};
  322. var els = document.querySelectorAll('*');
  323. for (var i = 0; i < els.length; i++) {
  324. var el = els[i];
  325. var attrs = el.attributes;
  326. for (var j = 0; j < attrs.length; j++) {
  327. var name = attrs[j].name;
  328. if (name.indexOf('stm-global-') !== 0) continue;
  329. var binding = parseBinding(name);
  330. if (!binding) continue;
  331. if (seenByName[binding.name] && seenByName[binding.name] !== el) {
  332. console.warn('[statum] stm-global-' + binding.name +
  333. ' declared more than once; the last declaration in document order wins');
  334. }
  335. seenByName[binding.name] = el;
  336. defineVar(rootScope, binding.name, 'global:' + binding.name,
  337. makeCompute(el, binding, rootScope));
  338. }
  339. }
  340. }
  341. // --- installation -------------------------------------------------------
  342. bridge.buildScope(buildScope);
  343. bridge.onPassStart(passStart);
  344. })();