202 lines
12 KiB
JavaScript
202 lines
12 KiB
JavaScript
// The interactive tutorials inside the IDE: starts one (creating or choosing its test project), connects the tour engine (tour.js) to the
|
|
// IDE (events, "Do it for me" commands), shows the panel and the ghost mouse (tour-ui.js), resumes where the user left per project.
|
|
// Offers the Symfony tutorial once after a new Symfony project is made (offer.js).
|
|
import { backend } from '../backend.js';
|
|
import { el, dialog, notify, progressBar, prefs, t, uiLang } from '../ui.js';
|
|
import { Tour } from './tour.js';
|
|
import { TourUi } from './tour-ui.js';
|
|
import { symfonyTutorial } from './symfony-steps.js';
|
|
import { isSymfony, markCreated, shouldOffer, setNeverOffer, neverOffer } from './offer.js';
|
|
|
|
export const TUTORIALS = { symfony: symfonyTutorial };
|
|
const TEST_PROJECT = 'symfony-tutorial';
|
|
const ACTIVE_KEY = 'tutorial:active';
|
|
|
|
const store = { get: (k, fb) => prefs.get(k, fb), set: (k, v) => prefs.set(k, v) };
|
|
const visible = (node) => { const r = node.getBoundingClientRect(); return r.width > 0 && r.height > 0; };
|
|
|
|
export class TutorialManager {
|
|
constructor(app) {
|
|
this.app = app;
|
|
this.tour = null;
|
|
this.ui = null;
|
|
this.listeners = new Set();
|
|
this.attached = false;
|
|
}
|
|
|
|
/** Settings: "Don't offer the Symfony tutorial after a new project". */
|
|
static neverOffer() { return neverOffer(store); }
|
|
static setNeverOffer(v) { setNeverOffer(store, v); }
|
|
|
|
// the IDE seen by the tour ------------------------------------------------------------------------------------
|
|
emit(event) { for (const fn of [...this.listeners]) fn(event); }
|
|
|
|
/** Wraps the IDE's own entry points once, so the tour hears what the user does. */
|
|
attach() {
|
|
if (this.attached) return;
|
|
this.attached = true;
|
|
const app = this.app;
|
|
const showTool = app.showTool.bind(app);
|
|
app.showTool = (id, quiet) => { const r = showTool(id, quiet); this.emit({ type: 'tool', id }); return r; };
|
|
const run = app.actions.run.bind(app.actions);
|
|
app.actions.run = (id) => { const r = run(id); this.emit({ type: 'action', id }); return r; };
|
|
app.editors?.on('saved', (path) => this.emit({ type: 'saved', path }));
|
|
app.editors?.on('active', (tab) => { if (tab?.path) this.emit({ type: 'opened', path: tab.path }); });
|
|
document.addEventListener('click', (e) => this.emit({ type: 'click', target: e.target }), true);
|
|
}
|
|
|
|
host() {
|
|
return {
|
|
query: (selector) => [...document.querySelectorAll(selector)].find(visible) || null,
|
|
on: (fn) => { this.listeners.add(fn); return () => this.listeners.delete(fn); },
|
|
every: (ms, fn) => { const id = setInterval(fn, ms); return () => clearInterval(id); },
|
|
later: (ms, fn) => { const id = setTimeout(fn, ms); return () => clearTimeout(id); },
|
|
exists: (path) => backend.invoke('file.read', { path }).then(() => true, () => false),
|
|
contains: (element, target) => !!target && element.contains(target),
|
|
perform: (command) => this.perform(command),
|
|
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
reveal: (element) => element.scrollIntoView?.({ block: 'center', inline: 'nearest' }),
|
|
value: (selector) => { const n = document.querySelector(selector); return n ? (n.value ?? n.textContent) : ''; },
|
|
check: (name, step) => this.check(name, step),
|
|
};
|
|
}
|
|
|
|
/** The REAL result of a step, asked to the IDE: `route:<controller file>` (a route is declared in it), `migration` (a migration file exists),
|
|
* `schema-ok` (the last database check says the schema matches), `http-2xx` (the HTTP Client got a 2xx answer), `text:<selector>~<regex>`, `contains:<file>~<regex>` (a file holds this text). */
|
|
async check(name) {
|
|
const [kind, ...rest] = String(name).split(':');
|
|
const arg = rest.join(':');
|
|
try {
|
|
if (kind === 'route') { const r = await backend.invoke('controller.routes', { path: arg }); return !!r?.routes?.length; }
|
|
if (kind === 'migration') { const { files } = await backend.invoke('files.list', {}); return files.some((f) => /(^|\/)migrations\/Version[^/]*\.php$/.test(f.path)); }
|
|
if (kind === 'schema-ok') return this.app.schemaCheck?.result?.state === 'ok';
|
|
if (kind === 'http-2xx') return /^2\d\d/.test(document.querySelector('.hc-response .hc-status.ok')?.textContent || '');
|
|
if (kind === 'visible') return visible(document.querySelector(`[data-tour="${arg}"]`) || document.body) && !!document.querySelector(`[data-tour="${arg}"]`);
|
|
if (kind === 'contains') { const [path, re] = arg.split('~'); const f = await backend.invoke('file.read', { path }); return new RegExp(re).test(String(f?.content ?? f?.text ?? '')); }
|
|
if (kind === 'text') { const [sel, re] = arg.split('~'); return new RegExp(re).test(document.querySelector(sel)?.textContent || ''); }
|
|
} catch { return false; }
|
|
return false;
|
|
}
|
|
|
|
/** "Do it for me": a command of a step, through the IDE's own commands. */
|
|
async perform(command) {
|
|
const app = this.app;
|
|
// a control still loading (the Console lists its commands in Docker first): waited for, up to 15 s
|
|
const found = async (name) => { for (let i = 0; i < 100; i++) { const n = [...document.querySelectorAll(`[data-tour="${name}"]`)].find(visible); if (n) return n; await new Promise((r) => setTimeout(r, 150)); } return null; };
|
|
if (command.unless && [...document.querySelectorAll(`[data-tour="${command.unless}"]`)].some(visible)) return; // already open / done
|
|
if (command.click) { (await found(command.click))?.click(); await new Promise((r) => setTimeout(r, 700)); } // what the click opens needs a moment to draw
|
|
else if (command.dblclick) (await found(command.dblclick))?.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, cancelable: true }));
|
|
else if (command.fill) {
|
|
const node = await found(command.fill.target);
|
|
if (node) { node.focus?.(); node.value = command.fill.value; node.dispatchEvent(new Event('input', { bubbles: true })); node.dispatchEvent(new Event('change', { bubbles: true })); }
|
|
}
|
|
else if (command.tool) app.showTool(command.tool, true);
|
|
else if (command.action) app.actions.run(command.action);
|
|
else if (command.open) await app.editors.open(command.open);
|
|
else if (command.edit) {
|
|
// "Do it for me" for a step that waits for a save: the text changed in the real editor, then saved (Ctrl+S)
|
|
await app.editors.open(command.edit.path);
|
|
const file = app.editors.files.get(command.edit.path);
|
|
const text = file?.model?.getValue() ?? '';
|
|
if (file?.model && text.includes(command.edit.find)) { file.model.setValue(text.replace(command.edit.find, command.edit.replace)); await app.editors.save(command.edit.path); }
|
|
else if (file?.model) { file.model.setValue(text + command.edit.replace); await app.editors.save(command.edit.path); }
|
|
}
|
|
else if (command.write) { await backend.invoke('file.write', { path: command.write.path, content: command.write.content }); await app.tree?.refresh(); await app.tests?.discover?.(); }
|
|
else if (command.console) {
|
|
const r = await backend.invoke('console.run', { line: command.console });
|
|
if (r && r.code && r.code !== 0) notify(String(r.output || r.error || ''), 'error', { title: t('Symfony tutorial') });
|
|
await app.tree?.refresh();
|
|
} else if (command.docs) await app.docs.open(command.docs);
|
|
}
|
|
|
|
// starting, resuming ------------------------------------------------------------------------------------------
|
|
/** Opens the panel for a tutorial on the open project. */
|
|
open(id = 'symfony') {
|
|
const def = TUTORIALS[id];
|
|
if (!def || !this.app.project) return;
|
|
this.close(false);
|
|
this.attach();
|
|
const key = `${id}:${this.app.projectKey}`;
|
|
this.tour = new Tour(def, { host: this.host(), store, key, lang: uiLang() === 'fr' ? 'fr' : 'en' });
|
|
this.ui = new TourUi(this.tour, { onExit: () => this.close(true) });
|
|
this.tour.on('finish', () => notify(t('You finished the tutorial.'), 'success', { title: t('Symfony tutorial') }));
|
|
prefs.set(ACTIVE_KEY, { id, root: this.app.projectKey });
|
|
this.tour.start();
|
|
}
|
|
|
|
close(forget) {
|
|
if (this.tour) this.tour.exit();
|
|
this.ui?.destroy();
|
|
this.ui = null;
|
|
this.tour = null;
|
|
if (forget) prefs.set(ACTIVE_KEY, null);
|
|
}
|
|
|
|
/** A project was opened: resume the tutorial that was running on it, or offer the Symfony one after a new Symfony project. */
|
|
projectOpened(info) {
|
|
const active = prefs.get(ACTIVE_KEY, null);
|
|
if (active && TUTORIALS[active.id] && active.root === (info.root || info.name)) { setTimeout(() => this.open(active.id), 600); return; }
|
|
if (shouldOffer(store, info)) setTimeout(() => this.offer(), 900);
|
|
}
|
|
|
|
/** Right after a new Symfony project: start it, later, or never again. */
|
|
offer() {
|
|
const never = el('input', { type: 'checkbox' });
|
|
dialog({
|
|
title: t('Symfony tutorial'),
|
|
body: el('div', {}, el('p', {}, t('Your Symfony project is ready. Learn the IDE on it with an interactive tutorial: a guide panel and a ghost mouse show you where things are.')),
|
|
el('label', { style: { display: 'flex', gap: '6px', alignItems: 'center' } }, never, t('Don\'t offer it again'))),
|
|
buttons: [
|
|
{ label: t('Later'), action: () => { if (never.checked) setNeverOffer(store, true); } },
|
|
{ label: t('Start the Symfony tutorial'), primary: true, action: () => { if (never.checked) setNeverOffer(store, true); this.open('symfony'); } },
|
|
],
|
|
});
|
|
}
|
|
|
|
/** The user's entry (Help menu, Welcome, Search Everywhere, Doc): the test project, then the tour. */
|
|
async start(id = 'symfony') {
|
|
if (this.tour && this.ui) { this.ui.box.classList.remove('collapsed'); this.ui.setCollapsed(false); return; }
|
|
if (this.app.project && isSymfony(this.app.project) && this.app.projectKey.replace(/\\/g, '/').endsWith('/' + TEST_PROJECT)) { this.open(id); return; }
|
|
const choice = await this.choose();
|
|
if (choice === 'here') { this.open(id); return; }
|
|
if (choice === 'create') await this.createProject(id);
|
|
}
|
|
|
|
/** Create the test project, or use the open Symfony project. */
|
|
choose() {
|
|
return new Promise((resolve) => {
|
|
let done = false;
|
|
const pick = (v) => () => { done = true; resolve(v); };
|
|
const buttons = [{ label: t('Cancel'), action: pick(null) }];
|
|
if (this.app.project && isSymfony(this.app.project)) buttons.push({ label: t('Use this project'), action: pick('here') });
|
|
buttons.push({ label: t('Create the test project'), primary: true, action: pick('create') });
|
|
dialog({ title: t('Symfony tutorial'), body: el('p', {}, t('The tutorial works on a Symfony test project: create a fresh one (a few minutes, in Docker) or use the project that is open.')), buttons, onClose: () => { if (!done) resolve(null); } });
|
|
});
|
|
}
|
|
|
|
/** A fresh Symfony site (the New Project > Web site path), or the one made earlier; then it opens and the tour resumes there. */
|
|
async createProject(id) {
|
|
const state = await backend.invoke('session.state');
|
|
const path = `${String(state.projectsDir || '').replace(/[\\/]$/, '')}/${TEST_PROJECT}`;
|
|
const progress = el('div', {}, el('span.spinner'), ' ', t('Making the Symfony test project (a few minutes the first time)…'), progressBar(null));
|
|
const waiting = dialog({ title: t('Symfony tutorial'), body: progress, buttons: [], sticky: true });
|
|
try {
|
|
let info;
|
|
const known = (state.recent || []).find((r) => String(r.path).replace(/\\/g, '/').endsWith('/' + TEST_PROJECT));
|
|
if (known) info = await backend.invoke('projects.open', { path: known.path });
|
|
else {
|
|
try { info = await backend.invoke('web.create', { type: 'symfony', name: TEST_PROJECT, folder: state.projectsDir, db: 'mariadb' }); }
|
|
catch (e) { if (!/already exists/i.test(e.message)) throw e; info = await backend.invoke('projects.open', { path }); }
|
|
}
|
|
prefs.set(ACTIVE_KEY, { id, root: info.root || info.name });
|
|
waiting.close();
|
|
await this.app.projectOpened(info);
|
|
} catch (e) {
|
|
waiting.close();
|
|
notify(e.message, 'error', { title: t('Symfony tutorial') });
|
|
}
|
|
}
|
|
|
|
/** New Project made a site: remember it so that opening it offers the tutorial (a Symfony one only). */
|
|
static created(root, type) { markCreated(store, root, type); }
|
|
}
|