Files
mtgc/src/views/DeckView.tsx
garrettmills e57c3dec51 Deck actions UI, consistent icon buttons, native select fix, sidebar stats
- DeckView: rename/duplicate/delete deck via row-hover icon actions, with
  a ConfirmDialog for delete and PromptDialog (with friendly name-
  collision errors) for rename/duplicate.
- Add a shared IconButton (plus overlay/danger variants) and replace
  every ad hoc close/remove button in the app with it: deck actions,
  remove-card-from-deck (list and tile), clear-commander, the card-
  preview close, and the ingest-progress dismiss.
- Fix native <select> (Group by, Format, In deck): only color/border were
  overridden, leaving native OS chrome (height, arrow, popup) in place.
  Drop appearance and draw a custom chevron so they match text inputs.
- Click-to-preview: show both faces of a double-faced card side by side
  on wide viewports instead of requiring Flip, and size the preview
  images larger overall.
- Sidebar footer: replace the plain "N cards" line with a "Your library"
  panel (unique/copies/decks tiles + a WUBRG color-distribution bar),
  polling get_library_stats while card data is loaded.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-07 21:21:47 -05:00

476 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useState, useCallback } from "react";
import { api, CardRef, Deck, DeckEntry } from "../api";
import {
CardSearchBox,
CardThumb,
CardTile,
ColorPips,
ConfirmDialog,
GroupBySelect,
GroupMode,
IconButton,
Icons,
PromptDialog,
ViewToggle,
groupCards,
usePersistedState,
useViewMode,
} from "../components";
type DeckDialog =
| { kind: "delete"; deck: Deck }
| { kind: "rename"; deck: Deck }
| { kind: "duplicate"; deck: Deck }
| null;
function friendlyDeckError(err: unknown): string {
const msg = String(err);
return msg.includes("UNIQUE constraint failed") ? "A deck with that name already exists." : msg;
}
const FORMATS = [
"",
"Commander",
"Brawl",
"Standard",
"Pioneer",
"Modern",
"Legacy",
"Vintage",
"Pauper",
"Other",
];
const COMMANDER_FORMATS = ["Commander", "Brawl"];
/**
* Deck editor. A deck's cards are split into two groups — "In your library"
* (owned) and "Not owned" — each with its own search box, and each groupable by
* card attribute. Deck-level format + commander metadata sit at the top.
*/
export function DeckView() {
const [decks, setDecks] = useState<Deck[]>([]);
const [selected, setSelected] = usePersistedState<number | null>("deck-selected", null);
const [newName, setNewName] = useState("");
const [contents, setContents] = useState<DeckEntry[]>([]);
const [view, setView] = useViewMode("deck-view");
const [groupBy, setGroupBy] = usePersistedState<GroupMode>("deck-group", "none");
const [dialog, setDialog] = useState<DeckDialog>(null);
const [dialogError, setDialogError] = useState<string | null>(null);
const [libQuery, setLibQuery] = useState("");
const [libResults, setLibResults] = useState<CardRef[]>([]);
const [anyQuery, setAnyQuery] = useState("");
const [anyResults, setAnyResults] = useState<CardRef[]>([]);
const [cmdQuery, setCmdQuery] = useState("");
const [cmdResults, setCmdResults] = useState<CardRef[]>([]);
const deck = decks.find((d) => d.id === selected) ?? null;
const loadDecks = useCallback(async () => {
const d = await api.listDecks();
setDecks(d);
// Keep the persisted selection if it still exists, else fall back to the first.
if (d.length && (selected === null || !d.some((x) => x.id === selected))) {
setSelected(d[0].id);
}
}, [selected, setSelected]);
useEffect(() => {
loadDecks();
}, [loadDecks]);
const loadContents = useCallback(async () => {
if (selected === null) {
setContents([]);
return;
}
setContents(await api.deckContents(selected));
}, [selected]);
useEffect(() => {
loadContents();
}, [loadContents]);
useEffect(() => {
const q = libQuery.trim();
if (!q) return setLibResults([]);
const t = setTimeout(() => api.searchLibrary({ text: q }).then(setLibResults), 100);
return () => clearTimeout(t);
}, [libQuery]);
useEffect(() => {
const q = anyQuery.trim();
if (!q) return setAnyResults([]);
const t = setTimeout(() => api.searchCards(q, 12).then(setAnyResults), 80);
return () => clearTimeout(t);
}, [anyQuery]);
useEffect(() => {
const q = cmdQuery.trim();
if (!q) return setCmdResults([]);
const t = setTimeout(() => api.searchCards(q, 12).then(setCmdResults), 80);
return () => clearTimeout(t);
}, [cmdQuery]);
async function createDeck() {
if (!newName.trim()) return;
const d = await api.createDeck(newName.trim(), null);
setNewName("");
await loadDecks();
setSelected(d.id);
}
async function addToDeck(card: CardRef) {
if (selected === null) return;
const existing = contents.find((e) => e.oracle_id === card.oracle_id);
const qty = existing ? existing.quantity + 1 : 1;
await api.setDeckCard(selected, card.oracle_id, qty, false);
setLibQuery("");
setLibResults([]);
setAnyQuery("");
setAnyResults([]);
await loadContents();
}
async function setQty(oracleId: string, qty: number) {
if (selected === null) return;
await api.setDeckCard(selected, oracleId, qty, false);
await loadContents();
}
async function confirmDelete() {
if (dialog?.kind !== "delete") return;
await api.deleteDeck(dialog.deck.id);
if (selected === dialog.deck.id) setSelected(null);
setDialog(null);
await loadDecks();
}
async function confirmRename(name: string) {
if (dialog?.kind !== "rename") return;
try {
await api.renameDeck(dialog.deck.id, name);
setDialog(null);
setDialogError(null);
await loadDecks();
} catch (err) {
setDialogError(friendlyDeckError(err));
}
}
async function confirmDuplicate(newName: string) {
if (dialog?.kind !== "duplicate") return;
try {
const d = await api.duplicateDeck(dialog.deck.id, newName);
setDialog(null);
setDialogError(null);
await loadDecks();
setSelected(d.id);
} catch (err) {
setDialogError(friendlyDeckError(err));
}
}
async function changeFormat(format: string) {
if (selected === null) return;
await api.setDeckFormat(selected, format);
await loadDecks();
}
async function setCommander(card: CardRef) {
if (selected === null) return;
// Ensure the commander is in the deck, then flag it.
if (!contents.find((e) => e.oracle_id === card.oracle_id)) {
await api.setDeckCard(selected, card.oracle_id, 1, true);
}
await api.setDeckCommander(selected, card.oracle_id);
setCmdQuery("");
setCmdResults([]);
await loadContents();
await loadDecks();
}
async function clearCommander() {
if (selected === null) return;
await api.setDeckCommander(selected, null);
await loadContents();
await loadDecks();
}
const owned = contents.filter((e) => e.quantity_owned > 0);
const unowned = contents.filter((e) => e.quantity_owned === 0);
const commanderName =
deck?.commander_oracle_id &&
(contents.find((e) => e.oracle_id === deck.commander_oracle_id)?.name ??
deck.commander_oracle_id);
function deckTiles(entries: DeckEntry[]) {
return (
<div className="tile-grid">
{entries.map((e) => (
<CardTile
key={e.oracle_id}
card={e}
corner={
<IconButton
icon={Icons.close}
label="Remove from deck"
overlay
onClick={() => setQty(e.oracle_id, 0)}
/>
}
footer={
<span className="tile-badge">
{e.is_commander ? "★ " : ""}in deck ×{e.quantity}
</span>
}
/>
))}
</div>
);
}
function deckTable(entries: DeckEntry[]) {
return (
<table>
<thead>
<tr>
<th></th>
<th>Colors</th>
<th>Name</th>
<th>Type</th>
<th>In deck</th>
<th>Owned</th>
<th></th>
</tr>
</thead>
<tbody>
{entries.map((e) => (
<tr key={e.oracle_id}>
<td>
<CardThumb card={e} />
</td>
<td>
<ColorPips mask={e.color_identity} />
</td>
<td className="card-name">
{e.is_commander && <span title="Commander">★ </span>}
{e.name}
</td>
<td className="card-type">{e.type_line}</td>
<td>
<input
type="number"
min={0}
style={{ width: 60 }}
key={e.quantity}
defaultValue={e.quantity}
onBlur={(ev) => setQty(e.oracle_id, Number(ev.target.value))}
/>
</td>
<td>{e.quantity_owned}</td>
<td>
<IconButton
icon={Icons.close}
label="Remove from deck"
onClick={() => setQty(e.oracle_id, 0)}
/>
</td>
</tr>
))}
</tbody>
</table>
);
}
function cardsGroup(entries: DeckEntry[]) {
if (entries.length === 0) return <p className="hint">None yet.</p>;
return groupCards(entries, groupBy).map((g) => (
<div key={g.label || "all"} style={{ marginBottom: g.label ? 14 : 0 }}>
{g.label && (
<h4>
{g.label} <span className="badge">{g.cards.length}</span>
</h4>
)}
{view === "tiles" ? deckTiles(g.cards) : deckTable(g.cards)}
</div>
));
}
return (
<div style={{ display: "flex", gap: 20 }}>
<div style={{ width: 240, flexShrink: 0 }}>
<h2>Decks</h2>
<div className="row" style={{ marginBottom: 10 }}>
<input
value={newName}
placeholder="New deck name"
onChange={(e) => setNewName(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && createDeck()}
/>
<button className="primary" onClick={createDeck}>
+
</button>
</div>
<ul className="result-list">
{decks.map((d) => (
<li
key={d.id}
style={d.id === selected ? { background: "var(--accent-subtle)" } : undefined}
onClick={() => setSelected(d.id)}
>
<span className="card-name">{d.name}</span>
{d.format && <span className="deck-chip">{d.format}</span>}
<span className="spacer" />
<span className="row-actions">
<IconButton
icon={Icons.pencil}
label="Rename deck"
onClick={(e) => {
e.stopPropagation();
setDialogError(null);
setDialog({ kind: "rename", deck: d });
}}
/>
<IconButton
icon={Icons.copy}
label="Duplicate deck"
onClick={(e) => {
e.stopPropagation();
setDialogError(null);
setDialog({ kind: "duplicate", deck: d });
}}
/>
<IconButton
icon={Icons.trash}
label="Delete deck"
danger
onClick={(e) => {
e.stopPropagation();
setDialog({ kind: "delete", deck: d });
}}
/>
</span>
</li>
))}
{decks.length === 0 && (
<li style={{ cursor: "default" }} className="hint">
No decks yet.
</li>
)}
</ul>
</div>
<div style={{ flex: 1 }}>
{selected === null || !deck ? (
<p className="hint">Select or create a deck.</p>
) : (
<>
<div className="row" style={{ justifyContent: "space-between" }}>
<h2>{deck.name}</h2>
<div className="row" style={{ gap: 16 }}>
<GroupBySelect value={groupBy} onChange={setGroupBy} />
<ViewToggle mode={view} onChange={setView} />
</div>
</div>
{/* Deck metadata: format + (for Commander/Brawl) the commander card. */}
<div className="deck-meta">
<label className="row" style={{ gap: 6 }}>
<span className="muted">Format</span>
<select value={deck.format} onChange={(e) => changeFormat(e.target.value)}>
{FORMATS.map((f) => (
<option key={f} value={f}>
{f || "—"}
</option>
))}
</select>
</label>
{COMMANDER_FORMATS.includes(deck.format) && (
<div className="commander-box">
<div className="row" style={{ gap: 8 }}>
<span className="muted">Commander:</span>
<strong>{commanderName || "none"}</strong>
{commanderName && (
<IconButton icon={Icons.close} label="Clear commander" onClick={clearCommander} />
)}
</div>
<CardSearchBox
placeholder="Search to set the commander…"
value={cmdQuery}
onChange={setCmdQuery}
results={cmdResults}
onPick={setCommander}
/>
</div>
)}
</div>
<section style={{ marginTop: 18 }}>
<h3>
In your library <span className="badge">{owned.length}</span>
</h3>
<CardSearchBox
placeholder="Search your library to add owned cards…"
value={libQuery}
onChange={setLibQuery}
results={libResults}
onPick={addToDeck}
/>
{cardsGroup(owned)}
</section>
<section style={{ marginTop: 26 }}>
<h3>
Not owned <span className="badge">{unowned.length}</span>
</h3>
<CardSearchBox
placeholder="Search all cards to add ones you don't own…"
value={anyQuery}
onChange={setAnyQuery}
results={anyResults}
onPick={addToDeck}
/>
{cardsGroup(unowned)}
</section>
</>
)}
</div>
{dialog?.kind === "delete" && (
<ConfirmDialog
title="Delete deck"
message={`Delete "${dialog.deck.name}"? This can't be undone.`}
confirmLabel="Delete"
danger
onConfirm={confirmDelete}
onCancel={() => setDialog(null)}
/>
)}
{dialog?.kind === "rename" && (
<PromptDialog
title="Rename deck"
label="Deck name"
defaultValue={dialog.deck.name}
confirmLabel="Rename"
error={dialogError}
onConfirm={confirmRename}
onCancel={() => setDialog(null)}
/>
)}
{dialog?.kind === "duplicate" && (
<PromptDialog
title="Duplicate deck"
label="Name for the copy"
defaultValue={`${dialog.deck.name} (copy)`}
confirmLabel="Duplicate"
error={dialogError}
onConfirm={confirmDuplicate}
onCancel={() => setDialog(null)}
/>
)}
</div>
);
}