statum-binding.js 12 KB

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