feat: show the wanted list as a plain table

File name, size, CRC32, MD5 and SHA1, a header row per system, firmware and required first, filtered by name or hash. Each name links its emulator card, else its setup page. Rows carry no upload button: the drop box does that. wanted.json keeps only what the table and the drop box read.
This commit is contained in:
Abdessamad Derraz committed 2026-11-13 19:54:20 +01:00
1 parent 6ce6469d25
commit b1e8de7124
5 files changed
+193 -324

No files matched your search

+14 -1
View File
@@ -5914,6 +5914,19 @@ def _emulator_card_anchor(emulator: str, files: list, index: int) -> str:
return cached[1][index] if 0 <= index < len(cached[1]) else ""
def _wanted_link(profiles: dict) -> Callable[[str, str, dict], str]:
"""The page a row of the wanted list links: an emulator entry's card,
where its notes, hashes and source line are, else the setup's page."""
def link(kind: str, key: str, entry: dict) -> str:
files = (profiles.get(key) or {}).get("files") or [] if kind == "emulator" else []
index = next((i for i, f in enumerate(files) if f is entry), -1)
anchor = _emulator_card_anchor(key, files, index) if index >= 0 else ""
if anchor:
return f"emulators/{emulator_card_page(key, anchor)}/#{anchor}"
return sitewanted.reader_page(kind, key, entry)
return link
def _emulator_links(sha1: str, consumers: FileConsumers) -> list[str]:
"""Each emulator reading the file, linked to the entry that reads it.
@@ -12830,7 +12843,7 @@ def _generate(args: argparse.Namespace) -> None:
wanted = sitewanted.build_wanted(
profiles, coverages, gap_report, db, placer, system_name,
sitewanted.load_ledger(archive_build.ARCHIVES_FILE),
sitewanted.catalog_listings(provenance_report, _PROVENANCE_LABELS),
_wanted_link(profiles),
)
(public / "data").mkdir(parents=True, exist_ok=True)
write_if_changed(str(public / sitewanted.DATA_FILE),
+31 -50
View File
@@ -18,7 +18,7 @@ from __future__ import annotations
import re
import urllib.parse
from collections.abc import Callable, Iterable, Mapping
from collections.abc import Callable, Iterable
from pathlib import Path
import archive_build
@@ -259,22 +259,6 @@ NOT_SHAREABLE = re.compile("|".join([
def shareable(reason: str) -> bool:
"""False when a reason says no copy of the file can be shared."""
return not NOT_SHAREABLE.search(reason)
# What a row says the file is: the first sentence of the declaration's
# description or note, cut at a word past this many characters.
DESCRIPTION_LIMIT = 160
SENTENCE_END = re.compile(r"(?:(?<=\w\w[.!?])|(?<=[)\]][.!?]))\s+(?=[A-Z])")
def first_sentence(text: object, limit: int = DESCRIPTION_LIMIT) -> str:
"""The first sentence of a description, on one line and at most about
*limit* characters."""
flat = " ".join(str(text or "").replace("`", "").split())
end = SENTENCE_END.search(flat)
if end:
flat = flat[:end.start()]
if len(flat) > limit:
flat = flat[:limit].rsplit(" ", 1)[0].rstrip(",;:(") + "..."
return flat
def _settle_cut(records: list[dict]) -> None:
@@ -354,6 +338,12 @@ def _order(record: dict) -> tuple:
record["name"].casefold(), sorted(record["readers"]))
def reader_page(kind: str, key: str, entry: dict) -> str:
"""Where a reader's page is, below the site root: the page a row of
the list links when no card anchor is given."""
return f"{'emulators' if kind == 'emulator' else 'platforms'}/{key}/"
def build_wanted(
profiles: dict,
coverages: dict,
@@ -362,20 +352,20 @@ def build_wanted(
placer: Placer,
system_name: Callable[[str], str],
ledger: Iterable[dict] = (),
catalogued: Mapping[tuple[str, str], list[tuple[str, str]]] | None = None,
link: Callable[[str, str, dict], str] = reader_page,
) -> dict:
"""The wanted list, compact, as public/data/wanted.json carries it.
Readers, systems and folders are written once and named by position.
An entry: n name, h hashes (absent when the declarations write none:
the file is known by its name only), w readers, s systems, r required,
z sizes, k 1 when no core reads it and 2 for game data (firmware when
absent), d what the file is, u why
it is not collected yet, l the catalogs that list it with the name
they give it, f folder, t the name it is uploaded under, v that name
the file is known by its name only), c a crc32 a declaration writes
beside a stronger hash (shown, never matched), w readers, s systems,
r required, z sizes, a the page holding its details (*link*: the card
of the first emulator that reads it, else the page of the first setup
that lists it), f folder, t the name it is uploaded under, v that name
goes to the folder's .variants/ with the first 8 characters of its
sha1. Entries come most useful first. A file no one can share (the
reason says so, NOT_SHAREABLE) is left out.
sha1. Entries come most useful first (_order). A file no one can share
(the reason says so, NOT_SHAREABLE) is left out.
"""
held = Held(db, ledger)
records: dict[tuple, dict] = {}
@@ -394,8 +384,8 @@ def build_wanted(
record = records.setdefault(key, {
"name": declaration["name"], "hashes": {a: list(v) for a, v in hashes.items()},
"sizes": sizes, "systems": set(), "required": False, "readers": set(),
"description": "", "reason": "", "listed": [], "category": GAME_DATA,
"directory": declaration["directory"],
"category": GAME_DATA, "directory": declaration["directory"],
"crc": set(), "links": {},
})
if RANK[declaration["category"]] < RANK[record["category"]]:
record["category"] = declaration["category"]
@@ -403,14 +393,9 @@ def build_wanted(
record["systems"].add(declaration["system"])
record["required"] = record["required"] or declaration["required"]
record["readers"].add(declaration["reader"])
record["description"] = record["description"] or first_sentence(
entry.get("description") or entry.get("note"))
record["reason"] = record["reason"] or first_sentence(declaration["reason"])
record["crc"] |= {v.zfill(8) for v in parse_hash_list(entry.get("crc32")) if len(v) <= 8}
kind, reader_key, _label = declaration["reader"]
if kind == "emulator":
for where in (catalogued or {}).get((reader_key, declaration["name"].casefold()), []):
if where not in record["listed"]:
record["listed"].append(where)
record["links"].setdefault((kind != "emulator", reader_key), link(kind, reader_key, entry))
_merge_named(records)
ordered = sorted(records.values(), key=_order)
_settle_cut(ordered)
@@ -432,6 +417,8 @@ def build_wanted(
item: dict = {"n": record["name"]}
if record["hashes"]:
item["h"] = {algo: record["hashes"][algo] for algo in ALGORITHMS if algo in record["hashes"]}
if record["crc"] and "crc32" not in record["hashes"]:
item["c"] = sorted(record["crc"])
item["w"] = sorted(reader_at[reader] for reader in record["readers"])
systems = sorted({title_at[system_name(s)] for s in record["systems"]})
if systems:
@@ -440,13 +427,7 @@ def build_wanted(
item["r"] = 1
if record["sizes"]:
item["z"] = record["sizes"]
if RANK[record["category"]]:
item["k"] = RANK[record["category"]]
for field, value in (("d", record["description"]), ("u", record["reason"])):
if value:
item[field] = value
if record["listed"]:
item["l"] = [list(where) for where in record["listed"]]
item["a"] = record["links"][min(record["links"])]
if spot.folder:
item["f"] = folder_at[spot.folder]
if spot.name:
@@ -482,11 +463,11 @@ def _merge_named(records: dict[tuple, dict]) -> None:
target = targets[0]
target["readers"] |= record["readers"]
target["required"] = target["required"] or record["required"]
target["description"] = target["description"] or record["description"]
target["reason"] = target["reason"] or record["reason"]
target["crc"] |= record["crc"]
for where, href in record["links"].items():
target["links"].setdefault(where, href)
if RANK[record["category"]] < RANK[target["category"]]:
target["category"] = record["category"]
target["listed"] += [w for w in record["listed"] if w not in target["listed"]]
def load_ledger(path: Path) -> list[dict]:
@@ -496,7 +477,8 @@ def load_ledger(path: Path) -> list[dict]:
def page(total: int, known: int) -> str:
"""The wanted page: the drop box, the steps from a file in hand to a
file in the collection, then every wanted file (WantedList.astro).
file in the collection, then the table of every wanted file
(WantedList.astro).
Held to the Start here budgets (tests/test_site_copy.py): anyone with a
file in hand reads it.
@@ -521,13 +503,12 @@ def page(total: int, known: int) -> str:
"- An old SD card, or the BIOS folder of an emulator used before.",
"- A firmware update package from the maker.",
"",
"When a catalog lists a file, its row in the list names it.",
"To check any other file, use [Find or check a file](files/index.md).",
"",
"## Send it",
"",
"1. Make a free GitHub account once: [sign up](https://github.com/signup).",
"2. Press the upload button of the file. GitHub opens the right folder.",
"2. Drop the file at the top. If it is wanted, its button opens the right folder on GitHub.",
"3. Rename the file if the page asks, then drop it there.",
"4. GitHub makes a copy of the project and opens a pull request, a request to add the file.",
"5. A check reads the file and comments on the request.",
@@ -539,10 +520,10 @@ def page(total: int, known: int) -> str:
"",
"## The wanted list",
"",
(f"The list holds {total:,} files, firmware first and game data last. Of these, {known:,} have a "
"fingerprint (a hash), so a dropped copy is recognised."),
(f"{total:,} files, firmware first and game data last. A name opens its details. "
f"{known:,} have a fingerprint (a hash), so a dropped copy is recognised."),
"",
"The others are known by name only: upload one and the check decides.",
"The others are known by name only: a dropped file of that name gets a button too.",
"",
"<WantedList />",
"",
+70 -49
View File
@@ -188,20 +188,21 @@ class TheListHoldsWhatTheGapsReportLacks(_World):
for name in ("nohash.bin", "z.zip"):
with self.subTest(name=name):
self.assertNotIn("h", self.entry(name))
self.assertEqual(self.entry("nohash.bin")["d"], "A boot ROM.")
self.assertIn("h", self.entry("b.bin"))
# The world's categories: g.bin is game data, cut.bin a file a
# platform lists and no core reads, the others firmware.
KIND = {"g.bin": 2, "cut.bin": 1}
def test_required_entries_come_first(self):
firmware = [e for e in self.data["entries"] if not e.get("k")]
firmware = [e for e in self.data["entries"] if e["n"] not in self.KIND]
needs = [bool(e.get("r")) for e in firmware]
self.assertEqual(needs, sorted(needs, reverse=True))
self.assertTrue(any(needs) and not all(needs))
def test_firmware_comes_before_game_data(self):
kinds = [e.get("k", 0) for e in self.data["entries"]]
kinds = [self.KIND.get(e["n"], 0) for e in self.data["entries"]]
self.assertEqual(kinds, sorted(kinds))
self.assertEqual(self.entry("g.bin")["k"], 2)
self.assertEqual(self.entry("cut.bin")["k"], 1)
# g.bin is required, and still after every optional firmware file.
self.assertEqual(self.data["entries"][-1]["n"], "g.bin")
self.assertEqual(self.entry("g.bin").get("r"), 1)
@@ -248,10 +249,10 @@ class TheListHoldsWhatTheGapsReportLacks(_World):
("b.bin", (("sha1", ("x",)),), ()): {
"name": "b.bin", "hashes": {"sha1": ["x"]}, "systems": {"x"}, "required": False,
"readers": {("emulator", "engine", "Engine")}, "description": "",
"reason": "", "listed": [], "category": sitewanted.GAME_DATA},
"category": sitewanted.GAME_DATA, "crc": set(), "links": {(False, "engine"): "e"}},
("b.bin", "x", ""): {
"name": "b.bin", "hashes": {}, "systems": {"x"}, "required": True,
"readers": {reader}, "description": "B", "reason": "", "listed": [],
"readers": {reader}, "crc": {"1234abcd"}, "links": {(False, "other"): "o"},
"category": sitewanted.BIOS},
}
sitewanted._merge_named(records)
@@ -271,21 +272,38 @@ class TheListHoldsWhatTheGapsReportLacks(_World):
str, self.ledger)
self.assertNotIn("<serial>.txt", [e["n"] for e in data["entries"]])
def test_a_catalog_listing_reaches_its_entry(self):
listings = sitewanted.catalog_listings(
{"tosec": {"missing": [{"name": "Boot (1990)", "romsets": [],
"needed_by": [{"emulator": "engine", "name": "b.bin"}]}]}},
{"tosec": "TOSEC"})
data = sitewanted.build_wanted(self.profiles, self.coverages, self.gap_report, self.db,
self.placer, str, self.ledger, listings)
self.assertEqual(next(e for e in data["entries"] if e["n"] == "b.bin")["l"],
[["TOSEC", "Boot (1990)"]])
def test_every_name_links_its_details(self):
"""An emulator's entry links its card, a file only a setup lists
links that setup's page."""
seen = []
def test_first_sentence(self):
self.assertEqual(sitewanted.first_sentence("One. Two."), "One.")
self.assertEqual(sitewanted.first_sentence("Ver. 1.0 of A"), "Ver. 1.0 of A")
cut = sitewanted.first_sentence("word " * 60)
self.assertTrue(cut.endswith("...") and len(cut) <= sitewanted.DESCRIPTION_LIMIT + 3)
def link(kind: str, key: str, entry: dict) -> str:
seen.append((kind, key, entry["name"]))
return f"{kind}/{key}/#{entry['name']}"
data = sitewanted.build_wanted(self.profiles, self.coverages, self.gap_report, self.db,
self.placer, str, self.ledger, link)
links = {e["n"]: e["a"] for e in data["entries"]}
self.assertEqual(links["b.bin"], "emulator/engine/#b.bin")
self.assertEqual(links["v.bin"], "platform/plat/#v.bin")
self.assertTrue(all(e["a"] for e in data["entries"]))
self.assertEqual(sitewanted.reader_page("platform", "plat", {}), "platforms/plat/")
def test_a_crc32_beside_a_stronger_hash_is_shown_not_matched(self):
profiles = {"engine": {**self.profiles["engine"], "files": [
{**f, "crc32": crc(WANTED)} if f["name"] == "b.bin" else f
for f in self.profiles["engine"]["files"]]}}
data = sitewanted.build_wanted(profiles, self.coverages, self.gap_report, self.db,
self.placer, str, self.ledger)
entry = next(e for e in data["entries"] if e["n"] == "b.bin")
self.assertEqual(entry["h"], {"sha1": [sha1(WANTED)]})
self.assertEqual(entry["c"], [crc(WANTED)])
def test_the_list_carries_only_what_the_table_and_the_drop_box_read(self):
allowed = {"n", "h", "c", "w", "s", "r", "z", "a", "f", "t", "v"}
for entry in self.data["entries"]:
with self.subTest(entry=entry["n"]):
self.assertLessEqual(set(entry), allowed)
def test_an_entry_carries_its_readers_system_and_need(self):
entry = self.entry("b.bin")
@@ -450,28 +468,6 @@ class ThePageReadsTheListAsTheResolverDoes(_World):
self.assertEqual(variant, {"folder": "bios/Maker/Console/.variants/",
"name": f"v.bin.{sha1(VARIANT)[:8]}"})
def test_every_row_uploads_to_the_reviews_folder(self):
"""The list's own button on each row, against validate_pr.placement
for the declarations of that row."""
rows = json.loads(_node(
f"import {{ rowTarget, uploadUrl }} from {json.dumps(WANTED_TS.as_uri())};"
f"const data = {json.dumps(self.data)};"
"console.log(JSON.stringify(data.entries.map((e) => {"
" const place = rowTarget(data, e); return {...place, url: uploadUrl(data, place.folder)}; })));"
))
self.assertEqual(len(rows), len(self.data["entries"]))
for entry, place in zip(self.data["entries"], rows):
spot = self.placer.place(entry.get("h", {}), entry["n"], ["x"])
folder = (spot.folder or "bios/") + (".variants/" if spot.variant else "")
with self.subTest(entry=entry["n"]):
self.assertEqual(place["folder"], folder)
self.assertEqual(place["url"], sitewanted.upload_href(sitewanted.UPLOAD_ROOT, folder))
if spot.variant:
self.assertEqual(place["name"], f"{spot.name}.{entry['h']['sha1'][0][:8]}"
if len(entry.get("h", {}).get("sha1", [])) == 1 else "")
else:
self.assertEqual(place["name"], spot.name or entry["n"])
def test_a_dropped_file_meets_a_name_only_entry_by_its_name(self):
out = json.loads(_node(
f"import {{ byName, matches }} from {json.dumps(WANTED_TS.as_uri())};"
@@ -517,6 +513,19 @@ class ThePageSpeaksWithoutPronouns(unittest.TestCase):
self.assertTrue(texts)
self.assertEqual([t for t in texts if pronouns(t)], [])
def test_a_simple_table(self):
"""File name, size and the three hashes, a name linked to its
details: nothing else on a row."""
source = (COMPONENTS / "WantedList.astro").read_text(encoding="utf-8")
head = re.search(r"<thead>(.*?)</thead>", source, re.S)[1]
self.assertEqual(re.findall(r"<th[^>]*>([^<]*)</th>", head),
["File name", "Size", "CRC32", "MD5", "SHA1"])
script = source[source.index("<script>"):source.index("</script>")]
self.assertIn("name.href = `${base}${entry.a}`;", script)
for gone in ("entry.d", "entry.u", "entry.l", "entry.r", "entry.w", "Upload", "rb-badge",
"Copy"):
self.assertNotIn(gone, script)
def test_the_page_lists_the_steps(self):
text = sitewanted.page(1_165, 199)
for step in ("<WantedFiles />", "<WantedList />", "https://github.com/signup",
@@ -580,12 +589,7 @@ class ThePublishedList(unittest.TestCase):
with self.subTest(entry=entry["n"]):
self.assertFalse(held.holds(entry["h"], entry.get("z", [])))
def test_firmware_first_then_required_first(self):
kinds = [e.get("k", 0) for e in self.data["entries"]]
self.assertEqual(kinds, sorted(kinds))
for kind in (0, 1, 2):
needs = [bool(e.get("r")) for e in self.data["entries"] if e.get("k", 0) == kind]
self.assertEqual(needs, sorted(needs, reverse=True))
def test_name_only_entries_are_kept(self):
self.assertTrue(any("h" not in e for e in self.data["entries"]))
def test_every_folder_is_the_reviews(self):
@@ -608,6 +612,23 @@ class ThePublishedList(unittest.TestCase):
def test_weight(self):
self.assertLess(PUBLISHED.stat().st_size, 200_000)
def test_every_link_lands_on_its_details(self):
"""Each name's link is a built page, and a card anchor is on it."""
dist = WEBSITE / "dist"
if not dist.is_dir():
self.skipTest("no built site")
pages: dict[str, str] = {}
for entry in self.data["entries"]:
path, _, anchor = entry["a"].partition("#")
html = pages.get(path)
if html is None:
built = dist / path / "index.html"
html = pages[path] = built.read_text(encoding="utf-8") if built.is_file() else ""
with self.subTest(entry=entry["n"], link=entry["a"]):
self.assertTrue(html)
if anchor:
self.assertIn(f'id="{anchor}"', html)
def test_the_built_page_asks_for_this_list(self):
"""The list's address carries its version: a browser that cached an
older list (another shape) fetches this one."""
+76 -193
View File
@@ -1,9 +1,9 @@
---
// Every file of public/data/wanted.json (scripts/sitewanted.py), by system,
// most useful first. The list is fetched when the page runs, never written
// in the HTML: a group's rows are drawn when it opens or a filter reaches
// it. Each row carries its own upload button, to the folder
// validate_pr.placement() gives (wanted.ts rowTarget).
// Every file of public/data/wanted.json (scripts/sitewanted.py) in one
// table, a header row per system, most useful first: what someone needs
// to search for a file. The list is fetched when the page runs, never
// written in the HTML. A name links to the page holding the file's
// details, and an upload starts from the drop box above.
import { wantedVersion } from '../scripts/wanted-version.ts';
const base = import.meta.env.BASE_URL.replace(/\/?$/, '/');
@@ -14,17 +14,20 @@ const version = wantedVersion();
<div class="rb-table-filter rb-wanted-filter" hidden data-pagefind-ignore="all">
<label for="rb-wanted-filter">Filter the list</label>
<input id="rb-wanted-filter" type="search" autocomplete="off"
placeholder="Name, system, emulator, setup" aria-describedby="rb-wanted-filter-count" />
placeholder="Name or hash" aria-describedby="rb-wanted-filter-count" />
<span id="rb-wanted-filter-count" class="rb-table-filter-count" aria-live="polite"></span>
</div>
<p class="rb-wanted-state">The list loads with the page. Without JavaScript, the <a href={`${base}gaps/`}>gaps page</a> lists the same files.</p>
<div class="rb-wanted-groups"></div>
<div class="rb-wanted-scroll">
<table class="rb-wanted-table" hidden>
<thead><tr><th scope="col">File name</th><th scope="col">Size</th><th scope="col">CRC32</th><th scope="col">MD5</th><th scope="col">SHA1</th></tr></thead>
</table>
</div>
</div>
<script>
import { type Entry, type Wanted, loadWanted, rowIssueUrl, rowTarget, tooLarge, uploadUrl } from '../scripts/wanted.ts';
import { type Entry, loadWanted } from '../scripts/wanted.ts';
const LABELS: Record<string, string> = { sha1: 'SHA-1', sha256: 'SHA-256', md5: 'MD5', crc32: 'CRC32' };
const OTHER = 'Other files';
const size = (bytes: number) =>
@@ -37,19 +40,16 @@ const version = wantedVersion();
node.append(...content);
return node;
};
const code = (text: string) => element('code', text);
const listed = (nodes: Node[]) =>
nodes.flatMap((node, i) => (i === 0 ? [node] : [i === nodes.length - 1 ? ' and ' : ', ', node]));
const plural = (count: number, noun: string) => `${count.toLocaleString('en')} ${noun}${count === 1 ? '' : 's'}`;
// A system's fold: its entries, those the filter keeps, and those drawn.
type Group = {
title: string; entries: Entry[]; required: number;
details: HTMLDetailsElement; list: HTMLOListElement;
found: Entry[]; drawn: Entry[] | null;
// One value per line, as plain text to select and copy.
const hashCell = (values: string[] = []) => {
const cell = element('td');
values.forEach((value, i) => {
if (i) cell.append(element('br'));
cell.append(element('code', value));
});
return cell;
};
// A filter that keeps this many rows or fewer in a system opens it.
const OPEN_AT = 50;
for (const root of document.querySelectorAll<HTMLElement>('.rb-wanted-browse')) {
const base = root.dataset.base ?? '/';
@@ -58,199 +58,82 @@ const version = wantedVersion();
const input = root.querySelector<HTMLInputElement>('#rb-wanted-filter')!;
const count = root.querySelector<HTMLElement>('#rb-wanted-filter-count')!;
const state = root.querySelector<HTMLElement>('.rb-wanted-state')!;
const holder = root.querySelector<HTMLElement>('.rb-wanted-groups')!;
const link = (href: string, text: string) => {
const a = element('a', text);
a.href = href;
return a;
};
const row = (data: Wanted, entry: Entry): HTMLLIElement => {
const head = element('p', code(entry.n), ' ');
const need = element('span', entry.r ? 'Required' : 'Optional');
need.className = `rb-badge ${entry.r ? 'rb-badge-warning' : 'rb-badge-muted'}`;
const kind = element('span', entry.k === 2 ? 'Game data' : entry.k === 1 ? 'Read by no core' : 'Firmware');
kind.className = 'rb-badge rb-badge-info';
head.append(need, ' ', kind);
if (entry.z?.length) head.append(` ${entry.z.map(size).join(' or ')}`);
head.className = 'rb-wanted-row-head';
const item = element('li', head);
item.className = 'rb-wanted-row';
if (entry.d) item.append(element('p', entry.d));
const systems = (entry.s ?? []).map((index) => data.systems[index]);
const readers = entry.w.map((index) => {
const [kind, key, label] = data.readers[index];
return link(`${base}${kind === 'p' ? 'platforms' : 'emulators'}/${key}/`, label);
});
item.append(element('p', ...(systems.length ? [`For ${systems.join(', ')}. `] : []),
entry.r ? 'Needed by ' : 'Used by ', ...listed(readers), '.'));
if (entry.u) item.append(element('p', 'Not collected yet: ', entry.u.replace(/\.?$/, '.')));
for (const [where, name] of entry.l ?? []) item.append(element('p', `Listed in ${where} as `, code(name), '.'));
if (entry.h) {
const hashes = element('dl');
hashes.className = 'rb-wanted-hashes';
for (const [algo, values] of Object.entries(entry.h)) {
for (const value of values ?? []) {
const copy = element('button', 'Copy');
copy.type = 'button';
copy.className = 'rb-copy rb-wanted-copy';
copy.dataset.value = value;
copy.setAttribute('aria-label', `Copy the ${LABELS[algo]} of ${entry.n}`);
hashes.append(element('dt', LABELS[algo]), element('dd', code(value), copy));
}
}
item.append(hashes);
} else {
const note = element('p', 'No fingerprint in the list: the file is known by its name only. The check after the upload decides.');
note.className = 'rb-wanted-named';
item.append(note);
}
if (tooLarge(data, entry)) {
const issue = link(rowIssueUrl(data, entry), 'Open an issue');
issue.className = 'rb-button';
issue.target = '_blank';
issue.rel = 'noopener';
item.append(element('p', `Over ${size(data.limit)}, too large for the upload page. `, issue));
return item;
}
const place = rowTarget(data, entry);
const button = link(uploadUrl(data, place.folder), `Upload to ${place.folder}`);
button.className = 'rb-button rb-wanted-upload';
button.target = '_blank';
button.rel = 'noopener';
const naming = place.name
? ['Upload it as ', code(place.name), '.']
: ['Drop it above first: its name in that folder ends with part of its fingerprint.'];
item.append(element('p', ...naming), element('p', button));
return item;
};
const words = (text: string) => text.toLowerCase().split(/\s+/).filter(Boolean);
const draw = (data: Wanted, group: Group) => {
if (group.drawn === group.found) return;
group.list.replaceChildren(...group.found.map((entry) => row(data, entry)));
group.drawn = group.found;
};
const show = (data: Wanted, groups: Group[], haystack: Map<Entry, string>) => {
const query = words(input.value);
let rows = 0;
let visible = 0;
for (const group of groups) {
const title = group.title.toLowerCase();
group.found = query.length
? group.entries.filter((entry) => query.every((word) => haystack.get(entry)!.includes(word) || title.includes(word)))
: group.entries;
group.details.hidden = !group.found.length;
if (group.found.length) visible += 1;
rows += group.found.length;
if (query.length) group.details.open = group.found.length > 0 && group.found.length <= OPEN_AT;
if (group.details.open) draw(data, group);
}
count.textContent = query.length
? `${plural(rows, 'row')} in ${plural(visible, 'system')}`
: `${plural(data.entries.length, 'file')} in ${plural(groups.length, 'system')}`;
};
const table = root.querySelector<HTMLTableElement>('.rb-wanted-table')!;
loadWanted(base, version).then((data) => {
const row = (entry: Entry) => {
const name = element('a', entry.n);
name.href = `${base}${entry.a}`;
const tr = element('tr', element('td', name), element('td', (entry.z ?? []).map(size).join(' or ')),
hashCell(entry.h?.crc32 ?? entry.c), hashCell(entry.h?.md5), hashCell(entry.h?.sha1));
tr.dataset.find = [entry.n, ...Object.values(entry.h ?? {}).flat(), ...(entry.c ?? [])].join(' ').toLowerCase();
return tr;
};
// The list comes most useful first (sitewanted._order): a system
// comes where its first file does, and its rows keep that order.
const bySystem = new Map<string, Entry[]>();
for (const entry of data.entries) {
const titles = entry.s?.length ? entry.s.map((index) => data.systems[index]) : [OTHER];
for (const title of titles) {
for (const title of entry.s?.length ? entry.s.map((index) => data.systems[index]) : [OTHER]) {
if (!bySystem.has(title)) bySystem.set(title, []);
bySystem.get(title)!.push(entry);
}
}
const haystack = new Map(data.entries.map((entry) => [entry, [
entry.n, entry.d ?? '', ...(entry.s ?? []).map((index) => data.systems[index]),
...entry.w.map((index) => data.readers[index][2]),
].join(' ').toLowerCase()]));
// The list comes most useful first (sitewanted._order): a system
// comes where its first file does, and its rows keep that order.
const groups: Group[] = [...bySystem].map(([title, entries]) => {
const required = entries.filter((entry) => entry.r).length;
const summary = element('summary', element('span', title), ' ');
const counted = element('span', `${plural(entries.length, 'file')}${required ? `, ${required.toLocaleString('en')} required` : ''}`);
counted.className = 'rb-wanted-group-count';
summary.append(counted);
const list = element('ol');
list.className = 'rb-wanted-rows';
const details = element('details', summary, list);
details.className = 'rb-wanted-group';
return { title, entries, required, details, list, found: entries, drawn: null };
const groups = [...bySystem].map(([title, entries]) => {
const head = element('th', title);
head.colSpan = 5;
head.scope = 'colgroup';
const body = element('tbody', element('tr', head), ...entries.map(row));
return { title: title.toLowerCase(), body, rows: [...body.rows].slice(1) };
});
for (const group of groups) {
group.details.addEventListener('toggle', () => {
if (group.details.open) draw(data, group);
});
}
holder.replaceChildren(...groups.map((group) => group.details));
table.append(...groups.map((group) => group.body));
const show = () => {
const words = input.value.toLowerCase().split(/\s+/).filter(Boolean);
let shown = 0;
for (const group of groups) {
let kept = 0;
for (const tr of group.rows) {
const hit = words.every((word) => tr.dataset.find!.includes(word) || group.title.includes(word));
tr.hidden = !hit;
if (hit) kept += 1;
}
group.body.hidden = !kept;
shown += kept;
}
count.textContent = words.length ? plural(shown, 'row') : plural(data.entries.length, 'file');
};
state.remove();
table.hidden = false;
filter.hidden = false;
show(data, groups, haystack);
show();
let pending = 0;
input.addEventListener('input', () => {
window.clearTimeout(pending);
pending = window.setTimeout(() => show(data, groups, haystack), 150);
pending = window.setTimeout(show, 150);
});
}).catch((error) => {
console.error(error);
state.replaceChildren('The list could not load. The ', link(`${base}gaps/`, 'gaps page'), ' lists the same files.');
});
holder.addEventListener('click', async (event) => {
const button = (event.target as Element).closest?.<HTMLButtonElement>('button.rb-wanted-copy');
if (!button) return;
try {
await navigator.clipboard.writeText(button.dataset.value ?? '');
button.textContent = 'Copied';
} catch {
// No clipboard: the value is selected, for Ctrl+C.
const range = document.createRange();
range.selectNodeContents(button.previousElementSibling ?? button);
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}
const gaps = element('a', 'gaps page');
gaps.href = `${base}gaps/`;
state.replaceChildren('The list could not load. The ', gaps, ' lists the same files.');
});
}
</script>
<style is:global>
.rb-wanted-group { border-top: 1px solid var(--rb-border); }
.rb-wanted-group:last-child { border-bottom: 1px solid var(--rb-border); }
.rb-wanted-group[hidden] { display: none; }
.rb-wanted-group > summary {
display: flex;
flex-wrap: wrap;
gap: 0.25rem 0.75rem;
align-items: baseline;
min-height: 44px;
padding: 0.6rem 0;
cursor: pointer;
font-weight: 600;
}
.rb-wanted-group-count { color: var(--rb-text-secondary); font-size: 0.85rem; font-weight: 400; }
.sl-markdown-content .rb-wanted-rows { margin: 0 0 1rem; padding: 0; list-style: none; }
.sl-markdown-content .rb-wanted-row {
margin: 0.75rem 0 0;
padding: 0.75rem;
border: 1px solid var(--rb-border);
border-radius: 6px;
overflow-wrap: anywhere;
}
.sl-markdown-content .rb-wanted-row > * { margin: 0.35rem 0 0; }
.sl-markdown-content .rb-wanted-row > :first-child { margin-top: 0; }
.rb-wanted-row-head code { font-weight: 600; }
.rb-wanted-named { color: var(--rb-text-secondary); }
.sl-markdown-content .rb-wanted-hashes {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.2rem 0.75rem;
font-size: 0.85rem;
}
.sl-markdown-content .rb-wanted-hashes > * { margin: 0; }
.sl-markdown-content .rb-wanted-hashes dt { color: var(--rb-text-secondary); }
.sl-markdown-content .rb-wanted-hashes code { overflow-wrap: anywhere; }
/* The table scrolls inside its box on a phone, never the page. */
.rb-wanted-scroll { overflow-x: auto; }
.sl-markdown-content table.rb-wanted-table { display: table; width: 100%; font-size: 0.85rem; }
.rb-wanted-table[hidden], .rb-wanted-table tbody[hidden], .rb-wanted-table tr[hidden] { display: none; }
.rb-wanted-table tbody th { text-align: left; background: var(--rb-surface); }
.rb-wanted-table td { vertical-align: top; }
.rb-wanted-table td:nth-child(2) { white-space: nowrap; }
.rb-wanted-table thead th { white-space: nowrap; }
/* Hashes keep two lines at most: on a phone the box scrolls sideways. */
.rb-wanted-table td:nth-child(3) { min-width: 9ch; }
.rb-wanted-table td:nth-child(4) { min-width: 17ch; }
.rb-wanted-table td:nth-child(5) { min-width: 21ch; }
.rb-wanted-table td:nth-child(n+3) { font-family: var(--sl-font-mono); }
/* A hash breaks anywhere rather than widen the table, and a click
selects it whole for copying. */
.sl-markdown-content .rb-wanted-table code { padding: 0; background: none; word-break: break-all; user-select: all; }
</style>
+2 -31
View File
@@ -12,10 +12,8 @@ export type Entry = {
s?: number[];
r?: number;
z?: number[];
k?: number;
d?: string;
u?: string;
l?: [string, string][];
c?: string[];
a: string;
f?: number;
t?: string;
v?: number;
@@ -69,22 +67,6 @@ export const target = (data: Wanted, entry: Entry, file: FileHashes, ownName: st
return { folder, name: entry.t };
};
// Where the list sends a file before it is read: the drop target, under
// the name the declarations give. A variant's name ends with the first 8
// characters of its sha1: with no single sha1 declared, the name is known
// once the file is dropped, and name is empty.
export const rowTarget = (data: Wanted, entry: Entry) => {
const folder = entry.f === undefined ? 'bios/' : data.folders[entry.f];
if (!entry.t) return { folder, name: entry.n };
if (!entry.v) return { folder, name: entry.t };
const sha1 = entry.h?.sha1?.length === 1 ? entry.h.sha1[0] : '';
return { folder: `${folder}.variants/`, name: sha1 ? `${entry.t}.${sha1.slice(0, 8)}` : '' };
};
// Too large for GitHub's upload page: every size the declarations allow
// is over the limit.
export const tooLarge = (data: Wanted, entry: Entry) => !!entry.z?.length && entry.z.every((size) => size > data.limit);
let loaded: Promise<Wanted> | null = null;
// The list, fetched once for the drop box and the list below it. The
// version (wanted-version.ts) keeps a cached older list out.
@@ -107,14 +89,3 @@ export const issueUrl = (data: Wanted, name: string, file: FileHashes, size: num
md5: file.md5,
size: String(size),
})}`;
// The issue form for a listed file too large for the browser, with the
// hashes and the size its declarations write.
export const rowIssueUrl = (data: Wanted, entry: Entry) =>
`${data.issue}&${new URLSearchParams({
title: `[BIOS] Missing: ${entry.n}`,
filename: entry.n,
sha1: entry.h?.sha1?.[0] ?? '',
md5: entry.h?.md5?.find((value) => value.length === 32) ?? '',
size: entry.z?.length === 1 ? String(entry.z[0]) : '',
})}`;