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

181 lines
8 KiB
JavaScript

// The Doc browser's pure parts (no DOM; node --test ide/ui/js/docs-model.test.mjs): the pages of docs/ide/ in a language, the table of
// contents, the links between pages and to their anchors, the pictures, and the full-text search.
/** Where the same pages are online (jumphp.net publishes the repository's docs/). */
export const WEB = 'https://jumphp.net/docs/ide/';
export const WEB_DOCS = 'https://jumphp.net/docs/';
/** The page of each tool window (the "?" of its header). */
export const TOOL_PAGES = {
project: 'interface', commit: 'git', git: 'git', structure: 'php', hierarchy: 'php', calls: 'php', recent: 'navigation', find: 'search',
problems: 'php', run: 'run', debug: 'debugger', profile: 'profiler', cryo: 'cryo', composer: 'composer', scripts: 'scripts', tests: 'tests',
docker: 'docker', ssh: 'ssh', database: 'database', dbresults: 'database', cpc: 'amstrad-cpc', community: 'sharing', board: 'board',
terminal: 'terminal', console: 'symfony-console', sfEvents: 'symfony-events', messenger: 'messenger', logs: 'help-and-updates',
game: 'games', claude: 'claude', publish: 'publish', doctrine: 'doctrine', symfonyForms: 'symfony-forms', httpClient: 'http-client',
};
/** Lower case, without accents: what the search compares. */
export function fold(text) {
return String(text).toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
}
/** The anchor of a heading, as GitHub makes it (`## The PHP version` -> `the-php-version`). */
export function slug(text) {
return fold(String(text).replace(/[`*_]/g, '')).trim().replace(/[^\p{L}\p{N}\s-]/gu, '').replace(/\s/g, '-');
}
/** A page "coming soon": its text starts its first quote with **Coming soon**. */
export function isSoon(text) {
return /^>\s*\*\*(Coming soon|Bientôt)/m.test(String(text));
}
/** The pages to show in a language: each id in that language when it exists, else in English. @returns {Map<string, object>} */
export function pagesIn(pages, lang) {
const out = new Map();
for (const p of pages) if (p.lang === 'en') out.set(p.id, p);
for (const p of pages) if (p.lang === lang && lang !== 'en') out.set(p.id, p);
return out;
}
/**
* The table of contents in a language: [{id, title, pages: [{id, title, soon, translated}]}], the groups of toc.json in their order,
* then the pages no group names (in "More").
*/
export function buildToc(toc, pages, lang) {
const shown = pagesIn(pages, lang);
const named = new Set();
const entry = (id) => {
const p = shown.get(id);
named.add(id);
return p ? { id, title: p.title, soon: isSoon(p.text), translated: p.lang === lang } : null;
};
const groups = (toc.groups || []).map((g) => ({
id: g.id, title: (g.title && (g.title[lang] || g.title.en)) || g.id, pages: (g.pages || []).map(entry).filter(Boolean),
})).filter((g) => g.pages.length);
const rest = [...shown.keys()].filter((id) => !named.has(id)).sort().map(entry).filter(Boolean);
if (rest.length) groups.push({ id: 'more', title: (toc.more && (toc.more[lang] || toc.more.en)) || 'More', pages: rest });
return groups;
}
/** Every page id the table of contents names (for the checks). */
export function tocIds(toc) {
return (toc.groups || []).flatMap((g) => g.pages || []);
}
function normalise(parts) {
const out = [];
for (const part of parts) {
if (part === '' || part === '.') continue;
if (part === '..') { if (out.length && out[out.length - 1] !== '..') out.pop(); else out.push('..'); } else out.push(part);
}
return out;
}
/** The folder of a page, relative to docs/ide/ ('' for English, 'fr' for a French page). */
function folderOf(page) {
return page && page.lang && page.lang !== 'en' ? [page.lang] : [];
}
/**
* Where a link of a page leads:
* {url} an address of the web (http, mailto; a page of docs/ outside docs/ide/ goes to jumphp.net/docs),
* {page, anchor} a page of this documentation (its id; the language is the browser's), or an anchor of the same page.
*/
export function resolveLink(href, from) {
href = String(href || '').trim();
if (/^(https?:|mailto:)/i.test(href)) return { url: href };
const [path, anchor = ''] = href.split('#');
if (!path) return { page: from ? from.id : 'index', anchor };
const parts = normalise([...folderOf(from), ...path.split('/')]);
if (parts[0] === '..') {
// docs/<name>.md, docs/<name>.fr.md: the rest of JumPHP's documentation, online
const rest = normalise(parts.slice(1)).join('/');
return { url: WEB_DOCS + rest.replace(/\.md$/, '') + (anchor ? '#' + anchor : '') };
}
const name = parts[parts.length - 1] || '';
if (!/\.md$/.test(name)) return { url: WEB + parts.join('/') };
return { page: name.replace(/\.md$/, ''), anchor };
}
/** The path of a picture relative to docs/ide/ (`images/x.png`), or null when it is not one of the documentation's. */
export function resolveImage(src, from) {
if (/^(https?:|data:)/i.test(String(src))) return null;
const parts = normalise([...folderOf(from), ...String(src).split('/')]);
const path = parts.join('/');
return /^images\/[a-z0-9][a-z0-9._-]*\.(png|jpe?g|gif|webp)$/.test(path) ? path : null;
}
/** The headings of a page: [{level, text, anchor, offset}] (code blocks skipped). */
export function headings(text) {
const out = [];
let inCode = false;
let offset = 0;
for (const line of String(text).split('\n')) {
if (/^```/.test(line)) inCode = !inCode;
else if (!inCode) {
const m = /^(#{1,4})\s+(.+?)\s*$/.exec(line);
if (m) out.push({ level: m[1].length, text: m[2], anchor: slug(m[2]), offset });
}
offset += line.length + 1;
}
return out;
}
/** The words of a query: plain words, "a phrase" kept whole. */
export function terms(query) {
const out = [];
for (const m of fold(query).matchAll(/"([^"]+)"|(\S+)/g)) {
const term = (m[1] || m[2]).trim();
if (term.length >= 2 || /\d/.test(term)) out.push(term);
}
return out;
}
function count(haystack, needle) {
let n = 0;
for (let i = haystack.indexOf(needle); i !== -1; i = haystack.indexOf(needle, i + needle.length)) n++;
return n;
}
/**
* Searches the pages of a language (each id once, English when not translated): every term must be in the page.
* Score: a term in the title 10, in a heading 4, each time in the text 1. [{id, title, score, snippet, anchor}], best first.
*/
export function search(pages, query, lang, limit = 30) {
const words = terms(query);
if (!words.length) return [];
const results = [];
for (const p of pagesIn(pages, lang).values()) {
const body = fold(p.text);
if (!words.every((w) => body.includes(w))) continue;
const title = fold(p.title);
const heads = headings(p.text);
const headText = fold(heads.map((h) => h.text).join('\n'));
let score = 0;
for (const w of words) score += (title.includes(w) ? 10 : 0) + (headText.includes(w) ? 4 : 0) + Math.min(count(body, w), 20);
// where the first term is, the heading above it and the text around it
const at = body.indexOf(words[0]);
const above = heads.filter((h) => h.offset <= at).pop();
const start = Math.max(0, at - 60);
const snippet = p.text.slice(start, at + 120).replace(/\s+/g, ' ').replace(/[#*`|>]/g, '').trim();
results.push({ id: p.id, title: p.title, score, snippet: (start > 0 ? '…' : '') + snippet + '…', anchor: above && above.level > 1 ? above.anchor : '' });
}
return results.sort((a, b) => b.score - a.score || a.title.localeCompare(b.title)).slice(0, limit);
}
/** Back / forward through the pages seen. */
export class History {
constructor() { this.items = []; this.at = -1; }
push(entry) {
const cur = this.items[this.at];
if (cur && cur.page === entry.page && cur.anchor === entry.anchor) return;
this.items = this.items.slice(0, this.at + 1);
this.items.push(entry);
this.at = this.items.length - 1;
}
canBack() { return this.at > 0; }
canForward() { return this.at < this.items.length - 1; }
back() { if (this.canBack()) this.at--; return this.items[this.at]; }
forward() { if (this.canForward()) this.at++; return this.items[this.at]; }
current() { return this.items[this.at] || null; }
}