Repository navigation
Designer UI
English · Español
The React side of the card designer: the "Design" view (third tab of the app, next to "Deck" and "Library") plus its dialogs (collections, fonts/frames/symbols, "Design the deck", "Export images", crop an artwork). It only paints and keeps screen state; every render, hash and file operation is done by Rust (Designer App Layer) and the pure engine (Designer Engine).

src/features/design/design-screen.tsx → DesignScreen is passed to the shell as the design slot (src/App.tsx → src/features/shell/app-shell.tsx, a ToggleGroup over useUi.view = "deck" | "library" | "design"). The dialogs are mounted once in src/App.tsx (CollectionsDialog, ResourcesDialog, BatchDialog, PngDialog, CardEditorDialog) and opened through useUi.getState().open({ kind }) with the DialogName kinds collections, designResources, designDeck, exportPng (src/stores/ui-store.ts).
Ways to enter: the "Design" tab, or the card context menu item "Design proxy" / "Edit design" (src/features/preview/slot-menu.tsx, enabled when the card has a Scryfall id: scryfallIdOf(card) !== null), which calls useUi.design(id) (sets designing and switches view).
┌ top bar: ‹ › Alt+←/→ │ Renumber │ Design the deck │ Export images │ Collections │ Fonts, frames and symbols
├───────────┬─────────────────────────────┬────────────────────────┐
│ CardList│ DesignPreview (language, face,│ Form (6 tabs) │
│ (groups) │ safe margin, art overlay, │ + footer: remove, │
│ │ warnings) │ discard, Save, Save+next│
└───────────┴─────────────────────────────┴────────────────────────┘
The three panels are a ResizablePanelGroup (ids list, view, form); sizes persist in localStorage under proxybuilder.paneles.disenar (useDefaultLayout). Scrolling uses the shared ScrollArea (project rule: never overflow-auto), lists with ringed items use p-1 padding.
| File | Role |
|---|---|
design-screen.tsx |
Screen shell: selection, design language, face, resources, keyboard shortcut, save buttons |
use-draft.ts |
The editing hook: loads/creates the design, registers previews, warnings, save/remove |
use-summary.ts |
Debounced design_structure (layout kind and how text splits) |
per-face.ts |
Style and settings per face: project, updateOnFace, withOwnSettings, hasSettings
|
groups.ts |
Grouping of deck cards by Scryfall card; applyToDeck, removeDesign, beforeDesignOf, usedNumbers
|
card-list.tsx |
Left list with status badges and search |
design-preview.tsx |
Centre: the card image, language selector and face toggle, live artwork dragging |
issues.tsx |
The errors / warnings / information strip under the card, with its hover popover |
live-art.tsx |
The overlay compositor used while dragging artwork |
gestures.ts |
Pure finger gestures on the card (createGestures, gestureChange): one pointer drags, two drag and pinch |
rectangle.ts |
Pure maths of the crop rectangle for a finger (gripAt, dragRect) |
use-visible-height.ts, height.ts
|
The visible height with the on-screen keyboard open (useVisibleHeight, pure visibleHeight, cardHeight, isTextField) |
framing.ts |
Framing maths shared with Rust (moveFraming, artGeometry, layerKey) |
form.tsx |
Right panel, 6 tabs; also exports FrameEditor (reused by collections) |
fine-tuning.tsx |
Fine-tuning controls (FineTuningFields, NO_FINE_TUNING, hasFineTuning) used by the form and collections |
styles.ts |
Built-in styles and pack-specific styles in one selector; nameInLanguage picks a pack name in the interface language |
renumber.ts |
renumber, rebuildThumbnails, setDesignLanguage (change the deck's design language) and completeLanguage (the design_complete_lang job) |
texts.ts |
Label tables (styles, palettes, rarities, layouts) and warningText/isSevere
|
translation.tsx |
"Suggested translation" panel |
collections-dialog.tsx |
Collections manager |
resources-dialog.tsx |
Fonts, frame packs (including downloadable), symbols |
batch-dialog.tsx |
"Design the deck" |
png-dialog.tsx |
"Export images" |
crop-dialog.tsx |
Draw a rectangle on a finished card to use as artwork |
renumber.ts |
renumber, rebuildThumbnails, applyChanged
|
original-frames.ts, downloadable-packs.ts
|
Small zustand stores for download state of "Original" frames and downloadable packs |
src/lib/live-image.ts |
Real-time image loading utilities (also used by Card Editor Dialog) |
There is no dedicated designer store. State is split by lifetime:
| State | Where | Lifetime |
|---|---|---|
The deck (cards, each with an optional design) |
useDeck (src/stores/deck-store.ts) |
The truth; undoable via setCards
|
Which card is being designed (designing), current tab (view), open dialog |
useUi |
App session |
face (face index), onlyThis, collections, packs, symbols, fontsVersion
|
useState in DesignScreen
|
While the view is mounted |
design, original, fingerprint, warnings, loading, saving
|
useDraft |
Per selected card |
| Remembered collection for new drafts |
localStorage key proxybuilder.disenar.coleccion (rememberedCollection/rememberCollection) |
Per machine, wrapped in try/catch |
| Download progress of Original / downloadable packs |
useOriginalFrames, useDownloadablePacks
|
App session |
DesignScreen reads lang straight from deck.settings.designLang (it is not screen state), so what the designer shows is what the PDF prints (see Designer App Layer). The language selector of the preview calls setDesignLanguage(lang) (renumber.ts), the same function as the selector in the export panel: it writes designLang with setSettings, and for any language other than Spanish and English runs completeLanguage (the design_complete_lang job, job type "language": downloads the Japanese/Korean/Chinese font if needed and fetches the printing of every designed card missing that language; see Designer App Layer), then rebuildThumbnails(). When it finishes fontsVersion is bumped; it is part of the resources key, so the preview is requested again (a newly downloaded CJK font changes the image without changing anything else the screen knows about).
groupCards(cards) (groups.ts) groups deck cards by Scryfall id (s:<id>), including tokens and custom cards linked to Scryfall (scryfallIdOf); custom cards linked to a token Scryfall does not have (Cockatrice, externalRefOf) group by that token (e:cockatrice:<id>) and are designable too (CardGroup.linked, designable, also used by the sheet's context menu); blank slots are skipped; custom cards without a link go alone (c:<cardId>) and cannot be designed (disabled row with a tooltip pointing to "Link with a card…"). A design applies to all copies in a group unless "Only this copy (there are N)" is ticked. The copy being edited is the card that ui-store.designing names (its position in the group is copy, which useDraft takes as group.cards[copy]), so a group with several copies shows a "Copy:" row of numbered buttons in the footer to pick one; picking a copy ticks "Only this copy" and asks before discarding unsaved changes. "Remove design" follows the same box (this copy only, or the whole group). The state of a group is that of its first copy (stateOf): unlinked, undesigned, draft, ready (design.status).
flowchart TD
Sel["selected group changes"] --> Has{"main.design?"}
Has -->|yes| Load["design = original = main.design"]
Has -->|no| Draft["call design_draft(card, used, collection)"]
Draft --> Set["design = original = draft.design; warnings = draft.warnings"]
Load --> Edit
Set --> Edit["change(f): setDesign(f(d))"]
Edit --> Reg["effect: call design_register (one in flight, last wins)"]
Edit --> Warn["effect: 400 ms debounce, design_fit_report"]
Edit --> Struct["use-summary: 200 ms debounce, design_structure"]
Reg --> Hash["fingerprint -> pbimg d/fingerprint/width"]
Edit --> Save["save: design_save -> applyToDeck -> setCards"]
Key behaviours (all in use-draft.ts):
-
Turn counter (
turnref): responses from a previous card never overwrite the current one. -
Unsaved draft vs original:
changed = JSON.stringify(design) !== JSON.stringify(original). A fresh draft counts as unchanged ("Discard" returns to it). Choosing another card (list, arrows,Alt+←/→) whilechangedasks aConfirmDialogdialog ("Discard the changes?") with a third, focused button "Save and continue" (alternativeActionofConfirmDialog): it saves throughsaveCard()and then runs the pending move, so there is no cancel, save, repeat dance. If saving fails the dialog stays open (the error was already shown). "Discard" stays in the middle and Cancel on the left; while saving, all three buttons are disabled and the dialog cannot be dismissed. -
Registration for other screens (
stores/editing-store.ts,useEditing): whilechangedis true,DesignScreencallsuseEditing.put({ save })(an effect that clears it withput(null)on cleanup, so it vanishes when the changes are saved or discarded or the screen unmounts).savegoes through a ref to the latestsaveCard, so the registered callback never goes stale. The shell uses it to offer the same "Save and continue" when leaving the Design tab and when closing the app, without knowing how a card is saved (Settings and Shell). - External changes: if the deck's design for this card changes from outside (bulk drafts, undo, renumber, re-thumbnailing) and nothing is unsaved here, the new design is adopted.
-
Real-time registration: every change calls
design_registeras soon as the previous call finishes; if several arrive meanwhile only the last runs (queue.isInFlight/pending). No timer: the preview follows typing and sliders. The response is stored as{ h, de: design };upToDate = fingerprint.de === designtells the preview whether the hash belongs to the design as of now. -
Resources signal:
useDraft(..., resources)takes an opaqueresourcesvalue ({ collections, packs, symbols }); when it changes (collections edited, packs downloaded, symbols fetched) the design is re-registered and warnings recomputed even though the design is identical. -
Warnings (
design_fit_report) wait 400 ms because Rust renders every face to compute them. -
Save (
save(all, ready?)): callsdesign_savewith the deck'sdesignLang, applies the result with onesetCards(applyToDeck(...))so undo works, remembers the design's collection for the next drafts, and resetsdesign/originalto the saved design. Withall = truethe other copies get the same design with their ownbeforepreserved (beforeDesignOf). -
Create variant: the "Create variant" button (
lucide:copy-plusicon, in the footer on the same row as the "Copy:" buttons, shown whenever a card is chosen) runscreateVariantindesign-screen.tsx. If the draft has unsaved changes it first callssave(false)(this copy only) so the variant starts from them; thenduplicate(lib/deck-ops.ts) inserts a copy right after the current one with a new id and the same design, that copy getsmark: "variant"(printed, but left out of deck size, copies and statistics byproxy_core::model::counted), "only this copy" is switched on andui-store.design(id)selects it. The group keeps the same Scryfall id, so the list does not gain a row; the "Copy: 1 2…" buttons appear because the group now has several copies. The footer line with the copy buttons is only shown with more than one copy; the button row is always there. -
Remove: the "Remove design" button (trash icon plus label, in the footer, shown only when the card has a design) calls
remove, which uses the localremoveDesign(cards, ids)(restoresdesign.before) and bumps areloadCountcounter (a dependency of the card-change effect) so the editor asks for a fresh draft instead of keeping the removed design on screen; the Rust commanddesign_removeis registered but not used by the UI.
DesignScreen extras:
- Auto-selects the first designable card when entering with none selected.
-
Alt+←/Alt+→(windowkeydown) move to the previous/next designable group (wrap-around); also the chevron buttons. Both go throughadvanceWithWarning, which asks the discard dialog above when the draft has unsaved changes (they used to calladvancedirectly and dropped the changes silently). With the preferenceui-store.designCopies(box "Also step through copies with the arrows", off by default, remembered), the arrows and "Save and next" go copy by copy instead (neighboringroups.tscomputes the target), and saving applies to the current copy only ("Only this copy" is ticked on entering each copy), so every copy of a card can carry its own design. - "Save and next" saves then
advance(1).advanceis the unguarded move on purpose: it only runs after a successful save, so there is nothing left to ask about. - On entering,
symbols_status({ refresh: false })is called once: the first time it downloads Scryfall mana symbols (needs a connection), then bumpssymbolsso the preview repaints; with 0 loaded it shows a warning toast. - Collections and packs lists are re-read when a dialog opens/closes or when a download finishes (
originalsVersion,downloadablesVersion).
The card shown is whatever Rust paints for the registered hash: <img src={designUrl(fingerprint, width)}>.
-
Resolution: a
ResizeObserveron the frame picks 1000 / 745 / 488 px fromclientWidth × devicePixelRatio(>760, >500, else). -
Burst mode:
useBurst(fingerprint)is true while the hash changes more often than every 250 ms; the URL then asks for at most 488 px so it follows the cursor, and the full resolution comes when the burst ends. -
Never blank:
useLiveImagekeeps showing the last loaded image until the next one has finished loading. -
Controls: the language selector (
LanguagePickerfromsrc/components/language-picker.tsx: the 15 languages with flag and native name), face toggle when the design has more than one face ("Face n" for printed faces, "Part n" for split/adventure parts, usingsummary.printedFaces), and a "Safety margin" switch drawing a dashed rectangle inset 3 mm from each edge (3/63,3/88percentages). -
Incidences strip under the card (
issues.tsx→Issues, always rendered at a fixed height so the preview never jumps when a warning appears or goes away): one counter per level, even at 0 — errors, warnings and information — fromwarningLevel(a)intexts.ts(isSevere= error: text does not fit, missing symbols, missing fonts;noOfficialTextandrulesEdited= information; everything else, where the frame or text degrades, = warning). Hovering (or focusing) a counter opens a popover (PopoverwithPopoverAnchor, controlled, closing 150 ms after the pointer leaves so it can be entered) listing its messages, or "no errors/warnings/information to show" when empty.warningText(a, t)maps eachDesignWarningvariant to translated text (languages by their native name). ThemissingFontserror carries a "Download the fonts" button, which simply selects that language again, socompleteLanguagedownloads the font.
Problem: moving the artwork with a full Rust render per mouse move is too slow. Solution (Decision: render the card once without artwork and move the artwork with CSS):
sequenceDiagram
participant U as Pointer / wheel
participant VP as DesignPreview
participant R as Rust
U->>VP: pointerenter / down / wheel
VP->>R: design_overlay(design, face, lang, width)
R-->>VP: LayerInfo { fingerprint, art[x,y,w,h], radius, face, rotation }
VP->>VP: LiveArt mounts: art img (/b/blob/1000|2000) + overlay img (/c/fingerprint/width)
U->>VP: move (dx, dy) / wheel (zoom)
VP->>VP: moveFraming -> live (CSS, instant)
VP-->>VP: onFraming pushed to design every 100 ms
U->>VP: release / 200 ms after last wheel tick
VP->>R: normal design_register path renders the exact card
How it fits together:
-
layerKey(design, face, lang)(framing.ts) is the JSON of the design with theframingof the artwork being moved (face) nulled; the other parts' framing counts, because a composed card's layer paints them. While the key is unchanged the overlay layer stays valid; on a change of anything else (text, frame, language, the other part's framing) a new layer is requested lazily.requestedref ("<key>|<width>") prevents duplicate requests and discards stale answers. A change ofresourcesclears the layer. - The layer is requested ahead of time, 500 ms after the card stops changing (
LAYER_LEAD_MS), and also onpointerenter,pointerdown,wheeland when the framing changes through the form's sliders (framingKeyeffect). Why ahead of time: before, the first drag waited for the layer, and its first steps went through whole-card renders (noticeable on sagas, whose render is heavier). -
LiveArt(live-art.tsx) is always mounted while a valid layer exists, so both images are already loaded when needed;visibletoggles it. Structure: black rounded container (borderRadiusfromlayer.radiusas percentages) → the artwork<img>inside a box positioned atlayer.art(percentages of the card) withwidth/height/transform: translate(...) rotate(...)computed byartGeometry→ the overlay<img>on top. It reportsonList(true)when both images are loaded. - In a rotated piece (
layer.rotation= ±90: aftermath bottom half, split halves) the artwork goes in an unrotated box the size of the hole as the artwork sees it (unrotatedHole: the hole's sides swapped), centred in the hole and turned with CSSrotate(rotation); the fade extension is not used there. A drag is turned into the piece's frame (dragOnPiece) beforemoveFraming, so the artwork still follows the pointer. A harness check against the Rust render of an aftermath bottom half with zoom, offsets and rotation matched pixel for pixel apart from resampling. -
moveFraming(framing, change, hole)(in mm: hole =layer.art× 63×88 mm, orTYPICAL_HOLE=[0.08, 0.12, 0.84, 0.45]if no layer yet) returns the new framing: zoom clamped to 1–3, offsets in [-1, 1] scaled by the slack on each axis so that the artwork follows the pointer 1:1 until it reaches an edge, regardless of zoom or rotation.artGeometryre-implements the artwork placement used by the engine'spaint_art(same cover-the-hole maths with rotated bounding box); the unit tests in__tests__/framing.test.tspin the geometry in TypeScript only (no cross-language parity test). - While dragging:
live(local framing) is applied instantly;onFramingpushes it to the design at most everyPUSH_MS = 100; on release (orWHEEL_END_MS = 200ms after the last wheel tick)finish()flushes the final value. During the drag the displayed URL is frozen (frozenref) so intermediate Rust renders are not shown;compose = isLive && (live !== null || shown !== exact)keeps the overlay visible until the exact render (designUrl(fingerprint, width)of the up-to-date hash) is on screen. - Plain wheel zooms by ±0.04 per tick (Ctrl+wheel is ignored). Dragging is disabled when the face has no artwork.
-
With fingers (
gestures.ts,design-preview.tsx): the card frame istouch-none, so the browser does not scroll or zoom the page. One finger drags the artwork and two fingers drag and pinch it (zoom). Because a two-finger move delivers onepointermoveper finger, the gesture is not applied per event:gestures.moveonly records where each finger is and the change is taken once per animation frame (gestures.tomar, scheduled withrequestAnimationFrame); counting each event separately made the centre "dance" and shifted the artwork during a straight pinch. When a finger enters or leaves, the measurement restarts from zero so the artwork does not jump. A third finger changes nothing.gestureChangeturns the pixels into the fractionsmoveFramingexpects (movement over the frame size; zoom ascurrentZoom * (scale - 1)). With no hover on touch, the overlay layer is requested onpointerdown, before the drag starts. The result goes through the samelive/onFraming/finishpath as the mouse, so the card keeps the same fingerprint. - The artwork that moves is that of
artFace: the selected part, or part 1 when the selected part has no artwork of its own (summary.ownArt === false: part 2 of a flip or adventure shows part 1's). Faces without artwork, and the meld back, getnulland use the old path (each change repaints through/d/).
| Export | Behaviour |
|---|---|
LatestLoad |
Loads one image at a time; if more arrive meanwhile, only the last is kept; reports busy/idle |
useLiveImage(url) |
Keeps the last successfully loaded URL (shown) until the new one loads; loading flag |
useBurst(value, ms=250) |
true while the value changes faster than every ms
|
useThrottled(value, ms=60) |
Passes a value through at most every ms, always delivering the last |
loadInBrowser |
Default loader (an Image object warms the browser cache) |
Tests: src/lib/__tests__/live-image.test.ts (LatestLoad).
Six tabs in a Tabs component; change(d => d') is the only way to edit the design. All labels go through t() with English source strings.
| Tab | Content |
|---|---|
| Card | Read-only original data (name, cost, type, P/T, rarity, set/number, detected layout via CARD_LAYOUTS), PartList (how the text splits), style selector, variant selector (pack styles with variants), collection selector + "Manage collections…", "Ready to print" switch (status) |
| Texts | Two blocks: the deck's design language and, below it, English (the original); with English as design language, English and Spanish. Each has themed name, the type line (every language except English; edits typeLine of the card data for that language, an empty field goes back to the English line on blur; the placeholder is the English line), flavour text, rules (official text shown read-only; "Write by hand" sets rulesOverride; "Restore the official" clears it); SuggestedTranslation. Texts are read and written with textsFor/withLanguage from src/lib/by-language.ts, because the generated ByLang type only declares es and en (see Frontend Architecture); a language other than Spanish or English shows empty fields rather than the English texts, matching FaceDesign::texts in Rust. "Show flavour text" switch (options.showFlavor); any text may contain emoji, painted in colour by the engine (see Designer-Engine) |
| Art | Upload image / Paste / Scryfall art / Crop from a card; source and size; warning under 900 px width; sliders for zoom (1–3), horizontal/vertical offset (-1..1), rotation (-180..180); "Initial framing" |
| (Texts and Art) | Both tabs start with the part selector (PartSelector) when the design has more than one face: «Face n» / «Part n» plus the face's name, the same state as the preview's selector, so the second artwork of an aftermath or split card is set right where the artwork is edited. In Art, a part without artwork of its own (summary.ownArt === false) shows «This part has no art of its own…» and a «Go to part 1» button instead of the controls. |
| Frame | "Own frame for this card" switch (design.frame), FrameEditor, emblem (collection's / none / own), custom title squeeze |
| Footer | Collection number (typing sets numberManual), rarity letter, set code, artist, credit, universe, year, "original name" placement; empty means "from the collection" (placeholder shows the inherited value) |
| Fine tuning | Own fine-tuning for this card, or the collection's; "Use these settings for the whole collection" |
Details worth knowing:
-
Artwork sources (
ArtTab): "Upload" opens the native file dialog throughopenForImport(src/lib/dialogs.ts), imports it withblob_import_files, thenart_from_blob. "Paste" callsart_from_clipboard(Rust reads the clipboard because WebKitGTK deniesnavigator.clipboard.read()). "Scryfall art" callsart_from_scryfallfor the card'sscryfallIdand current face (disabled for a card Scryfall does not have, such as a Cockatrice token: itsscryfallIdis empty). "Crop from a card…" opensCropDialog. Sliders and the preview drag write the sameframing. -
Styles (
styles.ts): the selector merges built-inSTYLES(Borderless, Extended, Classic, Full art) with the pack's own styles, named withnameInLanguage(names, lang, id): the pack's name in the interface language, else English, else the id (the same for variants). A pack style is stored asstyle(its built-in base, used as fallback if the pack lacks it) +packStyle(its id), and shown as the valuepack:<id>;chooseStyleconverts back.effectivePack(design, collections)= card frame pack, else collection's, else"builtin". Changing the frame pack in the Frame tab clearspackStyleif the new pack lacks it. With nopackStyle,styleValue(style, packStyle, pack)shows the pack's stand-in (PackInfo.substitutes[style]) when the pack lacks the built-in style, so a Balatro card on Classic shows (and draws)joker; the variant selector follows that shown style. After removing a pack in Fonts, frames and symbols, the downloadable list is reloaded, so a removed downloadable pack (Balatro) is offered for download again. -
Frame editor (
FrameEditor, exported and reused by collections): pack selector, colour (auto / one palette colour / gradient / custom hex), legendary crown (auto/on/off), rules box (auto/dark/light/tint). Packs not yet installed appear as "Original (download)" and " (download)"; picking one starts the Rust download with a progress bar and then applies the pack. -
Fine tuning (
fine-tuning.tsx→FineTuningFields): size of title/mana symbols/type/rules/P-T/footer (50–160 %), rules and footer line spacing (70–160 %), per-element vertical offset in mm (-3..3), own radius for the artwork window and for the card corners. A 100 % size is stored asundefined; for rules,rulesSize === undefinedmeans "automatic" (the toggle "Rules: automatic size").hasFineTuningreports whether anything differs fromNO_FINE_TUNING. "Own settings for this card" copies the collection's fine tuning as a starting point. Under "Rules box": "Rules box height" (-10..10 mm in 0.5 steps; 0 = as the frame, stored asundefined) and "Height follows the text", a three-waySelectField(heightModeOf/BoxHeight: "By frame" =undefined, "Dynamic" =true, "Fixed" =false) that writesrulesBoxDynamic. In the frame editor (FrameEditor) the custom-tint box colour comes with a "Tint opacity" slider (SliderRow), the only rules-box opacity control (fine tuning used to have a second one, "more opaque rules box background", which was removed because it did the same): the native colour input has no alpha, so the opacity is stored as the alpha pair of an 8-digit hex (opacityOf/alphaHex) and preserved when the colour changes. Under the art: a "Custom art fade" switch that storesartFade: 12, artFadeExtension: 7(the extended frame's values) and shows the sliders "Art fade" (0–25 mm) and "Fade extension" (0–35 mm); switching it off clears both.hasFineTuningalso countsartFade,artFadeExtension,rulesBoxHeightandrulesBoxDynamic. -
Pass to collection:
SettingsTab.moveToCollectionsaves the card's fine tuning into its collection (collection_save), clears the card's own, and callsrebuildThumbnails()so other cards' thumbnails update. -
Style and settings per face (
per-face.ts,FaceSettingsinform.tsx): on cards with two printed faces (summary.printedFaces > 1) the Card, Frame and Fine tuning tabs start with the face selector and, from face 2 on, a switch "Style and settings of its own for this face". Off, the face follows the card (face 1) and the tab is shown dimmed and not editable; on,withOwnSettingsgives it a copy of the card's style, variant, frame, emblem and options (faces[i].settings). The tabs know nothing about faces: they receive the projected design (project(design, face)) and achangewrapped byupdateOnFace, which sends what changes in style, frame, emblem and options to the face'ssettingsand everything else (collection, status) to the card. Footer, texts and artwork keep their own per-face or per-card logic. Tests in__tests__/per-face.test.ts. -
Suggested translation (
translation.tsx): works on the deck's design language. Hidden for English and for the languages without printed cards (language(lang).has_printed_cardsfalse); otherwise shown only when that language has no official text (lacksTextIn(card, lang)fromby-language.ts) or its type line equals the English one. "Search official phrases" callsdesign_suggest_translation(design, face, lang)(slow: one Scryfall search per sentence); the result shows found sentences (translated, green) vs. left in English (amber), with "Use" for the type line and "Use as rules in {language}" (setsrulesOverrideon that language's text). The response is dropped if the card/face changed meanwhile (currentKeyref).
DesignScreen is one screen that changes with useFormFactor() (Mobile); the desktop layout above is untouched.
-
Tablet (
size === "tablet" && isTouch, or a phone:listInSheet): three panels do not fit, so the card list moves into a sheet (Sheet, opened by a "Cards of the deck" button in the toolbar) and the panels are two (proxybuilder.paneles.disenar2). With touch the toolbar may wrap onto several rows, and touch targets are 44 px; the «i» ofWithHelpnext to the toolbar's bigger buttons is bigger too (helpClassName={LARGE_HELP}). Why only with touch: a desktop window of 960–1023 px with a mouse istabletby width, and it keeps the three-panel layout it always had. -
Phone: the same form and the same options as on desktop, arranged differently. Upright: a bar (previous card, the current card's name and the deck's, which open the card list as a bottom sheet, next card, the save indicator and a "..."), the live card (
DesignPreviewwithcompact), thenFormand a footer with discard and save. The card takes 44 % of the visible height, 22 % while a field is being typed in, so the field fits above the keyboard. On its side: the card at full height in its own column (cardColumnWidth, the card's width plus room for its controls) and the bar, the form and the footer on the right. Why: every stacked row costs height, and with about 360 dp on its side the previous arrangement left no room for the card at all. Both orientations are one grid, not two trees: otherwise rotating the phone remounted the form and went back to its first tab. The footer hides while the keyboard is open (data-keyboard), and on its side the bar and the tabs too, so what is being typed stays visible. -
DesignPreviewwithcompact: no rows above or below the card. What desktop keeps there floats beside it, in the space the card's proportion leaves free (CARD_CONTROLSon each side): the design language (LanguagePickerwithflagOnly) and the faces or parts on the left, the safety margin and the warnings on the right (Issueswithcompact: in a column, and only the levels that have something). The card's height is what this buys. -
The "..." sheet (
MenuSheet, "Card options"): the copies, «Create variant» and «Remove design», and below them what desktop has in the toolbar: «Renumber», «Design the deck», «Export images», «Collections» and «Fonts, frames and symbols». Those four dialogs open as they are on any format; «Collections» is list then editor on a phone (SectionBar, which replaces the title in the editor, andbackOnEscapefor Back), since the two columns do not fit. The six tabs share one row: each measures what its text does (TAB_CLASSES) and a long label wraps. -
Keyboard.
useVisibleHeight(mobile)measures the visible height fromvisualViewport(the WebView does not shrink100%ordvh;visibleHeightis the pure maths) and whether a field is being typed in; the screen's box is cut to that height and the focused field is scrolled into view once the keyboard is up. Moving from one field to another does not shrink and stretch the card (a short delay absorbs the focus change). -
Incidences (
issues.tsx): with a finger or a pen the counters open their popover with a tap, as there is no hover, and it stays open while read; with the mouse, entering and leaving still open and close it (withMouse). -
Cropping artwork (
crop-dialog.tsx,rectangle.ts): with a finger or a pen, the rectangle is grabbed by the corner nearest to the finger (radii in px, as a finger covers more than a mouse), by its inside to move it or by the outside to draw a new one, and a second finger does not change what the first one grabbed; corner handles are bigger with touch. With the mouse it is as always: every press draws a new zone (mouse→grip = "new"). All in fractions of the card. - Leaving with an unsaved card: on a phone the card is saved and then the screen changes; there is no "discard" question (Settings and Shell). Android's back button from Design returns to Deck.
Tests: __tests__/gestures.test.ts, rectangle.test.ts and height.test.ts (pure logic only).
| Dialog | File | Commands | Notes |
|---|---|---|---|
| Collections | collections-dialog.tsx |
collection_list/save/delete, fonts_list, packs_list, blob_import_files
|
Sidebar list with per-row menu (duplicate, delete); editor sections General, Frame, Emblem, Fonts (title/rules family, weights 400–900), Footer (set code, rarity letter, artist, credit, universe, year, Spanish and English footer templates plus one for the deck's design language when it is another ("Footer template ({language})", written with withLanguage), with tokens {num} {rarity} {original} {set} {lang} {artist} {credit} {universe} {year} {brush} {star}, tab = column, newline = row, text after {>} right-aligned), Fine tuning. Closing with unsaved changes asks for confirmation (unsavedChanges). On close, if anything was saved or deleted, rebuildThumbnails() runs. |
| Fonts, frames and symbols | resources-dialog.tsx |
fonts_list/import/remove, fonts_free_list, font_free_download, packs_list/import/remove, original_*, packs_downloadable_*, pack_extra_use, symbols_status
|
Tabs Fonts / Frame packs / Symbols. Imports .ttf/.otf, pack from folder or .zip; free OFL fonts catalogue with PNG samples from src/assets/fonts/; downloadable pack rows with a "Contents" panel whose extras (backs, tokens, basic lands, finished cards) can be set as the deck back (useDeck.apply({ defaultBack })) or inserted as a custom card (customCard + insert). On close, rebuildThumbnails() if anything changed. |
| Design the deck | batch-dialog.tsx |
design_drafts_for_deck, job_cancel, events design://progress/done
|
Scope all/selection, collection selector, progress bar, cancel. Results collected and applied to the deck in one setCards even when cancelled. Network/rate-limit errors abort; per-card failures are counted and reported. |
| Export images | png-dialog.tsx |
design_export_png, design_complete_lang (via completeLanguage), job_cancel, events designpng://progress/done
|
300/600/900 dpi; "Languages": a checkbox per language of the 15 (flag + native name), the deck's design language ticked by default; folder via chooseExportFolder. Before exporting, each chosen language other than Spanish and English is completed on the chosen cards, then thumbnails are redone, because Rust paints whatever data the design has. Languages are sent in table order; each lands in a folder named by its code. Copies export once. |
| Crop artwork | crop-dialog.tsx |
art_from_card |
Lists deck cards that have an image and are not already designed, one per blob; drag a rectangle (initial guess x .08, y .11, w .84, h .45); must be at least 5 % per side; the result is a PNG blob. |
All long jobs use runJob (src/lib/jobs.ts): it subscribes to the progress and done events before launching so a fast job cannot lose its final event, and buffers events until the jobId is known.
-
renumber(t, message)→design_renumber→applyChanged(one history step) and an announcement ("N cards renumbered" / "Numbering already up to date"). -
rebuildThumbnails()→design_rerender→useDeck.refrescarCartas(before, new): replaces only cards that are still identical to what was sent, marks the deck dirty without a history entry (it is not a user edit; if the user changed the card meanwhile their change wins). Called when a deck opens (src/features/shell/use-initial-deck.ts) and when the collections/resources dialogs close, and after "pass to collection". Errors are swallowed (it will retry next time).
Rules from the project: all text through t("English source string") (equal English texts that mean different things are told apart with a ##context suffix on the key, which is not shown); each language's translation in src/i18n/<code>/design.json (an object keyed by the English string; Spanish is a translation like the others); label tables that live outside components use markForTranslation("…") (a no-op marker so pnpm i18n sees the literal) and are translated with t() where rendered (texts.ts, WEIGHTS, EXTRA_TYPES). pnpm i18n (scripts/check-translations.mjs) fails when a requested string is missing, and a string must not appear in two area files. Rust never writes user prose: warnings arrive as DesignWarning variants and are turned into text by warningText; errors by useLang().message(e). See Internationalization.
| File | Covers |
|---|---|
src/features/design/__tests__/framing.test.ts |
moveFraming (1:1 following, bounds, zoom 1–3), layerKey (ignores framing only), artGeometry (centered, edges, aspect-only, 90° rotation), unrotatedHole and dragOnPiece (rotated pieces) |
.../styles.test.ts |
built-in + pack styles in one selector; chooseStyle
|
.../groups.test.ts |
scryfallIdOf, groupCards (also Cockatrice tokens), stateOf, beforeDesignOf, usedNumbers, applyToDeck, removeDesign
|
.../renumber.test.ts |
applyChanged, renumber, rebuildThumbnails (errors, concurrent edits) |
.../texts.test.ts |
every DesignWarning variant has text, languages named by their native name (missingFonts, rulesEdited, missingName), isSevere, unique layout names |
src/lib/__tests__/live-image.test.ts |
LatestLoad |
There are no component tests for the form or the preview; the live behaviour is checked by running the app. Run with pnpm check (Testing and CI).
- Do not compute card geometry in the screen. The only geometry here is artwork placement during a drag, and it deliberately mirrors the engine's own computation; a final Rust render always replaces it.
-
design/originalcomparison isJSON.stringify, so key order matters: always spread existing objects rather than rebuilding them. -
useDraft's effects intentionally omit some dependencies (they key on card id/group key); adding them would reload the draft on every deck change. - Per-face state:
faceresets to 0 when the selected group changes. In split/aftermath layouts the "faces" are parts of one printed face (printedFaces === 1, the selector says "Part N"); each part still has its own artwork, so the Art tab with "Part 2" selected sets the art of an aftermath card's bottom half, and its "Scryfall art" button fetches only the second half's illustration (art_from_scryfallwithface = 1, see Designer-App-Layer). - A
fingerprintfrom before the latest edit may arrive late; always checkupToDatebefore treating it as exact. -
WithTooltipinstead of nativetitle=(checked bypnpm check:title); modals are fully opaque.
- New form field: add the field to the Rust model (
CardDesign/DesignOptions/FooterOptions,#[derive(TS)]), regenerate bindings (pnpm bindings), add a control in the rightTab…function usingchange, make sure the engine reads it (otherwise the hash will not change visibly), write the English source strings and add their translation to every language'sdesign.json(pnpm i18nfails otherwise). - New dialog: add a
DialogNamekind inui-store.ts, mount it insrc/App.tsx, reuserunJobfor jobs. - New warning: add the
DesignWarningvariant in Rust, a case inwarningText(Inferred: theswitchhas nodefault, so the compiler should flag the missing case), and a test line intexts.test.ts.
On a phone the form rows put the label above the control: Row of src/components/fields.tsx with stackOnMobile.
Use and build · Uso y desarrollo
- User-Guide · Guía de usuario
- Development-Setup · Preparación del entorno de desarrollo
- Testing-and-CI · Tests y CI
- Releases-and-Auto-Updates · Versiones y actualizaciones automáticas
- Conventions · Convenciones
- Rename-to-Tapete · Cambio de nombre a Tapete
- License · Licencia
Architecture · Arquitectura
- Architecture · Arquitectura
- IPC-and-Error-Handling · IPC y manejo de errores
- Rust-App-Layer · Capa de aplicación Rust
Data · Datos
- Deck-Model · Modelo del mazo
- Storage-and-Blobs · Almacenamiento y blobs
- Deck-Package-Format · Formato del paquete de mazo
- Deck-Library · Biblioteca de mazos
Getting cards · Conseguir cartas
- Decklist-Parsing · Parseo de la lista del mazo
- Scryfall-Integration · Integración con Scryfall
- External-Sources · Fuentes externas
- Card-Identification-and-OCR · Identificación de cartas y OCR
- Identify-From-a-Photo · Identificar por foto
Layout, images, PDF · Maquetación, imagen y PDF
- Layout-Engine · Motor de maquetación
- Imaging-and-PDF · Imagen y PDF
- Export · Exportación
- The-Card-Stamp · El sello de las cartas
- Live-Preview · Vista previa en vivo
- Statistics · Estadísticas
Card designer · Diseñador de cartas
- Designer-Overview · Visión general del diseñador
- Designer-Engine · Motor del diseñador
- Designer-Composition · Composición del diseñador
- Frame-Packs · Packs de marcos
- Designer-App-Layer · Capa de aplicación del diseñador
- Designer-UI · Interfaz del diseñador
- Card-Editor-Dialog · Diálogo Editar carta
Game table · Mesa de juego
- Game-Engine · Motor de la mesa
- Game-Table · Mesa de juego
- Online-Play · Juego en línea
- Friends-and-Messages · Amigos y mensajes
Mobile · Móvil
Frontend · Frontend
- Frontend-Architecture · Arquitectura del frontend
- State-Stores · Stores de estado
- Internationalization · Internacionalización
- Themes-and-Skins · Temas y skins
- Icons · Iconos
- Settings-and-Shell · Ajustes y shell
- Tutorials · Tutoriales
- Decklist-Panel · Panel de la lista del mazo
- Add-Card-and-Variants · Añadir carta y variantes
- Card-Search · Búsqueda de cartas
- Set-Browser · Explorador de sets
Reference · Referencia