rob-revisited/ide/ui/js/docs-browser.js

153 lines
7.5 KiB
JavaScript

// The Doc browser: the IDE's own documentation (docs/ide/, packaged with the IDE as ui/docs, read through the docs.* commands) in a
// window of the IDE. Left: the table of contents (docs/ide/toc.json), right: the page (markdown.js: pictures, code, tables, links between
// pages and to their headings), a full-text search over every page, back / forward, the IDE's language when the page is translated.
// Opened by the Doc button of the tool bar, Help > Documentation, Search Everywhere ("Documentation") and the "?" of tool windows.
import { backend } from './backend.js';
import { el, icon, dialog, t, uiLang } from './ui.js';
import { renderMarkdown } from './markdown.js';
import { buildToc, pagesIn, resolveLink, resolveImage, search, slug, History, TOOL_PAGES, WEB } from './docs-model.js';
document.head.append(el('link', { rel: 'stylesheet', href: new URL('../css/docs.css', import.meta.url).href }));
export class DocsBrowser {
constructor(app) {
this.app = app;
this.data = null;
this.images = new Map();
this.history = new History();
this.view = null;
}
/** The pages, read once (the folder ships with the IDE: it does not change while it runs). */
async load() {
if (!this.data) {
try { this.data = await backend.invoke('docs.index'); } catch { this.data = null; }
if (!this.data) return { toc: {}, pages: [], web: WEB };
}
return this.data;
}
/** The page of a tool window, or null when it has none. */
pageOfTool(id) {
return TOOL_PAGES[id] || null;
}
/** A "?" button for a tool window's header (null when the tool has no page). */
helpButton(toolId) {
const page = this.pageOfTool(toolId);
return page ? el('button.docs-help', { title: t('Help for this window'), onclick: () => this.open(page) }, '?') : null;
}
/** Opens the browser (or brings it to that page when it is open). */
async open(page = 'index', anchor = '') {
const data = await this.load();
this.lang = uiLang();
if (!this.view || !document.body.contains(this.view.box)) this.build(data);
this.go(page, anchor);
}
build(data) {
const search = el('input.input.docs-search', { type: 'search', placeholder: t('Search the documentation…'), spellcheck: false });
const back = el('button.docs-nav', { title: t('Back') + ' (Alt+←)', onclick: () => this.step(-1) }, '←');
const forward = el('button.docs-nav', { title: t('Forward') + ' (Alt+→)', onclick: () => this.step(1) }, '→');
const online = el('button.btn.small', { title: t('Open in the browser'), onclick: () => this.app.openUrl(this.onlineUrl()) }, icon('globe'), ' ', t('Open in the browser'));
const toc = el('nav.docs-toc');
const page = el('article.docs-page', { tabindex: -1 });
const body = el('div.docs', {}, el('div.docs-bar', {}, back, forward, search, el('span.docs-spacer'), online), el('div.docs-main', {}, toc, page));
const api = dialog({ title: t('Documentation'), body, wide: true, buttons: [{ label: 'Close' }], onClose: () => { this.view = null; } });
api.box.classList.add('docs-dialog');
let timer = 0;
search.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(() => this.showResults(search.value), 120); });
search.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && search.value) { e.stopPropagation(); search.value = ''; this.showResults(''); }
if (e.key === 'Enter') { e.preventDefault(); page.querySelector('.docs-result')?.click(); }
});
body.addEventListener('keydown', (e) => {
if (e.altKey && e.key === 'ArrowLeft') { e.preventDefault(); this.step(-1); }
if (e.altKey && e.key === 'ArrowRight') { e.preventDefault(); this.step(1); }
});
this.view = { box: api.box, close: api.close, toc, page, search, back, forward, data };
this.renderToc();
if (!data.pages.length) {
page.replaceChildren(el('p', {}, t('The documentation is not installed with this IDE: read it online.')),
el('button.btn.primary', { onclick: () => this.app.openUrl(WEB) }, t('Open in the browser')));
}
}
onlineUrl() {
const cur = this.history.current();
return WEB + (cur && cur.page !== 'index' ? cur.page : '') + (cur && cur.anchor ? '#' + cur.anchor : '');
}
renderToc() {
const v = this.view;
const cur = this.history.current();
v.toc.replaceChildren(...buildToc(v.data.toc || {}, v.data.pages, this.lang).map((g) => el('div.docs-group', {},
el('div.docs-group-title', {}, g.title),
...g.pages.map((p) => el(`a.docs-link${cur && cur.page === p.id ? '.on' : ''}`, { href: '#', dataset: { page: p.id }, onclick: (e) => { e.preventDefault(); v.search.value = ''; this.go(p.id); } },
p.title, p.soon ? el('span.docs-soon', {}, t('soon')) : null)))));
}
step(dir) {
const entry = dir < 0 ? this.history.back() : this.history.forward();
if (entry) this.show(entry.page, entry.anchor);
}
go(page, anchor = '') {
const pages = pagesIn(this.view.data.pages, this.lang);
if (!pages.has(page)) page = pages.has('index') ? 'index' : [...pages.keys()][0];
if (!page) return;
this.history.push({ page, anchor });
this.show(page, anchor);
}
show(id, anchor = '') {
const v = this.view;
if (!v) return;
const page = pagesIn(v.data.pages, this.lang).get(id);
if (!page) return;
v.back.disabled = !this.history.canBack();
v.forward.disabled = !this.history.canForward();
const onLink = (href) => {
if (/^tutorial:/.test(href)) { this.view?.close(); this.app.tutorial.start(href.slice(9)); return; }
const to = resolveLink(href, page);
if (to.url) this.app.openUrl(to.url);
else { v.search.value = ''; this.go(to.page, to.anchor); }
};
onLink.any = true;
const onImage = (src, alt) => {
const path = resolveImage(src, page);
const img = el('img.docs-img', { alt, title: alt });
if (path) this.image(path).then((url) => { if (url) img.src = url; });
return img;
};
const nodes = renderMarkdown(page.text, onLink, onImage);
const article = el('div.docs-article', {}, ...nodes);
for (const h of article.querySelectorAll('h2, h3, h4, h5')) h.id = 'doc-' + slug(h.textContent);
if (page.lang !== this.lang && this.lang !== 'en') article.prepend(el('p.docs-note', {}, t('This page is not translated yet: here it is in English.')));
v.page.replaceChildren(article);
this.renderToc();
v.toc.querySelector('.docs-link.on')?.scrollIntoView({ block: 'nearest' });
const target = anchor && article.querySelector('#doc-' + CSS.escape(anchor));
if (target) target.scrollIntoView({ block: 'start' }); else v.page.scrollTop = 0;
}
showResults(query) {
const v = this.view;
if (!query.trim()) { const cur = this.history.current(); if (cur) this.show(cur.page, cur.anchor); return; }
const results = search(v.data.pages, query, this.lang);
v.page.scrollTop = 0;
v.page.replaceChildren(el('div.docs-article', {},
el('h2', {}, t('{n} pages found', { n: results.length })),
...(results.length ? results.map((r) => el('a.docs-result', { href: '#', onclick: (e) => { e.preventDefault(); this.go(r.id, r.anchor); } },
el('b', {}, r.title), el('span.docs-snippet', {}, r.snippet))) : [el('p', {}, t('No page matches.'))])));
}
/** A picture of the documentation as a data: URL (read once). */
image(path) {
if (!this.images.has(path)) {
this.images.set(path, backend.invoke('docs.image', { path }).then((r) => (r ? `data:${r.mime};base64,${r.data}` : null)).catch(() => null));
}
return this.images.get(path);
}
}