| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131 |
- /**
- * DOM-walk + forms-module scenarios for the Statum client.
- *
- * Each scenario runs in a FRESH QuickJS context (run.sh invokes this script
- * once per scenario) with a minimal DOM shim (shim.js) that supports the
- * render walk and the forms module end to end, including capture-phase
- * events, form reset defaults and a scriptable fetch stub.
- *
- * State enters through the real machinery: a `set` directive returned by the
- * fetch stub and applied by bridge.loadEntrypoint() (which re-renders through
- * applyDirectives -> renderAll). Signatures vary per step so the idempotency
- * guard never short-circuits a deliberate re-render.
- *
- * 1 walk: stm-if/stm-else chain, stm-text, stm-class.*
- * 2 stm-for keyed: node identity preserved per key, removal honored
- * 3 stm-for unkeyed: instances rebuilt (all identities change)
- * 4 stm-prefill: input + textarea property writes (no attribute)
- * 5 stm-prefill: select single + multiple (array)
- * 6 stm-prefill: checkbox truthy/falsy/null
- * 7 stm-prefill: radio group, same expression per member
- * 8 dirty skip: dirty input keeps user value, clean sibling re-fills
- * 9 dirty is per element within a form
- * 10 reset event un-dirties; prefill re-applies after reset
- * 11 stm-clear-on-success: success resets + un-dirties the form
- * 12 stm-clear-on-success: failure keeps values and dirty state
- * 13 keyed loop of forms: clearing instance 2 leaves 1 and 3 alone
- * 14 two sibling forms: clearing A leaves B alone
- * 15 statum.document.reset: resets exactly the given form
- * 16 handler order: stm-prefill registered before stm-class.*
- * 17 reenter: action triggers an in-place entrypoint refresh (fetched twice)
- * 18 reenter ordering: refresh before navigate, both execute
- * 19 reenter failure: logged only; navigate still runs; promise resolves
- * 20 stm-on-success: applied on success, cleared on the next attempt
- * 21 stm-on-error/on-success mirroring: failure clears success + vice versa
- * 22 stm-clear-on-error: a failing action resets the form
- * 23 declined stm-confirm does NOT clear (clear-on-error present)
- * 24 headless core: stubbed fetch applies state, no walk, no crash
- * 25 stm-local basics: subtree scoping, evaluation through stm-text
- * 26 stm-local laziness: once per pass across two reads; twice across passes
- * 27 stm-global: page-wide visibility incl. before its declaring element
- * 28 stm-global duplicates: last declaration wins, one warn per pass
- * 29 variable cycles: logged, read undefined, walk survives
- * 30 from-attribute: observer redraws on real change only (same value: none)
- * 31 from-value: the declare/username example at the 3-char boundary
- * 32 from-checked on a checkbox
- * 33 declare-without-binder reads undefined; slot shadowing both ways
- * 34 stm-local replaces stm-def (demo's stamp pattern; stm-def inert)
- * 35 several -from- bindings on ONE element all update (review V1)
- * 36 observables: statum.binding.observe + explicit -from-attribute.{name}
- * 37 stm-update-attribute.{name}: writes only on evaluated-value change
- *
- * Usage: qjs tests/dom/scenarios.js <1..37>
- */
- import * as std from 'std';
- import { installShim } from './shim.js';
- // Repo root as a CWD-relative path; run.sh cds to the repo root first (same
- // convention as tests/markdown/spec-test.js).
- var ROOT = '.';
- var scenario = scriptArgs.length > 1 ? scriptArgs[1] : '';
- function fail(msg) {
- std.err.puts('FAIL [' + scenario + '] ' + msg + '\n');
- std.exit(1);
- }
- function check(cond, msg) {
- if (!cond) fail(msg);
- }
- function load(name) {
- (0, eval)(std.loadFile(ROOT + '/js/' + name));
- }
- function loadAll() {
- load('statum-core.js');
- load('statum-document.js');
- load('statum-markdown.js');
- }
- /** Yield to the job queue n times so promise chains settle. */
- async function spin(n) {
- for (var i = 0; i < (n || 30); i++) await Promise.resolve();
- }
- var sigCounter = 0;
- /**
- * Put `public` data into a slot type through a set directive, then re-render.
- * Uses loadEntrypoint (public bridge machinery) so the exact production path
- * (fetch -> handleResponse -> applyDirectives -> renderAll) runs.
- */
- async function setState(typeName, publicData) {
- sigCounter++;
- var snapshot = { slot: { key: 'k-' + typeName, type: typeName, scope: 'page' }, public: publicData };
- globalThis.__shim.setFetch(function () {
- return globalThis.__shim.okResponse([{
- type: 'set',
- snapshot_frame: { content: JSON.stringify(snapshot), signature: 'sig-' + sigCounter }
- }]);
- });
- await globalThis.statum._bridge.loadEntrypoint();
- await spin();
- }
- /** Fire a real (bubbling, non-cancelable-by-default) event on an element. */
- function fire(el, type) {
- var evt = globalThis.__shim.makeEvent(type);
- el.dispatchEvent(evt);
- return evt;
- }
- function el(tag) { return globalThis.__shim.makeElement(tag); }
- function input(type, name, value) {
- var i = el('input');
- if (type) i.setAttribute('type', type);
- if (name) i.setAttribute('name', name);
- if (value !== undefined) i.setAttribute('value', value);
- return i;
- }
- async function main() {
- installShim();
- var log = globalThis.__shim.log;
- var body = globalThis.__shim.body;
- // Scenario 24 runs HEADLESS: core alone, no document module.
- if (scenario !== '24') loadAll();
- else load('statum-core.js');
- // Binding-module scenarios additionally load it (after document).
- if (scenario >= 25) load('statum-binding.js');
- var s = globalThis.statum;
- check(s && s._bridge, 'statum did not load');
- if (scenario === '24') {
- // Headless core: stub the entrypoint fetch, boot, and prove state was
- // applied with no walk and no crash.
- check(s.registerAttribute === undefined,
- 'headless core must not expose registerAttribute (it is document API)');
- check(s.document === undefined, 'headless core must not expose statum.document');
- sigCounter++;
- var snap = { slot: { key: 'k-h', type: 'h', scope: 'page' }, public: { hello: 'world' } };
- globalThis.__shim.setFetch(function () {
- return globalThis.__shim.okResponse([{
- type: 'set',
- snapshot_frame: { content: JSON.stringify(snap), signature: 'sig-h-' + sigCounter }
- }]);
- });
- await s.init();
- await spin(50);
- check(s.read('h') && s.read('h').hello === 'world',
- 'headless boot did not apply the entrypoint state: ' + JSON.stringify(s.state()));
- check(JSON.stringify(s.state()) === '{"h":{"hello":"world"}}',
- 'unexpected state: ' + JSON.stringify(s.state()));
- // A render cycle with no driver and no hooks must not crash or warn.
- s._bridge.renderAll();
- await spin(20);
- check(log.errors.length === 0, 'headless core errored: ' + JSON.stringify(log.errors));
- check(log.warns.length === 0, 'headless core warned: ' + JSON.stringify(log.warns));
- print('scenario ' + scenario + ': OK');
- return;
- }
- check(s.document && typeof s.document.reset === 'function', 'statum.document.reset missing');
- check(typeof s.document.markDirty === 'function' && typeof s.document.isDirty === 'function',
- 'statum.document.markDirty/isDirty missing');
- check(s.forms === undefined, 'statum.forms must be gone (merged into statum.document)');
- check(s._bridge.formsDirty instanceof WeakSet, 'bridge.formsDirty missing');
- check(typeof s._bridge.markDirty === 'function' && typeof s._bridge.isDirty === 'function',
- 'bridge.markDirty/isDirty missing');
- if (scenario === '1') {
- // if/else-if/else chain + stm-text + stm-class.*
- var w = el('div');
- var a = el('p'); a.setAttribute('stm-if', "m.mood === 'up'"); a.textContent = 'up';
- var b = el('p'); b.setAttribute('stm-else-if', "m.mood === 'mid'"); b.textContent = 'mid';
- var c = el('p'); c.setAttribute('stm-else', ''); c.textContent = 'down';
- w.appendChild(a); w.appendChild(b); w.appendChild(c);
- var t = el('span'); t.setAttribute('stm-text', 'm.mood');
- var cl = el('span'); cl.setAttribute('stm-class.hi', "m.mood === 'up'");
- w.appendChild(t); w.appendChild(cl);
- body.appendChild(w);
- await setState('m', { mood: 'up' });
- check(!a.hasAttribute('hidden') && b.hasAttribute('hidden') && c.hasAttribute('hidden'),
- 'branch up not exclusively shown');
- check(t.textContent === 'up', 'stm-text wrote ' + JSON.stringify(t.textContent));
- check(cl.classList.contains('hi'), 'stm-class.hi not applied');
- await setState('m', { mood: 'mid' });
- check(a.hasAttribute('hidden') && !b.hasAttribute('hidden') && c.hasAttribute('hidden'),
- 'branch mid not exclusively shown');
- check(!cl.classList.contains('hi'), 'stm-class.hi not removed');
- check(t.textContent === 'mid', 'stm-text not updated');
- await setState('m', { mood: 'zzz' });
- check(a.hasAttribute('hidden') && b.hasAttribute('hidden') && !c.hasAttribute('hidden'),
- 'else branch not shown');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '2') {
- // Keyed loop: identity per key preserved; removal honored.
- var holder = el('div');
- holder.setAttribute('stm-for-item-in', 'list.items');
- holder.setAttribute('stm-key', 'item.id');
- var row = el('p');
- row.setAttribute('stm-text', 'item.name');
- holder.appendChild(row);
- body.appendChild(holder);
- await setState('list', { items: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }] });
- var insts = holder.parentNode.children.filter(function (n) { return n !== holder; });
- // holder is children[0]; instances follow it in order.
- var kids = body.children.filter(function (n) { return n !== holder; });
- check(kids.length === 3, 'expected 3 instances, got ' + kids.length);
- var k1 = kids[0], k2 = kids[1], k3 = kids[2];
- // The stm-text binding is on the template's child, so read the child.
- check(k1.children[0].textContent === 'a' && k2.children[0].textContent === 'b' &&
- k3.children[0].textContent === 'c',
- 'instance texts: ' + kids.map(function (n) { return n.children[0] && n.children[0].textContent; }).join(','));
- await setState('list', { items: [{ id: 1, name: 'a' }, { id: 3, name: 'c3' }] });
- var kids2 = body.children.filter(function (n) { return n !== holder; });
- check(kids2.length === 2, 'expected 2 instances after removal, got ' + kids2.length);
- check(kids2[0] === k1, 'key 1 node identity not preserved');
- check(kids2[1] === k3, 'key 3 node identity not preserved');
- check(kids2[1].children[0].textContent === 'c3', 'key 3 text not refreshed');
- check(k2.parentNode === null, 'removed instance still attached');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '3') {
- // Unkeyed loop: rebuild wholesale.
- var holder = el('div');
- holder.setAttribute('stm-for-item-in', 'list.items');
- var row = el('p');
- row.setAttribute('stm-text', 'item.name');
- holder.appendChild(row);
- body.appendChild(holder);
- await setState('list', { items: [{ name: 'a' }, { name: 'b' }] });
- var kids = body.children.filter(function (n) { return n !== holder; });
- check(kids.length === 2 && kids[0].children[0].textContent === 'a' &&
- kids[1].children[0].textContent === 'b', 'initial render');
- await setState('list', { items: [{ name: 'a' }, { name: 'b' }] });
- var kids2 = body.children.filter(function (n) { return n !== holder; });
- check(kids2.length === 2, 'instance count changed');
- check(kids2[0] !== kids[0] && kids2[1] !== kids[1], 'unkeyed loop reused nodes');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '4') {
- // Prefill writes the value PROPERTY, never the value attribute.
- var f = el('form');
- var ti = input('text', 'who'); ti.setAttribute('stm-prefill', 'p.who');
- var ta = el('textarea'); ta.setAttribute('name', 'bio'); ta.setAttribute('stm-prefill', 'p.bio');
- f.appendChild(ti); f.appendChild(ta);
- body.appendChild(f);
- await setState('p', { who: 'ada', bio: 'hi' });
- check(ti.value === 'ada', 'text input value = ' + JSON.stringify(ti.value));
- check(ta.value === 'hi', 'textarea value = ' + JSON.stringify(ta.value));
- check(ti.getAttribute('value') === null, 'text input value ATTRIBUTE was written');
- check(ta.getAttribute('stm-prefill') === 'p.bio', 'stm-prefill attribute consumed');
- await setState('p', { who: null, bio: undefined });
- check(ti.value === '', 'null should prefill as empty string, got ' + JSON.stringify(ti.value));
- check(ta.value === 'hi', 'undefined must leave the element untouched');
- await setState('p', { who: 42, bio: 'x' });
- check(ti.value === '42', 'number stringified: ' + JSON.stringify(ti.value));
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '5') {
- // Select single + multiple.
- var f = el('form');
- var sel = el('select'); sel.setAttribute('stm-prefill', 'p.pick');
- var o1 = el('option'); o1.setAttribute('value', 'a'); o1.textContent = 'A';
- var o2 = el('option'); o2.setAttribute('value', 'b'); o2.textContent = 'B';
- sel.appendChild(o1); sel.appendChild(o2);
- var multi = el('select'); multi.setAttribute('multiple', ''); multi.setAttribute('stm-prefill', 'p.set');
- var m1 = el('option'); m1.setAttribute('value', 'x');
- var m2 = el('option'); m2.setAttribute('value', 'y');
- var m3 = el('option'); m3.setAttribute('value', 'z');
- multi.appendChild(m1); multi.appendChild(m2); multi.appendChild(m3);
- f.appendChild(sel); f.appendChild(multi);
- body.appendChild(f);
- await setState('p', { pick: 'b', set: ['x', 'z'] });
- check(sel.value === 'b', 'single select value = ' + JSON.stringify(sel.value));
- check(o2.selected === true && o1.selected === false, 'single select option states wrong');
- check(m1.selected === true && m2.selected === false && m3.selected === true,
- 'multiple select option states wrong');
- await setState('p', { pick: 'nope', set: 'y' });
- check(sel.value === '', 'unmatched single select should yield empty value');
- check(m1.selected === false && m2.selected === true && m3.selected === false,
- 'non-array multiple value must behave like single');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '6') {
- // Checkbox: truthy -> checked, falsy/null -> unchecked.
- var f = el('form');
- var cb = input('checkbox', 'ok'); cb.setAttribute('stm-prefill', 'p.ok');
- f.appendChild(cb);
- body.appendChild(f);
- await setState('p', { ok: true });
- check(cb.checked === true, 'truthy did not check');
- await setState('p', { ok: false });
- check(cb.checked === false, 'falsy did not uncheck');
- await setState('p', { ok: null });
- check(cb.checked === false, 'null did not uncheck');
- await setState('p', { ok: 'yes' });
- check(cb.checked === true, 'non-empty string should check');
- await setState('p', {}); // ok undefined -> untouched
- check(cb.checked === true, 'undefined must leave checked untouched');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '7') {
- // Radio group: every member carries the same expression; the member whose
- // own value matches the resolved value gets checked.
- var f = el('form');
- var mk = function (v) {
- var r = input('radio', 'g', v);
- r.setAttribute('stm-prefill', 'p.choice');
- f.appendChild(r);
- return r;
- };
- var ra = mk('a'), rb = mk('b'), rc = mk('c');
- body.appendChild(f);
- await setState('p', { choice: 'b' });
- check(ra.checked === false && rb.checked === true && rc.checked === false,
- 'state b checked the wrong member(s)');
- await setState('p', { choice: 'd' });
- check(ra.checked === false && rb.checked === false && rc.checked === false,
- 'state d (no match) must leave all unchecked');
- await setState('p', { choice: null });
- check(rb.checked === false, 'null must uncheck (String(null) matches nothing)');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '8') {
- // A dirty element is never overwritten; a clean sibling still fills.
- var f = el('form');
- var i1 = input('text', 'one'); i1.setAttribute('stm-prefill', 'p.one');
- var i2 = input('text', 'two'); i2.setAttribute('stm-prefill', 'p.two');
- f.appendChild(i1); f.appendChild(i2);
- body.appendChild(f);
- await setState('p', { one: 'x', two: 'x' });
- check(i1.value === 'x' && i2.value === 'x', 'initial fill failed');
- fire(i1, 'input'); // user edits input 1
- check(s.document.isDirty(i1), 'input event did not mark the element dirty');
- await setState('p', { one: 'y', two: 'y' });
- check(i1.value === 'x', 'dirty element was overwritten: ' + JSON.stringify(i1.value));
- check(i2.value === 'y', 'clean sibling not re-filled');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '9') {
- // Dirtiness is per element.
- var f = el('form');
- var i1 = input('text', 'one'); i1.setAttribute('stm-prefill', 'p.v');
- var i2 = input('text', 'two'); i2.setAttribute('stm-prefill', 'p.v');
- f.appendChild(i1); f.appendChild(i2);
- body.appendChild(f);
- await setState('p', { v: 'a' });
- fire(i1, 'change');
- await setState('p', { v: 'b' });
- check(i1.value === 'a', 'dirty element overwritten');
- check(i2.value === 'b', 'clean element not filled');
- check(s.document.isDirty(i1) && !s.document.isDirty(i2), 'dirty flags wrong');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '10') {
- // Reset restores defaults, un-dirties, and prefill re-applies.
- var f = el('form');
- var i1 = input('text', 'one', 'init'); i1.setAttribute('stm-prefill', 'p.v');
- f.appendChild(i1);
- body.appendChild(f);
- await setState('p', { v: 'state' });
- check(i1.value === 'state', 'prefill did not apply');
- fire(i1, 'input');
- check(s.document.isDirty(i1), 'not dirty after edit');
- f.reset();
- check(i1.value === 'init', 'reset did not restore the attribute default: ' + JSON.stringify(i1.value));
- check(!s.document.isDirty(i1), 'reset did not un-dirty');
- await setState('p', { v: 'zzz' });
- check(i1.value === 'zzz', 'prefill did not re-apply after reset');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '11') {
- // Clear-on-success: action resolves -> form resets and un-dirties.
- var f = el('form');
- f.setAttribute('stm-action', 'p.act');
- f.setAttribute('stm-clear-on-success', '');
- var i1 = input('text', 'one', 'dflt'); i1.setAttribute('stm-prefill', 'p.v');
- f.appendChild(i1);
- body.appendChild(f);
- await setState('p', { v: 'typed', act: { uri: '/save', method: 'POST' } });
- check(i1.value === 'typed', 'prefill did not apply');
- fire(i1, 'input'); // user edits -> dirty; reset must still win via clear
- globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
- fire(f, 'submit');
- await spin(50);
- check(globalThis.__shim.fetchCalls.some(function (c) { return c.url === '/save'; }),
- 'the action request never fired');
- check(i1.value === 'dflt', 'form not reset after success: ' + JSON.stringify(i1.value));
- check(!s.document.isDirty(i1), 'form not un-dirtied after success');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '12') {
- // Clear-on-success: failure keeps values and dirty state.
- var f = el('form');
- f.setAttribute('stm-action', 'p.act');
- f.setAttribute('stm-clear-on-success', '');
- var i1 = input('text', 'one', 'dflt'); i1.setAttribute('stm-prefill', 'p.v');
- f.appendChild(i1);
- body.appendChild(f);
- await setState('p', { v: 'typed', act: { uri: '/save', method: 'POST' } });
- fire(i1, 'input');
- i1.value = 'edited';
- globalThis.__shim.setFetch(function () { return globalThis.__shim.failResponse(500); });
- fire(f, 'submit');
- await spin(50);
- check(i1.value === 'edited', 'form was reset despite failure: ' + JSON.stringify(i1.value));
- check(s.document.isDirty(i1), 'dirty state lost on failure');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- // Error-directive variant (statum response carrying an error directive).
- globalThis.__shim.setFetch(function () {
- return globalThis.__shim.okResponse([{ type: 'error', message: 'nope' }]);
- });
- fire(f, 'submit');
- await spin(50);
- check(i1.value === 'edited', 'form was reset after an error directive');
- // Core logs error directives by design; nothing else may error.
- check(log.errors.length === 1 && log.errors[0].indexOf('error directive') !== -1,
- 'unexpected console.error: ' + JSON.stringify(log.errors));
- log.errors.length = 0;
- } else if (scenario === '13') {
- // Keyed loop of forms: clearing one instance leaves the others intact.
- var holder = el('div');
- holder.setAttribute('stm-for-item-in', 'p.rows');
- holder.setAttribute('stm-key', 'item.id');
- var row = el('form');
- row.setAttribute('stm-action', 'item.act');
- row.setAttribute('stm-clear-on-success', '');
- var ri = input('text', 'val', 'blank');
- ri.setAttribute('stm-prefill', 'item.val');
- row.appendChild(ri);
- holder.appendChild(row);
- body.appendChild(holder);
- var mkAct = function (uri) { return { uri: uri, method: 'POST' }; };
- await setState('p', {
- rows: [
- { id: 1, val: 'one', act: mkAct('/save1') },
- { id: 2, val: 'two', act: mkAct('/save2') },
- { id: 3, val: 'three', act: mkAct('/save3') }
- ]
- });
- var forms = body.querySelectorAll('form').filter(function (n) {
- // The loop template lives inside the (hidden) holder; instances sit in
- // their own DIVs outside it.
- var p = n.parentNode;
- return p !== holder && p.tagName === 'DIV';
- });
- check(forms.length === 3, 'expected 3 instance forms, got ' + forms.length);
- check(forms[0].children[0].value === 'one', 'instance 1 prefill failed');
- // Dirty instance 2's input by editing it.
- var i2 = forms[1].children[0];
- i2.value = 'user2';
- fire(i2, 'input');
- // Instance 1 and 3 inputs are clean (state-filled).
- globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
- fire(forms[1], 'submit');
- await spin(50);
- check(forms[1].children[0].value === 'blank', 'instance 2 not reset: ' + JSON.stringify(forms[1].children[0].value));
- check(!s.document.isDirty(forms[1].children[0]), 'instance 2 not un-dirtied');
- check(forms[0].children[0].value === 'one', 'instance 1 was touched');
- check(forms[2].children[0].value === 'three', 'instance 3 was touched');
- var saved = globalThis.__shim.fetchCalls.filter(function (c) { return c.method === 'POST'; })
- .map(function (c) { return c.url; });
- check(saved.indexOf('/save2') !== -1 && saved.indexOf('/save1') === -1 && saved.indexOf('/save3') === -1,
- 'wrong action fired: ' + JSON.stringify(saved));
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '14') {
- // Two sibling forms: clear-on-success on A only.
- var fa = el('form');
- fa.setAttribute('stm-action', 'p.act');
- fa.setAttribute('stm-clear-on-success', '');
- var ia = input('text', 'a', 'dflt-a');
- ia.setAttribute('stm-prefill', 'p.va');
- fa.appendChild(ia);
- var fb = el('form');
- fb.setAttribute('stm-action', 'p.act');
- var ib = input('text', 'b', 'dflt-b');
- ib.setAttribute('stm-prefill', 'p.vb');
- fb.appendChild(ib);
- body.appendChild(fa); body.appendChild(fb);
- await setState('p', { va: 'A', vb: 'B', act: { uri: '/save', method: 'POST' } });
- fire(ib, 'input'); // B becomes dirty
- globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
- fire(fa, 'submit');
- await spin(50);
- check(ia.value === 'dflt-a', 'form A not reset');
- check(!s.document.isDirty(ia), 'form A not un-dirtied');
- check(ib.value === 'B', 'form B value was touched');
- check(s.document.isDirty(ib), 'form B dirty state was touched');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '15') {
- // statum.forms.reset resets exactly the given form.
- var fa = el('form');
- var ia = input('text', 'a', 'dflt-a');
- fa.appendChild(ia);
- var fb = el('form');
- var ib = input('text', 'b', 'dflt-b');
- fb.appendChild(ib);
- body.appendChild(fa); body.appendChild(fb);
- ia.value = 'x'; fire(ia, 'input');
- ib.value = 'y'; fire(ib, 'input');
- s.document.reset(fa);
- check(ia.value === 'dflt-a', 'form A not reset');
- check(!s.document.isDirty(ia), 'form A not un-dirtied');
- check(ib.value === 'y', 'form B was touched');
- check(s.document.isDirty(ib), 'form B dirty state was touched');
- // Passing a control inside a form resolves the owning form.
- ib.value = 'z';
- s.document.reset(ib);
- check(ib.value === 'dflt-b', 'forms.reset(el) did not resolve the owning form');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '16') {
- // Handler order: stm-prefill first (property writes feed later predicates).
- var names = s._bridge.attributeHandlers.map(function (h) { return h.name; });
- check(names.indexOf('stm-prefill') === 0, 'stm-prefill is not first: ' + JSON.stringify(names));
- check(names.indexOf('stm-class.') === 1, 'stm-class. is not second: ' + JSON.stringify(names));
- check(names.indexOf('stm-markdown') === names.indexOf('stm-html') + 1, 'markdown ordering broke');
- check(names[names.length - 1] === 'stm-h-demotion', 'last handler changed: ' + JSON.stringify(names));
- check(log.warns.length === 0, 'warnings: ' + JSON.stringify(log.warns));
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '17') {
- // reenter: an action response re-fetches the entrypoint in place.
- var t = el('span'); t.setAttribute('stm-text', 'm.mood');
- body.appendChild(t);
- sigCounter++;
- var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
- var snap2 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'second' } };
- var entrypointCount = 0;
- globalThis.__shim.setFetch(function (url) {
- if (String(url).indexOf('/_statum/entrypoint') !== -1) {
- entrypointCount++;
- return globalThis.__shim.okResponse([{
- type: 'set',
- snapshot_frame: {
- content: JSON.stringify(entrypointCount === 1 ? snap1 : snap2),
- signature: 'sig-r17-' + entrypointCount
- }
- }]);
- }
- // The action request: reply with a reenter directive.
- return globalThis.__shim.okResponse([{ type: 'reenter' }]);
- });
- await s._bridge.loadEntrypoint();
- await spin();
- check(t.textContent === 'first', 'initial entrypoint state not applied: ' + JSON.stringify(t.textContent));
- var initialFetches = globalThis.__shim.fetchCalls.length;
- await s._bridge.performAction({ uri: '/save', method: 'POST' }, {});
- await spin(50);
- var entryFetches = globalThis.__shim.fetchCalls.filter(function (c) {
- return c.url.indexOf('/_statum/entrypoint') !== -1;
- });
- check(entryFetches.length === 2, 'entrypoint fetched ' + entryFetches.length + ' time(s), expected 2 (initial + reenter)');
- check(globalThis.__shim.fetchCalls.length === initialFetches + 2,
- 'exactly two new requests were expected (action + refresh), got ' +
- (globalThis.__shim.fetchCalls.length - initialFetches));
- check(t.textContent === 'second', 'reentered entrypoint state not applied: ' + JSON.stringify(t.textContent));
- check(globalThis.location.href === 'http://localhost/', 'a bare reenter must not navigate');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '18') {
- // reenter + navigate in one response: refresh first, then navigate wins.
- var t = el('span'); t.setAttribute('stm-text', 'm.mood');
- body.appendChild(t);
- sigCounter++;
- var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
- var snap2 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'second' } };
- var entrypointCount = 0;
- var order = []; // shared log: reenter's fetch vs the location change
- globalThis.__shim.setFetch(function (url) {
- if (String(url).indexOf('/_statum/entrypoint') !== -1) {
- entrypointCount++;
- order.push('entrypoint:' + entrypointCount);
- return globalThis.__shim.okResponse([{
- type: 'set',
- snapshot_frame: {
- content: JSON.stringify(entrypointCount === 1 ? snap1 : snap2),
- signature: 'sig-r18-' + entrypointCount
- }
- }]);
- }
- return globalThis.__shim.okResponse([{ type: 'reenter' }, { type: 'navigate', uri: '/after' }]);
- });
- // Record the navigation in the shared order log.
- var originalHref = globalThis.location.href;
- Object.defineProperty(globalThis.location, 'href', {
- configurable: true,
- get: function () { return originalHref; },
- set: function (v) { order.push('navigate:' + v); }
- });
- await s._bridge.loadEntrypoint();
- await spin();
- check(t.textContent === 'first', 'initial entrypoint state not applied');
- await s._bridge.performAction({ uri: '/save', method: 'POST' }, {});
- await spin(50);
- check(globalThis.__shim.fetchCalls.filter(function (c) {
- return c.url.indexOf('/_statum/entrypoint') !== -1;
- }).length === 2, 'reenter did not refresh the entrypoint');
- check(order.indexOf('navigate:/after') !== -1, 'navigate did not run');
- check(order.indexOf('entrypoint:2') < order.indexOf('navigate:/after'),
- 'reenter must run before navigate, order was ' + JSON.stringify(order));
- check(t.textContent === 'second', 'refresh state not applied before navigating');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '19') {
- // A failing reenter refresh: logged, swallowed, navigate still runs, and
- // the action promise resolves.
- var t = el('span'); t.setAttribute('stm-text', 'm.mood');
- body.appendChild(t);
- sigCounter++;
- var snap1 = { slot: { key: 'k-m', type: 'm', scope: 'page' }, public: { mood: 'first' } };
- var entrypointCount = 0;
- globalThis.__shim.setFetch(function (url) {
- if (String(url).indexOf('/_statum/entrypoint') !== -1) {
- entrypointCount++;
- if (entrypointCount === 1) {
- return globalThis.__shim.okResponse([{
- type: 'set',
- snapshot_frame: { content: JSON.stringify(snap1), signature: 'sig-r19-1' }
- }]);
- }
- return Promise.reject(new Error('network down'));
- }
- return globalThis.__shim.okResponse([{ type: 'reenter' }, { type: 'navigate', uri: '/after' }]);
- });
- var navigatedTo = null;
- Object.defineProperty(globalThis.location, 'href', {
- configurable: true,
- get: function () { return 'http://localhost/'; },
- set: function (v) { navigatedTo = v; }
- });
- await s._bridge.loadEntrypoint();
- await spin();
- var resolved = false;
- var rejected = null;
- await s._bridge.performAction({ uri: '/save', method: 'POST' }, {}).then(function () {
- resolved = true;
- }, function (e) {
- rejected = e;
- });
- await spin(50);
- check(resolved && rejected === null, 'action promise should resolve after a failed reenter, rejected=' + String(rejected));
- check(log.errors.some(function (m) { return m.indexOf('[statum] reenter: entrypoint refresh failed') !== -1; }),
- 'reenter failure was not logged: ' + JSON.stringify(log.errors));
- check(navigatedTo === '/after', 'navigate did not run after the failed reenter, navigatedTo=' + JSON.stringify(navigatedTo));
- check(log.errors.length === 1, 'exactly one console.error expected: ' + JSON.stringify(log.errors));
- // Core logs the swallowed reenter failure by design; nothing else may error.
- log.errors.length = 0;
- } else if (scenario === '20') {
- // stm-on-success: applied on success, cleared on the next attempt.
- var b = el('button');
- b.setAttribute('stm-action', 'p.act');
- b.setAttribute('stm-on-success', 'saved ok');
- body.appendChild(b);
- await setState('p', { act: { uri: '/save', method: 'POST' } });
- globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
- fire(b, 'click');
- await spin(50);
- check(b.classList.contains('saved') && b.classList.contains('ok'),
- 'success classes not applied: ' + JSON.stringify(b.classList));
- // A new attempt clears them at attempt start. The fetch stub below never
- // resolves, freezing the attempt mid-flight so the cleared state (before
- // any outcome re-applies classes) is observable.
- var hang = new Promise(function () {});
- globalThis.__shim.setFetch(function () { return hang; });
- fire(b, 'click');
- await spin(20);
- check(!b.classList.contains('saved') && !b.classList.contains('ok'),
- 'success classes not cleared on a new attempt');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '21') {
- // Mirroring: a failure applies stm-on-error and clears stm-on-success;
- // a later success applies stm-on-success and clears stm-on-error.
- var b = el('button');
- b.setAttribute('stm-action', 'p.act');
- b.setAttribute('stm-on-error', 'boom');
- b.setAttribute('stm-on-success', 'yay');
- body.appendChild(b);
- await setState('p', { act: { uri: '/save', method: 'POST' } });
- globalThis.__shim.setFetch(function () { return globalThis.__shim.failResponse(500); });
- fire(b, 'click');
- await spin(50);
- check(b.classList.contains('boom'), 'error classes not applied');
- check(!b.classList.contains('yay'), 'success classes survived a failure');
- log.errors.length = 0;
- globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
- fire(b, 'click');
- await spin(50);
- check(b.classList.contains('yay'), 'success classes not applied after a failure');
- check(!b.classList.contains('boom'), 'error classes survived a success');
- // And an error-directive failure mirrors the HTTP failure exactly.
- globalThis.__shim.setFetch(function () {
- return globalThis.__shim.okResponse([{ type: 'error', message: 'nope' }]);
- });
- fire(b, 'click');
- await spin(50);
- check(b.classList.contains('boom'), 'error classes not applied (error directive)');
- check(!b.classList.contains('yay'), 'success classes survived an error directive');
- log.errors.length = 0;
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '22') {
- // stm-clear-on-error: a failing action resets the form (values and dirty).
- var f = el('form');
- f.setAttribute('stm-action', 'p.act');
- f.setAttribute('stm-clear-on-error', '');
- var i1 = input('text', 'a', 'dflt');
- i1.setAttribute('stm-prefill', 'p.v');
- f.appendChild(i1);
- body.appendChild(f);
- await setState('p', { v: 'from state', act: { uri: '/save', method: 'POST' } });
- i1.value = 'user typed';
- fire(i1, 'input');
- check(s.document.isDirty(i1), 'input not dirty after edit');
- globalThis.__shim.setFetch(function () { return globalThis.__shim.failResponse(500); });
- fire(f, 'submit');
- await spin(50);
- check(i1.value === 'dflt', 'form was not reset on failure: ' + JSON.stringify(i1.value));
- check(!s.document.isDirty(i1), 'form was not un-dirtied on failure');
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- // A success must NOT reset a stm-clear-on-error form.
- i1.value = 'typed again';
- fire(i1, 'input');
- globalThis.__shim.setFetch(function () { return globalThis.__shim.okResponse([]); });
- fire(f, 'submit');
- await spin(50);
- check(i1.value === 'typed again', 'stm-clear-on-error fired on success: ' + JSON.stringify(i1.value));
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- } else if (scenario === '23') {
- // A declined stm-confirm never clears: decline is cancellation, not error.
- var f = el('form');
- f.setAttribute('stm-action', 'p.act');
- f.setAttribute('stm-confirm', 'sure?');
- f.setAttribute('stm-clear-on-error', '');
- var i1 = input('text', 'a', 'dflt');
- f.appendChild(i1);
- body.appendChild(f);
- await setState('p', { act: { uri: '/save', method: 'POST' } });
- i1.value = 'user typed';
- fire(i1, 'input');
- // Decline the confirm (custom handler returning false).
- s.onConfirmHandler = function () { return false; };
- fire(f, 'submit');
- await spin(50);
- check(i1.value === 'user typed', 'declined confirm cleared the form: ' + JSON.stringify(i1.value));
- check(s.document.isDirty(i1), 'declined confirm un-dirtied the form');
- var posts = globalThis.__shim.fetchCalls.filter(function (c) { return c.method === 'POST'; });
- check(posts.length === 0, 'a declined confirm still fired a request: ' + JSON.stringify(posts));
- check(log.errors.length === 0, 'errors: ' + JSON.stringify(log.errors));
- // The error-directive path of clear-on-error: failure with a Statum body.
- s.onConfirmHandler = null; // window.confirm fallback: shim returns true
- i1.value = 'typed more';
- fire(i1, 'input');
- globalThis.__shim.setFetch(function () {
- return globalThis.__shim.okResponse([{ type: 'error', message: 'nope' }]);
- });
- fire(f, 'submit');
- await spin(50);
- check(i1.value === 'dflt', 'error directive did not reset a clear-on-error form: ' + JSON.stringify(i1.value));
- log.errors.length = 0;
- } else if (scenario === '25') {
- // stm-local basic: subtree scoping + evaluation through stm-text.
- var holder = el('div');
- holder.setAttribute('stm-local-x', '1 + 1');
- var span = el('span'); span.setAttribute('stm-text', 'x');
- holder.appendChild(span);
- body.appendChild(holder);
- var outside = el('span'); outside.setAttribute('stm-text', 'typeof x');
- body.appendChild(outside);
- await s._bridge.renderAll(); await spin();
- check(span.textContent === '2', 'stm-local-x did not resolve: ' + span.textContent);
- check(outside.textContent === 'undefined', 'local leaked outside its subtree');
- } else if (scenario === '26') {
- // Lazy evaluation: once per pass even when read many times.
- var calls = 0;
- globalThis.__count = function () { calls++; return calls; };
- var holder2 = el('div');
- holder2.setAttribute('stm-local-n', '__count()');
- var a2 = el('span'); a2.setAttribute('stm-text', 'n');
- var b2 = el('span'); b2.setAttribute('stm-text', 'n + n');
- holder2.appendChild(a2); holder2.appendChild(b2);
- body.appendChild(holder2);
- await s._bridge.renderAll(); await spin();
- check(a2.textContent === '1' && b2.textContent === '2', 'lazy value wrong: ' + a2.textContent + '/' + b2.textContent);
- check(calls === 1, 'expression evaluated ' + calls + ' times in one pass (must be 1)');
- await s._bridge.renderAll(); await spin();
- check(calls === 2, 'second pass did not re-evaluate (calls=' + calls + ')');
- } else if (scenario === '27') {
- // stm-global: visible page-wide on the FIRST pass (the pass-start sweep
- // exposes lazy getters; a reader before the declaring element resolves
- // the same binding on demand), and stable across passes.
- var early = el('span'); early.setAttribute('stm-text', 'typeof g');
- body.appendChild(early);
- var late = el('div'); late.setAttribute('stm-global-g', '41 + 1');
- var lateSpan = el('span'); lateSpan.setAttribute('stm-text', 'g');
- late.appendChild(lateSpan);
- body.appendChild(late);
- await s._bridge.renderAll(); await spin();
- check(early.textContent === 'number', 'global not visible before its declaration on pass 1');
- await s._bridge.renderAll(); await spin();
- check(early.textContent === 'number', 'global lost on second pass');
- // Prove the VALUE is reachable, not just the type, via an if-predicate.
- var gate = el('div'); gate.setAttribute('stm-if', 'g === 42');
- body.appendChild(gate);
- await s._bridge.renderAll(); await spin();
- check(!gate.hasAttribute('hidden'), 'g === 42 did not evaluate true');
- } else if (scenario === '28') {
- // Duplicate stm-global: last in document order wins, one warn per pass.
- var g1 = el('div'); g1.setAttribute('stm-global-dup', '1');
- var g2 = el('div'); g2.setAttribute('stm-global-dup', '2');
- var rd = el('span'); rd.setAttribute('stm-text', 'dup');
- body.appendChild(g1); body.appendChild(g2); body.appendChild(rd);
- log.warns.length = 0;
- await s._bridge.renderAll(); await spin();
- check(rd.textContent === '2', 'last duplicate did not win: ' + rd.textContent);
- check(log.warns.length === 1, 'expected exactly one duplicate warn, got ' + log.warns.length);
- log.warns.length = 0;
- await s._bridge.renderAll(); await spin();
- check(log.warns.length === 1, 'warn must fire once per pass');
- } else if (scenario === '29') {
- // Cycles: logged as an error, variables read undefined, walk survives.
- var ca = el('div'); ca.setAttribute('stm-global-a', 'b');
- var cb = el('div'); cb.setAttribute('stm-global-b', 'a');
- var ra = el('span'); ra.setAttribute('stm-text', 'typeof a');
- body.appendChild(ca); body.appendChild(cb); body.appendChild(ra);
- await s._bridge.renderAll(); await spin();
- check(log.errors.length >= 1 && /variable cycle/.test(log.errors[0]),
- 'cycle not logged: ' + JSON.stringify(log.errors));
- check(ra.textContent === 'undefined', 'cyclic variable must read undefined');
- log.errors.length = 0;
- } else if (scenario === '30') {
- // from-attribute (non-control): observer redraws on real change only.
- var host = el('div'); host.setAttribute('title', 'first');
- host.setAttribute('stm-local-t', 't'); // reads via the from binding below
- host.setAttribute('stm-local-t-from-title', '');
- // ^ both spellings would conflict; use only the from- form:
- host.removeAttribute('stm-local-t');
- var outT = el('span'); outT.setAttribute('stm-text', 't');
- host.appendChild(outT);
- body.appendChild(host);
- var cycles = 0;
- s.afterEvaluate(function () { cycles++; });
- await s._bridge.renderAll(); await spin();
- check(outT.textContent === 'first', 'from-title not read: ' + outT.textContent);
- cycles = 0;
- host.setAttribute('title', 'first'); // same value: no redraw
- await spin(10);
- check(cycles === 0, 'same-value attribute write triggered a redraw');
- host.setAttribute('title', 'second'); // real change: redraw
- await spin(10);
- check(cycles >= 1, 'changed attribute did not redraw');
- check(outT.textContent === 'second', 'variable not updated after change: ' + outT.textContent);
- } else if (scenario === '31') {
- // The operator's example: declare + local-from-value + stm-if.
- var box = el('div'); box.setAttribute('stm-declare-username', '');
- var f31 = el('form');
- var inp = input('text', 'username', '');
- inp.setAttribute('stm-local-username-from-value', '');
- f31.appendChild(inp);
- var alertBox = el('div'); alertBox.setAttribute('stm-if', 'username.length < 3');
- alertBox.textContent = 'Username is too short';
- var okBox = el('div'); okBox.setAttribute('stm-if', 'username.length >= 3');
- var okName = el('span'); okName.setAttribute('stm-text', 'username');
- okBox.appendChild(okName);
- box.appendChild(f31); box.appendChild(alertBox); box.appendChild(okBox);
- body.appendChild(box);
- await s._bridge.renderAll(); await spin();
- check(!alertBox.hasAttribute('hidden'), 'alert must show with empty username');
- check(okBox.hasAttribute('hidden'), 'ok box must hide with empty username');
- inp.value = 'ab'; fire(inp, 'input'); await spin(10);
- check(!alertBox.hasAttribute('hidden'), 'alert must show for "ab"');
- inp.value = 'abc'; fire(inp, 'input'); await spin(10);
- check(alertBox.hasAttribute('hidden'), 'alert must hide for "abc"');
- check(!okBox.hasAttribute('hidden') && okName.textContent === 'abc',
- 'ok box wrong: hidden=' + okBox.hasAttribute('hidden') + ' text=' + okName.textContent);
- } else if (scenario === '32') {
- // from-checked on a checkbox.
- var box32 = el('div'); box32.setAttribute('stm-declare-agree', '');
- var cbx = input('checkbox', 'agree', '');
- cbx.setAttribute('stm-local-agree-from-checked', '');
- var lab = el('span'); lab.setAttribute('stm-text', 'agree ? "yes" : "no"');
- box32.appendChild(cbx); box32.appendChild(lab);
- body.appendChild(box32);
- await s._bridge.renderAll(); await spin();
- check(lab.textContent === 'no', 'unchecked must read false: ' + lab.textContent);
- cbx.checked = true; fire(cbx, 'change'); await spin(10);
- check(lab.textContent === 'yes', 'checked must read true: ' + lab.textContent);
- } else if (scenario === '33') {
- // Declare without binder: undefined, page alive; shadowing.
- var box33 = el('div'); box33.setAttribute('stm-declare-later', '');
- var probe = el('span'); probe.setAttribute('stm-text', 'typeof later');
- box33.appendChild(probe);
- body.appendChild(box33);
- await s._bridge.renderAll(); await spin();
- check(probe.textContent === 'undefined', 'declared-but-unbound must read undefined');
- // Shadowing: a variable named like a slot type wins in its scope.
- await setState('counter', { n: 5 });
- var sh = el('div'); sh.setAttribute('stm-local-counter', '99');
- var shOut = el('span'); shOut.setAttribute('stm-text', 'typeof counter');
- sh.appendChild(shOut); body.appendChild(sh);
- var plain = el('span'); plain.setAttribute('stm-text', 'counter.n');
- body.appendChild(plain);
- await s._bridge.renderAll(); await spin();
- check(shOut.textContent === 'number', 'shadowing variable must hide the slot type: ' + shOut.textContent);
- check(plain.textContent === '5', 'slot type must still read outside the shadow');
- } else if (scenario === '34') {
- // stm-local replaces stm-def: the demo's stamp pattern, and the legacy
- // stm-def-{name}-as spelling works as an obsolescent alias (warns once
- // per element, binds identically).
- var box34 = el('div'); box34.setAttribute('stm-local-stamp', "'updated '" + ' + counter.n');
- var out34 = el('span'); out34.setAttribute('stm-text', 'stamp');
- box34.appendChild(out34); body.appendChild(box34);
- await setState('counter', { n: 7 });
- check(out34.textContent === 'updated 7', 'stamp local wrong: ' + out34.textContent);
- var legacy = el('div'); legacy.setAttribute('stm-def-old-as', '1');
- var legacyOut = el('span'); legacyOut.setAttribute('stm-text', 'old');
- legacy.appendChild(legacyOut); body.appendChild(legacy);
- log.warns.length = 0;
- await s._bridge.renderAll(); await spin();
- check(legacyOut.textContent === '1', 'legacy stm-def must still bind: ' + legacyOut.textContent);
- check(log.warns.length === 1 && /obsolescent/.test(log.warns[0]),
- 'legacy stm-def must warn once: ' + JSON.stringify(log.warns));
- var warnsAfter = log.warns.length;
- await s._bridge.renderAll(); await spin();
- check(log.warns.length === warnsAfter, 'obsolescence warn must fire once per element, not per pass');
- } else if (scenario === '35') {
- // Several -from- bindings on ONE element (review finding: the plumbing
- // was keyed per element, so the second binding never updated).
- var box35 = el('div'); box35.setAttribute('stm-declare-v', '');
- box35.setAttribute('stm-declare-w', '');
- var inp35 = input('text', 'dual', '');
- inp35.setAttribute('stm-local-v-from-value', '');
- inp35.setAttribute('stm-local-w-from-value', '');
- var outV = el('span'); outV.setAttribute('stm-text', 'v');
- var outW = el('span'); outW.setAttribute('stm-text', 'w');
- box35.appendChild(inp35); box35.appendChild(outV); box35.appendChild(outW);
- body.appendChild(box35);
- await s._bridge.renderAll(); await spin();
- check(outV.textContent === '' && outW.textContent === '',
- 'empty input must read "" for both (got ' + outV.textContent + '/' + outW.textContent + ')');
- inp35.value = 'hello'; fire(inp35, 'input'); await spin(10);
- check(outV.textContent === 'hello', 'first from-value binding stuck: ' + outV.textContent);
- check(outW.textContent === 'hello', 'SECOND from-value binding on the same element stuck: ' + outW.textContent);
- // Same for two attribute observers on one element.
- var host35 = el('div'); host35.setAttribute('title', 'T1'); host35.setAttribute('lang', 'L1');
- host35.setAttribute('stm-global-a', 'a'); host35.removeAttribute('stm-global-a');
- host35.setAttribute('stm-global-t-from-title', '');
- host35.setAttribute('stm-global-l-from-lang', '');
- var outT35 = el('span'); outT35.setAttribute('stm-text', 't');
- var outL35 = el('span'); outL35.setAttribute('stm-text', 'l');
- body.appendChild(host35); body.appendChild(outT35); body.appendChild(outL35);
- await s._bridge.renderAll(); await spin();
- check(outT35.textContent === 'T1' && outL35.textContent === 'L1',
- 'attribute forms did not read initially: ' + outT35.textContent + '/' + outL35.textContent);
- host35.setAttribute('lang', 'L2'); await spin(10);
- check(outL35.textContent === 'L2', 'SECOND attribute observer on the same element stuck: ' + outL35.textContent);
- host35.setAttribute('title', 'T2'); await spin(10);
- check(outT35.textContent === 'T2', 'first attribute observer stuck: ' + outT35.textContent);
- } else if (scenario === '36') {
- // Generic observables: a property registered through the public API
- // (not hard-coded) drives -from- bindings with events, not attributes.
- check(s.binding && typeof s.binding.observe === 'function',
- 'statum.binding.observe missing');
- s.binding.observe('selectedIndex', ['change']);
- var wrapSel = el('div'); wrapSel.setAttribute('stm-declare-sel', '');
- var sel = el('select');
- var o1 = el('option'); o1.setAttribute('value', 'a'); o1.value = 'a';
- var o2 = el('option'); o2.setAttribute('value', 'b'); o2.value = 'b';
- sel.appendChild(o1); sel.appendChild(o2);
- // The shim's element accepts ad-hoc properties; options feed nothing —
- // selectedIndex is ours to drive for the test.
- sel.selectedIndex = 0;
- sel.setAttribute('stm-local-sel-from-selectedIndex', '');
- var outSel = el('span'); outSel.setAttribute('stm-text', 'sel');
- wrapSel.appendChild(sel); wrapSel.appendChild(outSel);
- body.appendChild(wrapSel);
- await s._bridge.renderAll(); await spin();
- check(outSel.textContent === '0', 'observable property not read: ' + outSel.textContent);
- sel.selectedIndex = 1; fire(sel, 'change'); await spin(10);
- check(outSel.textContent === '1',
- 'custom observable did not update via its event: ' + outSel.textContent);
- // The explicit attribute spelling for a name outside the event mapping.
- var wrap36 = el('div'); wrap36.setAttribute('stm-declare-v36', '');
- var d36 = el('div'); d36.setAttribute('title', 'attr');
- d36.setAttribute('stm-local-v36-from-attribute.title', '');
- var out36 = el('span'); out36.setAttribute('stm-text', 'v36');
- wrap36.appendChild(d36); wrap36.appendChild(out36);
- body.appendChild(wrap36);
- await s._bridge.renderAll(); await spin();
- check(out36.textContent === 'attr', 'attribute source not read: ' + out36.textContent);
- d36.setAttribute('title', 'changed'); await spin(10);
- check(out36.textContent === 'changed',
- 'explicit attribute source did not update: ' + out36.textContent);
- } else if (scenario === '37') {
- // stm-update-attribute.{name}: writes only when the EVALUATED value
- // changes; local/scripted attribute changes survive between renders.
- var box37 = el('div');
- box37.setAttribute('stm-update-attribute.title', 'brand.title');
- body.appendChild(box37);
- await setState('brand', { title: 'v1' });
- check(box37.getAttribute('title') === 'v1',
- 'first evaluation did not write: ' + box37.getAttribute('title'));
- // A script/user changes the attribute; a render whose expression still
- // yields 'v1' must NOT clobber it.
- box37.setAttribute('title', 'user changed');
- await setState('brand', { title: 'v1' }); // same value, new signature
- check(box37.getAttribute('title') === 'user changed',
- 'unchanged expression clobbered a local change: ' + box37.getAttribute('title'));
- // The expression's output changes -> write once, then leave alone again.
- await setState('brand', { title: 'v2' });
- check(box37.getAttribute('title') === 'v2',
- 'changed expression did not write: ' + box37.getAttribute('title'));
- box37.setAttribute('title', 'local again');
- await setState('brand', { title: 'v2' });
- check(box37.getAttribute('title') === 'local again',
- 'rewrite happened despite unchanged evaluated value');
- // null removes the attribute (once); undefined never touches it.
- await setState('brand', { title: null });
- check(box37.getAttribute('title') === null,
- 'null did not remove the attribute: ' + box37.getAttribute('title'));
- // First-evaluation adoption: an attribute already holding the value is
- // adopted as baseline; a later local change then survives unchanged
- // renders (the observable difference between adopt and write).
- var box37b = el('div');
- box37b.setAttribute('title', 'v2');
- box37b.setAttribute('stm-update-attribute.title', 'brand.title');
- body.appendChild(box37b);
- await setState('brand', { title: 'v2' }); // adopts 'v2' as baseline
- box37b.setAttribute('title', 'kept');
- await setState('brand', { title: 'v2' }); // still v2: adopted, no write
- check(box37b.getAttribute('title') === 'kept',
- 'baseline adoption failed: ' + box37b.getAttribute('title'));
- } else {
- fail('unknown scenario: ' + scenario);
- }
- check(log.errors.length === 0, 'unexpected console.error: ' + JSON.stringify(log.errors));
- print('scenario ' + scenario + ': OK');
- }
- main().catch(function (e) {
- std.err.puts('FAIL [' + scenario + '] ' + (e && e.stack || e) + '\n');
- std.exit(1);
- });
|