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

250 lines
12 KiB
JavaScript

// The tour's face: a floating, draggable, collapsible panel (contents, the step's text, Previous / Next / Do it for me / Show me) and
// the GHOST MOUSE: an extra animated pointer drawn over the IDE (an overlay element, never the real cursor) that flies to the target of
// a step, lights it (spotlight + pulse) and shows click ripples. Targets are found by [data-tour] attributes, never by coordinates.
import { el, icon, t, prefs } from '../ui.js';
import { renderMarkdown } from '../markdown.js';
document.head.append(el('link', { rel: 'stylesheet', href: new URL('../../css/tutorial.css', import.meta.url).href }));
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const CURSOR = '<svg viewBox="0 0 24 24" width="26" height="26"><path d="M4 2l15 9-6.5 1.6L9.6 19z" fill="#fff" stroke="#111" stroke-width="1.5" stroke-linejoin="round"/></svg>';
export class TourUi {
constructor(tour, { onExit, lang } = {}) {
this.tour = tour;
this.onExit = onExit;
this.showToc = prefs.get('tutorial:toc', true);
this.collapsed = prefs.get('tutorial:collapsed', false);
this.runId = 0;
this.build();
this.unsubscribe = [tour.on('change', () => this.render()), tour.on('finish', () => this.render())];
this.onKey = (e) => {
if (!e.altKey || !e.shiftKey) return;
if (e.key === 'ArrowRight') { e.preventDefault(); this.tour.next(); }
if (e.key === 'ArrowLeft') { e.preventDefault(); this.tour.prev(); }
};
document.addEventListener('keydown', this.onKey, true);
this.render();
this.watchLost();
}
build() {
this.title = el('b.tour-title');
this.progress = el('span.tour-progress');
this.toggle = el('button.tour-icon', { onclick: () => this.setCollapsed(!this.collapsed) });
this.closeButton = el('button.tour-icon', { title: t('Quit the tutorial'), onclick: () => this.onExit?.() }, icon('close'));
this.head = el('div.tour-head', {}, icon('book'), this.title, this.progress, this.toggle, this.closeButton);
this.tocBox = el('nav.tour-toc');
this.textBox = el('div.tour-text');
this.noteBox = el('div.tour-note');
this.lost = el('div.tour-lost', { hidden: true });
this.tocButton = el('button.tour-link', { onclick: () => { this.showToc = !this.showToc; prefs.set('tutorial:toc', this.showToc); this.render(); } });
this.restartButton = el('button.tour-link', { onclick: () => this.tour.restart() }, t('Restart the tutorial'));
this.prevButton = el('button.btn', { onclick: () => this.tour.prev() });
this.nextButton = el('button.btn.primary', { onclick: () => this.tour.next() });
this.doButton = el('button.btn', { onclick: () => this.doIt() }, t('Do it for me'));
this.showButton = el('button.btn', { onclick: () => this.show() }, t('Show me'));
this.body = el('div.tour-body', {}, this.tocBox, this.textBox, this.noteBox, this.lost,
el('div.tour-actions', {}, this.doButton, this.showButton),
el('div.tour-nav', {}, this.prevButton, this.nextButton),
el('div.tour-foot', {}, this.tocButton, this.restartButton, el('span.tour-keys', {}, 'Alt+Shift+← / →')));
this.box = el('div.tour-panel', { dataset: { tourPanel: '1' }, tabindex: -1 }, this.head, this.body);
this.spot = el('div.tour-spot');
this.ghost = el('div.tour-ghost');
this.ghost.innerHTML = CURSOR;
this.layer = el('div.tour-layer', {}, this.spot, this.ghost);
document.body.append(this.layer, this.box);
this.place(prefs.get('tutorial:pos', null));
this.drag();
this.box.addEventListener('keydown', (e) => {
if (e.target.closest('button, a, input')) return;
if (e.key === 'ArrowRight') this.tour.next();
if (e.key === 'ArrowLeft') this.tour.prev();
});
}
place(pos) {
const w = this.box.offsetWidth || 380;
const x = pos ? Math.min(Math.max(0, pos.x), innerWidth - 60) : Math.max(8, innerWidth - w - 64);
const y = pos ? Math.min(Math.max(0, pos.y), innerHeight - 40) : 52;
this.box.style.left = x + 'px';
this.box.style.top = y + 'px';
}
drag() {
this.head.addEventListener('mousedown', (e) => {
if (e.target.closest('button')) return;
const dx = e.clientX - this.box.offsetLeft;
const dy = e.clientY - this.box.offsetTop;
const move = (m) => { this.box.style.left = Math.max(0, Math.min(innerWidth - 80, m.clientX - dx)) + 'px'; this.box.style.top = Math.max(0, Math.min(innerHeight - 40, m.clientY - dy)) + 'px'; };
const up = () => { removeEventListener('mousemove', move); removeEventListener('mouseup', up); prefs.set('tutorial:pos', { x: this.box.offsetLeft, y: this.box.offsetTop }); };
addEventListener('mousemove', move);
addEventListener('mouseup', up);
e.preventDefault();
});
}
setCollapsed(v) {
this.collapsed = v;
prefs.set('tutorial:collapsed', v);
this.render();
}
render() {
const tour = this.tour;
const step = tour.current();
this.title.textContent = tour.text(tour.def.title);
this.progress.textContent = t('Step {n} of {total}', { n: tour.index + 1, total: tour.count() });
this.toggle.textContent = this.collapsed ? '▾' : '▴';
this.toggle.title = this.collapsed ? t('Expand') : t('Collapse');
this.box.classList.toggle('collapsed', this.collapsed);
this.tocBox.hidden = !this.showToc;
this.tocButton.textContent = this.showToc ? t('Hide the contents') : t('Contents');
this.renderToc();
const chapter = tour.currentChapter();
this.textBox.replaceChildren(el('div.tour-chapter', {}, tour.text(chapter.title)), el('h3', {}, tour.text(step.title)), ...renderMarkdown(tour.text(step.text)));
this.noteBox.replaceChildren();
this.lost.hidden = true;
if (step.tip) this.noteBox.append(el('div.tour-tip', {}, el('b', {}, t('Tip') + ' '), tour.text(step.tip)));
if (tour.satisfied) this.noteBox.append(el('div.tour-ok', {}, icon('check'), ' ', t('Done, well played!')));
else if (step.wait) this.noteBox.append(el('div.tour-wait', {}, t('Waiting for you: do it, or press Next.')));
if (tour.finished()) this.noteBox.append(el('div.tour-ok', {}, icon('star'), ' ', t('You finished the tutorial.')));
this.prevButton.textContent = t('Previous');
this.prevButton.disabled = tour.isFirst();
this.nextButton.textContent = tour.isLast() ? t('Finish') : t('Next');
this.doButton.hidden = !step.do;
this.showButton.hidden = !step.target && !step.ghost;
}
renderToc() {
const tour = this.tour;
const stepLink = (s) => el(`a.tour-step${s.current ? '.on' : ''}${s.done ? '.done' : ''}`, { href: '#', dataset: { step: s.id }, onclick: (e) => { e.preventDefault(); tour.goto(s.index); } },
el('span.tour-tick', {}, s.done ? '✓' : '·'), s.title);
const chapter = (c) => {
const node = el(`div.tour-chap${c.current ? '.on' : ''}${c.done ? '.done' : ''}`, {}, el('div.tour-chap-title', {}, c.done ? icon('check') : el('i.ico'), c.title));
if (c.current) node.append(el('div.tour-steps', {}, ...c.steps.map(stepLink)));
return node;
};
this.tocBox.replaceChildren(...tour.toc().map(chapter));
// a chapter other than the current one opens at a click on its title
this.tocBox.querySelectorAll('.tour-chap-title').forEach((node, i) => { node.onclick = () => this.tour.goto(this.tour.toc()[i].steps[0].index); });
this.tocBox.querySelector('.tour-step.on')?.scrollIntoView({ block: 'nearest' });
}
async doIt() {
this.clear();
try { await this.tour.doIt(); } catch (e) { this.noteBox.append(el('div.tour-wait', {}, String(e.message || e))); return; }
await wait(350);
this.show();
}
// the ghost ---------------------------------------------------------------------------------------------------
clear() {
this.runId++;
this.spot.classList.remove('on');
this.ghost.classList.remove('on');
}
/** The ghost's demonstration of the step: the window opens first (the step's `before`), the control is waited for and scrolled into view,
* then the ghost flies to it, lights it (spotlight) and clicks (a ripple; nothing is clicked for real). The element is looked up again at
* every frame while it moves, so a panel that slides or a list that redraws does not make it miss. */
async show() {
const id = ++this.runId;
const step = this.tour.current();
this.tour.emit('change');
this.lost.hidden = true;
const ready = await this.tour.ensure(step);
if (id !== this.runId) return;
if (!ready.ok) { this.say(t('I cannot find this control on screen: {name}. Open its window, then press "Show me" again.', { name: ready.missing.join(', ') })); return; }
await wait(250); // the window finished opening
const items = step.ghost || (step.target ? [{ target: ready.hit.name, click: !!(step.wait?.click || step.wait?.tool) }] : []);
this.ghost.classList.add('on');
for (const item of items) {
if (id !== this.runId) return;
let hit = this.tour.resolve(step, item.target);
for (let i = 0; !hit && i < 12; i++) { await wait(150); hit = this.tour.resolve(step, item.target); }
if (!hit) continue;
this.tour.host.reveal?.(hit.element);
await this.follow(hit, step, id, item);
}
await wait(1200);
if (id === this.runId) this.clear();
}
/** Moves the ghost and the spotlight onto the element and keeps them on it (looked up again each frame) while it points, then clicks. */
async follow(hit, step, id, item) {
const place = () => {
if (!hit.element.isConnected) { const again = this.tour.resolve(step, hit.name); if (again) hit = again; else return null; }
const r = hit.element.getBoundingClientRect();
if (!r.width && !r.height) return null;
this.light(r);
this.avoid(r);
const x = r.left + Math.min(r.width / 2, 60);
const y = r.top + Math.min(r.height / 2, 30);
this.ghost.style.transform = `translate(${x}px, ${y}px)`;
return { x, y };
};
let at = place();
if (!at) return;
const frames = (ms) => new Promise((resolve) => {
const t0 = performance.now();
const tick = () => { if (id !== this.runId || performance.now() - t0 >= ms) return resolve(); at = place() || at; requestAnimationFrame(tick); };
requestAnimationFrame(tick);
});
await frames(950);
if (id !== this.runId) return;
if (item.click) { this.ripple(at.x, at.y); await frames(600); } else await frames(900);
}
/** Keeps the panel off the control it points at: when they overlap, the panel goes to the other side of the screen (until the user drags it). */
avoid(r) {
const b = this.box.getBoundingClientRect();
if (r.right < b.left || r.left > b.right || r.bottom < b.top || r.top > b.bottom) return;
const left = r.left + r.width / 2 > innerWidth / 2;
this.box.style.left = (left ? 8 + 44 : Math.max(8, innerWidth - b.width - 64)) + 'px';
this.box.style.top = '52px';
}
/** A message of the guide in the panel (the control is missing, ...). */
say(text) {
this.lost.hidden = false;
this.lost.replaceChildren(text);
this.clear();
}
/** While a step is shown: when its control left the screen (a window closed, another one opened), tell how to come back. */
watchLost() {
const lost = () => {
const tour = this.tour;
const step = tour.current();
const gone = !!step && !tour.satisfied && !tour.onScreen(step) && tour.readyNames(step).length > 0;
if (gone === !this.lost.hidden) return;
this.lost.hidden = !gone;
this.lost.replaceChildren(...(gone ? [t('The control of this step is not on screen (you opened or closed something else?). Press "Show me": I open it again and point at it.'), ...(step.back ? [el('div', {}, tour.text(step.back))] : [])] : []));
};
this.lostTimer = setInterval(lost, 800);
}
light(r) {
const pad = 4;
Object.assign(this.spot.style, { left: r.left - pad + 'px', top: r.top - pad + 'px', width: r.width + pad * 2 + 'px', height: r.height + pad * 2 + 'px' });
this.spot.classList.add('on');
}
ripple(x, y) {
const ring = el('div.tour-ripple');
ring.style.left = x + 'px';
ring.style.top = y + 'px';
this.layer.append(ring);
setTimeout(() => ring.remove(), 900);
}
destroy() {
this.clear();
for (const off of this.unsubscribe) off();
document.removeEventListener('keydown', this.onKey, true);
clearInterval(this.lostTimer);
this.layer.remove();
this.box.remove();
}
}