Files

118 lines
7.5 KiB
Python

#!/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'''<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{escape(title)} · VCC Plus Reference Lookup</title>
<style>body{{font:17px/1.6 -apple-system,BlinkMacSystemFont,sans-serif;max-width:78ch;margin:2rem auto;padding:0 1rem;color:#182721;background:#fff}}a{{color:#175b43}}pre{{white-space:pre-wrap;overflow-wrap:anywhere;background:#f1f5f2;padding:1rem}}section{{border-top:1px solid #d5ded8;margin-top:2rem;padding-top:1rem}}input{{font:inherit;max-width:100%;box-sizing:border-box;width:100%;padding:.5rem}}small{{display:block}}h1,h2{{line-height:1.25}}:target{{background:#f2f7ed}}</style>
</head><body><nav><a href="{home}">Lookup library</a></nav><main>
<h1>{escape(title)}</h1>{body}</main></body></html>\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("<p>" + escape(p) + "</p>" for p in paragraphs)
for syntax in row.get("syntax", []):
body += "<pre><code>" + escape(syntax) + "</code></pre>"
if row.get("sample"):
body += "<pre><code>" + escape(row["sample"]) + "</code></pre>"
body += "<p>Dialect: " + escape(row["dialect"]) + ". " + escape(citation) + "</p>"
html.append(f'<section id="{escape(anchor)}"><h2>{escape(row["title"])}</h2>{body}</section>')
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'<section id="{anchor}"><h2>{escape(row["name"])}</h2>' +
"".join("<p>" + escape(p) + "</p>" for p in paragraphs) + "</section>")
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 = '''<p>This source edition includes BASIC and Assembly lookup. The complete native quick-reference browsers are also available from the Develop menu.</p>
<ul><li><a href="programming-in-coco-basic/reference.html">BASIC commands</a></li><li><a href="programming-in-coco-basic/errors.html">BASIC errors</a></li><li><a href="assembly-language-programming/instructions.html">Assembly instructions, addressing and directives</a></li></ul>
<section id="search"><h2>Search the lookup library</h2><form id="search-form"><label for="manual-query">Commands, instructions or keywords</label><input id="manual-query" type="search" autocomplete="off"></form><p id="search-status" aria-live="polite"></p><ol id="search-results"></ol></section>
<script src="book-index.js"></script><script src="assembly-language-programming/book-index.js"></script><script src="lookup-search.js"></script>'''
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