scenarios.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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.forms.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. *
  34. * Usage: qjs tests/dom/scenarios.js <1..19>
  35. */
  36. import * as std from 'std';
  37. import { installShim } from './shim.js';
  38. // Repo root as a CWD-relative path; run.sh cds to the repo root first (same
  39. // convention as tests/markdown/spec-test.js).
  40. var ROOT = '.';
  41. var scenario = scriptArgs.length > 1 ? scriptArgs[1] : '';
  42. function fail(msg) {
  43. std.err.puts('FAIL [' + scenario + '] ' + msg + '\n');
  44. std.exit(1);
  45. }
  46. function check(cond, msg) {
  47. if (!cond) fail(msg);
  48. }
  49. function load(name) {
  50. (0, eval)(std.loadFile(ROOT + '/js/' + name));
  51. }
  52. function loadAll() {
  53. load('statum-core.js');
  54. load('statum-document.js');
  55. load('statum-markdown.js');
  56. load('statum-forms.js');
  57. }
  58. /** Yield to the job queue n times so promise chains settle. */
  59. async function spin(n) {
  60. for (var i = 0; i < (n || 30); i++) await Promise.resolve();
  61. }
  62. var sigCounter = 0;
  63. /**
  64. * Put `public` data into a slot type through a set directive, then re-render.
  65. * Uses loadEntrypoint (public bridge machinery) so the exact production path
  66. * (fetch -> handleResponse -> applyDirectives -> renderAll) runs.
  67. */
  68. async function setState(typeName, publicData) {
  69. sigCounter++;
  70. var snapshot = { slot: { key: 'k-' + typeName, type: typeName, scope: 'page' }, public: publicData };
  71. globalThis.__shim.setFetch(function () {
  72. return globalThis.__shim.okResponse([{
  73. type: 'set',
  74. snapshot_frame: { content: JSON.stringify(snapshot), signature: 'sig-' + sigCounter }
  75. }]);
  76. });
  77. await globalThis.statum._bridge.loadEntrypoint();
  78. await spin();
  79. }
  80. /** Fire a real (bubbling, non-cancelable-by-default) event on an element. */
  81. function fire(el, type) {
  82. var evt = globalThis.__shim.makeEvent(type);
  83. el.dispatchEvent(evt);
  84. return evt;
  85. }
  86. function el(tag) { return globalThis.__shim.makeElement(tag); }
  87. function input(type, name, value) {
  88. var i = el('input');
  89. if (type) i.setAttribute('type', type);
  90. if (name) i.setAttribute('name', name);
  91. if (value !== undefined) i.setAttribute('value', value);
  92. return i;
  93. }
  94. async function main() {
  95. installShim();
  96. var log = globalThis.__shim.log;
  97. var body = globalThis.__shim.body;
  98. loadAll();
  99. var s = globalThis.statum;
  100. check(s && s._bridge, 'statum did not load');
  101. check(s.forms && typeof s.forms.reset === 'function', 'statum.forms.reset missing');
  102. check(typeof s.forms.markDirty === 'function' && typeof s.forms.isDirty === 'function',
  103. 'statum.forms.markDirty/isDirty missing');
  104. check(s._bridge.formsDirty instanceof WeakSet, 'bridge.formsDirty missing');
  105. check(typeof s._bridge.markDirty === 'function' && typeof s._bridge.isDirty === 'function',
  106. 'bridge.markDirty/isDirty missing');
  107. if (scenario === '1') {
  108. // if/else-if/else chain + stm-text + stm-class.*
  109. var w = el('div');
  110. var a = el('p'); a.setAttribute('stm-if', "m.mood === 'up'"); a.textContent = 'up';
  111. var b = el('p'); b.setAttribute('stm-else-if', "m.mood === 'mid'"); b.textContent = 'mid';
  112. var c = el('p'); c.setAttribute('stm-else', ''); c.textContent = 'down';
  113. w.appendChild(a); w.appendChild(b); w.appendChild(c);
  114. var t = el('span'); t.setAttribute('stm-text', 'm.mood');
  115. var cl = el('span'); cl.setAttribute('stm-class.hi', "m.mood === 'up'");
  116. w.appendChild(t); w.appendChild(cl);
  117. body.appendChild(w);
  118. await setState('m', { mood: 'up' });
  119. check(!a.hasAttribute('hidden') && b.hasAttribute('hidden') && c.hasAttribute('hidden'),
  120. 'branch up not exclusively shown');
  121. check(t.textContent === 'up', 'stm-text wrote ' + JSON.stringify(t.textContent));
  122. check(cl.classList.contains('hi'), 'stm-class.hi not applied');
  123. await setState('m', { mood: 'mid' });
  124. check(a.hasAttribute('hidden') && !b.hasAttribute('hidden') && c.hasAttribute('hidden'),
  125. 'branch mid not exclusively shown');
  126. check(!cl.classList.contains('hi'), 'stm-class.hi not removed');
  127. check(t.textContent === 'mid', 'stm-text not updated');
  128. await setState('m', { mood: 'zzz' });
  129. check(a.hasAttribute('hidden') && b.hasAttribute('hidden') && !c.hasAttribute('hidden'),
  130. 'else branch not shown');
  131. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  132. } else if (scenario === '2') {
  133. // Keyed loop: identity per key preserved; removal honored.
  134. var holder = el('div');
  135. holder.setAttribute('stm-for-item-in', 'list.items');
  136. holder.setAttribute('stm-key', 'item.id');
  137. var row = el('p');
  138. row.setAttribute('stm-text', 'item.name');
  139. holder.appendChild(row);
  140. body.appendChild(holder);
  141. await setState('list', { items: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }] });
  142. var insts = holder.parentNode.children.filter(function (n) { return n !== holder; });
  143. // holder is children[0]; instances follow it in order.
  144. var kids = body.children.filter(function (n) { return n !== holder; });
  145. check(kids.length === 3, 'expected 3 instances, got ' + kids.length);
  146. var k1 = kids[0], k2 = kids[1], k3 = kids[2];
  147. // The stm-text binding is on the template's child, so read the child.
  148. check(k1.children[0].textContent === 'a' && k2.children[0].textContent === 'b' &&
  149. k3.children[0].textContent === 'c',
  150. 'instance texts: ' + kids.map(function (n) { return n.children[0] && n.children[0].textContent; }).join(','));
  151. await setState('list', { items: [{ id: 1, name: 'a' }, { id: 3, name: 'c3' }] });
  152. var kids2 = body.children.filter(function (n) { return n !== holder; });
  153. check(kids2.length === 2, 'expected 2 instances after removal, got ' + kids2.length);
  154. check(kids2[0] === k1, 'key 1 node identity not preserved');
  155. check(kids2[1] === k3, 'key 3 node identity not preserved');
  156. check(kids2[1].children[0].textContent === 'c3', 'key 3 text not refreshed');
  157. check(k2.parentNode === null, 'removed instance still attached');
  158. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  159. } else if (scenario === '3') {
  160. // Unkeyed loop: rebuild wholesale.
  161. var holder = el('div');
  162. holder.setAttribute('stm-for-item-in', 'list.items');
  163. var row = el('p');
  164. row.setAttribute('stm-text', 'item.name');
  165. holder.appendChild(row);
  166. body.appendChild(holder);
  167. await setState('list', { items: [{ name: 'a' }, { name: 'b' }] });
  168. var kids = body.children.filter(function (n) { return n !== holder; });
  169. check(kids.length === 2 && kids[0].children[0].textContent === 'a' &&
  170. kids[1].children[0].textContent === 'b', 'initial render');
  171. await setState('list', { items: [{ name: 'a' }, { name: 'b' }] });
  172. var kids2 = body.children.filter(function (n) { return n !== holder; });
  173. check(kids2.length === 2, 'instance count changed');
  174. check(kids2[0] !== kids[0] && kids2[1] !== kids[1], 'unkeyed loop reused nodes');
  175. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  176. } else if (scenario === '4') {
  177. // Prefill writes the value PROPERTY, never the value attribute.
  178. var f = el('form');
  179. var ti = input('text', 'who'); ti.setAttribute('stm-prefill', 'p.who');
  180. var ta = el('textarea'); ta.setAttribute('name', 'bio'); ta.setAttribute('stm-prefill', 'p.bio');
  181. f.appendChild(ti); f.appendChild(ta);
  182. body.appendChild(f);
  183. await setState('p', { who: 'ada', bio: 'hi' });
  184. check(ti.value === 'ada', 'text input value = ' + JSON.stringify(ti.value));
  185. check(ta.value === 'hi', 'textarea value = ' + JSON.stringify(ta.value));
  186. check(ti.getAttribute('value') === null, 'text input value ATTRIBUTE was written');
  187. check(ta.getAttribute('stm-prefill') === 'p.bio', 'stm-prefill attribute consumed');
  188. await setState('p', { who: null, bio: undefined });
  189. check(ti.value === '', 'null should prefill as empty string, got ' + JSON.stringify(ti.value));
  190. check(ta.value === 'hi', 'undefined must leave the element untouched');
  191. await setState('p', { who: 42, bio: 'x' });
  192. check(ti.value === '42', 'number stringified: ' + JSON.stringify(ti.value));
  193. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  194. } else if (scenario === '5') {
  195. // Select single + multiple.
  196. var f = el('form');
  197. var sel = el('select'); sel.setAttribute('stm-prefill', 'p.pick');
  198. var o1 = el('option'); o1.setAttribute('value', 'a'); o1.textContent = 'A';
  199. var o2 = el('option'); o2.setAttribute('value', 'b'); o2.textContent = 'B';
  200. sel.appendChild(o1); sel.appendChild(o2);
  201. var multi = el('select'); multi.setAttribute('multiple', ''); multi.setAttribute('stm-prefill', 'p.set');
  202. var m1 = el('option'); m1.setAttribute('value', 'x');
  203. var m2 = el('option'); m2.setAttribute('value', 'y');
  204. var m3 = el('option'); m3.setAttribute('value', 'z');
  205. multi.appendChild(m1); multi.appendChild(m2); multi.appendChild(m3);
  206. f.appendChild(sel); f.appendChild(multi);
  207. body.appendChild(f);
  208. await setState('p', { pick: 'b', set: ['x', 'z'] });
  209. check(sel.value === 'b', 'single select value = ' + JSON.stringify(sel.value));
  210. check(o2.selected === true && o1.selected === false, 'single select option states wrong');
  211. check(m1.selected === true && m2.selected === false && m3.selected === true,
  212. 'multiple select option states wrong');
  213. await setState('p', { pick: 'nope', set: 'y' });
  214. check(sel.value === '', 'unmatched single select should yield empty value');
  215. check(m1.selected === false && m2.selected === true && m3.selected === false,
  216. 'non-array multiple value must behave like single');
  217. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  218. } else if (scenario === '6') {
  219. // Checkbox: truthy -> checked, falsy/null -> unchecked.
  220. var f = el('form');
  221. var cb = input('checkbox', 'ok'); cb.setAttribute('stm-prefill', 'p.ok');
  222. f.appendChild(cb);
  223. body.appendChild(f);
  224. await setState('p', { ok: true });
  225. check(cb.checked === true, 'truthy did not check');
  226. await setState('p', { ok: false });
  227. check(cb.checked === false, 'falsy did not uncheck');
  228. await setState('p', { ok: null });
  229. check(cb.checked === false, 'null did not uncheck');
  230. await setState('p', { ok: 'yes' });
  231. check(cb.checked === true, 'non-empty string should check');
  232. await setState('p', {}); // ok undefined -> untouched
  233. check(cb.checked === true, 'undefined must leave checked untouched');
  234. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  235. } else if (scenario === '7') {
  236. // Radio group: every member carries the same expression; the member whose
  237. // own value matches the resolved value gets checked.
  238. var f = el('form');
  239. var mk = function (v) {
  240. var r = input('radio', 'g', v);
  241. r.setAttribute('stm-prefill', 'p.choice');
  242. f.appendChild(r);
  243. return r;
  244. };
  245. var ra = mk('a'), rb = mk('b'), rc = mk('c');
  246. body.appendChild(f);
  247. await setState('p', { choice: 'b' });
  248. check(ra.checked === false && rb.checked === true && rc.checked === false,
  249. 'state b checked the wrong member(s)');
  250. await setState('p', { choice: 'd' });
  251. check(ra.checked === false && rb.checked === false && rc.checked === false,
  252. 'state d (no match) must leave all unchecked');
  253. await setState('p', { choice: null });
  254. check(rb.checked === false, 'null must uncheck (String(null) matches nothing)');
  255. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  256. } else if (scenario === '8') {
  257. // A dirty element is never overwritten; a clean sibling still fills.
  258. var f = el('form');
  259. var i1 = input('text', 'one'); i1.setAttribute('stm-prefill', 'p.one');
  260. var i2 = input('text', 'two'); i2.setAttribute('stm-prefill', 'p.two');
  261. f.appendChild(i1); f.appendChild(i2);
  262. body.appendChild(f);
  263. await setState('p', { one: 'x', two: 'x' });
  264. check(i1.value === 'x' && i2.value === 'x', 'initial fill failed');
  265. fire(i1, 'input'); // user edits input 1
  266. check(s.forms.isDirty(i1), 'input event did not mark the element dirty');
  267. await setState('p', { one: 'y', two: 'y' });
  268. check(i1.value === 'x', 'dirty element was overwritten: ' + JSON.stringify(i1.value));
  269. check(i2.value === 'y', 'clean sibling not re-filled');
  270. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  271. } else if (scenario === '9') {
  272. // Dirtiness is per element.
  273. var f = el('form');
  274. var i1 = input('text', 'one'); i1.setAttribute('stm-prefill', 'p.v');
  275. var i2 = input('text', 'two'); i2.setAttribute('stm-prefill', 'p.v');
  276. f.appendChild(i1); f.appendChild(i2);
  277. body.appendChild(f);
  278. await setState('p', { v: 'a' });
  279. fire(i1, 'change');
  280. await setState('p', { v: 'b' });
  281. check(i1.value === 'a', 'dirty element overwritten');
  282. check(i2.value === 'b', 'clean element not filled');
  283. check(s.forms.isDirty(i1) && !s.forms.isDirty(i2), 'dirty flags wrong');
  284. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  285. } else if (scenario === '10') {
  286. // Reset restores defaults, un-dirties, and prefill re-applies.
  287. var f = el('form');
  288. var i1 = input('text', 'one', 'init'); i1.setAttribute('stm-prefill', 'p.v');
  289. f.appendChild(i1);
  290. body.appendChild(f);
  291. await setState('p', { v: 'state' });
  292. check(i1.value === 'state', 'prefill did not apply');
  293. fire(i1, 'input');
  294. check(s.forms.isDirty(i1), 'not dirty after edit');
  295. f.reset();
  296. check(i1.value === 'init', 'reset did not restore the attribute default: ' + JSON.stringify(i1.value));
  297. check(!s.forms.isDirty(i1), 'reset did not un-dirty');
  298. await setState('p', { v: 'zzz' });
  299. check(i1.value === 'zzz', 'prefill did not re-apply after reset');
  300. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  301. } else if (scenario === '11') {
  302. // Clear-on-success: action resolves -> form resets and un-dirties.
  303. var f = el('form');
  304. f.setAttribute('stm-action', 'p.act');
  305. f.setAttribute('stm-clear-on-success', '');
  306. var i1 = input('text', 'one', 'dflt'); i1.setAttribute('stm-prefill', 'p.v');
  307. f.appendChild(i1);
  308. body.appendChild(f);
  309. await setState('p', { v: 'typed', act: { uri: '/save', method: 'POST' } });
  310. check(i1.value === 'typed', 'prefill did not apply');
  311. fire(i1, 'input'); // user edits -> dirty; reset must still win via clear
  312. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  313. fire(f, 'submit');
  314. await spin(50);
  315. check(globalThis.__shim.fetchCalls.some(function (c) { return c.url === '/save'; }),
  316. 'the action request never fired');
  317. check(i1.value === 'dflt', 'form not reset after success: ' + JSON.stringify(i1.value));
  318. check(!s.forms.isDirty(i1), 'form not un-dirtied after success');
  319. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  320. } else if (scenario === '12') {
  321. // Clear-on-success: failure keeps values and dirty state.
  322. var f = el('form');
  323. f.setAttribute('stm-action', 'p.act');
  324. f.setAttribute('stm-clear-on-success', '');
  325. var i1 = input('text', 'one', 'dflt'); i1.setAttribute('stm-prefill', 'p.v');
  326. f.appendChild(i1);
  327. body.appendChild(f);
  328. await setState('p', { v: 'typed', act: { uri: '/save', method: 'POST' } });
  329. fire(i1, 'input');
  330. i1.value = 'edited';
  331. globalThis.__shim.setFetch(function () { return globalThis.__shim.failResponse(500); });
  332. fire(f, 'submit');
  333. await spin(50);
  334. check(i1.value === 'edited', 'form was reset despite failure: ' + JSON.stringify(i1.value));
  335. check(s.forms.isDirty(i1), 'dirty state lost on failure');
  336. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  337. // Error-directive variant (statum response carrying an error directive).
  338. globalThis.__shim.setFetch(function () {
  339. return globalThis.__shim.okResponse([{ type: 'error', message: 'nope' }]);
  340. });
  341. fire(f, 'submit');
  342. await spin(50);
  343. check(i1.value === 'edited', 'form was reset after an error directive');
  344. // Core logs error directives by design; nothing else may error.
  345. check(log.errors.length === 1 && log.errors[0].indexOf('error directive') !== -1,
  346. 'unexpected console.error: ' + JSON.stringify(log.errors));
  347. log.errors.length = 0;
  348. } else if (scenario === '13') {
  349. // Keyed loop of forms: clearing one instance leaves the others intact.
  350. var holder = el('div');
  351. holder.setAttribute('stm-for-item-in', 'p.rows');
  352. holder.setAttribute('stm-key', 'item.id');
  353. var row = el('form');
  354. row.setAttribute('stm-action', 'item.act');
  355. row.setAttribute('stm-clear-on-success', '');
  356. var ri = input('text', 'val', 'blank');
  357. ri.setAttribute('stm-prefill', 'item.val');
  358. row.appendChild(ri);
  359. holder.appendChild(row);
  360. body.appendChild(holder);
  361. var mkAct = function (uri) { return { uri: uri, method: 'POST' }; };
  362. await setState('p', {
  363. rows: [
  364. { id: 1, val: 'one', act: mkAct('/save1') },
  365. { id: 2, val: 'two', act: mkAct('/save2') },
  366. { id: 3, val: 'three', act: mkAct('/save3') }
  367. ]
  368. });
  369. var forms = body.querySelectorAll('form').filter(function (n) {
  370. // The loop template lives inside the (hidden) holder; instances sit in
  371. // their own DIVs outside it.
  372. var p = n.parentNode;
  373. return p !== holder && p.tagName === 'DIV';
  374. });
  375. check(forms.length === 3, 'expected 3 instance forms, got ' + forms.length);
  376. check(forms[0].children[0].value === 'one', 'instance 1 prefill failed');
  377. // Dirty instance 2's input by editing it.
  378. var i2 = forms[1].children[0];
  379. i2.value = 'user2';
  380. fire(i2, 'input');
  381. // Instance 1 and 3 inputs are clean (state-filled).
  382. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  383. fire(forms[1], 'submit');
  384. await spin(50);
  385. check(forms[1].children[0].value === 'blank', 'instance 2 not reset: ' + JSON.stringify(forms[1].children[0].value));
  386. check(!s.forms.isDirty(forms[1].children[0]), 'instance 2 not un-dirtied');
  387. check(forms[0].children[0].value === 'one', 'instance 1 was touched');
  388. check(forms[2].children[0].value === 'three', 'instance 3 was touched');
  389. var saved = globalThis.__shim.fetchCalls.filter(function (c) { return c.method === 'POST'; })
  390. .map(function (c) { return c.url; });
  391. check(saved.indexOf('/save2') !== -1 && saved.indexOf('/save1') === -1 && saved.indexOf('/save3') === -1,
  392. 'wrong action fired: ' + JSON.stringify(saved));
  393. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  394. } else if (scenario === '14') {
  395. // Two sibling forms: clear-on-success on A only.
  396. var fa = el('form');
  397. fa.setAttribute('stm-action', 'p.act');
  398. fa.setAttribute('stm-clear-on-success', '');
  399. var ia = input('text', 'a', 'dflt-a');
  400. ia.setAttribute('stm-prefill', 'p.va');
  401. fa.appendChild(ia);
  402. var fb = el('form');
  403. fb.setAttribute('stm-action', 'p.act');
  404. var ib = input('text', 'b', 'dflt-b');
  405. ib.setAttribute('stm-prefill', 'p.vb');
  406. fb.appendChild(ib);
  407. body.appendChild(fa); body.appendChild(fb);
  408. await setState('p', { va: 'A', vb: 'B', act: { uri: '/save', method: 'POST' } });
  409. fire(ib, 'input'); // B becomes dirty
  410. globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
  411. fire(fa, 'submit');
  412. await spin(50);
  413. check(ia.value === 'dflt-a', 'form A not reset');
  414. check(!s.forms.isDirty(ia), 'form A not un-dirtied');
  415. check(ib.value === 'B', 'form B value was touched');
  416. check(s.forms.isDirty(ib), 'form B dirty state was touched');
  417. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  418. } else if (scenario === '15') {
  419. // statum.forms.reset resets exactly the given form.
  420. var fa = el('form');
  421. var ia = input('text', 'a', 'dflt-a');
  422. fa.appendChild(ia);
  423. var fb = el('form');
  424. var ib = input('text', 'b', 'dflt-b');
  425. fb.appendChild(ib);
  426. body.appendChild(fa); body.appendChild(fb);
  427. ia.value = 'x'; fire(ia, 'input');
  428. ib.value = 'y'; fire(ib, 'input');
  429. s.forms.reset(fa);
  430. check(ia.value === 'dflt-a', 'form A not reset');
  431. check(!s.forms.isDirty(ia), 'form A not un-dirtied');
  432. check(ib.value === 'y', 'form B was touched');
  433. check(s.forms.isDirty(ib), 'form B dirty state was touched');
  434. // Passing a control inside a form resolves the owning form.
  435. ib.value = 'z';
  436. s.forms.reset(ib);
  437. check(ib.value === 'dflt-b', 'forms.reset(el) did not resolve the owning form');
  438. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  439. } else if (scenario === '16') {
  440. // Handler order: stm-prefill first (property writes feed later predicates).
  441. var names = s._bridge.attributeHandlers.map(function (h) { return h.name; });
  442. check(names.indexOf('stm-prefill') === 0, 'stm-prefill is not first: ' + JSON.stringify(names));
  443. check(names.indexOf('stm-class.') === 1, 'stm-class. is not second: ' + JSON.stringify(names));
  444. check(names.indexOf('stm-markdown') === names.indexOf('stm-html') + 1, 'markdown ordering broke');
  445. check(names[names.length - 1] === 'stm-h-demotion', 'last handler changed: ' + JSON.stringify(names));
  446. check(log.warns.length === 0, 'warnings: ' + JSON.stringify(log.warns));
  447. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  448. } else if (scenario === '17') {
  449. // reenter: an action response re-fetches the entrypoint in place.
  450. var t = el('span'); t.setAttribute('stm-text', 'm.mood');
  451. body.appendChild(t);
  452. sigCounter++;
  453. var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
  454. var snap2 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'second' } };
  455. var entrypointCount = 0;
  456. globalThis.__shim.setFetch(function (url) {
  457. if (String(url).indexOf('/_statum/entrypoint') !== -1) {
  458. entrypointCount++;
  459. return globalThis.__shim.okResponse([{
  460. type: 'set',
  461. snapshot_frame: {
  462. content: JSON.stringify(entrypointCount === 1 ? snap1 : snap2),
  463. signature: 'sig-r17-' + entrypointCount
  464. }
  465. }]);
  466. }
  467. // The action request: reply with a reenter directive.
  468. return globalThis.__shim.okResponse([{ type: 'reenter' }]);
  469. });
  470. await s._bridge.loadEntrypoint();
  471. await spin();
  472. check(t.textContent === 'first', 'initial entrypoint state not applied: ' + JSON.stringify(t.textContent));
  473. var initialFetches = globalThis.__shim.fetchCalls.length;
  474. await s._bridge.performAction({ uri: '/save', method: 'POST' }, {});
  475. await spin(50);
  476. var entryFetches = globalThis.__shim.fetchCalls.filter(function (c) {
  477. return c.url.indexOf('/_statum/entrypoint') !== -1;
  478. });
  479. check(entryFetches.length === 2, 'entrypoint fetched ' + entryFetches.length + ' time(s), expected 2 (initial + reenter)');
  480. check(globalThis.__shim.fetchCalls.length === initialFetches + 2,
  481. 'exactly two new requests were expected (action + refresh), got ' +
  482. (globalThis.__shim.fetchCalls.length - initialFetches));
  483. check(t.textContent === 'second', 'reentered entrypoint state not applied: ' + JSON.stringify(t.textContent));
  484. check(globalThis.location.href === 'http://localhost/', 'a bare reenter must not navigate');
  485. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  486. } else if (scenario === '18') {
  487. // reenter + navigate in one response: refresh first, then navigate wins.
  488. var t = el('span'); t.setAttribute('stm-text', 'm.mood');
  489. body.appendChild(t);
  490. sigCounter++;
  491. var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
  492. var snap2 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'second' } };
  493. var entrypointCount = 0;
  494. var order = []; // shared log: reenter's fetch vs the location change
  495. globalThis.__shim.setFetch(function (url) {
  496. if (String(url).indexOf('/_statum/entrypoint') !== -1) {
  497. entrypointCount++;
  498. order.push('entrypoint:' + entrypointCount);
  499. return globalThis.__shim.okResponse([{
  500. type: 'set',
  501. snapshot_frame: {
  502. content: JSON.stringify(entrypointCount === 1 ? snap1 : snap2),
  503. signature: 'sig-r18-' + entrypointCount
  504. }
  505. }]);
  506. }
  507. return globalThis.__shim.okResponse([{ type: 'reenter' }, { type: 'navigate', uri: '/after' }]);
  508. });
  509. // Record the navigation in the shared order log.
  510. var originalHref = globalThis.location.href;
  511. Object.defineProperty(globalThis.location, 'href', {
  512. configurable: true,
  513. get: function () { return originalHref; },
  514. set: function (v) { order.push('navigate:' + v); }
  515. });
  516. await s._bridge.loadEntrypoint();
  517. await spin();
  518. check(t.textContent === 'first', 'initial entrypoint state not applied');
  519. await s._bridge.performAction({ uri: '/save', method: 'POST' }, {});
  520. await spin(50);
  521. check(globalThis.__shim.fetchCalls.filter(function (c) {
  522. return c.url.indexOf('/_statum/entrypoint') !== -1;
  523. }).length === 2, 'reenter did not refresh the entrypoint');
  524. check(order.indexOf('navigate:/after') !== -1, 'navigate did not run');
  525. check(order.indexOf('entrypoint:2') < order.indexOf('navigate:/after'),
  526. 'reenter must run before navigate, order was ' + JSON.stringify(order));
  527. check(t.textContent === 'second', 'refresh state not applied before navigating');
  528. check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
  529. } else if (scenario === '19') {
  530. // A failing reenter refresh: logged, swallowed, navigate still runs, and
  531. // the action promise resolves.
  532. var t = el('span'); t.setAttribute('stm-text', 'm.mood');
  533. body.appendChild(t);
  534. sigCounter++;
  535. var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
  536. var entrypointCount = 0;
  537. globalThis.__shim.setFetch(function (url) {
  538. if (String(url).indexOf('/_statum/entrypoint') !== -1) {
  539. entrypointCount++;
  540. if (entrypointCount === 1) {
  541. return globalThis.__shim.okResponse([{
  542. type: 'set',
  543. snapshot_frame: { content: JSON.stringify(snap1), signature: 'sig-r19-1' }
  544. }]);
  545. }
  546. return Promise.reject(new Error('network down'));
  547. }
  548. return globalThis.__shim.okResponse([{ type: 'reenter' }, { type: 'navigate', uri: '/after' }]);
  549. });
  550. var navigatedTo = null;
  551. Object.defineProperty(globalThis.location, 'href', {
  552. configurable: true,
  553. get: function () { return 'http://localhost/'; },
  554. set: function (v) { navigatedTo = v; }
  555. });
  556. await s._bridge.loadEntrypoint();
  557. await spin();
  558. var resolved = false;
  559. var rejected = null;
  560. await s._bridge.performAction({ uri: '/save', method: 'POST' }, {}).then(function () {
  561. resolved = true;
  562. }, function (e) {
  563. rejected = e;
  564. });
  565. await spin(50);
  566. check(resolved && rejected === null, 'action promise should resolve after a failed reenter, rejected=' + String(rejected));
  567. check(log.errors.some(function (m) { return m.indexOf('[statum] reenter: entrypoint refresh failed') !== -1; }),
  568. 'reenter failure was not logged: ' + JSON.stringify(log.errors));
  569. check(navigatedTo === '/after', 'navigate did not run after the failed reenter, navigatedTo=' + JSON.stringify(navigatedTo));
  570. check(log.errors.length === 1, 'exactly one console.error expected: ' + JSON.stringify(log.errors));
  571. // Core logs the swallowed reenter failure by design; nothing else may error.
  572. log.errors.length = 0;
  573. } else {
  574. fail('unknown scenario: ' + scenario);
  575. }
  576. check(log.errors.length === 0, 'unexpected console.error: ' + JSON.stringify(log.errors));
  577. print('scenario ' + scenario + ': OK');
  578. }
  579. main().catch(function (e) {
  580. std.err.puts('FAIL [' + scenario + '] ' + (e && e.stack || e) + '\n');
  581. std.exit(1);
  582. });