scenarios.js 49 KB

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