269 lines
12 KiB
JavaScript
269 lines
12 KiB
JavaScript
// The tour engine: an interactive tutorial as DATA (a definition with chapters and steps, see symfony-steps.js) walked step by step.
|
|
// No DOM here and no IDE import: everything the tour needs from the outside goes through `host` (so node --test drives it with fakes):
|
|
// host.query(selector) -> an element (or anything truthy) or null: where the step points
|
|
// host.on(listener) -> off(): the IDE's events {type: 'tool'|'action'|'saved'|'opened'|'click', ...}
|
|
// host.every(ms, fn) -> stop(): a poll (waiting for a file to exist)
|
|
// host.later(ms, fn) -> cancel(): a delay (auto-advance)
|
|
// host.exists(path) -> Promise<boolean>
|
|
// host.perform(command) -> Promise: "Do it for me" ({tool}, {action}, {open}, {write}, {console}, {docs})
|
|
// host.contains(el, target) -> true when the click target is inside the element
|
|
// store: {get(key, fallback), set(key, value)}.
|
|
//
|
|
// host.check(name) -> Promise<boolean>: a check of the real result (route present, migration file, schema ok, request answered 2xx)
|
|
// host.value(selector) -> the value / text of the field (waiting for what the user types)
|
|
// host.sleep(ms) -> Promise; host.reveal(el) scrolls the element into view
|
|
// A step: {id, title: T, text: T, tip?: T, target?: 'name' | ['name', ...], wait?: W, do?: command | [command], ghost?: [{target, click}], auto?: false,
|
|
// before?: command | [command] the precondition: played when the target is not on screen (opens the window / dialog) before the step points at it,
|
|
// ready?: 'name' | [...] what must exist and be visible before the ghost moves (default: the ghost's first target, else the step's targets),
|
|
// back?: T what to do when the user went elsewhere (shown with "Show me again")}
|
|
// T is a string or {en, fr}; the language falls back to English. A target is a data-tour name: the engine builds [data-tour="name"].
|
|
// A wait W is {tool: id} | {action: id} | {saved: 'regex'} | {opened: 'regex'} | {click: 'name'} | {exists: 'path'} | {check: 'name'} |
|
|
// {value: {target: 'name', match: 'regex'}} (a field typed into) | {any: [W...]}. exists / check / value are polled: the REAL result is verified.
|
|
|
|
/** A text in a language: a string as is, an object by language then English. */
|
|
export function localize(value, lang = 'en') {
|
|
if (value == null) return '';
|
|
if (typeof value === 'string') return value;
|
|
return value[lang] ?? value.en ?? Object.values(value)[0] ?? '';
|
|
}
|
|
|
|
/** The CSS selector of a target name (`tool-console` -> [data-tour="tool-console"]). */
|
|
export function selectorOf(name) {
|
|
return `[data-tour="${String(name).replace(/"/g, '')}"]`;
|
|
}
|
|
|
|
/** Every target name of a step, in order (its target and the ghost's own targets). */
|
|
export function targetsOf(step) {
|
|
const list = [];
|
|
const add = (v) => { for (const n of [].concat(v ?? [])) if (typeof n === 'string' && n) list.push(n); };
|
|
add(step.target);
|
|
for (const g of step.ghost || []) add(g.target);
|
|
return list;
|
|
}
|
|
|
|
/** Every wait of a step flattened ({any: [...]} opened). */
|
|
export function waitsOf(wait) {
|
|
if (!wait) return [];
|
|
if (wait.any) return wait.any.flatMap(waitsOf);
|
|
return [wait];
|
|
}
|
|
|
|
/** Does this event satisfy this wait? */
|
|
export function matches(wait, event, host) {
|
|
if (!wait || !event) return false;
|
|
if (wait.any) return wait.any.some((w) => matches(w, event, host));
|
|
switch (event.type) {
|
|
case 'tool': return wait.tool !== undefined && wait.tool === event.id;
|
|
case 'action': return wait.action !== undefined && wait.action === event.id;
|
|
case 'saved': return wait.saved !== undefined && new RegExp(wait.saved).test(String(event.path || ''));
|
|
case 'opened': return wait.opened !== undefined && new RegExp(wait.opened).test(String(event.path || ''));
|
|
case 'click': {
|
|
if (wait.click === undefined) return false;
|
|
const el = host.query(selectorOf(wait.click));
|
|
return !!el && host.contains(el, event.target);
|
|
}
|
|
default: return false;
|
|
}
|
|
}
|
|
|
|
export class Tour {
|
|
constructor(def, { host, store, key = def.id, lang = 'en', advanceDelay = 900 } = {}) {
|
|
this.def = def;
|
|
this.host = host;
|
|
this.store = store;
|
|
this.key = key;
|
|
this.lang = lang;
|
|
this.advanceDelay = advanceDelay;
|
|
this.steps = [];
|
|
this.chapterOf = [];
|
|
def.chapters.forEach((c, ci) => c.steps.forEach((s) => { this.steps.push(s); this.chapterOf.push(ci); }));
|
|
this.index = 0;
|
|
this.done = new Set();
|
|
this.satisfied = false;
|
|
this.running = false;
|
|
this.listeners = new Map();
|
|
this.stops = [];
|
|
const saved = store?.get(this.storeKey(), null);
|
|
if (saved) {
|
|
this.index = Math.min(Math.max(0, saved.index | 0), this.steps.length - 1);
|
|
for (const id of saved.done || []) if (this.steps.some((s) => s.id === id)) this.done.add(id);
|
|
}
|
|
}
|
|
|
|
storeKey() { return `tutorial:${this.key}`; }
|
|
|
|
// events (change, satisfied, finish, exit) ------------------------------------------------------------------
|
|
on(name, fn) { (this.listeners.get(name) || this.listeners.set(name, new Set()).get(name)).add(fn); return () => this.listeners.get(name)?.delete(fn); }
|
|
emit(name, ...args) { for (const fn of [...(this.listeners.get(name) || [])]) fn(...args); }
|
|
|
|
text(value) { return localize(value, this.lang); }
|
|
setLang(lang) { this.lang = lang; this.emit('change'); }
|
|
|
|
// state ----------------------------------------------------------------------------------------------------
|
|
current() { return this.steps[this.index]; }
|
|
currentChapter() { return this.def.chapters[this.chapterOf[this.index]]; }
|
|
count() { return this.steps.length; }
|
|
isFirst() { return this.index === 0; }
|
|
isLast() { return this.index === this.steps.length - 1; }
|
|
finished() { return this.steps.every((s) => this.done.has(s.id)); }
|
|
|
|
/** The table of contents: chapters with their steps, done ticks, the current one. */
|
|
toc() {
|
|
return this.def.chapters.map((c, ci) => {
|
|
const steps = c.steps.map((s) => ({ id: s.id, index: this.steps.indexOf(s), title: this.text(s.title), done: this.done.has(s.id), current: this.steps[this.index] === s }));
|
|
return { id: c.id, title: this.text(c.title), steps, done: steps.every((s) => s.done), current: this.chapterOf[this.index] === ci };
|
|
});
|
|
}
|
|
|
|
save() {
|
|
this.store?.set(this.storeKey(), { index: this.index, done: [...this.done] });
|
|
}
|
|
|
|
// navigation -----------------------------------------------------------------------------------------------
|
|
start() {
|
|
this.running = true;
|
|
this.enter();
|
|
}
|
|
|
|
/** Enters the current step: its waiting starts. */
|
|
enter() {
|
|
this.clearWaiting();
|
|
this.satisfied = false;
|
|
this.save();
|
|
const step = this.current();
|
|
if (this.running && step?.wait) this.listen(step);
|
|
this.emit('change');
|
|
if (this.running && step) this.ensure(step).catch(() => null);
|
|
}
|
|
|
|
clearWaiting() {
|
|
for (const stop of this.stops.splice(0)) stop();
|
|
}
|
|
|
|
listen(step) {
|
|
this.stops.push(this.host.on((event) => { if (matches(step.wait, event, this.host)) this.satisfy(step); }));
|
|
for (const w of waitsOf(step.wait)) {
|
|
let probe = null;
|
|
let every = 1500;
|
|
if (w.exists !== undefined) probe = () => this.host.exists(w.exists);
|
|
else if (w.check !== undefined) probe = () => this.host.check(w.check, step);
|
|
else if (w.value !== undefined) { every = 500; probe = () => Promise.resolve(new RegExp(w.value.match).test(String(this.host.value(selectorOf(w.value.target)) ?? ''))); }
|
|
if (!probe) continue;
|
|
let busy = false;
|
|
const check = () => { if (busy) return; busy = true; Promise.resolve(probe()).then((yes) => { if (yes) this.satisfy(step); }).catch(() => null).finally(() => { busy = false; }); };
|
|
check();
|
|
this.stops.push(this.host.every(every, check));
|
|
}
|
|
}
|
|
|
|
/** The user did what the step waits for: ticked, then on to the next one after a short delay (step.auto === false: they press Next). */
|
|
satisfy(step) {
|
|
if (this.current() !== step || this.satisfied) return;
|
|
this.satisfied = true;
|
|
this.done.add(step.id);
|
|
this.clearWaiting();
|
|
this.save();
|
|
this.emit('satisfied', step);
|
|
this.emit('change');
|
|
if (step.auto !== false && !this.isLast()) {
|
|
this.stops.push(this.host.later(this.advanceDelay, () => { if (this.current() === step) this.next(); }));
|
|
}
|
|
}
|
|
|
|
next() {
|
|
this.done.add(this.current().id);
|
|
if (this.isLast()) { this.save(); this.clearWaiting(); this.emit('change'); this.emit('finish'); return false; }
|
|
this.index++;
|
|
this.enter();
|
|
return true;
|
|
}
|
|
|
|
prev() {
|
|
if (this.isFirst()) return false;
|
|
this.index--;
|
|
this.enter();
|
|
return true;
|
|
}
|
|
|
|
/** To a step by its index or its id. */
|
|
goto(to) {
|
|
const i = typeof to === 'number' ? to : this.steps.findIndex((s) => s.id === to);
|
|
if (i < 0 || i >= this.steps.length) return false;
|
|
this.index = i;
|
|
this.enter();
|
|
return true;
|
|
}
|
|
|
|
/** Forgets the progress and starts again at the first step. */
|
|
restart() {
|
|
this.done.clear();
|
|
this.index = 0;
|
|
this.enter();
|
|
}
|
|
|
|
/** Leaves the tour (the progress stays: a later start resumes). */
|
|
exit() {
|
|
this.clearWaiting();
|
|
this.running = false;
|
|
this.save();
|
|
this.emit('exit');
|
|
}
|
|
|
|
// what the step points at ----------------------------------------------------------------------------------
|
|
/** The first present element among the targets (the step's, or `names`): {name, selector, element}, or null. */
|
|
resolve(step = this.current(), names = null) {
|
|
for (const name of [].concat(names ?? step?.target ?? [])) {
|
|
const selector = selectorOf(name);
|
|
const element = this.host.query(selector);
|
|
if (element) return { name, selector, element };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** The names that must be on screen before the ghost points: `ready`, else the first target of the ghost's route, else the step's targets. */
|
|
readyNames(step = this.current()) {
|
|
if (step.ready) return [].concat(step.ready);
|
|
if (step.ghost?.length) return [].concat(step.ghost[0].target);
|
|
return [].concat(step.target ?? []);
|
|
}
|
|
|
|
/** The precondition: when the target is not on screen, plays `before` (opens the tool window / dialog), then waits (up to `timeout` ms) until the
|
|
* target exists and is visible, and scrolls it into view. {ok: true, hit} or {ok: false, missing: [names]}. */
|
|
async ensure(step = this.current(), { timeout = 15000 } = {}) {
|
|
const names = this.readyNames(step);
|
|
if (!names.length) return { ok: true, hit: null };
|
|
let hit = this.resolve(step, names);
|
|
if (!hit && step.before) {
|
|
for (const command of [].concat(step.before)) { await this.host.perform(command); if (this.current() !== step) return { ok: false, missing: [] }; }
|
|
}
|
|
const sleep = this.host.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
for (let waited = 0; !hit && waited < timeout; waited += 150) { await sleep(150); if (this.current() !== step) return { ok: false, missing: [] }; hit = this.resolve(step, names); }
|
|
if (!hit) return { ok: false, missing: names };
|
|
this.host.reveal?.(hit.element);
|
|
return { ok: true, hit };
|
|
}
|
|
|
|
/** Is the step's target on screen now? (the panel says how to come back when it is not) */
|
|
onScreen(step = this.current()) {
|
|
const names = this.readyNames(step);
|
|
return !names.length || !!this.resolve(step, names);
|
|
}
|
|
|
|
/** The ghost's route for a step: [{name, selector, element, click}], the items whose target exists. */
|
|
route(step = this.current()) {
|
|
const items = step.ghost || (step.target ? [{ target: step.target, click: !!(step.wait?.click || step.wait?.tool) }] : []);
|
|
const out = [];
|
|
for (const item of items) {
|
|
const hit = this.resolve(step, item.target);
|
|
if (hit) out.push({ ...hit, click: !!item.click });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** "Do it for me": the step's commands, one after the other through the host. */
|
|
async doIt(step = this.current()) {
|
|
const commands = [].concat(step.do ?? []);
|
|
for (const command of commands) await this.host.perform(command);
|
|
return commands.length;
|
|
}
|
|
}
|