statum-binding.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. /**
  69. * Per-(element, source) plumbing registries: which property listeners /
  70. * attribute observers are already attached, so several bindings may share
  71. * one element without one starving the other (review finding V1).
  72. * @type {WeakMap} element -> { source: true }
  73. */
  74. var propBound = new WeakMap();
  75. var observed = new WeakMap();
  76. /** Variables bound to each (element, property): element -> { name: prop }. */
  77. var propNames = new WeakMap();
  78. /** Live property values: element -> { varName: value }. @type {WeakMap} */
  79. var liveProps = new WeakMap();
  80. /** Stable per-element identity for cache keys. @type {WeakMap} */
  81. var elIds = new WeakMap();
  82. var elSeq = 0;
  83. function elId(el) {
  84. var id = elIds.get(el);
  85. if (id === undefined) { id = ++elSeq; elIds.set(el, id); }
  86. return id;
  87. }
  88. /**
  89. * Resolve one binding for this pass: evaluate at most once, cache, and
  90. * detect re-entrant evaluation of the SAME binding (a cycle).
  91. * @param {string} key unique per binding site (stable across passes)
  92. * @param {string} name variable name, for diagnostics
  93. * @param {Function} compute () => value
  94. */
  95. function resolve(key, name, compute) {
  96. if (Object.prototype.hasOwnProperty.call(passCache, key)) {
  97. return passCache[key];
  98. }
  99. for (var i = 0; i < evalStack.length; i++) {
  100. if (evalStack[i].key === key) {
  101. var chain = [];
  102. for (var j = i; j < evalStack.length; j++) chain.push(evalStack[j].name);
  103. console.error('[statum] variable cycle: ' + chain.concat(name).join(' → '));
  104. return undefined;
  105. }
  106. }
  107. evalStack.push({ key: key, name: name });
  108. try {
  109. var value = compute();
  110. passCache[key] = value;
  111. return value;
  112. } finally {
  113. evalStack.pop();
  114. }
  115. }
  116. /**
  117. * Parse a binding attribute name into {kind, name, source, attr};
  118. * source is the attribute/property name for -from- forms, else null.
  119. * @param {string} attr
  120. */
  121. function parseBinding(attr) {
  122. var m;
  123. if ((m = attr.match(/^stm-global-([A-Za-z_$][\w$]*)-from-(.+)$/)))
  124. return { kind: 'global', name: m[1], source: m[2], attr: attr };
  125. if ((m = attr.match(/^stm-global-([A-Za-z_$][\w$]*)$/)))
  126. return { kind: 'global', name: m[1], source: null, attr: attr };
  127. if ((m = attr.match(/^stm-local-([A-Za-z_$][\w$]*)-from-(.+)$/)))
  128. return { kind: 'local', name: m[1], source: m[2], attr: attr };
  129. if ((m = attr.match(/^stm-local-([A-Za-z_$][\w$]*)$/)))
  130. return { kind: 'local', name: m[1], source: null, attr: attr };
  131. return null;
  132. }
  133. /** Live-property form: from-value/from-checked on a form control. */
  134. function isPropSource(el, source) {
  135. if (source !== 'value' && source !== 'checked') return false;
  136. var tag = el.tagName;
  137. return tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA';
  138. }
  139. /**
  140. * Attach the redraw plumbing for one -from- binding. The listener/observer
  141. * is attached ONCE per (element, source); the VARIABLE registration
  142. * (propNames + seed) happens for every binding — several variables may
  143. * bind the same source, and each must see updates (review finding V1).
  144. */
  145. function bindSource(el, binding) {
  146. var propKey = binding.source;
  147. if (isPropSource(el, propKey)) {
  148. // Register this variable against the property (always).
  149. var names = propNames.get(el) || {};
  150. names[binding.name] = propKey;
  151. propNames.set(el, names);
  152. var seed = liveProps.get(el) || {};
  153. if (!Object.prototype.hasOwnProperty.call(seed, binding.name)) {
  154. seed[binding.name] = el[propKey];
  155. liveProps.set(el, seed);
  156. }
  157. // Attach the shared listener once per (element, property).
  158. var bound = propBound.get(el);
  159. if (bound && bound[propKey]) return;
  160. if (!bound) bound = {};
  161. bound[propKey] = true;
  162. propBound.set(el, bound);
  163. var onChange = function () {
  164. var n = propNames.get(el);
  165. if (!n) return;
  166. var changed = false;
  167. var store = liveProps.get(el) || {};
  168. for (var name in n) {
  169. var key = n[name];
  170. if (store[name] !== el[key]) {
  171. store[name] = el[key];
  172. changed = true;
  173. }
  174. }
  175. if (changed) liveProps.set(el, store);
  176. if (changed) renderAll();
  177. };
  178. el.addEventListener('input', onChange);
  179. el.addEventListener('change', onChange);
  180. return;
  181. }
  182. var seen = observed.get(el);
  183. if (seen && seen[propKey]) return;
  184. if (typeof MutationObserver !== 'function') return;
  185. if (!seen) seen = {};
  186. seen[propKey] = true;
  187. observed.set(el, seen);
  188. var last = el.getAttribute(propKey);
  189. new MutationObserver(function () {
  190. var now = el.getAttribute(propKey);
  191. if (now === last) return; // same-value write: never redraw
  192. last = now;
  193. renderAll();
  194. }).observe(el, { attributes: true, attributeFilter: [propKey] });
  195. }
  196. /**
  197. * Build one binding's value computation. Expression forms evaluate
  198. * against the PARENT scope (a binding cannot reference itself or a
  199. * same-element sibling, matching the stm-def semantics this replaces).
  200. * -from- forms read their live source (attaching plumbing on first use).
  201. */
  202. function makeCompute(el, binding, parentScope) {
  203. if (binding.source === null) {
  204. return function () {
  205. return evalExpr(el.getAttribute(binding.attr), parentScope);
  206. };
  207. }
  208. return function () {
  209. bindSource(el, binding);
  210. if (isPropSource(el, binding.source)) {
  211. var store = liveProps.get(el);
  212. if (store && Object.prototype.hasOwnProperty.call(store, binding.name)) {
  213. return store[binding.name];
  214. }
  215. }
  216. return el.getAttribute(binding.source);
  217. };
  218. }
  219. /**
  220. * Expose a lazily-resolved variable on a scope. `slot`, when present, is
  221. * a declared slot (see buildScope): resolution goes through the slot so
  222. * the NEWEST binder in the subtree supplies the value, and the cache key
  223. * is the SLOT's (one evaluation per pass no matter which getter is read).
  224. */
  225. function defineVar(scope, name, key, compute, slot) {
  226. if (slot) slot.compute = compute;
  227. Object.defineProperty(scope, name, {
  228. configurable: true,
  229. enumerable: true,
  230. get: function () {
  231. if (slot) return resolve(key, name, slot.compute);
  232. return resolve(key, name, compute);
  233. },
  234. set: function (v) { // expressions never assign; escape hatch only
  235. Object.defineProperty(scope, name, {
  236. configurable: true, writable: true, value: v
  237. });
  238. }
  239. });
  240. }
  241. /**
  242. * Walk UP a scope chain for a declared slot named `name`.
  243. * @returns {{key: string, compute: Function}|null}
  244. */
  245. function findDeclared(scope, name) {
  246. var s = scope;
  247. while (s) {
  248. if (Object.prototype.hasOwnProperty.call(s, DECLARED) && s[DECLARED][name]) {
  249. return s[DECLARED][name];
  250. }
  251. s = Object.getPrototypeOf(s);
  252. }
  253. return null;
  254. }
  255. /**
  256. * Scope construction seam (document's walk calls this for every element;
  257. * core defaults to identity). Elements carrying stm-local-* or
  258. * stm-declare-* get a child scope with lazy getters; others pass through
  259. * unchanged.
  260. */
  261. function buildScope(el, scope) {
  262. var attrs = el.attributes;
  263. var child = null;
  264. var declaredHere = null;
  265. for (var i = 0; i < attrs.length; i++) {
  266. var attrName = attrs[i].name;
  267. var binding = parseBinding(attrName);
  268. if (binding && binding.kind === 'local') {
  269. if (!child) child = Object.create(scope || null);
  270. // If an ancestor declared this name, bind into its slot so the
  271. // declarer's whole subtree (including siblings of this element)
  272. // reads this binding.
  273. var slot = findDeclared(child, binding.name);
  274. var key = slot ? slot.key
  275. : 'local:' + binding.name + ':' + elId(el) + ':' + attrName;
  276. defineVar(child, binding.name, key,
  277. makeCompute(el, binding, scope), slot);
  278. } else if (attrName.indexOf('stm-declare-') === 0) {
  279. var dName = attrName.slice('stm-declare-'.length);
  280. if (!dName) continue;
  281. if (!child) child = Object.create(scope || null);
  282. if (!declaredHere) {
  283. declaredHere = {};
  284. Object.defineProperty(child, DECLARED, { value: declaredHere });
  285. }
  286. if (!declaredHere[dName]) {
  287. var dSlot = { key: 'declare:' + dName + ':' + elId(el),
  288. compute: function () { return undefined; } };
  289. declaredHere[dName] = dSlot;
  290. defineVar(child, dName, dSlot.key, dSlot.compute, dSlot);
  291. }
  292. }
  293. }
  294. return child || scope;
  295. }
  296. /**
  297. * Pass start (document's walk driver calls this with the root scope):
  298. * reset the per-pass cache and expose every stm-global-* on the root
  299. * scope so they are visible page-wide. Later declarations overwrite
  300. * earlier ones (getters redefine); duplicates warn once per pass.
  301. */
  302. function passStart(rootScope) {
  303. passCache = {};
  304. var seenByName = {};
  305. var els = document.querySelectorAll('*');
  306. for (var i = 0; i < els.length; i++) {
  307. var el = els[i];
  308. var attrs = el.attributes;
  309. for (var j = 0; j < attrs.length; j++) {
  310. var name = attrs[j].name;
  311. if (name.indexOf('stm-global-') !== 0) continue;
  312. var binding = parseBinding(name);
  313. if (!binding) continue;
  314. if (seenByName[binding.name] && seenByName[binding.name] !== el) {
  315. console.warn('[statum] stm-global-' + binding.name +
  316. ' declared more than once; the last declaration in document order wins');
  317. }
  318. seenByName[binding.name] = el;
  319. defineVar(rootScope, binding.name, 'global:' + binding.name,
  320. makeCompute(el, binding, rootScope));
  321. }
  322. }
  323. }
  324. // --- installation -------------------------------------------------------
  325. bridge.buildScope(buildScope);
  326. bridge.onPassStart(passStart);
  327. })();