scenarios.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. /**
  2. * DOM-walk + forms-module scenarios for the Statum client.
  3. *
  4. * Each scenario runs in a FRESH QuickJS context (run.sh invokes this script
  5. * once per scenario) with a minimal DOM shim (shim.js) that supports the
  6. * render walk and the forms module end to end, including capture-phase
  7. * events, form reset defaults and a scriptable fetch stub.
  8. *
  9. * State enters through the real machinery: a `set` directive returned by the
  10. * fetch stub and applied by bridge.loadEntrypoint() (which re-renders through
  11. * applyDirectives -> renderAll). Signatures vary per step so the idempotency
  12. * guard never short-circuits a deliberate re-render.
  13. *
  14. * 1 walk: stm-if/stm-else chain, stm-text, stm-class.*
  15. * 2 stm-for keyed: node identity preserved per key, removal honored
  16. * 3 stm-for unkeyed: instances rebuilt (all identities change)
  17. * 4 stm-prefill: input + textarea property writes (no attribute)
  18. * 5 stm-prefill: select single + multiple (array)
  19. * 6 stm-prefill: checkbox truthy/falsy/null
  20. * 7 stm-prefill: radio group, same expression per member
  21. * 8 dirty skip: dirty input keeps user value, clean sibling re-fills
  22. * 9 dirty is per element within a form
  23. * 10 reset event un-dirties; prefill re-applies after reset
  24. * 11 stm-clear-on-success: success resets + un-dirties the form
  25. * 12 stm-clear-on-success: failure keeps values and dirty state
  26. * 13 keyed loop of forms: clearing instance 2 leaves 1 and 3 alone
  27. * 14 two sibling forms: clearing A leaves B alone
  28. * 15 statum.document.reset: resets exactly the given form
  29. * 16 handler order: stm-prefill registered before stm-class.*
  30. * 17 reenter: action triggers an in-place entrypoint refresh (fetched twice)
  31. * 18 reenter ordering: refresh before navigate, both execute
  32. * 19 reenter failure: logged only; navigate still runs; promise resolves
  33. * 20 stm-on-success: applied on success, cleared on the next attempt
  34. * 21 stm-on-error/on-success mirroring: failure clears success + vice versa
  35. * 22 stm-clear-on-error: a failing action resets the form
  36. * 23 declined stm-confirm does NOT clear (clear-on-error present)
  37. * 24 headless core: stubbed fetch applies state, no walk, no crash
  38. * 25 stm-local basics: subtree scoping, evaluation through stm-text
  39. * 26 stm-local laziness: once per pass across two reads; twice across passes
  40. * 27 stm-global: page-wide visibility incl. before its declaring element
  41. * 28 stm-global duplicates: last declaration wins, one warn per pass
  42. * 29 variable cycles: logged, read undefined, walk survives
  43. * 30 from-attribute: observer redraws on real change only (same value: none)
  44. * 31 from-value: the declare/username example at the 3-char boundary
  45. * 32 from-checked on a checkbox
  46. * 33 declare-without-binder reads undefined; slot shadowing both ways
  47. * 34 stm-local replaces stm-def (demo's stamp pattern; stm-def inert)
  48. * 35 several -from- bindings on ONE element all update (review V1)
  49. * 36 generic observables: statum.binding.observe + attribute fallback
  50. *
  51. * Usage: qjs tests/dom/scenarios.js <1..36>
  52. */
  53. import * as std from 'std';
  54. import { installShim } from './shim.js';
  55. // Repo root as a CWD-relative path; run.sh cds to the repo root first (same
  56. // convention as tests/markdown/spec-test.js).
  57. var ROOT = '.';
  58. var scenario = scriptArgs.length > 1 ? scriptArgs[1] : '';
  59. function fail(msg) {
  60. std.err.puts('FAIL [' + scenario + '] ' + msg + '\n');
  61. std.exit(1);
  62. }
  63. function check(cond, msg) {
  64. if (!cond) fail(msg);
  65. }
  66. function load(name) {
  67. (0, eval)(std.loadFile(ROOT + '/js/' + name));
  68. }
  69. function loadAll() {
  70. load('statum-core.js');
  71. load('statum-document.js');
  72. load('statum-markdown.js');
  73. }
  74. /** Yield to the job queue n times so promise chains settle. */
  75. async function spin(n) {
  76. for (var i = 0; i < (n || 30); i++) await Promise.resolve();
  77. }
  78. var sigCounter = 0;
  79. /**
  80. * Put `public` data into a slot type through a set directive, then re-render.
  81. * Uses loadEntrypoint (public bridge machinery) so the exact production path
  82. * (fetch -> handleResponse -> applyDirectives -> renderAll) runs.
  83. */
  84. async function setState(typeName, publicData) {
  85. sigCounter++;
  86. var snapshot = { slot: { key: 'k-' + typeName, type: typeName, scope: 'page' }, public: publicData };
  87. globalThis.__shim.setFetch(function () {
  88. return globalThis.__shim.okResponse([{
  89. type: 'set',
  90. snapshot_frame: { content: JSON.stringify(snapshot), signature: 'sig-' + sigCounter }
  91. }]);
  92. });
  93. await globalThis.statum._bridge.loadEntrypoint();
  94. await spin();
  95. }
  96. /** Fire a real (bubbling, non-cancelable-by-default) event on an element. */
  97. function fire(el, type) {
  98. var evt = globalThis.__shim.makeEvent(type);
  99. el.dispatchEvent(evt);
  100. return evt;
  101. }
  102. function el(tag) { return globalThis.__shim.makeElement(tag); }
  103. function input(type, name, value) {
  104. var i = el('input');
  105. if (type) i.setAttribute('type', type);
  106. if (name) i.setAttribute('name', name);
  107. if (value !== undefined) i.setAttribute('value', value);
  108. return i;
  109. }
  110. async function main() {
  111. installShim();
  112. var log = globalThis.__shim.log;
  113. var body = globalThis.__shim.body;
  114. // Scenario 24 runs HEADLESS: core alone, no document module.
  115. if (scenario !== '24') loadAll();
  116. else load('statum-core.js');
  117. // Binding-module scenarios additionally load it (after document).
  118. if (scenario >= 25) load('statum-binding.js');
  119. var s = globalThis.statum;
  120. check(s && s._bridge, 'statum did not load');
  121. if (scenario === '24') {
  122. // Headless core: stub the entrypoint fetch, boot, and prove state was
  123. // applied with no walk and no crash.
  124. check(s.registerAttribute === undefined,
  125. 'headless core must not expose registerAttribute (it is document API)');
  126. check(s.document === undefined, 'headless core must not expose statum.document');
  127. sigCounter++;
  128. var snap = { slot: { key: 'k-h', type: 'h', scope: 'page' }, public: { hello: 'world' } };
  129. globalThis.__shim.setFetch(function () {
  130. return globalThis.__shim.okResponse([{
  131. type: 'set',
  132. snapshot_frame: { content: JSON.stringify(snap), signature: 'sig-h-' + sigCounter }
  133. }]);
  134. });
  135. await s.init();
  136. await spin(50);
  137. check(s.read('h') && s.read('h').hello === 'world',
  138. 'headless boot did not apply the entrypoint state: ' + JSON.stringify(s.state()));
  139. check(JSON.stringify(s.state()) === '{"h":{"hello":"world"}}',
  140. 'unexpected state: ' + JSON.stringify(s.state()));
  141. // A render cycle with no driver and no hooks must not crash or warn.
  142. s._bridge.renderAll();
  143. await spin(20);
  144. check(log.errors.length === 0, 'headless core errored: ' + JSON.stringify(log.errors));
  145. check(log.warns.length === 0, 'headless core warned: ' + JSON.stringify(log.warns));
  146. print('scenario ' + scenario + ': OK');
  147. return;
  148. }
  149. check(s.document && typeof s.document.reset === 'function', 'statum.document.reset missing');
  150. check(typeof s.document.markDirty === 'function' && typeof s.document.isDirty === 'function',
  151. 'statum.document.markDirty/isDirty missing');
  152. check(s.forms === undefined, 'statum.forms must be gone (merged into statum.document)');
  153. check(s._bridge.formsDirty instanceof WeakSet, 'bridge.formsDirty missing');
  154. check(typeof s._bridge.markDirty === 'function' && typeof s._bridge.isDirty === 'function',
  155. 'bridge.markDirty/isDirty missing');
  156. if (scenario === '1') {
  157. // if/else-if/else chain + stm-text + stm-class.*
  158. var w = el('div');
  159. var a = el('p'); a.setAttribute('stm-if', "m.mood === 'up'"); a.textContent = 'up';
  160. var b = el('p'); b.setAttribute('stm-else-if', "m.mood === 'mid'"); b.textContent = 'mid';
  161. var c = el('p'); c.setAttribute('stm-else', ''); c.textContent = 'down';
  162. w.appendChild(a); w.appendChild(b); w.appendChild(c);
  163. var t = el('span'); t.setAttribute('stm-text', 'm.mood');
  164. var cl = el('span'); cl.setAttribute('stm-class.hi', "m.mood === 'up'");
  165. w.appendChild(t); w.appendChild(cl);
  166. body.appendChild(w);
  167. await setState('m', { mood: 'up' });
  168. check(!a.hasAttribute('hidden') && b.hasAttribute('hidden') && c.hasAttribute('hidden'),
  169. 'branch up not exclusively shown');
  170. check(t.textContent === 'up', 'stm-text wrote ' + JSON.stringify(t.textContent));
  171. check(cl.classList.contains('hi'), 'stm-class.hi not applied');
  172. await setState('m', { mood: 'mid' });
  173. check(a.hasAttribute('hidden') && !b.hasAttribute('hidden') && c.hasAttribute('hidden'),
  174. 'branch mid not exclusively shown');
  175. check(!cl.classList.contains('hi'), 'stm-class.hi not removed');
  176. check(t.textContent === 'mid', 'stm-text not updated');
  177. await setState('m', { mood: 'zzz' });
  178. check(a.hasAttribute('hidden') && b.hasAttribute('hidden') && !c.hasAttribute('hidden'),
  179. 'else branch not shown');
  180. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  181. } else if (scenario === '2') {
  182. // Keyed loop: identity per key preserved; removal honored.
  183. var holder = el('div');
  184. holder.setAttribute('stm-for-item-in', 'list.items');
  185. holder.setAttribute('stm-key', 'item.id');
  186. var row = el('p');
  187. row.setAttribute('stm-text', 'item.name');
  188. holder.appendChild(row);
  189. body.appendChild(holder);
  190. await setState('list', { items: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }] });
  191. var insts = holder.parentNode.children.filter(function (n) { return n !== holder; });
  192. // holder is children[0]; instances follow it in order.
  193. var kids = body.children.filter(function (n) { return n !== holder; });
  194. check(kids.length === 3, 'expected 3 instances, got ' + kids.length);
  195. var k1 = kids[0], k2 = kids[1], k3 = kids[2];
  196. // The stm-text binding is on the template's child, so read the child.
  197. check(k1.children[0].textContent === 'a' && k2.children[0].textContent === 'b' &&
  198. k3.children[0].textContent === 'c',
  199. 'instance texts: ' + kids.map(function (n) { return n.children[0] && n.children[0].textContent; }).join(','));
  200. await setState('list', { items: [{ id: 1, name: 'a' }, { id: 3, name: 'c3' }] });
  201. var kids2 = body.children.filter(function (n) { return n !== holder; });
  202. check(kids2.length === 2, 'expected 2 instances after removal, got ' + kids2.length);
  203. check(kids2[0] === k1, 'key 1 node identity not preserved');
  204. check(kids2[1] === k3, 'key 3 node identity not preserved');
  205. check(kids2[1].children[0].textContent === 'c3', 'key 3 text not refreshed');
  206. check(k2.parentNode === null, 'removed instance still attached');
  207. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  208. } else if (scenario === '3') {
  209. // Unkeyed loop: rebuild wholesale.
  210. var holder = el('div');
  211. holder.setAttribute('stm-for-item-in', 'list.items');
  212. var row = el('p');
  213. row.setAttribute('stm-text', 'item.name');
  214. holder.appendChild(row);
  215. body.appendChild(holder);
  216. await setState('list', { items: [{ name: 'a' }, { name: 'b' }] });
  217. var kids = body.children.filter(function (n) { return n !== holder; });
  218. check(kids.length === 2 && kids[0].children[0].textContent === 'a' &&
  219. kids[1].children[0].textContent === 'b', 'initial render');
  220. await setState('list', { items: [{ name: 'a' }, { name: 'b' }] });
  221. var kids2 = body.children.filter(function (n) { return n !== holder; });
  222. check(kids2.length === 2, 'instance count changed');
  223. check(kids2[0] !== kids[0] && kids2[1] !== kids[1], 'unkeyed loop reused nodes');
  224. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  225. } else if (scenario === '4') {
  226. // Prefill writes the value PROPERTY, never the value attribute.
  227. var f = el('form');
  228. var ti = input('text', 'who'); ti.setAttribute('stm-prefill', 'p.who');
  229. var ta = el('textarea'); ta.setAttribute('name', 'bio'); ta.setAttribute('stm-prefill', 'p.bio');
  230. f.appendChild(ti); f.appendChild(ta);
  231. body.appendChild(f);
  232. await setState('p', { who: 'ada', bio: 'hi' });
  233. check(ti.value === 'ada', 'text input value = ' + JSON.stringify(ti.value));
  234. check(ta.value === 'hi', 'textarea value = ' + JSON.stringify(ta.value));
  235. check(ti.getAttribute('value') === null, 'text input value ATTRIBUTE was written');
  236. check(ta.getAttribute('stm-prefill') === 'p.bio', 'stm-prefill attribute consumed');
  237. await setState('p', { who: null, bio: undefined });
  238. check(ti.value === '', 'null should prefill as empty string, got ' + JSON.stringify(ti.value));
  239. check(ta.value === 'hi', 'undefined must leave the element untouched');
  240. await setState('p', { who: 42, bio: 'x' });
  241. check(ti.value === '42', 'number stringified: ' + JSON.stringify(ti.value));
  242. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  243. } else if (scenario === '5') {
  244. // Select single + multiple.
  245. var f = el('form');
  246. var sel = el('select'); sel.setAttribute('stm-prefill', 'p.pick');
  247. var o1 = el('option'); o1.setAttribute('value', 'a'); o1.textContent = 'A';
  248. var o2 = el('option'); o2.setAttribute('value', 'b'); o2.textContent = 'B';
  249. sel.appendChild(o1); sel.appendChild(o2);
  250. var multi = el('select'); multi.setAttribute('multiple', ''); multi.setAttribute('stm-prefill', 'p.set');
  251. var m1 = el('option'); m1.setAttribute('value', 'x');
  252. var m2 = el('option'); m2.setAttribute('value', 'y');
  253. var m3 = el('option'); m3.setAttribute('value', 'z');
  254. multi.appendChild(m1); multi.appendChild(m2); multi.appendChild(m3);
  255. f.appendChild(sel); f.appendChild(multi);
  256. body.appendChild(f);
  257. await setState('p', { pick: 'b', set: ['x', 'z'] });
  258. check(sel.value === 'b', 'single select value = ' + JSON.stringify(sel.value));
  259. check(o2.selected === true && o1.selected === false, 'single select option states wrong');
  260. check(m1.selected === true && m2.selected === false && m3.selected === true,
  261. 'multiple select option states wrong');
  262. await setState('p', { pick: 'nope', set: 'y' });
  263. check(sel.value === '', 'unmatched single select should yield empty value');
  264. check(m1.selected === false && m2.selected === true && m3.selected === false,
  265. 'non-array multiple value must behave like single');
  266. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  267. } else if (scenario === '6') {
  268. // Checkbox: truthy -> checked, falsy/null -> unchecked.
  269. var f = el('form');
  270. var cb = input('checkbox', 'ok'); cb.setAttribute('stm-prefill', 'p.ok');
  271. f.appendChild(cb);
  272. body.appendChild(f);
  273. await setState('p', { ok: true });
  274. check(cb.checked === true, 'truthy did not check');
  275. await setState('p', { ok: false });
  276. check(cb.checked === false, 'falsy did not uncheck');
  277. await setState('p', { ok: null });
  278. check(cb.checked === false, 'null did not uncheck');
  279. await setState('p', { ok: 'yes' });
  280. check(cb.checked === true, 'non-empty string should check');
  281. await setState('p', {}); // ok undefined -> untouched
  282. check(cb.checked === true, 'undefined must leave checked untouched');
  283. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  284. } else if (scenario === '7') {
  285. // Radio group: every member carries the same expression; the member whose
  286. // own value matches the resolved value gets checked.
  287. var f = el('form');
  288. var mk = function (v) {
  289. var r = input('radio', 'g', v);
  290. r.setAttribute('stm-prefill', 'p.choice');
  291. f.appendChild(r);
  292. return r;
  293. };
  294. var ra = mk('a'), rb = mk('b'), rc = mk('c');
  295. body.appendChild(f);
  296. await setState('p', { choice: 'b' });
  297. check(ra.checked === false && rb.checked === true && rc.checked === false,
  298. 'state b checked the wrong member(s)');
  299. await setState('p', { choice: 'd' });
  300. check(ra.checked === false && rb.checked === false && rc.checked === false,
  301. 'state d (no match) must leave all unchecked');
  302. await setState('p', { choice: null });
  303. check(rb.checked === false, 'null must uncheck (String(null) matches nothing)');
  304. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  305. } else if (scenario === '8') {
  306. // A dirty element is never overwritten; a clean sibling still fills.
  307. var f = el('form');
  308. var i1 = input('text', 'one'); i1.setAttribute('stm-prefill', 'p.one');
  309. var i2 = input('text', 'two'); i2.setAttribute('stm-prefill', 'p.two');
  310. f.appendChild(i1); f.appendChild(i2);
  311. body.appendChild(f);
  312. await setState('p', { one: 'x', two: 'x' });
  313. check(i1.value === 'x' && i2.value === 'x', 'initial fill failed');
  314. fire(i1, 'input'); // user edits input 1
  315. check(s.document.isDirty(i1), 'input event did not mark the element dirty');
  316. await setState('p', { one: 'y', two: 'y' });
  317. check(i1.value === 'x', 'dirty element was overwritten: ' + JSON.stringify(i1.value));
  318. check(i2.value === 'y', 'clean sibling not re-filled');
  319. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  320. } else if (scenario === '9') {
  321. // Dirtiness is per element.
  322. var f = el('form');
  323. var i1 = input('text', 'one'); i1.setAttribute('stm-prefill', 'p.v');
  324. var i2 = input('text', 'two'); i2.setAttribute('stm-prefill', 'p.v');
  325. f.appendChild(i1); f.appendChild(i2);
  326. body.appendChild(f);
  327. await setState('p', { v: 'a' });
  328. fire(i1, 'change');
  329. await setState('p', { v: 'b' });
  330. check(i1.value === 'a', 'dirty element overwritten');
  331. check(i2.value === 'b', 'clean element not filled');
  332. check(s.document.isDirty(i1) && !s.document.isDirty(i2), 'dirty flags wrong');
  333. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  334. } else if (scenario === '10') {
  335. // Reset restores defaults, un-dirties, and prefill re-applies.
  336. var f = el('form');
  337. var i1 = input('text', 'one', 'init'); i1.setAttribute('stm-prefill', 'p.v');
  338. f.appendChild(i1);
  339. body.appendChild(f);
  340. await setState('p', { v: 'state' });
  341. check(i1.value === 'state', 'prefill did not apply');
  342. fire(i1, 'input');
  343. check(s.document.isDirty(i1), 'not dirty after edit');
  344. f.reset();
  345. check(i1.value === 'init', 'reset did not restore the attribute default: ' + JSON.stringify(i1.value));
  346. check(!s.document.isDirty(i1), 'reset did not un-dirty');
  347. await setState('p', { v: 'zzz' });
  348. check(i1.value === 'zzz', 'prefill did not re-apply after reset');
  349. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  350. } else if (scenario === '11') {
  351. // Clear-on-success: action resolves -> form resets and un-dirties.
  352. var f = el('form');
  353. f.setAttribute('stm-action', 'p.act');
  354. f.setAttribute('stm-clear-on-success', '');
  355. var i1 = input('text', 'one', 'dflt'); i1.setAttribute('stm-prefill', 'p.v');
  356. f.appendChild(i1);
  357. body.appendChild(f);
  358. await setState('p', { v: 'typed', act: { uri: '/save', method: 'POST' } });
  359. check(i1.value === 'typed', 'prefill did not apply');
  360. fire(i1, 'input'); // user edits -> dirty; reset must still win via clear
  361. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  362. fire(f, 'submit');
  363. await spin(50);
  364. check(globalThis.__shim.fetchCalls.some(function (c) { return c.url === '/save'; }),
  365. 'the action request never fired');
  366. check(i1.value === 'dflt', 'form not reset after success: ' + JSON.stringify(i1.value));
  367. check(!s.document.isDirty(i1), 'form not un-dirtied after success');
  368. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  369. } else if (scenario === '12') {
  370. // Clear-on-success: failure keeps values and dirty state.
  371. var f = el('form');
  372. f.setAttribute('stm-action', 'p.act');
  373. f.setAttribute('stm-clear-on-success', '');
  374. var i1 = input('text', 'one', 'dflt'); i1.setAttribute('stm-prefill', 'p.v');
  375. f.appendChild(i1);
  376. body.appendChild(f);
  377. await setState('p', { v: 'typed', act: { uri: '/save', method: 'POST' } });
  378. fire(i1, 'input');
  379. i1.value = 'edited';
  380. globalThis.__shim.setFetch(function () { return globalThis.__shim.failResponse(500); });
  381. fire(f, 'submit');
  382. await spin(50);
  383. check(i1.value === 'edited', 'form was reset despite failure: ' + JSON.stringify(i1.value));
  384. check(s.document.isDirty(i1), 'dirty state lost on failure');
  385. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  386. // Error-directive variant (statum response carrying an error directive).
  387. globalThis.__shim.setFetch(function () {
  388. return globalThis.__shim.okResponse([{ type: 'error', message: 'nope' }]);
  389. });
  390. fire(f, 'submit');
  391. await spin(50);
  392. check(i1.value === 'edited', 'form was reset after an error directive');
  393. // Core logs error directives by design; nothing else may error.
  394. check(log.errors.length === 1 && log.errors[0].indexOf('error directive') !== -1,
  395. 'unexpected console.error: ' + JSON.stringify(log.errors));
  396. log.errors.length = 0;
  397. } else if (scenario === '13') {
  398. // Keyed loop of forms: clearing one instance leaves the others intact.
  399. var holder = el('div');
  400. holder.setAttribute('stm-for-item-in', 'p.rows');
  401. holder.setAttribute('stm-key', 'item.id');
  402. var row = el('form');
  403. row.setAttribute('stm-action', 'item.act');
  404. row.setAttribute('stm-clear-on-success', '');
  405. var ri = input('text', 'val', 'blank');
  406. ri.setAttribute('stm-prefill', 'item.val');
  407. row.appendChild(ri);
  408. holder.appendChild(row);
  409. body.appendChild(holder);
  410. var mkAct = function (uri) { return { uri: uri, method: 'POST' }; };
  411. await setState('p', {
  412. rows: [
  413. { id: 1, val: 'one', act: mkAct('/save1') },
  414. { id: 2, val: 'two', act: mkAct('/save2') },
  415. { id: 3, val: 'three', act: mkAct('/save3') }
  416. ]
  417. });
  418. var forms = body.querySelectorAll('form').filter(function (n) {
  419. // The loop template lives inside the (hidden) holder; instances sit in
  420. // their own DIVs outside it.
  421. var p = n.parentNode;
  422. return p !== holder && p.tagName === 'DIV';
  423. });
  424. check(forms.length === 3, 'expected 3 instance forms, got ' + forms.length);
  425. check(forms[0].children[0].value === 'one', 'instance 1 prefill failed');
  426. // Dirty instance 2's input by editing it.
  427. var i2 = forms[1].children[0];
  428. i2.value = 'user2';
  429. fire(i2, 'input');
  430. // Instance 1 and 3 inputs are clean (state-filled).
  431. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  432. fire(forms[1], 'submit');
  433. await spin(50);
  434. check(forms[1].children[0].value === 'blank', 'instance 2 not reset: ' + JSON.stringify(forms[1].children[0].value));
  435. check(!s.document.isDirty(forms[1].children[0]), 'instance 2 not un-dirtied');
  436. check(forms[0].children[0].value === 'one', 'instance 1 was touched');
  437. check(forms[2].children[0].value === 'three', 'instance 3 was touched');
  438. var saved = globalThis.__shim.fetchCalls.filter(function (c) { return c.method === 'POST'; })
  439. .map(function (c) { return c.url; });
  440. check(saved.indexOf('/save2') !== -1 && saved.indexOf('/save1') === -1 && saved.indexOf('/save3') === -1,
  441. 'wrong action fired: ' + JSON.stringify(saved));
  442. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  443. } else if (scenario === '14') {
  444. // Two sibling forms: clear-on-success on A only.
  445. var fa = el('form');
  446. fa.setAttribute('stm-action', 'p.act');
  447. fa.setAttribute('stm-clear-on-success', '');
  448. var ia = input('text', 'a', 'dflt-a');
  449. ia.setAttribute('stm-prefill', 'p.va');
  450. fa.appendChild(ia);
  451. var fb = el('form');
  452. fb.setAttribute('stm-action', 'p.act');
  453. var ib = input('text', 'b', 'dflt-b');
  454. ib.setAttribute('stm-prefill', 'p.vb');
  455. fb.appendChild(ib);
  456. body.appendChild(fa); body.appendChild(fb);
  457. await setState('p', { va: 'A', vb: 'B', act: { uri: '/save', method: 'POST' } });
  458. fire(ib, 'input'); // B becomes dirty
  459. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  460. fire(fa, 'submit');
  461. await spin(50);
  462. check(ia.value === 'dflt-a', 'form A not reset');
  463. check(!s.document.isDirty(ia), 'form A not un-dirtied');
  464. check(ib.value === 'B', 'form B value was touched');
  465. check(s.document.isDirty(ib), 'form B dirty state was touched');
  466. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  467. } else if (scenario === '15') {
  468. // statum.forms.reset resets exactly the given form.
  469. var fa = el('form');
  470. var ia = input('text', 'a', 'dflt-a');
  471. fa.appendChild(ia);
  472. var fb = el('form');
  473. var ib = input('text', 'b', 'dflt-b');
  474. fb.appendChild(ib);
  475. body.appendChild(fa); body.appendChild(fb);
  476. ia.value = 'x'; fire(ia, 'input');
  477. ib.value = 'y'; fire(ib, 'input');
  478. s.document.reset(fa);
  479. check(ia.value === 'dflt-a', 'form A not reset');
  480. check(!s.document.isDirty(ia), 'form A not un-dirtied');
  481. check(ib.value === 'y', 'form B was touched');
  482. check(s.document.isDirty(ib), 'form B dirty state was touched');
  483. // Passing a control inside a form resolves the owning form.
  484. ib.value = 'z';
  485. s.document.reset(ib);
  486. check(ib.value === 'dflt-b', 'forms.reset(el) did not resolve the owning form');
  487. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  488. } else if (scenario === '16') {
  489. // Handler order: stm-prefill first (property writes feed later predicates).
  490. var names = s._bridge.attributeHandlers.map(function (h) { return h.name; });
  491. check(names.indexOf('stm-prefill') === 0, 'stm-prefill is not first: ' + JSON.stringify(names));
  492. check(names.indexOf('stm-class.') === 1, 'stm-class. is not second: ' + JSON.stringify(names));
  493. check(names.indexOf('stm-markdown') === names.indexOf('stm-html') + 1, 'markdown ordering broke');
  494. check(names[names.length - 1] === 'stm-h-demotion', 'last handler changed: ' + JSON.stringify(names));
  495. check(log.warns.length === 0, 'warnings: ' + JSON.stringify(log.warns));
  496. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  497. } else if (scenario === '17') {
  498. // reenter: an action response re-fetches the entrypoint in place.
  499. var t = el('span'); t.setAttribute('stm-text', 'm.mood');
  500. body.appendChild(t);
  501. sigCounter++;
  502. var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
  503. var snap2 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'second' } };
  504. var entrypointCount = 0;
  505. globalThis.__shim.setFetch(function (url) {
  506. if (String(url).indexOf('/_statum/entrypoint') !== -1) {
  507. entrypointCount++;
  508. return globalThis.__shim.okResponse([{
  509. type: 'set',
  510. snapshot_frame: {
  511. content: JSON.stringify(entrypointCount === 1 ? snap1 : snap2),
  512. signature: 'sig-r17-' + entrypointCount
  513. }
  514. }]);
  515. }
  516. // The action request: reply with a reenter directive.
  517. return globalThis.__shim.okResponse([{ type: 'reenter' }]);
  518. });
  519. await s._bridge.loadEntrypoint();
  520. await spin();
  521. check(t.textContent === 'first', 'initial entrypoint state not applied: ' + JSON.stringify(t.textContent));
  522. var initialFetches = globalThis.__shim.fetchCalls.length;
  523. await s._bridge.performAction({ uri: '/save', method: 'POST' }, {});
  524. await spin(50);
  525. var entryFetches = globalThis.__shim.fetchCalls.filter(function (c) {
  526. return c.url.indexOf('/_statum/entrypoint') !== -1;
  527. });
  528. check(entryFetches.length === 2, 'entrypoint fetched ' + entryFetches.length + ' time(s), expected 2 (initial + reenter)');
  529. check(globalThis.__shim.fetchCalls.length === initialFetches + 2,
  530. 'exactly two new requests were expected (action + refresh), got ' +
  531. (globalThis.__shim.fetchCalls.length - initialFetches));
  532. check(t.textContent === 'second', 'reentered entrypoint state not applied: ' + JSON.stringify(t.textContent));
  533. check(globalThis.location.href === 'http://localhost/', 'a bare reenter must not navigate');
  534. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  535. } else if (scenario === '18') {
  536. // reenter + navigate in one response: refresh first, then navigate wins.
  537. var t = el('span'); t.setAttribute('stm-text', 'm.mood');
  538. body.appendChild(t);
  539. sigCounter++;
  540. var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
  541. var snap2 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'second' } };
  542. var entrypointCount = 0;
  543. var order = []; // shared log: reenter's fetch vs the location change
  544. globalThis.__shim.setFetch(function (url) {
  545. if (String(url).indexOf('/_statum/entrypoint') !== -1) {
  546. entrypointCount++;
  547. order.push('entrypoint:' + entrypointCount);
  548. return globalThis.__shim.okResponse([{
  549. type: 'set',
  550. snapshot_frame: {
  551. content: JSON.stringify(entrypointCount === 1 ? snap1 : snap2),
  552. signature: 'sig-r18-' + entrypointCount
  553. }
  554. }]);
  555. }
  556. return globalThis.__shim.okResponse([{ type: 'reenter' }, { type: 'navigate', uri: '/after' }]);
  557. });
  558. // Record the navigation in the shared order log.
  559. var originalHref = globalThis.location.href;
  560. Object.defineProperty(globalThis.location, 'href', {
  561. configurable: true,
  562. get: function () { return originalHref; },
  563. set: function (v) { order.push('navigate:' + v); }
  564. });
  565. await s._bridge.loadEntrypoint();
  566. await spin();
  567. check(t.textContent === 'first', 'initial entrypoint state not applied');
  568. await s._bridge.performAction({ uri: '/save', method: 'POST' }, {});
  569. await spin(50);
  570. check(globalThis.__shim.fetchCalls.filter(function (c) {
  571. return c.url.indexOf('/_statum/entrypoint') !== -1;
  572. }).length === 2, 'reenter did not refresh the entrypoint');
  573. check(order.indexOf('navigate:/after') !== -1, 'navigate did not run');
  574. check(order.indexOf('entrypoint:2') < order.indexOf('navigate:/after'),
  575. 'reenter must run before navigate, order was ' + JSON.stringify(order));
  576. check(t.textContent === 'second', 'refresh state not applied before navigating');
  577. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  578. } else if (scenario === '19') {
  579. // A failing reenter refresh: logged, swallowed, navigate still runs, and
  580. // the action promise resolves.
  581. var t = el('span'); t.setAttribute('stm-text', 'm.mood');
  582. body.appendChild(t);
  583. sigCounter++;
  584. var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
  585. var entrypointCount = 0;
  586. globalThis.__shim.setFetch(function (url) {
  587. if (String(url).indexOf('/_statum/entrypoint') !== -1) {
  588. entrypointCount++;
  589. if (entrypointCount === 1) {
  590. return globalThis.__shim.okResponse([{
  591. type: 'set',
  592. snapshot_frame: { content: JSON.stringify(snap1), signature: 'sig-r19-1' }
  593. }]);
  594. }
  595. return Promise.reject(new Error('network down'));
  596. }
  597. return globalThis.__shim.okResponse([{ type: 'reenter' }, { type: 'navigate', uri: '/after' }]);
  598. });
  599. var navigatedTo = null;
  600. Object.defineProperty(globalThis.location, 'href', {
  601. configurable: true,
  602. get: function () { return 'http://localhost/'; },
  603. set: function (v) { navigatedTo = v; }
  604. });
  605. await s._bridge.loadEntrypoint();
  606. await spin();
  607. var resolved = false;
  608. var rejected = null;
  609. await s._bridge.performAction({ uri: '/save', method: 'POST' }, {}).then(function () {
  610. resolved = true;
  611. }, function (e) {
  612. rejected = e;
  613. });
  614. await spin(50);
  615. check(resolved && rejected === null, 'action promise should resolve after a failed reenter, rejected=' + String(rejected));
  616. check(log.errors.some(function (m) { return m.indexOf('[statum] reenter: entrypoint refresh failed') !== -1; }),
  617. 'reenter failure was not logged: ' + JSON.stringify(log.errors));
  618. check(navigatedTo === '/after', 'navigate did not run after the failed reenter, navigatedTo=' + JSON.stringify(navigatedTo));
  619. check(log.errors.length === 1, 'exactly one console.error expected: ' + JSON.stringify(log.errors));
  620. // Core logs the swallowed reenter failure by design; nothing else may error.
  621. log.errors.length = 0;
  622. } else if (scenario === '20') {
  623. // stm-on-success: applied on success, cleared on the next attempt.
  624. var b = el('button');
  625. b.setAttribute('stm-action', 'p.act');
  626. b.setAttribute('stm-on-success', 'saved ok');
  627. body.appendChild(b);
  628. await setState('p', { act: { uri: '/save', method: 'POST' } });
  629. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  630. fire(b, 'click');
  631. await spin(50);
  632. check(b.classList.contains('saved') && b.classList.contains('ok'),
  633. 'success classes not applied: ' + JSON.stringify(b.classList));
  634. // A new attempt clears them at attempt start. The fetch stub below never
  635. // resolves, freezing the attempt mid-flight so the cleared state (before
  636. // any outcome re-applies classes) is observable.
  637. var hang = new Promise(function () {});
  638. globalThis.__shim.setFetch(function () { return hang; });
  639. fire(b, 'click');
  640. await spin(20);
  641. check(!b.classList.contains('saved') && !b.classList.contains('ok'),
  642. 'success classes not cleared on a new attempt');
  643. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  644. } else if (scenario === '21') {
  645. // Mirroring: a failure applies stm-on-error and clears stm-on-success;
  646. // a later success applies stm-on-success and clears stm-on-error.
  647. var b = el('button');
  648. b.setAttribute('stm-action', 'p.act');
  649. b.setAttribute('stm-on-error', 'boom');
  650. b.setAttribute('stm-on-success', 'yay');
  651. body.appendChild(b);
  652. await setState('p', { act: { uri: '/save', method: 'POST' } });
  653. globalThis.__shim.setFetch(function () { return globalThis.__shim.failResponse(500); });
  654. fire(b, 'click');
  655. await spin(50);
  656. check(b.classList.contains('boom'), 'error classes not applied');
  657. check(!b.classList.contains('yay'), 'success classes survived a failure');
  658. log.errors.length = 0;
  659. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  660. fire(b, 'click');
  661. await spin(50);
  662. check(b.classList.contains('yay'), 'success classes not applied after a failure');
  663. check(!b.classList.contains('boom'), 'error classes survived a success');
  664. // And an error-directive failure mirrors the HTTP failure exactly.
  665. globalThis.__shim.setFetch(function () {
  666. return globalThis.__shim.okResponse([{ type: 'error', message: 'nope' }]);
  667. });
  668. fire(b, 'click');
  669. await spin(50);
  670. check(b.classList.contains('boom'), 'error classes not applied (error directive)');
  671. check(!b.classList.contains('yay'), 'success classes survived an error directive');
  672. log.errors.length = 0;
  673. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  674. } else if (scenario === '22') {
  675. // stm-clear-on-error: a failing action resets the form (values and dirty).
  676. var f = el('form');
  677. f.setAttribute('stm-action', 'p.act');
  678. f.setAttribute('stm-clear-on-error', '');
  679. var i1 = input('text', 'a', 'dflt');
  680. i1.setAttribute('stm-prefill', 'p.v');
  681. f.appendChild(i1);
  682. body.appendChild(f);
  683. await setState('p', { v: 'from state', act: { uri: '/save', method: 'POST' } });
  684. i1.value = 'user typed';
  685. fire(i1, 'input');
  686. check(s.document.isDirty(i1), 'input not dirty after edit');
  687. globalThis.__shim.setFetch(function () { return globalThis.__shim.failResponse(500); });
  688. fire(f, 'submit');
  689. await spin(50);
  690. check(i1.value === 'dflt', 'form was not reset on failure: ' + JSON.stringify(i1.value));
  691. check(!s.document.isDirty(i1), 'form was not un-dirtied on failure');
  692. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  693. // A success must NOT reset a stm-clear-on-error form.
  694. i1.value = 'typed again';
  695. fire(i1, 'input');
  696. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  697. fire(f, 'submit');
  698. await spin(50);
  699. check(i1.value === 'typed again', 'stm-clear-on-error fired on success: ' + JSON.stringify(i1.value));
  700. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  701. } else if (scenario === '23') {
  702. // A declined stm-confirm never clears: decline is cancellation, not error.
  703. var f = el('form');
  704. f.setAttribute('stm-action', 'p.act');
  705. f.setAttribute('stm-confirm', 'sure?');
  706. f.setAttribute('stm-clear-on-error', '');
  707. var i1 = input('text', 'a', 'dflt');
  708. f.appendChild(i1);
  709. body.appendChild(f);
  710. await setState('p', { act: { uri: '/save', method: 'POST' } });
  711. i1.value = 'user typed';
  712. fire(i1, 'input');
  713. // Decline the confirm (custom handler returning false).
  714. s.onConfirmHandler = function () { return false; };
  715. fire(f, 'submit');
  716. await spin(50);
  717. check(i1.value === 'user typed', 'declined confirm cleared the form: ' + JSON.stringify(i1.value));
  718. check(s.document.isDirty(i1), 'declined confirm un-dirtied the form');
  719. var posts = globalThis.__shim.fetchCalls.filter(function (c) { return c.method === 'POST'; });
  720. check(posts.length === 0, 'a declined confirm still fired a request: ' + JSON.stringify(posts));
  721. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  722. // The error-directive path of clear-on-error: failure with a Statum body.
  723. s.onConfirmHandler = null; // window.confirm fallback: shim returns true
  724. i1.value = 'typed more';
  725. fire(i1, 'input');
  726. globalThis.__shim.setFetch(function () {
  727. return globalThis.__shim.okResponse([{ type: 'error', message: 'nope' }]);
  728. });
  729. fire(f, 'submit');
  730. await spin(50);
  731. check(i1.value === 'dflt', 'error directive did not reset a clear-on-error form: ' + JSON.stringify(i1.value));
  732. log.errors.length = 0;
  733. } else if (scenario === '25') {
  734. // stm-local basic: subtree scoping + evaluation through stm-text.
  735. var holder = el('div');
  736. holder.setAttribute('stm-local-x', '1 + 1');
  737. var span = el('span'); span.setAttribute('stm-text', 'x');
  738. holder.appendChild(span);
  739. body.appendChild(holder);
  740. var outside = el('span'); outside.setAttribute('stm-text', 'typeof x');
  741. body.appendChild(outside);
  742. await s._bridge.renderAll(); await spin();
  743. check(span.textContent === '2', 'stm-local-x did not resolve: ' + span.textContent);
  744. check(outside.textContent === 'undefined', 'local leaked outside its subtree');
  745. } else if (scenario === '26') {
  746. // Lazy evaluation: once per pass even when read many times.
  747. var calls = 0;
  748. globalThis.__count = function () { calls++; return calls; };
  749. var holder2 = el('div');
  750. holder2.setAttribute('stm-local-n', '__count()');
  751. var a2 = el('span'); a2.setAttribute('stm-text', 'n');
  752. var b2 = el('span'); b2.setAttribute('stm-text', 'n + n');
  753. holder2.appendChild(a2); holder2.appendChild(b2);
  754. body.appendChild(holder2);
  755. await s._bridge.renderAll(); await spin();
  756. check(a2.textContent === '1' && b2.textContent === '2', 'lazy value wrong: ' + a2.textContent + '/' + b2.textContent);
  757. check(calls === 1, 'expression evaluated ' + calls + ' times in one pass (must be 1)');
  758. await s._bridge.renderAll(); await spin();
  759. check(calls === 2, 'second pass did not re-evaluate (calls=' + calls + ')');
  760. } else if (scenario === '27') {
  761. // stm-global: visible page-wide on the FIRST pass (the pass-start sweep
  762. // exposes lazy getters; a reader before the declaring element resolves
  763. // the same binding on demand), and stable across passes.
  764. var early = el('span'); early.setAttribute('stm-text', 'typeof g');
  765. body.appendChild(early);
  766. var late = el('div'); late.setAttribute('stm-global-g', '41 + 1');
  767. var lateSpan = el('span'); lateSpan.setAttribute('stm-text', 'g');
  768. late.appendChild(lateSpan);
  769. body.appendChild(late);
  770. await s._bridge.renderAll(); await spin();
  771. check(early.textContent === 'number', 'global not visible before its declaration on pass 1');
  772. await s._bridge.renderAll(); await spin();
  773. check(early.textContent === 'number', 'global lost on second pass');
  774. // Prove the VALUE is reachable, not just the type, via an if-predicate.
  775. var gate = el('div'); gate.setAttribute('stm-if', 'g === 42');
  776. body.appendChild(gate);
  777. await s._bridge.renderAll(); await spin();
  778. check(!gate.hasAttribute('hidden'), 'g === 42 did not evaluate true');
  779. } else if (scenario === '28') {
  780. // Duplicate stm-global: last in document order wins, one warn per pass.
  781. var g1 = el('div'); g1.setAttribute('stm-global-dup', '1');
  782. var g2 = el('div'); g2.setAttribute('stm-global-dup', '2');
  783. var rd = el('span'); rd.setAttribute('stm-text', 'dup');
  784. body.appendChild(g1); body.appendChild(g2); body.appendChild(rd);
  785. log.warns.length = 0;
  786. await s._bridge.renderAll(); await spin();
  787. check(rd.textContent === '2', 'last duplicate did not win: ' + rd.textContent);
  788. check(log.warns.length === 1, 'expected exactly one duplicate warn, got ' + log.warns.length);
  789. log.warns.length = 0;
  790. await s._bridge.renderAll(); await spin();
  791. check(log.warns.length === 1, 'warn must fire once per pass');
  792. } else if (scenario === '29') {
  793. // Cycles: logged as an error, variables read undefined, walk survives.
  794. var ca = el('div'); ca.setAttribute('stm-global-a', 'b');
  795. var cb = el('div'); cb.setAttribute('stm-global-b', 'a');
  796. var ra = el('span'); ra.setAttribute('stm-text', 'typeof a');
  797. body.appendChild(ca); body.appendChild(cb); body.appendChild(ra);
  798. await s._bridge.renderAll(); await spin();
  799. check(log.errors.length >= 1 && /variable cycle/.test(log.errors[0]),
  800. 'cycle not logged: ' + JSON.stringify(log.errors));
  801. check(ra.textContent === 'undefined', 'cyclic variable must read undefined');
  802. log.errors.length = 0;
  803. } else if (scenario === '30') {
  804. // from-attribute (non-control): observer redraws on real change only.
  805. var host = el('div'); host.setAttribute('title', 'first');
  806. host.setAttribute('stm-local-t', 't'); // reads via the from binding below
  807. host.setAttribute('stm-local-t-from-title', '');
  808. // ^ both spellings would conflict; use only the from- form:
  809. host.removeAttribute('stm-local-t');
  810. var outT = el('span'); outT.setAttribute('stm-text', 't');
  811. host.appendChild(outT);
  812. body.appendChild(host);
  813. var cycles = 0;
  814. s.afterEvaluate(function () { cycles++; });
  815. await s._bridge.renderAll(); await spin();
  816. check(outT.textContent === 'first', 'from-title not read: ' + outT.textContent);
  817. cycles = 0;
  818. host.setAttribute('title', 'first'); // same value: no redraw
  819. await spin(10);
  820. check(cycles === 0, 'same-value attribute write triggered a redraw');
  821. host.setAttribute('title', 'second'); // real change: redraw
  822. await spin(10);
  823. check(cycles >= 1, 'changed attribute did not redraw');
  824. check(outT.textContent === 'second', 'variable not updated after change: ' + outT.textContent);
  825. } else if (scenario === '31') {
  826. // The operator's example: declare + local-from-value + stm-if.
  827. var box = el('div'); box.setAttribute('stm-declare-username', '');
  828. var f31 = el('form');
  829. var inp = input('text', 'username', '');
  830. inp.setAttribute('stm-local-username-from-value', '');
  831. f31.appendChild(inp);
  832. var alertBox = el('div'); alertBox.setAttribute('stm-if', 'username.length < 3');
  833. alertBox.textContent = 'Username is too short';
  834. var okBox = el('div'); okBox.setAttribute('stm-if', 'username.length >= 3');
  835. var okName = el('span'); okName.setAttribute('stm-text', 'username');
  836. okBox.appendChild(okName);
  837. box.appendChild(f31); box.appendChild(alertBox); box.appendChild(okBox);
  838. body.appendChild(box);
  839. await s._bridge.renderAll(); await spin();
  840. check(!alertBox.hasAttribute('hidden'), 'alert must show with empty username');
  841. check(okBox.hasAttribute('hidden'), 'ok box must hide with empty username');
  842. inp.value = 'ab'; fire(inp, 'input'); await spin(10);
  843. check(!alertBox.hasAttribute('hidden'), 'alert must show for "ab"');
  844. inp.value = 'abc'; fire(inp, 'input'); await spin(10);
  845. check(alertBox.hasAttribute('hidden'), 'alert must hide for "abc"');
  846. check(!okBox.hasAttribute('hidden') && okName.textContent === 'abc',
  847. 'ok box wrong: hidden=' + okBox.hasAttribute('hidden') + ' text=' + okName.textContent);
  848. } else if (scenario === '32') {
  849. // from-checked on a checkbox.
  850. var box32 = el('div'); box32.setAttribute('stm-declare-agree', '');
  851. var cbx = input('checkbox', 'agree', '');
  852. cbx.setAttribute('stm-local-agree-from-checked', '');
  853. var lab = el('span'); lab.setAttribute('stm-text', 'agree ? "yes" : "no"');
  854. box32.appendChild(cbx); box32.appendChild(lab);
  855. body.appendChild(box32);
  856. await s._bridge.renderAll(); await spin();
  857. check(lab.textContent === 'no', 'unchecked must read false: ' + lab.textContent);
  858. cbx.checked = true; fire(cbx, 'change'); await spin(10);
  859. check(lab.textContent === 'yes', 'checked must read true: ' + lab.textContent);
  860. } else if (scenario === '33') {
  861. // Declare without binder: undefined, page alive; shadowing.
  862. var box33 = el('div'); box33.setAttribute('stm-declare-later', '');
  863. var probe = el('span'); probe.setAttribute('stm-text', 'typeof later');
  864. box33.appendChild(probe);
  865. body.appendChild(box33);
  866. await s._bridge.renderAll(); await spin();
  867. check(probe.textContent === 'undefined', 'declared-but-unbound must read undefined');
  868. // Shadowing: a variable named like a slot type wins in its scope.
  869. await setState('counter', { n: 5 });
  870. var sh = el('div'); sh.setAttribute('stm-local-counter', '99');
  871. var shOut = el('span'); shOut.setAttribute('stm-text', 'typeof counter');
  872. sh.appendChild(shOut); body.appendChild(sh);
  873. var plain = el('span'); plain.setAttribute('stm-text', 'counter.n');
  874. body.appendChild(plain);
  875. await s._bridge.renderAll(); await spin();
  876. check(shOut.textContent === 'number', 'shadowing variable must hide the slot type: ' + shOut.textContent);
  877. check(plain.textContent === '5', 'slot type must still read outside the shadow');
  878. } else if (scenario === '34') {
  879. // stm-local replaces stm-def: the demo's stamp pattern, and the legacy
  880. // stm-def-{name}-as spelling works as an obsolescent alias (warns once
  881. // per element, binds identically).
  882. var box34 = el('div'); box34.setAttribute('stm-local-stamp', "'updated '" + ' + counter.n');
  883. var out34 = el('span'); out34.setAttribute('stm-text', 'stamp');
  884. box34.appendChild(out34); body.appendChild(box34);
  885. await setState('counter', { n: 7 });
  886. check(out34.textContent === 'updated 7', 'stamp local wrong: ' + out34.textContent);
  887. var legacy = el('div'); legacy.setAttribute('stm-def-old-as', '1');
  888. var legacyOut = el('span'); legacyOut.setAttribute('stm-text', 'old');
  889. legacy.appendChild(legacyOut); body.appendChild(legacy);
  890. log.warns.length = 0;
  891. await s._bridge.renderAll(); await spin();
  892. check(legacyOut.textContent === '1', 'legacy stm-def must still bind: ' + legacyOut.textContent);
  893. check(log.warns.length === 1 && /obsolescent/.test(log.warns[0]),
  894. 'legacy stm-def must warn once: ' + JSON.stringify(log.warns));
  895. var warnsAfter = log.warns.length;
  896. await s._bridge.renderAll(); await spin();
  897. check(log.warns.length === warnsAfter, 'obsolescence warn must fire once per element, not per pass');
  898. } else if (scenario === '35') {
  899. // Several -from- bindings on ONE element (review finding: the plumbing
  900. // was keyed per element, so the second binding never updated).
  901. var box35 = el('div'); box35.setAttribute('stm-declare-v', '');
  902. box35.setAttribute('stm-declare-w', '');
  903. var inp35 = input('text', 'dual', '');
  904. inp35.setAttribute('stm-local-v-from-value', '');
  905. inp35.setAttribute('stm-local-w-from-value', '');
  906. var outV = el('span'); outV.setAttribute('stm-text', 'v');
  907. var outW = el('span'); outW.setAttribute('stm-text', 'w');
  908. box35.appendChild(inp35); box35.appendChild(outV); box35.appendChild(outW);
  909. body.appendChild(box35);
  910. await s._bridge.renderAll(); await spin();
  911. check(outV.textContent === '' && outW.textContent === '',
  912. 'empty input must read "" for both (got ' + outV.textContent + '/' + outW.textContent + ')');
  913. inp35.value = 'hello'; fire(inp35, 'input'); await spin(10);
  914. check(outV.textContent === 'hello', 'first from-value binding stuck: ' + outV.textContent);
  915. check(outW.textContent === 'hello', 'SECOND from-value binding on the same element stuck: ' + outW.textContent);
  916. // Same for two attribute observers on one element.
  917. var host35 = el('div'); host35.setAttribute('title', 'T1'); host35.setAttribute('lang', 'L1');
  918. host35.setAttribute('stm-global-a', 'a'); host35.removeAttribute('stm-global-a');
  919. host35.setAttribute('stm-global-t-from-title', '');
  920. host35.setAttribute('stm-global-l-from-lang', '');
  921. var outT35 = el('span'); outT35.setAttribute('stm-text', 't');
  922. var outL35 = el('span'); outL35.setAttribute('stm-text', 'l');
  923. body.appendChild(host35); body.appendChild(outT35); body.appendChild(outL35);
  924. await s._bridge.renderAll(); await spin();
  925. check(outT35.textContent === 'T1' && outL35.textContent === 'L1',
  926. 'attribute forms did not read initially: ' + outT35.textContent + '/' + outL35.textContent);
  927. host35.setAttribute('lang', 'L2'); await spin(10);
  928. check(outL35.textContent === 'L2', 'SECOND attribute observer on the same element stuck: ' + outL35.textContent);
  929. host35.setAttribute('title', 'T2'); await spin(10);
  930. check(outT35.textContent === 'T2', 'first attribute observer stuck: ' + outT35.textContent);
  931. } else if (scenario === '36') {
  932. // Generic observables: a property registered through the public API
  933. // (not hard-coded) drives -from- bindings with events, not attributes.
  934. check(s.binding && typeof s.binding.observe === 'function',
  935. 'statum.binding.observe missing');
  936. s.binding.observe('selectedIndex', ['change']);
  937. var wrapSel = el('div'); wrapSel.setAttribute('stm-declare-sel', '');
  938. var sel = el('select');
  939. var o1 = el('option'); o1.setAttribute('value', 'a'); o1.value = 'a';
  940. var o2 = el('option'); o2.setAttribute('value', 'b'); o2.value = 'b';
  941. sel.appendChild(o1); sel.appendChild(o2);
  942. // The shim's element accepts ad-hoc properties; options feed nothing —
  943. // selectedIndex is ours to drive for the test.
  944. sel.selectedIndex = 0;
  945. sel.setAttribute('stm-local-sel-from-selectedIndex', '');
  946. var outSel = el('span'); outSel.setAttribute('stm-text', 'sel');
  947. wrapSel.appendChild(sel); wrapSel.appendChild(outSel);
  948. body.appendChild(wrapSel);
  949. await s._bridge.renderAll(); await spin();
  950. check(outSel.textContent === '0', 'observable property not read: ' + outSel.textContent);
  951. sel.selectedIndex = 1; fire(sel, 'change'); await spin(10);
  952. check(outSel.textContent === '1',
  953. 'custom observable did not update via its event: ' + outSel.textContent);
  954. // A registered property the element does NOT have falls back to the
  955. // attribute (a real browser has no `value` property on a div; the shim
  956. // does, so exercise the fallback with a property only the select had).
  957. var wrap36 = el('div'); wrap36.setAttribute('stm-declare-v36', '');
  958. var d36 = el('div'); d36.setAttribute('selectedIndex', 'attr');
  959. d36.setAttribute('stm-local-v36-from-selectedIndex', '');
  960. var out36 = el('span'); out36.setAttribute('stm-text', 'v36');
  961. wrap36.appendChild(d36); wrap36.appendChild(out36);
  962. body.appendChild(wrap36);
  963. await s._bridge.renderAll(); await spin();
  964. check(out36.textContent === 'attr', 'attribute fallback broken: ' + out36.textContent);
  965. } else {
  966. fail('unknown scenario: ' + scenario);
  967. }
  968. check(log.errors.length === 0, 'unexpected console.error: ' + JSON.stringify(log.errors));
  969. print('scenario ' + scenario + ': OK');
  970. }
  971. main().catch(function (e) {
  972. std.err.puts('FAIL [' + scenario + '] ' + (e && e.stack || e) + '\n');
  973. std.exit(1);
  974. });