site built from 6b4b1344

This commit is contained in:
Atlas data bot
2026-11-20 10:29:17 +00:00
commit d671c61c97
29 changed files with 22432 additions and 0 deletions
+205
View File
@@ -0,0 +1,205 @@
/* register.js — the Dragon Register section: clean, merge, sort and display bonded dragons.
* Works in the browser (window.DragonRegister) and in Node (module.exports) for testing. */
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.DragonRegister = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
const COLOUR_ORDER = ["Red", "Orange", "Brown", "Green", "Blue", "Black"];
const TAILS = ["Clubtail", "Daggertail", "Morningstartail", "Scorpiontail", "Swordtail"];
const KEYS = {
timestamp: ["timestamp"], cadet: ["cadet name"], wing: ["assignment - wing"], section: ["assignment - section"],
squad: ["assignment - squad"], name: ["dragon", "name"], lineage: ["lineage"], colour: ["colour"], tail: ["tail"],
sex: ["sex"], age: [/\bage\b/],
};
const str = (v) => (v === null || v === undefined ? null : String(v).trim() || null);
const title = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1).toLowerCase() : s);
function findCols(headers) {
const C = {};
for (const [k, words] of Object.entries(KEYS)) {
const h = headers.find((x) => words.every((w) => (w instanceof RegExp ? w.test(String(x).toLowerCase()) : String(x).toLowerCase().includes(w))) && !(k === "name" && /cadet/i.test(x)));
if (h) C[k] = h;
}
return C;
}
function tailOf(v) {
const t = (str(v) || "").toLowerCase().replace(/[^a-z]/g, "");
return TAILS.find((x) => x.toLowerCase() === t || x.toLowerCase().replace("tail", "") === t) || (t ? title(t) : "Unknown");
}
function lev(a, b) {
const m = a.length, n = b.length, d = Array.from({ length: m + 1 }, (_, i) => [i, ...new Array(n).fill(0)]);
for (let j = 1; j <= n; j++) d[0][j] = j;
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++)
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
return d[m][n];
}
const lkey = (s) => (str(s) || "").toLowerCase().replace(/[^a-z]/g, "");
// rows: raw register form rows; extra: dragons from other sources (already structured)
function build(raw) {
const C = findCols(raw.headers || Object.keys(raw.rows[0] || {}));
const items = raw.rows.map((r, i) => ({
source: "Register form", source_url: null, submitted: str(r[C.timestamp]),
cadet: str(r[C.cadet]), wing: str(r[C.wing]), section: str(r[C.section]), squad: str(r[C.squad]),
// names typed in capitals ("RAERNUAL") are shown as names ("Raernual")
name: ((n) => (n && n.length > 1 && n === n.toUpperCase() ? n[0] + n.slice(1).toLowerCase() : n))(str(r[C.name])), lineage_raw: str(r[C.lineage]), colour: title(str(r[C.colour])), tail: tailOf(r[C.tail]),
sex: title(str(r[C.sex])), age: parseInt(r[C.age], 10), flags: [],
}));
(raw.extra || []).forEach((e) => items.push({
source: "Reddit (dragonkind.com result page)", source_url: e.url, submitted: null, cadet: null, wing: null, section: null, squad: null,
name: str(e.name), lineage_raw: str(e.lineage), colour: title(e.colour), tail: tailOf(e.tail), sex: title(e.sex), age: parseInt(e.age, 10), flags: [],
}));
// lineage spelling: spellings used 3+ times are canonical; others snap to a canonical of the same colour within 2 edits
const counts = {};
items.forEach((it) => { const k = lkey(it.lineage_raw); if (k) counts[k] = (counts[k] || 0) + 1; });
// spellings confirmed by an official dragonkind.com result page also count as canonical
const official = new Set(items.filter((it) => it.source_url).map((it) => lkey(it.lineage_raw)));
const canon = Object.keys(counts).filter((k) => counts[k] >= 3 || official.has(k));
const colourOfKey = {};
items.forEach((it) => { const k = lkey(it.lineage_raw); if (canon.includes(k)) (colourOfKey[k] = colourOfKey[k] || new Set()).add(it.colour); });
items.forEach((it) => {
let k = lkey(it.lineage_raw);
if (k && !canon.includes(k)) {
const best = canon.filter((c) => colourOfKey[c] && colourOfKey[c].has(it.colour)).map((c) => [c, lev(k, c)]).sort((a, b) => a[1] - b[1])[0];
if (best && best[1] <= 2) { it.flags.push(`lineage spelled "${it.lineage_raw}"`); k = best[0]; }
else it.flags.push("lineage seen fewer than 3 times");
}
it.lineage = k ? title(k) : "Unknown";
if (!Number.isFinite(it.age)) { it.age = null; it.flags.push("age missing"); }
if (!COLOUR_ORDER.includes(it.colour)) it.flags.push("unrecognised colour");
});
// a lineage should belong to one colour
const lc = {};
items.forEach((it) => (lc[it.lineage] = lc[it.lineage] || new Set()).add(it.colour));
items.forEach((it) => { if (lc[it.lineage].size > 1) it.flags.push(`lineage also recorded under ${[...lc[it.lineage]].filter((c) => c !== it.colour).join("/")}`); });
// duplicates: same dragon name + colour + tail + sex + age + lineage
const seen = new Map(), out = [];
items.forEach((it) => {
const key = [it.name && it.name.toLowerCase(), it.colour, it.tail, it.sex, it.age, it.lineage].join("|");
if (seen.has(key)) {
const first = seen.get(key);
first.duplicates = (first.duplicates || 0) + 1;
if (!first.also.includes(it.source) && it.source !== first.source) first.also.push(it.source);
if (it.source_url && !first.source_url) first.source_url = it.source_url;
return;
}
it.also = []; seen.set(key, it); out.push(it);
});
out.sort(compare);
return out;
}
function compare(a, b) {
const ci = (c) => (COLOUR_ORDER.indexOf(c) + 1 || 99);
return ci(a.colour) - ci(b.colour) || a.tail.localeCompare(b.tail) || a.lineage.localeCompare(b.lineage) ||
(b.age ?? -1) - (a.age ?? -1) || (a.name || "").localeCompare(b.name || "");
}
// ---------------------------------------------------------------- browser UI
function mount(opts) {
const $ = (q) => document.querySelector(q);
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const st = { all: [], label: "", f: { colour: "", tail: "", lineage: "", sex: "", q: "" }, bundled: null };
function load(raw, label) { st.all = build(raw); st.label = label; st.f = { colour: "", tail: "", lineage: "", sex: "", q: "" }; ["reg-colour", "reg-tail", "reg-lineage", "reg-sex", "reg-q"].forEach((id) => ($("#" + id).value = "")); render(); }
const filtered = () => st.all.filter((d) => (!st.f.colour || d.colour === st.f.colour) && (!st.f.tail || d.tail === st.f.tail) &&
(!st.f.lineage || d.lineage === st.f.lineage) && (!st.f.sex || d.sex === st.f.sex) &&
(!st.f.q || [d.name, d.lineage].join(" ").toLowerCase().includes(st.f.q.toLowerCase())));
const sw = (c) => `<span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:var(${DV[c] || "--faint"});margin-right:6px;vertical-align:-1px;box-shadow:0 0 0 1px color-mix(in srgb, var(--ink) 25%, transparent)"></span>`;
const median = (a) => { const s = a.slice().sort((x, y) => x - y); const m = s.length >> 1; return s.length ? (s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2) : null; };
function fillSelect(id, values, label) {
const el = $("#" + id), cur = el.value;
el.innerHTML = `<option value="">${label}</option>` + values.map((v) => `<option>${esc(v)}</option>`).join("");
el.value = values.includes(cur) ? cur : "";
}
function render() {
const all = st.all, rows = filtered();
const colours = COLOUR_ORDER.filter((c) => all.some((d) => d.colour === c));
fillSelect("reg-colour", colours, "All colours");
fillSelect("reg-tail", TAILS.filter((t) => all.some((d) => d.tail === t)), "All tails");
fillSelect("reg-lineage", [...new Set(all.filter((d) => !st.f.colour || d.colour === st.f.colour).map((d) => d.lineage))].sort(), "All lineages");
fillSelect("reg-sex", [...new Set(all.map((d) => d.sex).filter(Boolean))].sort(), "Any sex");
const src = {}; all.forEach((d) => (src[d.source] = (src[d.source] || 0) + 1));
$("#reg-status").innerHTML = `<b>${all.length}</b> bonded dragons · ${Object.entries(src).map(([k, v]) => `${esc(k)} ${v}`).join(" · ")} · <span class="pill">${esc(st.label)}</span>`;
// colour x tail matrix
$("#reg-matrix").innerHTML = `<table><thead><tr><th>Colour</th>${TAILS.map((t) => `<th class="num">${t.replace("tail", "")}</th>`).join("")}<th class="num">Total</th></tr></thead><tbody>${colours.map((c) => {
const cs = rows.filter((d) => d.colour === c);
return `<tr><td>${sw(c)}${c}</td>${TAILS.map((t) => { const n = cs.filter((d) => d.tail === t).length; return `<td class="num"${n ? "" : ' style="color:var(--faint)"'}>${n || "·"}</td>`; }).join("")}<td class="num"><b>${cs.length}</b></td></tr>`;
}).join("")}</tbody></table>`;
// lineages
const lin = {};
rows.forEach((d) => { const k = d.colour + "|" + d.lineage; (lin[k] = lin[k] || []).push(d); });
$("#reg-lineages").innerHTML = `<table><thead><tr><th>Colour</th><th>Lineage</th><th class="num">Dragons</th><th class="num">Ages</th><th class="num">Median</th><th class="num">F / M</th></tr></thead><tbody>${Object.keys(lin).sort((a, b) => COLOUR_ORDER.indexOf(a.split("|")[0]) - COLOUR_ORDER.indexOf(b.split("|")[0]) || a.localeCompare(b)).map((k) => {
const g = lin[k], ages = g.map((d) => d.age).filter(Number.isFinite), [c, l] = k.split("|");
return `<tr><td>${sw(c)}${c}</td><td>${esc(l)}</td><td class="num">${g.length}</td><td class="num">${ages.length ? Math.min(...ages) + "–" + Math.max(...ages) : "–"}</td><td class="num">${ages.length ? median(ages) : "–"}</td><td class="num">${g.filter((d) => d.sex === "Female").length} / ${g.filter((d) => d.sex === "Male").length}</td></tr>`;
}).join("")}</tbody></table>`;
// main table, grouped by colour then tail
let lastGroup = "";
$("#reg-table").innerHTML = rows.length ? `<table><thead><tr><th>Colour</th><th>Tail</th><th>Lineage</th><th class="num">Age</th><th>Sex</th><th>Dragon</th><th>Rider's assignment</th><th>Source</th><th>Notes</th></tr></thead><tbody>${rows.map((d) => {
const g = d.colour + "|" + d.tail, head = g !== lastGroup; lastGroup = g;
return `<tr${head ? ' style="border-top:2px solid var(--line)"' : ""}><td>${sw(d.colour)}${esc(d.colour)}</td><td>${esc(d.tail)}</td><td>${esc(d.lineage)}</td><td class="num">${d.age ?? "–"}</td><td>${esc(d.sex)}</td><td><b>${esc(d.name)}</b></td><td class="small">${[d.wing, d.section, d.squad].filter(Boolean).map(esc).join(" · ") || "–"}</td><td class="small">${[d.source === "Register form" || d.also.includes("Register form") ? "form" : null, d.source_url ? `<a href="${esc(d.source_url)}" target="_blank" rel="noopener">result page</a>` : null].filter(Boolean).join(" + ")}${d.duplicates ? ` <span class="muted">(${d.duplicates + 1} entries merged)</span>` : ""}</td><td class="small muted">${esc(d.flags.join("; "))}</td></tr>`;
}).join("")}</tbody></table>` : `<p class="small muted" style="padding:12px">No dragons match these filters.</p>`;
$("#reg-count").textContent = `${rows.length} shown`;
renderGallery(rows);
}
// tail glyphs (24-unit box), drawn as simple original marks
const TAIL_GLYPH = {
Clubtail: '<path d="M5 19 L14 10" stroke-width="2.4"/><circle cx="16" cy="8" r="3.6" stroke="none" fill="currentColor"/>',
Daggertail: '<path d="M5 19 L8.5 15.5" stroke-width="2.4"/><path d="M7 14 L10 17" stroke-width="1.8"/><path d="M8.5 15.5 L19 5 L13.5 15.5 Z" fill="currentColor" stroke="none"/>',
Morningstartail: '<path d="M5 19 L11 13" stroke-width="2.4"/><circle cx="14.5" cy="9.5" r="3.4" fill="currentColor" stroke="none"/><path d="M14.5 3.5v2.5M14.5 13v2.5M8.5 9.5h2.5M18 9.5h2.5M10.3 5.3l1.8 1.8M16.9 11.9l1.8 1.8M18.7 5.3l-1.8 1.8M12.1 11.9l-1.8 1.8" stroke-width="1.6"/>',
Scorpiontail: '<path d="M5 19 C5 10 11 5.5 17 6.5 C20.5 7.2 20.5 11.5 17.5 12.5" stroke-width="2.2"/><path d="M17.5 12.5 L14.5 11 L16.2 15 Z" fill="currentColor" stroke="none"/>',
Swordtail: '<path d="M5 19 L19 5" stroke-width="2.6"/><path d="M6.5 13.5 L10.5 17.5" stroke-width="2"/><path d="M19 5 L16 6 L18 8 Z" fill="currentColor" stroke="none"/>',
};
function emblem(d) {
const col = cssVar(DV[d.colour] || "--faint");
const rgbv = (col.match(/[0-9a-f]{2}/gi) || ["80", "80", "80"]).slice(0, 3).map((h) => parseInt(h, 16));
const lum = col.startsWith("#") ? (0.299 * rgbv[0] + 0.587 * rgbv[1] + 0.114 * rgbv[2]) / 255 : 0.4;
const ink = lum > 0.6 ? "#14181d" : "#f4f1ea";
return `<svg viewBox="0 0 64 64" aria-hidden="true"><defs><radialGradient id="g${d.colour}" cx="35%" cy="30%" r="80%"><stop offset="0" stop-color="${col}" stop-opacity="0.85"/><stop offset="1" stop-color="${col}"/></radialGradient></defs>
<path d="M32 3 L57 17 L57 47 L32 61 L7 47 L7 17 Z" fill="url(#g${d.colour})" stroke="var(--ink)" stroke-opacity="0.25"/>
<path d="M32 9 L52 20 L52 44 L32 55 L12 44 L12 20 Z" fill="none" stroke="${ink}" stroke-opacity="0.35"/>
<g transform="translate(16 16) scale(1.35)" stroke="${ink}" fill="none" stroke-linecap="round" style="color:${ink}">${TAIL_GLYPH[d.tail] || ""}</g></svg>`;
}
function renderGallery(rows) {
const g = $("#reg-gallery");
if (!g) return;
const byC = {};
rows.forEach((d) => (byC[d.colour] = byC[d.colour] || []).push(d));
g.innerHTML = Object.keys(byC).sort((a, b) => COLOUR_ORDER.indexOf(a) - COLOUR_ORDER.indexOf(b)).map((c) => `
<div class="gal-group"><h3>${sw(c)}${esc(c)} dragons <span class="small muted" style="font-family:var(--font-body);letter-spacing:0">${byC[c].length}</span></h3>
<div class="cards">${byC[c].map((d) => `<div class="dcard" style="--dc: var(${DV[d.colour] || "--accent"})" title="${esc(d.flags.join("; "))}"><span class="age">${d.age ?? "?"} yrs</span>${emblem(d)}<span class="nm">${esc(d.name)}</span><span class="meta">${esc(d.sex || "")} ${esc(d.tail)}<br>${esc(d.lineage)} lineage${d.source_url ? `<br><a href="${esc(d.source_url)}" target="_blank" rel="noopener">result page</a>` : ""}</span></div>`).join("")}</div></div>`).join("") || `<p class="small muted">No dragons match these filters.</p>`;
}
document.querySelectorAll("#reg-view button").forEach((b) => b.addEventListener("click", () => {
document.querySelectorAll("#reg-view button").forEach((x) => x.setAttribute("aria-pressed", x === b));
$("#reg-gallery").hidden = b.dataset.v !== "cards";
$("#reg-table").hidden = b.dataset.v !== "table";
}));
function csv() {
const cols = ["colour", "tail", "lineage", "age", "sex", "name", "wing", "section", "squad", "source", "source_url", "lineage_raw", "flags"];
const q = (v) => { if (v === null || v === undefined) return ""; const s = Array.isArray(v) ? v.join("; ") : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
return [cols.join(","), ...filtered().map((d) => cols.map((c) => q(d[c])).join(","))].join("\n");
}
[["reg-colour", "colour"], ["reg-tail", "tail"], ["reg-lineage", "lineage"], ["reg-sex", "sex"]].forEach(([id, k]) =>
$("#" + id).addEventListener("change", (e) => { st.f[k] = e.target.value; if (k === "colour") st.f.lineage = ""; render(); }));
$("#reg-q").addEventListener("input", (e) => { st.f.q = e.target.value.trim(); render(); });
$("#reg-copy").addEventListener("click", () => opts.copy(csv(), "register CSV"));
$("#reg-upload").addEventListener("change", async (e) => {
const f = e.target.files[0]; if (!f) return;
try {
const wb = XLSX.read(await f.arrayBuffer(), { type: "array", cellDates: true });
const ws = wb.Sheets[wb.SheetNames.find((n) => /form responses/i.test(n)) || wb.SheetNames[0]];
const headers = (XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false })[0] || []).map(String);
const rows = XLSX.utils.sheet_to_json(ws, { defval: null, raw: true });
load({ headers, rows, extra: st.bundled.extra }, `uploaded ${f.name} + Reddit result pages`);
opts.toast(`Loaded ${rows.length} register rows`);
} catch (err) { opts.toast("That file could not be read. Export the register sheet as .xlsx or .csv."); console.error(err); }
e.target.value = "";
});
fetch("data/register.json").then((r) => r.json()).then((raw) => { st.bundled = raw; load(raw, `bundled snapshot (${raw.source}, exported ${raw.exported})`); })
.catch((e) => ($("#reg-status").textContent = "The register data could not load."));
}
return { build, compare, mount, COLOUR_ORDER, TAILS, lev };
});