Craft

Script cards

A script that players can see is named on the loading line while it runs ("Running: Buy From Shop"), like the GM's other tools, and what it decided reaches players in the story. Give the script a card(result, input) function and it also shows a card in the story where it ran: an attack that reads as a roll, a shop with tiles and Buy buttons, a level-up with points to spend. A card's buttons can run the script's actions, which change the game's files straight away, without a GM turn.

Cards show on the game screen and in the script editor's test run.

You don't need to write the code yourself. Ask Orbit for the card you want ("a shop card where players buy from the blacksmith with their gold") and it writes the script, tests it and tells you how it looks.

Drawing a card

card(result, input) returns the card's root element. Each element has a type, props and, for a container, children: the elements inside it, in order. A child that is null or false is left out, so result.crit && { type: "Badge", … } adds the badge only on a crit. To give the card a starting state, return { root, state } with the element as root (see "The card's own state" below).

export default defineScript({
  description: "Rolls the loot in a defeated foe's pockets.",
  beforeNarrationTrigger: "The party searches a defeated foe.",
  visibility: "player",
  input: { tier: { type: "integer", minimum: 1, maximum: 3, default: 1 } },
  run({ tier }) {
    const gold = tier * (1 + Math.floor(Math.random() * 10));
    return { gold, items: tier > 1 ? ["Silver ring", "Map scrap"] : ["Lint"] };
  },
  card(result) {
    return {
      type: "Frame",
      props: { eyebrow: "Loot", title: "The bandit's pockets", icon: "bag" },
      children: [
        { type: "Currency", props: { amounts: [{ amount: result.gold, unit: "gp" }] } },
        { type: "Tags", props: { items: result.items } },
      ],
    };
  },
});

A card can also be written flat, in a file type layout's format (the layout spec): { root, elements, state }, with every element under a key of its own and children listing keys. Both draw the same card. Nested needs no keys, so write new cards nested.

  • card runs after the script's run succeeds, with what it returned and its input (defaults filled in). It gets no game and changes nothing: it only draws.
  • A script shows its card unless it is GM-only (visibility: "gm"): a GM-only script's card is never sent to players.
  • Return null (or nothing) for no card.
  • The GM never sees the card. It reads what the script returned, so return readable values the GM can tell the story from ("A pack of wolves", not a row number).
  • Write values straight from result. A prop can also bind { "$state": "/result/gold" }, and repeat works over a list in the result.
  • The card is saved with the turn, so reading back shows the card players saw, even after the script is edited.
  • Only the script the GM ran draws a card. A script it calls by name draws none.

What a card can use

The card components below are made for a moment in play, drawn on the story's dark panel. Prefer them to the layout components. A card can also use any layout component except these, which look files up, pick among them or hold sections: Include, SectionSwitch, FileReferenceGrid, PageReferenceGrid, ReferenceValue, TurnTracker, Select, VoiceSelect. To show the world's files, use FileTiles.

A layout component takes the same props in a card as in a file type's layout, with its values of more than one word written in snake_case like the rest of a script: Stack's, Grid's and Card's bgImageFit is "tile_x" or "tile_y" in a card, where a layout writes "tile-x" and "tile-y".

Every card component takes tone, from one list, so a colour means the same thing in every world: neutral, success, failure, critical, fumble, partial, info, magic. success is emerald, failure rose, critical gold, fumble red, partial amber, info sky and magic violet. The tables below write this type as Tone.

icon is one of these names, or any short text such as an emoji: sword, swords, shield, heart, skull, coins, scroll, sparkles, flame, snowflake, droplet, dice, key, lock, eye, moon, sun, tent, crown, gem, flask, book, target, zap, trophy, users, user, map, compass, wand, star, check, x, hourglass, footprints, hammer, cpu, brain, vote, bag, feather, ghost, leaf, anchor, castle, music, message, alert, info, plus, minus, arrow.

A die's color (in Dice, Roll and Roster) is one of red, orange, gold, green, teal, blue, violet, pink.

Limits

What Limit
A card's size, as card returns it 32 KB
Elements in one card 200
Files across a card's tiles 100
Actions one script declares 20
A card's starting state 4 KB
Files a card reads live (files) 10
Bindings one press runs in a chain 5
A tile's detail or badge 80 characters
A tile button's label or reason 60 characters
A drop target's reason 200 characters

card runs inside the script's own time limit.

A card's size and element count depend on the run's data, so the limits are met only when a run draws the card. The test run shows how close a drawn card came ("12.3 of 32 KB, 85 of 200 elements"): test the run with the largest input you expect, and keep room under both. A card whose written-out parts alone come near a limit, before any data, gets a warning in the script editor.

When a card is wrong

The component names and prop values a card writes out are checked with the rest of the script, like a syntax error: a bad one is a problem in the script. Values worked out while it runs are checked when it runs. A card that is wrong, or that throws, never fails the run: what the script did still counts, players see no card, and the test run says why.

A press is different. When an action works but the card it draws next is wrong (over a limit, or a bad value), the press fails and saves nothing, so players never see an old card over changes it doesn't show. The player who pressed is told only that the card hit a problem; someone who can edit the world is told why ("the card is 34.7 KB; a card can be at most 32 KB").

To check a card, open the script and run it from the Test tab under the code.

File tiles

To show the world's own files (items found, wares for sale, people in the room, monsters met), use FileTiles. Each tile is the file's picture and name, and a tap opens the file. The script's run looks the files up and returns their $ids. Craft fills in each name and picture after the run, from this world or game only, and leaves out any file that isn't there.

export default defineScript({
  description: "Finds what's in a chest: some of the world's own items.",
  beforeNarrationTrigger: "The party opens a chest.",
  visibility: "player",
  async run(input, { game }) {
    const LOOT = ["silver-ring", "map-scrap", "rusted-key", "tallow-candle"];
    const picks = LOOT.filter(() => Math.random() < 0.5);
    const items = await game.files("Item").getMany(picks);
    return { found: items.filter(Boolean).map((item) => ({ id: item.$id, name: item.$name })) };
  },
  card(result) {
    return {
      type: "FileTiles",
      props: { files: result.found.map((item) => item.id), size: "md", emptyText: "Empty." },
    };
  },
});
  • A tile can be { file, detail, badge, button, drag }: detail is a line under the name (a price, a requirement), badge sits on the picture ("2 left", "Taken"), and button is { label, press, disabled, reason, variant }. Its press runs like a Button's on.press: one binding or a chain of up to 5, each one of the script's actions or the card's own setState, pushState or removeState. drag makes the tile something to pick up (see Drag and drop). detail and badge can be at most 80 characters, a button's label and reason at most 60; a tile past them stops the card drawing, so players see the default card.
  • selected marks tiles as picked: a file's id or a list of them, usually bound to the card's state (selected: { $state: "/picks/ring" }). With a tile button that sets that pick, one FileTiles is a whole tap-to-choose strip.
  • layout is "grid" (the default), "list" (a row per file with its button at the end, good for comparing prices) or "row" (one line that scrolls sideways, so the story stays in view). size is "xs" (icon sized, an inventory strip), "sm", "md" or "lg". face: "image" draws only the pictures, every tile the same height, with the name on hover and read aloud.
  • For more than about 12 tiles, set shown: 8 and a moreLabel such as "Browse all wares". The card shows 8 tiles and a button that opens all of them in a window players can scroll and search.
  • List files by $id, not as whole files: the card's size counts what card returns.
  • A tile also takes a file the current state or a reference field names: a person's file (person.file, from game.currentState.get()), its referenceId, or a file's $referenceId. There's no need to get() each one first.
  • Prefer tiles with buttons to a Button per row. A list of 25 rows of Buttons and Text reaches the element limit.

Drag and drop

Any element of a card can be picked up and dropped on another: a satchel's herbs onto a recipe's slots, a gem into a setting, glyphs into a formula, cards into a hand. Players drag with a mouse or a finger, or tap the thing and then tap where it goes (on a phone a finger holds still a moment before it drags, so swiping still scrolls the story). Keyboards work too: Enter picks up and Enter drops.

  • Something to drag gets drag: { kind, data } beside its props. kind is a word for what it is ("material", "glyph"); data is what it carries, any values the drop will need. disabled: true (or a value bound to the card's state) stops it being picked up. A file tile takes drag too, and always carries its file in data as $id, $name, $image and $type.
  • Somewhere to drop is an element with on: { drop: … }: what a drop on it runs, the same bindings a Button's on.press takes (one of the script's actions, or the card's own state actions; a chain of up to 5).
  • What it takes is drop: { kind, accepts, reason }. kind names the kinds it takes (one, or a list); a target that doesn't take what is picked up stays as it is. accepts is a condition, written as visible writes one; reason says why it refuses when accepts fails, and can name what was dragged ("${/drag/data/$name} isn't a strainer").
  • While something is picked up the card's state has it at /drag: { kind, data }. Conditions read it ({ "$state": "/drag/data/material", eq: "willow-bark" }), and so do a drop's params ({ "$state": "/drag/data/$id" }). A card that drags can't write /drag itself.
  • Every target works out accepts as soon as something is picked up, in the player's browser: those that would take it light up, those that wouldn't dim, and a drop on one that wouldn't shakes it and shows the reason. Nothing reaches the game until a drop lands, and an action a drop runs still checks again on the server, as a press does.
  • A drop that lands pops its target, and a drop or a Button whose action is refused shakes, with nothing to write. Players who ask for less motion see a short glow instead.
card(result) {
  return {
    root: {
      type: "Frame",
      props: { title: "Willow-bark draught", icon: "flask" },
      children: [
        {
          type: "Slot",
          props: {
            label: "Extract source",
            hint: "Drop a herb",
            shape: "diamond",
            title: { $state: "/picks/extract/$name" },
            image: { $state: "/picks/extract/$image" },
          },
          drop: {
            kind: "material",
            accepts: { $state: "/drag/data/material", eq: "willow-bark" },
            reason: "${/drag/data/$name} can't be the extract",
          },
          on: { drop: { action: "setState", params: { statePath: "/picks/extract", value: { $state: "/drag/data" } } } },
        },
        {
          type: "FileTiles",
          props: {
            size: "xs",
            face: "image",
            files: result.satchel.map((batch) => ({
              file: batch.$id,
              badge: `×${batch.count}`,
              drag: { kind: "material", data: { material: batch.material } },
            })),
          },
        },
        {
          type: "Button",
          props: { label: "Begin the work", variant: "default" },
          on: { press: { action: "brew", params: { extract: { $state: "/picks/extract/$id" } } } },
        },
      ],
    },
    state: { picks: {} },
  };
},

Slot is made for this: a socket with an empty look (a dashed outline and a hint) and a filled one (the thing's picture and name), labelled by its role. Bind its title and image to what was dropped and it fills as the player plays, before anything is sent.

Motion

Every component takes className, and the motion classes below always work there. Anything else may or may not: a card only gets the classes Craft itself ships. Tailwind can't build a class while the game runs, so write a listed number instead of an arbitrary value: duration-2500, scale-115 and delay-650 work, duration-[2500ms] doesn't.

Classes What they do
animate-in with fade-in, zoom-in-50 … zoom-in-150, slide-in-from-bottom (or top, left, right; alone for its full height, or -1, -2, -4, -8, -12, -16, -full), spin-in-90, blur-in Comes in once as the card first shows
animate-out with fade-out, zoom-out-95, slide-out-to-right-full, spin-out-90, blur-out, and fill-mode-forwards Leaves once, and stays gone with fill-mode-forwards
delay-0 … delay-3000 (steps of 50) with fill-mode-backwards Waits that many milliseconds first; fill-mode-backwards keeps it hidden until then
duration-0 … duration-3000 (steps of 50 to 1000, then 100), ease-linear, ease-in, ease-out, ease-in-out How long an entrance, exit or transition takes, and its pace
repeat-1 … repeat-3, repeat-infinite, direction-alternate An entrance or exit played more than once, or back and forth
animate-pulse, animate-ping, animate-bounce, animate-spin, animate-spin-slow, animate-wiggle, animate-float Over and over while it shows
transition, transition-all, transition-transform, transition-opacity, transition-colors, transition-shadow A class that changes eases in instead of snapping
scale-0 … scale-200, rotate-* and -rotate-* (1, 2, 3, 6, 12, 45, 90, 180), translate-x-* / translate-y-* and negatives (0.5, 1, 2, 4, 8), brightness-50 … brightness-200, shadow-xs … shadow-2xl, opacity-0 … opacity-100, origin-* Size, turn, nudge, light, lift and fade
Any of the row above after hover:, active:, focus-visible:, group-hover: or group-active: Answers the pointer: under it, pressed, focused from the keyboard, or anywhere over an ancestor marked group
perspective-near … perspective-distant, transform-3d, backface-hidden, rotate-x-* / rotate-y-* (0, 12, 45, 90, 180) 3D, for a card flip
drop-shadow-sm … drop-shadow-2xl, blur-xs … blur-lg, saturate-0 … saturate-200, hue-rotate-15 … hue-rotate-180, grayscale, sepia, each also after hover: or group-hover:; shadow- and drop-shadow- in amber, yellow, violet, sky, emerald, rose or red at 400 or 500 Glows and tints, for a rarity or a lit rune
  • A reveal in turn. Give a result's parts the same entrance and rising delays, and they show one after another: className: "animate-in fade-in slide-in-from-bottom-2 fill-mode-backwards delay-900". Without fill-mode-backwards a part shows, then jumps back to start when its delay ends.
  • A cut-in. Slide a banner in, hold it, and send it off, then show what happened. One element can't come in and leave, so the leaving goes on a Stack around it: the outer Stack "absolute inset-0 z-10 pointer-events-none animate-out fade-out slide-out-to-right-full duration-300 delay-2100 fill-mode-forwards", the banner inside it "animate-in fade-in slide-in-from-left-full duration-300", and the result after them with delay-2400 fill-mode-backwards.
  • Answering the pointer. Put transition beside the hover and press classes, or they snap: a Button with "transition duration-150 hover:scale-105 active:scale-95". Mark a tile group and its parts can move with it: a title with "transition-transform group-hover:translate-x-1". It all happens on the player's screen, with no wait on the server.
  • Changing with the card's state. Bind the class to the card's state, so an empty slot pulses only while it is empty: className: { $cond: { $state: "/picks/extract", not: true }, $then: "animate-pulse", $else: "" }. The element isn't drawn again, only its class changes, so with transition a change of state eases. A flip is a Stack with perspective-distant holding one with relative h-28 transform-3d transition-transform duration-700, whose class adds rotate-y-180 while /flipped is set; inside it two faces, each absolute inset-0 backface-hidden, the back one also rotate-y-180.
  • When it plays. A card's motion starts when the player can see it. A card that waits for its moment on the map (the dice to land, the hit to show) stays out of sight until then, and its entrance starts as it shows, not when the turn arrived.
  • When a card is read back it shows as it ends up: entrances shown, what left gone, loops still. Players who ask for less motion see it that way too, and its transitions snap. Nothing to write for either.
  • A drop or a Button that is refused already shakes, and a drop that lands pops (drag and drop).

Actions

A card's Buttons can change the game. Declare actions on the script, and give a Button an on.press that names one. The binding goes on the element, beside type and props, never inside props.

export default defineScript({
  description: "Opens the fence's stall: a few pieces for sale.",
  beforeNarrationTrigger: "The party browses a fence's stall.",
  visibility: "player",
  waitsForPlayer: true,
  async run(input, { game }) {
    const ring = await game.files("Item").get("silver-ring");
    return { stock: ring ? [{ id: ring.$id, name: ring.$name, price: 15 }] : [], sold: [] };
  },
  card(result) {
    const files = result.stock.map((item) => {
      const sold = result.sold.includes(item.id);
      return {
        file: item.id,
        detail: item.price + " gp",
        button: {
          label: "Buy",
          press: { action: "buy", params: { item: item.id }, confirm: { title: "Buy " + item.name + "?", message: item.price + " gp" } },
          disabled: sold,
          reason: sold ? "Sold" : undefined,
        },
      };
    });
    return { type: "FileTiles", props: { files, size: "md", emptyText: "Nothing left." } };
  },
  actions: {
    buy: {
      input: { item: { type: "string" } },
      async run({ item }, { game, result }) {
        const offer = result.stock.find((piece) => piece.id === item);
        if (!offer || result.sold.includes(item)) throw new Error("That's gone.");
        const me = await game.playerCharacter();
        if (!me) throw new Error("Join the game to buy.");
        if ((me.gold ?? 0) < offer.price) throw new Error("You need " + offer.price + " gp.");
        await me.update({ gold: me.gold - offer.price });
        return { ...result, sold: [...result.sold, item] };
      },
    },
  },
});
  • Actions need card and visibility: "player". An action is { input, run, startsTurn }, with input written like the script's own. It can't be named setState, pushState, removeState, validateForm.
  • A press runs the action on the server with the press's params as its input. Its run gets { game, result }: the game's files, and what the card was last drawn from (read-only).
  • It returns the card's next result, or nothing to keep the card as it is. The card is drawn again from it, with the script's first input, for every player at once.
  • game.playerCharacter() is the character of whoever pressed. It is null when there is no one, so check it.
  • To refuse, throw an Error with words for the player ("You need 15 gp; you have 4."). The card shows them under the Button, and nothing changes. A mistake in the script (a TypeError, a game call it got wrong, a card() that can't draw the result, running out of time) changes nothing either. Someone who can edit the world reads what went wrong under the Button, with the line; other players read only that the script hit a problem. Only a thrown Error reads as the card saying no.
  • An action reads the game's current state as the GM's last turn left it (game.currentState.get(), game.currentLocation(), a roll by someone there), but changes files, never the current state. Moving people, the time and trackers stay the GM's.
  • At the start of the next turn the GM is told each press (the card, the action, its input and the card's new result), then what it changed in the files, already applied. Actions that change no file, like a vote, reach it the same way.
  • Every player sees the same card. When one player's press changes it (a starter claimed), every player's copy redraws. Of two presses at the same moment, one saves first and the other runs again on the card it left, so the action can say "Someone took that".
  • A player can press about 20 times in a row, then once a second.

Trusting a press

A player can send any params, and a card stays live as long as its message does. Write every action to check for itself:

  • Take prices, stock and limits from result and the files, never from the params.
  • disabled only greys a Button out. Re-check every rule in the action: sold out, already taken, closed, full health.
  • Only Buttons (and tile buttons) the card draws from its root can run an action. An element left in elements that nothing shows runs nothing.
  • Players can scroll back and press an old card. Keep a flag in the result (taken, closed, applied), refuse once it is set, and draw a smaller card then ("Learned Spherewright Focus").
  • Re-read the sheet in the action instead of trusting numbers copied into the result: the GM may have changed them since. To show those numbers, read them live from the file (live values from files) rather than copying them into the result.
  • Keep rules (prices, recipes, DCs) in constants in the script, not in the result, so a fix to the script reaches cards already drawn. A press runs the script as it is now, even renamed: it keeps the file the card came from.
  • The result is shared by every player. Record who did what in it by id and name ({ by: me.$id, name: me.$name }), and keep a log to its last few entries.
  • To add to a list on a file, find the entry for the same thing and raise its quantity rather than adding a second entry.

Starting the GM's turn

Most presses don't start a turn: players buy as often as they like, then tell the GM what they do in their own words. For a pick that moves the story on (a path to take, a cost to pay, a side to join), add startsTurn: true to the action:

actions: {
  choose: {
    input: { path: { type: "string" } },
    startsTurn: true,
    run({ path }, { result }) {
      if (result.chosen) throw new Error("The party already chose.");
      return { ...result, chosen: path };
    },
  },
},
  • Once a press of it works, the GM's next turn starts with the Button's label as the player's words, so write labels that read as what the player does ("Take the left path"). A tile's button sends its label and the file's name.
  • A Confirm whose label says nothing of the pick takes the Button prop turn, the words to send instead: turn: { $template: "I take ${/picks/label}" }.
  • The turn starts only while the card is the newest thing in the story, and only for the first such press on it. Later presses, presses on an older card and presses while a turn is running still run their action but start nothing, so close the choice once it is made.
  • Pair it with waitsForPlayer: true on the script, so the GM stops at the card (defining a script).

The card's own state

Picks a player makes before confirming (stat points, two skills of five, how many torches) live in the card's own state, in their browser. Return the card as root with its starting state beside it, bind controls to the state, and have a Button send it:

return {
  root: {
    type: "Frame",
    props: { title: "Spend 2 points" },
    children: [
      { type: "Stepper", props: { label: "STR", value: { $state: "/picks/str" }, max: 2 } },
      { type: "Stepper", props: { label: "DEX", value: { $state: "/picks/dex" }, max: 2 } },
      {
        type: "Button",
        props: { label: "Confirm", variant: "default" },
        on: { press: { action: "spend", params: { str: { $state: "/picks/str" }, dex: { $state: "/picks/dex" } } } },
      },
    ],
  },
  state: { picks: { str: 0, dex: 0 } },
};
  • Bind a Stepper or a Toggle to a pick. A Stepper stays within its min and max.
  • Seed every pick the card reads. A $state param with no value is left out of the input.
  • The card also reads /result (what it was drawn from) and /viewer (the id of the character looking). Its state can't set either.
  • setState { statePath, value }, pushState { statePath, value } and removeState { statePath, index } change only the card's state.
  • press can be a list of bindings, run in order, and a refusal stops the rest: an action, then a setState that marks the row done.
  • confirm (title, message, and optionally confirmLabel, cancelLabel, variant: "danger") asks before an action runs. Put one on anything that spends. ${/picks/qty} in its words is filled from the card's state.
  • onSuccess: { set: { "/picks/qty": 0 } } resets picks after the action works (onError takes the same shape). Without it the picks stay, and the next press sends them again.
  • Picks start again on a reload. Anything an action saved stays.
  • The action checks the picks: a player can send anything.

Any prop can be worked out from the state as the player picks:

  • { $cond: <condition>, $then: a, $else: b }. A condition is { $state: "/picks/feat" } (has a value), with eq, neq, gt, gte, lt, lte or not: true, or { $and: [...] } and { $or: [...] }; inside a repeat, { $item: "equipped" } and { $index: true, lt: 3 } read the item and its place. An element's visible takes a condition too. A condition reads a path and compares it with a value or another path (lt: { $state: "/result/price" }), never a worked-out value: to set a prop by one, use the if function below. visible reads paths only.

  • { $template: "Chosen: ${/picks/label}" } for words with values in them.

  • { $math: "subtract", a: 6, b: { $state: "/picks/spent" } }: add, subtract, multiply, divide, mod, min, max, round, floor, ceil, abs.

  • $count for a list's length and $concat to join values: label: { $concat: ["Pay ", total, " gp"] }.

  • { $join: <list>, separator: ", " } joins a list into words, { $pluralize: <count>, one: "arrow", other: "arrows", zero: "no arrows" } gives "3 arrows", { $truncate: <text>, length: 40 } cuts long text (with "..."), and { $format: "number", value: <number> } writes a number for the reader ("1,250"; also "percent", "date", and "currency" with currency: "USD").

  • { $computed: "<function>", args: { ... } } calls one of the card's functions. Each arg is worked out first, so it can be bound, a $math or another call.

  • get (value, path): A value inside another, by a path. {"$computed":"get","args":{"value":{"$state":"/files/me"},"path":"stats/str"}}

  • coalesce (any values, named or as values: [...]): The first of its values that is set. {"$computed":"coalesce","args":{"nick":{"$state":"/files/me/nickname"},"name":"Traveller"}}

  • sum (any values, named or as values: [...]): Its values added up (anything not a number is skipped). {"$computed":"sum","args":{"str":{"$state":"/picks/str"},"dex":{"$state":"/picks/dex"}}}

  • min (any values, named or as values: [...]): The smallest of its values, or null with none. {"$computed":"min","args":{"hp":{"$state":"/files/me/hp"},"cap":10}}

  • max (any values, named or as values: [...]): The largest of its values, or null with none. {"$computed":"max","args":{"left":{"$state":"/files/foe/hp"},"floor":0}}

  • compare (a, op, b): true or false: a compared with b, as a condition compares. gt, gte, lt and lte need two numbers, and are false otherwise.

    • op: eq, neq, gt, gte, lt, lte {"$computed":"compare","args":{"a":{"$state":"/files/me/gold"},"op":"lt","b":{"$math":"multiply","a":15,"b":{"$state":"/picks/count"}}}}
  • and (any values, named or as values: [...]): true when every one of its values is set (truthy). {"$computed":"and","args":{"alive":{"$state":"/files/me/hp"},"picked":{"$state":"/picks/target"}}}

  • or (any values, named or as values: [...]): true when any of its values is set (truthy). {"$computed":"or","args":{"blessed":{"$state":"/files/me/blessed"},"lucky":{"$state":"/picks/luck"}}}

  • not (value): true when value isn't set (false, 0, empty or missing). {"$computed":"not","args":{"value":{"$state":"/picks/target"}}}

  • if (when, then?, else?): then when when is set (truthy), else else: a $cond whose condition is worked out (a compare, an and).

    • when: the condition
    • then: what the prop takes when it holds
    • else: what the prop takes when it doesn't {"$computed":"if","args":{"when":{"$computed":"compare","args":{"a":{"$state":"/files/me/hp"},"op":"lt","b":5}},"then":"failure","else":"neutral"}}
  • sumBy (list, field, times?): A field added up across a list's items, each multiplied by times when given (an item without a number there counts once).

    • list: the list, usually bound: { $state: "/files/me/inventory" }
    • field: the field to add up ("weight", or a path)
    • times: a field to multiply each by ("quantity") {"$computed":"sumBy","args":{"list":{"$state":"/files/me/inventory"},"field":"weight","times":"quantity"}}
  • countWhere (list, field?, op?, value?): How many of a list's items match.

    • list: the list, usually bound: { $state: "/files/me/inventory" }
    • field: the field each item is compared on ("weight", or a path: "stats/str"); left out, the item itself
    • op: eq, neq, gt, gte, lt, lte; left out, eq when there is a value, else the field just has to be set
    • value: what the field is compared with {"$computed":"countWhere","args":{"list":{"$state":"/files/me/inventory"},"field":"weight","op":"gt","value":5}}
  • find (list, field?, op?, value?): The first of a list's items that matches, or null. Read a field of it with get.

    • list: the list, usually bound: { $state: "/files/me/inventory" }
    • field: the field each item is compared on ("weight", or a path: "stats/str"); left out, the item itself
    • op: eq, neq, gt, gte, lt, lte; left out, eq when there is a value, else the field just has to be set
    • value: what the field is compared with {"$computed":"find","args":{"list":{"$state":"/files/me/weapons"},"field":"equipped"}}
  • pluck (list, field): One field from each of a list's items, as a list (items without it are left out): for $join or $count.

    • list: the list, usually bound: { $state: "/files/me/inventory" }
    • field: the field ("name", or a path) {"$join":{"$computed":"pluck","args":{"list":{"$state":"/files/me/inventory"},"field":"name"}}}
  • includes (list, value, field?): true when a list has value in it (or, with field, an item whose field is value).

    • list: the list, usually bound: { $state: "/files/me/inventory" }
    • value: what to look for
    • field: the field each item is compared on ("weight", or a path: "stats/str"); left out, the item itself {"$computed":"includes","args":{"list":{"$state":"/result/claims"},"field":"by","value":{"$state":"/viewer"}}}
  • clamp (value, min?, max?): value kept between min and max (either can be left out), or null when it isn't a number.

    • min: the lowest it can be
    • max: the highest it can be {"$computed":"clamp","args":{"value":{"$math":"subtract","a":{"$state":"/files/foe/hp"},"b":{"$state":"/picks/damage"}},"min":0}}

A Buy button that greys out when the player can't pay for the number they picked, and a weight that adds up the pack as it is now:

disabled: {
  $computed: "compare",
  args: {
    a: { $state: "/files/me/gold" },
    op: "lt",
    b: { $math: "multiply", a: result.price, b: { $state: "/picks/count" } },
  },
},
text: {
  $concat: [
    { $computed: "sumBy", args: { list: { $state: "/files/me/inventory" }, field: "weight", times: "quantity" } },
    " lb carried",
  ],
},

The card check refuses a function a card doesn't have, an arg its function doesn't take (or one it needs left out), and a worked-out value where a condition reads a path. The reason shows in the editor's test run, rather than an empty prop on every player's screen. A rule of the world (encumbrance, armor class) is better as a computed field on its file type: the GM, sheets and scripts see it too.

card itself can't see who is looking: it draws one card for everyone. The card can still tell "you" from others by comparing /viewer with ids it recorded: text: { $cond: { $state: "/viewer", eq: claim.by }, $then: "Your pick", $else: "Taken by " + claim.name }.

For a pick-one card, each option's Button sets /picks/id and /picks/label, its selected is a $cond on the pick, and one Confirm sends it. For a Confirm that lights up only once 3 points are spent, have each "+1" push onto /picks/spent and set the Confirm's disabled to { $cond: { $state: "/picks/spent/2", not: true }, $then: true, $else: false } (index 2 exists once 3 are spent). The action then takes spent as a list, and refuses until every point is spent. A Reset Button can set /picks back to where it started.

Live values from files

A value a script copies into its result (a character's HP, their gold, the slots they have used) is the value when the run happened. If the GM, a sheet edit or another card changes it later, the card still shows the old number. To show a value as it is now, have the card read it from the file: name the file in the card's files, and bind the field at /files/<name>/<field>.

export default defineScript({
  description: "Opens the fence's stall: a few pieces for sale.",
  beforeNarrationTrigger: "The party browses a fence's stall.",
  visibility: "player",
  async run(input, { game }) {
    const ring = await game.files("Item").get("silver-ring");
    return { ringId: ring.$id, price: 15 };
  },
  card(result) {
    return {
      root: {
        type: "Frame",
        props: { title: "The fence's stall" },
        children: [
          { type: "Currency", props: { label: "Your purse", amounts: [{ amount: { $state: "/files/me/gold" }, unit: "gp" }] } },
          {
            type: "Button",
            props: {
              label: "Buy the ring for " + result.price + " gp",
              disabled: { $cond: { $state: "/files/me/gold", lt: result.price }, $then: true, $else: false },
            },
            on: { press: { action: "buy" } },
          },
        ],
      },
      files: { me: "$viewer", ring: result.ringId },
    };
  },
  // actions: { buy: … } re-reads the sheet and checks the price, as always.
});
  • files sits beside root (and state). Each name is a file's $id, the file itself, a current-state person's file, or "$viewer" for the character of whoever is looking. Names are letters, digits and _.
  • /files/<name>/<field> is the field as a script reads it, computed fields included. /files/<name>/$name and /files/<name>/$id are the file's name and id. Use them anywhere a $state goes: a prop, a $cond, a $template ("${/files/me/hp} HP"), a repeat over a list field, a function's args (sumBy over an inventory), a confirm's words.
  • The values are read whenever the card is drawn, and again on every player's screen whenever one of the files changes, whoever changed it. Only cards on the latest three GM replies follow their files; an older card reads them once, when it appears, and doesn't change after that. Bind what a player acts on now, not what an old card should keep telling.
  • "$viewer" is a different file for each player: every player sees their own purse on the same card. card still draws one card for everyone; only the bound values differ.
  • A card reads only the files and fields its bindings name, of this game, and only files a script can reach. A file that isn't there (deleted, hidden from the GM, or no one looking for "$viewer") reads as nothing, so give a binding a fallback where it matters.
  • The values are only shown. Controls bound to /files can't change them, and setState can't write there: change a file with one of the script's actions.
  • Choose per value what a card shows. Put what happened in the result (the goblin had 3 HP when it was hit), so the card keeps telling it in read back. Bind what is true now (your gold, the slots you have left).
  • In the test run, "$viewer" is the "Test as" character, and a press shows the files as the dry run would have left them.

Cards and the map

When the same run plays on the map (an attack's dice and the wound, a monster stepping out), the card goes on the same page as that moment by default, and its result shows once the blow lands. A card that decides what happens next, like an encounter table, can go first on a page of its own: set cardOrder: "card_first" (defining a script). A card that introduces what comes next, like whose turn it is in a fight, can be card-first too: it opens the next fighter's page, and their attack plays under it.

A roll made with game.roll already gets its own dice card in the story. When the script's card draws those dice itself, pass show: "map" to the roll so the story doesn't show them twice (rolls and effects).

Good cards

  • Use Frame as the shell, with a short eyebrow and a title that says what happened. Save critical and fumble for a natural 20 that hit or a natural 1 that missed.
  • Ask before anything that costs, with a confirm.
  • Show why an option is locked ("Needs CON 15") instead of hiding it. Work out what each option needs in the script's run, put the reasons in the result, and check again in the action. A disabled worked out from a live value (/files/me/gold) stays right as the sheet changes; one worked out in card is drawn once.
  • Once a choice is made, shrink the card to what was chosen, and draw every choice selected and disabled with an Outcome saying what was picked.
  • Keep Button labels short. The full sentence goes in the confirm.
  • Close the card when its moment is over.
  • To try the Buttons, use the Test tab, where you press them as the character you pick under Test as. Presses there are dry runs: nothing is saved, and the test shows what they would change and the words a turn-starting press would send.

Card components

Every card component, read from the card catalog. Each also takes className. A Stepper or Dots bound to /result shows its value and saves nothing.

The card's shell and buttons

Frame

The card's shell. A header (an icon or a portrait image, a small eyebrow line above the title such as "Attack" or "Shop", the title, a subtitle) and its children stacked below. The frame stays neutral and tone tints its icon; only "critical" (a gold rule and a foil sweep) and "fumble" (a red rule) mark the frame itself, so save them for a natural 20 or 1. image is a portrait URL in place of the icon (a merchant, a speaker). tag is a small label at the header's end ("Live", "Secret"). Keep eyebrow to two short parts ("Longsword · advantage"); put mechanics such as a roll's position in Tags. Put an Actions element last among its children for a footer of Buttons.

Prop Type Required
eyebrow string
title string
subtitle string
icon string
image string
tag string
tone Tone
{
  "type": "Frame",
  "props": {
    "eyebrow": "Attack",
    "title": "Brom swings at the goblin",
    "subtitle": "Longsword · advantage",
    "icon": "sword",
    "tone": "success"
  }
}

Actions

A row of Buttons. Last inside a Frame it is the frame's footer, set apart by a rule; elsewhere it is a plain row. align "stretch" gives each Button an equal share.

Prop Type Required
align "start" | "end" | "stretch"
{"type":"Actions","props":{"align":"start"}}

Button

A button that runs what its element's on.press names. One of the script's actions ({ action: "buy", params: { item: "silver-ring" } }) changes the game's files and redraws the card; setState, pushState and removeState change the card's own state. disabled (often a $cond) greys it out, and reason says why ("Need 27 gp"). variant "default" is the card's one primary action, "secondary" the rest, "danger" for something that can't be undone. variant "choice" draws it as an option row, full width: icon, label, description under it, meta at its end (a price, a tally: "5 gp", "2 votes"). Set selected (often a $cond on the card's state) when the choices are a pick among them: a check shows on the picked one. Once the pick is made and the card redraws, keep selected and set disabled on every choice: the chosen row stays bright with a check and the rest fade. icon names a card icon (sword, shield, heart, coins, flask…) or is an emoji. meta also shows after a plain Button's label. When its action starts the next turn (startsTurn on the action), the press is sent as the player's turn in the Button's label, or in turn when set: words that read as what the player does, for a Confirm whose label says nothing of the pick (often a $template on the card's state).

Prop Type Required
label string yes
variant "default" | "secondary" | "outline" | "danger" | "choice"
disabled boolean
icon string
description string
meta string | number
selected boolean
reason string
turn string
{
  "type": "Button",
  "props": {"label":"Buy · 15 gp","variant":"secondary","disabled":null}
}

The binding goes on the element as on: { press: ... }, never in its props (actions).

Rolls and results

Roll

One roll read as a whole: its dice, what was added, the total large, what it was against and the verdict as a stamp. dice as in Dice (Each die is { sides, value, kept, tone, color, label, exploded }: sides 4, 6, 8, 10, 12, 20 or 100 draws that die's shape (any other is a square); value is its face, a number or a short text ("+", "−" and " " for Fate dice, "?" for a die players don't see); kept: false strikes it out (the low die of advantage, a pool's dropped dice); a kept d20's natural 20 glows gold and its natural 1 breaks; tone gives it a meaning (a Blades pool's highest die "partial"), while color only colors it (red, orange, gold, green, teal, blue, violet, pink: "orange" for fire); label is a word under it ("fire", "hope"); exploded: true marks a die that exploded.). modifiers is [{ value, label }] ({ value: 5, label: "STR" }). target is { label, value } ("AC", 15; "DC", 13). outcome is { text, tone } ("Hit" success, "Critical" critical, "Miss" failure, "Mixed" partial). The total is written by the script; the card doesn't add it up. A lone die with nothing added is its own total: it shows large with the verdict beside it. With a numeric target the card shows how far the roll beat or missed it, except on a natural 20 or 1.

Prop Type Required
label string
dice any[] yes
modifiers any[]
total string | number
target { label?, value? }
outcome { text?, tone? }
{
  "type": "Roll",
  "props": {
    "label": "Attack roll",
    "dice": [{"sides":20,"value":17}],
    "modifiers": [{"value":5,"label":"STR"}],
    "total": 22,
    "target": {"label":"AC","value":15},
    "outcome": {"text":"Hit","tone":"success"}
  }
}

A roll made with game.roll already has its own dice card. Draw it here only when the roll passes show: "map".

Dice

Dice as they landed, each drawn as its own shape with its face. Each die is { sides, value, kept, tone, color, label, exploded }: sides 4, 6, 8, 10, 12, 20 or 100 draws that die's shape (any other is a square); value is its face, a number or a short text ("+", "−" and " " for Fate dice, "?" for a die players don't see); kept: false strikes it out (the low die of advantage, a pool's dropped dice); a kept d20's natural 20 glows gold and its natural 1 breaks; tone gives it a meaning (a Blades pool's highest die "partial"), while color only colors it (red, orange, gold, green, teal, blue, violet, pink: "orange" for fire); label is a word under it ("fire", "hope"); exploded: true marks a die that exploded.

Prop Type Required
dice any[] yes
size "sm" | "md" | "lg"
{
  "type": "Dice",
  "props": {
    "dice": [{"sides":20,"value":17},{"sides":20,"value":6,"kept":false}],
    "size": "md"
  }
}

Outcome

What happened, in words, as a band across the card: "The goblin falls", "Poisoned for 1 hour". title is the headline (keep it under about 60 characters: it shows two lines at most), text the detail under it.

Prop Type Required
title string yes
text string
icon string
tone Tone
{
  "type": "Outcome",
  "props": {
    "title": "Poisoned for 1 hour",
    "text": "Disadvantage on attack rolls and ability checks.",
    "icon": "flask",
    "tone": "failure"
  }
}

Hero

The moment's one big number without dice: a level reached (label "Level", value 4), experience earned ("+450", unit "XP"), gold found, damage dealt, days left. tone "critical" celebrates it in gold with a burst (a level up, a milestone); other tones tint it. caption is a small line under the number.

Prop Type Required
value string | number yes
label string
unit string
caption string
icon string
tone Tone
{
  "type": "Hero",
  "props": {
    "label": "Level",
    "value": 4,
    "icon": "star",
    "tone": "critical",
    "caption": "Fighter · 2,700 XP"
  }
}

Meter

A value against its max: hit points, mana, experience, a trace, votes in. from is where it was before this run: a loss drains and leaves an outlined ghost of what was lost (health shows a skull at zero), a gain glows, and the change shows signed beside the value. tone "health" (the default) goes green, amber, red as it empties; any other tone fixes the color. display "boxes" or "pips" draws one cell per point (supplies, death saves; up to 20); pips with an icon draw that icon in each (hearts, skulls). min below zero makes it two-sided around a centre tick (faction standing −5 to +5, sanity); valueLabel names where it stands ("Friendly"); minLabel and maxLabel label the ends (put them on the last of a group). better: "lower" when going up is bad (a trace, an alarm). caption is a small line under it. hideValue hides the numbers (an enemy's health).

Prop Type Required
label string
value number yes
max number yes
min number
from number
icon string
tone Tone | "health"
display "bar" | "boxes" | "pips"
better "higher" | "lower"
caption string
valueLabel string
minLabel string
maxLabel string
hideValue boolean
{
  "type": "Meter",
  "props": {"label":"Hit points","value":9,"from":21,"max":32,"icon":"heart"}
}

Changes

What this run changed, a row each: { label, from, to, delta, unit, icon, detail, tone, better }. from → to shows before and after; delta is the signed difference (worked out from numbers when left out); a row with only delta reads "Gold −25 gp"; a row with only to reads as something gained ("New feature: Second Wind"). A row that didn't change is left out. Going up is green unless better is "lower"; tone "success" or "failure" overrides it.

Prop Type Required
items any[] yes
{
  "type": "Changes",
  "props": {
    "items": [
      {"label":"Hit point maximum","from":32,"to":41,"icon":"heart"},
      {"label":"Gold","delta":-25,"unit":"gp","icon":"coins"}
    ]
  }
}

Details and lists

Facts

Short label/value pairs, [{ label, value, tone }]: DC 15 · Range 60 ft · Save WIS. layout "inline" (the default) runs them on one wrapping line; "grid" sets them in cells with the value large (columns, 2 to 4).

Prop Type Required
items any[] yes
layout "inline" | "grid"
columns number
{
  "type": "Facts",
  "props": {
    "items": [{"label":"DC","value":15},{"label":"Range","value":"60 ft"}],
    "layout": "inline"
  }
}

Tags

Small pills for conditions, damage types, traits: [{ text, tone, icon }] or plain strings.

Prop Type Required
items any[] yes
{
  "type": "Tags",
  "props": {"items":[{"text":"Poisoned","tone":"fumble","icon":"flask"},"Prone"]}
}

Log

What happened, line by line: a contest's rounds, a fight's blows, tries at a lock. items is [{ label, text, detail, tone }] or plain strings; label is a short marker ("R1", "Try 2"); detail is a small breakdown after the line ("16+5 · 9+4"); tone success or critical marks the line with a check, failure or fumble with a cross.

Prop Type Required
items any[] yes
{
  "type": "Log",
  "props": {
    "items": [
      {"label":"R1","text":"21 vs 13","tone":"success"},
      {"label":"R2","text":"9 vs 18","tone":"failure"}
    ]
  }
}

Steps

Stages in order: a level up's choices, a ritual, clues found, a journey's legs. items is [{ label, detail, status }] with status "done", "current", "failed" or "todo" (the default). direction "horizontal" fits up to five short labels on one line. tone is the current stage's accent (violet by default).

Prop Type Required
items any[] yes
direction "vertical" | "horizontal"
tone Tone
{
  "type": "Steps",
  "props": {
    "items": [
      {"label":"Roll hit points","status":"done"},
      {"label":"Choose a feat","status":"current"},
      {"label":"Review your sheet"}
    ]
  }
}

RollTable

A table of ranges with the row the roll landed on lit: a random encounter table, a move's bands (10+ / 7–9 / 6−), a percentile ladder. rows is [{ range, label, text, tone }]; landed is the index of the row that came up (0 first); rolled is the number shown on it; with sides (20) it shows as that die. text shows only on the landed row, so keep each label short and put what it means in text.

Prop Type Required
rows any[] yes
landed number
rolled string | number
sides number
{
  "type": "RollTable",
  "props": {
    "rows": [
      {"range":"10+","label":"You do it","tone":"success"},
      {"range":"7–9","label":"You stumble","tone":"partial"},
      {"range":"6−","label":"The GM makes a move","tone":"failure"}
    ],
    "landed": 1,
    "rolled": 8
  }
}

Roster

People in order: initiative, a party at rest, who voted. Each is { name, subtitle, image, value, valueLabel, dice, modifier, meter: { value, max }, tags, tone, state, you }: image is a portrait URL; without one the game shows the person's own portrait when it knows them by name (the player, a character, an extra), else initials; value is a number at the row's end with valueLabel under it ("19", "init"); dice ([{ sides, value, kept }], up to 3, as Dice takes them) show small before the value with modifier ("+2") between, for a roster of rolls such as initiative; meter is a thin health bar; state "current" lights the row (whose turn it is), "done" and "down" dim it ("down" strikes the name and shows a skull); you: true marks the player's own row. numbered shows 1, 2, 3. tone is the current row's accent (violet by default); an entry's own tone tints its initials ("failure" for enemies).

Prop Type Required
items any[] yes
numbered boolean
tone Tone
{
  "type": "Roster",
  "props": {
    "numbered": true,
    "items": [
      {
        "name": "Sera",
        "subtitle": "Ranger",
        "dice": [{"sides":20,"value":16}],
        "modifier": "+3",
        "value": 19,
        "valueLabel": "init"
      },
      {"name":"Goblin","value":8,"tone":"failure","state":"down"}
    ]
  }
}

Versus

Two sides head to head: a contest, an opposed check, a duel. left and right are { name, image, detail, value }: value is the score or roll shown large, detail a line under the name ("+5"). winner "left" or "right" crowns that side and dims the other; leave it out while it's undecided. label is a small line under "VS" ("best of 3").

Prop Type Required
left { } yes
right { } yes
winner "left" | "right"
label string
{
  "type": "Versus",
  "props": {
    "left": {"name":"Brom","detail":"+5","value":2},
    "right": {"name":"Old Hask","detail":"+4","value":1},
    "winner": "left",
    "label": "best of 3"
  }
}

Currency

Money as coins: [{ amount, unit, color }]. Units pp, gp, ep, sp and cp draw as platinum, gold, electrum, silver and copper coins; any other unit ("credits", "crowns") draws a plain coin, or one of color. signed: true shows amounts as changes, +14 green and −3 red. label is a small word before them ("Your purse").

Prop Type Required
amounts any[] yes
label string
signed boolean
{
  "type": "Currency",
  "props": {
    "label": "Your purse",
    "amounts": [{"amount":23,"unit":"gp"},{"amount":7,"unit":"sp"}]
  }
}

The world's files

FileTiles

A grid of the world's files, each its picture and name, opening the file on a tap in play. files lists them by id (a handle's $id or $referenceId, or the handle itself), as a current-state person's file (person.file) or a reference field's value, or as { file, detail, badge, button, drag } for a tile with a line under its name, a badge on its picture, a button ({ label, press, disabled, reason }: press runs one of the script's actions or the card's setState, one binding or a chain, as a Button's on.press) and drag ({ kind, data }) to pick the tile up and drop it on the card's drop targets; a tile's drag always carries its file as data.$id, $name, $image and $type. Craft fills in each name and picture after the run and leaves out any that aren't in the game. layout is how the tiles sit: "grid" (the default), "list" (a row per file, its button at the end: for comparing many, like prices) or "row" (one line that scrolls sideways, keeping the story in view). size is the tile size, "md" by default ("xs" for icon-sized pictures, as in an inventory strip); a grid's columns follow the size and the screen. face "image" draws only the pictures, the name shown on hover and read aloud, every tile the same height. selected marks tiles as picked: a file id or a list of them, usually bound to the card's state ({ "$state": "/picks/held" }). shown keeps the set to that many tiles, with a button (moreLabel, "See all" by default) that opens every tile in a window players can scroll and search, laid out as moreLayout (the card's layout by default, a grid for a row).

Prop Type Required
files any[] yes
size "xs" | "sm" | "md" | "lg"
layout "grid" | "list" | "row"
face "full" | "image"
selected string | string[]
emptyText string
shown number
moreLabel string
moreLayout "grid" | "list" | "row"
{
  "type": "FileTiles",
  "props": {
    "files": [],
    "size": "md",
    "layout": "grid",
    "emptyText": null,
    "shown": null,
    "moreLabel": null,
    "moreLayout": null
  }
}

See File tiles above for tiles with a price, a badge and a button.

Places to drop

Slot

A socket something goes into: a crafting recipe's ingredients, a gem setting, an equipment slot, a spell's components, a puzzle's pieces. Empty, it shows a dashed outline with icon (a question mark by default) and hint under label ("Extract source", "Drop here"); filled, it shows image and title (what is in it), with detail under it. filled is true once there is a title or an image unless it is set. label is the slot's role ("Light core", "Housing") and shows in both states. shape is "square" (the default), "round" or "diamond"; size "sm", "md" (the default) or "lg". tone tints a filled slot's frame. Give a Slot on.drop (and drop to narrow what it takes) to fill it by drag and drop or a tap; bind its title and image to the card's state ({ "$state": "/picks/bark/$name" }) to show what was dropped before anything is sent.

Prop Type Required
label string
hint string
icon string
image string
title string
detail string
filled boolean
shape "square" | "round" | "diamond"
size "sm" | "md" | "lg"
tone Tone
{
  "type": "Slot",
  "props": {
    "label": "Extract source",
    "hint": "Drop a herb",
    "icon": "leaf",
    "shape": "diamond"
  }
}

Give it on: { drop: ... } to fill it by drag and drop, and drop to narrow what it takes (drag and drop).