First commit
This commit is contained in:
6
frontend/.dockerignore
Normal file
6
frontend/.dockerignore
Normal file
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
.nuxt
|
||||
.output
|
||||
.env
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
24
frontend/.gitignore
vendored
Normal file
24
frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Nuxt dev/build outputs
|
||||
.output
|
||||
.data
|
||||
.nuxt
|
||||
.nitro
|
||||
.cache
|
||||
dist
|
||||
|
||||
# Node dependencies
|
||||
node_modules
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
.fleet
|
||||
.idea
|
||||
|
||||
# Local env files
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
22
frontend/Dockerfile
Normal file
22
frontend/Dockerfile
Normal file
@@ -0,0 +1,22 @@
|
||||
FROM node:24-alpine AS base
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM base AS dev
|
||||
COPY . .
|
||||
EXPOSE 3000
|
||||
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0"]
|
||||
|
||||
FROM base AS build
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:24-alpine AS production
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=3000
|
||||
COPY --from=build /app/.output ./.output
|
||||
EXPOSE 3000
|
||||
CMD ["node", ".output/server/index.mjs"]
|
||||
71
frontend/app/app.vue
Normal file
71
frontend/app/app.vue
Normal file
@@ -0,0 +1,71 @@
|
||||
<script setup lang="ts">
|
||||
import { AUTH_CHANGED, authToken } from '~/utils/auth'
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const route = useRoute()
|
||||
const SESSION_PREFIX = 'commander-session-'
|
||||
|
||||
const authCookie = useCookie('commander-auth-token')
|
||||
const signedIn = ref(Boolean(authCookie.value))
|
||||
|
||||
const seatedGames = ref<{ id: string; label: string }[]>([])
|
||||
let poll: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
function syncAuth() {
|
||||
signedIn.value = Boolean(authToken())
|
||||
}
|
||||
|
||||
function seatedGameIds(): string[] {
|
||||
return Object.keys(sessionStorage)
|
||||
.filter(key => key.startsWith(SESSION_PREFIX))
|
||||
.map(key => key.slice(SESSION_PREFIX.length))
|
||||
}
|
||||
|
||||
async function refreshSeatedGames() {
|
||||
const ids = seatedGameIds()
|
||||
const known = ids.length === seatedGames.value.length && ids.every(id => seatedGames.value.some(game => game.id === id))
|
||||
if (known) return
|
||||
if (!ids.length) {
|
||||
seatedGames.value = []
|
||||
return
|
||||
}
|
||||
try {
|
||||
const { games } = await $fetch<{ games: { id: string; hostName: string }[] }>(`${apiBase}/games`)
|
||||
seatedGames.value = ids.flatMap(id => {
|
||||
const game = games.find(entry => entry.id === id)
|
||||
return game ? [{ id, label: `${game.hostName}'s game` }] : []
|
||||
})
|
||||
} catch {
|
||||
// Keep the current tabs when the game list is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
syncAuth()
|
||||
window.addEventListener(AUTH_CHANGED, syncAuth)
|
||||
void refreshSeatedGames()
|
||||
poll = setInterval(refreshSeatedGames, 5000)
|
||||
})
|
||||
watch(() => route.fullPath, refreshSeatedGames)
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener(AUTH_CHANGED, syncAuth)
|
||||
if (poll) clearInterval(poll)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NuxtRouteAnnouncer />
|
||||
<nav v-if="signedIn" class="app-nav">
|
||||
<strong>Commander</strong>
|
||||
<NuxtLink to="/">Play</NuxtLink>
|
||||
<NuxtLink to="/decks">Decks</NuxtLink>
|
||||
<NuxtLink to="/cards">Cards</NuxtLink>
|
||||
<NuxtLink to="/account">Account</NuxtLink>
|
||||
<div v-if="seatedGames.length" class="nav-games">
|
||||
<NuxtLink v-for="game in seatedGames" :key="game.id" :to="`/games/${game.id}`">
|
||||
{{ game.label }}
|
||||
</NuxtLink>
|
||||
</div>
|
||||
</nav>
|
||||
<NuxtPage />
|
||||
</template>
|
||||
411
frontend/app/assets/main.css
Normal file
411
frontend/app/assets/main.css
Normal file
@@ -0,0 +1,411 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #0f1117;
|
||||
--panel: #171a23;
|
||||
--panel-2: #11151d;
|
||||
--line: #2a2f3d;
|
||||
--text: #e8e6e3;
|
||||
--muted: #9aa2b1;
|
||||
--accent: #7aa2f7;
|
||||
--ok: #7dd3a0;
|
||||
--warn: #e8c07d;
|
||||
--bad: #e07a7a;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#__nuxt {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: system-ui, sans-serif;
|
||||
}
|
||||
|
||||
h1, h2, h3, p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.app-nav {
|
||||
height: 3rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 0 1.25rem;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: #12151d;
|
||||
}
|
||||
|
||||
.app-nav strong {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.app-nav a {
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
padding: 0.25rem 0;
|
||||
}
|
||||
|
||||
.app-nav a.router-link-active {
|
||||
color: var(--text);
|
||||
border-bottom: 2px solid var(--accent);
|
||||
}
|
||||
|
||||
.nav-games {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-left: auto;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.nav-games a {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.head-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
padding: 0.3rem 0.6rem;
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.tabs button.active {
|
||||
color: var(--text);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
main.fill-page {
|
||||
height: calc(100vh - 3rem);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 1rem 1.25rem;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
main.page {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
main > header {
|
||||
display: flex;
|
||||
align-items: start;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--bad);
|
||||
font-size: 0.85rem;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.ok {
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.warn {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(18rem, 26rem) 1fr;
|
||||
gap: 1rem;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.list-panel,
|
||||
.detail-panel,
|
||||
.panel {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 0.85rem;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.search {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.filters select {
|
||||
flex: 1 1 8rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
input, select, textarea, button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 0.45rem 0.6rem;
|
||||
}
|
||||
|
||||
input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
button:not(:disabled):hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
button.primary {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
button.danger {
|
||||
border-color: var(--bad);
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.card-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.detail-head {
|
||||
display: flex;
|
||||
align-items: start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.card-row {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
text-align: left;
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
padding: 0.45rem 0.5rem;
|
||||
}
|
||||
|
||||
.card-row.selected {
|
||||
background: #202636;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.card-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.card-main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.card-main .card-name {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.badges {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
border-radius: 99px;
|
||||
padding: 0.1rem 0.45rem;
|
||||
border: 1px solid currentColor;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.badge.supported {
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.badge.partial {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.badge.unsupported {
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.badge.manual {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.pager {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.oracle {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
border-left: 2px solid var(--line);
|
||||
padding-left: 0.75rem;
|
||||
font-size: 0.9rem;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
textarea {
|
||||
min-height: 12rem;
|
||||
resize: vertical;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.saved-at {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.wrap {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.grow {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.tag {
|
||||
font-size: 0.75rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 99px;
|
||||
padding: 0.1rem 0.45rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.tag.good {
|
||||
color: var(--ok);
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
.tag.bad {
|
||||
color: var(--bad);
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
main.fill-page {
|
||||
height: auto;
|
||||
min-height: calc(100vh - 3rem);
|
||||
}
|
||||
|
||||
.layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.list {
|
||||
max-height: 40vh;
|
||||
}
|
||||
|
||||
.detail-panel {
|
||||
min-height: 60vh;
|
||||
}
|
||||
}
|
||||
1094
frontend/app/components/CardGraphEditor.vue
Normal file
1094
frontend/app/components/CardGraphEditor.vue
Normal file
File diff suppressed because it is too large
Load Diff
77
frontend/app/components/CardHover.vue
Normal file
77
frontend/app/components/CardHover.vue
Normal file
@@ -0,0 +1,77 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{ oracleId: string; name: string }>()
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
|
||||
const PREVIEW_WIDTH = 244
|
||||
const PREVIEW_HEIGHT = 340
|
||||
|
||||
const visible = ref(false)
|
||||
const failed = ref(false)
|
||||
const left = ref(0)
|
||||
const top = ref(0)
|
||||
|
||||
const src = computed(() => `${apiBase}/cards/${encodeURIComponent(props.oracleId)}/image`)
|
||||
|
||||
function follow(event: MouseEvent) {
|
||||
left.value = Math.max(8, Math.min(
|
||||
event.clientX + 20,
|
||||
window.innerWidth - PREVIEW_WIDTH - 8,
|
||||
))
|
||||
top.value = Math.max(8, Math.min(
|
||||
event.clientY - PREVIEW_HEIGHT / 2,
|
||||
window.innerHeight - PREVIEW_HEIGHT - 8,
|
||||
))
|
||||
}
|
||||
|
||||
function enter(event: MouseEvent) {
|
||||
failed.value = false
|
||||
follow(event)
|
||||
visible.value = true
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
class="card-hover"
|
||||
@mouseenter="enter"
|
||||
@mousemove="follow"
|
||||
@mouseleave="visible = false"
|
||||
@pointerdown="visible = false"
|
||||
>
|
||||
<slot />
|
||||
<Teleport to="body">
|
||||
<img
|
||||
v-if="visible && !failed"
|
||||
class="card-art"
|
||||
:src="src"
|
||||
:alt="`${name} card art`"
|
||||
:style="{ left: `${left}px`, top: `${top}px` }"
|
||||
@error="failed = true"
|
||||
>
|
||||
</Teleport>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.card-hover {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.card-art {
|
||||
position: fixed;
|
||||
z-index: 100;
|
||||
width: 244px;
|
||||
height: auto;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.55);
|
||||
pointer-events: none;
|
||||
animation: card-art-in 140ms ease-out;
|
||||
}
|
||||
|
||||
@keyframes card-art-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.96);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
98
frontend/app/components/GameCard.vue
Normal file
98
frontend/app/components/GameCard.vue
Normal file
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
oracleId: string
|
||||
name: string
|
||||
tapped?: boolean
|
||||
}>()
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
|
||||
const failed = ref(false)
|
||||
const src = computed(() => `${apiBase}/cards/${encodeURIComponent(props.oracleId)}/image`)
|
||||
const token = computed(() => props.oracleId.startsWith('token:'))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="game-card" :class="{ tapped, token }">
|
||||
<div class="card-face">
|
||||
<img
|
||||
v-if="!failed && !token"
|
||||
:src="src"
|
||||
:alt="name"
|
||||
loading="lazy"
|
||||
draggable="false"
|
||||
@error="failed = true"
|
||||
>
|
||||
<div v-else class="card-fallback">
|
||||
<span class="fallback-name">{{ name }}</span>
|
||||
<span v-if="token" class="fallback-kind">Token</span>
|
||||
</div>
|
||||
</div>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.game-card {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 488 / 680;
|
||||
}
|
||||
|
||||
.game-card.tapped {
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.card-face {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
transform-origin: center;
|
||||
transition: transform 150ms ease;
|
||||
}
|
||||
|
||||
.game-card.tapped .card-face {
|
||||
transform: rotate(90deg) scale(0.7);
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 6px;
|
||||
object-fit: cover;
|
||||
background: #0b0d12;
|
||||
box-shadow: 0 3px 10px rgb(0 0 0 / 45%);
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.card-fallback {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0.6rem;
|
||||
border: 1px solid #5b563f;
|
||||
border-radius: 6px;
|
||||
background:
|
||||
radial-gradient(circle at 50% 30%, rgb(232 192 125 / 14%), transparent 70%),
|
||||
#1d211b;
|
||||
box-shadow: 0 3px 10px rgb(0 0 0 / 45%);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.fallback-name {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.fallback-kind {
|
||||
font-size: 0.6rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--muted);
|
||||
}
|
||||
</style>
|
||||
54
frontend/app/components/ManaCost.vue
Normal file
54
frontend/app/components/ManaCost.vue
Normal file
@@ -0,0 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{ cost?: string }>()
|
||||
|
||||
const groups = computed(() => (props.cost ?? '')
|
||||
.split('//')
|
||||
.map(group => group.match(/\{([^}]+)\}/g)?.map(token => token.slice(1, -1)) ?? [])
|
||||
.filter(group => group.length > 0))
|
||||
|
||||
/** mana-font names a few symbols differently from Scryfall's code. */
|
||||
const ALIASES: Record<string, string> = { T: 'tap', Q: 'untap', '∞': 'infinity' }
|
||||
|
||||
function classOf(symbol: string): string {
|
||||
return ALIASES[symbol.toUpperCase()] ?? symbol.replaceAll('/', '').toLowerCase()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
v-if="groups.length"
|
||||
class="mana-cost"
|
||||
role="img"
|
||||
:aria-label="`Mana cost ${cost}`"
|
||||
>
|
||||
<template v-for="(group, groupIndex) in groups" :key="groupIndex">
|
||||
<span v-if="groupIndex" class="mana-separator" aria-hidden="true">//</span>
|
||||
<i
|
||||
v-for="(symbol, index) in group"
|
||||
:key="`${symbol}-${index}`"
|
||||
class="ms ms-cost mana-symbol"
|
||||
:class="`ms-${classOf(symbol)}`"
|
||||
:title="`{${symbol}}`"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</template>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.mana-cost {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.mana-symbol {
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
|
||||
.mana-separator {
|
||||
color: var(--muted);
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
</style>
|
||||
199
frontend/app/components/PlaymatPicker.vue
Normal file
199
frontend/app/components/PlaymatPicker.vue
Normal file
@@ -0,0 +1,199 @@
|
||||
<script setup lang="ts">
|
||||
import type { PlaymatSelection } from '~/utils/playmat'
|
||||
import { resizeImage } from '~/utils/image'
|
||||
|
||||
interface CardSummary {
|
||||
oracle_id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
current?: { kind: 'card'; oracleId: string } | { kind: 'upload'; url: string } | null
|
||||
busy?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ select: [selection: PlaymatSelection] }>()
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
|
||||
const query = ref('')
|
||||
const results = ref<CardSummary[]>([])
|
||||
const searching = ref(false)
|
||||
const localError = ref('')
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const previewUrl = computed(() => {
|
||||
const current = props.current
|
||||
if (!current) return undefined
|
||||
return current.kind === 'card'
|
||||
? `${apiBase}/cards/${encodeURIComponent(current.oracleId)}/art`
|
||||
: current.url
|
||||
})
|
||||
|
||||
async function search() {
|
||||
const term = query.value.trim()
|
||||
if (term.length < 2) {
|
||||
results.value = []
|
||||
searching.value = false
|
||||
return
|
||||
}
|
||||
searching.value = true
|
||||
try {
|
||||
const data = await $fetch<{ cards: CardSummary[] }>(`${apiBase}/cards`, {
|
||||
query: { q: term, limit: 24 },
|
||||
})
|
||||
if (query.value.trim() === term) results.value = data.cards
|
||||
} catch {
|
||||
if (query.value.trim() === term) results.value = []
|
||||
} finally {
|
||||
if (query.value.trim() === term) searching.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(query, () => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(search, 300)
|
||||
})
|
||||
|
||||
onUnmounted(() => clearTimeout(searchTimer))
|
||||
|
||||
function choose(card: CardSummary) {
|
||||
results.value = []
|
||||
query.value = ''
|
||||
emit('select', { kind: 'card', oracleId: card.oracle_id })
|
||||
}
|
||||
|
||||
/** The API caps uploaded JPEG playmats at 3 MB, so shrink large images first. */
|
||||
async function upload(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = ''
|
||||
if (!file) return
|
||||
localError.value = ''
|
||||
if (!file.type.startsWith('image/')) {
|
||||
localError.value = 'Choose an image file.'
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await resizeImage(file, 1920)
|
||||
if (data.length > 4_000_000) {
|
||||
localError.value = 'That image is too large. Try a smaller one.'
|
||||
return
|
||||
}
|
||||
emit('select', { kind: 'upload', data })
|
||||
} catch {
|
||||
localError.value = 'Could not read that image.'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="playmat-picker">
|
||||
<div
|
||||
class="preview"
|
||||
role="img"
|
||||
:aria-label="previewUrl ? 'Current playmat' : 'No playmat selected'"
|
||||
:style="previewUrl ? { backgroundImage: `url('${previewUrl}')` } : undefined"
|
||||
>
|
||||
<span v-if="!previewUrl" class="muted">No playmat</span>
|
||||
</div>
|
||||
<input
|
||||
v-model="query"
|
||||
type="search"
|
||||
placeholder="Search Magic art…"
|
||||
aria-label="Search Magic art"
|
||||
>
|
||||
<p v-if="busy || searching" class="muted">Working…</p>
|
||||
<p v-else-if="query.trim().length >= 2 && !results.length" class="muted">No cards found.</p>
|
||||
<div v-if="results.length" class="results">
|
||||
<button
|
||||
v-for="card in results"
|
||||
:key="card.oracle_id"
|
||||
type="button"
|
||||
:disabled="busy"
|
||||
:title="`Use ${card.name} as your playmat`"
|
||||
@click="choose(card)"
|
||||
>
|
||||
<img :src="`${apiBase}/cards/${card.oracle_id}/art`" :alt="card.name" loading="lazy">
|
||||
<span>{{ card.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<label class="field">
|
||||
<span class="muted">Upload an image</span>
|
||||
<input type="file" accept="image/*" :disabled="busy" @change="upload">
|
||||
</label>
|
||||
<p v-if="localError" class="error">{{ localError }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="remove"
|
||||
:disabled="busy || !current"
|
||||
@click="emit('select', { kind: 'none' })"
|
||||
>Remove playmat</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.playmat-picker {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
aspect-ratio: 16 / 7;
|
||||
max-height: 14rem;
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel-2) center / cover no-repeat;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.field input[type="file"] {
|
||||
padding: 0.3rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.results {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.4rem;
|
||||
max-height: 18rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.results button {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
padding: 0.25rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.results img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 626 / 457;
|
||||
border-radius: 4px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.results span {
|
||||
overflow: hidden;
|
||||
font-size: 0.72rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.remove {
|
||||
align-self: flex-start;
|
||||
padding: 0.2rem 0.45rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
</style>
|
||||
212
frontend/app/components/PseudoGuide.vue
Normal file
212
frontend/app/components/PseudoGuide.vue
Normal file
@@ -0,0 +1,212 @@
|
||||
<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 <trigger>:</code></td><td><code>on dies(this):</code></td></tr>
|
||||
<tr><td><code>activate <cost>:</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 <name></code></td><td><code>keyword Flying</code></td></tr>
|
||||
<tr><td><code>keywords <a>, <b></code></td><td><code>keywords Flying, vigilance</code></td></tr>
|
||||
<tr><td><code>additional cost: <cost></code></td><td><code>additional cost: pay 2 life</code></td></tr>
|
||||
<tr><td><code>if <condition>:</code></td><td>Nested effects, indented below.</td></tr>
|
||||
<tr><td><code>choose <n>:</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>
|
||||
27
frontend/app/components/SymbolText.vue
Normal file
27
frontend/app/components/SymbolText.vue
Normal file
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{ text?: string }>()
|
||||
|
||||
/** Runs of {symbols} render through ManaCost; everything else stays text. */
|
||||
const parts = computed(() => (props.text ?? '')
|
||||
.split(/((?:\{[^}]+\})+)/)
|
||||
.filter(Boolean))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="symbol-text">
|
||||
<template v-for="(part, index) in parts" :key="index">
|
||||
<ManaCost v-if="part.startsWith('{')" :cost="part" />
|
||||
<template v-else>{{ part }}</template>
|
||||
</template>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.symbol-text {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.symbol-text :deep(.mana-cost) {
|
||||
vertical-align: -0.15em;
|
||||
}
|
||||
</style>
|
||||
7
frontend/app/middleware/auth.ts
Normal file
7
frontend/app/middleware/auth.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { authToken } from '~/utils/auth'
|
||||
|
||||
export default defineNuxtRouteMiddleware(to => {
|
||||
const token = import.meta.server ? useCookie('commander-auth-token').value : authToken()
|
||||
if (token) return
|
||||
return navigateTo({ path: '/account', query: { next: to.fullPath } })
|
||||
})
|
||||
370
frontend/app/pages/account.vue
Normal file
370
frontend/app/pages/account.vue
Normal file
@@ -0,0 +1,370 @@
|
||||
<script setup lang="ts">
|
||||
import { authHeaders, hasAuth, setAuthToken } from '~/utils/auth'
|
||||
import { saveDeck, type SavedDeck } from '~/utils/decks'
|
||||
import { loadPlaymatChoice, savePlaymatChoice, type PlaymatChoice, type PlaymatSelection } from '~/utils/playmat'
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const route = useRoute()
|
||||
|
||||
const mode = ref<'login' | 'register'>('login')
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const signedIn = ref('')
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const playmat = ref<PlaymatChoice>()
|
||||
const playmatError = ref('')
|
||||
const playmatPreview = computed(() => {
|
||||
if (playmat.value?.kind === 'card') return playmat.value
|
||||
if (playmat.value?.kind === 'upload') return { kind: 'upload' as const, url: playmat.value.data }
|
||||
return null
|
||||
})
|
||||
|
||||
async function choosePlaymat(selection: PlaymatSelection) {
|
||||
playmatError.value = ''
|
||||
if (selection.kind === 'none') {
|
||||
if (!(await savePlaymatChoice(apiBase, undefined))) {
|
||||
playmatError.value = 'Could not save that playmat to your account.'
|
||||
return
|
||||
}
|
||||
playmat.value = undefined
|
||||
return
|
||||
}
|
||||
const choice: PlaymatChoice = selection.kind === 'card'
|
||||
? { kind: 'card', oracleId: selection.oracleId }
|
||||
: { kind: 'upload', data: selection.data }
|
||||
if (!(await savePlaymatChoice(apiBase, choice))) {
|
||||
playmatError.value = 'Could not save that playmat to your account. Try a smaller image.'
|
||||
return
|
||||
}
|
||||
playmat.value = choice
|
||||
}
|
||||
|
||||
function nextPath(): string {
|
||||
const next = route.query.next
|
||||
return typeof next === 'string' && next.startsWith('/') && !next.startsWith('//') ? next : '/'
|
||||
}
|
||||
|
||||
function message(caught: unknown): string {
|
||||
const data = (caught as { data?: { error?: string } })?.data
|
||||
return data?.error ?? 'Could not reach the server.'
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
if (!hasAuth()) return
|
||||
try {
|
||||
const data = await $fetch<{ username: string }>(`${apiBase}/auth/me`, { headers: authHeaders() })
|
||||
signedIn.value = data.username
|
||||
} catch {
|
||||
setAuthToken(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
/** Move decks and cosmetic preferences saved by older browser-only versions. */
|
||||
async function migrateLocalData() {
|
||||
if (typeof localStorage === 'undefined') return
|
||||
|
||||
const decks = localStorage.getItem('commander-decks-v1')
|
||||
if (decks !== null) {
|
||||
try {
|
||||
const parsed = JSON.parse(decks) as SavedDeck[]
|
||||
if (Array.isArray(parsed)) {
|
||||
for (const deck of parsed) await saveDeck(apiBase, deck)
|
||||
localStorage.removeItem('commander-decks-v1')
|
||||
}
|
||||
} catch {
|
||||
// Keep corrupt data in place rather than deleting it.
|
||||
}
|
||||
}
|
||||
|
||||
const playmat = localStorage.getItem('commander-playmat-v1')
|
||||
if (playmat !== null) {
|
||||
try {
|
||||
const choice = JSON.parse(playmat) as PlaymatChoice | null
|
||||
if (await savePlaymatChoice(apiBase, choice ?? undefined)) {
|
||||
localStorage.removeItem('commander-playmat-v1')
|
||||
}
|
||||
} catch {
|
||||
// Keep corrupt data in place rather than deleting it.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await $fetch<{ token: string; username: string }>(`${apiBase}/auth/${mode.value}`, {
|
||||
method: 'POST',
|
||||
body: { username: username.value, password: password.value },
|
||||
})
|
||||
setAuthToken(data.token)
|
||||
signedIn.value = data.username
|
||||
try {
|
||||
await migrateLocalData()
|
||||
} catch {
|
||||
// A failed migration must not block signing in.
|
||||
}
|
||||
await navigateTo(nextPath())
|
||||
} catch (caught) {
|
||||
error.value = message(caught)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await $fetch(`${apiBase}/auth/logout`, { method: 'POST', headers: authHeaders() })
|
||||
} catch {
|
||||
// Clearing the token locally is enough.
|
||||
}
|
||||
setAuthToken(undefined)
|
||||
password.value = ''
|
||||
signedIn.value = ''
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await refresh()
|
||||
if (!signedIn.value) return
|
||||
playmat.value = await loadPlaymatChoice(apiBase)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="page account-page">
|
||||
<section class="auth-card" :class="{ wide: signedIn }">
|
||||
<header class="auth-head">
|
||||
<span class="auth-mark" aria-hidden="true">◆</span>
|
||||
<p v-if="signedIn" class="muted">
|
||||
Signed in as <strong>{{ signedIn }}</strong>
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<template v-if="signedIn">
|
||||
<div class="signed-actions">
|
||||
<NuxtLink class="auth-link" to="/">Play</NuxtLink>
|
||||
<NuxtLink class="auth-link" to="/decks">Decks</NuxtLink>
|
||||
<button type="button" class="mini" @click="logout">Sign out</button>
|
||||
</div>
|
||||
|
||||
<section class="prefs">
|
||||
<h2>Playmat</h2>
|
||||
<p class="muted">
|
||||
Your mat for new games. Pick card art or upload an image; you can still change it in-game.
|
||||
</p>
|
||||
<p v-if="playmatError" class="error">{{ playmatError }}</p>
|
||||
<PlaymatPicker :current="playmatPreview" @select="choosePlaymat" />
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="auth-tabs" role="tablist" aria-label="Account mode">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="mode === 'login'"
|
||||
:class="{ active: mode === 'login' }"
|
||||
@click="mode = 'login'"
|
||||
>Sign in</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="mode === 'register'"
|
||||
:class="{ active: mode === 'register' }"
|
||||
@click="mode = 'register'"
|
||||
>Create account</button>
|
||||
</div>
|
||||
|
||||
<form @submit.prevent="submit">
|
||||
<label class="field">
|
||||
<span>Username</span>
|
||||
<input
|
||||
v-model="username"
|
||||
autocomplete="username"
|
||||
minlength="3"
|
||||
maxlength="32"
|
||||
placeholder="your name"
|
||||
required
|
||||
>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Password</span>
|
||||
<input
|
||||
v-model="password"
|
||||
type="password"
|
||||
:autocomplete="mode === 'login' ? 'current-password' : 'new-password'"
|
||||
minlength="8"
|
||||
maxlength="200"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
>
|
||||
</label>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<button type="submit" class="primary" :disabled="busy">
|
||||
{{ busy ? 'Working…' : mode === 'login' ? 'Sign in' : 'Create account' }}
|
||||
</button>
|
||||
</form>
|
||||
</template>
|
||||
</section>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
main.account-page {
|
||||
min-height: calc(100vh - 3rem);
|
||||
max-width: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 2rem 1.25rem;
|
||||
background: radial-gradient(60rem 32rem at 50% -12%, rgba(122, 162, 247, 0.13), transparent 70%);
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
width: 100%;
|
||||
max-width: 26rem;
|
||||
padding: 1.75rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(180deg, #1b1f2b, var(--panel));
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.auth-card.wide {
|
||||
max-width: 42rem;
|
||||
}
|
||||
|
||||
.prefs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
padding-top: 1.25rem;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.prefs h2 {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.auth-head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.auth-head h1 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.auth-head p {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.auth-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, rgba(122, 162, 247, 0.35), rgba(122, 162, 247, 0.08));
|
||||
color: var(--accent);
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.auth-tabs {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.25rem;
|
||||
padding: 0.25rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.auth-tabs button {
|
||||
padding: 0.5rem;
|
||||
border: 0;
|
||||
border-radius: 7px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.auth-tabs button:hover {
|
||||
border: 0;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.auth-tabs button.active {
|
||||
color: var(--text);
|
||||
background: rgba(122, 162, 247, 0.16);
|
||||
box-shadow: inset 0 0 0 1px rgba(122, 162, 247, 0.35);
|
||||
}
|
||||
|
||||
.auth-card form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.85rem;
|
||||
}
|
||||
|
||||
.auth-card .field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.auth-card .field span {
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.auth-card .field input {
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.75rem;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.auth-card .field input:focus {
|
||||
border-color: var(--accent);
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(122, 162, 247, 0.16);
|
||||
}
|
||||
|
||||
.auth-card button[type="submit"] {
|
||||
margin-top: 0.25rem;
|
||||
padding: 0.65rem;
|
||||
border-radius: 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.auth-card .error {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.signed-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.auth-link {
|
||||
padding: 0.45rem 0.7rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.auth-link:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--text);
|
||||
}
|
||||
</style>
|
||||
445
frontend/app/pages/cards.vue
Normal file
445
frontend/app/pages/cards.vue
Normal file
@@ -0,0 +1,445 @@
|
||||
<script setup lang="ts">
|
||||
import CardGraphEditor from '../components/CardGraphEditor.vue'
|
||||
import PseudoGuide from '../components/PseudoGuide.vue'
|
||||
|
||||
type Status = 'supported' | 'partial' | 'unsupported'
|
||||
|
||||
interface CardSummary {
|
||||
oracle_id: string
|
||||
name: string
|
||||
mana_cost?: string
|
||||
type_line: string
|
||||
oracle_text?: string
|
||||
card_faces?: Array<{
|
||||
name: string
|
||||
mana_cost?: string
|
||||
type_line?: string
|
||||
oracle_text?: string
|
||||
}>
|
||||
implementation: { status: Status; manual: boolean } | null
|
||||
}
|
||||
|
||||
interface ImplementationResponse {
|
||||
card: CardSummary
|
||||
compiled: { status: Status }
|
||||
source: string
|
||||
manual: boolean
|
||||
updatedAt?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface Stats {
|
||||
supported: number
|
||||
partial: number
|
||||
unsupported: number
|
||||
manual: number
|
||||
}
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const pageSize = 50
|
||||
|
||||
const formatOptions = [
|
||||
{ value: 'commander', label: 'Commander' },
|
||||
{ value: 'brawl', label: 'Brawl' },
|
||||
{ value: 'standard', label: 'Standard' },
|
||||
{ value: 'pioneer', label: 'Pioneer' },
|
||||
{ value: 'modern', label: 'Modern' },
|
||||
{ value: 'legacy', label: 'Legacy' },
|
||||
{ value: 'vintage', label: 'Vintage' },
|
||||
{ value: 'pauper', label: 'Pauper' },
|
||||
{ value: 'historic', label: 'Historic' },
|
||||
{ value: 'timeless', label: 'Timeless' },
|
||||
{ value: 'explorer', label: 'Explorer' },
|
||||
{ value: 'alchemy', label: 'Alchemy' },
|
||||
{ value: 'oathbreaker', label: 'Oathbreaker' },
|
||||
{ value: 'duel', label: 'Duel Commander' },
|
||||
{ value: 'paupercommander', label: 'Pauper Commander' },
|
||||
{ value: 'standardbrawl', label: 'Standard Brawl' },
|
||||
{ value: 'gladiator', label: 'Gladiator' },
|
||||
{ value: 'competitivebrawl', label: 'Competitive Brawl' },
|
||||
{ value: 'premodern', label: 'Premodern' },
|
||||
{ value: 'predh', label: 'PreDH' },
|
||||
{ value: 'oldschool', label: 'Old School' },
|
||||
{ value: 'penny', label: 'Penny Dreadful' },
|
||||
]
|
||||
const colorOptions = [
|
||||
{ value: 'W', label: 'White' },
|
||||
{ value: 'U', label: 'Blue' },
|
||||
{ value: 'B', label: 'Black' },
|
||||
{ value: 'R', label: 'Red' },
|
||||
{ value: 'G', label: 'Green' },
|
||||
{ value: 'M', label: 'Multicolor' },
|
||||
{ value: 'C', label: 'Colorless' },
|
||||
]
|
||||
const typeOptions = [
|
||||
{ value: 'creature', label: 'Creature' },
|
||||
{ value: 'instant', label: 'Instant' },
|
||||
{ value: 'sorcery', label: 'Sorcery' },
|
||||
{ value: 'artifact', label: 'Artifact' },
|
||||
{ value: 'enchantment', label: 'Enchantment' },
|
||||
{ value: 'planeswalker', label: 'Planeswalker' },
|
||||
{ value: 'battle', label: 'Battle' },
|
||||
{ value: 'land', label: 'Land' },
|
||||
{ value: 'kindred', label: 'Kindred' },
|
||||
{ value: 'legendary', label: 'Legendary' },
|
||||
]
|
||||
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('')
|
||||
const colorFilter = ref('')
|
||||
const typeFilter = ref('')
|
||||
const rarityFilter = ref('')
|
||||
const cmcFilter = ref('')
|
||||
const cards = ref<CardSummary[]>([])
|
||||
const total = ref(0)
|
||||
const offset = ref(0)
|
||||
const loadingList = ref(false)
|
||||
const listError = ref('')
|
||||
|
||||
const stats = ref<Stats | null>(null)
|
||||
const selectedId = ref('')
|
||||
const detail = ref<ImplementationResponse | null>(null)
|
||||
const source = ref('')
|
||||
const detailLoading = ref(false)
|
||||
const saving = ref(false)
|
||||
const translating = ref(false)
|
||||
const editorError = ref('')
|
||||
|
||||
const page = computed(() => Math.floor(offset.value / pageSize) + 1)
|
||||
const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize)))
|
||||
const dirty = computed(() => Boolean(detail.value) && source.value !== detail.value!.source)
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
const data = (error as { data?: { error?: string } })?.data
|
||||
return data?.error ?? (error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
|
||||
function manaCostOf(card: CardSummary): string | undefined {
|
||||
const faces = card.card_faces?.map(face => face.mana_cost).filter(Boolean) ?? []
|
||||
return card.mana_cost ?? (faces.length ? faces.join(' // ') : undefined)
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
stats.value = await $fetch<Stats>(`${apiBase}/stats`)
|
||||
} catch {
|
||||
stats.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCards(reset = false) {
|
||||
loadingList.value = true
|
||||
listError.value = ''
|
||||
if (reset) offset.value = 0
|
||||
try {
|
||||
const data = await $fetch<{ total: number; cards: CardSummary[] }>(`${apiBase}/cards`, {
|
||||
query: {
|
||||
q: search.value,
|
||||
status: statusFilter.value,
|
||||
format: formatFilter.value || undefined,
|
||||
color: colorFilter.value || undefined,
|
||||
type: typeFilter.value || undefined,
|
||||
rarity: rarityFilter.value || undefined,
|
||||
cmcMin: cmcFilter.value === '7+' ? '7' : cmcFilter.value || undefined,
|
||||
cmcMax: cmcFilter.value === '7+' ? undefined : cmcFilter.value || undefined,
|
||||
limit: pageSize,
|
||||
offset: offset.value,
|
||||
},
|
||||
})
|
||||
cards.value = data.cards
|
||||
total.value = data.total
|
||||
} catch (error) {
|
||||
listError.value = errorMessage(error)
|
||||
} finally {
|
||||
loadingList.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function selectCard(card: CardSummary) {
|
||||
selectedId.value = card.oracle_id
|
||||
detailLoading.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
detail.value = await $fetch<ImplementationResponse>(
|
||||
`${apiBase}/cards/${card.oracle_id}/implementation`,
|
||||
)
|
||||
source.value = detail.value.source
|
||||
} catch (error) {
|
||||
detail.value = null
|
||||
editorError.value = errorMessage(error)
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!detail.value || saving.value) return
|
||||
saving.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
const data = await $fetch<ImplementationResponse>(
|
||||
`${apiBase}/cards/${detail.value.card.oracle_id}/implementation`,
|
||||
{ method: 'PUT', body: { source: source.value } },
|
||||
)
|
||||
detail.value = data
|
||||
source.value = data.source
|
||||
updateSummary(data)
|
||||
await loadStats()
|
||||
} catch (error) {
|
||||
editorError.value = errorMessage(error)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function translate() {
|
||||
if (!detail.value || translating.value) return
|
||||
if (dirty.value && !window.confirm('Replace the current edits with an AI draft?')) return
|
||||
translating.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
const data = await $fetch<{ source: string }>(
|
||||
`${apiBase}/cards/${detail.value.card.oracle_id}/translate`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
source.value = data.source
|
||||
} catch (error) {
|
||||
editorError.value = errorMessage(error)
|
||||
} finally {
|
||||
translating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function reset() {
|
||||
if (!detail.value || saving.value) return
|
||||
if (!window.confirm('Delete the manual implementation and restore the generated one?')) return
|
||||
saving.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
const data = await $fetch<ImplementationResponse>(
|
||||
`${apiBase}/cards/${detail.value.card.oracle_id}/implementation`,
|
||||
{ method: 'DELETE' },
|
||||
)
|
||||
detail.value = data
|
||||
source.value = data.source
|
||||
updateSummary(data)
|
||||
await loadStats()
|
||||
} catch (error) {
|
||||
editorError.value = errorMessage(error)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function updateSummary(data: ImplementationResponse) {
|
||||
const card = cards.value.find(entry => entry.oracle_id === data.card.oracle_id)
|
||||
if (card) card.implementation = { status: data.compiled.status, manual: data.manual }
|
||||
}
|
||||
|
||||
function previousPage() {
|
||||
if (offset.value === 0) return
|
||||
offset.value = Math.max(0, offset.value - pageSize)
|
||||
loadCards()
|
||||
}
|
||||
|
||||
function nextPage() {
|
||||
if (offset.value + pageSize >= total.value) return
|
||||
offset.value += pageSize
|
||||
loadCards()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadStats()
|
||||
loadCards(true)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="fill-page">
|
||||
<header>
|
||||
<div>
|
||||
<h1>Card implementations</h1>
|
||||
<p class="muted">
|
||||
<template v-if="stats">
|
||||
{{ stats.supported.toLocaleString() }} supported ·
|
||||
{{ stats.partial.toLocaleString() }} partial ·
|
||||
{{ stats.unsupported.toLocaleString() }} unsupported ·
|
||||
{{ stats.manual.toLocaleString() }} manual
|
||||
</template>
|
||||
<template v-else>Loading stats…</template>
|
||||
</p>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<div class="tabs">
|
||||
<button type="button" :class="{ active: view === 'editor' }" @click="view = 'editor'">Editor</button>
|
||||
<button type="button" :class="{ active: view === 'guide' }" @click="view = 'guide'">Guide</button>
|
||||
</div>
|
||||
<a :href="`${apiBase}/health`" target="_blank" rel="noreferrer">API health</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div v-if="view === 'editor'" class="layout">
|
||||
<section class="list-panel">
|
||||
<form class="search" @submit.prevent="loadCards(true)">
|
||||
<input v-model="search" type="search" placeholder="Search card names…">
|
||||
<select v-model="statusFilter" aria-label="Implementation status" @change="loadCards(true)">
|
||||
<option value="needs-work">Needs work</option>
|
||||
<option value="unsupported">Not implemented</option>
|
||||
<option value="partial">Partial</option>
|
||||
<option value="supported">Supported</option>
|
||||
<option value="manual">Manual</option>
|
||||
<option value="all">All cards</option>
|
||||
</select>
|
||||
<button type="submit">Search</button>
|
||||
</form>
|
||||
|
||||
<div class="filters">
|
||||
<select v-model="formatFilter" aria-label="Format legality" @change="loadCards(true)">
|
||||
<option value="">Any format</option>
|
||||
<option v-for="format in formatOptions" :key="format.value" :value="format.value">
|
||||
{{ format.label }}
|
||||
</option>
|
||||
</select>
|
||||
<select v-model="colorFilter" aria-label="Color identity" @change="loadCards(true)">
|
||||
<option value="">Any color</option>
|
||||
<option v-for="color in colorOptions" :key="color.value" :value="color.value">
|
||||
{{ color.label }}
|
||||
</option>
|
||||
</select>
|
||||
<select v-model="typeFilter" aria-label="Card type" @change="loadCards(true)">
|
||||
<option value="">Any type</option>
|
||||
<option v-for="type in typeOptions" :key="type.value" :value="type.value">
|
||||
{{ type.label }}
|
||||
</option>
|
||||
</select>
|
||||
<select v-model="rarityFilter" aria-label="Rarity" @change="loadCards(true)">
|
||||
<option value="">Any rarity</option>
|
||||
<option v-for="rarity in rarityOptions" :key="rarity" :value="rarity">
|
||||
{{ rarity }}
|
||||
</option>
|
||||
</select>
|
||||
<select v-model="cmcFilter" aria-label="Mana value" @change="loadCards(true)">
|
||||
<option value="">Any mana value</option>
|
||||
<option v-for="cmc in cmcOptions" :key="cmc" :value="cmc">
|
||||
{{ cmc === '7+' ? '7 or more' : cmc }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<p v-if="listError" class="error">{{ listError }}</p>
|
||||
<p v-else-if="loadingList" class="muted">Loading…</p>
|
||||
<p v-else-if="!cards.length" class="muted">No cards match.</p>
|
||||
|
||||
<ul class="card-list">
|
||||
<li v-for="card in cards" :key="card.oracle_id">
|
||||
<CardHover :oracle-id="card.oracle_id" :name="card.name">
|
||||
<button
|
||||
type="button"
|
||||
class="card-row"
|
||||
:class="{ selected: card.oracle_id === selectedId }"
|
||||
@click="selectCard(card)"
|
||||
>
|
||||
<span class="card-main">
|
||||
<span class="card-name">{{ card.name }}</span>
|
||||
<ManaCost :cost="manaCostOf(card)" />
|
||||
</span>
|
||||
<span class="badges">
|
||||
<span
|
||||
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>
|
||||
</span>
|
||||
</button>
|
||||
</CardHover>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="pager">
|
||||
<button type="button" :disabled="offset === 0 || loadingList" @click="previousPage">Previous</button>
|
||||
<span class="muted">Page {{ page }} of {{ pageCount }} · {{ total.toLocaleString() }} cards</span>
|
||||
<button type="button" :disabled="offset + pageSize >= total || loadingList" @click="nextPage">Next</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="detail-panel">
|
||||
<p v-if="!selectedId" class="muted">Select a card to view or edit its implementation.</p>
|
||||
<p v-else-if="detailLoading" class="muted">Loading card…</p>
|
||||
<template v-else-if="detail">
|
||||
<div class="detail-head">
|
||||
<div>
|
||||
<h2>{{ detail.card.name }}</h2>
|
||||
<p class="muted">
|
||||
{{ detail.card.type_line }}
|
||||
<ManaCost :cost="manaCostOf(detail.card)" />
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="detail.card.card_faces?.length">
|
||||
<div v-for="face in detail.card.card_faces" :key="face.name" class="oracle">
|
||||
<h3>{{ face.name }}</h3>
|
||||
<p class="muted">{{ face.type_line }}</p>
|
||||
<p><SymbolText :text="face.oracle_text" /></p>
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="oracle">
|
||||
<p><SymbolText :text="detail.card.oracle_text" /></p>
|
||||
</div>
|
||||
|
||||
<p v-if="detail.error" class="error">
|
||||
The saved implementation does not parse: {{ detail.error }}
|
||||
</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>
|
||||
|
||||
<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">
|
||||
{{ saving ? 'Saving…' : 'Save' }}
|
||||
</button>
|
||||
<span class="muted">{{ dirty ? 'Unsaved changes' : 'Saved' }}</span>
|
||||
<button type="button" :disabled="saving || translating" @click="translate">
|
||||
{{ translating ? 'Drafting…' : 'Draft with AI' }}
|
||||
</button>
|
||||
<button type="button" :disabled="saving || !detail.manual" @click="reset">
|
||||
Reset to generated
|
||||
</button>
|
||||
<span v-if="detail.updatedAt" class="muted saved-at">
|
||||
Updated {{ new Date(detail.updatedAt).toLocaleString() }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<PseudoGuide v-else />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
1002
frontend/app/pages/decks.vue
Normal file
1002
frontend/app/pages/decks.vue
Normal file
File diff suppressed because it is too large
Load Diff
2236
frontend/app/pages/games/[id].vue
Normal file
2236
frontend/app/pages/games/[id].vue
Normal file
File diff suppressed because it is too large
Load Diff
258
frontend/app/pages/index.vue
Normal file
258
frontend/app/pages/index.vue
Normal file
@@ -0,0 +1,258 @@
|
||||
<script setup lang="ts">
|
||||
import { deckValidation, loadDecks, type SavedDeck } from '~/utils/decks'
|
||||
import { loadPlaymatChoice, type PlaymatChoice } from '~/utils/playmat'
|
||||
|
||||
interface MatchSummary {
|
||||
id: string
|
||||
hostName: string
|
||||
status: 'lobby' | 'active' | 'finished'
|
||||
playerCount: number
|
||||
maxPlayers: number
|
||||
players: string[]
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
definePageMeta({ middleware: 'auth' })
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const SESSION_PREFIX = 'commander-session-'
|
||||
|
||||
const playerName = ref('')
|
||||
const maxPlayers = ref(4)
|
||||
const decks = ref<SavedDeck[]>([])
|
||||
const selectedDeckId = ref('')
|
||||
const games = ref<MatchSummary[]>([])
|
||||
const loading = ref(false)
|
||||
const starting = ref(false)
|
||||
const error = ref('')
|
||||
let poll: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
const selectedDeck = computed(() => decks.value.find(deck => deck.id === selectedDeckId.value))
|
||||
const deckErrors = computed(() => selectedDeck.value ? deckValidation(selectedDeck.value) : ['Choose a deck.'])
|
||||
const canStart = computed(() => Boolean(playerName.value.trim() && selectedDeck.value && !deckErrors.value.length))
|
||||
|
||||
const playmat = ref<PlaymatChoice>()
|
||||
|
||||
function deckPayload(deck: SavedDeck) {
|
||||
return {
|
||||
commander: deck.commander.oracleId,
|
||||
cards: deck.cards.map(card => card.oracleId),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadGames() {
|
||||
try {
|
||||
const data = await $fetch<{ games: MatchSummary[] }>(`${apiBase}/games`)
|
||||
games.value = data.games
|
||||
} catch (caught) {
|
||||
error.value = errorMessage(caught)
|
||||
}
|
||||
}
|
||||
|
||||
async function createGame() {
|
||||
if (!canStart.value || !selectedDeck.value) return
|
||||
starting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await $fetch<{ matchId: string; playerId: string; token: string }>(`${apiBase}/games`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: playerName.value,
|
||||
maxPlayers: maxPlayers.value,
|
||||
deck: deckPayload(selectedDeck.value),
|
||||
playmat: playmat.value,
|
||||
},
|
||||
})
|
||||
enterGame(data.matchId, data)
|
||||
} catch (caught) {
|
||||
error.value = errorMessage(caught)
|
||||
} finally {
|
||||
starting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function joinGame(game: MatchSummary) {
|
||||
if (!canStart.value || !selectedDeck.value) {
|
||||
error.value = 'Choose a valid deck and enter your name first.'
|
||||
return
|
||||
}
|
||||
starting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await $fetch<{ matchId: string; playerId: string; token: string }>(
|
||||
`${apiBase}/games/${game.id}/join`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: { name: playerName.value, deck: deckPayload(selectedDeck.value), playmat: playmat.value },
|
||||
},
|
||||
)
|
||||
enterGame(data.matchId, data)
|
||||
} catch (caught) {
|
||||
error.value = errorMessage(caught)
|
||||
} finally {
|
||||
starting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function enterGame(matchId: string, data: { playerId: string; token: string }) {
|
||||
sessionStorage.setItem(`${SESSION_PREFIX}${matchId}`, JSON.stringify(data))
|
||||
void navigateTo(`/games/${matchId}`)
|
||||
}
|
||||
|
||||
function errorMessage(caught: unknown): string {
|
||||
const data = (caught as { data?: { error?: string } })?.data
|
||||
return data?.error ?? (caught instanceof Error ? caught.message : String(caught))
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
playerName.value = localStorage.getItem('commander-player-name') ?? ''
|
||||
playmat.value = await loadPlaymatChoice(apiBase)
|
||||
decks.value = (await loadDecks(apiBase)).sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
selectedDeckId.value = decks.value.find(deck => !deckValidation(deck).length)?.id
|
||||
?? decks.value[0]?.id
|
||||
?? ''
|
||||
void loadGames()
|
||||
poll = setInterval(loadGames, 5000)
|
||||
})
|
||||
|
||||
watch(playerName, value => {
|
||||
if (typeof localStorage !== 'undefined') localStorage.setItem('commander-player-name', value)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (poll) clearInterval(poll)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="page">
|
||||
<header>
|
||||
<h1>Play Commander</h1>
|
||||
<p class="muted">
|
||||
Four-player free-for-all with 40 life, command zones, commander tax, and
|
||||
21 commander damage. Games live in the API process and disappear on restart.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
|
||||
<div class="home-grid">
|
||||
<section class="panel">
|
||||
<h2>Start or join</h2>
|
||||
<label class="field">
|
||||
<span class="muted">Your name</span>
|
||||
<input v-model="playerName" maxlength="30" placeholder="Player">
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="muted">Deck</span>
|
||||
<select v-model="selectedDeckId">
|
||||
<option v-for="deck in decks" :key="deck.id" :value="deck.id">
|
||||
{{ deck.name }} ({{ deck.cards.length + 1 }})
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="!decks.length" class="warn">
|
||||
No decks yet. <NuxtLink to="/decks">Create or import one</NuxtLink>.
|
||||
</p>
|
||||
<ul v-else-if="deckErrors.length" class="errors">
|
||||
<li v-for="message in deckErrors.slice(0, 3)" :key="message" class="warn">{{ message }}</li>
|
||||
</ul>
|
||||
<label v-else class="field">
|
||||
<span class="muted">Seats</span>
|
||||
<select v-model.number="maxPlayers">
|
||||
<option :value="2">2 players</option>
|
||||
<option :value="3">3 players</option>
|
||||
<option :value="4">4 players</option>
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" class="primary" :disabled="!canStart || starting" @click="createGame">
|
||||
{{ starting ? 'Starting…' : 'Create game' }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="row">
|
||||
<h2 class="grow">Open games</h2>
|
||||
<button type="button" class="mini" @click="loadGames">Refresh</button>
|
||||
</div>
|
||||
<p v-if="!games.length" class="muted">No games yet. Create one and send the link to your friends.</p>
|
||||
<ul class="games">
|
||||
<li v-for="game in games" :key="game.id" class="game-row">
|
||||
<div class="grow">
|
||||
<div class="row wrap">
|
||||
<strong>{{ game.hostName }}'s game</strong>
|
||||
<span class="tag">{{ game.status }}</span>
|
||||
<span class="tag">{{ game.playerCount }}/{{ game.maxPlayers }}</span>
|
||||
</div>
|
||||
<p class="muted">{{ game.players.join(', ') || 'Waiting for players' }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="game.status === 'lobby' && game.playerCount < game.maxPlayers"
|
||||
type="button"
|
||||
:disabled="!canStart || starting"
|
||||
@click="joinGame(game)"
|
||||
>Join</button>
|
||||
<span v-else class="muted">{{ game.status === 'active' ? 'In progress' : 'Full' }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.home-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(18rem, 24rem) 1fr;
|
||||
gap: 1rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.field select,
|
||||
.field input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.errors {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.games {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.game-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 0.6rem 0;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.game-row:first-child {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.mini {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.2rem 0.45rem;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.home-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
29
frontend/app/utils/auth.ts
Normal file
29
frontend/app/utils/auth.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
const TOKEN_KEY = 'commander-auth-token'
|
||||
export const AUTH_CHANGED = 'commander-auth-change'
|
||||
|
||||
// Stored in a cookie (not localStorage) so the server can redirect before rendering.
|
||||
export function authToken(): string | undefined {
|
||||
if (typeof document === 'undefined') return undefined
|
||||
const value = document.cookie
|
||||
.split('; ')
|
||||
.find(cookie => cookie.startsWith(`${TOKEN_KEY}=`))
|
||||
?.slice(TOKEN_KEY.length + 1)
|
||||
return value ? decodeURIComponent(value) : undefined
|
||||
}
|
||||
|
||||
export function setAuthToken(token: string | undefined): void {
|
||||
if (typeof document === 'undefined') return
|
||||
document.cookie = token
|
||||
? `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=31536000; SameSite=Lax`
|
||||
: `${TOKEN_KEY}=; path=/; max-age=0; SameSite=Lax`
|
||||
window.dispatchEvent(new Event(AUTH_CHANGED))
|
||||
}
|
||||
|
||||
export function hasAuth(): boolean {
|
||||
return Boolean(authToken())
|
||||
}
|
||||
|
||||
export function authHeaders(): Record<string, string> {
|
||||
const token = authToken()
|
||||
return token ? { Authorization: `Bearer ${token}` } : {}
|
||||
}
|
||||
10
frontend/app/utils/cardBack.ts
Normal file
10
frontend/app/utils/cardBack.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
/** Plain backs offered in the menu; the first is the default when nothing is stored. */
|
||||
export const CARD_BACK_COLORS = ['#26304a', '#1f3a2e', '#4a1f24', '#33244f', '#4a3520', '#14161c']
|
||||
|
||||
/** CSS variables for a stored back: `data:` values are images, anything else a plain colour. */
|
||||
export function cardBackVars(back: string | null | undefined): Record<string, string> | undefined {
|
||||
if (!back) return undefined
|
||||
return back.startsWith('data:')
|
||||
? { '--card-back-image': `url("${back}")` }
|
||||
: { '--card-back-color': back }
|
||||
}
|
||||
846
frontend/app/utils/cardGraph.ts
Normal file
846
frontend/app/utils/cardGraph.ts
Normal file
@@ -0,0 +1,846 @@
|
||||
// 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
|
||||
}
|
||||
132
frontend/app/utils/decks.ts
Normal file
132
frontend/app/utils/decks.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { authHeaders } from './auth'
|
||||
|
||||
export interface CardImplementation {
|
||||
status: 'supported' | 'partial' | 'unsupported'
|
||||
manual: boolean
|
||||
}
|
||||
|
||||
export interface DeckCard {
|
||||
oracleId: string
|
||||
name: string
|
||||
manaCost?: string
|
||||
typeLine: string
|
||||
colorIdentity: string[]
|
||||
oracleText?: string
|
||||
imageUri?: string
|
||||
implementation?: CardImplementation | null
|
||||
}
|
||||
|
||||
export interface SavedDeck {
|
||||
id: string
|
||||
name: string
|
||||
commander: DeckCard
|
||||
cards: DeckCard[]
|
||||
cardBack?: string | null
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface ApiCard {
|
||||
oracle_id: string
|
||||
name: string
|
||||
mana_cost?: string
|
||||
type_line: string
|
||||
color_identity?: string[]
|
||||
oracle_text?: string
|
||||
image_uri?: string
|
||||
implementation?: CardImplementation | null
|
||||
}
|
||||
|
||||
export function deckCardFromApi(card: ApiCard): DeckCard {
|
||||
return {
|
||||
oracleId: card.oracle_id,
|
||||
name: card.name,
|
||||
manaCost: card.mana_cost,
|
||||
typeLine: card.type_line,
|
||||
colorIdentity: card.color_identity ?? [],
|
||||
oracleText: card.oracle_text,
|
||||
imageUri: card.image_uri,
|
||||
implementation: card.implementation,
|
||||
}
|
||||
}
|
||||
|
||||
export function newDeckId(): string {
|
||||
return typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
||||
? crypto.randomUUID()
|
||||
: `deck-${Date.now()}-${Math.random().toString(16).slice(2)}`
|
||||
}
|
||||
|
||||
export async function loadDecks(apiBase: string): Promise<SavedDeck[]> {
|
||||
const { Authorization } = authHeaders()
|
||||
if (!Authorization) return []
|
||||
try {
|
||||
const data = await $fetch<{ decks: SavedDeck[] }>(`${apiBase}/me/decks`, {
|
||||
headers: { Authorization },
|
||||
})
|
||||
return Array.isArray(data.decks) ? data.decks : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveDeck(apiBase: string, deck: SavedDeck): Promise<void> {
|
||||
await $fetch(`${apiBase}/me/decks/${encodeURIComponent(deck.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: authHeaders(),
|
||||
body: { name: deck.name, commander: deck.commander, cards: deck.cards, cardBack: deck.cardBack ?? null },
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteDeck(apiBase: string, id: string): Promise<void> {
|
||||
await $fetch(`${apiBase}/me/decks/${encodeURIComponent(id)}`, {
|
||||
method: 'DELETE',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
}
|
||||
|
||||
export function isBasicLand(card: DeckCard): boolean {
|
||||
return /\bbasic\b/i.test(card.typeLine) && /\bland\b/i.test(card.typeLine)
|
||||
}
|
||||
|
||||
export function canBeCommander(card: DeckCard): boolean {
|
||||
return (/\blegendary\b/i.test(card.typeLine) && /\bcreature\b/i.test(card.typeLine))
|
||||
|| /can be your commander/i.test(card.oracleText ?? '')
|
||||
}
|
||||
|
||||
export function deckValidation(deck: SavedDeck): string[] {
|
||||
const errors: string[] = []
|
||||
if (!canBeCommander(deck.commander)) errors.push('The commander must be a legendary creature.')
|
||||
if (deck.cards.length + 1 !== 100) {
|
||||
errors.push(`The deck has ${deck.cards.length + 1} cards; it needs exactly 100.`)
|
||||
}
|
||||
|
||||
const identity = new Set(deck.commander.colorIdentity)
|
||||
const counts = new Map<string, number>()
|
||||
for (const card of deck.cards) {
|
||||
counts.set(card.oracleId, (counts.get(card.oracleId) ?? 0) + 1)
|
||||
if (card.oracleId === deck.commander.oracleId) {
|
||||
errors.push('The commander cannot also be in the deck.')
|
||||
}
|
||||
if (card.colorIdentity.some(color => !identity.has(color))) {
|
||||
errors.push(`${card.name} is outside the commander's color identity.`)
|
||||
}
|
||||
}
|
||||
for (const [oracleId, count] of counts) {
|
||||
if (count < 2) continue
|
||||
const card = deck.cards.find(entry => entry.oracleId === oracleId)
|
||||
if (card && !isBasicLand(card)) {
|
||||
errors.push(`${card.name} appears ${count} times; only basic lands may repeat.`)
|
||||
}
|
||||
}
|
||||
return [...new Set(errors)]
|
||||
}
|
||||
|
||||
export function exportDeckText(deck: SavedDeck): string {
|
||||
const counts = new Map<string, { card: DeckCard; count: number }>()
|
||||
for (const card of deck.cards) {
|
||||
const entry = counts.get(card.oracleId)
|
||||
if (entry) entry.count++
|
||||
else counts.set(card.oracleId, { card, count: 1 })
|
||||
}
|
||||
const deckLines = [...counts.values()].map(entry => `${entry.count} ${entry.card.name}`)
|
||||
return [`Commander`, `1 ${deck.commander.name}`, '', 'Deck', ...deckLines].join('\n')
|
||||
}
|
||||
21
frontend/app/utils/image.ts
Normal file
21
frontend/app/utils/image.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/** Downscale an image file to a JPEG data URL with its long side at most `max` pixels. */
|
||||
export async function resizeImage(file: File, max: number, quality = 0.82): Promise<string> {
|
||||
const url = URL.createObjectURL(file)
|
||||
try {
|
||||
const image = new Image()
|
||||
image.src = url
|
||||
await image.decode()
|
||||
const scale = Math.min(1, max / Math.max(image.naturalWidth, image.naturalHeight))
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = Math.max(1, Math.round(image.naturalWidth * scale))
|
||||
canvas.height = Math.max(1, Math.round(image.naturalHeight * scale))
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) throw new Error('Canvas unavailable')
|
||||
context.fillStyle = '#11151d'
|
||||
context.fillRect(0, 0, canvas.width, canvas.height)
|
||||
context.drawImage(image, 0, 0, canvas.width, canvas.height)
|
||||
return canvas.toDataURL('image/jpeg', quality)
|
||||
} finally {
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
}
|
||||
42
frontend/app/utils/playmat.ts
Normal file
42
frontend/app/utils/playmat.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { authHeaders } from './auth'
|
||||
|
||||
export type PlaymatChoice =
|
||||
| { kind: 'card'; oracleId: string }
|
||||
| { kind: 'upload'; data: string }
|
||||
|
||||
export type PlaymatSelection = PlaymatChoice | { kind: 'none' }
|
||||
|
||||
export async function loadPlaymatChoice(apiBase: string): Promise<PlaymatChoice | undefined> {
|
||||
const { Authorization } = authHeaders()
|
||||
if (!Authorization) return undefined
|
||||
try {
|
||||
const data = await $fetch<{ playmat: PlaymatChoice | null }>(`${apiBase}/me/preferences`, {
|
||||
headers: { Authorization },
|
||||
})
|
||||
const saved = data.playmat
|
||||
if (saved?.kind === 'card' && typeof saved.oracleId === 'string') {
|
||||
return { kind: 'card', oracleId: saved.oracleId }
|
||||
}
|
||||
if (saved?.kind === 'upload' && typeof saved.data === 'string') {
|
||||
return { kind: 'upload', data: saved.data }
|
||||
}
|
||||
} catch {
|
||||
// An unavailable account should not block the page.
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** False when the account cannot store the image; the caller should say so. */
|
||||
export async function savePlaymatChoice(apiBase: string, choice: PlaymatChoice | undefined): Promise<boolean> {
|
||||
if (!authHeaders().Authorization) return false
|
||||
try {
|
||||
await $fetch(`${apiBase}/me/preferences`, {
|
||||
method: 'PUT',
|
||||
headers: authHeaders(),
|
||||
body: { playmat: choice ?? null },
|
||||
})
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
11
frontend/nuxt.config.ts
Normal file
11
frontend/nuxt.config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
// https://nuxt.com/docs/api/configuration/nuxt-config
|
||||
export default defineNuxtConfig({
|
||||
compatibilityDate: '2025-07-15',
|
||||
devtools: { enabled: true },
|
||||
css: ['mana-font/css/mana.css', '~/assets/main.css'],
|
||||
runtimeConfig: {
|
||||
public: {
|
||||
apiBase: 'http://localhost:4000',
|
||||
},
|
||||
},
|
||||
})
|
||||
8684
frontend/package-lock.json
generated
Normal file
8684
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
frontend/package.json
Normal file
19
frontend/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "nuxt build",
|
||||
"dev": "nuxt dev",
|
||||
"test": "node --test test/*.test.ts",
|
||||
"generate": "nuxt generate",
|
||||
"preview": "nuxt preview",
|
||||
"postinstall": "nuxt prepare"
|
||||
},
|
||||
"dependencies": {
|
||||
"mana-font": "^1.18.0",
|
||||
"nuxt": "^4.6.2",
|
||||
"vue": "^3.5.44",
|
||||
"vue-router": "^5.4.0"
|
||||
}
|
||||
}
|
||||
BIN
frontend/public/favicon.ico
Normal file
BIN
frontend/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
2
frontend/public/robots.txt
Normal file
2
frontend/public/robots.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
User-Agent: *
|
||||
Disallow:
|
||||
215
frontend/test/cardGraph.test.ts
Normal file
215
frontend/test/cardGraph.test.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
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)
|
||||
})
|
||||
18
frontend/tsconfig.json
Normal file
18
frontend/tsconfig.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
// https://nuxt.com/docs/guide/concepts/typescript
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./.nuxt/tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./.nuxt/tsconfig.server.json"
|
||||
},
|
||||
{
|
||||
"path": "./.nuxt/tsconfig.shared.json"
|
||||
},
|
||||
{
|
||||
"path": "./.nuxt/tsconfig.node.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user