This commit is contained in:
2026-10-29 15:21:05 +01:00
parent bb85881cac
commit bc05b63083
36 changed files with 4654 additions and 5080 deletions

View File

@@ -298,11 +298,14 @@ button.danger {
}
.badge {
font-size: 0.7rem;
flex: none;
font-size: 0.62rem;
line-height: 1.2;
text-transform: uppercase;
letter-spacing: 0.03em;
letter-spacing: 0.02em;
white-space: nowrap;
border-radius: 99px;
padding: 0.1rem 0.45rem;
padding: 0.04rem 0.35rem;
border: 1px solid currentColor;
color: var(--muted);
}
@@ -319,7 +322,7 @@ button.danger {
color: var(--bad);
}
.badge.manual {
.badge.verified {
color: var(--accent);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,212 +0,0 @@
<template>
<section class="pseudo-guide">
<header class="guide-head">
<h2>Card pseudocode guide</h2>
<p class="muted">
The editor and the compiler use the same two-way format. The
<strong>Visual</strong> tab is a node canvas: drag sockets to connect an ability to its
effects, and drag green value nodes (players, targets, selectors, costs) into argument
sockets. Selector <strong>OR</strong>/<strong>AND</strong> nodes can combine two selector
slots. It writes the same source as the text editor. Use <strong>Draft with AI</strong> for
a first pass, then review and save.
</p>
</header>
<article>
<h3>Shape</h3>
<p>
One ability per block. The header starts at column 0 and ends with a colon; effects are
indented two spaces, one call per line. A leading <code># Card [status]</code> line is
optional and ignored. Multi-face cards use <code>## Face Name [status]</code> sections in
card order. Use <code>(no abilities)</code> for an empty face.
</p>
<pre># Soul Warden [supported]
on enters(each other creature):
gain_life(you, 1)
# Llanowar Elves [supported]
activate {T}:
add_mana(you, {G})</pre>
</article>
<article>
<h3>Ability blocks</h3>
<table>
<thead>
<tr><th>Header</th><th>Example</th></tr>
</thead>
<tbody>
<tr><td><code>on &lt;trigger&gt;:</code></td><td><code>on dies(this):</code></td></tr>
<tr><td><code>activate &lt;cost&gt;:</code></td><td><code>activate {2}, {T}:</code></td></tr>
<tr><td><code>static:</code></td><td><code>static:</code></td></tr>
<tr><td><code>spell:</code></td><td>An instant or sorcery effect line.</td></tr>
<tr><td><code>keyword &lt;name&gt;</code></td><td><code>keyword Flying</code></td></tr>
<tr><td><code>keywords &lt;a&gt;, &lt;b&gt;</code></td><td><code>keywords Flying, vigilance</code></td></tr>
<tr><td><code>additional cost: &lt;cost&gt;</code></td><td><code>additional cost: pay 2 life</code></td></tr>
<tr><td><code>if &lt;condition&gt;:</code></td><td>Nested effects, indented below.</td></tr>
<tr><td><code>choose &lt;n&gt;:</code></td><td>Numbered modes <code>1.</code>, <code>2.</code></td></tr>
<tr><td><code>schedule(next_upkeep):</code></td><td>Delayed effects.</td></tr>
</tbody>
</table>
</article>
<article>
<h3>Effect calls</h3>
<p>Effects are lowercase calls. Separate several on one line with <code>;</code>.</p>
<pre>damage(target creature, 3)
draw(you, 2)
gain_life(you, 1)
create_token(you, 1, 1/1 red goblin creature)
put_counters(target creature, +1/+1, 2)
destroy(target creature)
exile(target artifact you control)
add_mana(you, {G}{G})
search(you, creature, 1, to hand, shuffle)
scry(you, 2)
pump(each creature you control, 1/1, until end of turn)</pre>
</article>
<article>
<h3>Targets, values and costs</h3>
<table>
<tbody>
<tr>
<th>Targets</th>
<td><code>this</code>, <code>the triggering object</code>, <code>target creature</code>, <code>each opponent</code>, <code>up to 2 target creatures</code>, <code>any target</code></td>
</tr>
<tr>
<th>Selectors</th>
<td><code>other tapped creature you control</code>, <code>red instant from a graveyard</code>, <code>creature with power 4 or greater</code></td>
</tr>
<tr>
<th>Values</th>
<td><code>2</code>, <code>X</code>, <code>count(creature you control)</code>, <code>its power</code>, <code>that much</code></td>
</tr>
<tr>
<th>Costs</th>
<td><code>{2}{U}</code>, <code>{T}</code>, <code>pay 3 life</code>, <code>discard 1 card(s)</code>, <code>sacrifice this</code>, <code>remove 1 +1/+1 counter(s) from this</code></td>
</tr>
<tr>
<th>Durations</th>
<td><code>until end of turn</code>, <code>until your next turn</code>, <code>until the end of your next turn</code>, <code>for as long as this remains on the battlefield</code></td>
</tr>
</tbody>
</table>
</article>
<article>
<h3>Triggers, conditions and modes</h3>
<pre>on attacks(this):
create_token(you, 1, tapped 1/1 red goblin creature)
on upkeep(you):
if you control at least 3 artifacts:
draw(you, 1)
spell:
choose 1:
1. draw(you, 2)
2. gain_life(you, 3)
static:
grant(each creature you control, Flying)</pre>
<p class="muted">
Common triggers: <code>enters</code>, <code>dies</code>, <code>attacks</code>,
<code>upkeep</code>, <code>end_step</code>, <code>cast</code>,
<code>deals_damage</code>. Always check the generated line after saving.
</p>
</article>
<article>
<h3>When the syntax cannot express it</h3>
<p>
Never guess a wrong effect. Use the preserved form and leave the line unsupported:
</p>
<pre>unsupported (modal bullet outside a choose block): Choose one — ...</pre>
<p class="muted">
The full reference lives in <code>backend/docs/card-effects.md</code>.
</p>
</article>
</section>
</template>
<style scoped>
.pseudo-guide {
flex: 1;
min-height: 0;
overflow-y: auto;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 1rem 1.25rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.guide-head {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
h3 {
margin-bottom: 0.4rem;
}
p {
line-height: 1.5;
font-size: 0.9rem;
}
code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.85em;
background: #11151d;
border: 1px solid var(--line);
border-radius: 4px;
padding: 0.05rem 0.3rem;
}
pre {
margin: 0.5rem 0 0;
padding: 0.65rem 0.8rem;
background: #11151d;
border: 1px solid var(--line);
border-radius: 6px;
overflow-x: auto;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.82rem;
line-height: 1.5;
}
table {
border-collapse: collapse;
width: 100%;
font-size: 0.85rem;
}
th,
td {
border-bottom: 1px solid var(--line);
padding: 0.35rem 0.5rem;
text-align: left;
vertical-align: top;
}
th {
white-space: nowrap;
color: var(--muted);
font-weight: 600;
}
tbody th {
width: 7rem;
}
@media (max-width: 800px) {
tbody th {
width: auto;
}
}
</style>

View File

@@ -0,0 +1,227 @@
<template>
<section class="source-guide">
<header class="guide-head">
<h2>Card source guide</h2>
<p class="muted">
Implementations are a small, literal JavaScript expression that the backend evaluates with
its own safe interpreter. It is never run as JavaScript: only the names below exist. The
editor and the compiler use the same two-way format. Use <strong>Draft with AI</strong> for
a first pass, then review and save.
</p>
</header>
<article>
<h3>Shape</h3>
<p>
Export the card's type line and an array of abilities with
<code>card(typeLine, [...])</code>. A leading <code>// Card [status]</code> comment is
optional and ignored. Multi-face cards export
<code>faces(face('Name', 'Type line', [...]), ...)</code> in card order.
</p>
<pre>export default card('Creature — Human Cleric', [
keywords('Flying', 'Ward {2}'),
triggered(when.enters(each(permanents.other().withType('creature'))), [
gainLife(you, 1),
]),
activated([tapCost()], [
addMana(you, mana('{G}')),
]),
])
export default faces(
face('Front', 'Instant', [spell([draw(you, 2)])]),
face('Back', 'Creature — Human', [keyword('Flying')]),
)</pre>
<p class="muted">
Plain <code>export default [...]</code> is still accepted and uses the Scryfall type line.
Effect lists also accept callbacks: <code>() =&gt; draw(you, 1)</code> for one effect,
or <code>() =&gt; { draw(you, 1); gainLife(you, 1) }</code> for several. Arrays remain
valid; the formatter emits callbacks.
</p>
</article>
<article>
<h3>Abilities</h3>
<table>
<thead>
<tr><th>Call</th><th>Example</th></tr>
</thead>
<tbody>
<tr><td><code>triggered(event, [effects], options)</code></td><td><code>triggered(when.dies(self), [draw(you, 1)])</code></td></tr>
<tr><td><code>activated([costs], [effects], options)</code></td><td><code>activated([manaCost('{2}'), tapCost()], [...])</code></td></tr>
<tr><td><code>staticAbility([effects], options)</code></td><td><code>staticAbility([staticPump(each(creatures.youControl()), 1, 1)])</code></td></tr>
<tr><td><code>spell([effects], options)</code></td><td>An instant or sorcery.</td></tr>
<tr><td><code>keyword(name, value)</code></td><td><code>keyword('Ward', '{2}')</code></td></tr>
<tr><td><code>keywords(...names)</code></td><td><code>keywords('Flying', 'Trample')</code></td></tr>
<tr><td><code>additionalCost([costs])</code></td><td><code>additionalCost([payLife(2)])</code></td></tr>
<tr><td><code>chapter(['I', 'II'], [effects])</code></td><td>Saga chapters.</td></tr>
<tr><td><code>unsupported(reason, text)</code></td><td>Preserve the oracle text when it cannot be expressed.</td></tr>
</tbody>
</table>
<p class="muted">
Options include <code>{ condition, optional }</code>; activated abilities also accept
<code>timing: 'sorcery'</code> and <code>activationsPerTurn</code>.
</p>
</article>
<article>
<h3>Selectors and targets</h3>
<p>
Start from <code>permanents</code>, <code>cards</code> or <code>creatures</code> and chain
filters: <code>withType</code>, <code>withSubtype</code>, <code>withSupertype</code>,
<code>withColor</code>, <code>withKeyword</code>, <code>youControl</code>,
<code>other</code>, <code>tapped</code>, <code>token</code>, <code>powerAtLeast</code>,
<code>manaValueAtMost</code>, <code>named</code>, <code>inZone</code>.
</p>
<pre>target(permanents.withType('creature').other().youControl())
each(creatures.withColor('red').withKeyword('flying'))
pick(cards.withType('land'), { upTo: 2 })
targetSpell(permanents.withType('instant'))
divided(3, creatures.attacking())
self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker</pre>
<p class="muted">
Values: numbers, <code>X</code>, <code>itsPower</code>, <code>itsToughness</code>,
<code>count(selector)</code>, <code>cardsInHand(you)</code>,
<code>totalPower(selector)</code>, <code>eventAmount()</code>.
</p>
</article>
<article>
<h3>Effects and costs</h3>
<pre>damage(target(creature), 3)
draw(you, 2)
gainLife(you, 1)
createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1 }))
putCounters(target(creature), '+1/+1', 2)
destroy(target(creature))
addMana(you, mana('{G}{G}'))
search(you, cards.withType('creature'), 1, { destination: 'battlefield', shuffle: true })
pump(each(creatures.youControl()), 1, 1, untilEndOfTurn)
ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)])
modal(1, 1, [[draw(you, 2)], [gainLife(you, 3)]])</pre>
<p>
Costs are separate: <code>manaCost('{2}{U}')</code>, <code>tapCost()</code>,
<code>sacrificeSelf()</code>, <code>payLife(3)</code>,
<code>discardCost(1)</code>, <code>removeCountersCost('+1/+1', 1)</code>.
</p>
<p class="muted">
Durations: <code>permanent</code>, <code>untilEndOfTurn</code>,
<code>untilYourNextTurn</code>, <code>untilEndOfYourNextTurn</code>,
<code>untilEndOfCombat</code>, <code>whileSourceOnBattlefield</code>.
</p>
</article>
<article>
<h3>Triggers, statics and conditions</h3>
<pre>triggered(when.attacks(self), [
createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1, tapped: true })),
])
triggered(when.upkeep(you), [
ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)]),
])
staticAbility([
staticGrant(each(creatures.youControl()), 'Flying'),
])</pre>
<p class="muted">
Common triggers: <code>when.enters</code>, <code>when.dies</code>,
<code>when.attacks</code>, <code>when.upkeep</code>, <code>when.endStep</code>,
<code>when.cast</code>, <code>when.dealsDamage</code>. Common conditions:
<code>yourTurn()</code>, <code>youControl(selector, n)</code>, <code>wasKicked()</code>,
<code>ifYouDo()</code>, <code>otherwise()</code>. Always check the compiled result after
saving.
</p>
</article>
<article>
<h3>When the syntax cannot express it</h3>
<p>Never guess a wrong effect. Preserve the oracle text and leave it unsupported:</p>
<pre>unsupported('modal bullet outside a modal block', 'Choose one — ...')</pre>
<p class="muted">
The full reference lives in <code>backend/docs/card-effects.md</code>.
</p>
</article>
</section>
</template>
<style scoped>
.source-guide {
flex: 1;
min-height: 0;
overflow-y: auto;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 1rem 1.25rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.guide-head {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
h3 {
margin-bottom: 0.4rem;
}
p {
line-height: 1.5;
font-size: 0.9rem;
}
code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.85em;
background: #11151d;
border: 1px solid var(--line);
border-radius: 4px;
padding: 0.05rem 0.3rem;
}
pre {
margin: 0.5rem 0 0;
padding: 0.65rem 0.8rem;
background: #11151d;
border: 1px solid var(--line);
border-radius: 6px;
overflow-x: auto;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.82rem;
line-height: 1.5;
}
table {
border-collapse: collapse;
width: 100%;
font-size: 0.85rem;
}
th,
td {
border-bottom: 1px solid var(--line);
padding: 0.35rem 0.5rem;
text-align: left;
vertical-align: top;
}
th {
white-space: nowrap;
color: var(--muted);
font-weight: 600;
}
tbody th {
width: 7rem;
}
@media (max-width: 800px) {
tbody th {
width: auto;
}
}
</style>

View File

@@ -1,9 +1,14 @@
<script setup lang="ts">
import CardGraphEditor from '../components/CardGraphEditor.vue'
import PseudoGuide from '../components/PseudoGuide.vue'
import SourceGuide from '../components/SourceGuide.vue'
type Status = 'supported' | 'partial' | 'unsupported'
const statusLabels: Record<Status, string> = {
supported: 'Supported',
partial: 'Partial',
unsupported: 'Unsupported',
}
interface CardSummary {
oracle_id: string
name: string
@@ -87,7 +92,6 @@ const rarityOptions = ['common', 'uncommon', 'rare', 'mythic', 'special', 'bonus
const cmcOptions = ['0', '1', '2', '3', '4', '5', '6', '7+']
const view = ref<'editor' | 'guide'>('editor')
const editorMode = ref<'text' | 'visual'>('text')
const search = ref('')
const statusFilter = ref('needs-work')
const formatFilter = ref('')
@@ -217,7 +221,7 @@ async function translate() {
async function reset() {
if (!detail.value || saving.value) return
if (!window.confirm('Delete the manual implementation and restore the generated one?')) return
if (!window.confirm('Delete the verified implementation and restore the generated one?')) return
saving.value = true
editorError.value = ''
try {
@@ -269,7 +273,7 @@ onMounted(() => {
{{ stats.supported.toLocaleString() }} supported ·
{{ stats.partial.toLocaleString() }} partial ·
{{ stats.unsupported.toLocaleString() }} unsupported ·
{{ stats.manual.toLocaleString() }} manual
{{ stats.manual.toLocaleString() }} verified
</template>
<template v-else>Loading stats…</template>
</p>
@@ -292,7 +296,7 @@ onMounted(() => {
<option value="unsupported">Not implemented</option>
<option value="partial">Partial</option>
<option value="supported">Supported</option>
<option value="manual">Manual</option>
<option value="manual">Verified</option>
<option value="all">All cards</option>
</select>
<button type="submit">Search</button>
@@ -353,8 +357,16 @@ onMounted(() => {
v-if="card.implementation"
class="badge"
:class="card.implementation.status"
>{{ card.implementation.status }}</span>
<span v-if="card.implementation?.manual" class="badge manual">manual</span>
:title="statusLabels[card.implementation.status]"
:aria-label="statusLabels[card.implementation.status]"
>{{ card.implementation.status[0] }}</span>
<span
v-if="card.implementation"
class="badge"
:class="card.implementation.manual ? 'verified' : 'generated'"
:title="card.implementation.manual ? 'Verified' : 'Generated'"
:aria-label="card.implementation.manual ? 'Verified' : 'Generated'"
>{{ card.implementation.manual ? 'V' : 'G' }}</span>
</span>
</button>
</CardHover>
@@ -381,8 +393,18 @@ onMounted(() => {
</p>
</div>
<div class="badges">
<span class="badge" :class="detail.compiled.status">{{ detail.compiled.status }}</span>
<span v-if="detail.manual" class="badge manual">manual</span>
<span
class="badge"
:class="detail.compiled.status"
:title="statusLabels[detail.compiled.status]"
:aria-label="statusLabels[detail.compiled.status]"
>{{ detail.compiled.status[0] }}</span>
<span
class="badge"
:class="detail.manual ? 'verified' : 'generated'"
:title="detail.manual ? 'Verified' : 'Generated'"
:aria-label="detail.manual ? 'Verified' : 'Generated'"
>{{ detail.manual ? 'V' : 'G' }}</span>
</div>
</div>
@@ -402,23 +424,15 @@ onMounted(() => {
</p>
<p v-else-if="editorError" class="error">{{ editorError }}</p>
<div class="row">
<div class="tabs">
<button type="button" :class="{ active: editorMode === 'text' }" @click="editorMode = 'text'">Text</button>
<button type="button" :class="{ active: editorMode === 'visual' }" @click="editorMode = 'visual'">Visual</button>
</div>
<span class="muted grow">{{ editorMode === 'text' ? 'Pseudocode' : 'Node graph' }}</span>
</div>
<span class="muted">Card source</span>
<textarea
v-if="editorMode === 'text'"
v-model="source"
spellcheck="false"
aria-label="Card implementation"
@keydown.ctrl.s.prevent="save"
@keydown.meta.s.prevent="save"
/>
<CardGraphEditor v-else :key="detail.card.oracle_id" v-model="source" />
<div class="actions">
<button type="button" class="primary" :disabled="saving || !dirty" @click="save">
@@ -439,7 +453,7 @@ onMounted(() => {
</section>
</div>
<PseudoGuide v-else />
<SourceGuide v-else />
</main>
</template>

View File

@@ -74,6 +74,7 @@ interface MatchView {
priority: string
status: string
winner?: string
mulligans?: { player: string; count: number; kept: boolean; bottom: number }[]
stack: { id: string; kind: string; label: string; controller: string }[]
log: string[]
hand: CardView[]
@@ -83,6 +84,7 @@ interface MatchView {
what: string
sourceId: string
sourceName: string
amount?: number
options: string[]
}
pendingSearch?: {
@@ -206,6 +208,15 @@ const myPlaymat = computed(() => {
: { kind: 'upload' as const, url: `${apiBase}/playmats/${encodeURIComponent(playmat.id)}` }
})
const viewerId = computed(() => state.value?.viewerId ?? '')
const mulligan = computed(() => game.value?.status === 'mulligan'
? game.value.mulligans?.find(entry => entry.player === viewerId.value)
: undefined)
const mulliganBottom = computed(() => mulligan.value?.bottom ?? 0)
const mulliganWaiting = computed(() => (game.value?.mulligans ?? [])
.filter(entry => !entry.kept
&& !state.value?.players.find(player => player.id === entry.player)?.lost)
.map(entry => playerName(entry.player))
.join(', '))
const isHost = computed(() => state.value?.hostId === viewerId.value)
const emptySeats = computed(() => state.value ? state.value.maxPlayers - state.value.players.length : 0)
const opponents = computed(() => (state.value?.players ?? []).filter(player => player.id !== viewerId.value && !player.lost))
@@ -262,6 +273,9 @@ const filteredSearchLibrary = computed(() => {
: searchLibrary.value
})
const pendingChoice = computed(() => game.value?.pendingChoice)
const pendingCostLabel = computed(() => pendingChoice.value?.amount === undefined
? 'the cost'
: `${pendingChoice.value.amount} life`)
const choiceFilter = ref('')
const choiceInput = ref<HTMLInputElement | null>(null)
const filteredChoiceOptions = computed(() => {
@@ -601,13 +615,26 @@ async function playLand(card: CardView) {
await act({ type: 'play_land', cardId: card.id })
}
async function keepHand() {
await act({ type: 'keep_hand' })
}
async function takeMulligan() {
await act({ type: 'mulligan' })
}
/** Cards with choices need the cast panel; everything else plays on click. */
function needsCastOptions(card: CardView): boolean {
return Boolean(card.manaCost?.includes('X') || /\btarget|choose (one|two|three)/i.test(card.oracleText ?? ''))
}
async function playCard(card: CardView) {
if (busy.value || !card.playable) return
if (busy.value) return
if (mulliganBottom.value > 0) {
await act({ type: 'mulligan_bottom', cardId: card.id })
return
}
if (!card.playable) return
cancelCast()
if (isLand(card)) {
await playLand(card)
@@ -826,6 +853,11 @@ async function chooseCreatureType(type: string) {
await act({ type: 'choose_type', choice: type })
}
async function chooseCost(pay: boolean) {
if (busy.value) return
await act({ type: 'choose_cost', pay })
}
async function attack() {
const attackers = selectedAttackers.value
.filter(attackerId => attackTargets[attackerId])
@@ -1026,7 +1058,8 @@ onUnmounted(() => {
<header class="game-head">
<div>
<h1>{{ summary ? `${summary.hostName}'s game` : 'Commander game' }}</h1>
<p v-if="game" class="muted">
<p v-if="game?.status === 'mulligan'" class="muted">Opening hands · keep or mulligan</p>
<p v-else-if="game" class="muted">
Turn {{ game.turn }} · {{ phaseLabel }} · priority: {{ priorityName }}
</p>
<p v-else class="muted">{{ state?.status ?? summary?.status ?? 'Loading…' }}</p>
@@ -1360,7 +1393,22 @@ onUnmounted(() => {
</TransitionGroup>
</section>
<section class="hand-panel">
<div v-if="game.status === 'mulligan'" class="mulligan-backdrop" aria-hidden="true" />
<section class="hand-panel" :class="{ 'mulligan-mode': game.status === 'mulligan' }">
<div v-if="mulligan" class="mulligan-bar">
<template v-if="mulligan.kept">
<span class="muted">Hand kept. Waiting for {{ mulliganWaiting || 'the other players' }}.</span>
</template>
<template v-else-if="mulligan.bottom">
<span>Click {{ mulligan.bottom }} card{{ mulligan.bottom === 1 ? '' : 's' }} in your hand to put
{{ mulligan.bottom === 1 ? 'it' : 'them' }} on the bottom of your library.</span>
</template>
<template v-else>
<span>Mulligans: {{ mulligan.count }}.</span>
<button type="button" class="primary" :disabled="busy" @click="keepHand">Keep hand</button>
<button type="button" :disabled="busy" @click="takeMulligan">Mulligan</button>
</template>
</div>
<div class="row wrap hand-head">
<h2>Your hand</h2>
<span class="tag">{{ game.hand.length }}</span>
@@ -1385,14 +1433,16 @@ onUnmounted(() => {
v-for="(card, index) in game.hand"
:key="card.id"
class="hand-card"
:class="{ playable: card.playable, unplayable: !card.playable }"
:class="{ playable: card.playable || mulliganBottom > 0 }"
:style="fanStyle(index, game.hand.length)"
:title="card.playable
? `Click to ${isLand(card) ? 'play' : 'cast'} ${card.name}`
: card.oracleText"
:title="mulliganBottom > 0
? `Put ${card.name} on the bottom of your library`
: card.playable
? `Click to ${isLand(card) ? 'play' : 'cast'} ${card.name}`
: card.oracleText"
role="button"
:tabindex="card.playable ? 0 : -1"
:aria-disabled="!card.playable"
:tabindex="card.playable || mulliganBottom > 0 ? 0 : -1"
:aria-disabled="!card.playable && !mulliganBottom"
@click="playCard(card)"
@keydown.enter.prevent="playCard(card)"
@keydown.space.prevent="playCard(card)"
@@ -1450,9 +1500,12 @@ onUnmounted(() => {
</section>
<section v-if="pendingChoice && pendingChoice.player !== viewerId" class="panel side search-panel">
<h2>Choose a type</h2>
<h2>{{ pendingChoice.what === 'pay_cost' ? 'Pay a cost' : 'Choose a type' }}</h2>
<p class="muted">
{{ playerName(pendingChoice.player) }} is choosing a creature type for {{ pendingChoice.sourceName }}.
{{ playerName(pendingChoice.player) }}
{{ pendingChoice.what === 'pay_cost'
? `is deciding whether to pay ${pendingCostLabel} for ${pendingChoice.sourceName}.`
: `is choosing a creature type for ${pendingChoice.sourceName}.` }}
</p>
</section>
@@ -1535,7 +1588,7 @@ onUnmounted(() => {
</template>
</template>
<div v-if="state?.status === 'active' && game" class="turn-actions">
<div v-if="state?.status === 'active' && game?.status === 'active'" class="turn-actions">
<button
type="button"
class="turn-button"
@@ -1555,30 +1608,49 @@ onUnmounted(() => {
<section class="search-modal" role="dialog" aria-modal="true" aria-labelledby="choice-title">
<header class="search-head">
<div class="grow">
<h2 id="choice-title">Choose a creature type</h2>
<h2 id="choice-title">{{ pendingChoice.what === 'pay_cost' ? `Pay ${pendingCostLabel}?` : 'Choose a creature type' }}</h2>
<p class="muted">{{ pendingChoice.sourceName }} enters.</p>
</div>
<span class="tag">{{ filteredChoiceOptions.length }} types</span>
<span v-if="pendingChoice.what !== 'pay_cost'" class="tag">{{ filteredChoiceOptions.length }} types</span>
</header>
<input
ref="choiceInput"
v-model="choiceFilter"
class="search-filter"
type="search"
placeholder="Search creature types"
autocomplete="off"
>
<p v-if="!filteredChoiceOptions.length" class="muted">No creature types match “{{ choiceFilter }}”.</p>
<div v-else class="choice-grid">
<button
v-for="type in filteredChoiceOptions"
:key="type"
type="button"
class="choice-option"
:disabled="busy"
@click="chooseCreatureType(type)"
>{{ type }}</button>
</div>
<template v-if="pendingChoice.what === 'pay_cost'">
<p class="muted">If you don't, it enters tapped.</p>
<div class="choice-grid">
<button
type="button"
class="choice-option"
:disabled="busy || (pendingChoice.amount !== undefined && (me?.life ?? 0) < pendingChoice.amount)"
@click="chooseCost(true)"
>Pay {{ pendingCostLabel }}</button>
<button
type="button"
class="choice-option"
:disabled="busy"
@click="chooseCost(false)"
>Enter tapped</button>
</div>
</template>
<template v-else>
<input
ref="choiceInput"
v-model="choiceFilter"
class="search-filter"
type="search"
placeholder="Search creature types"
autocomplete="off"
>
<p v-if="!filteredChoiceOptions.length" class="muted">No creature types match “{{ choiceFilter }}”.</p>
<div v-else class="choice-grid">
<button
v-for="type in filteredChoiceOptions"
:key="type"
type="button"
class="choice-option"
:disabled="busy"
@click="chooseCreatureType(type)"
>{{ type }}</button>
</div>
</template>
</section>
</div>
</Teleport>
@@ -2593,6 +2665,13 @@ onUnmounted(() => {
font-size: 0.85rem;
}
.mulligan-backdrop {
position: fixed;
inset: 0;
z-index: 65;
background: rgb(0 0 0 / 82%);
}
.hand-panel {
position: absolute;
bottom: 0;
@@ -2608,12 +2687,37 @@ onUnmounted(() => {
transform: translateX(-50%);
}
.hand-panel.mulligan-mode {
position: fixed;
top: 50%;
bottom: auto;
z-index: 66;
width: min(100%, 60rem);
padding: 0 0.5rem;
transform: translate(-50%, -50%);
}
.hand-head {
justify-content: center;
padding: 0 0.25rem;
pointer-events: auto;
}
.mulligan-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin: 0 0.5rem;
padding: 0.45rem 0.7rem;
border: 1px solid var(--line);
border-radius: 0.5rem;
background: var(--panel);
font-size: 0.9rem;
pointer-events: auto;
}
.hand-head h2 {
font-size: 0.95rem;
white-space: nowrap;
@@ -2675,6 +2779,12 @@ onUnmounted(() => {
cursor: pointer;
}
.hand-card.playable .hand-lift {
outline: 2px solid #58a6ff;
outline-offset: 2px;
border-radius: 8px;
}
.hand-card:hover,
.hand-card:focus-within {
z-index: 30;
@@ -2694,18 +2804,6 @@ onUnmounted(() => {
filter: drop-shadow(0 14px 22px rgb(0 0 0 / 55%));
}
.hand-card.playable:hover .hand-lift,
.hand-card.playable:focus-within .hand-lift {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 8px;
}
.hand-card.unplayable {
filter: grayscale(1);
opacity: 0.45;
}
.hand-options {
position: absolute;
bottom: 0.4em;

View File

@@ -1,846 +0,0 @@
// Line-level model behind the visual card editor. It mirrors the canonical
// formatter output (abilities at column 0, nested calls indented two spaces) so
// editing a node and serializing it back keeps the pseudocode valid.
export interface GraphNode {
id: number
text: string
kind: 'ability' | 'effect' | 'raw'
children: GraphNode[]
}
let nextId = 1
export function nextNodeId(): number {
return nextId++
}
export function makeNode(text: string, kind: GraphNode['kind'], children: GraphNode[] = []): GraphNode {
return { id: nextNodeId(), text, kind, children }
}
export function parseGraph(source: string): GraphNode[] {
const roots: GraphNode[] = []
const stack: Array<{ indent: number; node: GraphNode }> = []
for (const raw of source.split('\n')) {
if (!raw.trim()) continue
const indent = (raw.match(/^[ \t]*/)?.[0] ?? '').replace(/\t/g, ' ').length
const text = raw.trim()
const kind: GraphNode['kind'] =
text.startsWith('#') || text === '(no abilities)' ? 'raw' : indent === 0 ? 'ability' : 'effect'
const node = makeNode(text, kind)
while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop()
if (stack.length) stack[stack.length - 1].node.children.push(node)
else roots.push(node)
stack.push({ indent, node })
}
return roots
}
export function serializeGraph(list: GraphNode[], depth = 0): string {
return list
.map(node => {
const line = ' '.repeat(depth) + node.text
return node.children.length ? `${line}\n${serializeGraph(node.children, depth + 1)}` : line
})
.join('\n')
}
/** Inserted at the top level by the visual editor's "Add ability" menu. */
export const ABILITY_PALETTE = [
{
group: 'Triggered',
items: [
{ label: 'Enters the battlefield', value: 'on enters(this):' },
{ label: 'Dies', value: 'on dies(this):' },
{ label: 'Attacks', value: 'on attacks(this):' },
{ label: 'Upkeep', value: 'on upkeep(you):' },
{ label: 'Cast a spell', value: 'on cast(you, any spell):' },
{ label: 'Deals damage', value: 'on deals_damage(this, any):' },
],
},
{
group: 'Other',
items: [
{ label: 'Activated {T}', value: 'activate {T}:' },
{ label: 'Activated {2}, {T}', value: 'activate {2}, {T}:' },
{ label: 'Static', value: 'static:' },
{ label: 'Static if a condition', value: 'static if it is your turn:' },
{ label: 'Spell effect', value: 'spell:' },
{ label: 'Keyword: Flying', value: 'keyword Flying' },
],
},
]
/** Appended below an ability or nested block. Keep every value parseable. */
export const EFFECT_PALETTE = [
{
group: 'Removal',
items: [
{ label: 'Damage', value: 'damage(target creature, 3)' },
{ label: 'Destroy', value: 'destroy(target creature)' },
{ label: 'Exile', value: 'exile(target permanent)' },
{ label: 'Tap', value: 'tap(target creature)' },
{ label: 'Counter spell', value: 'counter(spell, target spell)' },
{ label: 'Sacrifice', value: 'sacrifice(you, target creature)' },
],
},
{
group: 'Cards and life',
items: [
{ label: 'Draw', value: 'draw(you, 1)' },
{ label: 'Discard', value: 'discard(you, 1)' },
{ label: 'Mill', value: 'mill(you, 1)' },
{ label: 'Scry', value: 'scry(you, 2)' },
{ label: 'Surveil', value: 'surveil(you, 1)' },
{ label: 'Search library', value: 'search(you, creature, 1, to hand, shuffle)' },
{ label: 'Look at top', value: 'look_top(you, 3)' },
{ label: 'Gain life', value: 'gain_life(you, 2)' },
{ label: 'Lose life', value: 'lose_life(opponent, 2)' },
{ label: 'Energy', value: 'energy(you, 2)' },
],
},
{
group: 'Board',
items: [
{ label: 'Create token', value: 'create_token(you, 1, 1/1 white soldier creature)' },
{ label: 'Create copy token', value: 'create_token(you, 1, copy of the triggering object, not legendary)' },
{ label: 'Put counters', value: 'put_counters(target creature, +1/+1, 1)' },
{ label: 'Pump', value: 'pump(target creature, 2/2, until end of turn)' },
{ label: 'Grant keyword', value: 'grant(each creature you control, Flying)' },
{ label: 'Untap', value: 'untap(target permanent you control)' },
{ label: 'Return to hand', value: 'return_to_hand(target creature)' },
{ label: 'Add mana', value: 'add_mana(you, {G})' },
],
},
{
group: 'Flow',
items: [
{ label: 'If condition', value: 'if you control at least 3 artifacts:' },
],
},
]
/** Static abilities accept a different effect vocabulary than triggered/spell ones. */
export const STATIC_EFFECT_PALETTE = [
{
group: 'Static effects',
items: [
{ label: 'Pump', value: 'pump(each creature you control, 1/1)' },
{ label: 'Grant keyword', value: 'grant(each creature you control, Flying)' },
{ label: 'Enters tapped', value: 'enters_tapped(this)' },
{ label: 'Enters with counters', value: 'enters_with_counters(this, +1/+1, 1)' },
{ label: 'Restrict', value: 'restrict(target creature, cant_attack)' },
{ label: 'Set base P/T', value: 'set_pt(target creature, base, 1/1)' },
],
},
]
/** Value nodes that can be wired into argument sockets. */
export const VALUE_PALETTE = [
{
group: 'Players',
items: [
{ label: 'A player', value: 'target player' },
{ label: 'Each opponent', value: 'each opponent' },
{ label: 'Each player', value: 'each player' },
{ label: 'You', value: 'you' },
{ label: 'That player', value: 'that player' },
{ label: 'Its controller', value: 'its controller' },
],
},
{
group: 'Targets',
items: [
{ label: 'A creature', value: 'target creature' },
{ label: 'A permanent', value: 'target permanent' },
{ label: 'An artifact', value: 'target artifact' },
{ label: 'A land', value: 'target land' },
{ label: 'A spell', value: 'target spell' },
{ label: 'An ability', value: 'target ability' },
{ label: 'Any target', value: 'any target' },
{ label: 'This', value: 'this' },
{ label: 'The triggering object', value: 'the triggering object' },
{ label: 'Each creature you control', value: 'each creature you control' },
{ label: 'Each creature an opponent controls', value: 'each creature an opponent controls' },
],
},
{
group: 'Selectors',
items: [
{ label: 'Creature', value: 'creature' },
{ label: 'Artifact', value: 'artifact' },
{ label: 'Enchantment', value: 'enchantment' },
{ label: 'Land', value: 'land' },
{ label: 'Red', value: 'red' },
{ label: 'Creature you control', value: 'creature you control' },
{ label: 'Artifact you control', value: 'artifact you control' },
{ label: 'Tapped creature', value: 'tapped creature' },
{ label: 'Power 4 or greater', value: 'creature with power 4 or greater' },
{ label: 'Nontoken Dragon', value: 'each other nontoken dragon creature you control' },
{ label: 'Nontoken Angel', value: "each nontoken angel you don't control" },
{ label: 'Selector builder', value: '__selector__' },
],
},
{
group: 'Tokens',
items: [
{ label: '1/1 white Soldier', value: '1/1 white soldier creature' },
{ label: '1/1 red Goblin', value: '1/1 red goblin creature' },
{ label: 'Copy of the triggering object', value: 'copy of the triggering object' },
{ label: 'Copy, not legendary', value: 'copy of the triggering object, not legendary' },
],
},
{
group: 'Values',
items: [
{ label: '1', value: '1' },
{ label: '2', value: '2' },
{ label: '3', value: '3' },
{ label: 'X', value: 'X' },
{ label: 'That much', value: 'that much' },
{ label: 'Its power', value: 'its power' },
{ label: 'Its toughness', value: 'its toughness' },
{ label: 'Count creatures you control', value: 'count(creature you control)' },
{ label: 'Cards in your hand', value: 'cards in your hand' },
],
},
{
group: 'Costs',
items: [
{ label: 'Tap', value: '{T}' },
{ label: 'Mana {2}', value: '{2}' },
{ label: 'Pay 2 life', value: 'pay 2 life' },
{ label: 'Sacrifice this', value: 'sacrifice this' },
{ label: 'Discard 1 card(s)', value: 'discard 1 card(s)' },
{ label: 'Mill 1 card(s)', value: 'mill 1 card(s)' },
{ label: 'Remove 1 +1/+1 counter(s)', value: 'remove 1 +1/+1 counter(s) from this' },
],
},
{
group: 'Conditions',
items: [
{ label: 'It is your turn', value: 'it is your turn' },
{ label: 'This is tapped', value: 'this is tapped' },
{ label: 'You control at least 3 artifacts', value: 'you control at least 3 artifacts' },
{ label: 'You have at least 10 life', value: 'you have at least 10 life' },
],
},
{
group: 'Durations',
items: [
{ label: 'Until end of turn', value: 'until end of turn' },
{ label: 'Until your next turn', value: 'until your next turn' },
{ label: 'Until the end of your next turn', value: 'until the end of your next turn' },
{ label: 'While this remains', value: 'for as long as this remains on the battlefield' },
],
},
{
group: 'Logic',
items: [
{ label: 'Selector OR', value: '__or__' },
{ label: 'Selector AND', value: '__and__' },
],
},
]
/** Human labels for effect/ability argument sockets. */
export const ARG_HINTS: Record<string, string[]> = {
damage: ['target', 'amount', 'source'],
damage_divided: ['amount', 'target'],
draw: ['player', 'amount'],
discard: ['player', 'amount'],
mill: ['player', 'amount'],
gain_life: ['player', 'amount'],
lose_life: ['player', 'amount'],
pump: ['target', 'power/toughness', 'duration'],
set_pt: ['target', 'power/toughness', 'duration'],
grant: ['target', 'keyword', 'duration'],
put_counters: ['target', 'counter', 'amount'],
remove_counters: ['target', 'counter', 'amount'],
create_token: ['player', 'amount', 'token', 'options'],
destroy: ['target'],
exile: ['target'],
tap: ['target'],
untap: ['target'],
regenerate: ['target'],
return_to_hand: ['target'],
put_on_top: ['target'],
sacrifice: ['player', 'target'],
counter: ['spell|ability', 'target'],
return_to_battlefield: ['target', 'options'],
scry: ['player', 'amount'],
surveil: ['player', 'amount'],
search: ['player', 'selector', 'amount', 'destination', 'options'],
add_mana: ['player', 'mana'],
fight: ['target', 'target'],
energy: ['player', 'amount'],
attach: ['target'],
restrict: ['target', 'rule'],
prevent_damage: ['target', 'amount', 'duration'],
gain_control: ['target', 'duration'],
look_top: ['player', 'amount', 'options'],
pay: ['cost'],
transform: ['target'],
}
/** Human labels for trigger event arguments. */
const TRIGGER_ARG_HINTS: Record<string, string[]> = {
enters: ['subject'],
dies: ['subject'],
attacks: ['subject'],
blocks: ['subject'],
attacks_or_blocks: ['subject'],
enters_or_attacks: ['subject'],
enters_or_dies: ['subject'],
leaves_battlefield: ['subject'],
deals_damage: ['subject', 'recipient'],
deals_combat_damage: ['subject', 'recipient'],
upkeep: ['player'],
end_step: ['player'],
begin_combat: ['player'],
first_main_phase: ['player'],
postcombat_main_phase: ['player'],
cast: ['player', 'spell'],
becomes_level: ['level'],
draw: ['player'],
counter_placed: ['subject', 'counter'],
becomes_target: ['subject'],
gain_life: ['player'],
lose_life: ['player'],
}
const TRIGGER_SUBJECT_OPTIONS = [
'this',
'each other creature',
'each creature you control',
'each other nontoken dragon creature you control',
"each nontoken angel you don't control",
]
const PLAYER_OPTIONS = ['you', 'target player', 'each opponent', 'each player', 'that player', 'its controller']
const AMOUNT_OPTIONS = ['1', '2', '3', '4', '5', 'X', 'that much', 'count(creature you control)']
const TOKEN_OPTIONS = [
'1/1 white soldier creature',
'1/1 red goblin creature',
'copy of the triggering object',
]
/** Argument slots with fixed choices become dropdowns in the visual editor. */
export const SLOT_OPTIONS: Record<string, string[][]> = {
enters: [TRIGGER_SUBJECT_OPTIONS],
create_token: [PLAYER_OPTIONS, AMOUNT_OPTIONS, TOKEN_OPTIONS, ['not legendary']],
}
/** Splits on `separator` outside parentheses, brackets, braces and quotes. */
export function splitTopLevel(text: string, separator: string): string[] {
const parts: string[] = []
let depth = 0
let quote = false
let escape = false
let start = 0
for (let index = 0; index < text.length; index++) {
const char = text[index]
if (quote) {
if (escape) escape = false
else if (char === '\\') escape = true
else if (char === '"') quote = false
continue
}
if (char === '"') {
quote = true
continue
}
if (char === '(' || char === '[' || char === '{') depth++
else if (char === ')' || char === ']' || char === '}') depth--
else if (depth === 0 && text.startsWith(separator, index)) {
parts.push(text.slice(start, index))
index += separator.length - 1
start = index + 1
}
}
parts.push(text.slice(start))
return parts
}
export function blockOf(text: string): { kind: 'if' | 'choose' | 'schedule'; value: string } | undefined {
const ifMatch = text.match(/^if (.+):$/)
if (ifMatch) return { kind: 'if', value: ifMatch[1] }
const chooseMatch = text.match(/^choose (\d+(?:-\d+)?):$/)
if (chooseMatch) return { kind: 'choose', value: chooseMatch[1] }
const scheduleMatch = text.match(/^schedule\((next_upkeep|next_end_step)\):$/)
if (scheduleMatch) return { kind: 'schedule', value: scheduleMatch[1] }
return undefined
}
/** True for nodes that carry an indented body. Mode lines can nest too. */
export function isBlockText(text: string): boolean {
return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text) || /^\d+\.\s/.test(text)
}
/** Blocks that are invalid without at least one nested effect. */
function requiresBody(text: string): boolean {
return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text)
}
export function abilityRequiresEffects(text: string): boolean {
return /^(?:on |activate |static|spell|chapter )/.test(text)
}
/** Reads a `name(arg, arg)` prefix, leaving any suffix after the closing paren. */
export function readCallPrefix(text: string): { name: string; args: string[]; end: number } | undefined {
const match = text.match(/^([a-z][a-z0-9_]*)\s*\(/)
if (!match) return undefined
const open = match[0].length - 1
let depth = 0
let quote = false
let escape = false
for (let index = open; index < text.length; index++) {
const char = text[index]
if (quote) {
if (escape) escape = false
else if (char === '\\') escape = true
else if (char === '"') quote = false
continue
}
if (char === '"') {
quote = true
continue
}
if (char === '(') depth++
else if (char === ')') {
depth--
if (depth === 0) {
const inner = text.slice(open + 1, index).trim()
return {
name: match[1],
args: inner ? splitTopLevel(inner, ',').map(arg => arg.trim()) : [],
end: index + 1,
}
}
}
}
return undefined
}
/** Reads a complete `name(arg, arg)` call; returns undefined for block headers. */
export function parseCall(text: string): { name: string; args: string[] } | undefined {
const trimmed = text.trim()
const call = readCallPrefix(trimmed)
return call && call.end === trimmed.length ? { name: call.name, args: call.args } : undefined
}
/**
* Splits a supported line into fixed text plus argument slots. Unsupported
* lines return undefined and stay as free text.
*/
export function shapeFromText(text: string): NodeShape | undefined {
if (text.startsWith('on ') && text.endsWith(':')) {
const inner = text.slice(3, -1)
const call = readCallPrefix(inner)
if (call) {
const suffix = inner.slice(call.end)
return {
name: `on ${call.name}`,
head: `on ${call.name}(`,
tail: `)${suffix}:`,
separator: ', ',
slots: call.args.map((arg, index) => {
const options = SLOT_OPTIONS[call.name]?.[index]
return {
label: TRIGGER_ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`,
text: arg,
...(options ? { options } : {}),
}
}),
}
}
}
if (text.startsWith('activate ') && text.endsWith(':')) {
return {
head: 'activate ',
tail: ':',
separator: ', ',
slots: [{ label: 'cost', text: text.slice('activate '.length, -1) }],
}
}
if (text.startsWith('static if ') && text.endsWith(':')) {
return {
head: 'static if ',
tail: ':',
separator: ', ',
slots: [{ label: 'condition', text: text.slice('static if '.length, -1) }],
}
}
const block = blockOf(text)
if (block) {
if (block.kind === 'if') {
return { head: 'if ', tail: ':', separator: ', ', slots: [{ label: 'condition', text: block.value }] }
}
if (block.kind === 'choose') {
return { head: 'choose ', tail: ':', separator: ', ', slots: [{ label: 'modes', text: block.value }] }
}
return { head: 'schedule(', tail: '):', separator: ', ', slots: [{ label: 'when', text: block.value }] }
}
const call = parseCall(text)
if (call) {
return {
head: `${call.name}(`,
tail: ')',
separator: ', ',
slots: call.args.map((arg, index) => {
const options = SLOT_OPTIONS[call.name]?.[index]
return {
label: ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`,
text: arg,
...(options ? { options } : {}),
}
}),
}
}
return undefined
}
/**
* Rebuilds every shaped line from its slots and connected value nodes. Value
* nodes are evaluated recursively, so `or`/`and` combinators can nest.
*/
export function syncTexts(model: GraphModel): void {
const byId = new Map(model.nodes.map(node => [node.id, node]))
const valueEdges = new Map<string, number>()
for (const edge of model.edges) {
if (edge.port === 'value' && edge.slot !== undefined) {
valueEdges.set(`${edge.to}:${edge.slot}`, edge.from)
}
}
function renderSlot(node: CanvasNode, index: number, stack: Set<number>): string {
const childId = valueEdges.get(`${node.id}:${index}`)
const child = childId !== undefined ? byId.get(childId) : undefined
return child ? render(child, stack) : node.shape?.slots[index]?.text ?? ''
}
function render(node: CanvasNode | undefined, stack: Set<number>): string {
if (!node) return ''
if (stack.has(node.id)) return node.kind === 'value' ? node.literal ?? '' : ''
stack.add(node.id)
let text: string
if (node.kind === 'value' && node.combine) {
text = `${renderSlot(node, 0, stack)} ${node.combine} ${renderSlot(node, 1, stack)}`
} else if (node.shape) {
text = node.shape.head
+ node.shape.slots.map((_, index) => renderSlot(node, index, stack)).join(node.shape.separator)
+ node.shape.tail
} else if (node.kind === 'value') {
text = node.literal ?? node.text
} else {
text = node.text
}
stack.delete(node.id)
node.text = text
return text
}
for (const node of model.nodes) render(node, new Set())
}
// ---------------------------------------------------------------------------
// Node canvas. The tree above is converted into flat nodes with explicit
// `next` (sibling) and `body` (indented) links. Source is regenerated by
// following those links, so the canvas and the pseudocode stay in sync.
// ---------------------------------------------------------------------------
export interface NodeSlot {
label: string
text: string
/** Fixed choices rendered as a dropdown instead of a free-text input. */
options?: string[]
}
/** A line split into a fixed shell and the slots a value node can fill. */
export interface NodeShape {
name?: string
head: string
tail: string
separator: string
slots: NodeSlot[]
}
export interface CanvasNode {
id: number
text: string
kind: 'ability' | 'effect' | 'raw' | 'value'
x: number
y: number
shape?: NodeShape
/** Value nodes: literal source text. */
literal?: string
/** Value nodes: combines its two slots instead of using a literal. */
combine?: 'or' | 'and'
valueLabel?: string
}
export type GraphPort = 'next' | 'body' | 'value'
export interface GraphEdge {
id: number
from: number
port: GraphPort
to: number
/** Target argument index when port is 'value'. */
slot?: number
}
export interface GraphModel {
nodes: CanvasNode[]
edges: GraphEdge[]
}
export interface GraphSource {
source: string
unlinked: number
problems: string[]
}
export const NODE_WIDTH = 230
const CHAIN_GAP = 70
const BODY_INDENT = NODE_WIDTH + 20
const BODY_GAP = 70
const ROOT_GAP = 70
let nextEdgeId = 1
export function estimateNodeHeight(text: string, slots?: number, hasName?: boolean): number {
const count = slots ?? parseCall(text)?.args.length ?? 0
if (!count) return hasName ? 84 : 74
return 64 + count * 48 + (hasName ? 24 : 0)
}
export function hasBodyPort(model: GraphModel, node: CanvasNode): boolean {
return node.kind === 'effect'
&& (isBlockText(node.text) || model.edges.some(edge => edge.from === node.id && edge.port === 'body'))
}
/** Converts pseudocode into nodes and links, laid out roughly left to right. */
export function graphFromSource(source: string): GraphModel {
const model: GraphModel = { nodes: [], edges: [] }
let y = 40
for (const root of parseGraph(source)) {
if (root.kind === 'raw') {
model.nodes.push({ id: root.id, text: root.text, kind: 'raw', x: 40, y })
y += 64
continue
}
const bounds = layoutTreeChain(model, [root], 40, y, 0)
y += bounds.height + ROOT_GAP
}
return model
}
function layoutTreeChain(
model: GraphModel,
list: GraphNode[],
x: number,
y: number,
depth: number,
): { width: number; height: number } {
let cursorX = x
let maxHeight = 0
let previous: number | undefined
for (const treeNode of list) {
const kind: CanvasNode['kind'] = depth === 0 ? treeNode.kind : 'effect'
const node: CanvasNode = {
id: treeNode.id,
text: treeNode.text,
kind,
x: cursorX,
y,
shape: shapeFromText(treeNode.text),
}
model.nodes.push(node)
if (previous !== undefined) {
model.edges.push({ id: nextEdgeId++, from: previous, port: 'next', to: node.id })
}
previous = node.id
const height = estimateNodeHeight(node.text, node.shape?.slots.length, Boolean(node.shape?.name))
let totalHeight = height
let advance = NODE_WIDTH
if (treeNode.children.length) {
if (depth === 0) {
// An ability's output is its effect chain, laid out to the right.
const chain = layoutTreeChain(model, treeNode.children, cursorX + NODE_WIDTH + CHAIN_GAP, y, 1)
model.edges.push({ id: nextEdgeId++, from: node.id, port: 'next', to: treeNode.children[0].id })
totalHeight = Math.max(totalHeight, chain.height)
advance = NODE_WIDTH + CHAIN_GAP + chain.width
} else {
// Blocks own an indented body below and just right of their socket.
const body = layoutTreeChain(model, treeNode.children, cursorX + BODY_INDENT, y + height + BODY_GAP, depth + 1)
model.edges.push({ id: nextEdgeId++, from: node.id, port: 'body', to: treeNode.children[0].id })
totalHeight = Math.max(totalHeight, height + BODY_GAP + body.height)
}
}
maxHeight = Math.max(maxHeight, totalHeight)
cursorX += advance + CHAIN_GAP
}
return { width: cursorX - x, height: maxHeight }
}
/** Rebuilds pseudocode by walking next/body links from every ability root. */
export function sourceFromGraph(model: GraphModel): GraphSource {
syncTexts(model)
const byId = new Map(model.nodes.map(node => [node.id, node]))
const outgoing = new Map<string, GraphEdge>()
for (const edge of model.edges) {
outgoing.set(`${edge.from}:${edge.port}`, edge)
}
const lines: string[] = []
const visited = new Set<number>()
const problems: string[] = []
const label = (text: string) => (text.length > 52 ? `${text.slice(0, 49)}…` : text)
const checkModes = (startId: number) => {
let mode = byId.get(startId)
let expected = 1
const seenModes = new Set<number>()
while (mode && !seenModes.has(mode.id)) {
seenModes.add(mode.id)
const number = mode.text.match(/^(\d+)\.\s/)
if (!number || Number(number[1]) !== expected) {
problems.push('A choose body must be numbered 1, 2, 3…')
return
}
expected++
const next = outgoing.get(`${mode.id}:next`)
mode = next ? byId.get(next.to) : undefined
}
}
const emitChain = (startId: number, depth: number) => {
let current: number | undefined = startId
while (current !== undefined) {
if (visited.has(current)) {
problems.push(`Cycle at ${label(byId.get(current)?.text ?? 'node')}`)
return
}
const node = byId.get(current)
if (!node) return
visited.add(current)
lines.push(`${' '.repeat(depth)}${node.text}`)
const body = outgoing.get(`${current}:body`)
if (body) {
if (blockOf(node.text)?.kind === 'choose') checkModes(body.to)
emitChain(body.to, depth + 1)
} else if (requiresBody(node.text)) {
problems.push(`"${label(node.text)}" has no body`)
}
current = outgoing.get(`${current}:next`)?.to
}
}
for (const node of model.nodes) {
if (node.kind === 'raw') {
if (!visited.has(node.id)) {
visited.add(node.id)
lines.push(node.text)
}
continue
}
if (node.kind !== 'ability' || visited.has(node.id)) continue
visited.add(node.id)
lines.push(node.text)
const next = outgoing.get(`${node.id}:next`)
if (next) emitChain(next.to, 1)
else if (abilityRequiresEffects(node.text)) problems.push(`"${label(node.text)}" has no effects`)
}
const usedValues = new Set(model.edges.filter(edge => edge.port === 'value').map(edge => edge.from))
const unlinked = model.nodes.filter(node =>
(node.kind === 'effect' && !visited.has(node.id))
|| (node.kind === 'value' && !usedValues.has(node.id)),
).length
if (unlinked) {
problems.push(`${unlinked} unconnected node${unlinked === 1 ? '' : 's'} will be ignored`)
}
return { source: lines.join('\n'), unlinked, problems }
}
function reaches(model: GraphModel, start: number, target: number): boolean {
const stack = [start]
const seen = new Set<number>()
while (stack.length) {
const id = stack.pop()!
if (id === target) return true
if (seen.has(id)) continue
seen.add(id)
for (const edge of model.edges) {
if (edge.from === id) stack.push(edge.to)
}
}
return false
}
/** Links an output socket to a node input or an argument slot. */
export function connectNodes(
model: GraphModel,
from: number,
port: GraphPort,
to: number,
slot?: number,
): boolean {
if (from === to) return false
const source = model.nodes.find(node => node.id === from)
const target = model.nodes.find(node => node.id === to)
if (!source || !target) return false
if (port === 'value') {
if (source.kind !== 'value' || !target.shape || slot === undefined || !target.shape.slots[slot]) {
return false
}
} else {
if (target.kind !== 'effect') return false
if (port === 'body' && !hasBodyPort(model, source)) return false
}
if (reaches(model, to, from)) return false
if (port === 'value') {
model.edges = model.edges.filter(edge =>
!(edge.port === 'value' && edge.to === to && edge.slot === slot)
&& !(edge.from === from && edge.port === 'value'),
)
model.edges.push({ id: nextEdgeId++, from, port, to, slot })
} else {
model.edges = model.edges.filter(edge =>
!((edge.port === 'next' || edge.port === 'body') && edge.to === to)
&& !(edge.from === from && edge.port === port),
)
model.edges.push({ id: nextEdgeId++, from, port, to })
}
return true
}

View File

@@ -1,215 +0,0 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
connectNodes,
graphFromSource,
nextNodeId,
parseCall,
parseGraph,
serializeGraph,
shapeFromText,
sourceFromGraph,
syncTexts,
} from '../app/utils/cardGraph.ts'
import type { GraphModel } from '../app/utils/cardGraph.ts'
const SOURCE = `# Soul Warden [supported]
on enters(each other creature):
gain_life(you, 1)
on upkeep(you):
if you control at least 3 artifacts:
draw(you, 1)
create_token(you, 1, 1/1 white soldier creature)`
test('parseGraph builds ability and nested effect nodes', () => {
const roots = parseGraph(SOURCE)
assert.equal(roots.length, 3)
assert.equal(roots[0].kind, 'raw')
assert.equal(roots[1].kind, 'ability')
assert.equal(roots[1].text, 'on enters(each other creature):')
assert.deepEqual(roots[1].children.map(node => node.text), ['gain_life(you, 1)'])
const upkeep = roots[2]
assert.equal(upkeep.children[0].text, 'if you control at least 3 artifacts:')
assert.deepEqual(upkeep.children[0].children.map(node => node.text), ['draw(you, 1)'])
assert.equal(upkeep.children[1].text, 'create_token(you, 1, 1/1 white soldier creature)')
})
test('serializeGraph round-trips formatter output and normalizes indentation', () => {
assert.equal(serializeGraph(parseGraph(SOURCE)), SOURCE.replace('\n\n', '\n'))
assert.equal(
serializeGraph(parseGraph('on dies(this):\n draw(you, 1)')),
'on dies(this):\n draw(you, 1)',
)
})
test('graph conversion round-trips abilities, chains and nested bodies', () => {
const model = graphFromSource(SOURCE)
const result = sourceFromGraph(model)
assert.equal(result.source, SOURCE.replace('\n\n', '\n'))
assert.equal(result.unlinked, 0)
assert.deepEqual(result.problems, [])
})
test('connectNodes replaces an input link and rejects cycles', () => {
const model = graphFromSource(SOURCE)
const ability = model.nodes.find(node => node.kind === 'ability' && node.text.startsWith('on enters'))
const first = model.nodes.find(node => node.text === 'gain_life(you, 1)')
const second = model.nodes.find(node => node.text === 'create_token(you, 1, 1/1 white soldier creature)')
assert.ok(ability && first && second)
assert.equal(connectNodes(model, ability.id, 'next', second.id), true)
assert.equal(sourceFromGraph(model).unlinked, 1)
assert.equal(connectNodes(model, first.id, 'next', second.id), true)
assert.equal(connectNodes(model, second.id, 'next', first.id), false)
})
test('shapeFromText exposes trigger and effect arguments', () => {
const trigger = shapeFromText('on attacks(this):')
assert.equal(trigger?.name, 'on attacks')
assert.deepEqual(trigger?.slots, [{ label: 'subject', text: 'this' }])
const damage = shapeFromText('damage(target creature, 3)')
assert.deepEqual(damage?.slots.map(slot => slot.label), ['target', 'amount'])
})
test('shapeFromText adds dropdown choices for constant slots', () => {
const enters = shapeFromText('on enters(each other nontoken dragon creature you control):')
assert.deepEqual(enters?.slots[0]?.options, [
'this',
'each other creature',
'each creature you control',
'each other nontoken dragon creature you control',
"each nontoken angel you don't control",
])
const copy = shapeFromText("create_token(you, 1, copy of the triggering object, not legendary)")
assert.deepEqual(copy?.slots.map(slot => slot.label), ['player', 'amount', 'token', 'options'])
assert.ok(copy?.slots[2]?.options?.includes('copy of the triggering object'))
assert.deepEqual(copy?.slots[3]?.options, ['not legendary'])
})
test('value nodes fill trigger and effect argument sockets', () => {
const model = graphFromSource(`# Test [supported]
on attacks(this):
damage(target creature, 3)`)
const trigger = model.nodes.find(node => node.kind === 'ability')
const damage = model.nodes.find(node => node.text.startsWith('damage('))
assert.ok(trigger && damage)
const player = {
id: nextNodeId(),
kind: 'value' as const,
text: 'target player',
literal: 'target player',
valueLabel: 'Players',
x: 0,
y: 0,
}
model.nodes.push(player)
assert.equal(connectNodes(model, player.id, 'value', trigger.id, 0), true)
const artifact = {
id: nextNodeId(),
kind: 'value' as const,
text: 'target artifact',
literal: 'target artifact',
valueLabel: 'Targets',
x: 0,
y: 0,
}
model.nodes.push(artifact)
assert.equal(connectNodes(model, artifact.id, 'value', damage.id, 0), true)
assert.equal(sourceFromGraph(model).source, `# Test [supported]
on attacks(target player):
damage(target artifact, 3)`)
})
test('or and and value nodes combine selector slots', () => {
const model = graphFromSource(`# Test [supported]
spell:
search(you, creature, 1, to hand, shuffle)`)
const search = model.nodes.find(node => node.text.startsWith('search('))
assert.ok(search)
const combo: GraphModel['nodes'][number] = {
id: nextNodeId(),
kind: 'value',
text: '',
combine: 'or',
valueLabel: 'Logic',
x: 0,
y: 0,
shape: {
head: '',
tail: '',
separator: ' or ',
slots: [
{ label: 'left', text: 'creature' },
{ label: 'right', text: 'artifact' },
],
},
}
model.nodes.push(combo)
assert.equal(connectNodes(model, combo.id, 'value', search.id, 1), true)
assert.match(sourceFromGraph(model).source, /search\(you, creature or artifact, 1, to hand, shuffle\)/)
syncTexts(model)
assert.equal(combo.text, 'creature or artifact')
combo.combine = 'and'
combo.shape!.slots[0].text = 'red'
combo.shape!.slots[1].text = 'creature'
syncTexts(model)
assert.equal(combo.text, 'red and creature')
})
test('structured selector value nodes render their slots', () => {
const model = graphFromSource(`# Test [supported]
on enters(this):`)
const trigger = model.nodes.find(node => node.kind === 'ability')
assert.ok(trigger)
const selector: GraphModel['nodes'][number] = {
id: nextNodeId(),
kind: 'value',
text: '',
valueLabel: 'Selector',
x: 0,
y: 0,
shape: {
head: '',
tail: '',
separator: ' ',
slots: [
{ label: 'prefix', text: 'each' },
{ label: 'state', text: 'nontoken' },
{ label: 'type', text: 'angel' },
{ label: 'controller', text: "you don't control" },
],
},
}
model.nodes.push(selector)
assert.equal(connectNodes(model, selector.id, 'value', trigger.id, 0), true)
syncTexts(model)
assert.equal(selector.text, "each nontoken angel you don't control")
assert.equal(sourceFromGraph(model).source, `# Test [supported]
on enters(each nontoken angel you don't control):`)
})
test('parseCall splits arguments outside nested groups', () => {
assert.deepEqual(parseCall('draw(you, 1)'), { name: 'draw', args: ['you', '1'] })
assert.deepEqual(parseCall('proliferate()'), { name: 'proliferate', args: [] })
assert.deepEqual(parseCall('damage(divided(any number, creature), 3)'), {
name: 'damage',
args: ['divided(any number, creature)', '3'],
})
assert.equal(parseCall('if you control at least 3 artifacts:'), undefined)
})