infrastructure/portal/docs/docs.js

288 lines
15 KiB
JavaScript

"use strict";
(() => {
const $ = selector => document.querySelector(selector);
const el = (tag, text, className) => {
const node = document.createElement(tag);
if (text !== undefined) node.textContent = text;
if (className) node.className = className;
return node;
};
let data;
let currentView = 'timeline';
const form = $('#filters');
const query = $('#query');
const status = $('#status');
const order = $('#order');
function sourceURL(path, line) {
const url = `${data.source_repository}/src/commit/${data.source_revision}/${path.split('/').map(encodeURIComponent).join('/')}`;
return url + (line ? `#L${line}` : '');
}
function link(text, href) {
const a = el('a', text);
const url = new URL(href, location.href);
if (['https:', 'http:'].includes(url.protocol)) a.href = url.href;
return a;
}
function routeLink(href, path) {
const resolved = new URL(href, `https://docs.invalid/${path}`);
if (resolved.origin !== 'https://docs.invalid') return resolved.href;
const target = resolved.pathname.slice(1);
const rfc = data.rfcs.find(item => item.path === target);
if (rfc) return `#${rfc.id}${resolved.hash ? '/' + resolved.hash.slice(1) : ''}`;
if (target === 'spec/decision-log.md') {
const id = resolved.hash.match(/d-\d{3}/i);
if (id) return `#${id[0].toUpperCase()}`;
}
if (href.startsWith('#')) {
const own = data.rfcs.find(item => item.path === path);
if (own) return `#${own.id}/${href.slice(1)}`;
}
return sourceURL(target) + resolved.hash;
}
// Source Markdown is rendered into DOM nodes. Raw HTML is never executed.
function inline(parent, text, path, autoRefs = true) {
const re = /(`+)([\s\S]*?)\1|\[([^\]]+)\]\(([^\s)]+)\)|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*]+)\*|\b(RFC-\d{4}|D-\d{3})\b/g;
let start = 0;
for (const m of text.matchAll(re)) {
parent.append(document.createTextNode(text.slice(start, m.index)));
if (m[1]) parent.append(el('code', m[2]));
else if (m[3]) {
const a = link('', routeLink(m[4], path));
inline(a, m[3], path, false);
parent.append(a);
} else if (m[5] || m[6]) {
const strong = el('strong'); inline(strong, m[5] || m[6], path, false); parent.append(strong);
} else if (m[7]) {
const em = el('em'); inline(em, m[7], path, false); parent.append(em);
} else if (autoRefs && [...data.rfcs, ...data.decisions].some(item => item.id === m[8])) {
parent.append(link(m[8], `#${m[8]}`));
} else parent.append(document.createTextNode(m[8]));
start = m.index + m[0].length;
}
parent.append(document.createTextNode(text.slice(start).replace(/\\([|*_`])/g, '$1')));
}
function markdown(text, path, headingPrefix = '') {
const root = el('div', undefined, 'markdown');
const lines = text.replace(/\r/g, '').split('\n');
const headings = [];
const used = new Map();
const special = line => /^(?:#{1,6}\s|```|~~~|>\s?|\s*[-*+]\s|\s*\d+\.\s|\|)/.test(line);
const cells = line => line.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map(s => s.trim().replace(/\\\|/g, '|'));
for (let i = 0; i < lines.length;) {
let line = lines[i];
if (!line.trim()) { i++; continue; }
const fence = line.match(/^(```+|~~~+)\s*(.*)$/);
if (fence) {
const content = []; i++;
while (i < lines.length && !lines[i].startsWith(fence[1])) content.push(lines[i++]);
if (i < lines.length) i++;
const pre = el('pre'); pre.append(el('code', content.join('\n'))); root.append(pre); continue;
}
const h = line.match(/^(#{1,6})\s+(.+?)\s*#*$/);
if (h) {
const node = el(`h${h[1].length}`); inline(node, h[2], path);
const base = node.textContent.toLowerCase().replace(/[^\w\s-]/g, '').trim().replace(/\s+/g, '-');
const count = used.get(base) || 0; used.set(base, count + 1);
const slug = base + (count ? `-${count}` : '');
node.id = headingPrefix + slug;
root.append(node); headings.push({slug, id: node.id, title: node.textContent, level: h[1].length}); i++; continue;
}
if (/^\s*([-*_])(?:\s*\1){2,}\s*$/.test(line)) { root.append(el('hr')); i++; continue; }
if (line.startsWith('>')) {
const quote = [];
while (i < lines.length && lines[i].startsWith('>')) quote.push(lines[i++].replace(/^>\s?/, ''));
const block = el('blockquote'); block.append(markdown(quote.join('\n'), path).node); root.append(block); continue;
}
if (line.trim().startsWith('|') && /^\s*\|?\s*:?-{3}/.test(lines[i + 1] || '')) {
const wrap = el('div', undefined, 'table-scroll'); const table = el('table'); const head = el('thead'); const tr = el('tr');
for (const cell of cells(line)) { const th = el('th'); th.scope = 'col'; inline(th, cell, path); tr.append(th); }
head.append(tr); table.append(head); const body = el('tbody'); i += 2;
while (i < lines.length && lines[i].trim().startsWith('|')) {
const row = el('tr');
for (const cell of cells(lines[i++])) { const td = el('td'); inline(td, cell, path); row.append(td); }
body.append(row);
}
table.append(body); wrap.append(table); root.append(wrap); continue;
}
const item = line.match(/^(\s*)([-*+]|\d+\.)\s+(.*)$/);
if (item) {
const indent = item[1].length;
const ordered = /\d/.test(item[2]); const list = el(ordered ? 'ol' : 'ul');
if (ordered) list.start = parseInt(item[2], 10);
while (i < lines.length) {
const entry = lines[i].match(/^(\s*)([-*+]|\d+\.)\s+(.*)$/);
if (!entry || entry[1].length !== indent || /\d/.test(entry[2]) !== ordered) break;
const content = [entry[3]];
const contentIndent = lines[i].length - entry[3].length;
i++;
while (i < lines.length) {
if (!lines[i].trim()) {
let next = i + 1;
while (next < lines.length && !lines[next].trim()) next++;
if (next >= lines.length || lines[next].search(/\S/) <= indent) break;
content.push(''); i++; continue;
}
if (lines[i].search(/\S/) <= indent) break;
content.push(lines[i++].slice(contentIndent));
}
const li = el('li'); li.append(markdown(content.join('\n'), path).node); list.append(li);
while (i < lines.length && !lines[i].trim()) i++;
}
root.append(list); continue;
}
const paragraph = [line]; i++;
while (i < lines.length && lines[i].trim() && !special(lines[i])) paragraph.push(lines[i++]);
const p = el('p'); inline(p, paragraph.join(' '), path); root.append(p);
}
return {node: root, headings};
}
function related(parent, title, ids) {
if (!ids.length) return;
const box = el('div', undefined, 'related'); box.append(el('span', title + ' '));
ids.forEach(id => box.append(link(id, '#' + id))); parent.append(box);
}
function matches(item) {
const terms = query.value.toLowerCase().trim().split(/\s+/).filter(Boolean);
const text = `${item.id} ${item.title} ${item.markdown}`.toLowerCase();
return (!status.value || status.value === item.status) && terms.every(term => text.includes(term));
}
function synchronizeFilters() {
const params = new URLSearchParams(location.search);
query.value = params.get('q') || '';
status.value = ['Accepted', 'Proposed', 'Draft', 'Superseded', 'Rejected'].includes(params.get('status')) ? params.get('status') : '';
order.value = params.get('order') === 'oldest' ? 'oldest' : 'newest';
}
function saveFilters() {
const url = new URL(location.href);
for (const [key, value] of [['q', query.value.trim()], ['status', status.value], ['order', order.value === 'oldest' ? 'oldest' : '']]) {
if (value) url.searchParams.set(key, value); else url.searchParams.delete(key);
}
history.replaceState(null, '', url); render(false);
}
function decisionNode(item, selected) {
const detail = el('details', undefined, 'decision'); detail.id = 'entry-' + item.id;
const summary = el('summary'); summary.append(el('span', item.id, 'decision-id'), el('span', item.title, 'decision-title'));
detail.append(summary);
// Lazy rendering keeps the full 93-entry timeline fast and keyboard navigable.
function populate() {
if (detail.dataset.loaded) return;
const body = el('div', undefined, 'decision-body');
body.append(markdown(item.markdown, item.path, item.id + '-').node);
related(body, 'References:', item.references);
related(body, 'Referenced by later decisions:', item.later_references);
const meta = el('div', undefined, 'decision-meta');
meta.append(el('span', item.status, 'status-badge'), el('span', item.date_source), link('Permalink ↗', '#' + item.id), link('Pinned source ↗', sourceURL(item.path, item.line)));
body.append(meta); detail.append(body); detail.dataset.loaded = 'true';
}
detail.addEventListener('toggle', () => { if (detail.open) populate(); });
if (selected) { populate(); detail.open = true; }
return detail;
}
function renderTimeline(selected) {
let items = data.decisions.filter(item => item.status === 'Accepted' && (item.id === selected || matches(item)));
items.sort((a, b) => {
if (!a.date && b.date) return 1;
if (a.date && !b.date) return -1;
const comparison = (a.date || '').localeCompare(b.date || '') || a.id.localeCompare(b.id);
return order.value === 'oldest' ? comparison : -comparison;
});
const list = $('#timeline-list'); list.replaceChildren();
let previous; let entries;
items.forEach(item => {
const date = item.date || 'Undated';
if (date !== previous) {
const group = el('section', undefined, 'timeline-group');
const label = el('div', undefined, 'timeline-date'); label.append(el('strong', date));
if (!item.date) label.append('Ordered by decision ID');
entries = el('div', undefined, 'timeline-entries'); group.append(label, entries); list.append(group); previous = date;
}
entries.append(decisionNode(item, item.id === selected));
});
$('#results').textContent = `${items.length} accepted decision${items.length === 1 ? '' : 's'} shown / ${data.decisions.filter(x => x.status === 'Accepted').length} total`;
if (!items.length) list.append(el('p', 'No decisions match these filters. Try another keyword or reset the filters.', 'empty'));
}
function renderRegistry() {
const items = data.rfcs.filter(matches).sort((a, b) => order.value === 'oldest' ? a.id.localeCompare(b.id) : b.id.localeCompare(a.id));
const list = $('#rfc-list'); list.replaceChildren();
items.forEach(item => {
const card = el('article', undefined, 'rfc-card');
const header = el('header'); header.append(el('span', item.id), el('span', item.status, 'status-badge'));
const title = el('h2'); title.append(link(item.title, '#' + item.id));
const actions = el('div', undefined, 'rfc-actions'); actions.append(link('Read RFC →', '#' + item.id), link('Source ↗', sourceURL(item.path)));
card.append(header, title, el('p', item.scope || item.status_detail), el('p', `Version ${item.version} / ${item.date || 'Date not recorded'}`), actions); list.append(card);
});
$('#results').textContent = `${items.length} RFC${items.length === 1 ? '' : 's'} shown / ${data.rfcs.length} total`;
if (!items.length) list.append(el('p', 'No RFCs match these filters. Try another keyword or reset the filters.', 'empty'));
}
function renderReader(item, anchor, navigate) {
const article = $('#document'); article.replaceChildren();
$('#reader-source').href = sourceURL(item.path);
const intro = el('div', undefined, 'document-links');
intro.append(el('span', item.status, 'status-badge'));
related(intro, 'Referenced decisions:', item.decisions);
article.append(intro);
const content = markdown(item.markdown, item.path, 'section-'); article.append(content.node);
const toc = $('#toc'); toc.replaceChildren();
content.headings.filter(h => h.level === 2 || h.level === 3).forEach(h => {
const a = link(h.title, '#' + item.id + '/' + h.slug); if (h.level === 3) a.className = 'toc-sub'; toc.append(a);
});
$('#results').textContent = `${item.id} / source ${data.source_revision.slice(0, 12)}`;
document.title = `${item.id}: ${item.title} // Archipelago Docs`;
if (navigate) {
requestAnimationFrame(() => {
const target = content.headings.find(h => h.slug === anchor);
if (target) document.getElementById(target.id).scrollIntoView();
else { $('#reader').scrollIntoView(); article.focus({preventScroll: true}); }
});
}
}
function render(navigate = true) {
if (!data) return;
let hash;
try { hash = decodeURIComponent(location.hash.slice(1)); } catch { hash = ''; }
const [id, anchor] = hash.split('/');
const rfc = data.rfcs.find(item => item.id === id);
const decision = data.decisions.find(item => item.id === id);
currentView = rfc || id === 'rfcs' ? 'rfcs' : 'timeline';
$('#timeline').hidden = currentView !== 'timeline';
$('#rfcs').hidden = currentView !== 'rfcs' || Boolean(rfc);
$('#reader').hidden = !rfc;
form.hidden = Boolean(rfc);
for (const name of ['timeline', 'rfcs']) {
if (name === currentView) $('#' + name + '-tab').setAttribute('aria-current', 'page');
else $('#' + name + '-tab').removeAttribute('aria-current');
}
document.title = 'Docs // Archipelago';
if (rfc) renderReader(rfc, anchor, navigate);
else if (currentView === 'rfcs') renderRegistry();
else {
renderTimeline(decision?.id);
if (decision && navigate) requestAnimationFrame(() => $('#entry-' + decision.id)?.scrollIntoView());
if (/^(RFC-|D-)/.test(id) && !decision) $('#results').textContent = 'Document not found in this source revision. Browse the index below.';
}
}
form.addEventListener('submit', event => { event.preventDefault(); saveFilters(); });
query.addEventListener('input', saveFilters);
status.addEventListener('change', saveFilters);
order.addEventListener('change', saveFilters);
form.addEventListener('reset', () => { queueMicrotask(saveFilters); });
window.addEventListener('hashchange', () => { synchronizeFilters(); render(); });
window.addEventListener('popstate', () => { synchronizeFilters(); render(); });
async function load() {
try {
const response = await fetch('./data.json', {cache: 'no-cache'});
if (!response.ok) throw new Error('index unavailable');
data = await response.json();
if (data.version !== 1 || !Array.isArray(data.decisions) || !Array.isArray(data.rfcs) || !/^[0-9a-f]{40}$/.test(data.source_revision)) throw new Error('invalid index');
$('#decision-count').textContent = data.decisions.filter(item => item.status === 'Accepted').length;
$('#rfc-count').textContent = data.rfcs.length;
$('#provenance').replaceChildren('SOURCE ', link(data.source_revision.slice(0, 12), `${data.source_repository}/commit/${data.source_revision}`), ` / ${data.source_committed_at.slice(0, 10)}`);
synchronizeFilters(); render(Boolean(location.hash));
} catch {
$('#provenance').textContent = 'Documentation source temporarily unavailable.';
$('#results').replaceChildren('Could not load the documentation index. ', link('Read the RFC repository ↗', 'https://git.fasoley.net/Archipelago/rfc'));
form.hidden = true;
}
}
load();
})();