rob-revisited/ide/ui/js/tutorial/tour.test.mjs

346 lines
17 KiB
JavaScript

// Run: node --test ide/ui/js/tutorial/tour.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Tour, localize, selectorOf, matches, targetsOf } from './tour.js';
import { symfonyTutorial } from './symfony-steps.js';
import { shouldOffer, markCreated, setNeverOffer, PENDING_KEY } from './offer.js';
const here = dirname(fileURLToPath(import.meta.url));
const ui = join(here, '..', '..');
/** A fake IDE: elements by selector, events, timers kept by hand, files that exist. */
function fakeHost(elements = {}) {
const h = {
elements, listeners: new Set(), timers: [], files: new Set(), performed: [],
query: (sel) => h.elements[sel] || null,
on: (fn) => { h.listeners.add(fn); return () => h.listeners.delete(fn); },
every: (ms, fn) => { const t = { ms, fn, every: true }; h.timers.push(t); return () => h.timers.splice(h.timers.indexOf(t), 1); },
later: (ms, fn) => { const t = { ms, fn }; h.timers.push(t); return () => h.timers.splice(h.timers.indexOf(t), 1); },
exists: async (p) => h.files.has(p),
contains: (el, target) => el === target || el.children?.includes(target),
perform: async (c) => { h.performed.push(c); },
sleep: () => new Promise((r) => setTimeout(r, 1)),
emit: (e) => { for (const fn of [...h.listeners]) fn(e); },
flushLater: () => { for (const t of [...h.timers].filter((x) => !x.every)) { h.timers.splice(h.timers.indexOf(t), 1); t.fn(); } },
};
return h;
}
const memory = () => { const m = new Map(); return { get: (k, fb) => (m.has(k) ? m.get(k) : fb), set: (k, v) => m.set(k, v), m }; };
const def = {
id: 'demo', title: 'Demo',
chapters: [
{ id: 'a', title: { en: 'A', fr: 'Un' }, steps: [{ id: 's1', title: 'One', text: { en: 'one', fr: 'un' } }, { id: 's2', title: 'Two', text: 'two', target: ['missing', 'btn'], wait: { tool: 'console' }, do: [{ tool: 'console' }] }] },
{ id: 'b', title: 'B', steps: [{ id: 's3', title: 'Three', text: 'three', wait: { exists: 'src/A.php' } }, { id: 's4', title: 'Four', text: 'four', wait: { any: [{ saved: '\\.twig$' }, { action: 'x' }] }, auto: false }] },
],
};
test('texts: the language, then English', () => {
assert.equal(localize({ en: 'a', fr: 'b' }, 'fr'), 'b');
assert.equal(localize({ en: 'a' }, 'de'), 'a');
assert.equal(localize('plain', 'fr'), 'plain');
assert.equal(selectorOf('tool-console'), '[data-tour="tool-console"]');
});
test('navigation: next, previous, goto, bounds', () => {
const tour = new Tour(def, { host: fakeHost(), store: memory() });
tour.start();
assert.equal(tour.current().id, 's1');
assert.equal(tour.prev(), false);
assert.equal(tour.next(), true);
assert.equal(tour.current().id, 's2');
assert.ok(tour.goto('s4'));
assert.ok(tour.isLast());
assert.equal(tour.next(), false);
assert.equal(tour.goto(99), false);
assert.ok(tour.goto(0));
});
test('table of contents: chapters, done ticks, current', () => {
const tour = new Tour(def, { host: fakeHost(), store: memory(), lang: 'fr' });
tour.start();
tour.next();
const toc = tour.toc();
assert.equal(toc[0].title, 'Un');
assert.deepEqual(toc[0].steps.map((s) => s.done), [true, false]);
assert.equal(toc[0].current, true);
assert.equal(toc[1].current, false);
assert.equal(tour.text(tour.current().text), 'two');
tour.setLang('en');
assert.equal(tour.toc()[0].title, 'A');
});
test('waiting: a tool opened satisfies the step and moves on after the delay', () => {
const host = fakeHost();
const tour = new Tour(def, { host, store: memory() });
tour.start();
tour.next(); // s2 waits for the console
host.emit({ type: 'tool', id: 'docker' });
assert.equal(tour.satisfied, false);
host.emit({ type: 'tool', id: 'console' });
assert.equal(tour.satisfied, true);
assert.equal(tour.current().id, 's2');
host.flushLater();
assert.equal(tour.current().id, 's3');
assert.ok(tour.done.has('s2'));
});
test('waiting: a file that appears (polled), any-of waits, no auto-advance', async () => {
const host = fakeHost();
const tour = new Tour(def, { host, store: memory() });
tour.start();
tour.goto('s3');
await new Promise((r) => setTimeout(r, 0));
assert.equal(tour.satisfied, false);
host.files.add('src/A.php');
host.timers.find((t) => t.every).fn();
await new Promise((r) => setTimeout(r, 0));
assert.equal(tour.satisfied, true);
host.flushLater();
assert.equal(tour.current().id, 's4');
host.emit({ type: 'saved', path: 'templates/x.html.twig' });
assert.equal(tour.satisfied, true);
host.flushLater();
assert.equal(tour.current().id, 's4'); // auto: false
assert.ok(tour.done.has('s4'));
});
test('waiting stops when the user leaves the step', () => {
const host = fakeHost();
const tour = new Tour(def, { host, store: memory() });
tour.start();
tour.goto('s2');
assert.equal(host.listeners.size, 1);
tour.goto('s1');
assert.equal(host.listeners.size, 0);
tour.exit();
});
test('events: click waits use the data-tour element', () => {
const button = { children: [] };
const inner = {}; button.children.push(inner);
const host = fakeHost({ '[data-tour="run-button"]': button });
assert.ok(matches({ click: 'run-button' }, { type: 'click', target: inner }, host));
assert.equal(matches({ click: 'run-button' }, { type: 'click', target: {} }, host), false);
assert.equal(matches({ opened: 'a\\.php$' }, { type: 'opened', path: 'src/a.php' }, host), true);
});
test('selector resolution: the first present target, the ghost route', () => {
const btn = { id: 'b' };
const host = fakeHost({ '[data-tour="btn"]': btn });
const tour = new Tour(def, { host, store: memory() });
tour.goto('s2');
const hit = tour.resolve();
assert.equal(hit.name, 'btn');
assert.equal(hit.element, btn);
const route = tour.route();
assert.equal(route.length, 1);
assert.equal(route[0].click, true); // the step waits for a tool: the ghost clicks
tour.goto('s1');
assert.equal(tour.resolve(), null);
assert.deepEqual(tour.route(), []);
});
test('do it for me performs the step commands', async () => {
const host = fakeHost();
const tour = new Tour(def, { host, store: memory() });
tour.goto('s2');
assert.equal(await tour.doIt(), 1);
assert.deepEqual(host.performed, [{ tool: 'console' }]);
});
test('persistence: resume where the user left, per key; restart clears', () => {
const store = memory();
const a = new Tour(def, { host: fakeHost(), store, key: 'demo:/p1' });
a.start();
a.next();
a.next();
a.exit();
const b = new Tour(def, { host: fakeHost(), store, key: 'demo:/p1' });
assert.equal(b.current().id, 's3');
assert.ok(b.done.has('s1') && b.done.has('s2'));
const other = new Tour(def, { host: fakeHost(), store, key: 'demo:/p2' });
assert.equal(other.current().id, 's1');
b.start();
b.restart();
assert.equal(b.current().id, 's1');
assert.equal(b.done.size, 0);
assert.equal(new Tour(def, { host: fakeHost(), store, key: 'demo:/p1' }).done.size, 0);
});
// the offer after a new Symfony project -----------------------------------------------------------------------
const symfony = { root: '/p/shop', name: 'shop', capabilities: { console: 'bin/console' } };
const laravel = { root: '/p/blog', name: 'blog', capabilities: { console: 'artisan' } };
const plain = { root: '/p/site', name: 'site', capabilities: {} };
test('offer: once for a new Symfony project', () => {
const store = memory();
markCreated(store, '/p/shop', 'symfony');
assert.equal(shouldOffer(store, symfony), true);
assert.equal(shouldOffer(store, symfony), false); // the mark is consumed
markCreated(store, '/p/shop', 'symfony');
assert.equal(shouldOffer(store, symfony), false); // and the project was offered once
});
test('offer: never after "don\'t offer again"; it can be undone', () => {
const store = memory();
setNeverOffer(store, true);
markCreated(store, '/p/shop', 'symfony');
assert.equal(shouldOffer(store, symfony), false);
setNeverOffer(store, false);
markCreated(store, '/p/shop2', 'symfony');
assert.equal(shouldOffer(store, { ...symfony, root: '/p/shop2' }), true);
});
test('offer: not for other kinds of site, nor for a project that was not just made', () => {
const store = memory();
markCreated(store, '/p/blog', 'laravel');
assert.equal(store.get(PENDING_KEY, null), null);
assert.equal(shouldOffer(store, laravel), false);
markCreated(store, '/p/site', 'symfony'); // made as Symfony but the opened project is not
assert.equal(shouldOffer(store, plain), false);
assert.equal(shouldOffer(store, symfony), false); // an old Symfony project opened later: no mark, no offer
});
// the Symfony tutorial's data -----------------------------------------------------------------------------------
function walk(dir) {
return readdirSync(dir).flatMap((n) => { const p = join(dir, n); return statSync(p).isDirectory() ? walk(p) : [p]; });
}
const sources = walk(ui).filter((f) => /\.(js|html)$/.test(f) && !f.endsWith('.test.mjs') && !f.includes('/lib/') && !f.includes('/tutorial/'));
const all = sources.map((f) => readFileSync(f, 'utf8')).join('\n');
const indexHtml = readFileSync(join(ui, 'index.html'), 'utf8');
const toolIds = new Set([...all.matchAll(/\bT\('([A-Za-z]+)'/g)].map((m) => m[1]));
const actionIds = new Set([...all.matchAll(/\ba\.add\('([A-Za-z]+)'/g)].map((m) => m[1]));
const steps = symfonyTutorial.chapters.flatMap((c) => c.steps);
test('symfony tutorial: ids unique, every text in English and French', () => {
assert.equal(new Set(steps.map((s) => s.id)).size, steps.length);
for (const s of steps) for (const k of ['title', 'text']) assert.ok(s[k].en && s[k].fr, `${s.id}.${k}`);
for (const c of symfonyTutorial.chapters) assert.ok(c.title.en && c.title.fr, c.id);
});
// the names a data-tour attribute can have in the UI: literals, prefixes of computed names ('console-cmd-' + name), dialog buttons (tour: '...'),
// the hub's entries ('new-' + the label's slug), the tool windows' stripe buttons
const staticNames = new Set([...indexHtml.matchAll(/data-tour="([a-z0-9-]+)"/g)].map((m) => m[1]));
const prefixes = new Set();
for (const m of all.matchAll(/(?:'data-tour'\s*:|\btour\s*:|setAttribute\('data-tour',)\s*'([A-Za-z0-9:_-]+)'(\s*\+)?/g)) { if (m[2]) prefixes.add(m[1]); else staticNames.add(m[1]); }
prefixes.delete('new-');
const hubSource = readFileSync(join(ui, 'js', 'new-hub.js'), 'utf8');
for (const m of hubSource.matchAll(/\[[^\]\n]*?'(?:Project|Symfony|Doctrine|Security|API and HTTP|Scripts and tests|Translations)', '([^']+)',/g)) staticNames.add('new-' + m[1].toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''));
const known = (name) => staticNames.has(name) || [...prefixes].some((p) => name.startsWith(p) && name.length > p.length)
|| (/^tool-(.+)$/.test(name) && toolIds.has(/^tool-(.+)$/.exec(name)[1]) && /tour: 'tool-' \+ tool\.id/.test(all));
const isStatic = (name) => indexHtml.includes(`data-tour="${name}"`) || /^tool-/.test(name);
const waitList = (w) => (!w ? [] : w.any ? w.any.flatMap(waitList) : [w]);
const commandsOf = (s) => [].concat(s.do ?? [], s.before ?? []);
test('symfony tutorial: every target is a data-tour attribute of the UI (the controls inside the tool windows too)', () => {
const missing = [];
for (const s of steps) for (const name of [...targetsOf(s), ...[].concat(s.ready ?? [])]) if (!known(name)) missing.push(`${s.id}: ${name}`);
assert.deepEqual(missing, []);
assert.ok(staticNames.has('doctrine-new-entity') && staticNames.has('http-refresh-api') && staticNames.has('migrations-diff'));
});
test('symfony tutorial: a control inside a window or a dialog has a precondition (before) or a way back', () => {
const bad = [];
for (const s of steps) {
const names = [...targetsOf(s), ...[].concat(s.ready ?? [])];
if (names.length && names.every((n) => !isStatic(n)) && !s.before && !s.back) bad.push(s.id);
}
assert.deepEqual(bad, []);
});
test('symfony tutorial: every command and wait refers to something that exists', () => {
const bad = [];
for (const s of steps) {
for (const c of commandsOf(s)) {
if (c.action && !actionIds.has(c.action)) bad.push(`${s.id}: action ${c.action}`);
if (c.tool && !toolIds.has(c.tool)) bad.push(`${s.id}: tool ${c.tool}`);
if (c.click && !known(c.click)) bad.push(`${s.id}: click ${c.click}`);
if (c.fill && !known(c.fill.target)) bad.push(`${s.id}: fill ${c.fill.target}`);
}
for (const w of waitList(s.wait)) {
if (w.tool && !toolIds.has(w.tool)) bad.push(`${s.id}: wait tool ${w.tool}`);
if (w.action && !actionIds.has(w.action)) bad.push(`${s.id}: wait action ${w.action}`);
if (w.click && !known(w.click)) bad.push(`${s.id}: wait click ${w.click}`);
if (w.value && !known(w.value.target)) bad.push(`${s.id}: wait value ${w.value.target}`);
if (w.value) new RegExp(w.value.match);
if (w.check && !/^(route:[\w/.]+\.php|migration|schema-ok|http-2xx|visible:[\w:-]+|text:[^~]+~.+|contains:[\w/.]+~.+)$/.test(w.check)) bad.push(`${s.id}: wait check ${w.check}`);
const visible = /^visible:(.+)$/.exec(w.check || '');
if (visible && !known(visible[1])) bad.push(`${s.id}: wait visible ${visible[1]}`);
for (const k of ['saved', 'opened']) if (w[k]) new RegExp(w[k]);
}
if (s.back) assert.ok(s.back.en && s.back.fr, `${s.id}.back`);
}
assert.deepEqual(bad, []);
});
test('symfony tutorial: a step tells one precise thing (bold control, French twin) and the actions are verified', () => {
const bad = [];
for (const s of steps) {
if (/^tour-welcome$|^tour-tools$|^tour-reindex$/.test(s.id)) continue;
if (!/\*\*/.test(s.text.en) || !/\*\*/.test(s.text.fr)) bad.push(`${s.id}: no bold control`);
}
assert.deepEqual(bad, []);
// the actions that make something real are verified by their result, not by a click
const wait = (id) => waitList(steps.find((s) => s.id === id).wait);
assert.ok(wait('console-run').some((w) => w.exists === 'src/Controller/HomeController.php'));
assert.ok(wait('controller-routes').some((w) => /^route:/.test(w.check)));
assert.ok(wait('doctrine-apply').some((w) => w.exists === 'src/Entity/Product.php'));
assert.ok(wait('migrations-write').some((w) => w.check === 'migration'));
assert.ok(wait('migrations-migrate').some((w) => w.check === 'schema-ok'));
assert.ok(wait('api-send').some((w) => w.check === 'http-2xx'));
});
// ensure: the precondition, then the target is waited for ---------------------------------------------------------
test('ensure: plays before when the target is missing, waits for it, reveals it', async () => {
const host = fakeHost();
host.sleep = async () => {};
host.revealed = [];
host.reveal = (e) => host.revealed.push(e);
const btn = { id: 'ok' };
host.perform = async (c) => { host.performed.push(c); if (c.action === 'open') host.elements['[data-tour="field"]'] = btn; };
const d = { id: 'd', title: 'D', chapters: [{ id: 'c', title: 'C', steps: [{ id: 'a', title: 'A', text: 'a', target: 'field', before: { action: 'open' } }, { id: 'b', title: 'B', text: 'b', target: 'never', before: { action: 'noop' } }] }] };
const tour = new Tour(d, { host, store: memory() });
const r = await tour.ensure();
assert.equal(r.ok, true);
assert.deepEqual(host.performed, [{ action: 'open' }]);
assert.deepEqual(host.revealed, [btn]);
host.performed.length = 0;
await tour.ensure(); // already there: nothing played again
assert.deepEqual(host.performed, []);
tour.goto('b');
const lost = await tour.ensure(tour.current(), { timeout: 450 });
assert.equal(lost.ok, false);
assert.deepEqual(lost.missing, ['never']);
assert.equal(tour.onScreen(), false);
});
test('waits that verify the real result: check, value', async () => {
const host = fakeHost({ '[data-tour="name"]': {} });
host.checks = new Set();
host.check = async (n) => host.checks.has(n);
host.fieldValue = '';
host.value = () => host.fieldValue;
const d = { id: 'd', title: 'D', chapters: [{ id: 'c', title: 'C', steps: [
{ id: 'v', title: 'V', text: 'v', wait: { value: { target: 'name', match: '^Product$' } } },
{ id: 'k', title: 'K', text: 'k', wait: { check: 'migration' } },
] }] };
const tour = new Tour(d, { host, store: memory() });
tour.start();
const poll = host.timers.find((t) => t.every);
assert.equal(poll.ms, 500);
host.fieldValue = 'Prod';
poll.fn(); await new Promise((r) => setTimeout(r, 0));
assert.equal(tour.satisfied, false);
host.fieldValue = 'Product';
poll.fn(); await new Promise((r) => setTimeout(r, 0));
assert.equal(tour.satisfied, true);
tour.goto('k');
host.timers.find((t) => t.every).fn(); await new Promise((r) => setTimeout(r, 0));
assert.equal(tour.satisfied, false); // the file is not there: not done
host.checks.add('migration');
host.timers.find((t) => t.every).fn(); await new Promise((r) => setTimeout(r, 0));
assert.equal(tour.satisfied, true);
});