clio.html32 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,47 @@
1
+ // Verify that every internal src/href/background in the built site resolves to an existing file
2
+ // and that all #fragment anchors exist on their target pages.
3
+ import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
4
+ import { join, relative } from "node:path";
5
+
6
+ export function checkLinks(dist, base = "/") {
7
+ const walk = d => readdirSync(d).flatMap(n => {
8
+ const p = join(d, n);
9
+ return statSync(p).isDirectory() ? walk(p) : [p];
10
+ });
11
+ const html = walk(dist).filter(f => f.endsWith(".html"));
12
+ const names = new Map(html.map(f => [
13
+ relative(dist, f),
14
+ new Set([...readFileSync(f, "latin1").matchAll(/<a name="([^"]+)"/g)].map(m => m[1])),
15
+ ]));
16
+ let bad = 0, checked = 0;
17
+ for (const f of html) {
18
+ const s = readFileSync(f, "latin1"), rel = relative(dist, f);
19
+ for (const [, attr, u] of s.matchAll(/\b(src|href|background)="([^"]+)"/g)) {
20
+ if (!u.startsWith(base) || u.startsWith("//")) continue;
21
+ checked++;
22
+ let [p, frag] = u.slice(base.length).split("#");
23
+ p = p.split("?")[0] || "index.html";
24
+ const file = p.startsWith("n/") ? p.slice(2) : p;
25
+ if (!existsSync(join(dist, file))) {
26
+ bad++;
27
+ console.log(`missing ${rel}: ${attr}=${u}`);
28
+ continue;
29
+ }
30
+ if (frag && file.endsWith(".html") && !names.get(file)?.has(frag)) {
31
+ bad++;
32
+ console.log(`no anchor ${rel}: ${u}`);
33
+ }
34
+ }
35
+ }
36
+ console.log(`${html.length} pages, ${checked} internal references, ${bad} broken`);
37
+ return bad === 0;
38
+ }
39
+
40
+ if (import.meta.url === `file://${process.argv[1]}`) {
41
+ const [dist, base = "/"] = process.argv.slice(2);
42
+ if (!dist) {
43
+ console.error("usage: checklinks.mjs <dist> [base=/]");
44
+ process.exit(1);
45
+ }
46
+ process.exit(checkLinks(dist, base) ? 0 : 1);
47
+ }
package/src/chrome.mjs ADDED
@@ -0,0 +1,76 @@
1
+ // HTML 3.2 window frames, menu bars and page layout, shared by the build and the edge worker.
2
+ // Every era is described by measurements taken from clio.css (see build.mjs, measureFrame):
3
+ // frame = { border, borderColor: {a, i}, bandL: {a: [colours], i}, bandR, shadow: {a, i}, paper }
4
+ // head / foot = GIFs cut from the window above and below its pane
5
+ // No rowspan and no height="100%": Netscape 3/4 and IE 5 ignore both on table cells.
6
+
7
+ export const esc = s => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
8
+
9
+ export function imgMap(b, { alt = "", name = "m", href = h => h } = {}) {
10
+ const im = `<img src="${b.url}" width=${b.w} height=${b.h} alt="${esc(alt)}" border=0`;
11
+ if (!b.areas?.length) return im + ">";
12
+ const areas = b.areas.map(a => `<area shape=rect coords="${a.x},${a.y},${a.x + a.w},${a.y + a.h}" href="${esc(href(a.href))}" alt="${esc(a.alt)}" target="_top">`).join("");
13
+ return `<map name="${name}">${areas}</map>${im} usemap="#${name}">`;
14
+ }
15
+
16
+ const runs = cols => cols.reduce((out, c) => {
17
+ if (out.length && out[out.length - 1].c === c) out[out.length - 1].n++;
18
+ else out.push({ c, n: 1 });
19
+ return out;
20
+ }, []);
21
+
22
+ // The body keeps the same width in every era (content GIFs are cut once): frame bands take the
23
+ // place of side padding, 8px above and below.
24
+ function pane(cw, inner, body, sp) {
25
+ const pad = Math.max(0, Math.floor((cw - inner) / 2)), w = cw - 2 * pad;
26
+ const side = pad ? `<td width=${pad}>${sp(pad, 1)}</td>` : "", gap = `<tr><td colspan=${pad ? 3 : 1}>${sp(1, 8)}</td></tr>`;
27
+ return `<table border=0 cellspacing=0 cellpadding=0 width=${cw}>${gap}` +
28
+ `<tr>${side}<td width=${w} valign=top><!--B-->${body}<!--/B--></td>${side}</tr>${gap}</table>`;
29
+ }
30
+
31
+ // One window. The markers let the worker rebuild the frame for another era around the same body.
32
+ export function windowFrame(fr, { key, width, active, head, foot, body, titleHref = "", alt = "", sp }) {
33
+ const s = active ? "a" : "i", b = fr.border, bc = fr.borderColor[s], sh = fr.shadow[s];
34
+ const L = runs(fr.bandL[s]), R = runs(fr.bandR[s]);
35
+ const lw = fr.bandL[s].length, rw = fr.bandR[s].length;
36
+ const IW = width - 2 * b, CW = IW - lw - rw, span = L.length + 1 + R.length, cols = span + (b ? 2 : 0);
37
+ const B = b ? `<td bgcolor="${bc}" width=${b}>${sp(b, 1)}</td>` : "";
38
+ const S = sh ? `<td bgcolor="${sh}" width=1>${sp(1, 1)}</td>` : "";
39
+ const band = rs => rs.map(r => `<td bgcolor="${r.c}" width=${r.n}>${sp(r.n, 1)}</td>`).join("");
40
+ const line = last => b ? `<tr><td bgcolor="${bc}" colspan=${cols}>${sp(width, b)}</td>${sh ? (last ? S : `<td width=1>${sp(1, 1)}</td>`) : ""}</tr>` : "";
41
+ const headImg = imgMap(head, { alt });
42
+ const strip = (img, first) => `<tr>${B}<td colspan=${span} width=${IW}>${img}</td>${B}${sh ? (first && !b ? `<td width=1>${sp(1, 1)}</td>` : S) : ""}</tr>`;
43
+ const shadowRow = sh
44
+ ? `<tr><td colspan=${cols + 1}><table border=0 cellspacing=0 cellpadding=0><tr><td width=1>${sp(1, 1)}</td><td bgcolor="${sh}">${sp(width, 1)}</td></tr></table></td></tr>`
45
+ : "";
46
+ return `<!--W k=${key}${titleHref ? ` h=${titleHref}` : ""} a=${active ? 1 : 0} w=${width}-->` +
47
+ `<table border=0 cellspacing=0 cellpadding=0 width=${width + (sh ? 1 : 0)}>` +
48
+ line(false) +
49
+ strip(titleHref ? `<a href="${esc(titleHref)}" target="_top">${headImg}</a>` : headImg, true) +
50
+ `<tr>${B}${band(L)}<td width=${CW} bgcolor="${fr.paper}">${pane(CW, width - 18, body, sp)}</td>${band(R)}${B}${S}</tr>` +
51
+ (foot ? strip(imgMap(foot), false) : "") +
52
+ line(true) + shadowRow + `</table><!--/W-->`;
53
+ }
54
+
55
+ // Menu bar, closed or with one menu open. layout "bar": a strip across the top (Mac OS);
56
+ // "column": NeXTSTEP's main menu, a panel at the top left with submenus to its right.
57
+ export function menuHTML(m, { layout, bar, drop = null, href = h => h, sp, fallback = false }) {
58
+ const barImg = imgMap(bar, { alt: "Menu", name: "mb", href });
59
+ const dropImg = drop ? imgMap(drop, { alt: "", name: "md", href }) : "";
60
+ if (layout === "column") {
61
+ if (!drop) return barImg;
62
+ if (fallback) return `<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top>${barImg}</td><td>${sp(Math.max(1, drop.offsetX - bar.w), 1)}</td><td valign=top>${dropImg}</td></tr></table>`;
63
+ return `${barImg}<div style="position:absolute;left:${drop.offsetX}px;top:${drop.offsetY}px;z-index:99">${dropImg}</div>`;
64
+ }
65
+ const strip = `<table border=0 cellspacing=0 cellpadding=0 width="100%"><tr><td bgcolor="${m.barFill}">${barImg}</td></tr><tr><td bgcolor="${m.barLine}">${sp(1, 1)}</td></tr></table>`;
66
+ if (!drop) return strip;
67
+ if (fallback) return strip + `<table border=0 cellspacing=0 cellpadding=0><tr>${drop.offsetX > 0 ? `<td>${sp(drop.offsetX, 1)}</td>` : ""}<td valign=top>${dropImg}</td></tr></table>`;
68
+ return strip + `<div style="position:absolute;left:${drop.offsetX}px;top:${drop.offsetY}px;z-index:99">${dropImg}</div>`;
69
+ }
70
+
71
+ // Everything between <body> and </body>.
72
+ export function pageBody(layout, menu, inner, sp) {
73
+ return layout === "column"
74
+ ? `<!--L--><table border=0 cellspacing=0 cellpadding=0><tr><td valign=top><!--M-->${menu}<!--/M--></td><td valign=top><br><!--P-->${inner}<!--/P--></td></tr></table><!--/L-->`
75
+ : `<!--L--><!--M-->${menu}<!--/M-->\n<br><!--P-->${inner}<!--/P--><!--/L-->`;
76
+ }
@@ -0,0 +1,48 @@
1
+ // Clean-room HTML5 -> HTML 3.2 downgrade helpers for arbitrary modern static pages.
2
+ // Runs before Playwright layout and nativeHTML emission.
3
+
4
+ export function downgradeHTML5(html) {
5
+ let out = html;
6
+
7
+ // 1. Extract simple JS redirects into <meta http-equiv="refresh"> before stripping <script>.
8
+ const jsRedir = out.match(/<script\b[^>]*>[\s\S]*?(?:window|document)\.location(?:\.href)?\s*=\s*['"](https?:\/\/[^'"]+)['"][\s\S]*?<\/script>/i)
9
+ || out.match(/<script\b[^>]*>[\s\S]*?window\.location\.replace\(\s*['"](https?:\/\/[^'"]+)['"]\s*\)[\s\S]*?<\/script>/i);
10
+ if (jsRedir) {
11
+ const meta = `<meta http-equiv="refresh" content="0;url=${jsRedir[1].replace(/"/g, "&quot;")}">`;
12
+ out = /<head\b[^>]*>/i.test(out)
13
+ ? out.replace(/<head\b[^>]*>/i, m => `${m}${meta}`)
14
+ : meta + out;
15
+ }
16
+
17
+ // 2. Unwrap <noscript> before stripping <script> so lazy-loaded fallback <img> tags survive.
18
+ out = out.replace(/<\/?noscript\b[^>]*>/gi, "");
19
+
20
+ // 3. Strip scripts, stylesheets, and unsupported modern media/interactive tags (including <applet> which crashes MRJ).
21
+ out = out
22
+ .replace(/<(script|style|svg|canvas|video|audio|template|slot|dialog|applet)\b[^>]*>[\s\S]*?<\/\1>/gi, "")
23
+ .replace(/<(script|style|svg|canvas|video|audio|template|slot|dialog|applet|source|link)\b[^>]*\/?>/gi, "")
24
+ .replace(/<\/?(picture)\b[^>]*>/gi, "")
25
+ .replace(/\s+on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "")
26
+ .replace(/\s+(?:integrity|crossorigin|loading|decoding|srcset|sizes)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
27
+
28
+ // 4. Downgrade HTML5 semantic block/inline tags to HTML 3.2-safe equivalents.
29
+ out = out
30
+ .replace(/<(\/?)(?:nav|section|article|aside|header|footer|main|figure|figcaption)\b([^>]*)>/gi, "<$1div$2>")
31
+ .replace(/<(\/?)(?:mark|time|output)\b([^>]*)>/gi, "<$1span$2>");
32
+
33
+ return out;
34
+ }
35
+
36
+ // Convert basic inline CSS attributes (color, text-align) to HTML 3.2 attributes/tags.
37
+ export function inlineStyleToHTML32(html) {
38
+ return html.replace(/<([a-z0-9]+)\b([^>]*?)\sstyle="([^"]*)"([^>]*)>/gi, (m, tag, before, style, after) => {
39
+ const color = style.match(/(?:^|;)\s*color\s*:\s*(#[0-9a-f]{3,6})\b/i)?.[1];
40
+ const align = style.match(/(?:^|;)\s*text-align\s*:\s*(left|center|right)\b/i)?.[1];
41
+ let attrs = before + after;
42
+ if (align && !/\balign=/i.test(attrs) && /^(div|p|h[1-6]|td|th|table)$/i.test(tag)) {
43
+ attrs += ` align="${align.toLowerCase()}"`;
44
+ }
45
+ const open = `<${tag}${attrs}>`;
46
+ return color && !/^(img|br|hr|table|tr)$/i.test(tag) ? `${open}<font color="${color}">` : open;
47
+ });
48
+ }
package/src/gif.mjs ADDED
@@ -0,0 +1,43 @@
1
+ // A small GIF87a encoder for pictures with at most 256 exact colours (clio.css renders its pixel
2
+ // fonts and chrome without anti-aliasing, so a title bar has a handful of colours).
3
+ // The colour table is only as large as the picture needs (2, 4, 8 … entries), which ffmpeg's
4
+ // encoder does not do: it always writes 256 entries (768 bytes) even for a two-colour title.
5
+ // Returns null when the picture has more than 256 colours.
6
+ export function encodeGif(rgb, w, h) {
7
+ const index = new Map(), pal = [], pix = new Uint8Array(w * h);
8
+ for (let i = 0; i < w * h; i++) {
9
+ const key = (rgb[i * 3] << 16) | (rgb[i * 3 + 1] << 8) | rgb[i * 3 + 2];
10
+ let k = index.get(key);
11
+ if (k === undefined) { if (pal.length === 256) return null; k = pal.length; index.set(key, k); pal.push(key); }
12
+ pix[i] = k;
13
+ }
14
+ let bits = 1; while ((1 << bits) < pal.length) bits++;
15
+ const size = 1 << bits, minCode = Math.max(2, bits);
16
+ const out = [];
17
+ const u16 = v => out.push(v & 255, v >> 8);
18
+ out.push(...Buffer.from("GIF87a")); u16(w); u16(h);
19
+ out.push(0x80 | (bits - 1), 0, 0); // global table of 2^bits entries
20
+ for (let i = 0; i < size; i++) { const c = pal[i] ?? 0; out.push(c >> 16, (c >> 8) & 255, c & 255); }
21
+ out.push(0x2c); u16(0); u16(0); u16(w); u16(h); out.push(0); // image descriptor, no local table
22
+ out.push(minCode);
23
+ // LZW with variable code width, packed LSB first, in sub-blocks of up to 255 bytes.
24
+ const clear = 1 << minCode, eoi = clear + 1, data = [];
25
+ let width = minCode + 1, next = eoi + 1, acc = 0, nacc = 0;
26
+ const emit = code => { acc |= code << nacc; nacc += width; while (nacc >= 8) { data.push(acc & 255); acc >>>= 8; nacc -= 8; } };
27
+ let dict = new Map();
28
+ emit(clear);
29
+ let prefix = pix[0];
30
+ for (let i = 1; i < pix.length; i++) {
31
+ const c = pix[i], key = prefix * 4096 + c, hit = dict.get(key);
32
+ if (hit !== undefined) { prefix = hit; continue; }
33
+ emit(prefix);
34
+ if (next < 4096) { dict.set(key, next++); if (next > (1 << width) && width < 12) width++; }
35
+ else { emit(clear); dict = new Map(); width = minCode + 1; next = eoi + 1; }
36
+ prefix = c;
37
+ }
38
+ emit(prefix); emit(eoi);
39
+ if (nacc > 0) data.push(acc & 255);
40
+ for (let i = 0; i < data.length; i += 255) { const n = Math.min(255, data.length - i); out.push(n, ...data.slice(i, i + n)); }
41
+ out.push(0, 0x3b);
42
+ return Buffer.from(out);
43
+ }
@@ -0,0 +1,127 @@
1
+ // ClassicMacSupport preset: System 7 home page (4 interactive windows) + Chinese font install guide.
2
+ import { readFileSync } from "node:fs";
3
+ import { join, dirname } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const here = dirname(fileURLToPath(import.meta.url));
7
+ const iconSvg = readFileSync(join(here, "assets/icons.svg"), "utf8");
8
+ const icon = id => { const [, vb, body] = iconSvg.match(new RegExp(`<symbol id="${id}" viewBox="([^"]+)">([\\s\\S]*?)</symbol>`)); return `<svg width="32" height="32" viewBox="${vb}" shape-rendering="crispEdges" style="display:block">${body}</svg>`; };
9
+ const linkCss = "color:#0000cc;text-decoration:underline;cursor:pointer";
10
+
11
+ export const handles = p => p === "index.html";
12
+
13
+ export async function emit(k) {
14
+ const { plan, pic, txt, img, sp, hEsc, windowHTML, pageShell, snapHTML, encodeOut, writeOut, frameset, ORIGIN, BASE, STATIC_ONLY, report, setMapSeq } = k;
15
+ const block = (key, html, width) => snapHTML(key, html, width);
16
+ const src = plan.get("index.html")?.html || "";
17
+ const news = [...src.matchAll(/(\d{4}\/\d{1,2}\/\d{1,2})\s*-\s*([^<\n]+)/g)].map(m => [m[1], m[2].trim()]);
18
+ const intro = [...src.matchAll(/<p>([^<]*犄角旮旯[^<]*)<\/p>/g)].map(m => m[1].trim());
19
+ const head = (id, h, sub) => block(`head|${id}|${h}|${sub}`, `<table style="border-collapse:collapse"><tr><td style="padding:0 8px 0 0;vertical-align:top">${icon(id)}</td><td style="vertical-align:top;line-height:16px">${hEsc(h)}<br><span style="color:#666">${hEsc(sub)}</span></td></tr></table>`);
20
+
21
+ for (const mode of ["img", "text"]) {
22
+ const cjkImg = mode === "img", L = cjkImg ? pic : txt;
23
+ const txtRun = async (t, w, o = {}) => cjkImg && /[^\x00-\x7f]/.test(t)
24
+ ? img(await block(`p|${w}|${o.ink || ""}|${o.bold ? 1 : 0}|${t}`, `<div style="font-family:var(--clio-font-${o.bold ? "chrome" : "text"});font-size:12px;line-height:16px;color:${o.ink || "#000"}">${hEsc(t)}</div>`, w), t)
25
+ : (o.ink ? `<font color="${o.ink}">${o.bold ? `<b>${hEsc(t)}</b>` : hEsc(t)}</font>` : (o.bold ? `<b>${hEsc(t)}</b>` : hEsc(t)));
26
+
27
+ setMapSeq(0);
28
+ const LW = 200, RW = 468, GAP = 12, NW = LW + GAP + RW;
29
+ const navItems = [["主页", L("index.html")], ["入门", L("beginner.html")], ["硬件指南", L("hardware.html")], ["软件指南", L("software.html")],
30
+ ["Mac 帮助", L("help.html")], ["关于本站", L("about.html")], ["Mac OS X 专区", L("macosx/index.html")], ["安装中文字体", pic("fonts.html")]];
31
+ const nav = cjkImg
32
+ ? img(await block(`nav|${mode}`, navItems.map(([t, h]) => `<div style="line-height:18px">·&nbsp;&nbsp;<span data-href="${h}" style="${linkCss}">${hEsc(t)}</span></div>`).join(""), LW - 2 - 16), "站点导航")
33
+ : navItems.map(([t, h]) => `&middot; <a href="${h}" target="_top">${hEsc(t)}</a>`).join("<br>");
34
+ const tipW = LW - 2 - 16;
35
+ const otherLinks = [["原站首页", ORIGIN], ["English 版", L("index_en.html")]];
36
+ const other = cjkImg
37
+ ? img(await block(`other|${mode}`, `<div style="line-height:16px"><b>其他版本</b><br>${otherLinks.map(([t, h]) => `<span data-href="${h}" style="${linkCss}">${t}</span>`).join("<br>")}</div>`, tipW), "其他版本")
38
+ : `<b>其他版本</b><br>${otherLinks.map(([t, h]) => `<a href="${h}" target="_top">${t}</a>`).join("<br>")}`;
39
+ const textSwitchHref = STATIC_ONLY ? txt("index.html") : `${txt("index.html")}?cjk=text`;
40
+ const imgSwitchHref = STATIC_ONLY ? pic("index.html") : `${pic("index.html")}?cjk=img`;
41
+ const tips = `${await txtRun("IE 4.0 / NS 3.0 以上", tipW)}<br>${await txtRun("800x600 以上", tipW)}<br>${await txtRun("GB2312 编码", tipW)}<br>${sp(1, 8)}<br>` +
42
+ `${other}<br>${sp(1, 8)}<br>` +
43
+ (cjkImg ? `<a href="${textSwitchHref}" target="_top">Chinese fonts installed? Show text</a>`
44
+ : `<a href="${imgSwitchHref}" target="_top">Chinese text garbled? Show it as pictures</a> | <a href="${pic("fonts.html")}" target="_top">Install Chinese fonts</a>`);
45
+
46
+ const shotW = 160, shotH = 120, paraW = RW - 2 - 16 - shotW - 12;
47
+ const launcher = [["i-folder", "主页", L("index.html")], ["i-book", "入门", L("beginner.html")], ["i-drive", "硬件", L("hardware.html")],
48
+ ["i-floppy", "软件", L("software.html")], ["i-help", "帮助", L("help.html")], ["i-globe", "关于", L("about.html")]];
49
+ const launch = img(await block(`launch|${mode}`, `<table style="border-collapse:collapse;width:${RW - 2 - 16}px"><tr>${launcher.map(([i, t, h]) =>
50
+ `<td style="text-align:center;vertical-align:top;padding:0"><span data-href="${h}" style="display:inline-block;${linkCss};line-height:16px"><span style="display:block;width:32px;margin:0 auto 2px">${icon(i)}</span>${hEsc(t)}</span></td>`).join("")}</tr></table>`), "");
51
+ const caption = img(await block("caption", `<div style="color:#666;text-align:center;width:${shotW}px">点击看大图</div>`), "点击看大图");
52
+ const notice = cjkImg
53
+ ? `<table border=0 cellspacing=0 cellpadding=6 width=${RW - 2 - 16} bgcolor="#ffffcc"><tr><td>${img(await block(`notice|${RW - 30}`, `<div style="line-height:16px;background:#ffffcc">未装中文字体时,中文以图片显示,不能复制。<span data-href="${pic("fonts.html")}" style="${linkCss}">安装中文字体</span></div>`, RW - 2 - 16 - 12), "")}<br>` +
54
+ `No Chinese fonts: Chinese is shown as pictures and cannot be copied. <a href="${pic("fonts.html")}" target="_top">How to install Chinese fonts</a> | <a href="${textSwitchHref}" target="_top">I have Chinese fonts: show text</a></td></tr></table>${sp(1, 10)}<br>`
55
+ : "";
56
+ const introParas = [];
57
+ for (const t of (intro.length ? intro : ["如果你从犄角旮旯里翻出了一台老 Macintosh 电脑,先别急着扔掉。"])) {
58
+ introParas.push(await txtRun(t, paraW));
59
+ }
60
+ const main = notice +
61
+ `${img(await head("i-mac", "欢迎造访本站", "中文 Classic Mac OS 资料 · 软件 · 帮助"), "欢迎造访本站")}${sp(1, 8)}<br>` +
62
+ `<table border=0 cellspacing=0 cellpadding=0><tr><td valign=top width=${paraW}>` +
63
+ introParas.join(`<br>${sp(1, 8)}<br>`) +
64
+ `</td><td>${sp(12, 1)}</td><td valign=top align=center width=${shotW}><a href="${ORIGIN}page.png" target="_top"><img src="${BASE}i/page.thumb.gif" width=${shotW - 2} height=${shotH - 2} border=1 alt="本站截图"></a><br>${caption}</td></tr></table>${sp(1, 12)}<br>` +
65
+ `${launch}`;
66
+ const dateW = 84, newsTextW = NW - 2 - 16 - dateW - 8 - 6; // cellpadding=1 on three cells
67
+ const newsRows = [];
68
+ for (const [d, t] of news) {
69
+ newsRows.push(`<tr><td valign=top nowrap width=${dateW}><b>${d}:</b></td><td>${sp(8, 1)}</td><td valign=top width=${newsTextW}>${await txtRun(t, newsTextW)}</td></tr>`);
70
+ }
71
+ const newsHTML = `${img(await head("i-doc", "最新消息", "更新记录,新的在上面"), "最新消息")}${sp(1, 8)}<br><table border=0 cellspacing=0 cellpadding=1>` +
72
+ newsRows.join("") + `</table>`;
73
+
74
+ const prefix = cjkImg ? BASE : `${BASE}t/`;
75
+ for (const activeWin of ["main", "nav", "tips", "news"]) {
76
+ const winHref = w => {
77
+ if (activeWin === w) return "";
78
+ if (STATIC_ONLY) return prefix + (w === "main" ? "index.html" : `win/${w}.html`);
79
+ return prefix + "index.html" + (w === "main" ? "" : `?win=${w}`);
80
+ };
81
+ const rel = (cjkImg ? "" : "t/") + (activeWin === "main" ? "index.html" : `win/${activeWin}.html`);
82
+ const home = await pageShell("Classic Mac 非官方支持站", `<table border=0 cellspacing=0 cellpadding=0>
83
+ <tr><td>${sp(16, 1)}</td><td valign=top width=${LW}>${await windowHTML({ title: "站点导航", width: LW, active: activeWin === "nav", body: nav, titleHref: winHref("nav") })}<br>${await windowHTML({ title: "浏览提示", width: LW, active: activeWin === "tips", body: tips, titleHref: winHref("tips") })}</td>
84
+ <td>${sp(GAP, 1)}</td><td valign=top width=${RW}>${await windowHTML({ title: "Classic Mac 非官方支持站", width: RW, active: activeWin === "main", body: main, titleHref: winHref("main") })}</td></tr>
85
+ <tr><td></td><td colspan=3>${sp(1, 12)}<br>${await windowHTML({ title: "最新消息", width: NW, active: activeWin === "news", body: newsHTML, titleHref: winHref("news") })}<br></td></tr></table>`, "gb2312", rel.replace(/^t\//, ""), mode);
86
+ const buf = encodeOut(home, "gb2312");
87
+ writeOut(rel, buf); frameset(rel, "Classic Mac 非官方支持站", "gb2312");
88
+ if (cjkImg && activeWin === "main") report.push({ page: "index.html", html: buf.length, imgs: new Set([...home.matchAll(/<img src="([^"]+)"/g)].map(m => m[1])).size, total: buf.length });
89
+ }
90
+
91
+ // ---- Font guide ----
92
+ setMapSeq(0);
93
+ const FW = 680, FTW = FW - 2 - 16, nW = 20;
94
+ const zh = async (t, o = {}) => img(await block(`fz|${FTW - nW}|${o.bold ? 1 : 0}|${t}`, `<div style="line-height:16px;font-family:var(--clio-font-${o.bold ? "chrome" : "text"})">${hEsc(t)}</div>`, FTW - nW), t);
95
+ const steps = [
96
+ ["先看系统版本:在苹果菜单里选“关于本机”(或“关于这台电脑”)。", "First check your system version: Apple menu, About This Macintosh (or About This Computer)."],
97
+ ["System 7.1 到 7.6(性能允许建议至少升到 Mac OS 8.1):装 Chinese Language Kit 1.2(68k / PowerPC 通用)。用 StuffIt Expander 解压后,用 Disk Copy 6 挂载 .img 镜像。打开 Installation 里的 Installer,选 Custom Install,勾选 Install Simplified Chinese Language Kit,装完重启。",
98
+ "System 7.1 to 7.6 (Mac OS 8.1+ recommended if hardware permits): Chinese Language Kit 1.2 (68k and PowerPC). StuffIt Expander gives a .img disk image; mount it with Disk Copy 6. Open Installer in Installation, choose Custom Install, tick Install Simplified Chinese Language Kit, install, restart."],
99
+ ["System 7.6 到 Mac OS 8.1:也可以装 Chinese Language Kit 2.0,自带智能 ABC 输入法。不建议装在 Mac OS 8.5 及以后的系统上。",
100
+ "System 7.6 to Mac OS 8.1: Chinese Language Kit 2.0 also works and includes an input method. Not recommended on Mac OS 8.5 or later."],
101
+ ["Mac OS 8.5 / 8.6:安装光盘里的“Multilingual Internet Access”(多语言互联网访问)可以显示中文,但没有输入法。",
102
+ "Mac OS 8.5 / 8.6: Multilingual Internet Access on the install CD displays Chinese (no input method)."],
103
+ ["Mac OS 9:安装光盘的“Software Installers”里有“Language Kits”,用“Install Language Kits”勾选简体中文(Chinese using simplified characters),装完重启。",
104
+ "Mac OS 9: on the install CD, Software Installers, Language Kits, Install Language Kits: tick Chinese using simplified characters, then restart."],
105
+ ["装好后在浏览器编码菜单选“简体中文(GB2312)”,再点“显示文字”。复制到其他程序若乱码,把字体改成宋体(Song)即可。",
106
+ "Afterwards set the browser's encoding to Simplified Chinese (GB2312) and choose Show text. Text pasted into other programs may look garbled until you set a Chinese font such as Song."],
107
+ ];
108
+ const rowList = [];
109
+ for (let i = 0; i < steps.length; i++) {
110
+ const [z, e] = steps[i];
111
+ rowList.push(`<tr><td valign=top width=${nW}><b>${i + 1}.</b></td><td valign=top width=${FTW - nW}>${await zh(z)}<br>${e}<br>${sp(1, 6)}</td></tr>`);
112
+ }
113
+ const rows = rowList.join("");
114
+ const dl = `<table border=0 cellspacing=0 cellpadding=1><tr><td><b>Download</b> (from classicmac.top):</td></tr>` +
115
+ `<tr><td>- <a href="${ORIGIN}downloads/app/CLK-1.2.sit">Chinese Language Kit 1.2</a> (System 7.1 - 7.6)</td></tr>` +
116
+ `<tr><td>- <a href="${ORIGIN}downloads/app/CLK-2.0.sit">Chinese Language Kit 2.0</a> (System 7.6 - Mac OS 8.1)</td></tr>` +
117
+ `<tr><td>- <a href="${L("software.html")}" target="_top">Software guide</a> (Mac OS installers, Chinese fonts)</td></tr></table>`;
118
+ const back = `<a href="${textSwitchHref}" target="_top">Fonts installed: back, show text</a> | <a href="${imgSwitchHref}" target="_top">Back, keep pictures</a>`;
119
+ const fbody = `${img(await head("i-help", "安装中文字体", "安装后即可显示、选取和复制中文"), "安装中文字体")}${sp(1, 6)}<br>` +
120
+ `Install Chinese fonts so Chinese shows as text you can select and copy.${sp(1, 10)}<br>` +
121
+ `<table border=0 cellspacing=0 cellpadding=1>${rows}</table>${sp(1, 6)}<br>${dl}${sp(1, 10)}<br>${back}`;
122
+ const fonts = await pageShell("安装中文字体 - Classic Mac 非官方支持站", `<table border=0 cellspacing=0 cellpadding=0><tr><td>${sp(16, 1)}</td><td>${await windowHTML({ title: "安装中文字体", width: FW, active: true, body: fbody })}</td></tr></table>`, "gb2312", "fonts.html", mode);
123
+ const frel = (cjkImg ? "" : "t/") + "fonts.html", fbuf = encodeOut(fonts, "gb2312");
124
+ writeOut(frel, fbuf); frameset(frel, "安装中文字体", "gb2312");
125
+ if (cjkImg) report.push({ page: "fonts.html", html: fbuf.length, imgs: new Set([...fonts.matchAll(/<img src="([^"]+)"/g)].map(m => m[1])).size, total: fbuf.length });
126
+ }
127
+ }
@@ -0,0 +1,134 @@
1
+ // Edge routing for the static legacy site built by clio.html32.
2
+ // /<page> picture mode /t/<page> text mode
3
+ // /f/<page> Netscape 3 frameset whose frame loads /n/<page> (served here from /<page>)
4
+ // ?cjk=img|text records picture/text preference; ?menu=<key> opens a menu;
5
+ // ?win=main|nav|tips|news switches the active window on index.html;
6
+ // ?era=system6|system7|platinum|drawingboard|nextstep switches the look (from the User-Agent if unset).
7
+ // Pages carry markers (see src/chrome.mjs); for each request the worker rebuilds the menu bar and
8
+ // every window frame from art/eras.json around the same page body.
9
+ import { windowFrame, menuHTML, pageBody } from "../src/chrome.mjs";
10
+
11
+ const ERAS = ["system6", "system7", "platinum", "drawingboard", "nextstep"];
12
+ const YEAR = "path=/; expires=Fri, 31-Dec-2037 23:59:59 GMT";
13
+ let erasCache = null;
14
+ async function getEras(env, u) {
15
+ if (erasCache) return erasCache;
16
+ const r = await env.ASSETS.fetch(new Request(new URL("/art/eras.json", u)));
17
+ if (r.ok) erasCache = await r.json();
18
+ return erasCache;
19
+ }
20
+ function detectEraFromUA(ua) {
21
+ if (/NeXT|OmniWeb|OPENSTEP/i.test(ua)) return "nextstep";
22
+ if (/MacWeb|Mozilla\/[12]\.|68K/i.test(ua)) return "system6";
23
+ if (/(MSIE [45]\.|Mozilla\/4\.|Classilla|iCab)/i.test(ua) && /Mac|PPC/i.test(ua)) return "platinum";
24
+ return "system7";
25
+ }
26
+ // Pages are GB2312/Big5 bytes; latin1 keeps every byte as one char so markup can be edited safely.
27
+ function toLatin1(bytes) {
28
+ let s = "";
29
+ for (let i = 0; i < bytes.length; i += 8192) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192));
30
+ return s;
31
+ }
32
+ function fromLatin1(s) {
33
+ const res = new Uint8Array(s.length);
34
+ for (let i = 0; i < s.length; i++) res[i] = s.charCodeAt(i) & 0xff;
35
+ return res;
36
+ }
37
+ const sp = (w, h) => `<img src="/art/sp.gif" width=${w} height=${h} alt="">`;
38
+
39
+ function rebuild(html, cfg, { path, win, menuKey, subst, fallback }) {
40
+ let out = html.replace(/<body bgcolor="[^"]*"(?:\s+background="[^"]*")?/i,
41
+ `<body bgcolor="${cfg.deskBg}"${cfg.deskTile ? ` background="${cfg.deskTile}"` : ""}`);
42
+ out = out.replace(/<!--W k=(\w+)(?: h=(\S+))? a=(\d) w=(\d+)-->([\s\S]*?)<!--\/W-->/g, (all, key, titleHref, a, w, block) => {
43
+ const parts = cfg.titles?.[key], body = block.match(/<!--B-->([\s\S]*)<!--\/B-->/);
44
+ if (!parts || !body) return all;
45
+ const alt = (block.match(/<img [^>]*alt="([^"]*)"/) || [])[1] || "";
46
+ return windowFrame(cfg.frame, { key, width: +w, active: a === "1", head: parts.head, foot: parts.foot, body: body[1],
47
+ titleHref: titleHref || "", alt: alt.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&amp;/g, "&"), sp });
48
+ });
49
+ const L = out.indexOf("<!--L-->"), Le = out.indexOf("<!--/L-->"), P = out.indexOf("<!--P-->"), Pe = out.indexOf("<!--/P-->");
50
+ if (L < 0 || Le < 0 || P < 0 || Pe < 0) return out;
51
+ const inner = out.slice(P + 8, Pe);
52
+ const open = menuKey && cfg.menus?.[menuKey];
53
+ const menu = open
54
+ ? menuHTML(cfg, { layout: cfg.layout, bar: open.bar, drop: open.drop, href: subst, sp, fallback })
55
+ : menuHTML(cfg, { layout: cfg.layout, bar: { ...cfg.closedBar, areas: cfg.closedBar.boxes.map(b => ({ ...b, href: `${path}?${win ? `win=${win}&` : ""}menu=${b.key}` })) }, sp });
56
+ return out.slice(0, L) + pageBody(cfg.layout, menu, inner, sp) + out.slice(Le + 9);
57
+ }
58
+
59
+ export default {
60
+ async fetch(req, env) {
61
+ const u = new URL(req.url), h = req.headers, ua = h.get("user-agent") || "";
62
+ let path = u.pathname === "/" ? "/index.html" : u.pathname;
63
+ const isPage = /\.html?$/i.test(path) && path !== "/blank.html";
64
+ const asset = p => env.ASSETS.fetch(new Request(new URL(p, u), req));
65
+
66
+ const inFrame = path.startsWith("/n/");
67
+ if (inFrame) path = path.slice(2);
68
+ if (!isPage || /^\/(f|g|i|art)\//.test(path)) return asset(path);
69
+
70
+ const cookieHeader = h.get("cookie") || "";
71
+ const q = u.searchParams.get("cjk");
72
+ const cjkCookie = cookieHeader.match(/(?:^|;\s*)cjk=(img|text)/)?.[1];
73
+ const choice = q === "img" || q === "text" ? q : cjkCookie;
74
+ const zh = /\bzh\b/i.test(h.get("accept-language") || "") || /\[zh/i.test(ua);
75
+
76
+ const qEra = u.searchParams.get("era");
77
+ const eraCookie = cookieHeader.match(/(?:^|;\s*)era=(system6|system7|platinum|drawingboard|nextstep)/)?.[1];
78
+ const era = ERAS.includes(qEra) ? qEra : (eraCookie || detectEraFromUA(ua));
79
+
80
+ const cookies = [];
81
+ if (q === "img" || q === "text") cookies.push(`cjk=${q}; ${YEAR}`);
82
+ if (ERAS.includes(qEra)) cookies.push(`era=${qEra}; ${YEAR}`);
83
+
84
+ if (!inFrame && !path.startsWith("/t/") && (choice === "text" || (!choice && zh))) {
85
+ const headers = new Headers({ Location: "/t" + path + u.search });
86
+ for (const c of cookies) headers.append("Set-Cookie", c);
87
+ return new Response(null, { status: 302, headers });
88
+ }
89
+
90
+ const isNS3 = /^Mozilla\/[23]\./.test(ua) && !/MSIE/.test(ua);
91
+ const needFrameset = !inFrame && isNS3;
92
+ if (needFrameset && u.search) {
93
+ const frameHTML = `<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN"><html><head><title>Classic Mac</title></head>` +
94
+ `<frameset rows="100%,*" border=0 frameborder=0 framespacing=0><frame src="/n${path}${u.search}" marginwidth=1 marginheight=1 scrolling=auto noresize><frame src="/blank.html" scrolling=no noresize></frameset></html>`;
95
+ const headers = new Headers({ "Content-Type": "text/html; charset=iso-8859-1", "Cache-Control": "no-cache", Vary: "User-Agent, Accept-Language, Cookie" });
96
+ for (const c of cookies) headers.append("Set-Cookie", c);
97
+ return new Response(frameHTML, { status: 200, headers });
98
+ }
99
+
100
+ const rawWin = u.searchParams.get("win");
101
+ const win = rawWin === "nav" || rawWin === "tips" || rawWin === "news" ? rawWin : "";
102
+ let assetPath = path;
103
+ if (win && (path === "/index.html" || path === "/t/index.html")) {
104
+ assetPath = (path.startsWith("/t/") ? "/t" : "") + `/win/${win}.html`;
105
+ }
106
+
107
+ const res = await asset(needFrameset ? "/f" + assetPath : assetPath);
108
+ let body = res.body;
109
+ const data = !needFrameset && res.ok ? await getEras(env, u) : null;
110
+ const cfg = data?.eras?.[era];
111
+ if (cfg) {
112
+ const menuKey = u.searchParams.get("menu");
113
+ const rawPage = path.replace(/^\/t\//, "/");
114
+ const keep = win ? `win=${win}` : "";
115
+ const subst = href => {
116
+ if (href === "__CLOSE_MENU__") return path + (keep ? `?${keep}` : "");
117
+ if (href === "__IMG_MODE__") return `${rawPage}?cjk=img`;
118
+ if (href === "__TEXT_MODE__") return `/t${rawPage}?cjk=text`;
119
+ if (href === "__ORIGIN_PAGE__") return `http://classicmac.top${rawPage}`;
120
+ if (href.startsWith("__ERA_")) return `${path}?era=${href.slice(6, -2)}${keep ? `&${keep}` : ""}`;
121
+ if (href.startsWith("?menu=")) return `${path}?${keep ? `${keep}&` : ""}${href.slice(1)}`;
122
+ return href;
123
+ };
124
+ const html = rebuild(toLatin1(new Uint8Array(await res.arrayBuffer())), cfg, { path, win, menuKey, subst, fallback: isNS3 });
125
+ body = fromLatin1(html);
126
+ }
127
+
128
+ const out = new Response(body, res);
129
+ for (const c of cookies) out.headers.append("Set-Cookie", c);
130
+ out.headers.set("Cache-Control", "no-cache");
131
+ out.headers.set("Vary", "User-Agent, Accept-Language, Cookie");
132
+ return out;
133
+ },
134
+ };