/* 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]), name: 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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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) => ``; 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 = `` + values.map((v) => ``).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 = `${all.length} bonded dragons · ${Object.entries(src).map(([k, v]) => `${esc(k)} ${v}`).join(" · ")} · ${esc(st.label)}`; // colour x tail matrix $("#reg-matrix").innerHTML = `
| Colour | ${TAILS.map((t) => `${t.replace("tail", "")} | `).join("")}Total |
|---|---|---|
| ${sw(c)}${c} | ${TAILS.map((t) => { const n = cs.filter((d) => d.tail === t).length; return `${n || "·"} | `; }).join("")}${cs.length} |
| Colour | Lineage | Dragons | Ages | Median | F / M |
|---|---|---|---|---|---|
| ${sw(c)}${c} | ${esc(l)} | ${g.length} | ${ages.length ? Math.min(...ages) + "–" + Math.max(...ages) : "–"} | ${ages.length ? median(ages) : "–"} | ${g.filter((d) => d.sex === "Female").length} / ${g.filter((d) => d.sex === "Male").length} |
| Colour | Tail | Lineage | Age | Sex | Dragon | Rider's assignment | Source | Notes |
|---|---|---|---|---|---|---|---|---|
| ${sw(d.colour)}${esc(d.colour)} | ${esc(d.tail)} | ${esc(d.lineage)} | ${d.age ?? "–"} | ${esc(d.sex)} | ${esc(d.name)} | ${[d.wing, d.section, d.squad].filter(Boolean).map(esc).join(" · ") || "–"} | ${[d.source === "Register form" || d.also.includes("Register form") ? "form" : null, d.source_url ? `result page` : null].filter(Boolean).join(" + ")}${d.duplicates ? ` (${d.duplicates + 1} entries merged)` : ""} | ${esc(d.flags.join("; "))} |
No dragons match these filters.
`; $("#reg-count").textContent = `${rows.length} shown`; renderGallery(rows); } // tail glyphs (24-unit box), drawn as simple original marks const TAIL_GLYPH = { Clubtail: 'No dragons match these filters.
`; } 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_file}, exported ${raw.exported})`); }) .catch((e) => ($("#reg-status").textContent = "The register data could not load.")); } return { build, compare, mount, COLOUR_ORDER, TAILS, lev }; });