tag early.
var embedJson = JSON.stringify(embed).replace(/window.__ROUNDFLOW_OFFLINE__ = " + embedJson + ";<" + "/script>\n";
var out = html.slice(0, idx) + inject + html.slice(idx);
var blob = new Blob([out], { type: "text/html" });
var url = URL.createObjectURL(blob);
var rawName = state.title || (state.meta && state.meta.proTeam && state.meta.conTeam ? state.meta.proTeam + " vs " + state.meta.conTeam : "flow");
var fileName = rawName.trim().replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase() + "-offline.html";
var a = document.createElement("a");
a.href = url;
a.download = fileName || "roundflow-offline.html";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function () { URL.revokeObjectURL(url); }, 4000);
toast("Downloaded " + fileName + " — open it directly, even with no internet. When you're back online, use Copy flow here, then Import to bring your changes back.");
}).catch(function () {
toast("Couldn't build the offline file — check your connection and try again.");
});
}
function doImport() {
var root = document.getElementById("modal-root");
var veil = document.createElement("div");
veil.className = "modal-veil";
veil.innerHTML =
'
' +
"
Import
" +
"
Paste a full flow (replaces everything currently loaded) or a single shared sheet/case (adds it as a new sheet here).
" +
'' +
'' +
'
' +
'' +
'' +
"
" +
"
";
root.innerHTML = "";
root.appendChild(veil);
var ta = veil.querySelector("textarea");
var err = veil.querySelector(".modal-err");
veil.querySelector('[data-act="cancel"]').addEventListener("click", closeModal);
veil.querySelector('[data-act="load"]').addEventListener("click", function () {
try {
var parsed = JSON.parse(ta.value);
if (parsed && parsed.__flowlineSheet && parsed.page) {
if (!state || !state.setupDone) throw new Error("no-flow-yet");
var incoming = parsed.page;
incoming.id = uid("page");
if (incoming.type === "preflow") migratePreflowToCards(incoming, state.meta);
else { incoming.type = "flow"; migrateFlowPage(incoming); }
state.pages.push(incoming);
state.activePageId = incoming.id;
scheduleSave();
closeModal();
render();
toast(parsed.format && parsed.format !== state.meta.format
? "Sheet added — heads up, it was built for a different format, so some columns may not line up."
: "Sheet added: " + (incoming.title || "Untitled"));
return;
}
if (!parsed || !parsed.meta || !Array.isArray(parsed.pages)) throw new Error("shape");
parsed.id = uid("flow");
parsed.title = parsed.title || ((parsed.meta.proTeam && parsed.meta.conTeam) ? (parsed.meta.proTeam + " vs " + parsed.meta.conTeam) : "Imported flow");
parsed.tournamentId = null;
if (parsed.setupDone === undefined) parsed.setupDone = true;
migrateRoundOrFlow(parsed);
library.flows.push(parsed);
library.activeRef = { kind: "flow", flowId: parsed.id };
focused = null;
persistLibrary();
closeModal();
render();
toast("Flow imported as a new entry in your library.");
} catch (e) {
err.textContent = e && e.message === "no-flow-yet"
? "Set up a flow first, then import a sheet into it."
: "That doesn’t look like valid RoundFlow data — check you copied the whole block.";
}
});
setTimeout(function () { ta.focus(); }, 30);
}
/* ============ Card ops ============ */
function findCard(page, cardId) {
return page.cards.filter(function (c) { return c.id === cardId; })[0];
}
function addCard(colId, opts) {
var page = currentPage();
var card = newCard(colId, opts);
page.cards.push(card);
scheduleSave();
liveBroadcastCard(card);
return card;
}
function addCardFromMenu(colId, term) {
var page = currentPage();
if (!term) {
var card = addCard(colId, {});
render();
focusCardText(card.id);
return;
}
var parts = STRUCTURED_PARTS[term.tag];
var card = addCard(colId, { shellTag: term.tag });
if (parts) {
parts.forEach(function (part) {
var child = newCard(colId, { parentId: card.id, label: part });
page.cards.push(child);
liveBroadcastCard(child);
});
}
scheduleSave();
render();
if (parts) {
var firstChild = page.cards.filter(function (c) { return c.parentId === card.id; })[0];
if (firstChild) focusCardText(firstChild.id);
} else {
focusCardText(card.id);
}
}
function addSubpoint(cardId) {
var page = currentPage();
var parent = findCard(page, cardId);
if (!parent) return;
var child = newCard(parent.colId, { parentId: parent.id });
page.cards.push(child);
scheduleSave();
liveBroadcastCard(child);
render();
focusCardText(child.id);
}
function deleteCard(cardId) {
var page = currentPage();
var toRemove = { };
toRemove[cardId] = true;
page.cards.forEach(function (c) { if (c.parentId === cardId) toRemove[c.id] = true; });
page.cards = page.cards.filter(function (c) { return !toRemove[c.id]; });
page.links = (page.links || []).filter(function (l) { return !toRemove[l.fromId] && !toRemove[l.toId]; });
scheduleSave();
Object.keys(toRemove).forEach(function (id) { liveBroadcastDelete(id); });
render();
}
function updateCardText(cardId, value) {
var page = currentPage();
var card = findCard(page, cardId);
if (!card) return;
card.text = value;
scheduleSave();
liveBroadcastCardDebounced(cardId);
}
// Congress (singleQueue) speaker-name input — see renderCard(). No render()
// here, same reasoning as updateCardText(): re-rendering on every keystroke
// would steal focus out of the input while typing.
function updateCardLabel(cardId, value) {
var page = currentPage();
var card = findCard(page, cardId);
if (!card) return;
card.label = value;
scheduleSave();
liveBroadcastCardDebounced(cardId);
}
function setCardColor(cardId, color) {
var page = currentPage();
var card = findCard(page, cardId);
if (!card) return;
card.color = color;
scheduleSave();
liveBroadcastCard(card);
render();
}
// Added 2026-09-01 for the Evidence tab (§11 item 2 in the handoff brief,
// scoped with Bobby as "citation text + link, side by side"). Was a
// single-field promptText() for just the URL; now collects a short
// citation too (card.evidenceCite), since a card's own argument text
// isn't the same thing as a citation and openEvidenceModal() needs both.
function editCardEvidence(cardId) {
var page = currentPage();
var card = findCard(page, cardId);
if (!card) return;
var root = document.getElementById("modal-root");
var veil = document.createElement("div");
veil.className = "modal-veil";
var fieldStyle = "width:100%;padding:9px 11px;border-radius:7px;border:1px solid var(--rule-strong);background:var(--surface);color:var(--ink);font-size:14px;margin-bottom:10px;";
var labelStyle = "display:block;font-size:11px;color:var(--ink-dim);margin-bottom:4px;";
veil.innerHTML =
'
' +
"
Link evidence
" +
'
A short citation, plus a link to the cut card, doc, or source this argument comes from. Both show up together in Evidence (More ▾).
";
root.innerHTML = "";
root.appendChild(veil);
var citeInp = document.getElementById("evidence-cite-input");
var urlInp = document.getElementById("evidence-url-input");
veil.addEventListener("click", function (e) { if (e.target === veil) closeModal(); });
veil.querySelector('[data-act="cancel"]').addEventListener("click", closeModal);
var clearBtn = veil.querySelector('[data-act="clear"]');
if (clearBtn) clearBtn.addEventListener("click", function () {
card.evidenceCite = null;
card.evidenceUrl = null;
scheduleSave();
liveBroadcastCard(card);
closeModal();
render();
});
veil.querySelector('[data-act="ok"]').addEventListener("click", function () {
card.evidenceCite = citeInp.value.trim() || null;
card.evidenceUrl = urlInp.value.trim() || null;
scheduleSave();
liveBroadcastCard(card);
closeModal();
render();
});
setTimeout(function () { citeInp.focus(); citeInp.select(); }, 30);
}
// Added 2026-09-01 (§11 item 1 in the handoff brief): lets a card's
// shellTag (the term badge — Drop/Concede, Theory, etc.) be changed or
// removed after the fact, so picking the wrong one from a column's + menu
// no longer means deleting the card and starting over. Deliberately only
// touches shellTag — it never adds or removes the auto-generated
// sub-point children a *new* structured card gets (Theory/Topicality/
// Kritik/Counterplan/Disad), since a card being retagged may already have
// its own children (or none at all) and guessing which to add/remove
// would be more likely to surprise someone than help them.
function setCardShellTag(cardId, tag) {
var page = currentPage();
var card = findCard(page, cardId);
if (!card) return;
card.shellTag = tag || null;
openTypeMenu = null;
scheduleSave();
liveBroadcastCard(card);
render();
}
function renderTypeMenu(cardId) {
return '
";
}
// Congress-only (singleQueue formats): which side a speech card argues,
// changeable after the fact the same way a card's term badge is — this
// never touches the card's text/links/evidence/sub-points, only the label
// and the border/text color renderCard() derives from it.
function setCardQSide(cardId, side) {
var page = currentPage();
var card = findCard(page, cardId);
if (!card) return;
card.qSide = side || null;
openSideMenu = null;
scheduleSave();
liveBroadcastCard(card);
render();
}
function renderSideMenu(cardId) {
var sn = currentFormat().sideNames;
return '
";
}
// ---- Cites + quick add (added 2026-11-26) ----
// Start a card with "Author 24:" (or "Smith and Lee 2019:", "Downs et al. 17:")
// and the author/year moves into the card's cite tag. Needs a capitalized
// name, a 2- or 4-digit year and a colon, so "C1:" or "Harm 2:" never match.
function citeFromText(text) {
var m = /^\s*([A-Z][A-Za-z'\u2019.\-]*(?:\s+(?:and|&)\s+[A-Z][A-Za-z'\u2019.\-]*|\s+et\s+al\.?)?\s+'?(?:\d{2}|\d{4}))\s*:\s+([\s\S]+)$/.exec(text || "");
return m ? { cite: m[1].trim(), text: m[2] } : null;
}
function applyCiteSyntax(cardId, ta) {
var card = findCard(currentPage(), cardId);
if (!card || card.evidenceCite) return false;
var p = citeFromText(card.text);
if (!p) return false;
card.evidenceCite = p.cite;
card.text = p.text;
if (ta) {
ta.value = p.text;
autosize(ta);
var host = ta.parentNode;
if (host && !host.querySelector(":scope > .arg-card-cite")) {
var chip = document.createElement("button");
chip.type = "button";
chip.className = "arg-card-cite";
chip.textContent = p.cite;
chip.title = "Edit cite (Alt+C)";
chip.addEventListener("click", function () { editCardEvidence(cardId); });
host.insertBefore(chip, ta);
}
}
scheduleSave();
liveBroadcastCard(card);
return true;
}
// ---- Evidence card form + term chips (added 2026-11-26) ----
// Under each column: the quick box for an argument, "+ Evidence" for a card
// with its tag, author/year and link in one step, and the terms (Drop,
// Theory, DA...) listed as chips instead of hidden in a menu.
var evFormFor = "";
var TERM_SHORT = { "Drop/Concede": "Drop", "Role of the Ballot": "ROB", "Independent Voter": "Voter", "Uniqueness": "UQ", "Topicality": "T", "Kritik": "K", "Counterplan": "CP", "Disad": "DA" };
function renderTermChips(colId) {
return '
";
root.innerHTML = "";
root.appendChild(veil);
veil.querySelector('[data-act="cancel"]').addEventListener("click", closeModal);
var removeBtn = veil.querySelector('[data-act="remove"]');
if (removeBtn) removeBtn.addEventListener("click", function () {
card.groupId = null;
scheduleSave(); closeModal(); render();
});
veil.querySelector('[data-act="save"]').addEventListener("click", function () {
var name = document.getElementById("bundle-name").value.trim();
var checked = Array.from(veil.querySelectorAll("[data-cand]:checked")).map(function (el) { return el.getAttribute("data-cand"); });
if (!name && !checked.length) { card.groupId = null; scheduleSave(); closeModal(); render(); return; }
var gid = card.groupId || uid("group");
page.groups = page.groups || [];
var g = page.groups.filter(function (g) { return g.id === gid; })[0];
if (!g) { g = { id: gid, label: name || "Bundle", color: card.color || null }; page.groups.push(g); }
else { g.label = name || g.label; }
card.groupId = gid;
others.forEach(function (c) { if (checked.indexOf(c.id) !== -1) c.groupId = gid; else if (c.groupId === gid) c.groupId = null; });
scheduleSave();
closeModal();
render();
});
}
/* ============ Page ops ============ */
function addPage(type) {
if (type === "preflow") {
var gating = currentGating();
if (gating.maxPreflowPages != null) {
var existingPreflows = state.pages.filter(function (p) { return (p.type || "flow") === "preflow"; }).length;
if (existingPreflows >= gating.maxPreflowPages) {
openUpgradeModal("Free accounts get " + gating.maxPreflowPages + " preflow sheet per flow — upgrade for unlimited.");
return;
}
}
}
var trial = type === "witness-pro" || type === "witness-con" || type === "trial-speeches" || type === "trial-pretrial" ? type : null;
if (trial) type = "flow";
var count = state.pages.filter(function (p) { return (p.type || "flow") === type; }).length + 1;
var title = type === "preflow" ? "Preflow " + count : (currentFormat().singleQueue ? "Bill " + count : "Sheet " + (state.pages.length + 1));
if (trial === "trial-speeches") title = "Openings & closings";
if (trial === "trial-pretrial") title = "Pretrial motion";
var wSide = trial === "witness-con" ? "con" : "pro";
if (trial === "witness-pro" || trial === "witness-con") {
var wn = state.pages.filter(function (p) { return p.trialKind === "witness" && p.calledBy === wSide; }).length + 1;
title = (wSide === "con" ? "Defense" : "Prosecution") + " witness " + wn;
}
var p = newPage(title, type);
if (trial === "witness-pro" || trial === "witness-con") { p.trialKind = "witness"; p.calledBy = wSide; }
if (trial === "trial-pretrial") p.trialKind = "pretrial";
state.pages.push(p);
state.activePageId = p.id;
scheduleSave();
render();
}
function deletePage(id) {
if (state.pages.length <= 1) { toast("Keep at least one sheet."); return; }
confirmModal({
title: "Delete this sheet?", body: "This removes everything on this sheet. This can’t be undone.",
okLabel: "Delete sheet", danger: true,
onConfirm: function () {
state.pages = state.pages.filter(function (p) { return p.id !== id; });
if (state.activePageId === id) state.activePageId = state.pages[0].id;
scheduleSave();
render();
}
});
}
function renamePage(id, title) {
if (id === SHARED_PREFLOW_ID) {
var tour = currentTournament();
if (tour) { tour.preflow.title = title; scheduleSave(); }
return;
}
var p = state.pages.filter(function (pg) { return pg.id === id; })[0];
if (p) { p.title = title; scheduleSave(); }
}
function autosize(el) {
el.style.height = "auto";
el.style.height = (el.scrollHeight + 2) + "px";
scheduleRedrawLinks();
}
/* ============ Web-link geometry ============ */
function scheduleRedrawLinks() {
if (redrawScheduled) return;
redrawScheduled = true;
requestAnimationFrame(function () { redrawScheduled = false; redrawLinks(); });
}
function redrawLinks() {
var canvases = viewAllSheets() ? Array.prototype.slice.call(document.querySelectorAll("[data-sheet-canvas]")) : [document.querySelector(".web-canvas")];
canvases.forEach(function (cv) { drawLinksIn(cv); });
wireLinkLabels();
}
function drawLinksIn(canvas) {
if (!canvas) return;
var svg = canvas.querySelector(".web-svg");
var labelsWrap = canvas.querySelector(".web-labels");
if (!svg || !labelsWrap) return;
var sheetId = canvas.getAttribute("data-sheet-canvas");
var page = sheetId ? sheetPageById(sheetId) : currentPage();
if (!page || !page.links || !page.links.length) {
svg.innerHTML = ""; labelsWrap.innerHTML = "";
return;
}
var canvasRect = canvas.getBoundingClientRect();
var defs = '' +
'';
var paths = "", labels = "";
page.links.forEach(function (link) {
var fromEl = document.querySelector('[data-card="' + link.fromId + '"]');
var toEl = document.querySelector('[data-card="' + link.toId + '"]');
if (!fromEl || !toEl) return;
var r1 = fromEl.getBoundingClientRect(), r2 = toEl.getBoundingClientRect();
// Updated 2026-11-25: lines run edge-to-edge through the gutter between
// columns (and behind cards) instead of center-to-center across the text.
var ox = canvasRect.left, oy = canvasRect.top;
var y1 = r1.top + Math.min(r1.height / 2, 22) - oy, y2 = r2.top + Math.min(r2.height / 2, 22) - oy;
var x1, x2, mx, my;
if (r1.left >= r2.right - 1) { x1 = r1.left - ox; x2 = r2.right - ox; }
else if (r1.right <= r2.left + 1) { x1 = r1.right - ox; x2 = r2.left - ox; }
else { x1 = r1.right - ox; x2 = r2.right - ox; }
if (Math.abs(x1 - x2) < 2 || (r1.left < r2.right - 1 && r1.right > r2.left + 1)) {
mx = Math.max(x1, x2) + 26; my = (y1 + y2) / 2;
} else {
mx = (x1 + x2) / 2; my = (y1 + y2) / 2 - Math.min(24, Math.abs(x2 - x1) / 6 + 8);
}
var lx = (x1 + 2 * mx + x2) / 4, ly = (y1 + 2 * my + y2) / 4;
var short = link.tag === "Responds to" ? "\u21A9" : link.tag;
paths += '';
labels += '
' +
'" +
'' +
"
";
});
svg.innerHTML = defs + paths;
labelsWrap.innerHTML = labels;
}
function wireLinkLabels() {
document.querySelectorAll("[data-jump-link]").forEach(function (btn) {
btn.addEventListener("click", function () {
var link = (currentPage().links || []).filter(function (l) { return l.id === btn.getAttribute("data-jump-link"); })[0];
if (!link) return;
var el = document.querySelector('[data-card="' + link.toId + '"]');
if (el) {
el.scrollIntoView({ block: "center", inline: "center", behavior: "smooth" });
el.style.transition = "none"; el.style.boxShadow = "0 0 0 3px var(--accent)";
requestAnimationFrame(function () { el.style.transition = "box-shadow 900ms ease"; el.style.boxShadow = ""; });
}
});
});
document.querySelectorAll("[data-unlink]").forEach(function (btn) {
btn.addEventListener("click", function (e) { e.stopPropagation(); removeLink(btn.getAttribute("data-unlink")); });
});
}
/* ============ Setup screen ============ */
function openSetupNew(kind) {
setupDraft = { kind: kind, tournamentName: "", tabroomLink: "", meta: freshMeta() };
render();
}
function openAddRoundModal(tournamentId) {
var t = library.tournaments.filter(function (x) { return x.id === tournamentId; })[0];
if (!t) return;
var sn = formatFor(t.defaultMeta).sideNames;
var chosenSide = t.defaultMeta.mySide || "";
var root = document.getElementById("modal-root");
var veil = document.createElement("div");
veil.className = "modal-veil";
veil.innerHTML =
'
' +
"
Add a round
" +
"
" + escapeHtml(t.name || "This tournament") + " — this round inherits your team/topic setup, and shares the same Preflow as every other round. You can fine-tune it after.
" +
'' +
'' +
'' +
'' +
'
' +
'" +
'" +
'' +
"
" +
'' +
"
";
root.innerHTML = "";
root.appendChild(veil);
veil.querySelectorAll("[data-rside]").forEach(function (btn) {
btn.addEventListener("click", function () {
chosenSide = btn.getAttribute("data-rside");
veil.querySelectorAll("[data-rside]").forEach(function (b) { b.setAttribute("aria-pressed", b === btn ? "true" : "false"); });
});
});
veil.addEventListener("click", function (e) { if (e.target === veil) closeModal(); });
veil.querySelector('[data-act="cancel"]').addEventListener("click", closeModal);
veil.querySelector('[data-act="ok"]').addEventListener("click", function () {
var title = document.getElementById("round-title").value.trim() || ("Round " + (t.rounds.length + 1));
var judge = document.getElementById("round-judge").value.trim();
var meta = JSON.parse(JSON.stringify(t.defaultMeta));
meta.mySide = chosenSide;
meta.round = title;
meta.judge = judge;
meta.tabroomLink = document.getElementById("round-tabroom").value.trim();
meta.judgeLink = document.getElementById("round-judgelink").value.trim();
var round = { id: uid("round"), title: title, setupDone: true, tournamentId: t.id, meta: meta, pages: [], activePageId: null };
var mainPage = newPage("Main Flow", "flow");
round.pages.push(mainPage);
round.activePageId = mainPage.id;
t.rounds.push(round);
closeModal();
library.activeRef = { kind: "round", tournamentId: t.id, roundId: round.id };
persistLibrary();
render();
});
setTimeout(function () { document.getElementById("round-title").focus(); }, 30);
}
// Heuristic "smart paste" for pairing info copied from Tabroom (or any tab
// site, or an email) — there's no public Tabroom API to integrate against,
// so this looks for the same keywords most pairing postings share (Round,
// Judge, side labels, a URL, a resolution line) rather than assuming one
// exact template. It only fills fields it's confident about, and always
// leaves the result on-screen for the debater to review before saving.
function parsePastedPairing(text, existingMeta) {
text = String(text || "");
var values = {};
var filledLabels = [];
if (!text.trim()) return { any: false, values: values, filledLabels: filledLabels };
var roundMatch = text.match(/round\s*[:#]?\s*(\d+|octafinals?|octas?|quarterfinals?|quarters?|semifinals?|semis?|finals?|doubles?)/i);
if (roundMatch) {
var rNum = roundMatch[1];
values.round = /^\d+$/.test(rNum) ? ("Round " + rNum) : (rNum.charAt(0).toUpperCase() + rNum.slice(1).toLowerCase());
filledLabels.push("round");
}
var judgeMatch = text.match(/judges?\s*[:\-]\s*([^\n,;]{2,60})/i);
if (judgeMatch) {
values.judge = judgeMatch[1].trim();
filledLabels.push("judge");
}
var urlMatch = text.match(/https?:\/\/\S+/i);
if (urlMatch && !(existingMeta && existingMeta.tabroomLink)) {
values.tabroomLink = urlMatch[0].replace(/[),.;]+$/, "");
filledLabels.push("link");
}
var topicMatch = text.match(/(?:resolved|resolution|topic)\s*[:\-]\s*([^\n]{4,240})/i);
if (topicMatch) {
values.topic = (/^resolved/i.test(topicMatch[0]) ? "Resolved: " : "") + topicMatch[1].trim();
filledLabels.push("topic");
}
// Side labels vary by format/tab site (Aff/Neg, Pro/Con, Gov/Opp,
// Prop/Opp) — map whichever appears to this app's internal pro/con.
var SIDE_WORDS = {
aff: "pro", pro: "pro", gov: "pro", government: "pro", prop: "pro", proposition: "pro",
neg: "con", con: "con", opp: "con", opposition: "con"
};
Object.keys(SIDE_WORDS).forEach(function (word) {
// Stop the capture before "vs"/"v." or another side label butting up
// against this one on the same line (e.g. "Aff: Team A vs Neg: Team B"),
// not just at a comma/newline — pairings often have no comma there.
var re = new RegExp(
"\\b" + word + "\\b\\s*[:\\-]\\s*([^\\n,;]+?)(?=\\s+v(?:s\\.?|\\.)\\s+|\\s+(?:aff|neg|pro|con|gov|opp|prop)\\s*[:\\-]|[\\n,;]|$)",
"i"
);
var mm = text.match(re);
if (mm) {
var side = SIDE_WORDS[word];
var key = side === "pro" ? "proTeam" : "conTeam";
if (!values[key]) {
values[key] = mm[1].trim();
filledLabels.push(side === "pro" ? "your side's team" : "opponent team");
}
}
});
if (!values.proTeam && !values.conTeam) {
var vsMatch = text.match(/([A-Za-z][A-Za-z0-9 &'.\-]{1,40})\s+v(?:s\.?|\.)\s+([A-Za-z][A-Za-z0-9 &'.\-]{1,40})/i);
if (vsMatch) {
values.proTeam = vsMatch[1].trim();
values.conTeam = vsMatch[2].trim();
filledLabels.push("teams");
}
}
var uniqueLabels = filledLabels.filter(function (v, i) { return filledLabels.indexOf(v) === i; });
return { any: uniqueLabels.length > 0, values: values, filledLabels: uniqueLabels };
}
function renderSetup() {
var app = document.getElementById("app");
var draft = setupDraft;
var m = draft ? draft.meta : state.meta;
var formatKeys = Object.keys(FORMATS);
var sideNames = (FORMATS[m.format] || FORMATS.pf).sideNames;
var sideKeys = Object.keys(sideNames);
var colorsLocked = !currentGating().customColors;
var eyebrow = draft ? (draft.kind === "tournament" ? "New tournament" : "New flow") : "Edit setup";
var heading = draft && draft.kind === "tournament" ? "Set up your tournament" : "Set up your flow";
var subtext = draft && draft.kind === "tournament"
? "Pick a format and fill in who’s debating. Every round you add shares one Preflow you can prep once and reuse all day."
: "Pick a format and fill in who’s debating. You can edit any of this later — your arguments stay put.";
var html =
'
" + tools;
}
function smallModal(html) {
var root = document.getElementById("modal-root");
var veil = document.createElement("div");
veil.className = "modal-veil";
veil.innerHTML = '
' + html + "
";
root.innerHTML = "";
root.appendChild(veil);
veil.addEventListener("click", function (ev) { if (ev.target === veil) closeModal(); });
var c = veil.querySelector('[data-act="cancel"]');
if (c) c.addEventListener("click", closeModal);
return veil;
}
function openFolderPicker(kind, id) {
var e = findEntry(kind, id);
if (!e) return;
var folders = libFolders();
var veil = smallModal(
"
Put \u201c" + escapeHtml(entryTitle(kind, e)) + "\u201d in a folder
" : "") +
'' +
''
);
function setFolder(name) {
if (name) e.folder = name; else delete e.folder;
persistLibrary();
closeModal();
render();
toast(name ? "Moved to " + name + "." : "Taken out of its folder.");
}
veil.querySelectorAll("[data-pick]").forEach(function (b) { b.addEventListener("click", function () { setFolder(b.getAttribute("data-pick")); }); });
var inp = veil.querySelector("#new-folder-input");
function create() { var n = inp.value.trim().slice(0, 60); if (!n) { inp.focus(); return; } setFolder(n); }
veil.querySelector('[data-act="create"]').addEventListener("click", create);
inp.addEventListener("keydown", function (ev) { if (ev.key === "Enter") { ev.preventDefault(); create(); } });
setTimeout(function () { inp.focus(); }, 30);
}
function downloadBundle(name, entries, asFolder) {
var bundle = { roundflowBundle: 1, name: name, folder: asFolder ? name : null, exportedAt: new Date().toISOString(),
tournaments: entries.tournaments, flows: entries.flows };
var blob = new Blob([JSON.stringify(bundle)], { type: "application/json" });
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = ((name || "roundflow").trim().replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase() || "roundflow") + ".roundflow.json";
document.body.appendChild(a);
a.click();
setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1500);
var n = entries.tournaments.length + entries.flows.length;
toast("Downloaded " + n + (n === 1 ? " item" : " items") + ". Anyone can open it in RoundFlow with Import file.");
}
function importBundleFile(file) {
var reader = new FileReader();
reader.onload = function () {
var data;
try { data = JSON.parse(reader.result); } catch (err) { toast("That isn't a RoundFlow file."); return; }
var ts = [], fl = [];
if (data && data.roundflowBundle) { ts = data.tournaments || []; fl = data.flows || []; }
else if (data && Array.isArray(data.rounds)) ts = [data];
else if (data && Array.isArray(data.pages)) fl = [data];
else { toast("That isn't a RoundFlow file."); return; }
var folder = data && data.folder ? String(data.folder).slice(0, 60) : "";
function clean(x) { var c = JSON.parse(JSON.stringify(x)); delete c.teamPrivate; delete c.shareWith; delete c.publicUrl; delete c.isExample; c.pinned = false; if (folder) c.folder = folder; return c; }
ts.forEach(function (t) { var c = clean(t); c.id = uid("tournament"); (c.rounds || []).forEach(function (rd) { rd.tournamentId = c.id; }); library.tournaments.push(c); });
fl.forEach(function (f) { var c = clean(f); c.id = uid("flow"); c.tournamentId = null; library.flows.push(c); });
persistLibrary();
if (folder) libFolder = folder;
render();
var n = ts.length + fl.length;
toast("Imported " + n + (n === 1 ? " item" : " items") + (folder ? " into " + folder : "") + ".");
};
reader.readAsText(file);
}
function openFolderShare(name) {
var ents = folderEntries(name);
var all = ents.tournaments.concat(ents.flows).filter(function (e) { return !sharedInfo(e.id); });
var opts = [["private", "Only me", "Nobody else on the team sees these."], ["coach", "My coach", "Your coach can view them. Teammates can't."], ["team", "Whole team", "Coach and teammates can view them and make a copy."]];
var veil = smallModal(
"
Share everything in \u201c" + escapeHtml(name) + "\u201d
" +
"
Sets who on your team can see all " + all.length + (all.length === 1 ? " item" : " items") + ". You can still change any one later with its Share button.
" +
opts.map(function (o) { return '"; }).join("") +
''
);
veil.querySelectorAll("[data-share-all]").forEach(function (b) {
b.addEventListener("click", function () {
var v = b.getAttribute("data-share-all");
all.forEach(function (e) { e.shareWith = v; delete e.teamPrivate; });
persistLibrary();
closeModal();
render();
toast(v === "private" ? "Everything in " + name + " is private now." : v === "coach" ? "Your coach can see everything in " + name + "." : "Your whole team can see everything in " + name + ".");
});
});
}
function wireFolders() {
document.querySelectorAll("[data-folder-pick]").forEach(function (b) {
b.addEventListener("click", function () { libFolder = b.getAttribute("data-folder-pick"); render(); });
});
document.querySelectorAll("[data-folder-entry]").forEach(function (b) {
b.addEventListener("click", function (ev) { ev.stopPropagation(); var p = b.getAttribute("data-folder-entry").split("|"); openFolderPicker(p[0], p[1]); });
});
document.querySelectorAll("[data-download-tournament]").forEach(function (b) {
b.addEventListener("click", function () {
var t = findEntry("tournament", b.getAttribute("data-download-tournament"));
if (t) downloadBundle(t.name || "tournament", { tournaments: [t], flows: [] }, false);
});
});
document.querySelectorAll("[data-folder-act]").forEach(function (b) {
b.addEventListener("click", function () {
var act = b.getAttribute("data-folder-act");
var name = libFolder;
if (!name) return;
if (act === "download") downloadBundle(name, folderEntries(name), true);
else if (act === "share") openFolderShare(name);
else if (act === "remove") {
var ents = folderEntries(name);
ents.tournaments.concat(ents.flows).forEach(function (e) { delete e.folder; });
libFolder = "";
persistLibrary();
render();
toast("Folder removed. Its flows are still in My Flows.");
} else if (act === "rename") {
var veil = smallModal('
Rename folder
' +
'');
var inp = veil.querySelector("#rename-folder-input");
var ok = function () {
var n = inp.value.trim().slice(0, 60);
if (!n) return;
var ents = folderEntries(name);
ents.tournaments.concat(ents.flows).forEach(function (e) { e.folder = n; });
libFolder = n;
persistLibrary();
closeModal();
render();
};
veil.querySelector('[data-act="ok"]').addEventListener("click", ok);
inp.addEventListener("keydown", function (ev) { if (ev.key === "Enter") { ev.preventDefault(); ok(); } });
setTimeout(function () { inp.focus(); inp.select(); }, 30);
}
});
});
var impBtn = document.getElementById("btn-import-file");
var impInp = document.getElementById("import-file-input");
if (impBtn && impInp) {
impBtn.addEventListener("click", function () { impInp.click(); });
impInp.addEventListener("change", function () { if (impInp.files && impInp.files[0]) importBundleFile(impInp.files[0]); impInp.value = ""; });
}
}
function renderLibrary() {
var app = document.getElementById("app");
var q = libSearchQuery.trim().toLowerCase();
if (libFolder && !libFolders().some(function (f) { return f.name === libFolder; })) libFolder = "";
function hit(name, extra) {
if (!q) return true;
var hay = (name || "").toLowerCase() + " " + (extra || "").toLowerCase();
return hay.indexOf(q) !== -1;
}
var tournaments = library.tournaments.filter(function (t) {
if (libFolder && t.folder !== libFolder) return false;
if (!q) return true;
if (hit(t.name, (FORMATS[t.format] || FORMATS.pf).name)) return true;
return t.rounds.some(function (r) { return hit(r.title); });
});
var flows = library.flows.filter(function (f) {
if (libFolder && f.folder !== libFolder) return false;
return hit(f.title, (FORMATS[f.meta.format] || FORMATS.pf).name);
});
var top = '
' + top + searchRow + actions + folderBarHtml() + body + teamSectionHtml() + "
";
wireLibrary();
}
/* ============ Team library (added 2026-11-25) ============
For accounts on a team with a current license: flows saved to the cloud
are visible read-only to teammates and the coach unless marked private
(entry.teamPrivate, which syncs with the flow). My Flows gets a Team
section listing teammates' flows with View and "Make my own copy". */
var teamLib = { list: null, loading: false, err: "", owner: null };
function teamLibraryOn() {
return !!account && account.planTier === "PAID" && !!account.team && !!account.team.current && !OFFLINE_EMBED;
}
/* ============ Share dialog (added 2026-11-25) ============
Google-Docs-style sharing for each flow and tournament:
- Who on the team can see it: Only me / My coach / Whole team
(entry.shareWith, synced with the flow; default "coach").
- A team link (/app/?open=) for people who already have access.
- General access: Restricted, or "Anyone with the link can view"
(a public read-only link at /f/). */
function shareWithOf(e) {
if (e.shareWith === "private" || e.shareWith === "coach" || e.shareWith === "team") return e.shareWith;
return e.teamPrivate ? "private" : "coach";
}
function isCoachAccount() { return !!account && account.accountType === "EDUCATOR"; }
function shareLabel(e) {
var w = shareWithOf(e);
var who = !teamLibraryOn() ? "" : (w === "team" ? "Team" : (w === "coach" && !isCoachAccount() ? "Coach" : "Only me"));
return "Share" + (who ? " · " + who : "") + (e.publicUrl ? " · 🔗" : "");
}
function teamToggleBtn(kind, e) {
if (OFFLINE_EMBED) return "";
var sh = sharedInfo(e.id);
if (sh) return '' + escapeHtml((sh.from || "Teammate") + "\u2019s flow") + "";
return '";
}
function findEntry(kind, id) {
var list = kind === "tournament" ? library.tournaments : library.flows;
return list.filter(function (x) { return x.id === id; })[0] || null;
}
function entryTitle(kind, e) { return kind === "tournament" ? (e.name || "Tournament") : (e.title || "Untitled flow"); }
function copyText(text, okMsg) {
function fallback() {
var ta = document.createElement("textarea");
ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0";
document.body.appendChild(ta); ta.select();
try { document.execCommand("copy"); toast(okMsg); } catch (e) { toast("Copy this link: " + text); }
document.body.removeChild(ta);
}
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(function () { toast(okMsg); }, fallback);
else fallback();
}
function openShareModal(kind, id) {
var e = findEntry(kind, id);
if (!e) return;
if (!account) {
toast("Sign in to share flows.");
openAuthModal("signin");
return;
}
var teamOn = teamLibraryOn();
var coach = isCoachAccount();
var paid = account.planTier === "PAID";
var link = { url: e.publicUrl || null, busy: false, err: "", loaded: false };
var lock = { until: null, err: "" };
var root = document.getElementById("modal-root");
var veil = document.createElement("div");
veil.className = "modal-veil";
function option(value, title, desc) {
var cur = shareWithOf(e);
var on = cur === value || (coach && value === "private" && cur === "coach");
return '";
}
function paint() {
var teamName = teamOn ? escapeHtml(account.team.name || "your team") : "";
var who = "";
if (teamOn) {
who = '
Who on ' + teamName + " can see it
" +
option("private", "Only me", "Nobody else can see it" + (account.team && account.team.partner ? ", not even your partner" : "") + ".") +
(coach ? "" : option("coach", "My coach", "Your coach can view it" + (account.team.partner ? " (and your partner, " + account.team.partner.name + ", can edit it)" : "") + ". Other teammates can't.")) +
option("team", coach ? "Whole team" : "Whole team", coach ? "Every student on your team can view it and make their own copy." : "Your coach and teammates can view it and make their own copy.") +
"
";
} else if (account.team && !account.team.current) {
who = '
Team sharing turns on when your team has a current license.
';
}
var teamLink = "";
if (teamOn && shareWithOf(e) !== "private" && !(coach && shareWithOf(e) === "coach")) {
teamLink = '';
}
var access;
if (!coach && account.team && account.team.publicLinks === false && !link.url) {
access = '
Your coach has turned off share links for your team. You can still share with your coach and teammates above.
';
} else if (!link.loaded) {
access = '
Checking for a link…
';
} else {
access =
'" +
(link.url
? '
' +
'
' +
'
Anyone with this link can view it (read-only) without signing in, and make their own copy. It won’t show up in search engines. Pick Restricted to turn the link off.' +
(paid ? " The link always shows your latest version." : "") + "
" +
(paid ? "" : '')
: '
' + (paid ? "" : "Free accounts can have 3 links at a time. ") + "Turn this on to share a read-only link with a judge, parent, or another school.
") +
(link.err ? '
' + escapeHtml(link.err) + "
" : "");
}
veil.innerHTML =
'
' +
"
Share “" + escapeHtml(entryTitle(kind, e)) + "”
" +
who +
'
General access
' + access + "
" +
(teamOn && !coach ? '
Round lock
' +
(lock.until
? '
Round in progress until ' + escapeHtml(new Date(lock.until).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })) + '. Only you' + (account.team.partner ? " and your partner" : "") + ' can edit.
'
: '
Starting a round? Lock it so only you' + (account.team.partner ? " and your partner" : "") + ' can edit for the next 6 hours, even if your coach can edit team flows.
') +
(lock.err ? '
' + escapeHtml(lock.err) + "
" : "") + "
" : "") +
'
' + teamLink + '
' +
"
";
veil.querySelector('[data-act="done"]').addEventListener("click", closeModal);
veil.querySelectorAll('input[name="share-with"]').forEach(function (r) {
r.addEventListener("change", function () {
e.shareWith = r.value;
delete e.teamPrivate;
persistLibrary();
render();
paint();
toast(r.value === "private" ? "Only you can see this now." : r.value === "coach" ? "Your coach can see this now." : "Your whole team can see this now.");
});
});
var tl = veil.querySelector('[data-act="team-link"]');
if (tl) tl.addEventListener("click", function () {
copyText(window.location.origin + "/app/?open=" + encodeURIComponent(e.id), "Team link copied. It opens for people on your team who can see this flow.");
});
var sel = veil.querySelector("#share-access");
if (sel) sel.addEventListener("change", function () {
if (sel.value === "anyone") makePublic(false); else removePublic();
});
var cp = veil.querySelector('[data-act="copy-public"]');
if (cp) cp.addEventListener("click", function () { copyText(link.url, "Link copied. Anyone with it can view this flow."); });
var lk = veil.querySelector('[data-act="lock"]'), ul = veil.querySelector('[data-act="unlock"]');
function setLock(on) {
lock.err = "";
apiFetch("/api/flows/" + encodeURIComponent(e.id) + "/lock", { method: "POST", body: { on: on } }).then(function (d) {
lock.until = d.lockedUntil; paint();
toast(on ? "Round locked for 6 hours." : "Round lock ended.");
}).catch(function (err) { lock.err = err.message || "Couldn't change the round lock."; paint(); });
}
if (lk) lk.addEventListener("click", function () { setLock(true); });
if (ul) ul.addEventListener("click", function () { setLock(false); });
var rf = veil.querySelector('[data-act="refresh-public"]');
if (rf) rf.addEventListener("click", function () { makePublic(true); });
}
function makePublic(refresh) {
link.busy = true; link.err = ""; paint();
persistLibrary();
apiFetch("/api/flows/" + encodeURIComponent(e.id) + "/public", {
method: "POST",
body: { kind: kind, title: entryTitle(kind, e), data: e, refresh: !!refresh },
}).then(function (d) {
link.busy = false; link.url = d.publicUrl;
e.publicUrl = d.publicUrl;
// If this created the cloud copy, record its version so sync doesn't see a conflict.
if (cloudEnabled() && d.version) {
var meta = loadCloudMeta();
if (!meta[e.id] || !meta[e.id].v) { meta[e.id] = { v: d.version, h: cloudHash(JSON.stringify(e)) }; saveCloudMeta(meta); }
}
persistLibrary(); render(); paint();
if (refresh) toast("Link updated with your latest changes.");
}).catch(function (err) {
link.busy = false; link.err = err.message || "Couldn't make a link."; paint();
});
}
function removePublic() {
link.busy = true; link.err = ""; paint();
apiFetch("/api/flows/" + encodeURIComponent(e.id) + "/public", { method: "DELETE" }).catch(function () {}).then(function () {
link.busy = false; link.url = null;
delete e.publicUrl;
persistLibrary(); render(); paint();
toast("Link turned off. It no longer opens.");
});
}
root.innerHTML = "";
root.appendChild(veil);
veil.addEventListener("click", function (ev) { if (ev.target === veil) closeModal(); });
paint();
if (teamOn && !coach) apiFetch("/api/flows/" + encodeURIComponent(e.id)).then(function (d) { lock.until = d.flow && d.flow.lockedUntil; paint(); }).catch(function () {});
apiFetch("/api/flows/" + encodeURIComponent(e.id) + "/share").then(function (d) {
link.loaded = true;
if (d.visibility !== null || !paid) {
link.url = d.publicUrl || null;
if (link.url) e.publicUrl = link.url; else delete e.publicUrl;
}
paint();
}).catch(function () { link.loaded = true; paint(); });
}
// A flow from someone else (team link or public link) goes into my flows.
function copyIntoMyFlows(kind, data) {
var copy = JSON.parse(JSON.stringify(data));
delete copy.teamPrivate; delete copy.shareWith; delete copy.publicUrl;
copy.pinned = false;
if (kind === "tournament") {
copy.id = uid("tournament");
copy.name = (copy.name || "Tournament") + " (copy)";
(copy.rounds || []).forEach(function (rd) { rd.tournamentId = copy.id; });
library.tournaments.push(copy);
} else {
copy.id = uid("flow");
copy.title = (copy.title || "Flow") + " (copy)";
copy.tournamentId = null;
library.flows.push(copy);
}
persistLibrary();
render();
toast("Copied into your flows. Edit it however you like; the original stays theirs.");
}
// /app/?view= (public link) and /app/?open= (team link).
var linkParamsHandled = false;
function handleShareLinkParams(signedInKnown) {
if (linkParamsHandled || OFFLINE_EMBED) return;
var params = new URLSearchParams(window.location.search);
var slug = params.get("view");
var openId = params.get("open");
if (!slug && !openId) { linkParamsHandled = true; return; }
if (openId && !signedInKnown) return; // wait until we know who's signed in
linkParamsHandled = true;
try {
params.delete("view"); params.delete("open");
var qs = params.toString();
history.replaceState(null, "", window.location.pathname + (qs ? "?" + qs : ""));
} catch (e) {}
if (slug) {
try { var m = document.createElement("meta"); m.name = "robots"; m.content = "noindex"; document.head.appendChild(m); } catch (e) {}
apiFetch("/api/public/flows/" + encodeURIComponent(slug)).then(function (d) {
var f = d.flow;
openSubmissionViewer({
payload: viewableFromEntry(f.kind, f.data), title: f.title, student_name: f.ownerName, heading: "Shared by",
onCopy: function () { closeModal(); copyIntoMyFlows(f.kind, f.data); },
});
}).catch(function (err) { toast(err.message || "This link doesn't work anymore."); });
return;
}
var own = findEntry("flow", openId) ? "flow" : (findEntry("tournament", openId) ? "tournament" : null);
if (own === "flow") { library.activeRef = { kind: "flow", flowId: openId }; state = getActiveEntry(); persistLibrary(); render(); return; }
if (own === "tournament") { toast("That's one of your tournaments. It's in My Flows."); return; }
if (!account) { toast("Sign in to open this flow."); openAuthModal("signin"); linkParamsHandled = false; try { history.replaceState(null, "", window.location.pathname + "?open=" + encodeURIComponent(openId)); } catch (e) {} return; }
apiFetch("/api/flows/" + encodeURIComponent(openId)).then(function (d) {
var f = d.flow;
openSubmissionViewer({
payload: viewableFromEntry(f.kind, f.data), title: f.title, student_name: f.ownerName || "a teammate",
onCopy: function () { closeModal(); copyIntoMyFlows(f.kind, f.data); },
});
}).catch(function () { toast("You don't have access to that flow. Ask its owner to share it with you."); });
}
function teamSectionHtml() {
if (!teamLibraryOn()) return "";
var head = '
No team flows match “' + escapeHtml(libSearchQuery) + '”.
');
}
function loadTeamFlows() {
teamLib.loading = true;
teamLib.err = "";
render();
apiFetch("/api/team/flows").then(function (data) {
teamLib.loading = false;
teamLib.list = data.flows || [];
render();
}).catch(function (err) {
teamLib.loading = false;
teamLib.err = err.message || "Couldn't load your team's flows.";
render();
});
}
/* ============ Partners, coach editing, round lock (added 2026-11-26) ============ */
function sharedInfo(id) {
try { var m = loadCloudMeta()[id]; return m && m.shared ? m : null; } catch (e) { return null; }
}
// Open a partner's / student's flow for editing: it joins My Flows and syncs.
function editTeamFlow(id) {
apiFetch("/api/flows/" + encodeURIComponent(id) + "/join", { method: "POST" }).then(function (d) {
var f = d.flow;
replaceLocalEntry(f.kind, f.id, f.data);
var meta = loadCloudMeta();
meta[f.id] = { v: f.version, h: cloudHash(JSON.stringify(f.data)), shared: true, from: f.ownerName || "" };
saveCloudMeta(meta);
if (f.kind === "tournament") { library.activeRef = null; }
else { library.activeRef = { kind: "flow", flowId: f.id }; state = getActiveEntry(); }
try { localStorage.setItem(libraryKeyFor(libraryOwner), JSON.stringify(library)); } catch (e) {}
render();
toast("Editing " + (f.ownerName ? f.ownerName + "\u2019s" : "this") + " flow. Your changes save to their copy. It\u2019s in My Flows now.");
}).catch(function (err) { toast(err.message || "Couldn't open that flow for editing."); });
}
function viewAlumniFlow(id) {
apiFetch("/api/team/alumni/" + encodeURIComponent(id)).then(function (d) {
var f = d.flow;
openSubmissionViewer({
payload: viewableFromEntry(f.kind, f.data), title: f.title, student_name: (f.ownerName || "a former teammate") + " (graduated)",
onCopy: function () { closeModal(); copyIntoMyFlows(f.kind, f.data); },
});
}).catch(function (err) { toast(err.message || "Couldn't open that flow."); });
}
function fetchTeamFlow(id) {
var alum = (teamLib.list || []).filter(function (x) { return x.id === id && x.alumni; })[0];
return apiFetch((alum ? "/api/team/alumni/" : "/api/flows/") + encodeURIComponent(id)).then(function (data) { return data.flow; });
}
// A tournament is shown in the read-only viewer as one flow whose pages
// are the shared preflow followed by every round's pages.
function viewableFromEntry(kind, data) {
if (kind !== "tournament") return data;
var pages = [];
if (data.preflow) pages.push(Object.assign({}, data.preflow, { title: "Preflow (shared)" }));
(data.rounds || []).forEach(function (rd) {
(rd.pages || []).forEach(function (p) { pages.push(Object.assign({}, p, { title: (rd.title || "Round") + " · " + (p.title || "Flow") })); });
});
return { meta: data.defaultMeta || { format: data.format }, pages: pages };
}
function viewTeamFlow(id) {
fetchTeamFlow(id).then(function (flow) {
openSubmissionViewer({
payload: viewableFromEntry(flow.kind, flow.data), title: flow.title, student_name: flow.ownerName,
onCopy: function () { closeModal(); copyIntoMyFlows(flow.kind, flow.data); },
});
}).catch(function (err) { toast(err.message || "Couldn't open that flow."); });
}
function copyTeamFlow(id) {
fetchTeamFlow(id).then(function (flow) { copyIntoMyFlows(flow.kind, flow.data); })
.catch(function (err) { toast(err.message || "Couldn't copy that flow."); });
}
function wireTeamLibrary() {
if (teamLibraryOn()) {
if (teamLib.owner !== account.id) { teamLib = { list: null, loading: false, err: "", owner: account.id }; }
if (!teamLib.list && !teamLib.loading && !teamLib.err) { setTimeout(loadTeamFlows, 0); }
}
document.querySelectorAll("[data-team-load]").forEach(function (b) { b.addEventListener("click", loadTeamFlows); });
document.querySelectorAll("[data-team-view]").forEach(function (b) {
b.addEventListener("click", function () { viewTeamFlow(b.getAttribute("data-team-view")); });
});
document.querySelectorAll("[data-team-edit]").forEach(function (b) {
b.addEventListener("click", function () { editTeamFlow(b.getAttribute("data-team-edit")); });
});
document.querySelectorAll("[data-alumni-copy]").forEach(function (b) {
b.addEventListener("click", function () { copyTeamFlow(b.getAttribute("data-alumni-copy")); });
});
document.querySelectorAll("[data-team-copy]").forEach(function (b) {
b.addEventListener("click", function () { copyTeamFlow(b.getAttribute("data-team-copy")); });
});
document.querySelectorAll("[data-share-entry]").forEach(function (b) {
b.addEventListener("click", function () {
var parts = b.getAttribute("data-share-entry").split("|");
openShareModal(parts[0], parts[1]);
});
});
}
/* ============ First-run onboarding (added 2026-11-25) ============
A short 4-step tour (auto-opens once on a fresh device with no flows,
and from "How it works" in My Flows) plus a ready-made sample PF flow
that shows columns, responses, links, labels and a second sheet. */
var ONBOARD_KEY = "roundflow.onboarded.v1";
var onboardChecked = false;
function buildSampleFlow() {
var meta = {
format: "pf", mySide: "pro", topic: "Sample: Schools should switch to a four-day week",
proTeam: "Sample Pro", conTeam: "Sample Con", proNames: "", conNames: "",
proColor: "#db6300", conColor: "#5797ff", round: "Sample round", judge: "", judgeLink: "", tabroomLink: "",
};
var main = newPage("Main Flow", "flow");
var cards = main.cards, links = main.links;
function card(col, text, opts) {
opts = opts || {};
var c = newCard(col, { text: text, label: opts.label || "", evidenceCite: opts.cite || null, color: opts.color || null });
cards.push(c);
if (opts.respondsTo) links.push({ id: uid("link"), fromId: c.id, toId: opts.respondsTo.id, tag: "Responds to" });
return c;
}
var p1 = card("pro-case", "Burnout: a fifth day off gives students time to rest, catch up, and work.", { label: "C1", cite: "Sample card" });
var p2 = card("pro-case", "Budget: districts save on buses and utilities, money that can go to teachers.", { label: "C2" });
var c1 = card("con-case", "Learning loss: fewer school days hurt students who are already behind.", { label: "C1", cite: "Sample card" });
var c2 = card("con-case", "Childcare: working families have to pay for the fifth day.", { label: "C2" });
card("pro-reb", "Days get longer, so total hours of class stay about the same.", { respondsTo: c1 });
var pr2 = card("pro-reb", "Savings can fund optional Friday programs.", { respondsTo: c2 });
var cr1 = card("con-reb", "Longer days add fatigue. The burnout just moves to Monday through Thursday.", { respondsTo: p1 });
card("con-reb", "Savings are tiny next to the whole budget.", { respondsTo: p2 });
card("pro-sum", "Extend C1: fatigue from longer days is far smaller than a full recovery day.", { respondsTo: cr1 });
card("con-sum", "Friday programs are optional and unfunded, so childcare is still a cost for families.", { respondsTo: pr2 });
card("pro-ff", "Weigh: wellbeing affects every student, every single week.");
card("con-ff", "Weigh: learning loss is the hardest harm to undo. Prefer it.", { color: "#c0392b" });
var off = newPage("Off: Teacher pay K", "flow");
var o1 = newCard("con-case", { text: "Off-case positions get their own sheet. Use + Sheet to add one for each argument.", label: "1NC" });
off.cards.push(o1);
var o2 = newCard("pro-reb", { text: "Answers go in the next speech's column, linked back with Respond." });
off.cards.push(o2);
off.links.push({ id: uid("link"), fromId: o2.id, toId: o1.id, tag: "Responds to" });
return {
id: uid("flow"), title: "Sample flow: four-day school week", meta: meta,
pages: [main, off], activePageId: main.id, setupDone: true, tournamentId: null, pinned: false, shareWith: "private",
};
}
function openSampleFlow() {
var existing = library.flows.filter(function (f) { return f.isSample; })[0];
var flow = existing;
if (!flow) {
flow = buildSampleFlow();
flow.isSample = true;
library.flows.push(flow);
}
library.activeRef = { kind: "flow", flowId: flow.id };
state = getActiveEntry();
if (state && !state.activePageId && state.pages.length) state.activePageId = state.pages[0].id;
persistLibrary();
closeModal();
render();
toast("This is a sample flow. Edit anything, or delete it from My Flows when you're done.");
}
function openTour() {
try { localStorage.setItem(ONBOARD_KEY, "1"); } catch (e) {}
var steps = [
{ t: "Welcome to RoundFlow", b: "A flow sheet built for debate. Pick a format and the speeches are set up for you, one column per speech, left to right in speaking order." },
{ t: "Flow each speech", b: "Click + Add in a column and type. Press Enter for the next argument, Shift + Enter for a new line. + Add also has argument shells (disad, counterplan, kritik, topicality, theory) with their parts laid out for you." },
{ t: "Respond across the flow", b: "Press ⌘/Ctrl + Enter (or → Respond on an argument) and your answer lands in the next speech's column, linked back to what it answers. Use Link to connect any two arguments." },
{ t: "Sheets, colors, sharing", b: "Use + Sheet for separate pages (each off-case or advantage). Colors lets you color-code each side. Flows save as you go. Share sends one to your coach, your team, or anyone with a link." },
];
var i = 0;
var root = document.getElementById("modal-root");
var veil = document.createElement("div");
veil.className = "modal-veil";
function paint() {
var st = steps[i];
var last = i === steps.length - 1;
veil.innerHTML =
'
";
var b;
if ((b = veil.querySelector('[data-act="skip"]'))) b.addEventListener("click", closeModal);
if ((b = veil.querySelector('[data-act="back"]'))) b.addEventListener("click", function () { i--; paint(); });
if ((b = veil.querySelector('[data-act="next"]'))) b.addEventListener("click", function () { i++; paint(); });
if ((b = veil.querySelector('[data-act="keys"]'))) b.addEventListener("click", function () { closeModal(); openShortcutsModal(); });
if ((b = veil.querySelector('[data-act="sample"]'))) b.addEventListener("click", openExamplesPicker);
}
root.innerHTML = "";
root.appendChild(veil);
veil.addEventListener("click", function (e) { if (e.target === veil) closeModal(); });
paint();
}
function wireOnboarding() {
var b;
if ((b = document.getElementById("btn-how-it-works"))) b.addEventListener("click", openTour);
if ((b = document.getElementById("btn-sample-flow"))) b.addEventListener("click", openExamplesPicker);
if ((b = document.getElementById("btn-examples"))) b.addEventListener("click", openExamplesPicker);
if (onboardChecked || OFFLINE_EMBED) return;
onboardChecked = true;
var seen = false;
try { seen = !!localStorage.getItem(ONBOARD_KEY); } catch (e) { seen = true; }
var hasLinkParam = /[?&](view|open|checkout)=/.test(window.location.search);
if (!seen && !hasLinkParam && !library.flows.length && !library.tournaments.length) {
setTimeout(function () {
var root = document.getElementById("modal-root");
if (root && !root.children.length && !library.flows.length && !library.tournaments.length) openTour();
}, 700);
}
}
/* ============ Find it on Tabroom (added 2026-11-25) ============
New-tournament setup gets a search box. It matches the upcoming
tournaments on Tabroom's calendar (cached by our server), and searches
Tabroom by name for anything further out. Picking one fills in the
tournament name and Tabroom link. */
var tabroomList = null;
var tabroomListPromise = null;
function loadTabroomList() {
if (tabroomList) return Promise.resolve(tabroomList);
if (!tabroomListPromise) {
tabroomListPromise = apiFetch("/api/tabroom/tournaments").then(function (d) {
tabroomList = d.tournaments || [];
return tabroomList;
}).catch(function (err) { tabroomListPromise = null; throw err; });
}
return tabroomListPromise;
}
function tabroomRowHtml(t) {
var where = [t.city, t.state].filter(Boolean).join(", ");
return '";
}
function wireTabroomPicker(draft) {
var input = document.getElementById("f-tabroom-search");
var box = document.getElementById("tabroom-results");
if (!input || !box) return;
var shown = [];
var searchTimer = null;
var lastQ = "";
function show(list, note) {
shown = list;
box.innerHTML = list.map(tabroomRowHtml).join("") + (note ? '
' + escapeHtml(note) + "
" : "");
box.querySelectorAll("[data-tabroom-pick]").forEach(function (b) {
b.addEventListener("mousedown", function (e) { e.preventDefault(); });
b.addEventListener("click", function () {
var t = shown.filter(function (x) { return x.id === b.getAttribute("data-tabroom-pick"); })[0];
if (!t) return;
var nameEl = document.getElementById("f-tournament-name");
var linkEl = document.getElementById("f-tournament-tabroom");
if (nameEl) nameEl.value = t.name;
if (linkEl) linkEl.value = t.url;
if (draft) { draft.tournamentName = t.name; draft.tabroomLink = t.url; }
input.value = "";
box.innerHTML = '
Added ' + escapeHtml(t.name) + ". Pick your format below.
";
});
});
}
function matchLocal(q) {
var words = q.toLowerCase().split(/\s+/).filter(Boolean);
var today = new Date(); today.setDate(today.getDate() - 3);
var cutoff = today.toISOString().slice(0, 10);
return (tabroomList || []).filter(function (t) {
var hay = (t.name + " " + t.city + " " + t.state).toLowerCase();
return words.every(function (w) { return hay.indexOf(w) !== -1; }) && (!t.start || t.start >= cutoff);
}).sort(function (a, b) { return String(a.start || "").localeCompare(String(b.start || "")); });
}
function update() {
var q = input.value.trim();
lastQ = q;
clearTimeout(searchTimer);
if (q.length < 2) { box.innerHTML = ""; return; }
loadTabroomList().then(function () {
if (q !== lastQ) return;
var local = matchLocal(q).slice(0, 8);
show(local, local.length ? "" : "Searching all of Tabroom…");
if (q.length >= 3 && local.length < 4) {
searchTimer = setTimeout(function () {
apiFetch("/api/tabroom/search?q=" + encodeURIComponent(q)).then(function (d) {
if (q !== lastQ) return;
var ids = {};
local.forEach(function (t) { ids[t.id] = true; });
var more = (d.tournaments || []).filter(function (t) { return !ids[t.id]; }).slice(0, 8 - local.length);
var all = local.concat(more);
show(all, all.length ? "" : "No Tabroom tournaments match. You can type the name and paste the link instead.");
}).catch(function () {
if (q === lastQ && !local.length) show([], "Couldn't reach Tabroom. Type the name and paste the link instead.");
});
}, 350);
}
}).catch(function () {
show([], "Couldn't reach Tabroom right now. Type the name and paste the link instead.");
});
}
input.addEventListener("input", update);
input.addEventListener("focus", function () { loadTabroomList().catch(function () {}); });
input.addEventListener("keydown", function (e) {
if (e.key === "Enter") { e.preventDefault(); var first = box.querySelector("[data-tabroom-pick]"); if (first) first.click(); }
});
}
/* ============ All sheets on one page (added 2026-11-26) ============
Optional view: every sheet of the flow stacked top to bottom, so you can
scroll the whole round instead of switching tabs. Remembered per device.
Clicking or typing in a sheet makes it the active one, so all the normal
editing code (which works on the active sheet) keeps working. */
var VIEW_ALL_KEY = "roundflow.viewAllSheets.v1";
function viewAllSheets() { try { return localStorage.getItem(VIEW_ALL_KEY) === "1"; } catch (e) { return false; } }
function sheetList() {
var tour = currentTournament();
var list = [];
if (tour && tour.preflow) list.push({ id: SHARED_PREFLOW_ID, page: tour.preflow, title: "Preflow (shared)" });
state.pages.forEach(function (p) { list.push({ id: p.id, page: p, title: p.title }); });
return list;
}
function sheetPageById(id) {
var hit = sheetList().filter(function (x) { return x.id === id; })[0];
return hit ? hit.page : currentPage();
}
function renderAllSheets() {
return '
' + sheetList().map(function (s) {
var body = renderFlowBody(s.page).replace('
";
}
function activateSheetFromEvent(e) {
if (!state || pendingLink || !viewAllSheets() || !e.target || !e.target.closest) return;
var sec = e.target.closest("[data-sheet]");
if (!sec) return;
var id = sec.getAttribute("data-sheet");
if (id && sheetPageById(id) !== currentPage()) {
state.activePageId = id;
document.querySelectorAll(".sheet-section.active").forEach(function (x) { x.classList.remove("active"); });
sec.classList.add("active");
}
}
document.addEventListener("pointerdown", activateSheetFromEvent, true);
document.addEventListener("focusin", activateSheetFromEvent, true);
document.addEventListener("click", function (e) {
if (!e.target || !e.target.closest) return;
if (e.target.closest("#btn-view-all")) {
try { localStorage.setItem(VIEW_ALL_KEY, viewAllSheets() ? "0" : "1"); } catch (err) {}
render();
toast(viewAllSheets() ? "Showing every sheet on one page. Scroll to move between them." : "Showing one sheet at a time.");
return;
}
var tab = e.target.closest(".tab[data-page]");
if (tab && viewAllSheets() && !e.target.closest("button")) {
var pid = tab.getAttribute("data-page");
setTimeout(function () {
var s = document.querySelector('[data-sheet="' + pid + '"]');
if (s) s.scrollIntoView({ behavior: "smooth", block: "start" });
}, 60);
}
});
/* ============ Congress motions (added 2026-11-26) ============ */
var CONGRESS_MOTIONS = [
"Previous question", "Lay on the table", "Take from the table", "Amend", "Suspend the rules",
"Extend questioning", "Refer to committee", "Postpone", "Reconsider", "Recess", "Adjourn",
"Point of order", "Point of personal privilege", "Parliamentary inquiry", "Point of information",
"Appeal the chair", "Division of the chamber", "Withdraw a motion",
];
function renderMotionMenu(colId) {
return '
";
}
/* ============ Example rounds (added 2026-11-26) ============
Real national final rounds, flowed as examples (paraphrased taglines,
not transcripts). One per event; more events get added here.
Card tuple: [key, columnId, text, { l: label, c: cite, r: key it responds to }] */
var EXAMPLE_ROUNDS = {
pf: {
title: "Example: 2026 NSDA Nationals PF Final",
blurb: "Public Forum · US force to remove authoritarian leaders · Con won 12-3",
meta: { format: "pf", mySide: "", topic: "The United States is justified in using force to remove authoritarian leaders from power.",
proTeam: "Brentwood (Pro)", conTeam: "Theodore Roosevelt (Con)", round: "Final (Con spoke first)" },
sheets: [
{ title: "Con case", cards: [
["c0", "con-case", "Question isn't whether autocrats are bad, it's whether US force makes life better after. History says no.", { l: "Framing" }],
["c1", "con-case", "Harm 1, economy: intervention cuts US trade with the target 45% (~$272M/yr); post-change violence drives investors out.", { l: "C1: Bad deal worse", c: "Downs 17" }],
["c2", "con-case", "Iran war spillover: one month shrinks regional GDP 6%, 3.7M jobs lost, 4M into poverty.", { c: "UNDP via Al Jazeera" }],
["c3", "con-case", "Harm 2, conflict: 63 US-backed regime changes → civil war within a decade (power vacuum). Intensity 45x higher.", { c: "O'Rourke 17, Task 25" }],
["c4", "con-case", "38M displaced in the Middle East; ~30M killed by US intervention.", { c: "Brown U; Chossudovsky 15" }],
["c5", "con-case", "Harm 3, instability: more coups after US intervention; US-backed leaders seen as puppets. Only 3 of 28 attempts became lasting democracies.", { c: "Berger 24; Denison 20" }],
["p1", "pro-reb", "Turn: intervention raises target GDP per capita 39%, growth in 70% of cases. Downs only measures trade volume.", { c: "Sevika 16", r: "c1" }],
["p2", "pro-reb", "Conflict is inevitable under autocrats. Compare to the counterfactual: Saddam would have escalated.", { c: "Dawkins 04", r: "c3" }],
["p3", "pro-reb", "O'Rourke and Denison study Cold War covert ops that removed democratic socialists, not authoritarians. Not topical.", { r: "c3" }],
["p4", "pro-reb", "Berger uses declassified Cold War data, same flaw.", { r: "c5" }],
["s1", "con-sum", "Extend: civil war risk up and 45x intensity are conceded. 30M killed.", { r: "p2" }],
["s2", "con-sum", "Iraq: US was close to a peaceful deal with Saddam; diplomacy avoids the civil war.", { c: "Downs", r: "p2" }],
["s3", "con-sum", "Their indict: our data sets include removals of authoritarian leaders too.", { r: "p3" }],
["s4", "con-sum", "Weigh on scope: we know how many interventions killed; lives saved are unknown.", { l: "Weighing" }],
["q1", "pro-sum", "Yes, civil war risk rises temporarily, but autocrats kill 6x more than all wars combined.", { r: "s1" }],
["q2", "pro-sum", "Prefer our evidence on specificity: theirs lumps in removing democracies.", { r: "s3" }],
["f1", "con-ff", "45x intensity makes the atrocities they cite worse. Prefer us on specificity and scope.", { r: "q1" }],
["g1", "pro-ff", "Every con study counts removals of democracies. Don't vote on that evidence.", { r: "f1" }],
] },
{ title: "Pro case", cards: [
["a0", "pro-case", "Not perfection: US intervention stays necessary for global peace; restraint creates vacuums.", { l: "Framing", c: "Blackwell, CFR" }],
["a1", "pro-case", "On net, 64 US interventions promote democracy. Targeting autocrats → democracy in 76% of cases (Panama today; Iraq trending up).", { c: "Herman 08; Nomikos 14" }],
["a2", "pro-case", "A, US influence: US-led order kept the peace since WWII. Regime change is what autocrats fear and the only credible deterrent.", { l: "C1: Maintaining peace", c: "Brands 25; Yu; Will" }],
["a3", "pro-case", "B, atrocities: tied to autocracies; US action cuts genocide. No one else will act (Syria).", { c: "Van der Maat; Krain; Hamid 16" }],
["a4", "pro-case", "Autocratic mass killing claims 6x more lives than all wars combined.", { l: "Impact", c: "Rummel 94" }],
["b1", "con-reb", "Not anti-intervention: conventional force (bombing, peacekeeping) deters without a power vacuum.", { c: "SI 26", r: "a0" }],
["b2", "con-reb", "Nomikos: no published data; includes French action in CAR; countries already democratizing.", { c: "Downs", r: "a1" }],
["b3", "con-reb", "Panama is 1 of 3 successes, and Noriega was our own CIA asset.", { r: "a1" }],
["b4", "con-reb", "Threats corner leaders and kill diplomacy. Kosovo emboldened Russia; Venezuela emboldens China on Taiwan.", { c: "Denison; Carpenter", r: "a2" }],
["b5", "con-reb", "Krain isn't US-specific and is theoretical; you need to oppose leaders, not remove them.", { r: "a3" }],
["d1", "pro-sum", "Nomikos is a peer-reviewed postdoc; Herman's 64 cases are unanswered.", { r: "b2" }],
["d2", "pro-sum", "Diplomacy without a credible threat is a strongly worded letter.", { r: "b4" }],
["e1", "con-sum", "Conceded: intervention emboldens adversaries, and force alone deters (Burundi, Tanzania).", { r: "d2" }],
["h1", "con-ff", "Herman and Hamid are about intervention, not removing leaders. The 6x figure assumes we intervene everywhere.", { r: "d1" }],
["i1", "pro-ff", "Pressure without removal leaves the autocrat in power. Remove the root cause. Vote pro to save lives.", { r: "h1" }],
] },
],
},
ld: {
title: "Example: 2010 Nationals LD Final",
blurb: "Lincoln-Douglas · Compulsory DNA databases for non-felons",
meta: { format: "ld", mySide: "", topic: "Compulsory inclusion of non-felons' DNA in any government database is unjust.",
proTeam: "Aff", conTeam: "Neg (Harvard-Westlake)", round: "Final" },
sheets: [
{ title: "AC", cards: [
["a0", "aff-ac", "Value: human rights. Criterion: justified government interference (rights can be restricted only after you harm another).", { l: "Framework" }],
["a1", "aff-ac", "Burden: prove forcing innocent people's DNA is unjust. Not a debate about practicality.", { l: "Burden" }],
["a2", "aff-ac", "People labeled suspects stop cooperating with police.", { l: "C1: Obstructs justice", c: "White, Oxford" }],
["a3", "aff-ac", "Per-capita DNA convictions fell after the UK kept non-convicts' records.", { c: "GeneWatch UK 06" }],
["a4", "aff-ac", "Overreliance: stray hair or skin at a scene becomes a 'smoking gun'.", { c: "NYT 2010" }],
["a5", "aff-ac", "Presumption of innocence, self-incrimination, self-ownership of your own body.", { l: "C2: Violates rights", c: "UDHR 11 & 17; Locke" }],
["n1", "neg-nc", "Justice is comparative. His standard calls anything that harms one person unjust.", { r: "a0" }],
["n2", "neg-nc", "We already take fingerprints and newborn blood tests.", { r: "a0" }],
["n3", "neg-nc", "No causal link in GeneWatch. Trust goes up when DNA can clear you.", { r: "a3" }],
["n4", "neg-nc", "Self-incrimination means testimony, not samples. A cheek swab is minimal.", { r: "a5" }],
["n5", "neg-nc", "Alternative is eyewitness testimony, which convicts the innocent.", { c: "Grady 03", r: "a5" }],
["r1", "aff-1ar", "It's not one person: every innocent person loses self-ownership.", { r: "n1" }],
["r2", "aff-1ar", "It is causal: a per-capita study shows convictions fell.", { r: "n3" }],
["r3", "aff-1ar", "Overreliance argument is unanswered. Self-ownership is dropped: extend.", { r: "a4" }],
["m1", "neg-nr", "His justice is self-defeating. Prefer comparative justice.", { r: "r1" }],
["m2", "neg-nr", "Newborn tests show no real harm to the self. Eyewitness analysis unanswered.", { r: "r3" }],
["z1", "aff-2ar", "Their benefits are speculative: no universal database exists anywhere. Ours is a guaranteed harm.", { l: "Voter", r: "m2" }],
] },
{ title: "NC", cards: [
["k0", "neg-nc", "Value: justice (giving each their due). Criterion: minimizing discrimination.", { l: "Framework" }],
["k1", "neg-nc", "Justice is comparative. Don't let the perfect be the enemy of the good.", { l: "Obs 1", c: "London Times 09" }],
["k2", "neg-nc", "DNA databases are already entrenched. The question is everyone vs. selected groups.", { l: "Obs 2", c: "Polansky 05" }],
["k3", "neg-nc", "Selective databases mean DNA dragnets that target minorities (Ann Arbor).", { l: "C1: Discrimination", c: "Peterson 00" }],
["k4", "neg-nc", "A universal database ends dragnets and racial bias and prevents wrongful convictions.", { c: "Seringhaus, NYT 2010" }],
["j1", "aff-1ar", "Not topical: flaws in a felon-only database don't justify a compulsory one.", { r: "k2" }],
["j2", "aff-1ar", "Bias is a police problem, not a database problem.", { c: "Rothstein", r: "k3" }],
["j3", "aff-1ar", "Treating innocent people like criminals isn't equality.", { r: "k4" }],
["o1", "neg-nr", "Without universal inclusion, dragnets are inevitable.", { r: "j1" }],
["o2", "neg-nr", "Rothstein never explains why. Dragnets target minorities, not criminals.", { r: "j2" }],
["y1", "aff-2ar", "A database can't discriminate; police do. Universal inclusion doesn't fix racist policing.", { l: "Voter", r: "o2" }],
] },
],
},
policy: {
title: "Example: 2024 NSDA Nationals Policy Final",
blurb: "Policy · Fiscal redistribution: Social Security 2100 Act · stock issues",
meta: { format: "policy", mySide: "", topic: "The USFG should substantially increase fiscal redistribution in the United States.",
proTeam: "Aff (Bellarmine)", conTeam: "Neg (Bellarmine)", round: "Final" },
sheets: [
{ title: "Case", cards: [
["h1", "aff-1ac", "Social Security insolvent by 2035: benefits cut to ~80%, retiree poverty up 60%.", { l: "Harms", c: "Miller, NYT 23" }],
["h2", "aff-1ac", "Most workers pay 6.2%; the wealthiest pay an effective 0.08%.", { c: "Richtman 22" }],
["i1", "aff-1ac", "Partisan gridlock: Congress won't raise taxes or act.", { l: "Inherency", c: "Hooper 22" }],
["pl", "aff-1ac", "Pass the Social Security 2100 Act (2023 version).", { l: "Plan" }],
["s1", "aff-1ac", "Funds SS to ~2097: payroll tax above $400K + 12.4% on net investment income.", { l: "Solvency", c: "Goss, SSA 23" }],
["s2", "aff-1ac", "Only the top 1.8% of earners pay more.", { c: "Fabino 23" }],
["s3", "aff-1ac", "SS benefits stimulate local economies: $1.6T nationally.", { l: "Advantage", c: "Arno 17" }],
["n0", "neg-1nc", "Overview: the problem is demographics, and trillion-dollar tax hikes are the wrong fix.", { l: "Overview" }],
["n1", "neg-1nc", "Beneficiaries +50% vs. payers +15%: plan is 25 years short even without the cap.", { c: "Kessler 17", r: "s1" }],
["n2", "neg-1nc", "Their own Miller card blames lower birth rates.", { r: "h1" }],
["n3", "neg-1nc", "Projections fail (Clinton's 1990s fix).", { r: "s1" }],
["n4", "neg-1nc", "Tax avoidance: $4T offshore. Past the revenue-maximizing rate (~60%), hikes raise little.", { c: "Gleckman; Riedl 24", r: "s1" }],
["t1", "aff-2ac", "Demographics are why we need revenue. Top-earner wage growth was the unexpected change.", { c: "Goss testimony", r: "n1" }],
["t2", "aff-2ac", "New projections account for inequality; they're reliable.", { c: "Munnell 19", r: "n3" }],
["t3", "aff-2ac", "Removing the cap is what stops the avoidance.", { r: "n4" }],
["u1", "neg-2nc", "Costs went from $256B (1985) to $1.4T. A one-time tax can't keep up.", { r: "t1" }],
["u2", "neg-2nc", "Goss admits an 'extraordinarily high degree of uncertainty'.", { r: "t2" }],
["v1", "aff-1ar", "Goss models aging. No 75-year projection is perfect; we can't keep kicking the can.", { r: "u2" }],
["w1", "neg-2nr", "Their own author is uncertain, so you should be. Static tax ≠ long-term solvency.", { r: "v1" }],
["x1", "aff-2ar", "Even with uncertainty, the plan is the best way to keep 83M retirees' benefits paid.", { r: "w1" }],
] },
{ title: "Off: Economy DA", cards: [
["d1", "neg-1nc", "Link: employers must match the payroll hike. GDP −0.6%, 580K jobs lost.", { l: "Link", c: "Watson, Tax Foundation 24" }],
["d2", "neg-1nc", "Link: investment tax pulls capital; a 10% hike cuts capital 7%.", { c: "Riedl 23" }],
["d3", "neg-1nc", "Impact: economy barely avoided recession; trillion-dollar hikes slow growth.", { l: "Impact" }],
["e1", "aff-2ac", "Watson is about a different bill (Fair Share Act).", { r: "d1" }],
["e2", "aff-2ac", "Tax Foundation overstates tax burdens.", { c: "Marr, CBPP 18", r: "d1" }],
["e3", "aff-2ac", "Turn: SS benefits stimulate the economy.", { c: "Arno 17", r: "d3" }],
["e4", "aff-2ac", "Investment income tax only hits ~1% of households.", { c: "Gleckman", r: "d2" }],
["f1", "neg-1nr", "Ripple effects: $22T conceded in cross-ex; 580K leave the labor force.", { r: "e1" }],
["g1", "aff-1ar", "Employer match only applies above $400K. Taxes pull money out, lowering inflation.", { r: "f1" }],
["k1", "neg-2nr", "Businesses pass costs to consumers. Extend Riedl: revenue-max point.", { r: "g1" }],
["m1", "aff-2ar", "Evidence quality: CBPP shows Tax Foundation bias; only 1.8% are affected. Vote aff.", { r: "k1" }],
] },
],
},
parli: {
title: "Example: CHSSA State Parliamentary Quarterfinal",
blurb: "Parli · Punishment by its very nature should be somewhat cruel and unusual",
meta: { format: "parli", mySide: "", topic: "Resolved: Punishment by its very nature should be somewhat cruel and unusual.",
proTeam: "Government", conTeam: "Opposition", round: "CHSSA State quarterfinal (2014 demo video)" },
sheets: [
{ title: "Theory / value", cards: [
["v1", "gov-pmc", "Value: Justice. Whoever best upholds the criminal justice system wins.", { l: "Value" }],
["v2", "gov-pmc", "Cruel and unusual = Brennan in Furman v. Georgia: degrading to dignity, arbitrary, rejected by society, or unnecessary. Failing any one counts.", { l: "Definitions", c: "Furman v. Georgia" }],
["v3", "gov-pmc", "Obs 1: Gov only proves one of the four. Obs 2: Gov needn't say cruel punishment is good, only that punishment is that way.", { l: "Observations" }],
["v4", "opp-loc", "Interp: value should be societal welfare worldwide. Violation: Justice is too narrow. Standards: breadth, ground (victims and families are affected too). Voter: education.", { l: "Topicality", r: "v1" }],
["v5", "gov-mg", "Counter-interp: Justice. Depth beats breadth (breadth is just watching the news). Ground isn't skewed; creativity links to education. Reasonability: if ours is reasonable, drop the shell.", { r: "v4" }],
["v6", "gov-mg", "Opp conceded our framework and observations; use them to evaluate.", { r: "v3" }],
["v7", "opp-mo", "Justice matters because it leads to net benefits; net benefits is the end goal both sides want.", { r: "v5" }],
["v8", "opp-lor", "Gov dropped victims and families in the MG; T is a voting issue.", { r: "v5" }],
["v9", "gov-pmr", "Opp's advocacy shifted from societal welfare to net benefits: moving target, reverse the voter. Justice is reasonable; evaluate T for us.", { r: "v7" }],
] },
{ title: "Gov case", cards: [
["g1", "gov-pmc", "All punishment degrades dignity: it forces the state's will on you and violates autonomy (fines, jail, death).", { l: "C1: Human dignity" }],
["g2", "gov-pmc", "Same crime, different sentences; death sentences biased against Black defendants. Minorities sentenced more harshly.", { l: "C2: Arbitrariness", c: "Stewart, White, Douglas in Furman" }],
["g3", "gov-pmc", "If all punishment is cruel and unusual, society rejects it and the system turns to rehabilitation. Respectful treatment returns people to society.", { l: "C3: Rehabilitation", c: "Princeton, Harvard studies" }],
["g4", "gov-pmc", "Possession of marijuana can bring life under minimums; punishment isn't proportional. Dehumanization justifies violence.", { l: "Impact: dehumanization" }],
["g5", "opp-loc", "Punishment is just a penalty for a crime. A speeding fine isn't degrading.", { r: "g1" }],
["g6", "opp-loc", "Gov is advocating racism: they want punishment to be cruel and unusual.", { r: "g2" }],
["g7", "opp-loc", "Rehab breaks none of the four tests, so it isn't cruel and unusual; it's Opp ground.", { r: "g3" }],
["g8", "opp-loc", "Life sentences for marijuana are for large quantities = dealing.", { r: "g4" }],
["g9", "gov-mg", "A fine still forces you to give up wealth; yes, taxes and public school are degrading too.", { r: "g5" }],
["g10", "gov-mg", "Calling everything cruel and unusual makes all punishment unconstitutional, collapsing the retribution system. Organic backlash leads to rehab.", { r: "g6" }],
["g11", "gov-mg", "Only Gov gets rehab; the status quo prefers retribution (death penalty, Guantanamo).", { r: "g7" }],
["g12", "gov-mg", "Why should dealers lose dignity? Disagreeing with conduct doesn't justify stripping rights.", { r: "g8" }],
["g13", "opp-mo", "If every punishment (and taxes, school) is degrading, Gov means no punishment at all: anarchy, worse dehumanization.", { r: "g9" }],
["g14", "opp-mo", "Cruel punishment makes sentencing gaps bigger, so racism gets worse.", { r: "g10" }],
["g15", "opp-mo", "A reasonable person wouldn't call rehab cruel and unusual.", { r: "g11" }],
["g16", "opp-lor", "Rehab passes all four of Gov's own tests, so Gov can't claim it.", { r: "g11" }],
["g17", "gov-pmr", "Education and taxes aren't punishments, so no anarchy. We don't change constitutionality; we define all punishment as cruel and unusual. Rehab replaces every fine and sentence, so Gov gets more rehab.", { r: "g13" }],
] },
{ title: "Opp case", cards: [
["o1", "opp-loc", "Punishment that fits the crime reforms people. Rehab cuts reoffending (71% effective).", { l: "C1: Rehabilitation", c: "Lanet University" }],
["o2", "opp-loc", "Death penalty doesn't deter: Texas +23% homicides five years after reinstating (1989), North Dakota +35% after 1976.", { l: "C2: Deterrence fails", c: "CIA World Factbook" }],
["o3", "opp-loc", "Waterboarding, torture, numbers instead of names; terrorism increased as a direct result.", { l: "C3: Guantanamo Bay" }],
["o4", "gov-mg", "Opp's own impacts are about dehumanization, which Gov solves best by collapsing retribution.", { r: "o3" }],
["o5", "opp-mo", "Gov dropped all three contentions. Caron Butler turned his life around after rehab at 16.", { r: "o1" }],
["o6", "opp-mo", "Chicago: harsher punishment raised gang-police violence 133%. People don't know the penalty, so it can't deter.", { r: "o2" }],
["o7", "opp-mo", "Guantanamo is the Taliban's top propaganda; CIA's John Brennan says it undermines national security.", { r: "o3", c: "Matthew Alexander; John Brennan" }],
["o8", "opp-lor", "Voters: rehab (second chance, more humane), deterrence (death penalty raises deaths, unrefuted), racism, Guantanamo (outside US law, terrorism rises).", { l: "Voters" }],
["o9", "gov-pmr", "All impacts run through rehab, and Gov gets the most rehab. Opp accepts a status quo they concede is racist.", { l: "Voters", r: "o8" }],
] },
],
},
worldschools: {
title: "Example: 2023 NSDA Nationals World Schools Final",
blurb: "World Schools · This house supports a people's democratic right to secede · Prop won 12-1",
meta: { format: "worldschools", mySide: "", topic: "This house supports a people's democratic right to secede.",
proTeam: "West Los Angeles Violet (Prop)", conTeam: "Hoosier Crossroads Gold (Opp)", round: "Final" },
sheets: [
{ title: "Framing", cards: [
["f1", "prop-1", "A democratic right is inherent to people in a democracy, like dissent, protest and voting.", { l: "Def: democratic right" }],
["f2", "prop-1", "Prop only proves a legitimate right exists, not that every secession should happen or a plan for each case.", { l: "Burden" }],
["f3", "prop-1", "Opp must show why a people's democratic choice to secede was illegitimate.", { l: "Opp prerequisite" }],
["f4", "opp-1", "If Prop can't show what happens in their world, Opp wins on practical impacts.", { r: "f2" }],
["f5", "opp-1", "A right that hurts democracy long-term isn't a democratic right.", { l: "Framework 1" }],
["f6", "opp-1", "Alternative is negotiation between the people and the government; unilateral secession only needs one side.", { l: "Framework 2: counterplan" }],
["f7", "prop-2", "Negotiation is fantasy: what incentive does an oppressive government have to come to the table with people it strips of rights?", { r: "f6" }],
["f8", "prop-2", "We don't judge an election by whether we like its result. Principle comes first.", { l: "Weighing", r: "f4" }],
["f9", "opp-2", "Judge morality by impact on communities: weigh practical equally with principle.", { r: "f8" }],
["f10", "opp-2", "Negotiation doesn't always work, but it beats the war Prop's world supports.", { r: "f7" }],
["f11", "prop-3", "Secession is a last resort after every peaceful avenue fails; it also gives a people real power at the negotiating table.", { r: "f10" }],
["f12", "opp-3", "\"Last resort\" is new in the 3 and unwarranted; oppressed people won't negotiate with a government that never listens.", { r: "f11" }],
["f13", "opp-3", "Our framework (a right that stops future access to democracy isn't a democratic right) went uncontested.", { r: "f5" }],
] },
{ title: "Principle", cards: [
["p1", "prop-1", "Consent: people consent to a government but can revoke it, like quitting a job. South Sudan left Sudan's abuses.", { l: "S1: Self-determination" }],
["p2", "prop-1", "Autonomy: you can defend yourself when your rights are infringed. Voting to secede is like voting for any action.", {}],
["p3", "prop-1", "Retribution: people secede over oppression, state failure, or cultural disconnect.", {}],
["p4", "opp-1", "Secession treats rights like math: if 52% secede, it violates the 48%. Leaving a democracy rejects democratic values.", { l: "S1: Social contract", r: "p1" }],
["p5", "prop-2", "The government broke the contract first; you can back out of a breached contract. Most minorities never opted in anyway.", { r: "p4" }],
["p6", "prop-2", "Secession weakens imperial states: it takes their resources and strategic territory, so they can't keep oppressing.", { l: "S3: Weakens imperial states" }],
["p7", "opp-2", "Consent goes both ways: you can revoke your own consent but not on behalf of neighbors who don't want to leave.", { r: "p1" }],
["p8", "opp-2", "Opp doesn't support imperial states either; Prop ignores the people left inside them.", { r: "p6" }],
["p9", "prop-3", "Principle comes before practical, so even on Opp's best practical ground Prop wins. The social contract itself lets people replace a government that violates their rights.", { r: "p7" }],
["p10", "prop-3", "Self-defense against infringement and retribution were never answered.", { r: "p2" }],
["p11", "opp-3", "Individuals can't violate others' liberties to exercise their own consent; that ends any shared community.", { r: "p9" }],
["p12", "opp-reply", "Lifeboat on a plane over a desert: secession can stay a right without the world promoting it.", { l: "Reply" }],
["p13", "prop-reply", "Self-determination doesn't depend on consent or contracts. Oppressed groups are the stakeholders that matter. Consent can be revoked when the terms change.", { l: "Reply", r: "p11" }],
] },
{ title: "Practical", cards: [
["x1", "prop-1", "Secession peacefully resolves conflict and lets marginalized groups leave instead of fighting.", { l: "S2: Better for all" }],
["x2", "prop-1", "Even failed secession wins devolution of power. Overton window: Scottish independence went from fringe to ~50% support.", {}],
["x3", "opp-1", "Secession often brings violence and war; people mostly leave over ethnic differences, not rights.", { r: "x1" }],
["x4", "opp-1", "Happens in unstable places (Cyprus, Western Sahara). Catalonia leaving hurts Spain. Somaliland got no recognition, lost trade.", { l: "S2: Secession isn't always just" }],
["x5", "prop-2", "Protect the most vulnerable first. Transition is negotiated over time; former unions cooperate; new states form alliances. \"Supports\" means recognition and funding.", { r: "x4" }],
["x6", "prop-2", "Opp never mechanizes how war actually follows.", { r: "x3" }],
["x7", "opp-2", "South Sudan after 2011: violent protests, food shortages, poverty. Even the threat of secession invites a stronger state's violence.", { l: "S3: Quality of life and safety", r: "x5" }],
["x8", "prop-3", "Norway (1905), Montenegro (2006), Timor-Leste (2002), Czechoslovakia (1993): peaceful and stable.", { l: "Examples", r: "x7" }],
["x9", "prop-3", "Devolution even when secession fails was never answered.", { r: "x2" }],
["x10", "opp-3", "Contradiction: Prop's governments are too evil to negotiate yet will give seceding states what they need.", { r: "x5" }],
["x11", "opp-3", "Authoritarian states punish those left behind, and devolution just splits authoritarianism into factions.", { r: "x9" }],
["x12", "opp-reply", "Prop's world is war: economic, social and fatal harms for people who never wanted the conflict.", { l: "Reply" }],
["x13", "prop-reply", "Opp only explained war in the 3. The motion is about supporting a right, so the principle decides it.", { l: "Reply", r: "x12" }],
] },
],
},
extempdebate: {
title: "Example: 2025 NSDA Nationals Extemp Debate Final",
blurb: "Extemp Debate · When in conflict, prioritize free markets over government intervention",
meta: { format: "extempdebate", mySide: "", topic: "When in conflict, the United States should prioritize free markets over government intervention.",
proTeam: "Luke Ryan, Pembroke Hill (Aff)", conTeam: "Ethan Kuruvilla, Bellevue (Neg)", round: "Final (round 14)" },
sheets: [
{ title: "Flow", cards: [
["a1", "prop-con", "Tariff whiplash (on again, off again) makes businesses afraid to invest or expand, so growth stalls.", { l: "C1: Prosperity, A: Tariffs", c: "Shambaugh-Wright" }],
["a2", "prop-con", "Regulations pile up, duplicative and contradictory. Held at 1980 levels, the US economy would be 25% larger.", { l: "B: Regulations", c: "George Mason U 2016" }],
["a3", "prop-con", "Intervention breeds bribes and favoritism; open economies have less corruption.", { l: "C2: Corruption", c: "IMF" }],
["a4", "prop-con", "Intervention pushes businesses into politics; cronies gain the edge.", { c: "Holcombe 13" }],
["n0", "opp-con", "\"In conflict\" means the US at war, using its military against another power.", { l: "Definition" }],
["n1", "opp-con", "WWII: War Production Board ordered production. Ford built a B-24 an hour, GM built tanks, DuPont made parachutes. 300K planes, 86K tanks, 2.4M trucks by 1945.", { l: "C1: Government won WWII", c: "US Army Center of Military History" }],
["n2", "opp-con", "Over 90% of wartime manufacturing was federally coordinated; ~$3T in materials reallocated by quotas and price controls.", { c: "Hugh Rockoff" }],
["n3", "opp-con", "War shatters confidence: supply shocks, hoarding. OPA price controls and rationing kept fairness; the Fed says the economy would have collapsed without them. WWI Food Administration too.", { l: "C2: Only government restores trust", c: "Federal Reserve" }],
["a5", "prop-reb", "Prefer the Merriam-Webster definition: \"in conflict\" = two ideas that can't agree, in peace or war. Neg's definition has no source.", { l: "Definition", r: "n0" }],
["a6", "prop-reb", "Corruption turns wartime intervention: earmarks to favored firms hurt the war effort.", { r: "n1" }],
["a7", "prop-reb", "Intervention undermines confidence, as tariffs show, even in wartime.", { r: "n3" }],
["n4", "opp-reb", "\"When in conflict\" is how policy, law and history describe war and national emergencies.", { r: "a5" }],
["n5", "opp-reb", "In war prosperity comes from survival; planning accelerated output. Not defending peacetime tariffs.", { r: "a1" }],
["n6", "opp-reb", "WPB prevented corruption and price gouging, and let small businesses contribute. War isn't an open economy.", { r: "a6" }],
["n7", "opp-reb", "OPA boosted morale and curbed inflation; left alone, companies kept making radios and Cadillacs.", { r: "a7" }],
["n8", "opp-reb", "Aff's harms are speculative (a 25% bigger economy); Neg's are existential (losing the war).", { l: "Weighing" }],
["a8", "prop-final", "Past NSDA resolution \"when in conflict, academic freedom vs community standards\" clearly isn't about war. If Aff's definition wins, it's an auto-Aff vote, since only Aff argues peace and war.", { l: "Framing", r: "n4" }],
["a9", "prop-final", "Tariffs happen in war and peace; IMF and Holcombe show intervention causes corruption; WWII is Neg's only example.", { r: "n6" }],
["n9", "opp-final", "The round is about what works when stakes are highest, so look at real US conflicts.", { r: "a8" }],
["n10", "opp-final", "With no oversight in war, firms gouge and hoard (dropped). Aff dropped the production numbers.", { r: "a9" }],
["n11", "opp-final", "Aff wins hypothetical GDP; Neg wins WWII. Only one side shows what keeps a nation standing.", { l: "Weighing" }],
] },
],
},
bp: {
title: "Example: WADL 2017 British Parliamentary Demo",
blurb: "British Parliamentary · This House would privatise prisons · four teams",
meta: { format: "bp", mySide: "", topic: "This House would privatise prisons.",
proTeam: "Government (OG / CG)", conTeam: "Opposition (OO / CO)", round: "West Australian Debating League demo round" },
sheets: [
{ title: "Motion", cards: [
["pm0", "og-pm", "Status quo prisons are overcrowded, under-serviced and don't rehabilitate, so people cycle back in.", { l: "Context" }],
["pm1", "og-pm", "Private firms take over some public prisons and can build new, specialised ones, all under short government contracts that set service standards and welfare checks. Rivals can bid to do it better or cheaper.", { l: "Model" }],
["pm2", "og-pm", "Contracts force services (education, catering, job skills); competition plus business management cuts cost. Freed public money goes to prevention and courts.", { l: "1: Private prisons are more efficient" }],
["pm3", "og-pm", "Firms compete to offer the best services, so prisoners get programs they wouldn't get now. Specialised prisons (women, youth) and more sites nearer family help rehab.", { l: "2: Better services for prisoners" }],
["lo0", "oo-lo", "Profit motive means corners get cut on what you can't see from outside: rehab quality, programs. Contracts go to whoever is cheapest, not best.", { l: "Framing", r: "pm2" }],
["lo1", "oo-lo", "Prisons are an extension of the justice system. Government owes protection to inmates and safety to the community; privatising loses accountability.", { l: "1: Government's responsibility" }],
["lo2", "oo-lo", "Competition is on dollars per prisoner. Food and beds can be regulated, but rehab, programs and security can't. Overcrowding cuts security. Paid per prisoner = incentive for reoffending.", { l: "2: Profit incentive cuts facilities", r: "pm3" }],
["lo3", "oo-lo", "POI answer: ambulances differ because voters care; nobody protects prisoners' interests.", { r: "pm2" }],
["dp1", "og-dpm", "Responsibility point is moot: government must provide care either way, the question is who does it better.", { r: "lo1" }],
["dp2", "og-dpm", "Profit incentive works: firms bid to deliver better services at the same or lower price, and must meet contract terms. Privatised ambulances got faster and saved lives.", { r: "lo2" }],
["dp3", "og-dpm", "Government prisons have little accountability now; bureaucracy covers up abuse even after public outrage.", { l: "Accountability", r: "lo1" }],
["dp4", "og-dpm", "Private operators have links to outside employers; US private-prison releasees find jobs faster.", { l: "Ext: Workforce reintegration" }],
["dl1", "oo-dlo", "Key question: who gives better services? Contracts only get the bare minimum; intangible rehab can't be written into a contract.", { r: "dp2" }],
["dl2", "oo-dlo", "Ambulances aren't analogous: one goal (speed). Prisons have complex purposes and costs.", { r: "dp2" }],
["dl3", "oo-dlo", "Competition harms stability: switching operators mid-program wrecks rehab.", { r: "pm1" }],
["dl4", "oo-dlo", "Prisons near friends can mean prisons near your gang; worse for rehab.", { r: "pm3" }],
["dl5", "oo-dlo", "Firms hide failures to protect their reputation and can afford PR spin. Less accountability than government.", { l: "Ext: Accountability falls", r: "dp3" }],
["mg1", "cg-mg", "Contracts set criteria and competition rewards meeting them. Inmates trust non-government operators more, so they report abuse and engage with rehab.", { r: "dl1" }],
["mg2", "cg-mg", "Too much stability = stagnation. Prisoners were let down by government, so a new operator breaks the cycle.", { r: "dl3" }],
["mg3", "cg-mg", "You can sue a private operator for abuse; much harder against government.", { r: "dl5" }],
["mg4", "cg-mg", "Developing countries: governments lack capital, prisons are costly and poor. Private firms bring capital and growth; government money goes to hospitals, schools, infrastructure.", { l: "Ext: Developing countries" }],
["mo1", "co-mo", "Conflict of interest: a firm profiting from prisoners has power over whether they come back.", { r: "dp2" }],
["mo2", "co-mo", "We banned vigilante justice; private citizens shouldn't run punishment.", { r: "dp1" }],
["mo3", "co-mo", "Profiting from suffering and free prison labour echoes the slave trade. Firms tidy up only for scheduled checks.", { r: "dp4" }],
["mo4", "co-mo", "Developing countries have weaker oversight, so private prisons are worse there.", { r: "mg4" }],
["mo5", "co-mo", "Sentences should mean the same everywhere. Operators differ, so prisons in poorer areas (drug crime, high volume) and women's prisons (extra costs) get worse.", { l: "Ext: Variance between prisons" }],
["gw1", "cg-gw", "Competition: government picks the contract with the best outcomes per dollar (e.g. lower reoffending), so firms compete on quality.", { r: "lo2" }],
["gw2", "cg-gw", "Accountability: government only acts once abuse is extreme; with firms you can complain to a person or sue.", { r: "dl5" }],
["gw3", "cg-gw", "Firms go where crime is and government wants good prisons there; no rich/poor split.", { r: "mo5" }],
["gw4", "cg-gw", "Rehab: contracts reward low reoffending; prisoners distrust government and engage more with private programs. Savings fund prevention.", { r: "mo1" }],
["ow1", "co-ow", "Government already has a strong incentive to cut crime and reoffending; a firm paid per prisoner profits from the 77% who reoffend.", { r: "gw4" }],
["ow2", "co-ow", "Principle: conflict of interest, civilians dictating punishment, profiting off incarceration. Gov never answered the last two.", { r: "mo2" }],
["ow3", "co-ow", "Government still pays firms per prisoner, so no big savings for prevention. Rich operators become a powerful lobby.", { r: "pm2" }],
["ow4", "co-ow", "Prisoners can't realistically sue big corporations; poor oversight in developing countries makes it worse.", { r: "gw2" }],
["ow5", "co-ow", "Prisoners don't choose a prison, so there's no market for quality. Overcrowding and less food breed distrust, not rehab.", { l: "Weighing", r: "gw1" }],
] },
],
},
congress: {
title: "Example: 2022 NSDA Nationals House Final",
v: 2,
blurb: "Congress · House Final: high-speed rail, sugar tax and voting rights bills",
meta: { format: "congress", mySide: "", topic: "Docket: HF1 high-speed rail, HF3 sugar tax, HF4 right to vote",
proTeam: "", conTeam: "", round: "Representative Barbara Jordan Final, House" },
sheets: [
{ title: "Bill 1: High-speed rail", cards: [
["s1", "session", "Northeast Corridor already runs 125-150 mph in places, so it's doable. HSR creates jobs, boosts the economy, cuts oil use. China and Germany are ahead. Eminent domain exists for exactly this. Builds on the $7B NEC upgrade. CX: Section 4 eminent domain could push low-income people out.", { l: "Sponsor (Aff 1)", s: "pro", c: "APTA; Sec. Buttigieg" }],
["s2", "session", "Financial returns don't support HSR; LA-SF went from $25B projected (1999) to $100B. Little competition. Spain's review: none should have been built. Paid by deficit spending. Japan took 20 years for ~1,000 miles; too slow for the IPCC deadline. Amtrak itself says fix ~300-mile corridors first.", { l: "Neg 1", s: "con", c: "Mercatus 17; Cato 20; Vice 21" }],
["s3", "session", "More options: Amtrak's NY-DC share rose 37% to 75% (2000-12). Driving is 17x deadlier than HSR. Maryland-NY rail added 25,000 jobs; 52% of low-income households have someone out of work.", { l: "Aff 2", s: "pro", c: "Bloomberg 14; BWRR 19; Pew 21" }],
["s4", "session", "Metroliner failed. Trains run on a grid that's 60.8% fossil fuels, so no climate win. Essential Air Service ($290M) beats $450M for 23 miles of NJ track; planes are faster.", { l: "Neg 2", s: "con", c: "Exponents 20" }],
["s5", "session", "Funding exists: rail projects up $66B, $22B to Amtrak already. Section 4 adds oversight, so we choose where lines go (rail raises nearby property taxes 50%+). Lack of transport drives youth unemployment. HSR cuts oil use 2% by 2030.", { l: "Aff 3", s: "pro", c: "FRA; J. of Urban Studies 17; USHSR" }],
["s6", "session", "Electric HSR relies on lithium-ion batteries; two-thirds of cobalt comes from the DRC, with child and forced labor. A national HSR line costs $3T+ with no price tag in the bill; more debt fuels inflation.", { l: "Neg 3", s: "con", c: "Reuters 21; Cato 21; CFR 21" }],
["s7", "session", "Same arguments were made against the interstate highways in 1956. HSR displaces flights: 6M tons of CO2 saved over 40 years (WA study); 6,000 riders a train vs 150 a plane. Returns come through the whole economy.", { l: "Aff 4", s: "pro", c: "WSDOT 19" }],
["s8", "session", "Section 3B demands 200+ mph average, which France, Japan and China found not worth the cost. Eminent domain displaces low-income Black and brown communities (\"rail of tears\"). DC maglev is stalled on environmental review. Rural routes bring their own environmental damage.", { l: "Neg 4", s: "con", c: "CNN 22; Guardian 17; FRA 21" }],
["s9", "session", "Neg contradicts itself (nobody rides vs too many riders). 62% would switch from car and air; HSR cut other travel 54% across 11 lines. 8x more efficient than air, 4x cars; air pollution -22%. Commute length is the top factor in poverty.", { l: "Aff 5", s: "pro", c: "APTA; IEA 19; Chetty 15" }],
["s10", "session", "Even if built, it won't help the poor: 66% of ~200K households near rail earn $75K+. Property within 400m of rail rose 4.5%, so rich newcomers push low-income residents out (gentrification).", { l: "Neg 5", s: "con", c: "NCRC 18; WaPo 19" }],
["s11", "session", "Bill upgrades the Northeast Corridor, not all of America. One day of NEC shutdown costs $100M in congestion and lost productivity; NY airports cause half of flight delays; half the 40 most congested highways are here.", { l: "Aff 6", s: "pro", c: "NEC Commission 19; Lebron 17" }],
] },
{ title: "Bill 2: Sugar tax", cards: [
["t1", "session", "Diabetes under 20 to quadruple by 2050; 1 in 6 kids obese (was 1 in 10). 17-21% of calories from added sugar = 38% higher cardiac death risk. Berkeley's tax cut consumption 52% in low-income areas. Penny-per-ounce tax (Sec. 2A) prevents 2.4M diabetes deaths, saves $17B; revenue funds health programs (Sec. 2F).", { l: "Sponsor (Aff 1)", s: "pro", c: "Pew 16; Harvard Med 22; Berkeley Food Inst. 19" }],
["t2", "session", "Regressive: low-income households pay nearly 2x as much, and food deserts mean no alternative. Doesn't work nationally: Mexico cut only 7 calories a day. New programs take 34 months to start. Better: mandate companies cut sugar.", { l: "Neg 1", s: "con", c: "Tax Foundation 20; NZ Ministry of Health 17; CBPP" }],
["t3", "session", "Diabetes is 2x more common in low-income homes; heart-disease hospital visits cost them more than the tax. Public heart-health programs cut cardiovascular risk 28%; 600K+ die of heart disease yearly. Better to wait 34 months than never.", { l: "Aff 2", s: "pro", c: "NLM; Harvard SPH 20; CDC 22" }],
["t4", "session", "Aff must prove the tax lowers consumption and that it matters. It only hits drinks: people switch to sweet food (Philadelphia); Mexico -7 calories; New Zealand no link. Small businesses lost $80M+ and 1,000+ jobs in tax cities.", { l: "Neg 2", s: "con", c: "PBS 18; American Beverage Assn." }],
["t5", "session", "Americans drink 45 gallons of soda a year; a US small is a UK large. A penny an ounce raises about $19.1B for childhood obesity programs. US obesity 41.9% vs UK 28%.", { l: "Aff 3", s: "pro", c: "Madison Med 17" }],
["t6", "session", "Blames the poor instead of the system. Black and Hispanic women are more likely to face obesity and food insecurity; sugary food drives hunger and weight gain.", { l: "Neg 3", s: "con", c: "Brookings 20" }],
] },
{ title: "Bill 3: Right to vote", cards: [
["v1", "session", "Early voting cuts Election Day strain, shortens lines, catches registration errors. 12% of eligible voters (31M) didn't know they had to pre-register. 5.2M couldn't vote in 2020 over felony convictions; minorities are wrongly convicted 4x as often.", { l: "Sponsor (Aff 1)", s: "pro", c: "Brennan Center; Pew; Michigan Law" }],
["v2", "session", "If you won't follow the law you shouldn't make it: felons shouldn't vote. Same-day registration makes fraud easier and polls chaotic. 16,990 polling centers already exist; the problem is voter education.", { l: "Neg 1", s: "con", c: "Heritage 18, 19; National Review 18" }],
["v3", "session", "Felon disenfranchisement is rooted in race: 1 in 3 Black men has a felony record; 1 in 13 Black Americans can't vote. Sec. 2's 20-day early voting minimum removes cost barriers; Black voters use early voting 2-3x more. CX: Constitution lets states set eligibility.", { l: "Aff 2", s: "pro", c: "Marshall Project 18; Sentencing Project 17; Vera 18; ACLU" }],
["v4", "session", "Expands early voting without funding security: 85+ voters in 28 states saw firearms at polls. Last big federal election funding was $3.5B in 2002 (HAVA). 20 more days of exposure to intimidation; also understaffs polls.", { l: "Neg 2", s: "con", c: "Coalition to End Gun Violence 20; MIT Election Lab" }],
] },
],
},
bigq: {
title: "Example: 2025 NSDA Nationals Big Questions Final",
blurb: "Big Questions · Creativity vs. intelligence · with question segment notes",
meta: { format: "bigq", mySide: "", topic: "Creativity is a more powerful force than intelligence.",
proTeam: "Affirmative", conTeam: "Negative", round: "Final" },
sheets: [
{ title: "Aff case", q: {
"neg-con": "Aff asks: does society need intelligence to develop, or just to exist? Neg: both.\nNeg asks: is power about impact? Aff: yes, impact on humans and society.\nAff: an idea in one person's head still changes society (force = cause of change).\nNeg concedes they never defined force.\nAff: calculus is powerful because of the new idea, not prior math.",
"neg-reb": "Aff: what good is understanding a problem with no new solution? Neg: problem solving still builds knowledge; application needs real-world understanding.\nBaby touching a sharp object: Aff says the mistake is random, so creative. Neg says learning from it is understanding = intelligence.\nNeg: three sources of knowledge: observation, reasoning, creative ideation (which needs intelligence)."
}, cards: [
["a0", "aff-con", "Creativity = bringing something new into existence. Force = cause of motion or change. Weigh impact on humans and society; 'than' means compare, not prove intelligence useless.", { l: "Framework", c: "Britannica; Merriam-Webster" }],
["a1", "aff-con", "Innovation raises productivity: same input, more output. Wages rise, businesses hire.", { l: "C1: Creative economy", c: "European Central Bank 17" }],
["a2", "aff-con", "Impact: no new ideas = economic crisis. Inequality causes 1 in 3 deaths.", { c: "Frank 18; Brusha 14" }],
["a3", "aff-con", "Impact: climate. Growth makes cleaner tech cheaper; ~300,000 die from climate change every year.", { c: "Bailey 25; Schneider-Mayer 15" }],
["a4", "aff-con", "Creativity creates knowledge; highest form of intelligence. Newton imagined calculus.", { l: "C2: Progress", c: "Dano 08" }],
["a5", "aff-con", "Creative people engage with error. No mistakes, no learning, stagnant society.", { l: "Sub B: Learning", c: "Rothenberg 19" }],
["n1", "neg-reb", "Look at both prerequisite and impact: implementation and the initial cause.", { r: "a0" }],
["n2", "neg-reb", "Innovation is only implemented well through intelligence. Empirics: high-IQ states are more innovative.", { c: "Wilson 14", r: "a1" }],
["n3", "neg-reb", "Economy rests on intelligence: necessary, creativity only helps. Informed decisions drive growth; IQ drives job performance.", { c: "Awalda 22; Santilly 24", r: "a2" }],
["n4", "neg-reb", "Knowledge also comes from observing and reasoning. Calculus came from understanding the world.", { r: "a4" }],
["n5", "neg-reb", "Mistakes are failed applications of intelligence; learning is intelligence under both definitions.", { r: "a5" }],
["c1", "aff-consol", "Neg never defined force. Force = cause of change, so vote on the cause: creativity.", { r: "n1" }],
["c2", "aff-consol", "Understanding isn't a solution. Linear thinking repeats old answers; lateral thinking (creativity) makes new ones.", { r: "n2" }],
["c3", "aff-consol", "Not about individual jobs: creativity drives the economy, and when it crashes jobs go.", { r: "n3" }],
["c4", "aff-consol", "Baby has no knowledge to apply. The mistake is random and creative, and learning needs it.", { r: "n5" }],
["d1", "neg-consol", "Make them choose: initial cause matters, or it doesn't. Both cause and impact go Neg.", { r: "c1" }],
["d2", "neg-consol", "Wilson 14 dropped: the only empirical link to innovation. No impact without implementation.", { t: "Drop/Concede", r: "c2" }],
["d3", "neg-consol", "If mistakes are random, learning from them is intelligence. Both definitions of intelligence include learning.", { r: "c4" }],
["r1", "aff-rationale", "Only extended definition: force = cause of change. A creative idea causes it, even in one person.", { r: "d1" }],
["r2", "aff-rationale", "Mistakes are creative (Rothenberg 19). No mistakes, no learning, no progress.", { r: "d3" }],
["r3", "aff-rationale", "Climate: spotting a problem isn't fixing it. Only new solutions mitigate.", { r: "a3" }],
["m1", "neg-rationale", "Fixing climate change is implementation = intelligence. Wilson 14 and Awalda 22 still dropped; their economy impact flows Neg.", { r: "r3" }],
["m2", "neg-rationale", "Randomness isn't creativity; creativity is a cognitive function.", { r: "r2" }],
] },
{ title: "Neg case", cards: [
["k0", "neg-con", "Intelligence = learning, understanding, reasoned judgment, incl. creating knowledge by deduction and induction. Weigh scope of influence: if creative impacts rely on intelligence, Neg wins.", { l: "Framework", c: "Cambridge" }],
["k1", "neg-con", "Intelligence integrates perception, attention, memory, language, planning: the base for any creative idea.", { l: "C1: Intelligence needed for creativity", c: "NCBI 10" }],
["k2", "neg-con", "Idea generation = focused attention + controlled retrieval. 8 studies: intelligence is a necessary condition for creativity.", { c: "Gerwig 21; Karwowski 16" }],
["k3", "neg-con", "Intelligence predicts survival: +15 IQ points = 21% better odds of reaching 76.", { l: "C2A: People", c: "Hamburg 15" }],
["k4", "neg-con", "Social intelligence (reading emotions, relationships, language) lets people connect and communicate.", { c: "Henderson 08; Barbosa 23" }],
["k5", "neg-con", "National intelligence sustains a country's economic, political, military power. Problem solving is the source of new functions.", { l: "C2B: Society", c: "Awalda 22" }],
["b1", "aff-reb", "Both sides weigh impact on humans and society. Prerequisites aren't the question.", { r: "k0" }],
["b2", "aff-reb", "Intelligence alone reapplies old knowledge: no new solutions. Lateral thinking is creativity; cross-apply C1.", { r: "k1" }],
["b3", "aff-reb", "Survival is instinct; babies have the lowest IQ. Surviving isn't progressing.", { r: "k3" }],
["b4", "aff-reb", "Turn: knowing a friend is sad doesn't help; a creative way to cheer them up does.", { t: "Turn", r: "k4" }],
["b5", "aff-reb", "Language is itself a creative idea. Intelligence applies solutions; creativity creates them.", { r: "k5" }],
["e1", "neg-reb", "Scope of influence never answered. Their own framing says the initial cause matters most, and intelligence causes creativity.", { r: "b1" }],
["e2", "neg-reb", "Survival needs understanding your needs and environment; it's the origin of every other impact.", { r: "b3" }],
["f1", "aff-consol", "Force = cause of change, so vote on the cause, and creativity is the cause.", { r: "e1" }],
["g1", "neg-consol", "Reasoning from prior knowledge is intelligence, so knowledge grows without creativity. Intelligence covers its own impacts and creative ones = bigger scope.", { l: "Voter: scope", r: "f1" }],
["g2", "neg-consol", "No society forms without intelligence: greatest influence on the greatest many.", { r: "b5" }],
["h1", "aff-rationale", "Prerequisites don't matter. Vote for a society that lives, not one that just survives.", { r: "g1" }],
["i1", "neg-rationale", "Voter 1: intelligence is needed for creativity (intake skills + psychological condition). Even a lone idea needs it.", { r: "h1" }],
["i2", "neg-rationale", "Voter 2: greatest influence over the greatest many: survival, emotional intelligence, communication.", { r: "g2" }],
] },
],
},
mocktrial: {
fictional: true,
title: "Example: People v. Reyes (practice case)",
blurb: "Mock Trial · made-up burglary case · witness sheets, objections and a judge ballot",
meta: { format: "mocktrial", mySide: "", topic: "People v. Jordan Reyes: second-degree burglary of Riverside Music (fictional)",
proTeam: "Prosecution", conTeam: "Defense", round: "Practice round" },
ballot: { winner: "pro", ranks: {}, sheets: {},
rfd: "Close round. Defense's 'a hoodie isn't a face' theme landed, and the impeachment of Kim on cross was the best moment of the trial. Prosecution won on the case serial number (Exhibit 3) plus the phone being off 9:30-10:05, which the defense never explained in closing. Defense: the alibi photo needed a timestamp to carry reasonable doubt.",
scores: [
{ name: "Prosecution opening", pts: "8" }, { name: "Prosecution direct: Dana Kim", pts: "8" }, { name: "Witness: Dana Kim", pts: "7" },
{ name: "Prosecution direct: Officer Lee", pts: "9" }, { name: "Witness: Officer Lee", pts: "8" }, { name: "Prosecution cross: Sam Patel", pts: "9" },
{ name: "Prosecution closing", pts: "9" },
{ name: "Defense opening", pts: "9" }, { name: "Defense cross: Dana Kim", pts: "10" }, { name: "Defense cross: Officer Lee", pts: "7" },
{ name: "Defense direct: Sam Patel", pts: "7" }, { name: "Witness: Sam Patel", pts: "8" }, { name: "Defense closing", pts: "8" }
] },
sheets: [
{ title: "Openings & closings", kind: "speeches", cards: [
["p1", "p-open", "Theme: 'The camera doesn't lie.' Person in a red hoodie at the back door at 9:42 pm; guitar gone by 9:50.", { l: "Theme" }],
["p2", "p-open", "Witnesses: owner Dana Kim (inventory, video), Officer Lee (found the store's guitar case in Reyes's car).", {}],
["p3", "p-open", "Ask: guilty of second-degree burglary.", {}],
["d1", "d-open", "Theme: 'A hoodie isn't a face.' The video never shows a face.", { l: "Theme", r: "p1" }],
["d2", "d-open", "Reyes was at a library study session until 10 pm (roommate Sam Patel).", { r: "p2" }],
["d3", "d-open", "The case in the car was empty. No guitar, no prints.", { r: "p2" }],
["q1", "p-close", "Same red hoodie, same build, 9:42. Kim knows him as a regular.", { r: "d1" }],
["q2", "p-close", "Alibi is a roommate who splits rent; library is 6 minutes away.", { r: "d2" }],
["q3", "p-close", "Case serial RM-2207 matches the store's inventory: it left the store that night.", { t: "Exhibit", c: "Exhibit 3", r: "d3" }],
["e1", "d-close", "Nobody saw a face. Kim admitted the hoodie is common and changed her story on day 3.", { r: "q1" }],
["e2", "d-close", "9:40 group photo shows Reyes at the library table.", { c: "Exhibit B", r: "q2" }],
["e3", "d-close", "Serial only proves the case came from a store that sells cases. Reasonable doubt three times over.", { r: "q3" }],
["f1", "p-rebut", "The photo has no timestamp, and Reyes's phone was off 9:30 to 10:05. Why?", { r: "e2" }],
] },
{ title: "Dana Kim (store owner)", kind: "witness", calledBy: "pro", cards: [
["k1", "w-direct", "Owns Riverside Music 12 years. Signed guitar valued at $4,800.", {}],
["k2", "w-direct", "Locked up 9:30; back-door alarm at 9:44.", { t: "Key fact" }],
["k3", "w-direct", "Video still: person in a red hoodie at the back door, 9:42.", { t: "Exhibit", c: "Exhibit 1" }],
["k4", "w-direct", "Recognizes Reyes as a regular; saw him in the same hoodie last week.", {}],
["x1", "w-cross", "Never saw a face on the video. Admits.", { r: "k3" }],
["x2", "w-cross", "Red hoodies are common.", { r: "k4" }],
["x3", "w-cross", "Didn't tell police about 'regular customer' until day 3. Statement p. 2 says only 'a person in a hoodie.'", { t: "Impeach", r: "k4" }],
["y1", "w-redirect", "Was upset that night; height and walk match Reyes.", { r: "x3" }],
["z1", "w-recross", "'Walk' isn't in her statement either.", { r: "y1" }],
["o1", "w-obj", "Defense: speculation on 'it was definitely him.'", { t: "Sustained" }],
["o2", "w-obj", "Defense: leading on direct (alarm time).", { t: "Overruled" }],
] },
{ title: "Officer Lee", kind: "witness", calledBy: "pro", cards: [
["l1", "w-direct", "Traffic stop 10:20 pm. Guitar case in the back seat.", {}],
["l2", "w-direct", "Serial RM-2207 matches the store's inventory list.", { t: "Exhibit", c: "Exhibit 3" }],
["l3", "w-direct", "Reyes said: 'It's just a case I bought.'", { t: "For closing" }],
["m1", "w-cross", "Case was empty. The guitar was never found.", { r: "l1" }],
["m2", "w-cross", "No fingerprints were tested.", { r: "l2" }],
["m3", "w-cross", "Stop was for a taillight, unrelated to the burglary.", { r: "l1" }],
["n1", "w-redirect", "An empty case still left the store the night of the burglary.", { r: "m1" }],
["o3", "w-obj", "Defense: hearsay on Reyes's statement. Ruled a party admission.", { t: "Overruled" }],
] },
{ title: "Sam Patel (roommate)", kind: "witness", calledBy: "con", cards: [
["s1", "w-direct", "Studied with Reyes at the library from 8 to 10 pm.", {}],
["s2", "w-direct", "Group text at 9:40 with a photo of Reyes at the table.", { t: "Exhibit", c: "Exhibit B" }],
["t1", "w-cross", "Roommates, split rent: bias.", { r: "s1" }],
["t2", "w-cross", "Photo sent at 9:40 but could have been taken earlier; no timestamp shown.", { r: "s2" }],
["t3", "w-cross", "Library is 6 minutes from the store.", { t: "Key fact", r: "s1" }],
["u1", "w-redirect", "Photo shows the library's 9:30 closing-soon screen behind Reyes.", { r: "t2" }],
["o4", "w-obj", "Prosecution: relevance on Patel's grades.", { t: "Sustained" }],
] },
],
},
};
function buildExampleFlow(key) {
var ex = EXAMPLE_ROUNDS[key];
var meta = Object.assign({ judge: "", judgeLink: "", tabroomLink: "", proNames: "", conNames: "",
proColor: "#db6300", conColor: "#5797ff" }, ex.meta);
var pages = ex.sheets.map(function (sh) {
var page = newPage(sh.title, "flow");
if (sh.kind) page.trialKind = sh.kind;
if (sh.calledBy) page.calledBy = sh.calledBy;
if (sh.q) page.qNotes = Object.assign({}, sh.q);
var ids = {};
sh.cards.forEach(function (t) {
var o = t[3] || {};
var card = newCard(t[1], { text: t[2], label: o.l || "", evidenceCite: o.c || null, shellTag: o.t || null });
if (o.s) card.qSide = o.s;
ids[t[0]] = card.id;
page.cards.push(card);
});
sh.cards.forEach(function (t) {
var o = t[3] || {};
if (o.r && ids[o.r]) page.links.push({ id: uid("link"), fromId: ids[t[0]], toId: ids[o.r], tag: "Responds to" });
});
return page;
});
return { id: uid("flow"), title: ex.title, meta: meta, pages: pages, activePageId: pages[0].id,
setupDone: true, tournamentId: null, pinned: false, shareWith: "private", isExample: key, exampleVersion: ex.v || 1, ballot: ex.ballot ? JSON.parse(JSON.stringify(ex.ballot)) : undefined };
}
function openExampleFlow(key) {
var flow = library.flows.filter(function (f) { return f.isExample === key; })[0];
if (flow && (flow.exampleVersion || 1) !== (EXAMPLE_ROUNDS[key].v || 1)) {
// A newer version of this example shipped: refresh it in place.
var refreshed = buildExampleFlow(key);
refreshed.id = flow.id;
library.flows[library.flows.indexOf(flow)] = refreshed;
flow = refreshed;
}
if (!flow) { flow = buildExampleFlow(key); library.flows.push(flow); }
library.activeRef = { kind: "flow", flowId: flow.id };
state = getActiveEntry();
persistLibrary();
closeModal();
render();
toast(EXAMPLE_ROUNDS[key].fictional ? "Practice example with a made-up case. Edit anything, or delete it from My Flows." : "Example round, flowed from a real debate. Edit anything, or delete it from My Flows.");
}
function openExamplesPicker() {
var root = document.getElementById("modal-root");
var veil = document.createElement("div");
veil.className = "modal-veil";
veil.innerHTML =
'
' +
"
Example flows
" +
"
Real rounds in every format, flowed in RoundFlow so you can see how a round looks on the board.
" +
'
' +
Object.keys(EXAMPLE_ROUNDS).map(function (k) {
var ex = EXAMPLE_ROUNDS[k];
return '";
}).join("") +
'' +
"
" +
'' +
"
";
root.innerHTML = "";
root.appendChild(veil);
veil.addEventListener("click", function (e) { if (e.target === veil) closeModal(); });
veil.querySelector('[data-act="close"]').addEventListener("click", closeModal);
veil.querySelectorAll("[data-example]").forEach(function (b) {
b.addEventListener("click", function () {
var k = b.getAttribute("data-example");
if (k === "sample") openSampleFlow(); else openExampleFlow(k);
});
});
}
function wireLibrary() {
wireThemeToggle("theme-toggle-lib");
wireAccountWidget("lib");
wireTeamLibrary();
wireOnboarding();
wireFolders();
var searchInput = document.getElementById("lib-search");
if (searchInput) {
searchInput.addEventListener("input", function () {
libSearchQuery = searchInput.value;
var pos = searchInput.selectionStart;
render();
var again = document.getElementById("lib-search");
if (again) { again.focus(); again.setSelectionRange(pos, pos); }
});
}
var newTournamentBtn = document.getElementById("btn-new-tournament");
if (newTournamentBtn) newTournamentBtn.addEventListener("click", function () { openSetupNew("tournament"); });
var newFlowBtn = document.getElementById("btn-new-flow");
if (newFlowBtn) newFlowBtn.addEventListener("click", function () { openSetupNew("flow"); });
document.querySelectorAll("[data-open-round]").forEach(function (btn) {
btn.addEventListener("click", function () {
var parts = btn.getAttribute("data-open-round").split("|");
library.activeRef = { kind: "round", tournamentId: parts[0], roundId: parts[1] };
focused = null;
persistLibrary();
render();
});
});
document.querySelectorAll("[data-open-preflow]").forEach(function (btn) {
btn.addEventListener("click", function () {
var tid = btn.getAttribute("data-open-preflow");
var t = library.tournaments.filter(function (x) { return x.id === tid; })[0];
if (!t || !t.rounds.length) { toast("Add a round first."); return; }
var mostRecent = t.rounds[t.rounds.length - 1];
library.activeRef = { kind: "round", tournamentId: tid, roundId: mostRecent.id };
state = getActiveEntry();
if (state) state.activePageId = SHARED_PREFLOW_ID;
focused = null;
persistLibrary();
render();
});
});
document.querySelectorAll("[data-open-flow]").forEach(function (btn) {
btn.addEventListener("click", function () {
library.activeRef = { kind: "flow", flowId: btn.getAttribute("data-open-flow") };
focused = null;
persistLibrary();
render();
});
});
document.querySelectorAll("[data-add-round]").forEach(function (btn) {
btn.addEventListener("click", function () { openAddRoundModal(btn.getAttribute("data-add-round")); });
});
document.querySelectorAll("[data-pin-tournament]").forEach(function (btn) {
btn.addEventListener("click", function () {
var tid = btn.getAttribute("data-pin-tournament");
var t = library.tournaments.filter(function (x) { return x.id === tid; })[0];
if (!t) return;
t.pinned = !t.pinned;
persistLibrary();
render();
});
});
document.querySelectorAll("[data-pin-flow]").forEach(function (btn) {
btn.addEventListener("click", function () {
var fid = btn.getAttribute("data-pin-flow");
var f = library.flows.filter(function (x) { return x.id === fid; })[0];
if (!f) return;
f.pinned = !f.pinned;
persistLibrary();
render();
});
});
document.querySelectorAll("[data-edit-tournament-link]").forEach(function (btn) {
btn.addEventListener("click", function () {
var tid = btn.getAttribute("data-edit-tournament-link");
var t = library.tournaments.filter(function (x) { return x.id === tid; })[0];
if (!t) return;
promptText({
title: "Tabroom link",
hint: "Paste a link to this tournament's page on Tabroom.",
placeholder: "https://…",
inputType: "url",
current: t.tabroomLink || "",
allowClear: true,
onSave: function (v) { t.tabroomLink = v; persistLibrary(); render(); }
});
});
});
document.querySelectorAll("[data-rename-tournament]").forEach(function (btn) {
btn.addEventListener("click", function () {
var tid = btn.getAttribute("data-rename-tournament");
var t = library.tournaments.filter(function (x) { return x.id === tid; })[0];
if (!t) return;
promptRename(t.name, function (v) { t.name = v; persistLibrary(); render(); });
});
});
document.querySelectorAll("[data-delete-tournament]").forEach(function (btn) {
btn.addEventListener("click", function () {
var tid = btn.getAttribute("data-delete-tournament");
var t = library.tournaments.filter(function (x) { return x.id === tid; })[0];
confirmModal({
title: "Delete this tournament?",
body: "This removes " + (t ? "“" + t.name + "”" : "this tournament") + ", every round in it, and its shared preflow. This can’t be undone.",
okLabel: "Delete tournament", danger: true,
onConfirm: function () {
library.tournaments = library.tournaments.filter(function (x) { return x.id !== tid; });
if (library.activeRef && library.activeRef.kind === "round" && library.activeRef.tournamentId === tid) library.activeRef = null;
persistLibrary();
render();
}
});
});
});
document.querySelectorAll("[data-rename-flow]").forEach(function (btn) {
btn.addEventListener("click", function () {
var fid = btn.getAttribute("data-rename-flow");
var f = library.flows.filter(function (x) { return x.id === fid; })[0];
if (!f) return;
promptRename(f.title, function (v) { f.title = v; persistLibrary(); render(); });
});
});
document.querySelectorAll("[data-delete-flow]").forEach(function (btn) {
btn.addEventListener("click", function () {
var fid = btn.getAttribute("data-delete-flow");
var f = library.flows.filter(function (x) { return x.id === fid; })[0];
confirmModal({
title: "Delete this flow?",
body: "This removes " + (f ? "“" + f.title + "”" : "this flow") + " and everything on it. This can’t be undone.",
okLabel: "Delete flow", danger: true,
onConfirm: function () {
library.flows = library.flows.filter(function (x) { return x.id !== fid; });
if (library.activeRef && library.activeRef.kind === "flow" && library.activeRef.flowId === fid) library.activeRef = null;
persistLibrary();
render();
}
});
});
});
}
/* ============ Main app screen ============ */
function render() {
if (sessionKnown || account) switchLibraryOwner(account ? account.id : null);
if (setupDraft) { renderSetup(); return; }
if (!library.activeRef) { renderLibrary(); return; }
state = getActiveEntry();
if (!state) { library.activeRef = null; renderLibrary(); return; }
applyCustomColors();
if (!state.setupDone) { renderSetup(); return; }
var app = document.getElementById("app");
var page = currentPage();
var m = state.meta;
var tour = currentTournament();
var contextBadge = tour
? '' + escapeHtml(tour.name) + " · " + escapeHtml(state.title || "Round") + ""
: (library.activeRef.kind === "flow" ? '' + escapeHtml(state.title || "Flow") + "" : "");
var topbar =
'
' +
'
RoundFlow
' +
(contextBadge ? '" : "") +
'
' +
// singleQueue formats (Congress) don't have fixed team sides to
// summarize as chips — each card is tagged individually instead.
(currentFormat().singleQueue ? "" :
Object.keys(currentFormat().sideNames).map(function (k) {
var label = teamField(m, k, "team") || currentFormat().sideNames[k];
return '' + escapeHtml(label) + (m.mySide === k ? ' (you)' : "") + "";
}).join("")) +
(m.topic ? '' + escapeHtml(m.topic) + "" : "") +
"
Click the argument this ' + escapeHtml(pendingLink.tag) + ' connects to…
'
: "";
var bodyHtml = viewAllSheets() ? renderAllSheets() : renderFlowBody(page);
var footer = '";
app.innerHTML = topbar + tabs + pickerBar + bodyHtml + footer;
wireThemeToggle("theme-toggle-app");
wireApp();
autosizeCards();
// Re-measure once layout and web fonts settle (text was getting clipped on first paint).
requestAnimationFrame(autosizeCards);
scheduleRedrawLinks();
}
function autosizeCards() {
var app = document.getElementById("app");
if (!app) return;
app.querySelectorAll("textarea").forEach(function (el) {
el.style.height = "auto";
el.style.height = (el.scrollHeight + 2) + "px";
});
scheduleRedrawLinks();
}
if (document.fonts && document.fonts.ready) document.fonts.ready.then(function () { autosizeCards(); });
window.addEventListener("resize", function () { clearTimeout(window.__rfResize); window.__rfResize = setTimeout(autosizeCards, 150); });
var openPopover = null; /* "colors" | null */
function renderColorsPopover() {
var m = state.meta;
var sn = currentFormat().sideNames;
var locked = !currentGating().customColors;
return '
' +
(locked ? '
Custom colors are a paid feature.
' : "") +
Object.keys(sn).map(function (k) {
var color = teamField(m, k, "color") || DEFAULT_SIDE_COLOR[k];
return '";
}).join("") +
"
";
}
function renderFlowBody(page) {
var fmt = currentFormat();
var cols = pageCols(fmt, page).map(function (c) {
// singleQueue formats (Congress): speeches aren't tied to a fixed side,
// so instead of the generic "+ Add" + term-picker menu, offer two
// direct-action buttons that tag the new card's qSide immediately —
// this is the "tagged Aff/Neg as you add them" behavior Bobby asked for.
var addUi = fmt.singleQueue
? '
"
: "") +
// Congress (singleQueue) cards are titled with the speaker's name
// instead of the structured-term label every other format uses card.label
// for — that field is otherwise unused here (Congress has no shellTag/
// structured parts), so it's reused rather than adding a new one.
(fmt.singleQueue
? ''
: (card.label ? '' + escapeHtml(card.label) + "" : "")) +
(card.evidenceCite ? '" : "") +
(card.evidenceUrl ? '🔗' : "") +
'" +
'