#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the source content profile lookup from production reference catalogs.
The reader callback is restricted to explicitly enumerated application inputs;
full manual chapters, examples and maintainer collections are never opened.
"""
from html import escape
import hashlib
import json
LOOKUP_ROOT = "docs/manuals/"
def _json(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2)
def _bytes(value):
return value.encode("utf-8")
def basic_anchor(entry):
if entry["id"].startswith("ERROR."):
return "err-" + entry["keyword"].lower().replace("/0", "div-zero")
return "term-" + entry["id"].lower().replace(".", "-").replace("$", "-string").replace("@", "-at")
def _page(title, body, home="../index.html"):
return _bytes(f'''
{escape(title)} ยท VCC Plus Reference Lookup
{escape(title)}
{body}\n''')
def _index(book, directory, chapters):
return _bytes("(globalThis.manualBooks ??= []).push(" + _json({
"book": book, "directory": directory, "chapters": chapters,
}) + ");\n")
def build_resources(read_source):
"""Return generated lookup reader files; never read full manual content."""
catalog = json.loads(read_source("platforms/macos/Resources/BASICReference.json"))
assembly = json.loads(read_source("platforms/macos/Resources/AssemblyReference.json"))
signature = hashlib.sha256()
for suffix in ("", "Instructions", "Topics"):
name = f"AssemblyReference{suffix}.swift"
data = read_source("platforms/macos/App/" + name).replace(b"\r\n", b"\n")
signature.update(name.encode() + b"\0" + data + b"\0")
if assembly["sourceSHA256"] != signature.hexdigest():
raise ValueError("Assembly lookup snapshot differs from the selected production catalog")
resources = {}
chapters = []
for errors in (False, True):
page = "errors.html" if errors else "reference.html"
title = "BASIC errors" if errors else "BASIC command lookup"
rows = [r for r in catalog["entries"] if r["id"].startswith("ERROR.") == errors]
sections, html = [], []
for row in rows:
anchor = basic_anchor(row)
paragraphs = [row["summary"], *row.get("parameters", []), *row.get("notes", [])]
paragraphs = [p if isinstance(p, str) else _json(p) for p in paragraphs]
citation = f"Source: {row['source']}, {row['sourcePage']}."
body = "".join("" + escape(p) + "
" for p in paragraphs)
for syntax in row.get("syntax", []):
body += "" + escape(syntax) + "
"
if row.get("sample"):
body += "" + escape(row["sample"]) + "
"
body += "Dialect: " + escape(row["dialect"]) + ". " + escape(citation) + "
"
html.append(f'{escape(row["title"])}
{body}')
sections.append({"id": anchor, "title": row["title"],
"passages": [*paragraphs, *row.get("syntax", []), row.get("sample", ""), citation]})
resources[LOOKUP_ROOT + "programming-in-coco-basic/" + page] = _page(title, "\n".join(html))
chapters.append({"page": page, "label": "Lookup", "title": title, "sections": sections})
resources[LOOKUP_ROOT + "book-index.js"] = _index("BASIC Lookup", "programming-in-coco-basic", chapters)
sections, html = [], []
for i, row in enumerate(assembly["entries"]):
anchor = f"assembly-{i:04d}"
paragraphs = [str(row[key]) for key in ("category", "operation", "syntax", "flags", "detail") if row.get(key)]
if row.get("aliases"):
paragraphs.append("Aliases: " + ", ".join(row["aliases"]))
if row.get("hd6309"):
paragraphs.append("HD6309 only.")
paragraphs.extend(row.get("sources", []))
sections.append({"id": anchor, "title": row["name"], "passages": paragraphs})
html.append(f'{escape(row["name"])}
' +
"".join("" + escape(p) + "
" for p in paragraphs) + "")
resources[LOOKUP_ROOT + "assembly-language-programming/instructions.html"] = _page("Assembly lookup", "\n".join(html))
resources[LOOKUP_ROOT + "assembly-language-programming/catalog.json"] = read_source("platforms/macos/Resources/AssemblyReference.json")
resources[LOOKUP_ROOT + "assembly-language-programming/book-index.js"] = _index(
"Assembly Lookup", "assembly-language-programming", [{"page": "instructions.html", "label": "Lookup", "title": "Assembly", "sections": sections}])
home = '''This source edition includes BASIC and Assembly lookup. The complete native quick-reference browsers are also available from the Develop menu.
Search the lookup library
'''
resources[LOOKUP_ROOT + "index.html"] = _page("VCC Plus Reference Lookup", home, "index.html")
resources[LOOKUP_ROOT + "lookup-search.js"] = _bytes('''// SPDX-License-Identifier: GPL-3.0-or-later
const field = document.getElementById("manual-query"), results = document.getElementById("search-results"), statusLine = document.getElementById("search-status");
const topics = globalThis.manualBooks.flatMap(book => book.chapters.flatMap(chapter => chapter.sections.map(section => ({...section, url: book.directory + "/" + chapter.page + "#" + section.id}))));
document.getElementById("search-form").addEventListener("submit", event => event.preventDefault());
field.addEventListener("input", () => {
const words = field.value.trim().toLowerCase().split(/\\s+/).filter(Boolean);
const matches = words.length ? topics.filter(topic => words.every(word => (topic.title + " " + topic.passages.join(" ")).toLowerCase().includes(word))) : [];
results.replaceChildren();
for (const topic of matches) { const item = document.createElement("li"), link = document.createElement("a"); link.href = topic.url; link.textContent = topic.title; item.append(link); results.append(item); }
statusLine.textContent = words.length ? matches.length + " matching topics" : "Enter a search term.";
});
''')
return resources