Compare commits

...

6 commits

Author SHA1 Message Date
160848f881 Sheet canvas: page starts at the left edge so boxes can go left; docs
The page was placed in the middle of the canvas, so boxes could not be
dragged left of it. Design doc: Sheets status, open items, review list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:37:39 -06:00
317cac7a78 Sheets phase E: export/import, text toolbar and Lore links, Lore library and items, phone view
- E1: Export ▾ (share file with embedded pictures, print/PDF web page,
  PNG of the tab); Import a sheet file from Sheets and New sheet.
- E2: formatting toolbar (FormatMenu) in sheet text boxes; Lore links
  ([url=lore:ID]) with hover excerpt and the details panel.
- E3: Lore Index in Play and in sheets (shared LoreList); This spread |
  My library; item sheets on Lore Entries; drag entries into lists,
  slots and notes (copy, Shift keeps linked).
- E4: phone stacked view in phone order, Stacked | Canvas switch, 44 px
  touch sizes, bottom panels; sheet CLI flags split out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:25:09 -06:00
5941733af1 Sheets phase D: sheets on spreads as linked Sheet cards
- A Sheet card can show a sheet file (sheet, prefix): first-tab preview,
  Open sheet with a way back, the spread's Play/Build in the editor.
- Rolls read and write "Use in tables" boxes as @name or @prefix_name;
  locked boxes and formulas/lists keep their values; changed boxes glow.
- A roll reaching the card shows the sheet's text (SheetText) in the
  tray; text boxes also show spread values when on the spread.
- Old template Sheet cards migrate to a sheet with one text box (not in
  Help demos). Card palette lists your sheets.
- Sheet canvas: tiled grid (smooth panning); boxes no longer overlap
  (nearest free spot, drags stop short; Alt places freely).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:52:41 -06:00
dd0323c53f Sheets phase C: every field kind, details panel, canvas panning
- 25 palette items over 23 kinds: basics, trackers (bars, ticks, clocks,
  dots, step/usage dice, ladders), formulas and dice buttons (rule
  language with sheet @names), lists (rows, mini table, chips, point pool
  that may go negative, bonds), slots, conditions, spell slots, XP,
  currency, heading, divider, picture.
- Per-kind settings in the inspector; hover excerpts and an in-app
  details panel for list entries; live redraw of dependent boxes.
- Canvas: the page stays put after edits (boxes can go anywhere), a
  screen of room past the boxes, drag-to-pan and edge scrolling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:28:04 -06:00
2661744b06 Sheets phase B: main menu, Sheets list, sheet editor
- Main menu (Spreads, Sheets, Settings, Quit) on the theme background,
  with recent spreads and sheets; logo or ☰ returns to it.
- Sheets: data model, store, templates, snapshot undo; New sheet dialog
  (blank or a template); editor with folder tabs, snap-grid canvas on the
  spread background, field palette, inspector, Play/Build, status strip.
- Field kinds: Number, Text box (BBCode, live {@name}), Heading.
- PaletteList shared by the card and field palettes; shared top bar brand.
- Keys go to the screen that shows; theme reloads keep the screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 15:53:56 -06:00
16b34c40f6 Card palette: left dock Cards | List, search, click or drag to add
- CardCatalog: one list of card kinds for the palette, right-click New card
  and new-card names; Dice table and Deck are their own items.
- LeftDock holds the palette and List view in the shared dock tab style.
- Play greys the palette under a Switch to Build notice (replaces the
  greyed + Card button); + Card menu removed; Card palette button in Build.
- Templates dropped from the palette land where they are let go.
- Phones: + opens the palette full screen.
- docs/SHEETS.md: the Sheets and unified editor plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 14:58:56 -06:00
157 changed files with 8118 additions and 395 deletions

View file

@ -13,6 +13,9 @@ var details: String = ""
var tags: Array[String] = []
## A picture (BoardImages id). "" = none.
var image: String = ""
## Its item sheet (a SheetStore sheet id, e.g. a sword's Damage and Charges).
## "" = none. Saved as "sheet".
var sheet: String = ""
func label() -> String:
@ -29,6 +32,8 @@ func to_dict() -> Dictionary:
d["tags"] = tags.duplicate()
if image != "":
d["image"] = image
if sheet != "":
d["sheet"] = sheet
return d
@ -39,6 +44,12 @@ static func from_dict(d: Dictionary) -> BookPage:
p.text = str(d.get("text", ""))
p.details = str(d.get("details", ""))
p.image = str(d.get("image", ""))
p.sheet = str(d.get("sheet", ""))
for t: Variant in d.get("tags", []):
p.tags.append(str(t))
return p
## A copy with the same fields (the caller gives it a new id).
func copy() -> BookPage:
return BookPage.from_dict(to_dict())

View file

@ -24,7 +24,7 @@ const KIND_LABELS := {
RollTable.KIND_ROUTER: "Branch", RollTable.KIND_CHECK: "Check", RollTable.KIND_VARIABLE: "Variable",
RollTable.KIND_SHEET: "Sheet",
}
## What each kind of choice is called (the + Card menu, settings, card, previews).
## What each kind of choice is called (the card palette, settings, card, previews).
const CHOICE_LABELS := {"pick": "Which option", "number": "How many", "text": "Open ended"}

View file

@ -38,7 +38,8 @@ const IMPORT_ALLOWED_TAGS: Array[String] = [
]
## url parameters with these prefixes are TextExpander's internal markers.
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:", "error:"]
## "lore:" is a link to a Lore Entry (SheetLoreLinks): it means nothing outside the app.
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:", "error:", "lore:"]
## Matches one tag: [name], [/name], [name=param] or [name key=value ...].
## Parameters may contain quoted strings, so [url={"a":1}] is one tag.

77
core/lore_library.gd Normal file
View file

@ -0,0 +1,77 @@
class_name LoreLibrary
extends RefCounted
## "My library": the shared Lore Index level, kept outside every spread in
## <root>/lore_library.json ({"book": [BookPage dicts]}). Any spread and any
## sheet can use its Lore Entries. Links to it in sheet text say so:
## [url=lore:lib:ID] (SheetLoreLinks). There is no undo here; every change is
## saved at once (save()).
const FILE := "lore_library.json"
var root := "user://"
var pages: Array[BookPage] = []
## Goes up on every change, so open lists know to refresh.
var revision := 0
func _init(p_root: String = "user://") -> void:
root = p_root
load_file()
func path() -> String:
return root.path_join(FILE)
func load_file() -> void:
pages.clear()
if not FileAccess.file_exists(path()):
return
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path()))
if parsed is Dictionary and parsed.get("book") is Array:
for v: Variant in parsed["book"]:
if v is Dictionary:
var page := BookPage.from_dict(v)
if page.id == "":
page.id = TowerBoard.new_id("lib")
pages.append(page)
func save() -> Error:
revision += 1
DirAccess.make_dir_recursive_absolute(root)
var list: Array = []
for page in pages:
list.append(page.to_dict())
return BoardFileIO.write_text_atomic(path(), JSON.stringify({"book": list}, "\t"))
func get_page(id: String) -> BookPage:
for page in pages:
if page.id == id:
return page
return null
func add_page(text: String, details: String = "") -> BookPage:
var page := BookPage.new()
page.id = TowerBoard.new_id("lib")
page.text = text
page.details = details
pages.append(page)
save()
return page
## Adds a copy of `page` (a new id) and returns it.
func add_copy(page: BookPage) -> BookPage:
var added := page.copy()
added.id = TowerBoard.new_id("lib")
pages.append(added)
save()
return added
func remove_page(id: String) -> void:
pages = pages.filter(func(page: BookPage) -> bool: return page.id != id)
save()

1
core/lore_library.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cftrxlns3sxb5

View file

@ -130,6 +130,11 @@ var loop_expr: String = ""
var var_name: String = ""
var var_type: String = "number"
var initial: String = ""
## Sheet cards: the sheet they show (a SheetStore id; "" = an old template
## card, migrated by MainSheetLinks) and the prefix tables read its boxes by
## (@prefix_name; "" = plain @name). docs/SHEETS.md, phase D.
var sheet_id: String = ""
var sheet_prefix: String = ""
## Scale variables: the ordered steps, lowest first.
var steps: Array[String] = []
## A cost to roll this card (RollCosts): the value ("@luck") and the amount

View file

@ -72,6 +72,11 @@ static func to_dict(t: RollTable) -> Dictionary:
d["loop"] = t.loop_mode
if t.loop_expr != "":
d["loop_expr"] = t.loop_expr
elif t.kind == RollTable.KIND_SHEET:
if t.sheet_id != "":
d["sheet"] = t.sheet_id
if t.sheet_prefix != "":
d["prefix"] = t.sheet_prefix
elif t.kind == RollTable.KIND_VARIABLE:
if t.var_name != "":
d["var_name"] = t.var_name
@ -150,6 +155,8 @@ static func from_dict(d: Dictionary) -> RollTable:
var vt := str(d.get("var_type", "number"))
t.var_type = vt if RollTable.VAR_TYPES.has(vt) else "number"
t.initial = RollTable.expr_text(d.get("initial", ""), "")
t.sheet_id = str(d.get("sheet", ""))
t.sheet_prefix = str(d.get("prefix", ""))
t.steps = Scales.clean(d.get("steps", []))
t.members = LedgerMembers.clean(d.get("members", []))
t.list_repeats = bool(d.get("repeats", false))

View file

@ -44,6 +44,10 @@ extends RefCounted
## and fills in ctx.root as it goes. roll() is the plain form: it never waits
## (choices get the headless answers) and returns the tree directly.
## Gives a linked Sheet card's text (RollTable.sheet_id): set by the app
## (MainSheetLinks), which can read sheet files. Unset in headless use.
static var sheet_text := Callable()
## Deepest level inline references can nest (matches RollContext).
const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH
## Most actions one top-level roll may take (matches RollContext).
@ -247,7 +251,13 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
"kind": RollTable.KIND_SHEET}
_attach(f, sheet, ctx)
# A card showing a sheet file rolls the sheet's text (SheetText) in
# place of its own template, for this roll only.
var own := t.entries[0].text
if t.sheet_id != "" and sheet_text.is_valid():
t.entries[0].text = str(sheet_text.call(t))
await _enter(sheet, f, ctx, stack, true, true)
t.entries[0].text = own
_:
var node := RollCards.pick_for(t, ctx, f)
if node.has("nat"):

80
core/sheet_box.gd Normal file
View file

@ -0,0 +1,80 @@
class_name SheetBox
extends RefCounted
## One box on a sheet tab: a field (a number, a text box, a heading…) placed
## freely on the tab's canvas. `kind` picks how it looks and behaves
## (SheetKinds); `config` holds the kind's settings and `value` what the
## player filled in, so new kinds need no new fields here.
var id: String = ""
var kind: String = SheetKinds.TEXT
var title: String = ""
## Position and size on the tab, in canvas pixels (snapped to SheetKinds.GRID
## unless placed freely with Alt).
var x: float = 0.0
var y: float = 0.0
var w: float = 192.0
var h: float = 96.0
## Box colour as "#rrggbb", or "" for the theme's card colour.
var color: String = ""
var frameless: bool = false
## Place in the stacked phone view (0 = automatic: reading order).
var phone_order: int = 0
## Tables can read and write the box as @var_name ("" = not used in tables).
var var_name: String = ""
## Locked boxes ignore values written by rolls.
var locked: bool = false
var config: Dictionary = {}
var value: Variant = null
func _init(p_id: String = "", p_kind: String = SheetKinds.TEXT) -> void:
id = p_id
kind = p_kind
func rect() -> Rect2:
return Rect2(x, y, w, h)
func set_rect(r: Rect2) -> void:
x = r.position.x
y = r.position.y
w = r.size.x
h = r.size.y
func to_dict() -> Dictionary:
var d := {"id": id, "kind": kind, "title": title, "x": x, "y": y, "w": w, "h": h}
if color != "":
d["color"] = color
if frameless:
d["frameless"] = true
if phone_order != 0:
d["phone_order"] = phone_order
if var_name != "":
d["var"] = var_name
if locked:
d["locked"] = true
if not config.is_empty():
d["config"] = config.duplicate(true)
if value != null:
d["value"] = value.duplicate(true) if value is Array or value is Dictionary else value
return d
static func from_dict(d: Dictionary) -> SheetBox:
var box := SheetBox.new(str(d.get("id", "")), str(d.get("kind", SheetKinds.TEXT)))
box.title = str(d.get("title", ""))
box.x = float(d.get("x", 0))
box.y = float(d.get("y", 0))
box.w = float(d.get("w", 192))
box.h = float(d.get("h", 96))
box.color = str(d.get("color", ""))
box.frameless = bool(d.get("frameless", false))
box.phone_order = int(d.get("phone_order", 0))
box.var_name = str(d.get("var", ""))
box.locked = bool(d.get("locked", false))
var cfg: Variant = d.get("config", {})
box.config = (cfg as Dictionary).duplicate(true) if cfg is Dictionary else {}
box.value = d.get("value", null)
return box

1
core/sheet_box.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ceappwewpq0oa

61
core/sheet_demo.gd Normal file
View file

@ -0,0 +1,61 @@
class_name SheetDemo
extends RefCounted
## An example sheet (an OSR knight, after the mockup) for screenshots
## (--sheet-demo) and tests: every kind of box on three tabs.
static func create(id: String = "demo-brin") -> SheetDoc:
var doc := SheetDoc.new(id, "Brin Hollowmere")
var main: Array = doc.tabs[0]["boxes"]
var title := _add(doc, main, "heading", "Brin Hollowmere", 1, 1, 26, 4)
title.frameless = true
var kit := _add(doc, main, "short_text", "Class", 28, 1, 12, 4)
kit.value = "Hedge Knight"
var col := 0
for stat: Array in [["Strength", "str", 14], ["Dexterity", "dex", 9], ["Willpower", "wil", 12]]:
var b := _add(doc, main, "number", stat[0], 1 + col * 9, 6, 8, 5)
b.var_name = stat[1]
b.value = stat[2]
col += 1
var mod := _add(doc, main, "formula", "STR mod", 28, 6, 8, 5)
mod.config["expr"] = "floor((@str - 10) / 2)"
mod.var_name = "str_mod"
var hp := _add(doc, main, "resource", "Hit points", 1, 12, 17, 4)
hp.value = {"cur": 6, "max": 10}
_add(doc, main, "ticks", "Stress", 19, 12, 12, 4).value = 2
var conditions := _add(doc, main, "conditions", "Conditions", 1, 17, 30, 5)
conditions.value = ["Exhausted"]
var talents := _add(doc, main, "pool", "Talents", 1, 23, 26, 12)
talents.value = [
{"Name": "Shield Wall", "Cost": 6, "Effect": "+2 Armour beside allies", "details": "When an ally stands beside you, both of you gain +2 Armour until one of you moves."},
{"Name": "Keen Eye", "Cost": 4, "Effect": "Spot hidden things", "details": "You notice traps, secret doors and lies more often than not. Roll twice and keep the better when searching."},
{"Name": "Second Wind", "Cost": 8, "Effect": "Heal once a day", "details": "Once a day, catch your breath and regain 1d6 hit points."},
]
var attack := _add(doc, main, "dice", "Longsword", 28, 23, 11, 6)
attack.config["dice"] = "1d20 + @str_mod"
_add(doc, main, "clock", "Barrow wakes", 28, 29, 8, 7).value = 2
_add(doc, main, "slots", "Inventory", 40, 1, 17, 11)
_add(doc, main, "xp", "XP", 40, 13, 17, 5).value = 2600
var oath := _add(doc, main, "text", "Oath", 40, 19, 17, 8)
oath.value = "I swore to carry the crown back to the abbey at Vel. My blows land harder ([b]+{@str_mod}[/b] to damage)."
var spells := doc.add_tab("Spells")
var magic: Array = spells["boxes"]
_add(doc, magic, "spell_slots", "Spell slots", 1, 1, 15, 8).value = [1, 0]
_add(doc, magic, "step_die", "Faith", 17, 1, 9, 5).value = "d8"
_add(doc, magic, "usage_die", "Torches", 27, 1, 10, 5)
_add(doc, magic, "ladder", "Resolve", 17, 7, 20, 5).value = 4
_add(doc, magic, "dots", "Holy favour", 1, 10, 15, 4).value = 3
var notes := doc.add_tab("Notes")
var extra: Array = notes["boxes"]
_add(doc, extra, "currency", "Purse", 1, 1, 16, 8).value = {"gp": 12, "sp": 7, "cp": 30}
_add(doc, extra, "bonds", "Bonds", 18, 1, 16, 9)
_add(doc, extra, "chips", "Aspects", 1, 9, 16, 6)
_add(doc, extra, "checkbox", "Oath kept", 18, 11, 10, 4)
_add(doc, extra, "dropdown", "Alignment", 29, 11, 12, 4)
_add(doc, extra, "divider", "", 1, 16, 40, 2)
_add(doc, extra, "table", "Gear", 1, 18, 24, 9)
return doc
static func _add(doc: SheetDoc, boxes: Array, item_id: String, title: String, gx: int, gy: int, gw: int, gh: int) -> SheetBox:
return SheetKinds.place(doc, boxes, item_id, title, Rect2i(gx, gy, gw, gh))

1
core/sheet_demo.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b0f2v0kle4b3b

139
core/sheet_doc.gd Normal file
View file

@ -0,0 +1,139 @@
class_name SheetDoc
extends RefCounted
## A sheet: a character, a vehicle, anything you keep track of. It has tabs
## (Main, Spells, Notes…), each a free canvas of boxes (SheetBox). Saved as
## JSON by SheetStore; a template is a sheet saved in the templates folder.
## Spec: docs/SHEETS.md.
const FORMAT_VERSION := 1
var id: String = ""
var name: String = "New sheet"
## Sheet tint as "#rrggbb" ("" = the theme's), e.g. to tell vehicles apart.
var tint: String = ""
## The template this sheet was made from ("" = blank).
var from_template: String = ""
## Each tab: {"id", "name", "boxes": Array[SheetBox]}.
var tabs: Array[Dictionary] = []
func _init(p_id: String = "", p_name: String = "New sheet") -> void:
id = p_id
name = p_name
if tabs.is_empty():
add_tab("Main")
func add_tab(tab_name: String) -> Dictionary:
var boxes: Array[SheetBox] = []
var tab := {"id": new_tab_id(), "name": tab_name, "boxes": boxes}
tabs.append(tab)
return tab
func new_tab_id() -> String:
var n := tabs.size() + 1
while tabs.any(func(t: Dictionary) -> bool: return t["id"] == "tab%d" % n):
n += 1
return "tab%d" % n
func get_tab(tab_id: String) -> Dictionary:
for tab in tabs:
if tab["id"] == tab_id:
return tab
return {}
## The box with `box_id` on any tab, or null.
func find_box(box_id: String) -> SheetBox:
for tab in tabs:
for box: SheetBox in tab["boxes"]:
if box.id == box_id:
return box
return null
## The tab that holds `box_id` ({} if none).
func tab_of(box_id: String) -> Dictionary:
for tab in tabs:
for box: SheetBox in tab["boxes"]:
if box.id == box_id:
return tab
return {}
## A box id not used on this sheet.
func new_box_id() -> String:
var n := 1
while find_box("b%d" % n) != null:
n += 1
return "b%d" % n
## True when `r` would cover a box on `tab` other than `skip_id` (touching
## edges is fine).
static func overlaps(tab: Dictionary, r: Rect2, skip_id: String = "") -> bool:
for box: SheetBox in tab["boxes"]:
if box.id != skip_id and box.rect().grow(-0.5).intersects(r.grow(-0.5)):
return true
return false
## The nearest free place for `r` on `tab`: scanning grid steps down and
## then across from where it was asked for. Boxes don't overlap unless
## placed freely (Alt).
static func free_spot(tab: Dictionary, r: Rect2, step: float, skip_id: String = "") -> Vector2:
if not overlaps(tab, r, skip_id):
return r.position
for ring in range(1, 200):
for dy in range(0, ring + 1):
for dx: int in [ring - dy, -(ring - dy)]:
var at := r.position + Vector2(dx, dy) * step
if at.x >= 0 and not overlaps(tab, Rect2(at, r.size), skip_id):
return at
return r.position
func remove_box(box_id: String) -> void:
var tab := tab_of(box_id)
if not tab.is_empty():
(tab["boxes"] as Array).assign((tab["boxes"] as Array).filter(func(b: SheetBox) -> bool: return b.id != box_id))
func to_dict() -> Dictionary:
var tab_list: Array = []
for tab in tabs:
var boxes: Array = []
for box: SheetBox in tab["boxes"]:
boxes.append(box.to_dict())
tab_list.append({"id": tab["id"], "name": tab["name"], "boxes": boxes})
var d := {"format_version": FORMAT_VERSION, "id": id, "name": name, "tabs": tab_list}
if tint != "":
d["tint"] = tint
if from_template != "":
d["from_template"] = from_template
return d
static func from_dict(d: Dictionary) -> SheetDoc:
var doc := SheetDoc.new(str(d.get("id", "")), str(d.get("name", "New sheet")))
doc.tint = str(d.get("tint", ""))
doc.from_template = str(d.get("from_template", ""))
var tab_list: Variant = d.get("tabs", [])
if tab_list is Array and not (tab_list as Array).is_empty():
doc.tabs.clear()
for td: Variant in tab_list:
if not td is Dictionary:
continue
var boxes: Array[SheetBox] = []
for bd: Variant in (td as Dictionary).get("boxes", []):
if bd is Dictionary:
boxes.append(SheetBox.from_dict(bd))
doc.tabs.append({"id": str(td.get("id", doc.new_tab_id())), "name": str(td.get("name", "Tab")), "boxes": boxes})
return doc
## A deep copy (through the saved form), e.g. a new sheet from a template.
func copy() -> SheetDoc:
return SheetDoc.from_dict(to_dict())

1
core/sheet_doc.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dpnmmdfjlsfhb

71
core/sheet_file.gd Normal file
View file

@ -0,0 +1,71 @@
class_name SheetFile
extends RefCounted
## A share file: one sheet as JSON that someone else can import into their
## app. Pictures in picture boxes travel inside it (base64 under "pictures",
## keyed by file name), so the receiver sees them too.
## Form: {"tabletarot_sheet": 1, "sheet": SheetDoc.to_dict(), "pictures": {name: base64}}.
const FORMAT_KEY := "tabletarot_sheet"
const FORMAT_VERSION := 1
const EXTENSION := "sheet.json"
const FILTER := "*.sheet.json, *.json ; Sheet file"
## The share file's text for `doc`.
static func share_text(doc: SheetDoc) -> String:
var pictures := {}
for tab in doc.tabs:
for box: SheetBox in tab["boxes"]:
var path := _picture_path(box)
if path == "" or pictures.has(path.get_file()):
continue
var bytes := FileAccess.get_file_as_bytes(path)
if not bytes.is_empty():
pictures[path.get_file()] = Marshalls.raw_to_base64(bytes)
var sheet := doc.to_dict()
sheet.erase("from_template") # the receiver doesn't have our templates
return JSON.stringify({FORMAT_KEY: FORMAT_VERSION, "sheet": sheet, "pictures": pictures}, "\t")
## Reads share-file `text` into `store` as a new sheet (or a template) with a
## fresh id, saved, with its pictures written back. Null if it isn't one.
static func import_text(store: SheetStore, text: String, templates: bool = false) -> SheetDoc:
var parsed: Variant = JSON.parse_string(text)
if not parsed is Dictionary or not (parsed as Dictionary).get("sheet") is Dictionary:
return null
var data: Dictionary = parsed
var doc := SheetDoc.from_dict(data["sheet"])
doc.from_template = ""
var pictures: Variant = data.get("pictures", {})
var kept := {} # file name in the share file -> path in this store
if pictures is Dictionary:
for file_name: String in pictures:
var bytes := Marshalls.base64_to_raw(str(pictures[file_name]))
kept[file_name] = store.keep_picture_bytes(bytes, file_name.get_extension())
for tab in doc.tabs:
for box: SheetBox in tab["boxes"]:
var path := _picture_path(box)
if path != "":
box.value = str(kept.get(path.get_file(), ""))
doc.id = store.free_id(doc.name, templates)
if store.save(doc, templates) != OK:
return null
return doc
static func import_path(store: SheetStore, path: String, templates: bool = false) -> SheetDoc:
if not FileAccess.file_exists(path):
return null
return import_text(store, FileAccess.get_file_as_string(path), templates)
## A file name for sharing `doc` ("brin-hollowmere.sheet.json").
static func file_name(doc: SheetDoc) -> String:
var slug := LibraryStore.slugify(doc.name)
return "%s.%s" % [slug if slug != "" else "sheet", EXTENSION]
static func _picture_path(box: SheetBox) -> String:
if box.kind != SheetKinds.PICTURE or not box.value is String:
return ""
return str(box.value)

1
core/sheet_file.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://djngvnq5jin4i

60
core/sheet_items.gd Normal file
View file

@ -0,0 +1,60 @@
class_name SheetItems
extends RefCounted
## Item sheets: a Lore Entry (BookPage) can carry a small sheet of its own,
## e.g. the Ashen Blade with Damage, Charges and Notes (BookPage.sheet holds
## its SheetStore id). Dropped into a sheet box, an entry becomes a row or an
## item; a copy gets its own copy of the item sheet (copy_sheet), a linked one
## (Shift) points at the entry's sheet. The rows' keys: "lore" (a link ref,
## SheetLoreLinks) and "sheet" (a sheet id).
## A new item sheet for `page`, saved in `store`; the page now links to it.
static func make_sheet(store: SheetStore, page: BookPage) -> SheetDoc:
var name := Formatter.strip_tags(page.label()).strip_edges()
var doc := SheetDoc.new("", name if name != "" else "Item")
var boxes: Array = doc.tabs[0]["boxes"]
SheetKinds.place(doc, boxes, SheetKinds.HEADING, doc.name, Rect2i(1, 1, 24, 3)).frameless = true
SheetKinds.place(doc, boxes, SheetKinds.SHORT_TEXT, "Damage", Rect2i(1, 5, 11, 4))
SheetKinds.place(doc, boxes, SheetKinds.NUMBER, "Charges", Rect2i(13, 5, 8, 5))
var notes := SheetKinds.place(doc, boxes, SheetKinds.TEXT, "Notes", Rect2i(1, 11, 24, 8))
notes.value = (page.text + "\n\n" + page.details).strip_edges()
doc.id = store.free_id(doc.name)
store.save(doc)
page.sheet = doc.id
return doc
## Saves a copy of sheet `id` under a new id; returns it ("" when `id` is gone).
static func copy_sheet(store: SheetStore, id: String) -> String:
var doc := store.load_sheet(id) if id != "" else null
if doc == null:
return ""
var copied := doc.copy()
copied.id = store.free_id(doc.name)
store.save(copied)
return copied.id
## The row or item a dropped entry becomes. `fields` holds the box's own
## keys (name, details or size); "lore" and "sheet" are added here.
static func with_links(fields: Dictionary, page: BookPage, ref: String, linked: bool, store: SheetStore) -> Dictionary:
var out := fields.duplicate()
if linked:
out["lore"] = ref
if page.sheet != "":
out["sheet"] = page.sheet
elif page.sheet != "":
var copied := copy_sheet(store, page.sheet)
if copied != "":
out["sheet"] = copied
return out
## The entry's text and details without formatting, for a row's details.
static func plain_text(page: BookPage) -> String:
var parts := PackedStringArray()
for part in [page.text, page.details]:
var plain := Formatter.strip_tags(part).strip_edges()
if plain != "" and plain != Formatter.strip_tags(page.label()).strip_edges():
parts.append(plain)
return "\n\n".join(parts)

1
core/sheet_items.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cnh0colx35f3s

186
core/sheet_kinds.gd Normal file
View file

@ -0,0 +1,186 @@
class_name SheetKinds
extends RefCounted
## Every kind of box you can put on a sheet, in one list: the field palette,
## new boxes' starting size, title, settings (config) and value all read it
## (the sheet's version of CardCatalog). Several palette items can share a
## kind with different start settings (a Mini table and a Point pool are
## both a "list"). How each kind looks: SheetFieldViews; its settings:
## SheetKindSettings; its value for formulas and tables: SheetValues.
## The snap grid's step, in canvas pixels.
const GRID := 16.0
const NUMBER := "number"
const SHORT_TEXT := "short_text"
const TEXT := "text"
const CHECKBOX := "checkbox"
const DROPDOWN := "dropdown"
const RESOURCE := "resource"
const TICKS := "ticks"
const CLOCK := "clock"
const DOTS := "dots"
const STEP_DIE := "step_die"
const USAGE_DIE := "usage_die"
const LADDER := "ladder"
const FORMULA := "formula"
const DICE := "dice"
const LIST := "list"
const SLOTS := "slots"
const CONDITIONS := "conditions"
const SPELL_SLOTS := "spell_slots"
const XP := "xp"
const CURRENCY := "currency"
const HEADING := "heading"
const DIVIDER := "divider"
const PICTURE := "picture"
const GROUP_BASICS := "Basics"
const GROUP_TRACKERS := "Trackers"
const GROUP_SMART := "Smart"
const GROUP_LISTS := "Lists"
const GROUP_LAYOUT := "Layout"
const DIE_STEPS := ["d4", "d6", "d8", "d10", "d12"]
const FATE_LADDER := ["Terrible", "Poor", "Mediocre", "Average", "Fair", "Good", "Great", "Superb", "Fantastic", "Epic", "Legendary"]
## Each item: id, kind, label, group, tip, search words, start size (w, h in
## grid steps), title, config and value.
const ITEMS := [
{"id": "number", "kind": NUMBER, "label": "Number", "group": GROUP_BASICS, "tip": "A stat or count, like Strength 14",
"words": "stat score value count", "w": 8, "h": 5, "title": "Number", "config": {}, "value": 0},
{"id": "short_text", "kind": SHORT_TEXT, "label": "Short text", "group": GROUP_BASICS, "tip": "One line: a name, a class, a word",
"words": "name word line", "w": 12, "h": 4, "title": "Name", "config": {}, "value": ""},
{"id": "text", "kind": TEXT, "label": "Long notes", "group": GROUP_BASICS, "tip": "Notes or a description, with formatting and live values like {@str}",
"words": "notes description bbcode text paragraph", "w": 14, "h": 8, "title": "Notes", "config": {}, "value": ""},
{"id": "checkbox", "kind": CHECKBOX, "label": "Checkbox", "group": GROUP_BASICS, "tip": "Yes or no, like Inspired",
"words": "tick yes no toggle", "w": 10, "h": 4, "title": "Inspired", "config": {}, "value": false},
{"id": "dropdown", "kind": DROPDOWN, "label": "Dropdown", "group": GROUP_BASICS, "tip": "Pick one from a list you write",
"words": "choice pick list select", "w": 12, "h": 4, "title": "Alignment",
"config": {"options": ["Lawful", "Neutral", "Chaotic"]}, "value": "Neutral"},
{"id": "resource", "kind": RESOURCE, "label": "Current / max", "group": GROUP_TRACKERS, "tip": "A bar like HP 6 / 10",
"words": "hp bar health resource mana", "w": 14, "h": 4, "title": "HP", "config": {"color": "#a33a2c"}, "value": {"cur": 10, "max": 10}},
{"id": "ticks", "kind": TICKS, "label": "Tick boxes", "group": GROUP_TRACKERS, "tip": "A row of boxes to mark, like stress or ammo",
"words": "stress ammo boxes marks", "w": 12, "h": 4, "title": "Stress", "config": {"count": 5}, "value": 0},
{"id": "clock", "kind": CLOCK, "label": "Clock", "group": GROUP_TRACKERS, "tip": "A progress clock you fill in segments",
"words": "progress segments countdown", "w": 8, "h": 7, "title": "Clock", "config": {"segments": 6}, "value": 0},
{"id": "dots", "kind": DOTS, "label": "Dot rating", "group": GROUP_TRACKERS, "tip": "A rating in dots like ●●●○○",
"words": "dots stars rating", "w": 12, "h": 4, "title": "Rating", "config": {"max": 5}, "value": 2},
{"id": "step_die", "kind": STEP_DIE, "label": "Step die", "group": GROUP_TRACKERS, "tip": "A die that steps up or down, d4 to d12",
"words": "d4 d6 d8 d10 d12 dice trait", "w": 8, "h": 5, "title": "Trait", "config": {}, "value": "d6"},
{"id": "usage_die", "kind": USAGE_DIE, "label": "Usage die", "group": GROUP_TRACKERS, "tip": "Roll it when used; on a 1–2 it shrinks (torches, rations)",
"words": "dice shrink torches rations supply", "w": 10, "h": 5, "title": "Torches", "config": {}, "value": "d8"},
{"id": "ladder", "kind": LADDER, "label": "Word ladder", "group": GROUP_TRACKERS, "tip": "A rating in words, like the Fate ladder",
"words": "fate rating scale words", "w": 12, "h": 5, "title": "Rating", "config": {"steps": FATE_LADDER}, "value": 4},
{"id": "formula", "kind": FORMULA, "label": "Formula", "group": GROUP_SMART, "tip": "Worked out from other values, like (@str - 10) / 2",
"words": "computed modifier math calculate", "w": 8, "h": 5, "title": "Modifier", "config": {"expr": "floor((@str - 10) / 2)"}, "value": null},
{"id": "dice", "kind": DICE, "label": "Dice button", "group": GROUP_SMART, "tip": "Rolls dice with sheet values, like 1d20 + @str",
"words": "roll attack damage", "w": 10, "h": 5, "title": "Attack", "config": {"dice": "1d20 + @str"}, "value": null},
{"id": "rows", "kind": LIST, "label": "Rows box", "group": GROUP_LISTS, "tip": "Many entries in one box: a name and a value per row",
"words": "multi entry stats skills list", "w": 13, "h": 12, "title": "Skills",
"config": {"style": "rows", "columns": [{"name": "Name", "type": "text"}, {"name": "Value", "type": "number"}]},
"value": [{"Name": "Climb", "Value": 2}, {"Name": "Sneak", "Value": 1}]},
{"id": "table", "kind": LIST, "label": "Mini table", "group": GROUP_LISTS, "tip": "Entries with columns you choose",
"words": "columns table list", "w": 18, "h": 10, "title": "Gear",
"config": {"style": "table", "columns": [{"name": "Name", "type": "text"}, {"name": "Qty", "type": "number"}, {"name": "Notes", "type": "text"}]},
"value": [{"Name": "Rope", "Qty": 1, "Notes": "50 ft"}]},
{"id": "chips", "kind": LIST, "label": "Chips", "group": GROUP_LISTS, "tip": "Short entries side by side, like tags",
"words": "inline tags aspects", "w": 16, "h": 6, "title": "Aspects",
"config": {"style": "chips", "columns": [{"name": "Name", "type": "text"}]}, "value": [{"Name": "Hedge knight"}, {"Name": "Owes the ferryman"}]},
{"id": "pool", "kind": LIST, "label": "Point pool", "group": GROUP_LISTS, "tip": "A stock of points; each entry's cost comes off it",
"words": "points buy spend cost talents", "w": 20, "h": 12, "title": "Talents",
"config": {"style": "table", "pool": 20, "cost_column": "Cost",
"columns": [{"name": "Name", "type": "text"}, {"name": "Cost", "type": "number"}, {"name": "Effect", "type": "text"}]},
"value": [{"Name": "Shield Wall", "Cost": 6, "Effect": "+2 Armour beside allies", "details": "When an ally stands beside you, both of you gain +2 Armour until one of you moves."}]},
{"id": "bonds", "kind": LIST, "label": "Bonds", "group": GROUP_LISTS, "tip": "People and ties, each with a rating",
"words": "relationships bonds contacts ties", "w": 14, "h": 9, "title": "Bonds",
"config": {"style": "rows", "columns": [{"name": "Name", "type": "text"}, {"name": "Bond", "type": "number"}]},
"value": [{"Name": "Mother Ilse", "Bond": 2}]},
{"id": "slots", "kind": SLOTS, "label": "Slots", "group": GROUP_LISTS, "tip": "Slot inventory: items take slots; a full pack warns",
"words": "inventory encumbrance gear pack", "w": 16, "h": 11, "title": "Inventory", "config": {"slots": 10},
"value": [{"name": "Longsword", "size": 2}, {"name": "Rations", "size": 1}]},
{"id": "conditions", "kind": CONDITIONS, "label": "Conditions", "group": GROUP_LISTS, "tip": "Toggle chips like Poisoned or Exhausted",
"words": "tags status poisoned exhausted", "w": 16, "h": 6, "title": "Conditions",
"config": {"options": ["Poisoned", "Exhausted", "Frightened", "Wounded"]}, "value": []},
{"id": "spell_slots", "kind": SPELL_SLOTS, "label": "Spell slots", "group": GROUP_LISTS, "tip": "Slots per spell level to mark as used",
"words": "magic spells levels slots", "w": 14, "h": 8, "title": "Spell slots",
"config": {"levels": [{"name": "1st", "max": 4}, {"name": "2nd", "max": 2}]}, "value": [0, 0]},
{"id": "xp", "kind": XP, "label": "XP", "group": GROUP_LISTS, "tip": "Experience with the level it reaches and how far to the next",
"words": "experience level advancement", "w": 14, "h": 5, "title": "XP", "config": {"levels": [0, 2000, 4000, 8000, 16000]}, "value": 0},
{"id": "currency", "kind": CURRENCY, "label": "Currency", "group": GROUP_LISTS, "tip": "Coins with exchange rates and a total",
"words": "money coins gold silver copper", "w": 14, "h": 7, "title": "Purse",
"config": {"coins": [{"name": "gp", "rate": 1.0}, {"name": "sp", "rate": 0.1}, {"name": "cp", "rate": 0.01}]}, "value": {"gp": 0, "sp": 0, "cp": 0}},
{"id": "heading", "kind": HEADING, "label": "Heading", "group": GROUP_LAYOUT, "tip": "A title to label part of the sheet",
"words": "title label section", "w": 14, "h": 4, "title": "Heading", "config": {}, "value": null},
{"id": "divider", "kind": DIVIDER, "label": "Divider", "group": GROUP_LAYOUT, "tip": "A line between parts of the sheet",
"words": "line rule separator", "w": 20, "h": 2, "title": "", "config": {}, "value": null},
{"id": "picture", "kind": PICTURE, "label": "Picture", "group": GROUP_LAYOUT, "tip": "A portrait or picture from a file",
"words": "image portrait art", "w": 10, "h": 10, "title": "Portrait", "config": {}, "value": ""},
]
## The palette item with `id` ({} if none).
static func item(id: String) -> Dictionary:
for it: Dictionary in ITEMS:
if it["id"] == id:
return it
return {}
## The first palette item of `kind` ({} if none).
static func find(kind: String) -> Dictionary:
for it: Dictionary in ITEMS:
if it["kind"] == kind:
return it
return {}
## The name to show for a box's kind: its palette item's label.
static func label_of(box: SheetBox) -> String:
var it := item(str(box.config.get("preset", "")))
if it.is_empty():
it = find(box.kind)
return str(it.get("label", box.kind))
static func groups() -> Array[String]:
var out: Array[String] = []
for it: Dictionary in ITEMS:
if not out.has(it["group"]):
out.append(it["group"])
return out
## A new box from palette item `item_id` (or the first item of that kind) with
## its start size, title, settings and value, top-left at `at`.
static func make_box(item_id: String, id: String, at: Vector2) -> SheetBox:
var it := item(item_id)
if it.is_empty():
it = find(item_id)
var box := SheetBox.new(id, str(it.get("kind", TEXT)))
box.title = str(it.get("title", ""))
box.x = snap(at.x)
box.y = snap(at.y)
box.w = float(it.get("w", 12)) * GRID
box.h = float(it.get("h", 6)) * GRID
box.config = (it.get("config", {}) as Dictionary).duplicate(true)
if str(it.get("id", "")) != str(it.get("kind", "")):
box.config["preset"] = it["id"]
var start: Variant = it.get("value", null)
box.value = start.duplicate(true) if start is Array or start is Dictionary else start
return box
## Adds a box from palette item `item_id` to `boxes` of `doc`, placed on the
## grid by `cells` (x, y, width, height in grid steps), and returns it.
static func place(doc: SheetDoc, boxes: Array, item_id: String, title: String, cells: Rect2i) -> SheetBox:
var box := make_box(item_id, doc.new_box_id(), Vector2(cells.position) * GRID)
box.title = title
box.w = cells.size.x * GRID
box.h = cells.size.y * GRID
boxes.append(box)
return box
## Rounds to the nearest grid step.
static func snap(v: float) -> float:
return roundf(v / GRID) * GRID

1
core/sheet_kinds.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ddb544613vx0g

94
core/sheet_links.gd Normal file
View file

@ -0,0 +1,94 @@
class_name SheetLinks
extends RefCounted
## The bridge between a spread and the sheets on it (Sheet cards with a
## RollTable.sheet_id). Before a roll, every "Use in tables" box of each linked sheet
## becomes a spread variable: @var, or @prefix_var when the node has a prefix
## (RollTable.sheet_prefix: two characters on one spread). After the roll, values the roll changed go
## back into their boxes, unless the box is locked or its kind can't take a
## value (formulas, lists…); a locked box puts the variable back.
## Kinds a roll can write into, and how the value is stored.
const WRITABLE := [SheetKinds.NUMBER, SheetKinds.SHORT_TEXT, SheetKinds.TEXT, SheetKinds.CHECKBOX,
SheetKinds.DROPDOWN, SheetKinds.RESOURCE, SheetKinds.TICKS, SheetKinds.CLOCK, SheetKinds.DOTS,
SheetKinds.LADDER, SheetKinds.XP]
## The spread variable name for a box on a card: "str" or "brin_str".
static func var_for(card: RollTable, box: SheetBox) -> String:
var prefix := card.sheet_prefix.strip_edges()
return box.var_name if prefix == "" else "%s_%s" % [prefix, box.var_name]
## The spread's Sheet cards that show a sheet.
static func sheet_cards(board: TowerBoard) -> Array[RollTable]:
var out: Array[RollTable] = []
for t in board.tables:
if t.kind == RollTable.KIND_SHEET and t.sheet_id != "":
out.append(t)
return out
## Puts every linked box's value into `vars` (name -> {"value", "source"}).
## Returns what was put in: name -> {"sheet", "box", "value"}, for write_back.
## `load_doc` gives a SheetDoc for a sheet id (null when it is gone).
static func inject(board: TowerBoard, vars: Dictionary, load_doc: Callable) -> Dictionary:
var given := {}
for card in sheet_cards(board):
var doc: SheetDoc = load_doc.call(card.sheet_id)
if doc == null:
continue
var values := SheetValues.vars(doc)
for tab in doc.tabs:
for box: SheetBox in tab["boxes"]:
if box.var_name == "" or not values.has(box.var_name):
continue
var name := var_for(card, box)
var v: Variant = _plain(values[box.var_name])
vars[name] = {"value": v, "source": "sheet %s" % doc.name}
given[name] = {"sheet": doc.id, "box": box.id, "value": v}
return given
## After a roll: each variable that changed goes into its box. Returns
## [{"sheet", "box", "name", "value", "locked"}] for every change seen; locked
## boxes keep their value and their variable is put back.
static func changes(given: Dictionary, vars: Dictionary) -> Array:
var out: Array = []
for name: String in given:
var g: Dictionary = given[name]
var entry: Variant = vars.get(name)
var now: Variant = (entry as Dictionary).get("value") if entry is Dictionary else entry
if now == null or str(now) == str(g["value"]):
continue
out.append({"sheet": g["sheet"], "box": g["box"], "name": name, "value": now})
return out
## Writes `value` into `box` as its kind stores it. False when the box is
## locked or its kind can't take a value (the caller puts the variable back).
static func write(box: SheetBox, value: Variant) -> bool:
if box.locked or not WRITABLE.has(box.kind):
return false
match box.kind:
SheetKinds.NUMBER, SheetKinds.XP:
box.value = Expr.normalize(SheetValues.number(value))
SheetKinds.CHECKBOX:
box.value = Expr.truthy(value)
SheetKinds.RESOURCE:
var v: Dictionary = (box.value as Dictionary).duplicate() if box.value is Dictionary else {"cur": 0, "max": 10}
v["cur"] = int(SheetValues.number(value))
box.value = v
SheetKinds.TICKS, SheetKinds.CLOCK, SheetKinds.DOTS, SheetKinds.LADDER:
box.value = int(SheetValues.number(value))
_:
box.value = str(value)
return true
## Spread variables hold numbers and text only.
static func _plain(v: Variant) -> Variant:
if v is int or v is float or v is String:
return Expr.normalize(v)
if v == null:
return ""
return str(v)

1
core/sheet_links.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://vplavq1hccr2

135
core/sheet_store.gd Normal file
View file

@ -0,0 +1,135 @@
class_name SheetStore
extends RefCounted
## Sheets and sheet templates as JSON files: user://sheets/<id>.json and
## user://sheet_templates/<id>.json. `root` can point elsewhere for tests.
const SHEETS := "sheets"
const TEMPLATES := "sheet_templates"
var root := "user://"
func _init(p_root: String = "user://") -> void:
root = p_root
func dir_for(templates: bool) -> String:
return root.path_join(TEMPLATES if templates else SHEETS)
func path_for(id: String, templates: bool) -> String:
return dir_for(templates).path_join(id + ".json")
## Rows for the Sheets list, newest first: {id, name, modified, from_template}.
func list(templates: bool = false) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var dir := dir_for(templates)
if not DirAccess.dir_exists_absolute(dir):
return out
for file in DirAccess.get_files_at(dir):
if not file.ends_with(".json"):
continue
var path := dir.path_join(file)
var d := _read(path)
if d.is_empty():
continue
out.append({"id": file.get_basename(), "name": str(d.get("name", file.get_basename())),
"modified": FileAccess.get_modified_time(path), "from_template": str(d.get("from_template", ""))})
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: return int(a["modified"]) > int(b["modified"]))
return out
## The sheet with `id`, or null.
func load_sheet(id: String, templates: bool = false) -> SheetDoc:
if not LibraryStore.is_valid_id(id):
return null
var d := _read(path_for(id, templates))
if d.is_empty():
return null
var doc := SheetDoc.from_dict(d)
doc.id = id
return doc
func save(doc: SheetDoc, templates: bool = false) -> Error:
if not LibraryStore.is_valid_id(doc.id):
return ERR_INVALID_PARAMETER
DirAccess.make_dir_recursive_absolute(dir_for(templates))
return BoardFileIO.write_text_atomic(path_for(doc.id, templates), JSON.stringify(doc.to_dict(), "\t"))
func delete(id: String, templates: bool = false) -> Error:
if not LibraryStore.is_valid_id(id):
return ERR_INVALID_PARAMETER
return DirAccess.remove_absolute(path_for(id, templates))
## A file id from `name` not used yet in that folder ("brin", "brin-2"…).
func free_id(name: String, templates: bool = false) -> String:
var base := LibraryStore.slugify(name)
if base == "":
base = "sheet"
var id := base
var n := 2
while FileAccess.file_exists(path_for(id, templates)):
id = "%s-%d" % [base, n]
n += 1
return id
## Copies a picture into the sheets' pictures folder (so the sheet keeps it
## if the original moves) and returns the copy's path ("" if unreadable).
func keep_picture(path: String) -> String:
return keep_picture_bytes(FileAccess.get_file_as_bytes(path), path.get_extension())
## Saves picture `bytes` in the pictures folder, named by their hash (the
## same picture is kept once); returns its path ("" if it can't).
func keep_picture_bytes(bytes: PackedByteArray, extension: String) -> String:
if bytes.is_empty():
return ""
DirAccess.make_dir_recursive_absolute(pictures_dir())
var kept := pictures_dir().path_join("%s.%s" % [str(hash(bytes)).replace("-", "n"), extension.to_lower()])
var file := FileAccess.open(kept, FileAccess.WRITE)
if file == null:
return ""
file.store_buffer(bytes)
return kept
func pictures_dir() -> String:
return dir_for(false).path_join("pictures")
## A new sheet, blank or copied from a template, saved and returned.
func create(name: String, template_id: String = "") -> SheetDoc:
var doc: SheetDoc = null
if template_id != "":
var tpl := load_sheet(template_id, true)
if tpl:
doc = tpl.copy()
doc.from_template = template_id
if doc == null:
doc = SheetDoc.new()
doc.name = name
doc.id = free_id(name)
save(doc)
return doc
## Saves a copy of `doc` as a template named `name`; returns its id.
func save_as_template(doc: SheetDoc, name: String) -> String:
var tpl := doc.copy()
tpl.name = name
tpl.from_template = ""
tpl.id = free_id(name, true)
save(tpl, true)
return tpl.id
func _read(path: String) -> Dictionary:
if not FileAccess.file_exists(path):
return {}
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
return parsed if parsed is Dictionary else {}

1
core/sheet_store.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://f35bed3tfxiq

84
core/sheet_text.gd Normal file
View file

@ -0,0 +1,84 @@
class_name SheetText
extends RefCounted
## A sheet as one block of BBCode, for when a roll reaches its card: the tray
## headline, "Copy" and "Save as a file" show it (docs/LOGIC.md §6). Boxes
## used in tables become {@name} (with the card's prefix), so the roll fills
## in the values it just set; other boxes show their current value. Text
## boxes keep their own BBCode and {@…}, so they can show spread values too.
static func summary(doc: SheetDoc, prefix: String = "") -> String:
var lines: Array[String] = []
for tab in doc.tabs:
var text := tab_text(doc, tab, prefix)
if text != "":
lines.append(text)
return "\n".join(lines)
## One tab's boxes in reading order (top-down, then left-right). With
## `placeholders` off, boxes used in tables show their values instead of
## {@name} (the sheet's own print-out).
static func tab_text(doc: SheetDoc, tab: Dictionary, prefix: String = "", placeholders: bool = true) -> String:
var lines: Array[String] = []
var boxes: Array = (tab["boxes"] as Array).duplicate()
boxes.sort_custom(func(a: SheetBox, b: SheetBox) -> bool: return a.y < b.y or (a.y == b.y and a.x < b.x))
for box: SheetBox in boxes:
var line := _line(doc, box, prefix, placeholders)
if line != "":
lines.append(line)
return "\n".join(lines)
static func _line(doc: SheetDoc, box: SheetBox, prefix: String, placeholders: bool) -> String:
match box.kind:
SheetKinds.HEADING:
return "[b]%s[/b]" % box.title
SheetKinds.DIVIDER, SheetKinds.PICTURE, SheetKinds.DICE:
return ""
SheetKinds.TEXT:
var text := str(box.value if box.value != null else "").strip_edges()
if text == "":
return ""
return text if box.title == "" else "[b]%s:[/b] %s" % [box.title, text]
var shown := ""
if placeholders and box.var_name != "" and SheetLinks.WRITABLE.has(box.kind):
shown = "{@%s}" % (box.var_name if prefix == "" else "%s_%s" % [prefix, box.var_name])
else:
shown = _value(doc, box)
if shown == "":
return ""
return "[b]%s:[/b] %s" % [box.title, shown] if box.title != "" else shown
## A box's value in words: lists by their names, currency with its total…
static func _value(doc: SheetDoc, box: SheetBox) -> String:
var v: Variant = box.value
match box.kind:
SheetKinds.RESOURCE:
var r: Dictionary = v if v is Dictionary else {}
return "%s / %s" % [SheetValues.show(r.get("cur", 0)), SheetValues.show(r.get("max", 0))]
SheetKinds.LIST:
var names: Array = []
var cols: Array = box.config.get("columns", [])
var first := str((cols[0] as Dictionary).get("name", "Name")) if not cols.is_empty() else "Name"
for entry: Variant in (v if v is Array else []):
if entry is Dictionary:
names.append(str((entry as Dictionary).get(first, "")))
return ", ".join(names)
SheetKinds.SLOTS:
return ", ".join((v if v is Array else []).map(func(it: Variant) -> String: return str((it as Dictionary).get("name", "")) if it is Dictionary else ""))
SheetKinds.CONDITIONS:
return ", ".join((v if v is Array else []).map(func(x: Variant) -> String: return str(x)))
SheetKinds.CURRENCY:
var coins: Array = box.config.get("coins", [])
return "%s %s" % [SheetValues.show(SheetValues.currency_total(box)), str((coins[0] as Dictionary).get("name", "")) if not coins.is_empty() else ""]
SheetKinds.STEP_DIE, SheetKinds.USAGE_DIE, SheetKinds.SHORT_TEXT, SheetKinds.DROPDOWN:
return str(v if v != null else "")
SheetKinds.CHECKBOX:
return "Yes" if bool(v) else "No"
SheetKinds.LADDER:
var steps: Array = box.config.get("steps", SheetKinds.FATE_LADDER)
var i := int(SheetValues.number(v))
return str(steps[i]) if i >= 0 and i < steps.size() else ""
return SheetValues.show(SheetValues.value_of(doc, box))

1
core/sheet_text.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b4rdf1t4kkobt

135
core/sheet_values.gd Normal file
View file

@ -0,0 +1,135 @@
class_name SheetValues
extends RefCounted
## What a sheet's boxes are worth as values: for formulas, dice buttons, live
## {@name} text and (later) tables. A box counts once it has a name for
## tables (SheetBox.var_name). Each kind reads as one plain value: a number
## its number, a bar its current value, a checkbox 1 or 0, a list how many
## entries, currency its total, a formula its result.
## Formulas that use formulas stop this deep (a loop reads as 0).
const MAX_DEPTH := 8
## Every named box's value: {var_name: value}.
static func vars(doc: SheetDoc, depth: int = 0) -> Dictionary:
var out := {}
for tab in doc.tabs:
for box: SheetBox in tab["boxes"]:
if box.var_name != "":
out[box.var_name] = value_of(doc, box, depth)
return out
static func value_of(doc: SheetDoc, box: SheetBox, depth: int = 0) -> Variant:
var v: Variant = box.value
match box.kind:
SheetKinds.NUMBER, SheetKinds.TICKS, SheetKinds.CLOCK, SheetKinds.DOTS, SheetKinds.LADDER, SheetKinds.XP:
return number(v)
SheetKinds.CHECKBOX:
return 1 if bool(v) else 0
SheetKinds.RESOURCE:
return number((v as Dictionary).get("cur", 0)) if v is Dictionary else 0
SheetKinds.LIST, SheetKinds.SLOTS, SheetKinds.CONDITIONS:
return (v as Array).size() if v is Array else 0
SheetKinds.SPELL_SLOTS:
return slots_left(box)
SheetKinds.CURRENCY:
return currency_total(box)
SheetKinds.FORMULA:
return formula(doc, box, depth)["value"]
SheetKinds.HEADING, SheetKinds.DIVIDER, SheetKinds.DICE:
return null
return str(v) if v != null else ""
## A formula box's result: {"value", "error"}. A formula that reads itself,
## directly or through other formulas, is an error.
static func formula(doc: SheetDoc, box: SheetBox, depth: int = 0) -> Dictionary:
if depth == 0 and _loops(doc, box, []):
return {"value": null, "error": "This formula uses itself"}
return evaluate(doc, str(box.config.get("expr", "")), depth)
## True when following the @names a formula reads leads back to a box on `path`.
static func _loops(doc: SheetDoc, box: SheetBox, path: Array) -> bool:
if path.has(box.id):
return true
var next := path + [box.id]
for name: String in Expr.names_in(str(box.config.get("expr", ""))):
for tab in doc.tabs:
for other: SheetBox in tab["boxes"]:
if other.kind == SheetKinds.FORMULA and other.var_name != "" and other.var_name == name.trim_prefix("@"):
if _loops(doc, other, next):
return true
return false
## Works out `src` (the rule language, docs/LOGIC.md §4) with the sheet's
## values as @variables. Dice in it roll. {"value", "error"}.
static func evaluate(doc: SheetDoc, src: String, depth: int = 0, rng: RandomNumberGenerator = null) -> Dictionary:
if src.strip_edges() == "":
return {"value": null, "error": ""}
if depth >= MAX_DEPTH:
return {"value": 0, "error": "A formula uses itself"}
return Expr.evaluate(src, RollContext.new(vars(doc, depth + 1), rng))
static func number(v: Variant) -> float:
if v is int or v is float:
return float(v)
if v is bool:
return 1.0 if v else 0.0
if v is String and (v as String).strip_edges().is_valid_float():
return (v as String).to_float()
return 0.0
## "14" for whole numbers, "2.5" otherwise.
static func show(v: Variant) -> String:
if v == null:
return "—"
if v is int or v is float:
var n := float(v)
return str(int(n)) if n == floorf(n) else str(snappedf(n, 0.01))
return str(v)
static func currency_total(box: SheetBox) -> float:
var total := 0.0
var held: Dictionary = box.value if box.value is Dictionary else {}
for coin: Dictionary in box.config.get("coins", []):
total += number(held.get(coin.get("name", ""), 0)) * number(coin.get("rate", 1))
return total
static func slots_left(box: SheetBox) -> int:
var used: Array = box.value if box.value is Array else []
var left := 0
var levels: Array = box.config.get("levels", [])
for i in levels.size():
left += int(number((levels[i] as Dictionary).get("max", 0))) - (int(number(used[i])) if i < used.size() else 0)
return left
## A list's point pool: {"total", "spent", "left"} (total 0 = no pool).
static func pool(box: SheetBox) -> Dictionary:
var total := number(box.config.get("pool", 0))
var column := str(box.config.get("cost_column", "Cost"))
var spent := 0.0
for entry: Variant in (box.value if box.value is Array else []):
if entry is Dictionary:
spent += number((entry as Dictionary).get(column, 0))
return {"total": total, "spent": spent, "left": total - spent}
## The XP box's level (1 = first) and the next threshold (-1 at the top).
static func xp_level(box: SheetBox) -> Dictionary:
var xp := number(box.value)
var levels: Array = box.config.get("levels", [0])
var level := 1
for i in levels.size():
if xp >= number(levels[i]):
level = i + 1
var next := number(levels[level]) if level < levels.size() else -1.0
var prev := number(levels[level - 1]) if level - 1 < levels.size() else 0.0
return {"level": level, "next": next, "prev": prev}

1
core/sheet_values.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://c88b3omlh3rka

57
core/snapshot_history.gd Normal file
View file

@ -0,0 +1,57 @@
class_name SnapshotHistory
extends RefCounted
## Undo and redo by whole snapshots (Dictionaries), for small documents such
## as a sheet. The caller records the state before each edit (record) and
## gets back the state to show on undo or redo. Spreads use EditHistory, which
## keeps per-card strings because spreads can be large.
const MAX_STEPS := 200
var _undo: Array = [] # [{"state", "label"}]
var _redo: Array = []
func can_undo() -> bool:
return not _undo.is_empty()
func can_redo() -> bool:
return not _redo.is_empty()
func undo_label() -> String:
return str(_undo.back()["label"]) if can_undo() else ""
func redo_label() -> String:
return str(_redo.back()["label"]) if can_redo() else ""
func clear() -> void:
_undo.clear()
_redo.clear()
## Records `before`, the state just before an edit called `label`. Clears redo.
func record(before: Dictionary, label: String) -> void:
_undo.append({"state": before.duplicate(true), "label": label})
if _undo.size() > MAX_STEPS:
_undo.pop_front()
_redo.clear()
## Steps back: give the current state, get the one to show ({} if none).
func undo(current: Dictionary) -> Dictionary:
if not can_undo():
return {}
var step: Dictionary = _undo.pop_back()
_redo.append({"state": current.duplicate(true), "label": step["label"]})
return step["state"]
func redo(current: Dictionary) -> Dictionary:
if not can_redo():
return {}
var step: Dictionary = _redo.pop_back()
_undo.append({"state": current.duplicate(true), "label": step["label"]})
return step["state"]

View file

@ -0,0 +1 @@
uid://ot0yekk00psr

View file

@ -12,8 +12,8 @@ Read on demand (not every session). Status and plan: `docs/DESIGN.md`.
- **Play / Build modes.** Collapse a card, or every table from **View ▾**. Pan, zoom (8%–150%) with the
**− 90% ▾ +** control (the percentage opens Fit board, Zoom to 100% and the minimap), minimap (M).
- **Top bar.** Search (icon, Ctrl+F), **View ▾** (rules as Plain words or Rule text, Collapse/Expand
all tables, Striped rows, Minimap), **Help ▾** and the zoom control. Build adds undo/redo, + Card ▾
and Board ▾ (Test board, Reset sample, Pack collapsed groups, import, export).
all tables, Striped rows, Minimap), **Help ▾** and the zoom control. Build adds undo/redo
and Spread ▾ (Test board, Reset sample, Pack collapsed groups, import, export).
- **Striped rows.** Every second result row on a card is tinted (`Style.STRIPE`); lit, flicker and
selection paint over it. On by default; the `striped_rows` local setting.
- **Help.** Help ▾ lists the topics; F1 opens the window. Text in `help/topics.txt` (a small markup,
@ -63,13 +63,13 @@ Read on demand (not every session). Status and plan: `docs/DESIGN.md`.
- Rolls, variables and decks aren't undoable.
- Collection members aren't undoable either.
- **Group cards.** Frames that collapse whole blocks. Ctrl/Shift-click or Ctrl-drag to
select, Ctrl+G to group, then drag cards in or out, rename, ungroup or delete. Board ▾ → Pack collapsed groups.
select, Ctrl+G to group, then drag cards in or out, rename, ungroup or delete. Spread ▾ → Pack collapsed groups.
- **Templates.** Save a card, group or selection, with `{$param}` fill-ins. Insert from
"+ Card ▾ → From template…". The library is in `user://templates/`, and generic built-ins are in `templates/`:
the card palette's Templates group ("All templates…" opens the picker). The library is in `user://templates/`, and generic built-ins are in `templates/`:
skill check (a Check card, 2d6 + modifier vs target), ask-and-repeat, pick menu, counter
and simple sheet.
- **Search** (button or Ctrl+F) jumps to cards, opens groups and flashes the card.
- **Test board** (Board ▾): hundreds of random rolls plus static checks. It reports
- **Test board** (Spread ▾): hundreds of random rolls plus static checks. It reports
errors, dead ends, unreached cards and lint, and clicking an item jumps to the card.
- **Collections** (switcher in the top bar). Import and export via Board ▾: TableTower
JSON, JSON Canvas, GraphML (both ways), plus Mermaid and DOT (export only).
@ -154,8 +154,13 @@ templates/ built-in templates · examples/logic_demo.json (original demo board)
geometry/list/kind_rows.gd` (next to header/rows/editing/value/text).
- **Menus and selection:** `ui/actions.gd` (all menus), `ui/main_selection.gd` (groups in the
selection), `ui/main_layout.gd` (Main's layout, saving, mode, input; Main keeps delegators).
- **Left dock and card palette (2026-11-29):** `ui/left_dock.gd` ("Cards | List" tabs, setting
`left_dock`), `ui/card_palette.gd` (search, groups, click/drag to add, Play notice),
`ui/card_catalog.gd` (every card kind: one list for the palette, right-click › New card and
new-card names; variants "dice" and "deck"). `SideTabs.tab_row` is the shared dock tab style.
- **Lists and phones:** `ui/list_view.gd`, `ui/list_tree.gd`, `ui/list_order.gd`,
`ui/mobile_layout.gd`, `ui/touch_input.gd`.
`ui/mobile_layout.gd`, `ui/touch_input.gd`; sheets on phones: `ui/sheet_phone_layout.gd`,
`ui/sheet_stack_view.gd` (SHEETS.md E4).
- **Book and pictures:** `core/book_page.gd`, `core/board_images.gd`, `ui/book_panel.gd`,
`ui/page_editor.gd`, `ui/image_field.gd`. `TowerBoard` has `book`, `images`, nesting helpers
(`tables_in`, `groups_in`, `hidden_by`, `set_group_parent`).
@ -242,6 +247,9 @@ Each original file keeps one-line delegators, so callers are unchanged.
open ones build; `activate` points `selection`/`fields`/`effects` at the section clicked in),
`ui/inspector_range.gd` (a result's weight, range and position).
- **Dock tabs:** `ui/side_tabs.gd` (Build: Inspector | Lore Index; `BookPanel` is the Lore Index).
- **Lore Index (2026-11-29, E3):** `ui/lore_list.gd` (the shared list + `PageEditor`, used by `BookPanel` on the
spread and `SheetLoreDock` in the sheet editor), levels `ui/lore_level.gd` (+ `_spread`, `_library`),
`core/lore_library.gd` (My library file), `ui/lore_entry_actions.gd` (Copy to…, item sheet).
- **Rolling:** `ui/skip_animations.gd` (View ▾ setting); `ModalCard.animate_in` (pop-up entrance).
- **Look:** `ui/card_move_handle.gd` (Build grip on the header; `CardGrip` is the resize corner);
theme tokens `SELECTED` and `CARD_HEAD` (derived from CARD/CARD_SHADE when a theme omits it).

View file

@ -1,6 +1,6 @@
# Table Tarot (repo: TableTower) — Status and Plan
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-25 (test time
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-29 (Sheets merged; before that 2026-11-25, test time
budget and test audit, branch `test-budget`)
The short page to read at the start of every session. Everything else is read only when needed:
@ -33,6 +33,16 @@ mascot, **Morgan Fortuna** ("Morgan"; they/them in any UI text, kept gender-neut
| Ledger (card kind; "for the time being", user 2026-11-11) | variable card, `var_type: "collection"` |
Card, Result, Change, Reset, Dice wording rules: `docs/HISTORY.md` §6 "Terminology".
## 3a. Sheets and the unified editor (2026-11-29, merged to `main`)
Spec, the user's decisions, phases and code map: `docs/SHEETS.md`. All phases built, tested and
merged: A card palette (left dock Cards | List, search, drag to add), B main menu + Sheets + sheet
editor, C every field kind, D sheets on spreads as linked Sheet cards (@name / @prefix_name, locks,
old Sheet cards migrated), E export/import, text toolbar + Lore links, Lore Index "My library" +
item sheets, phone stacked view. The user hand-tested A–D during the work; E only lightly.
**Open for the user:** the setting limits (ticks 40, dots 20, clock 24, slots 60, phone order 999,
undo 200 steps, formula depth 8) and the review list at the end of `docs/SHEETS.md`.
**Size audit due:** `ui/sheet_editor.gd` ~373 lines, `ui/main_cli.gd` ~309.
## 3. Where things stand (2026-11-11)
- **Everything from the 2026-11-10 plan is built, tested and on `main`** (pushed): theme system,
rename and reskin, spread interaction, menus, Deck mode, nested groups, List view, phone layout,
@ -103,7 +113,7 @@ animations (+ Shift); questions animate like pauses; pop-ups fade in; ranged car
**Ranges** (auto-sort on by default); whole rows drag; empty cards can switch Plain/Ranged;
Inspector is one list (card + each result, collapsible; spread clicks open one, hand-opened stay);
result weight/range/position in the Inspector; thicker coloured header (`CARD_HEAD`), Build move
handle, green selection glow (`SELECTED`, also on the inspected card); Play's greyed + Card and ☰
handle, green selection glow (`SELECTED`, also on the inspected card); Play's greyed card palette and ☰
New card point to Build; Book → Lore Index / Lore Entries, a tab beside the Inspector in Build;
spellcheck (Hunspell; per-spread dictionary; off on Android). Modules: ARCHITECTURE §3g.
**Spellcheck:** the Godot-Hunspell prebuilt libraries (MIT, github.com/brunogbrito/Godot-Hunspell)

View file

@ -175,7 +175,7 @@ lazy). No existing test changed.
## 3b. Router cards
A router (`kind: "router"`, "Router" in the **+ Card ▾** menu, "if / else if / otherwise")
A router (`kind: "router"`, "Branch" in the card palette, "if / else if / otherwise")
has no dice. Its entries are **cases**, each with an entry-level `when` expression.
- When the chain reaches it, the cases are checked top to bottom and the **first** true case

165
docs/SHEETS.md Normal file
View file

@ -0,0 +1,165 @@
# Sheets and the unified editor: spec and plan
Agreed with the user 2026-11-29. Mockup canvas (design only, not code):
https://claude.ai/code/artifact/4311ebce-47e0-479c-bc1b-40800339b50b
## 1. Goal
A sheet builder for any TTRPG: odd OSR stats, point buy, a vehicle with only description
boxes. Sheets can be used on their own or as a node in a spread, and tables can read and write
them. The new Sheets replace today's Sheet card kind (`RollTable.KIND_SHEET`, a BBCode template):
an old sheet card becomes a sheet with one text box.
## 2. Decisions
- **Main menu:** Spreads / Sheets / Settings / Quit, titles only (no descriptions). Room for more.
- **Sheets standalone or in a spread.** On a spread the node shows a preview of the sheet's
**first tab**. Double-click opens it in an in-app tab (view only in Play).
- **Layout:** free placement with a snap grid; Alt places freely. A sheet has tabs, each its
own canvas. One Play/Build toggle; in a spread, the spread's toggle.
- **Multi-entry boxes** ("repeating section" elsewhere): each box picks rows, mini table or chips.
- **Point pools:** may go negative, shown red. Reuse the result `cost {value, amount}` variable.
- **Details:** hover tooltip (short, cut with "…"); click opens an in-app side panel.
- **Field types:** number, text, notes, checkbox, dropdown; current/max bars, tick rows, clocks;
computed fields, dice buttons; image, heading, divider; dots, step dice, usage dice, ladders;
slot inventory with encumbrance; tag/condition chips, aspects, bonds; spell slots, XP, currency.
- **Tables ↔ sheets:** tables write and read fields. A field gets an @variable only when
"Use in tables" is on. Each field has a lock: locked fields ignore roll writes.
Later: a sheet event triggers a table roll (fumble → critical-failure table).
- **Templates and one-off sheets.** New sheet = blank canvas or one of your templates.
- **Look:** app theme, plus per-box colour and per-sheet tint; frameless boxes.
- **Text:** all BBCode, buttons for common tags, live {@var}, links to Lore Entries.
- **Lore Index:** opens in Play and Build, in spreads and sheets. Holds sheet entries and whole
sheets as items (a rolled sword → a character's inventory). Gains a shared "My library" level
beside "This spread". Drop copies; Shift keeps it linked.
- **Undo/redo** for values and layout. **Export:** share file, PDF/print, PNG.
- **Phone:** Play stacks boxes full width in reading order (top-down, then left-right), with a
manual "Phone order" per box; a Canvas switch shows the real layout with pan/zoom.
## 3. Unified editor (spreads and sheets look alike)
- **Card palette** replaces "+ Card ▾": a left dock with tabs **Cards | List**. Cards has a
search box at the top, grouped kinds, templates as a group; drag onto the spread (click adds
at the view centre). Roll table, Dice table and Deck are separate items (same kind, different
start settings). Right-click › New card stays.
- **Play mode:** the Cards tab stays, greyed, with "Cards are added in Build mode" and a
**Switch to Build** button. This replaces the greyed "+ Card" button.
- **Right dock:** Inspector | Lore Index (as today), same tab style as the left dock.
- **Top bar:** "Board ▾" is renamed "Spread ▾". Later one shared top bar for spreads and sheets.
- **Open documents as tabs** (needed for sheets opened from a spread node).
- Sheet editor uses the same palette (with search) for fields.
## 4. Phases
- **A. Card palette** — done 2026-11-29 (commit 16b34c4 on `card-palette`): left dock Cards | List, search, drag/click to
add, Play-mode notice, remove "+ Card ▾", rename Board ▾ → Spread ▾. Phone: "+" opens a
searchable list.
- **B. Sheets core** — base built 2026-11-29 (branch `sheets`): main menu, Sheets list, New
sheet dialog, sheet editor with tabs, snap canvas (Alt = free), field palette (shared
`PaletteList`), inspector, Play/Build, snapshot undo, saving. Kinds so far: Number, Text box,
Heading. Theme changes keep the screen (`MainScreens.resume`). Was planned as: data model + storage (sheets and templates), main menu, Sheets list,
New sheet dialog, sheet editor (tabs, snap canvas, palette, inspector, Play/Build, undo).
- **C. Field types** — built 2026-11-29 (branch `sheets`): every kind in §2 (`SheetKinds.ITEMS`,
25 palette items over 23 kinds). Values for formulas/dice/live text: `core/sheet_values.gd`
(rule language with sheet @names; loops are errors). Views: `ui/sheet_field_views.gd` (basics,
dispatch), `sheet_fields_trackers/smart/list/niche.gd`; settings: `ui/sheet_kind_settings.gd`;
details side panel: `ui/sheet_detail_panel.gd`. Pictures are copied to `sheets/pictures/`.
Not yet: per-entry variables in lists (phase D), BBCode buttons and Lore links in text (done in E2).
- **D. Sheets on spreads** — built 2026-11-29: a sheet on a spread is a **Sheet card** linked to a
sheet file (`RollTable.sheet_id`, `sheet_prefix`; JSON `sheet`, `prefix`), so threads, groups, undo,
List view and the tray headline work as for any card. The card shows `SheetPreview` (first tab,
values, gold outline on boxes the last roll changed; double-click / "Open sheet" opens it with
"← spread"; the sheet editor then uses the spread's Play/Build). A roll reaching the card rolls
`SheetText.summary` (boxes as "Title: value", linked ones as {@prefix_name}) through
`Roller.sheet_text`. Bridge `core/sheet_links.gd` + `ui/main_sheet_links.gd`: before a roll "Use in
tables" boxes become @name / @prefix_name; after it changed values go back unless locked or not
writable. Text boxes on a sheet that is on the open spread also show spread values ({@answer}).
Migration: an old template Sheet card gets a sheet file (id `<spread>-<card>`, one text box with
its template) when the spread loads or the card arrives (not inside Help demos). The user's picks:
prefix per card (blank allowed; the second sheet gets one from its name), only "Use in tables" boxes.
Card palette › Sheets: "New sheet" + your sheets. Sheet canvas: grid is one tiled texture (smooth
panning); boxes don't overlap (new ones take the nearest free spot, drags stop short; Alt = free).
- **E. Lore Index library + items, export (PDF, PNG, share file), phone stacked view.**
- **E1. Export and import** — built 2026-11-29: sheet top bar **Export ▾** (Play and Build):
"Share file…" (`*.sheet.json`: `{"tabletarot_sheet": 1, "sheet", "pictures"}`, picture boxes'
files inside as base64; no template link), "Print / PDF (web page)…" (Godot has no PDF writer:
an HTML page, one `<section>` per tab printed on its own page, boxes as "Title: value" lines
from `SheetText.tab_text` with values, through the tray's `SheetExport.to_html`), "Image
(PNG)…" (the window's pixels under the canvas: this tab as you see it). **Import…** on the
Sheets list and "Import a sheet file…" in the New sheet dialog: a new id, pictures written to
`sheets/pictures/`, saved and opened (from the card palette: placed on the spread).
- **E2. Text tools and Lore links** — built 2026-11-29: editing a Long notes box (Play) shows
`SheetTextToolbar` above it: B I U S, Colour ▾ / Size ▾ / Effect ▾ (the tags of `FormatMenu`,
which the TextEdit also gets as its right-click menu), {@} ▾ (the sheet's @names as live
values) and "§ Link…" (Link a Lore Entry…, `LoreLinkPicker` with search). **Link syntax:**
plain BBCode `[url=lore:ENTRY_ID]words[/url]` (no selection: the entry's name is added).
`RichText.decorate` draws it in REF_INK on REF_BG; hover (`DetailsPopup` "lore:") shows the
name and an excerpt cut with "…"; a click opens it in the side panel
(`SheetDetailPanel.open_lore`, read only). "lore:" is an internal meta (Copy as BBCode drops
the link, keeps the words). Which Lore Index: the open spread's, even for a sheet not on a
spread; the one lookup is `SheetLoreLinks.entries` (E3 adds "My library" there).
- **E3. Lore Index everywhere, My library, sheet items** — built 2026-11-29: the Lore Index
panel is `LoreList` (title, + Lore Entry, ×, **This spread | My library** tabs, search, list,
`PageEditor`), shown by `BookPanel` (spread, Play and Build) and `SheetLoreDock` (sheet editor:
the inspector's Lore tab in Build, top bar **Lore Index** toggle in both modes). Levels are
`LoreLevel` objects (`SpreadLoreLevel`: spread undo, `sync_page`; `LibraryLoreLevel`: saved at
once, no undo). **My library** is `LoreLibrary`, `<store root>/lore_library.json`
(`{"book": [BookPage dicts]}`; user:// when saving, the sheets' scratch folder otherwise).
**Link refs:** `lore:ID` = this spread, `lore:lib:ID` = My library (`SheetLoreLinks.ref/find`).
Under an entry: "Copy to My library / This spread" (a new id; its item sheet copied; pictures only
stay in the spread) and "Make a sheet for this entry" / "Open its sheet": `BookPage.sheet` (JSON
`sheet`, a SheetStore id) → `SheetItems.make_sheet` (Heading, Damage, Charges, Notes). A library
entry dropped on a spread card is copied into the spread first. **Drops into a sheet**
(`SheetLoreDrop`, one `set_value` undo step): list box → a row (first column = name, `details` =
plain text), Slots → an item `{name, size: 1}`, Long notes → a link appended. A drop copies (the
item sheet too, `SheetItems.copy_sheet`); Shift links: `lore` = ref and `sheet` = the entry's own
sheet. Marks: § before a linked row/item, ▤ opens a row's sheet (Slots: the item's menu); ⓘ on such
a row has "Read the Lore Entry" / "Open its sheet". Opening a sheet from a sheet uses `SheetItemNav`
("← previous sheet", then back to the spread). A linked row keeps its own copy of the text (it
doesn't follow later edits of the entry); deleting an entry leaves its item sheet in Sheets.
- **E4. Phones and tablets** — built 2026-11-29: in the phone layout (`MobileLayout`, also
`--mobile`) the sheet editor uses `SheetPhoneLayout`. Play shows the **stacked view**
(`SheetStackView`): the open tab's boxes in one full-width column, each the same `SheetBoxView`
at its own height or taller if its content needs it. **Phone order rule** (`SheetStackView.order_of`):
boxes with a Phone order number (> 0) come first, smallest first; then the automatic ones (0) in
reading order (y, then x); equal numbers also fall back to reading order. Touch size: while the
stack builds a box, `SheetFieldViews.touch` is on and `tap_size` grows step buttons, ticks, dots and
slot cells to 44 px (no second set of views). A **bottom bar** replaces the status strip: Undo,
**Stacked | Canvas** (Play; Canvas is the real layout, drag to pan, no pinch zoom yet), and
"+ Field" (Build, which always uses the canvas) that opens the field palette full screen; a pick
goes back to the canvas. The inspector (only while a box is selected), the Lore Index and the
details panel open as **bottom panels**. The top bar drops the brand words, hint, Lore Index and
Export ▾ (both move into ☰). Not done: narrow desktop windows keep the desktop layout; a stats
list in Rows style stays rows (no big tiles); Lore drops onto stacked boxes don't land.
## 5. Code map (phase B)
- Data: `core/sheet_doc.gd` (tabs of boxes), `core/sheet_box.gd`, `core/sheet_kinds.gd` (the
kinds list, grid step, `make_box`), `core/sheet_store.gd` (user://sheets, user://sheet_templates;
a scratch folder when not saving), `core/snapshot_history.gd`, `core/sheet_demo.gd`.
- Screens: `ui/main_screens.gd` (menu / spread / sheets; start screen; resume after a theme
change), `ui/main_menu.gd`, `ui/sheets_screen.gd`, `ui/new_sheet_dialog.gd`.
- Editor: `ui/sheet_editor.gd` (mode, tab, selection, edit/undo/save), `ui/sheet_top_bar.gd`,
`ui/sheet_tabs_bar.gd`, `ui/sheet_canvas.gd`, `ui/sheet_box_view.gd`, `ui/sheet_field_views.gd`,
`ui/sheet_inspector.gd`, `ui/field_palette.gd`; `ui/palette_list.gd` is shared with the card palette.
- Look (2026-11-29, matched to the mockup): `ui/menu_icons.gd` (drawn icons), `MainTopBar.make_brand`
(shared brand), `SheetBoxView.look` (tinted card, band, border), canvas and menu draw the
theme's spread background (`BoardBackdrop`). Sheets in Play keep the greyed palette (user's rule).
- Keys: `MainLayout._shortcut_input` sends keys to the screen that shows.
- Export/import (E1): `core/sheet_file.gd` (share file), `ui/sheet_export_menu.gd` (Export ▾,
PNG capture), `SheetExport.sheet_html`, `SheetStore.keep_picture_bytes`, `SheetsScreen.import_sheet`.
- Text tools and Lore links (E2): `ui/sheet_text_box.gd` (the Long notes view), `ui/sheet_text_toolbar.gd`,
`ui/sheet_lore_links.gd` (lookup, excerpt, hover), `ui/lore_link_picker.gd`; `FormatMenu.colours/selection`.
- Lore Index everywhere (E3): `ui/lore_list.gd`, `ui/lore_level*.gd`, `core/lore_library.gd`,
`ui/lore_entry_actions.gd`, `ui/sheet_lore_dock.gd`, `ui/sheet_lore_drop.gd`, `ui/sheet_item_nav.gd`,
`core/sheet_items.gd`; `SheetKinds.place` (a box on the grid; `SheetDemo` uses it too).
- Phones (E4): `ui/sheet_phone_layout.gd` (bottom bar, bottom panels, full-screen palette),
`ui/sheet_stack_view.gd` (stacked view, `order_of`); `SheetFieldViews.touch/tap_size`. Suite: `test_mobile`.
- CLI (`ui/main_cli_sheets.gd`): `--menu`, `--sheets`, `--sheet-demo` (+ `--sheet-build`, `--sheet-lore` (a linked Lore Entry
in the panel), `--sheet-edit=TITLE` (that text box open with its toolbar), `--sheet-lore-index` (the Lore
Index beside it, with a My library item dropped in)), `--new-sheet`. Suites: `test_sheets`, `test_sheet_editor`.
## 6. Review list (decisions made during phase E, for the user)
- My library has no undo (saved at once); copying an entry into it drops its picture.
- A linked list row keeps its own copy of the entry's text; deleting an entry leaves its item sheet.
- A Lore drop on notes appends the link (not at the cursor); the print page leaves out pictures; no
"import as template".
- Phones: no pinch zoom on the sheet canvas; Rows-style stats stay rows (no big tiles); no Lore drops
onto stacked boxes; narrow desktop windows keep the desktop layout.
- Sheet canvas (2026-11-29 fix): the page starts at the left edge, not centred, so boxes can be
dragged anywhere, left included.

View file

@ -33,7 +33,8 @@ Drag the tray's top edge to make it taller or shorter. Double-click the edge to
# Building tables
Switch to [b]Build[/b] to edit.
- [b]+ Card ▾[/b] adds a new roll table or one of the logic cards.
- The [b]Cards[/b] tab on the left lists every kind of card and your templates. Search it, then click a card to add it in the middle of the view, or drag it onto the spread. Press Enter in the search box to add the first match.
- No Cards tab? Open it from [b]View ▾ → Card palette[/b].
- Type straight into a card's name and results. [b]+ Add result[/b] adds a row at the bottom.
- The [b]×1[/b] beside a result is its weight. A weight of 3 makes that result three times as likely as a weight of 1.
- Hover a row to show its [b]×[/b] delete button.
@ -124,7 +125,7 @@ Deck mode decks ignore the modifier.
[demo]deck[/demo]
# Choice cards
A choice card stops the roll and asks the player. Add one from [b]+ Card ▾[/b].
A choice card stops the roll and asks the player. Add one from the [b]Cards[/b] tab (Ask the player).
- [b]Which option[/b] lists the card's options to pick from. [b]Random[/b] is always offered too. The picked option runs exactly as if it had been rolled: its changes happen and its threads follow.
- [b]How many[/b] asks for a number between a lowest and highest value.
- [b]Open ended[/b] asks for any text.
@ -152,7 +153,7 @@ A spread can remember [b]values[/b] between rolls, such as Luck, Gold or the cur
Conditions are used by Only if threads, branches, repeats, Show only if on options, and [b]Can come up only if[/b] on results (a result whose condition is false is rolled again). In plain words they read "Luck is at least 2". As text: `@luck >= 2`, `@town = "Saltmere"`, `@gold > 0 and @luck < 3`.
# Scales
A [b]Scale[/b] is a value that moves along steps in order, lowest first, such as a Climate that runs [b]Supercold, Cold, Temperate, Hot, Superhot[/b]. Add one with [b]+ Card ▾ → Scale (ordered steps)[/b], then list its steps, one per line, and pick the step it starts at. The card shows the current step, and the row of steps under it shows where that sits.
A [b]Scale[/b] is a value that moves along steps in order, lowest first, such as a Climate that runs [b]Supercold, Cold, Temperate, Hot, Superhot[/b]. Add one from the [b]Cards[/b] tab ([b]Values → Scale[/b]), then list its steps, one per line, and pick the step it starts at. The card shows the current step, and the row of steps under it shows where that sits.
- Changes move it a step at a time and stop at the ends, so a result such as [i]Unexpectedly warmer[/i] can say [b]Climate 1 step up[/b]. Other changes: [b]Climate 2 steps down[/b], [b]Set Climate to Hot[/b], [b]Climate 1 step toward Temperate[/b], [b]Atmosphere at least Medium[/b] (raises it if it's lower) and [b]Atmosphere at most Thin[/b] (lowers it if it's higher).
- Conditions compare steps by their order: a thread can go [b]only if Atmosphere is at least Thin[/b], which is true for Thin and every step above it.
- Text shows the step's name: `{@climate}` reads "Cold".
@ -164,7 +165,7 @@ A [b]Scale[/b] is a value that moves along steps in order, lowest first, such as
- `@atmo >= "Thin"` is a condition.
# Logic cards
Besides roll tables and choices, [b]+ Card ▾[/b] adds:
Besides roll tables and choices, the [b]Cards[/b] tab adds:
- [b]Check card[/b]: rolls dice plus a modifier against a target, such as 2d6 + Skill against 8, and follows its Success or Failure result.
- [b]Repeat[/b]: repeats its Each time result a number of times, or while or until a condition holds, then runs Afterwards once.
- [b]Branch[/b]: checks its cases from top to bottom (if, else if, otherwise) and follows the first one that's true.
@ -197,7 +198,7 @@ Result text can do more than plain words:
## Templates
A template is a saved card, group or selection that you can insert again, with blanks to fill in.
- Save one from a card's ⋯ menu, a group's ⋯ menu, or the selection bar.
- Insert one from [b]+ Card ▾ → From template…[/b].
- Insert one from the [b]Cards[/b] tab ([b]Templates[/b]). [b]All templates…[/b] there also imports, renames and deletes them.
- Built-in templates include a skill check, ask-and-repeat, a pick menu, a counter and a simple sheet.
# Menus: right-click and ☰
@ -237,6 +238,9 @@ The [b]Lore Index[/b] holds [b]Lore Entries[/b]: results you want to use on more
- Open it from View ▾, ☰ or right-click the spread. In Build it is a tab beside the inspector. [b]+ Lore Entry[/b] adds one; in Build, a result's inspector has [b]Save to the Lore Index[/b].
- Drag a Lore Entry onto a result to use it there, or onto a card to add it as a new result. Results using a Lore Entry show a small §.
- Edit a Lore Entry and every result using it changes. Change a result's own text and it stops following the Lore Entry ([b]Unlink[/b] does the same).
- At the top, [b]This spread | My library[/b] switches levels. This spread's entries are saved with the spread. [b]My library[/b] is shared by every spread and sheet. [b]Copy to My library[/b] (or [b]Copy to This spread[/b]) under an entry adds a copy to the other level. Drag a My library entry onto a result and the spread gets its own copy.
- [b]Make a sheet for this entry[/b] gives it a small item sheet, such as a sword's Damage, Charges and Notes. Entries with a sheet show ▤; [b]Open its sheet[/b] opens it.
- The Lore Index opens in Play too, and inside sheets (see Sheets).
[demo]book[/demo]
# Rolling more than once
@ -270,6 +274,38 @@ A result or a Lore Entry can have a picture: [b]Picture → Choose…[/b] in its
- The list fills the screen; [b]Spread[/b] and [b]List[/b] swap between them.
- Press and hold for the right-click menu. Two fingers move and zoom the spread.
- View, Help and Play/Build are in the [b]☰[/b] menu.
- A sheet in Play shows its boxes one under the other, full width. A box's [b]Phone order[/b] (in Build, on the right) puts it first; boxes left at 0 follow from top to bottom, then left to right.
- [b]Stacked[/b] and [b]Canvas[/b] at the bottom swap between that list and the real layout. Drag to move around the canvas.
- In Build, [b]+ Field[/b] at the bottom opens the fields. Tap a box to change its settings in the panel below.
- On a sheet, [b]Lore Index[/b] and [b]Export[/b] are in the [b]☰[/b] menu.
# The main menu and Sheets
The app opens on the [b]main menu[/b]: Spreads, Sheets, Settings and Quit. To come back to it, click the logo at the top left, or use [b]☰ → Main menu[/b].
[b]Sheets[/b] are pages for anything you keep track of: a character, a vehicle, a ship. They work on their own, without a spread.
- [b]+ New sheet[/b] starts from a blank canvas or one of your templates.
- In [b]Build[/b], add fields from the [b]Fields[/b] palette on the left: click to add one in the middle, or drag it where you want it. Drag a box to move it and its corner to resize it. Boxes snap to the grid and don't cover each other; hold [b]Alt[/b] to place one freely. Drag empty space to move around the sheet.
- Click a box to edit its title, colour and frame on the right. With nothing selected, the right side edits the whole sheet: its name and tint.
- [b]+ Tab[/b] adds a tab, each with its own canvas. Right-click a tab to rename, move or delete it.
- In [b]Play[/b], type in the boxes to change values. Undo and redo work for both values and layout (Ctrl+Z, Ctrl+Shift+Z).
- Field kinds: [b]Basics[/b] (number, short text, long notes, checkbox, dropdown), [b]Trackers[/b] (current / max bars, tick boxes, clocks, dot ratings, step dice, usage dice, word ladders), [b]Smart[/b] (formulas and dice buttons), [b]Lists[/b] (rows, mini tables, chips, point pools, bonds, slot inventory, conditions, spell slots, XP, currency) and [b]Layout[/b] (heading, divider, picture). Click a box in Build to change its settings on the right, such as a dropdown's options or a list's columns.
- Turn on [b]Use in tables[/b] and give the box a name, such as str. Formulas and dice buttons use it as @str, like [b]floor((@str - 10) / 2)[/b] or [b]1d20 + @str[/b], and a text box shows it with {@str}.
- A list with a [b]point pool[/b] takes each entry's cost off the pool. You can go over; the pool turns red.
- Click a [b]Long notes[/b] box in Play to write in it. The buttons above the text add the common formatting: [b]B[/b], [i]I[/i], [u]U[/u], [s]S[/s], [b]Colour[/b], [b]Size[/b] and [b]Effect[/b] wrap the selected words; [b]{@}[/b] adds a live value. Right-click the text for the same formatting. Any BBCode works.
- [b]§ Link…[/b] links the selected words to a Lore Entry from the spread's Lore Index or My library. Hover the link to see the start of the entry; click it to read it all in the side panel.
- [b]Lore Index[/b] at the top shows the Lore Index beside the sheet, in Play and Build (in Build it is a tab beside the inspector). Drag a Lore Entry onto a box: onto a list or Slots box it adds an entry or item, with the entry's text as its details; onto a Long notes box it adds a link. A drop is a copy, and the entry's item sheet is copied with it. Hold [b]Shift[/b] while you drop to keep it linked: it shows §, and it uses the entry's own sheet. Undo takes it out again.
- An item with a sheet shows ▤ (in Slots: click the item). That opens its sheet; [b]←[/b] at the top goes back to the sheet you came from. ⓘ on a linked entry has [b]Read the Lore Entry[/b].
- Hover a list entry to see the start of its details; click its ⓘ (or a chip) to read and edit them in full in the side panel.
- In Build, [b]Save as template…[/b] at the top (also in [b]☰[/b]) keeps the layout to start new sheets from.
- [b]Export ▾[/b] at the top right saves the sheet as a file: [b]Share file…[/b] for others to import (pictures go with it), [b]Print / PDF (web page)…[/b] to open in a browser and print or save as PDF (one page per tab), or [b]Image (PNG)…[/b] of the tab as you see it.
- To add a sheet someone sent you, press [b]Import…[/b] on the Sheets page, or [b]Import a sheet file…[/b] in the New sheet window. It becomes a new sheet of your own.
## Sheets on a spread
- In Build, drag one of your sheets from the card palette's [b]Sheets[/b] group onto the spread (or pick [b]New sheet[/b]). It becomes a Sheet card showing a small picture of its first tab. Threads can lead into it: a roll that reaches it shows the sheet in the tray, ready to copy or save.
- Every box with [b]Use in tables[/b] on becomes a value tables can use: a result's change like [b]@hp -= 4[/b] or [b]@background = "Soldier"[/b] writes into the sheet, and the box glows to show a roll changed it. A [b]locked[/b] box ignores rolls.
- Text boxes on the sheet can show the spread's values too, like {@name} saved by a choice card.
- Two sheets on one spread? Right-click one and give it a [b]Prefix for tables[/b], such as brin: its boxes are then @brin_str, @brin_hp…
- Double-click a sheet (or press [b]Open sheet[/b]) to open it; [b]←[/b] at the top goes back to the spread.
- Older spreads' Sheet cards turn into sheets by themselves: their template becomes a text box.
# Spreads, import and export
A [b]spread[/b] is one layout of cards, saved under its own name. Use the switcher beside Play | Build (it shows the spread's name) to switch, or to make a new spread, rename, duplicate, delete one, or sort spreads into folders.

View file

@ -131,7 +131,7 @@ static func _canon_table(td: Dictionary) -> Dictionary:
for e in src_entries:
entries.append(_canon_entry(e))
t["entries"] = entries
_keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps", "members", "repeats", "cost"])
_keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps", "members", "repeats", "cost", "sheet", "prefix"])
# A separator may be just a space, so it isn't trimmed.
if td.get("column_join") is String and td["column_join"] != "":
t["column_join"] = td["column_join"]

View file

@ -28,7 +28,11 @@ func _test_lists() -> void:
_check(play.has("Roll") and not play.has("Delete table"), "Play: a card can be rolled, not deleted: %s" % str(play))
var bg := _texts(Actions.background(main, Vector2.ZERO))
_check(bg.has("Search… Ctrl+F") and bg.has("Shuffle all decks") and not bg.has("New card from template…"), "Play spread menu: %s" % str(bg))
var new_card: Dictionary = Actions.background(main, Vector2.ZERO)[bg.find("New card")]
var new_card: Dictionary = {}
for item: Dictionary in Actions.background(main, Vector2.ZERO):
if item.get("text", "") == "New card":
new_card = item
_check(bg.has("Main menu"), "the spread menu leads back to the main menu")
_check(new_card.get("disabled", false), "Play: New card shows greyed, pointing to Build mode")
main.set_mode(Main.Mode.BUILD)
await _frames()
@ -55,7 +59,7 @@ func _test_popup_and_run() -> void:
for c in pm.get_children():
if c is PopupMenu and sub == null:
sub = c
_check(sub != null and sub.item_count == MainEditing.ADD_KINDS.size(), "New card ▸ lists every kind")
_check(sub != null and sub.item_count == CardCatalog.ITEMS.size(), "New card ▸ lists every kind")
var before := main.data.tables.size()
_check(Actions.press(sub, "Roll table"), "pressing an item runs it")
await _frames()

View file

@ -1,6 +1,7 @@
extends AppTestBase
## The Book: pages saved from results, linked results following a page's edits,
## dropping a page onto a result or a card, unlinking, saving and undo.
## dropping a page onto a result or a card, unlinking, saving and undo; the
## two levels (This spread | My library) and Lore Entries in sheets (items).
## Run: tools/run_tests.sh book
@ -11,6 +12,8 @@ func run() -> void:
await _frames()
await _test_book()
_test_pictures()
await _test_levels()
await _test_sheet_items()
finish()
@ -119,3 +122,67 @@ func _test_pictures() -> void:
_check(e3.combine_for("loot") == "max" and e3.pipe_pause.has("loot") and e3.pipe_color.get("loot") == "#c04a86", "thread options import")
_check(b2.get_group(g2.id).parent == g.id and b2.book.size() == main.data.book.size() and b2.images.has(r["id"]), "nesting, the Book and pictures import")
## My library beside This spread: new entries go to the level shown, Copy to
## moves a copy across, and a library entry dropped on a card is copied in.
func _test_levels() -> void:
var lore := main.book.lore
var library := SheetLoreLinks.library(main)
var before := library.pages.size()
lore.set_level(LoreLevel.LIBRARY)
var shared := lore.new_page()
_eq(library.pages.size(), before + 1, "+ Lore Entry in My library adds it there")
_eq(lore.list.item_count, library.pages.size(), "the list shows My library")
lore.set_level(LoreLevel.SPREAD)
_eq(lore.list.item_count, main.data.book.size(), "This spread shows the spread's entries again")
var spread_count := main.data.book.size()
var copied := LoreEntryActions.copy_to(lore, shared, lore.levels[LoreLevel.SPREAD])
_check(main.data.book.size() == spread_count + 1 and copied.id != shared.id, "Copy to This spread adds a copy")
_check(SheetLoreLinks.find(main, "lib:" + shared.id) == shared and SheetLoreLinks.find(main, copied.id) == copied, "links name their level: lore:lib:ID or lore:ID")
await _frames()
var card := main.card_for("loot")
_check(main.book.drop_page(shared.id, card.get_global_rect().position + Vector2(20, 12), lore.levels[LoreLevel.LIBRARY]), "a My library entry drops onto a card")
_eq(main.data.book.size(), spread_count + 2, "and is copied into the spread first")
library.remove_page(shared.id)
## The Lore Index in a sheet: an entry with an item sheet dropped on a Slots
## box (a copy with its own sheet) and on a list box with Shift (linked), one
## undo step each; its sheet opens with a way back.
func _test_sheet_items() -> void:
var sheets := main.screens.sheets
var doc := SheetDemo.create("lore-items")
sheets.store.save(doc)
main.screens.show(MainScreens.SHEETS)
sheets.open_doc(doc)
var ed := sheets.editor
ed.set_mode(Main.Mode.PLAY)
ed.set_lore_shown(true)
_check(ed.lore_dock.visible and not ed.inspector.visible, "Play: the Lore Index opens beside the sheet")
var level: LoreLevel = ed.lore_dock.lore.levels[LoreLevel.LIBRARY]
var blade := level.add_page("Ashen Blade", "Burns what it cuts.")
LoreEntryActions.open_or_make_sheet(ed.lore_dock.lore, blade)
_check(blade.sheet != "" and ed.doc.id == blade.sheet, "Make a sheet for this entry opens its new sheet")
_eq(ed.top_bar.back_button.text, "← Brin Hollowmere", "with a way back")
ed.nav.back()
_eq(ed.doc.id, doc.id, "back returns to the character")
await _frames()
var inventory := MainCliSheets.box_titled(ed.doc, "Inventory")
var at: Vector2 = ed.canvas.views[inventory.id].get_global_rect().get_center()
_check(SheetLoreDrop.drop(ed, blade, level, at, false), "an entry drops onto a Slots box")
var item: Dictionary = (MainCliSheets.box_titled(ed.doc, "Inventory").value as Array).back()
_check(item["name"] == "Ashen Blade" and str(item.get("sheet", "")) not in ["", blade.sheet] and not item.has("lore"), "as an item with its own copy of the sheet")
await _frames()
var talents := MainCliSheets.box_titled(ed.doc, "Talents")
var rows := (talents.value as Array).size()
SheetLoreDrop.drop(ed, blade, level, ed.canvas.views[talents.id].get_global_rect().get_center(), true)
var row: Dictionary = (MainCliSheets.box_titled(ed.doc, "Talents").value as Array).back()
_check(row["Name"] == "Ashen Blade" and row["details"] == "Burns what it cuts." and row["lore"] == "lib:" + blade.id and row["sheet"] == blade.sheet, "Shift: a list row stays linked")
_check(ed.canvas.views[talents.id].find_child("LoreMark", true, false) != null, "and shows §")
ed.undo()
_eq((MainCliSheets.box_titled(ed.doc, "Talents").value as Array).size(), rows, "undo takes the row out again")
ed.set_lore_shown(false)
level.remove_page(blade.id)
sheets.show_list()
main.screens.show(MainScreens.SPREAD)

View file

@ -545,11 +545,10 @@ func _test_other_cards() -> void:
func _test_add_kinds() -> void:
print("+ Card ▾")
var labels: Array = main.editing.ADD_KINDS.map(func(k: Array) -> String: return k[0])
_check(labels.any(func(s: String) -> bool: return s.begins_with("Check")), "Check card is in the menu")
_check(labels.any(func(s: String) -> bool: return s.begins_with("Ledger")), "Ledger is in the menu")
_eq(main.editing._add_menu.text, "+ Card ▾", "the button reads + Card ▾")
print("Card kinds")
var labels: Array = CardCatalog.ITEMS.map(func(item: Dictionary) -> String: return item["label"])
_check(labels.has("Check"), "Check card is in the catalog")
_check(labels.has("Ledger"), "Ledger is in the catalog")
var c := main.editing.add_table(RollTable.KIND_CHECK)
_check(c.kind == RollTable.KIND_CHECK and c.name == "Check" and c.entries.size() == 2, "adding a check card")
_eq(insp.selection.get("tid"), c.id, "a new card is selected in the inspector")

View file

@ -30,7 +30,7 @@ func _find(id: String) -> TreeItem:
func _test_rows() -> void:
var lv := main.list_view
_check(not lv.visible, "the list starts hidden")
_check(not lv.shown(), "the list starts hidden")
lv.set_shown(true)
await _frames(2)
var rows := _rows(lv.tree.get_root(), [])

View file

@ -138,8 +138,8 @@ func _test_scripted() -> void:
var hp := main.card_for("v_hp")
_eq(hp.value_ui.var_value.text, Expr.format_value(_var("hp")), "the HP card shows the new value after the roll")
var sheet := main.card_for("report")
_check(Formatter.strip_tags(sheet.rows_ui.sheet_label.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the sheet card is up to date")
_check(Formatter.strip_tags(sheet.rows_ui.sheet_label.text).begins_with("Brin the delver"), "the sheet shows the name")
_check(sheet.table.sheet_id != "" and sheet.find_child("SheetPreview", true, false) != null, "the old sheet card was migrated to a sheet file")
_check(Formatter.strip_tags(main.tray._headline_text.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the headline shows the sheet up to date")
main.prompt_hook = main.rolling._ask_player
@ -306,7 +306,10 @@ func _test_live_edits() -> void:
main.set_variable("gold", "42")
_eq(_var("gold"), 42, "a number variable stays a number")
_eq(main.card_for("v_gold").value_ui.var_value.text, "42", "the variable card follows an edit")
_check(Formatter.strip_tags(main.card_for("report").rows_ui.sheet_label.text).contains("Gold 42"), "the sheet follows an edit")
var report := main.data.get_table("report")
var report_doc := main.sheet_links.load_doc(report.sheet_id)
var shown := main.sheet_links.expand(report_doc, str(report_doc.tabs[0]["boxes"][0].value))
_check(Formatter.strip_tags(shown).contains("Gold 42"), "the sheet's text box follows a spread value")
main.reset_variable("gold")
_eq(_var("gold"), 0, "reset goes back to the starting value")
main.set_variable("hp", "3")
@ -325,11 +328,6 @@ func _test_live_edits() -> void:
_check(dlg != null and dlg.is_inside_tree(), "Reset all asks first, in the app")
dlg.close()
main.tray.set_side(ResultTray.Side.EARLIER)
# Rendering live cards doesn't happen per frame: the sheet's text stays put.
var before := main.card_for("report").rows_ui.sheet_label.text
for i in 3:
await process_frame
_eq(main.card_for("report").rows_ui.sheet_label.text, before, "live cards only re-render on change")
# ---------------------------------------------------------------- build rules
@ -373,10 +371,14 @@ func _test_settings_rules() -> void:
func _test_add_kinds() -> void:
main.set_mode(Main.Mode.BUILD)
var n := main.data.tables.size()
for k: Array in MainEditing.ADD_KINDS:
var t := main.editing.add_table(str(k[1]), str(k[2]))
_check(t.kind == k[1] and main.card_for(t.id) != null, "+ Table adds a %s" % str(k[0]))
_eq(main.data.tables.size(), n + MainEditing.ADD_KINDS.size(), "one card per menu item")
for item: Dictionary in CardCatalog.ITEMS:
var t := main.editing.add_table(str(item["kind"]), str(item["sub"]), Vector2.INF, str(item["variant"]))
_check(t.kind == item["kind"] and main.card_for(t.id) != null and t.name == item["name"], "the palette adds a %s" % str(item["label"]))
if item["variant"] == CardCatalog.VARIANT_DICE:
_check(t.is_ranged() and t.entries[0].has_range, "a dice table starts ranged")
if item["variant"] == CardCatalog.VARIANT_DECK:
_check(t.card_mode, "a deck starts in Deck mode")
_eq(main.data.tables.size(), n + CardCatalog.ITEMS.size(), "one card per catalog item")
var v1 := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
var v2 := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
_check(v1.var_name != v2.var_name, "new variable cards get distinct names")

View file

@ -1,7 +1,8 @@
extends AppTestBase
## The phone layout (List fills the screen, Spread/List swap, slim bar and
## tray, View/Help/Play-Build in ☰) and touch gestures (pinch zoom, a long
## press timing out into a right-click).
## press timing out into a right-click), and sheets on a phone (the stacked
## view in phone order, the Stacked | Canvas switch, Build's "+ Field").
## Run: tools/run_tests.sh mobile
@ -10,6 +11,7 @@ func run() -> void:
return
await _test_layout()
await _test_touch()
await _test_sheet()
finish()
@ -17,10 +19,14 @@ func _test_layout() -> void:
main.mobile = MobileLayout.new(main)
main.mobile.apply()
await _frames()
_check(main.list_view.visible and not main.board.visible, "the list fills the screen")
_check(main.list_view.is_visible_in_tree() and not main.board.visible, "the list fills the screen")
_check(not main.top_bar.view_menu.visible and not main.top_bar.help_menu.visible and not main.tray.side_panel.visible, "the bar and tray slim down")
main.mobile.swap.pressed.emit()
_check(main.board.visible and not main.list_view.visible and main.mobile.swap.text == "List", "Spread/List swaps to the spread")
_check(main.board.visible and not main.list_view.is_visible_in_tree() and main.mobile.swap.text == "List", "Spread/List swaps to the spread")
main.mobile.add_button.pressed.emit()
_check(main.left_dock.palette.is_visible_in_tree() and not main.board.visible, "+ opens the card palette full screen")
main.left_dock.show_tab(LeftDock.LIST)
main.mobile.show_list(false)
main.mobile.swap.pressed.emit()
var texts: Array = Actions.background(main, Vector2.ZERO).map(func(a: Dictionary) -> String: return str(a.get("text", "")))
_check(texts.has("Switch to Build") and texts.has("Help…"), "☰ carries Play/Build and Help: %s" % str(texts))
@ -51,6 +57,50 @@ func _test_touch() -> void:
touch._input(_tap(0, Vector2(120, 320), false))
func _test_sheet() -> void:
var a := SheetBox.new("a")
var b := SheetBox.new("b")
var c := SheetBox.new("c")
var d := SheetBox.new("d")
a.set_rect(Rect2(200, 0, 10, 10))
b.set_rect(Rect2(0, 0, 10, 10))
c.set_rect(Rect2(0, 50, 10, 10))
d.set_rect(Rect2(0, 90, 10, 10))
d.phone_order = 1
var ids: Array = SheetStackView.order_of([a, b, c, d]).map(func(box: SheetBox) -> String: return box.id)
_eq(ids, ["d", "b", "a", "c"], "phone order: numbers first, then top-down, left-right")
main.screens.show(MainScreens.SHEETS)
var ed := main.screens.sheets.editor
main.screens.sheets.open_doc(SheetDemo.create())
await _frames()
var phone := ed.phone
_check(phone != null and phone.stack.visible and not ed.canvas.visible and not ed.palette_dock.visible, "Play on a phone shows the stacked view")
_eq(phone.stack.views.size(), (ed.current_tab()["boxes"] as Array).size(), "every box of the tab is in the stack")
var number: SheetBox = null
for box: SheetBox in ed.current_tab()["boxes"]:
if box.kind == SheetKinds.NUMBER and number == null:
number = box
var plus: Button = phone.stack.views[number.id].find_child("Plus", true, false)
_check(plus.custom_minimum_size.y >= SheetFieldViews.TOUCH, "step buttons are touch size")
_check(not SheetFieldViews.touch, "the touch flag is off again")
var before: Variant = number.value
plus.pressed.emit()
_eq(number.value, int(before) + 1, "+ in the stack changes the value")
phone.undo_button.pressed.emit()
_eq(ed.doc.find_box(number.id).value, before, "Undo in the bottom bar takes it back")
phone.canvas_button.pressed.emit()
_check(ed.canvas.visible and not phone.stack.visible, "Canvas shows the real layout")
ed.set_mode(Main.Mode.BUILD)
_check(ed.canvas.visible and not phone.canvas_button.visible and phone.add_button.visible, "Build uses the canvas, with + Field")
phone.add_button.pressed.emit()
_check(ed.palette_dock.visible and not ed.canvas.visible, "+ Field opens the palette full screen")
ed.palette._add(Vector2.INF, SheetKinds.NUMBER)
_check(ed.canvas.visible and not ed.palette_dock.visible and ed.inspector.visible, "a pick goes back to the canvas, inspector below")
ed.set_mode(Main.Mode.PLAY)
phone.stacked_button.pressed.emit()
main.screens.show(MainScreens.SPREAD)
func _tap(i: int, at: Vector2, down: bool) -> InputEventScreenTouch:
var t := InputEventScreenTouch.new()
t.index = i

376
tests/test_sheet_editor.gd Normal file
View file

@ -0,0 +1,376 @@
extends AppTestBase
## The main menu and the sheet editor in the app: switching screens, making a
## sheet, adding boxes from the field palette, moving them on the snap grid,
## undo, tabs, number fields, saving, and keys staying on their own screen.
## Run: tools/run_tests.sh sheet_editor
func run() -> void:
if not await start_main(false):
return
await _test_menu()
await _test_new_sheet()
await _test_boxes()
await _test_tabs()
await _test_keys()
await _test_kinds()
await _test_links()
await _test_overlap()
await _test_export()
await _test_text_tools()
finish()
func _test_menu() -> void:
var screens := main.screens
_check(screens.showing(MainScreens.SPREAD), "tests start on the spread")
main.top_bar.brand_title.get_parent().gui_input.emit(_click())
_check(screens.menu.visible and not screens.spread_root.visible, "clicking the logo opens the main menu")
var labels: Array = screens.menu.buttons.keys()
_eq(labels, ["Spreads", "Sheets", "Settings", "Quit"], "the menu lists Spreads first, titles only")
(screens.menu.buttons["Sheets"] as Button).pressed.emit()
_check(screens.sheets.visible and screens.sheets.list_page.visible, "Sheets opens the sheet list")
await _frames()
func _test_new_sheet() -> void:
var sheets := main.screens.sheets
sheets.open_new_sheet()
await _frames()
var dialog: NewSheetDialog = null
for c in main.get_children():
if c is NewSheetDialog:
dialog = c
_check(dialog != null, "+ New sheet asks for a name")
dialog.name_edit.text = "Rusty Mule"
dialog._create()
await _frames()
var ed := sheets.editor
_check(ed.visible and ed.doc.name == "Rusty Mule" and ed.building(), "a blank sheet opens in Build")
_eq(sheets.store.list().size(), 1, "it is saved")
func _test_boxes() -> void:
var ed := main.screens.sheets.editor
(ed.palette.list.find_child("Number", true, false) as Button).pressed.emit()
await _frames()
_eq((ed.current_tab()["boxes"] as Array).size(), 1, "clicking Number adds a box")
var box: SheetBox = ed.current_tab()["boxes"][0]
_eq(ed.selected, box.id, "the new box is selected")
var spot := ed.canvas.global_position + ed.canvas.size / 2.0 + Vector2(17, 9)
var want := ed.canvas.drop_point(spot)
_check(ed.palette.drop_at(ed.palette._add.bind(SheetKinds.TEXT), spot), "dropping on the canvas adds there")
var text_box: SheetBox = ed.current_tab()["boxes"][1]
_eq(Vector2(text_box.x, text_box.y).posmod(SheetKinds.GRID), Vector2.ZERO, "a dropped box snaps to the grid")
_check(Vector2(text_box.x, text_box.y).distance_to(want) < 400, "near where it was dropped")
var view: SheetBoxView = ed.canvas.views[box.id]
view.begin_drag("move")
view.drag_to(Vector2(37, 21), false)
view.end_drag()
_eq(Vector2(box.x, box.y).posmod(SheetKinds.GRID), Vector2.ZERO, "moving snaps to the grid")
var snapped := Vector2(box.x, box.y)
view = ed.canvas.views[box.id]
view.begin_drag("move")
view.drag_to(Vector2(5, 3), true)
view.end_drag()
_eq(Vector2(box.x, box.y), snapped + Vector2(5, 3), "Alt places it off the grid")
ed.undo()
box = ed.doc.find_box(box.id)
_eq(Vector2(box.x, box.y), snapped, "undo puts the box back")
await _frames()
var page_x := ed.canvas.area.position.x
view = ed.canvas.views[box.id]
view.begin_drag("move")
view.drag_to(Vector2(ed.canvas.size.x * 1.5, 0), false)
view.end_drag()
ed.canvas._fit_area()
_eq(ed.canvas.area.position.x, page_x, "moving a box far right doesn't shift the page")
_check(ed.canvas.holder.custom_minimum_size.x > box.x + box.w + ed.canvas.size.x * 0.9, "the canvas keeps a screen of room past the box")
_eq(ed.canvas.area.position.x, SheetCanvas.MARGIN, "the page starts at the canvas's left edge")
view = ed.canvas.views[box.id]
view.begin_drag("move")
view.drag_to(Vector2(-100000, 0), true)
view.end_drag()
_eq(box.x, 0.0, "a box can go all the way to the left edge")
ed.undo()
box = ed.doc.find_box(box.id)
ed.canvas.pan_to(Vector2(300, 0))
await _frames()
_eq(ed.canvas.scroll_horizontal, 300, "panning scrolls the canvas")
ed.undo()
box = ed.doc.find_box(box.id)
ed.redo()
ed.set_mode(Main.Mode.PLAY)
await _frames()
_check(ed.palette.notice.visible and not ed.inspector.visible, "Play greys the palette and hides the inspector")
view = ed.canvas.views[box.id]
(view.find_child("Plus", true, false) as Button).pressed.emit()
_eq(int(ed.doc.find_box(box.id).value), 1, "+ adds one in Play")
ed.undo()
_eq(int(ed.doc.find_box(box.id).value), 0, "a value change can be undone")
ed.save_now()
var saved := main.screens.sheets.store.load_sheet(ed.doc.id)
_eq((saved.tabs[0]["boxes"] as Array).size(), 2, "the sheet's boxes are saved")
ed.set_mode(Main.Mode.BUILD)
func _test_tabs() -> void:
var ed := main.screens.sheets.editor
ed.tabs_bar.add_tab()
await _frames()
_check(ed.doc.tabs.size() == 2 and ed.tab_id == str(ed.doc.tabs[1]["id"]), "+ Tab adds a tab and opens it")
_eq(ed.canvas.views.size(), 0, "a new tab has its own empty canvas")
var second := str(ed.doc.tabs[1]["id"])
ed.tabs_bar.move_tab(second, -1)
_eq(str(ed.doc.tabs[0]["id"]), second, "Move left moves it")
ed.tabs_bar.delete_tab(second)
_eq(ed.doc.tabs.size(), 1, "an empty tab deletes without asking")
_check(ed.tabs_bar.menu_for(str(ed.doc.tabs[0]["id"]))[3]["disabled"], "the last tab can't be deleted")
ed.undo()
_eq(ed.doc.tabs.size(), 2, "undo brings the tab back")
func _test_keys() -> void:
var ed := main.screens.sheets.editor
var spread_label := main.undo_redo.edits.undo_label() if main.undo_redo.edits else ""
var key := InputEventKey.new()
key.keycode = KEY_Z
key.ctrl_pressed = true
key.pressed = true
var step := ed.history.undo_label()
main.layout._shortcut_input(key)
_eq(ed.history.redo_label(), step, "Ctrl+Z on the Sheets screen undoes the sheet")
_eq(main.undo_redo.edits.undo_label() if main.undo_redo.edits else "", spread_label, "and leaves the spread alone")
ed.screen.show_list()
_check(ed.screen.list_page.visible and ed.doc == null, "← Sheets closes the sheet")
main.screens.show(MainScreens.SPREAD)
## The example sheet: every kind draws in Play and Build; clicks and typing
## change values (and undo); lists add, remove and go over their pool; ⓘ
## opens the details panel; dice roll; a setting change redraws the box.
func _test_kinds() -> void:
var sheets := main.screens.sheets
main.screens.show(MainScreens.SHEETS)
var doc := SheetDemo.create("kinds-demo")
sheets.store.save(doc)
sheets.open_doc(doc)
var ed := sheets.editor
ed.set_mode(Main.Mode.PLAY)
for tab in ed.doc.tabs:
ed.show_tab(str(tab["id"]))
_eq(ed.canvas.views.size(), (tab["boxes"] as Array).size(), "every box on %s draws" % tab["name"])
ed.set_mode(Main.Mode.BUILD)
_eq(ed.canvas.views.size(), (ed.current_tab()["boxes"] as Array).size(), "and draws in Build")
ed.set_mode(Main.Mode.PLAY)
ed.show_tab(str(ed.doc.tabs[0]["id"]))
var stress := _box(ed, "Stress")
_press(ed, stress, "Mark4")
_eq(int(stress.value), 4, "clicking the 4th tick box marks four")
ed.undo()
_eq(int(_box(ed, "Stress").value), 2, "undo puts the ticks back")
var talents := _box(ed, "Talents")
_press(ed, talents, "Add")
_eq((_box(ed, "Talents").value as Array).size(), 4, "+ Add adds an entry")
var cost: LineEdit = _view(ed, "Talents").find_child("Row3", true, false).find_child("Cost", true, false)
cost.text = "9"
cost.text_changed.emit("9")
var pool: Label = _view(ed, "Talents").find_child("Pool", true, false)
_check(pool.text.contains("over by 7"), "the pool shows red past zero: " + pool.text)
_press(ed, _box(ed, "Talents"), "Details")
_check(ed.details.visible and ed.details.index == 0, "ⓘ opens the details panel")
var details: TextEdit = ed.details.find_child("DetailsText", true, false)
details.text = "New text"
details.text_changed.emit()
_eq(str((_box(ed, "Talents").value as Array)[0]["details"]), "New text", "typing in the panel saves the details")
var row: Control = _view(ed, "Talents").find_child("Row0", true, false)
_check(row.tooltip_text.begins_with("Shield Wall\nNew text"), "hovering an entry shows its details")
_press(ed, _box(ed, "Conditions"), "Poisoned")
_check((_box(ed, "Conditions").value as Array).has("Poisoned"), "a condition chip switches on")
_press(ed, _box(ed, "Longsword"), "Roll")
_check(str(_box(ed, "Longsword").value).begins_with("Rolled"), "the dice button rolls")
(_view(ed, "Strength").find_child("Plus", true, false) as Button).pressed.emit()
var shown: Label = _view(ed, "STR mod").find_child("Value", true, false)
_eq(shown.text, "2", "a formula follows the number it reads (15 → still 2)")
(_view(ed, "Strength").find_child("Plus", true, false) as Button).pressed.emit()
shown = _view(ed, "STR mod").find_child("Value", true, false)
_eq(shown.text, "3", "and changes when it should (16 → 3)")
ed.set_mode(Main.Mode.BUILD)
ed.select(talents.id)
var chips: Button = ed.inspector.find_child("chips", true, false)
chips.pressed.emit()
_eq(str(_box(ed, "Talents").config["style"]), "chips", "the inspector switches a list to chips")
_check(_view(ed, "Talents").find_child("Chip0", true, false) != null, "and the box shows chips")
sheets.show_list()
## A sheet on the spread: its node draws, a roll writes its boxes (not the
## locked one), undo takes the node away and back, double-click opens it.
func _test_links() -> void:
var sheets := main.screens.sheets
main.screens.show(MainScreens.SPREAD)
var doc := sheets.store.create("Linked")
var boxes: Array = doc.tabs[0]["boxes"]
for spec: Array in [["short_text", "Background", "background", ""], ["number", "HP", "hp", 10], ["number", "Luck", "luck", 3]]:
var b := SheetKinds.make_box(spec[0], doc.new_box_id(), Vector2(0, boxes.size() * 96))
b.title = spec[1]
b.var_name = spec[2]
b.value = spec[3]
b.locked = spec[1] == "Luck"
boxes.append(b)
sheets.store.save(doc)
main.set_mode(Main.Mode.BUILD)
var card := main.sheet_links.add_card(doc.id)
await _frames()
_check(card.kind == RollTable.KIND_SHEET and card.sheet_id == doc.id and card.name == "Linked", "placing a sheet adds a Sheet card for it")
_check(main.card_for(card.id).find_child("SheetPreview", true, false) != null, "the card shows the sheet's picture")
var t := main.editing.add_table()
t.entries.resize(1)
t.entries[0].effects = '@background = "Soldier"; @hp -= 4; @luck = 0'
t.entries[0].pipes = [card.id]
main.set_mode(Main.Mode.PLAY)
await main.rolling.start_roll(t.id, true)
await _frames()
var after := sheets.store.load_sheet(doc.id)
_eq(str(after.tabs[0]["boxes"][0].value), "Soldier", "a roll writes text into the sheet")
_eq(int(after.tabs[0]["boxes"][1].value), 6, "and numbers (HP 10 - 4)")
_eq(int(after.tabs[0]["boxes"][2].value), 3, "a locked box keeps its value")
_eq(int(main.persistent_vars["luck"]["value"]), 3, "and its variable goes back too")
_check((main.sheet_links.recent.get(doc.id, {}) as Dictionary).has(boxes[0].id), "the changed boxes are marked for a highlight")
var headline := TrayText.sheet_step(main.current.get("all", []))
_check(str(headline.get("text", "")).contains("Soldier"), "a thread into the card ends on the sheet text: %s / %s" % [str(headline.get("text", "")).left(120), str((main.current.get("all", []) as Array).size())])
main.sheet_links.open(card.id)
var ed := sheets.editor
_check(main.screens.showing(MainScreens.SHEETS) and ed.doc.id == doc.id and ed.top_bar.back_button.visible, "opening the card shows the sheet with a way back")
_check(not ed.building(), "in the spread's mode (Play)")
ed.back_to_spread()
_check(main.screens.showing(MainScreens.SPREAD), "← goes back to the spread")
main.set_mode(Main.Mode.BUILD)
var old := RollTable.create(RollTable.KIND_SHEET, TowerBoard.new_id("t"), "Hero")
old.entries[0].text = "[b]Hero[/b] {@background}"
main.data.tables.append(old)
main._board_changed()
await _frames()
_check(old.sheet_id != "", "an old template Sheet card gets a sheet file")
var made := sheets.store.load_sheet(old.sheet_id)
_eq(str(made.tabs[0]["boxes"][0].value), "[b]Hero[/b] {@background}", "holding its template in a text box")
## Boxes don't overlap: a new one lands on a free spot; a drag stops before
## covering another; Alt places it anywhere.
func _test_overlap() -> void:
var sheets := main.screens.sheets
main.screens.show(MainScreens.SHEETS)
sheets.open_doc(sheets.store.create("Tidy"))
var ed := sheets.editor
ed.set_mode(Main.Mode.BUILD)
var a := ed.add_box("number", Vector2(32, 32))
var b := ed.add_box("number", Vector2(32, 32))
_check(not a.rect().intersects(b.rect().grow(-0.5)), "a second box dropped on the first lands beside it")
var view: SheetBoxView = ed.canvas.views[b.id]
view.begin_drag("move")
view.drag_to(a.rect().position - b.rect().position, false)
view.end_drag()
_check(not a.rect().intersects(b.rect().grow(-0.5)), "dragging onto another box stops short")
view = ed.canvas.views[b.id]
view.begin_drag("move")
view.drag_to(a.rect().position - b.rect().position, true)
view.end_drag()
_eq(b.rect().position, a.rect().position, "Alt lets it overlap")
sheets.show_list()
func _box(ed: SheetEditor, title: String) -> SheetBox:
for tab in ed.doc.tabs:
for b: SheetBox in tab["boxes"]:
if b.title == title:
return b
return null
func _view(ed: SheetEditor, title: String) -> SheetBoxView:
return ed.canvas.views.get(_box(ed, title).id)
func _press(ed: SheetEditor, box: SheetBox, child: String) -> void:
var b: Button = (ed.canvas.views[box.id] as SheetBoxView).find_child(child, true, false)
b.pressed.emit()
func _click() -> InputEventMouseButton:
var mb := InputEventMouseButton.new()
mb.button_index = MOUSE_BUTTON_LEFT
mb.pressed = true
return mb
func _test_export() -> void:
var sheets := main.screens.sheets
var doc := SheetDemo.create("export-demo")
sheets.store.save(doc)
sheets.open_doc(doc)
var ed := sheets.editor
ed.set_mode(Main.Mode.PLAY)
var bar: SheetTopBar = ed.top_bar
_check(bar.export_button.is_visible_in_tree(), "Export ▾ shows in Play")
var popup := bar.export_button.get_popup()
popup.about_to_popup.emit()
_eq(range(popup.item_count).map(func(i: int) -> String: return popup.get_item_text(i)), SheetExportMenu.ITEMS, "Export ▾ offers share file, print page and PNG")
var page := SheetExportMenu.page_html(ed)
_check(page.contains(doc.name) and page.count("<section>") == doc.tabs.size(), "the print page has the sheet, one section per tab")
_check(SheetExportMenu.capture(ed.canvas) == null, "headless runs have no picture to take")
sheets.show_list()
_check(sheets.list_page.find_child("ImportSheet", true, false) != null, "the Sheets list can import a sheet file")
sheets.open_new_sheet()
await _frames()
for c in main.get_children():
if c is NewSheetDialog:
_check(c.footer.find_child("Import", false, false) != null, "the New sheet dialog can import too")
c.close()
## A text box being edited shows the formatting toolbar; B wraps the
## selection; "Link a Lore Entry…" links it; the link shows as a reference,
## hovers an excerpt and opens the entry in the side panel.
func _test_text_tools() -> void:
var sheets := main.screens.sheets
var page := main.data.add_page("Abbey of Vel", "Ruined. The monks left in a hurry, and something stayed behind in the crypt. The bell still rings at night, though no rope hangs from it and no one climbs the tower.")
var doc := sheets.store.create("Notes")
var note := SheetKinds.make_box(SheetKinds.TEXT, doc.new_box_id(), Vector2(0, 0))
note.value = "Go to the abbey"
doc.tabs[0]["boxes"].append(note)
sheets.store.save(doc)
sheets.open_doc(doc)
var ed := sheets.editor
ed.set_mode(Main.Mode.PLAY)
var view: SheetBoxView = ed.canvas.views[note.id]
var shown: RichTextLabel = view.find_child("Shown", true, false)
shown.gui_input.emit(_click())
var toolbar: SheetTextToolbar = view.find_child("Toolbar", true, false)
_check(toolbar.is_visible_in_tree(), "editing a text box shows the toolbar")
var edit: TextEdit = view.find_child("Edit", true, false)
edit.select(0, 0, 0, 2)
(toolbar.find_child("Bold", false, false) as Button).pressed.emit()
_eq(str(note.value), "[b]Go[/b] to the abbey", "B wraps the selection in [b]")
edit.select(0, 17, 0, 22)
toolbar.pick_lore()
var picker: LoreLinkPicker = null
for child in main.get_children():
if child is LoreLinkPicker:
picker = child
_check(picker != null, "Link a Lore Entry… opens the picker")
picker.search.text = "abbey"
picker.fill()
(picker.find_child(page.id.validate_node_name(), true, false) as Button).pressed.emit()
note = ed.doc.find_box(note.id)
_eq(str(note.value), "[b]Go[/b] to the [url=lore:%s]abbey[/url]" % page.id, "picking an entry links the selected words")
shown = ed.canvas.views[note.id].find_child("Shown", true, false)
_check(shown.text.contains("[bgcolor=#%s]" % Style.REF_BG.to_html(false)), "the link shows in the reference colours")
_check(SheetLoreLinks.excerpt(page).ends_with("…"), "the hover excerpt is cut with …")
shown.meta_clicked.emit("lore:" + page.id)
_check(ed.details.visible and ed.details.lore_id == page.id, "clicking the link opens the side panel")
var title: Label = ed.details.find_child("Title", true, false)
_eq(title.text, "Abbey of Vel", "with the Lore Entry")
ed.details.close()
main.data.remove_page(page.id)
sheets.show_list()

View file

@ -0,0 +1 @@
uid://d2tj2tr8qawy4

213
tests/test_sheets.gd Normal file
View file

@ -0,0 +1,213 @@
extends TestBase
## Headless checks for sheets (no UI): the file format round trip, boxes and
## tabs, the store (save, list, templates, new from template) and snapshot undo;
## My library (LoreLibrary) and item sheets of Lore Entries (SheetItems).
## Run: tools/run_tests.sh sheets
const ROOT := "user://test_sheets/"
func run() -> void:
_wipe(ROOT)
_test_round_trip()
_test_boxes()
_test_store()
_test_history()
_test_values()
_test_links()
_test_share_file()
_test_lore_items()
_wipe(ROOT)
finish()
func _test_round_trip() -> void:
var doc := SheetDoc.new("brin", "Brin Hollowmere")
doc.tint = "#3a7bd5"
var box := SheetKinds.make_box(SheetKinds.NUMBER, doc.new_box_id(), Vector2(37, 9))
box.title = "Strength"
box.value = 14
box.var_name = "str"
box.config = {"min": 3}
doc.tabs[0]["boxes"].append(box)
doc.add_tab("Spells")
var back := SheetDoc.from_dict(JSON.parse_string(JSON.stringify(doc.to_dict())))
_eq(back.name, "Brin Hollowmere", "the name survives")
_eq(back.tint, "#3a7bd5", "the tint survives")
_eq(back.tabs.size(), 2, "both tabs survive")
var b2 := back.find_box(box.id)
_check(b2 != null and b2.title == "Strength" and int(b2.value) == 14 and b2.var_name == "str", "a box keeps its title, value and variable")
_eq(Vector2(b2.x, b2.y), Vector2(32, 16), "a new box snaps to the grid")
_eq(int(b2.config.get("min", 0)), 3, "a box keeps its settings")
func _test_boxes() -> void:
var doc := SheetDoc.new("t", "T")
var a := SheetKinds.make_box(SheetKinds.TEXT, doc.new_box_id(), Vector2.ZERO)
doc.tabs[0]["boxes"].append(a)
var b := SheetKinds.make_box(SheetKinds.HEADING, doc.new_box_id(), Vector2.ZERO)
doc.tabs[0]["boxes"].append(b)
_check(a.id != b.id, "boxes get different ids")
doc.remove_box(a.id)
_check(doc.find_box(a.id) == null and doc.find_box(b.id) != null, "removing a box keeps the others")
var t2 := doc.add_tab("Notes")
_check(t2["id"] != doc.tabs[0]["id"], "tabs get different ids")
func _test_store() -> void:
var store := SheetStore.new(ROOT)
var doc := store.create("Brin")
_eq(doc.id, "brin", "the file id comes from the name")
var box := SheetKinds.make_box(SheetKinds.NUMBER, doc.new_box_id(), Vector2.ZERO)
box.value = 9
doc.tabs[0]["boxes"].append(box)
store.save(doc)
_eq(store.create("Brin").id, "brin-2", "a second sheet with the same name gets its own id")
_eq(store.list().size(), 2, "the list shows both sheets")
var tpl_id := store.save_as_template(doc, "Knight")
_eq(store.list(true).size(), 1, "the template is listed apart")
var made := store.create("Sir Ada", tpl_id)
_eq(made.from_template, tpl_id, "a sheet remembers its template")
_eq(int(made.tabs[0]["boxes"][0].value), 9, "a sheet from a template starts with its boxes")
_eq(store.load_sheet(made.id).name, "Sir Ada", "it is saved")
store.delete("brin-2")
_eq(store.list().size(), 2, "deleting removes it from the list")
_check(store.load_sheet("../x") == null, "bad ids are refused")
func _test_history() -> void:
var hist := SnapshotHistory.new()
var doc := SheetDoc.new("h", "One")
hist.record(doc.to_dict(), "Rename")
doc.name = "Two"
_check(hist.can_undo() and hist.undo_label() == "Rename", "an edit can be undone")
doc = SheetDoc.from_dict(hist.undo(doc.to_dict()))
_eq(doc.name, "One", "undo puts it back")
doc = SheetDoc.from_dict(hist.redo(doc.to_dict()))
_eq(doc.name, "Two", "redo does it again")
hist.record(doc.to_dict(), "Again")
_check(not hist.can_redo(), "a new edit clears redo")
func _test_values() -> void:
var doc := SheetDemo.create()
var values := SheetValues.vars(doc)
_eq(values.get("str"), 14.0, "a number reads as its value")
_eq(values.get("str_mod"), 2, "a formula reads other boxes: floor((14 - 10) / 2)")
var talents := _box(doc, "Talents")
var p := SheetValues.pool(talents)
_check(p["total"] == 20.0 and p["spent"] == 18.0 and p["left"] == 2.0, "the pool takes each cost off: %s" % str(p))
(talents.value as Array).append({"Name": "Big", "Cost": 5})
_eq(SheetValues.pool(talents)["left"], -3.0, "going over the pool is allowed")
var purse := _box(doc, "Purse")
_check(is_equal_approx(SheetValues.currency_total(purse), 12.0 + 0.7 + 0.3), "currency adds up in the first coin")
var xp := _box(doc, "XP")
var lv := SheetValues.xp_level(xp)
_check(lv["level"] == 2 and lv["next"] == 4000.0, "XP 2600 is level 2, next at 4000: %s" % str(lv))
_eq(SheetValues.slots_left(_box(doc, "Spell slots")), 5, "spell slots left: 4 + 2 - 1 used")
var loop := _box(doc, "STR mod")
loop.config["expr"] = "@str_mod + 1"
_check(SheetValues.formula(doc, loop)["error"] != "", "a formula that uses itself gives an error, not a hang")
var rolled := SheetValues.evaluate(doc, "1d1 + @str")
_eq(rolled["value"], 15, "dice in a formula roll with sheet values")
func _box(doc: SheetDoc, title: String) -> SheetBox:
for tab in doc.tabs:
for b: SheetBox in tab["boxes"]:
if b.title == title:
return b
return null
## The spread bridge: names with and without a prefix, what a roll may write,
## and locks.
func _test_links() -> void:
var doc := SheetDemo.create()
var board := TowerBoard.new()
var card := RollTable.create(RollTable.KIND_SHEET, "c1", "Brin")
card.sheet_id = doc.id
board.tables.append(card)
var vars := {}
var given := SheetLinks.inject(board, vars, func(_id: String) -> SheetDoc: return doc)
_eq(vars["str"]["value"], 14, "a linked box becomes @str")
_check(given.has("str_mod"), "formulas are lent too")
card.sheet_prefix = "brin"
vars = {}
given = SheetLinks.inject(board, vars, func(_id: String) -> SheetDoc: return doc)
_check(vars.has("brin_str") and not vars.has("str"), "a prefix makes it @brin_str")
vars["brin_str"] = {"value": 16, "source": "roll"}
var found := SheetLinks.changes(given, vars)
_eq(found.size(), 1, "only the changed value is seen")
var strength := doc.find_box(found[0]["box"])
_check(SheetLinks.write(strength, 16) and int(strength.value) == 16, "a number box takes the rolled value")
strength.locked = true
_check(not SheetLinks.write(strength, 3) and int(strength.value) == 16, "a locked box keeps its value")
var mod: SheetBox = null
for b: SheetBox in doc.tabs[0]["boxes"]:
if b.var_name == "str_mod":
mod = b
_check(not SheetLinks.write(mod, 9), "a formula can't be written by a roll")
var saved := TowerBoard.new()
saved.load_dict(board.to_dict())
_check(saved.tables[0].sheet_id == doc.id and saved.tables[0].sheet_prefix == "brin", "a Sheet card keeps its sheet and prefix")
var text := SheetText.summary(doc, "brin")
_check(text.contains("[b]Strength:[/b] {@brin_str}"), "a roll shows linked boxes as {@prefix_name}")
_check(text.contains("[b]Talents:[/b] Shield Wall, Keen Eye, Second Wind"), "and lists by their names")
var tab := doc.tabs[0]
var first: SheetBox = tab["boxes"][1]
_check(SheetDoc.overlaps(tab, first.rect()), "a box's own place overlaps it")
var spot := SheetDoc.free_spot(tab, first.rect(), SheetKinds.GRID)
_check(not SheetDoc.overlaps(tab, Rect2(spot, first.rect().size)), "free_spot finds a place that covers nothing")
func _test_share_file() -> void:
var store := SheetStore.new(ROOT.path_join("mine"))
var doc := store.create("Brin")
doc.from_template = "fighter"
var source := ROOT.path_join("portrait.png")
Image.create(4, 4, false, Image.FORMAT_RGB8).save_png(source)
var portrait := SheetKinds.make_box(SheetKinds.PICTURE, doc.new_box_id(), Vector2.ZERO)
portrait.value = store.keep_picture(source)
doc.tabs[0]["boxes"].append(portrait)
var heading := SheetKinds.make_box(SheetKinds.HEADING, doc.new_box_id(), Vector2(0, 200))
heading.title = "Gear"
doc.add_tab("Spells")["boxes"].append(heading)
var text := SheetFile.share_text(doc)
_check(text.contains("\"pictures\"") and not text.contains("fighter"), "a share file carries its pictures, not our template")
var theirs := SheetStore.new(ROOT.path_join("theirs"))
var got := SheetFile.import_text(theirs, text)
_check(got != null and got.name == "Brin" and got.tabs.size() == 2 and got.from_template == "", "a share file imports with its tabs")
var picture := str(got.find_box(portrait.id).value)
_check(picture.begins_with(theirs.pictures_dir()), "the picture is written into the receiver's pictures")
_eq(FileAccess.get_file_as_bytes(picture), FileAccess.get_file_as_bytes(source), "the picture arrives whole")
_check(theirs.load_sheet(got.id) != null, "the imported sheet is saved")
_eq(SheetFile.import_text(store, text).id, "brin-2", "importing beside the original gets a new id")
_check(SheetFile.import_text(store, "{\"name\": 1}") == null, "other files are refused")
var page := SheetExport.sheet_html(got, func(_doc: SheetDoc, line: String) -> String: return line)
_eq(page.count("<section>"), 2, "the print page has one section per tab")
_check(page.contains("<h2>Spells</h2>") and page.contains("<b>Gear</b>"), "it shows the tab names and boxes")
## My library survives a reload; a Lore Entry keeps its item sheet link in the
## spread file; a dropped copy gets its own copy of the sheet, a linked one doesn't.
func _test_lore_items() -> void:
var store := SheetStore.new(ROOT.path_join("lore"))
var library := LoreLibrary.new(store.root)
var blade := library.add_page("[b]Ashen Blade[/b]", "Burns what it cuts.")
blade.tags.assign(["weapon"])
var doc := SheetItems.make_sheet(store, blade)
library.save()
_check(store.load_sheet(blade.sheet) != null and (doc.tabs[0]["boxes"][2] as SheetBox).title == "Charges", "an entry gets an item sheet with Damage, Charges and Notes")
var back := LoreLibrary.new(store.root).get_page(blade.id)
_check(back != null and back.sheet == doc.id and back.tags == blade.tags, "My library comes back from its file, with the sheet link")
var board := TowerBoard.new()
var page := board.add_page("Ashen Blade")
page.sheet = doc.id
var again := TowerBoard.new()
again.load_dict(JsonIO.canonical(JSON.parse_string(board.to_json())))
_eq(again.get_page(page.id).sheet, doc.id, "a spread's Lore Entry saves its sheet link")
var copied := SheetItems.with_links({"name": "Ashen Blade"}, blade, "lib:" + blade.id, false, store)
_check(str(copied.get("sheet", "")) not in ["", doc.id] and not copied.has("lore"), "a copy gets its own item sheet")
var linked := SheetItems.with_links({"name": "Ashen Blade"}, blade, "lib:" + blade.id, true, store)
_check(linked["sheet"] == doc.id and linked["lore"] == "lib:" + blade.id, "a linked item keeps the entry and its sheet")

1
tests/test_sheets.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://1kc8uuaa5gt6

View file

@ -1,5 +1,5 @@
extends AppTestBase
## The top bar's menus (View ▾, the zoom control, Board ▾ with Pack, Help ▾),
## The top bar's menus (View ▾, the zoom control, Spread ▾ with Pack, Help ▾),
## striped result rows, the Build card's ⋯ menu and the row × that shows on
## hover or selection, and the Help window's topics and links.
## Run: tools/run_tests.sh top_bar
@ -17,6 +17,7 @@ func run() -> void:
await _test_card_menu()
await _test_help()
await _test_build_hint()
await _test_palette()
await _test_welcome()
finish()
@ -138,22 +139,29 @@ func _test_help() -> void:
await _frames()
## Play shows that Build mode exists: a greyed "+ Card" that explains and
## offers to switch, and a greyed "New card" in the ☰ menu.
## Play shows that Build mode exists: the card palette is greyed under a
## notice with Switch to Build, a greyed item explains, and the ☰ menu shows
## a greyed "New card".
func _test_build_hint() -> void:
main.set_mode(Main.Mode.PLAY)
var bar := main.top_bar
_check(bar.play_add_button.visible and not bar._build_tools.visible, "Play shows the greyed + Card, not the Build tools")
var palette := main.left_dock.palette
main.left_dock.show_tab(LeftDock.CARDS)
await _frames()
_check(palette.notice.visible and not bar._build_tools.visible, "Play shows the palette notice, not the Build tools")
var names := Actions.background(main, Vector2.ZERO).map(func(a: Dictionary) -> String: return str(a.get("text", "")))
var item: Dictionary = Actions.background(main, Vector2.ZERO)[names.find("New card")] if names.has("New card") else {}
_check(item.get("disabled", false), "the ☰ menu shows New card greyed in Play")
bar.play_add_button.pressed.emit()
var before := main.data.tables.size()
(palette.find_child("Roll table", true, false) as Button).pressed.emit()
_eq(main.data.tables.size(), before, "a greyed palette item adds nothing in Play")
_eq(bar._toast_label.text, BuildModeHint.MESSAGE, "clicking it explains Build mode")
_check(bar._toast_undo.visible and bar._toast_undo.text == "Switch to Build", "the toast offers Switch to Build")
bar._toast_undo.pressed.emit()
await _frames()
_eq(main.mode, Main.Mode.BUILD, "Switch to Build switches")
_check(not bar.play_add_button.visible, "Build hides the greyed button")
await _frames()
_check(not palette.notice.visible, "Build hides the palette notice")
main.toast("Saved")
_eq(bar._toast_undo.text, "Undo", "a later toast's button is Undo again")
@ -171,3 +179,52 @@ func _test_welcome() -> void:
(dialog.footer.get_child(2) as Button).pressed.emit()
await _frames(20)
_check(not is_instance_valid(dialog) or dialog.is_queued_for_deletion(), "Explore the demo closes it")
## The card palette: search narrows it, a click adds in the middle of the
## view, a drop on the spread adds there, Enter adds the first match.
func _test_palette() -> void:
main.set_mode(Main.Mode.BUILD)
var palette := main.left_dock.palette
main.left_dock.show_tab(LeftDock.CARDS)
palette.search.text = "dice"
palette.search.text_changed.emit("dice")
_check(palette.find_child("Dice table", true, false) != null and palette.find_child("Branch", true, false) == null, "search narrows the palette")
palette.search.text = "zzqx"
palette.search.text_changed.emit("zzqx")
_check(palette.find_child("Dice table", true, false) == null, "a search with no match empties it")
palette.search.text = ""
palette.search.text_changed.emit("")
var before := main.data.tables.size()
(palette.find_child("Deck", true, false) as Button).pressed.emit()
var deck := main.data.tables[main.data.tables.size() - 1]
_check(main.data.tables.size() == before + 1 and deck.card_mode, "clicking Deck adds a deck")
var spot := main.board.global_position + main.board.size / 2.0 + Vector2(40, 30)
var item: Dictionary = CardCatalog.find(RollTable.KIND_CHECK)
_check(palette.drop_at(palette._add_card.bind(item), spot), "a drop on the spread is taken")
var check := main.data.tables[main.data.tables.size() - 1]
var want := (main.board.screen_to_world(spot - main.board.global_position) - Vector2(128, 20)).round()
_check(check.kind == RollTable.KIND_CHECK and check.position == want, "the dropped card sits where it was let go")
_check(not palette.drop_at(palette._add_card.bind(item), Vector2(-50, -50)), "a drop off the spread adds nothing")
var button := main.top_bar.palette_button
_check(button.is_visible_in_tree() and button.button_pressed, "Build shows a lit Card palette button")
button.pressed.emit()
_check(not main.left_dock.visible and not button.button_pressed, "the button closes the palette")
button.pressed.emit()
_check(main.left_dock.showing(LeftDock.CARDS) and button.button_pressed, "and opens it again")
var tpl_id := str(main.templating.templates().list()[0]["id"])
var spot2 := spot + Vector2(-200, 60)
var at2 := (main.board.screen_to_world(spot2 - main.board.global_position) - Vector2(128, 20)).round()
var tpl := main.templating.templates().get_template(tpl_id)
var made: Dictionary = main.templating.insert_template(tpl, {}, at2)
var top_left := Vector2(INF, INF)
for t: RollTable in made["tables"]:
top_left = Vector2(minf(top_left.x, t.position.x), minf(top_left.y, t.position.y))
for g: TableGroup in made.get("groups", []):
top_left = Vector2(minf(top_left.x, g.position.x), minf(top_left.y, g.position.y))
_eq(top_left, at2, "a template dropped on the spread lands where it was let go")
palette.search.text = "branch"
palette.search.text_submitted.emit("branch")
_eq(main.data.tables[main.data.tables.size() - 1].kind, RollTable.KIND_ROUTER, "Enter adds the first match")
palette.search.text = ""
palette.search.text_changed.emit("")

View file

@ -1,5 +1,5 @@
extends AppTestBase
## Scale values in the UI (Scales): making one (+ Card, the inspector's steps
## Scale values in the UI (Scales): making one (the card palette, the inspector's steps
## and starting step, switching type), showing one (the card's value and row
## of steps, the Variables tab), the effect and condition rows for a scale,
## and the help topic.
@ -51,9 +51,9 @@ func _t(id: String) -> RollTable:
func _test_add_card() -> void:
var found := false
for k: Array in MainEditing.ADD_KINDS:
found = found or (k[1] == RollTable.KIND_VARIABLE and k[2] == RollTable.VAR_SCALE and str(k[0]).begins_with("Scale"))
_check(found, "+ Card lists Scale (ordered steps)")
for item: Dictionary in CardCatalog.ITEMS:
found = found or (item["kind"] == RollTable.KIND_VARIABLE and item["sub"] == RollTable.VAR_SCALE and item["label"] == "Scale")
_check(found, "the card catalog lists Scale")
var t := main.editing.add_table(RollTable.KIND_VARIABLE, RollTable.VAR_SCALE)
_check(t.is_scale() and t.steps == (["Low", "Medium", "High"] as Array[String]) and t.initial == "Low", "a new scale has Low, Medium, High and starts Low")
main.data.remove_table(t.id)

View file

@ -90,6 +90,8 @@ static func card(m: Main, t: RollTable) -> Array:
list.append({"text": "Roll", "do": m.rolling.start_roll.bind(t.id)})
list.append({"text": "Roll several times…", "do": BatchRoll.ask.bind(m, t.id),
"tip": "Roll the whole chain a number of times and see every result together"})
if t.kind == RollTable.KIND_SHEET and t.sheet_id != "":
list.append_array(m.sheet_links.menu_items(t))
if t.card_mode:
list.append({"text": "Shuffle the deck", "do": m.reshuffle_table.bind(t.id)})
if c and c.can_collapse():
@ -165,16 +167,20 @@ static func group(m: Main, g: TableGroup) -> Array:
## bar's ☰ menu (at = the view's centre).
static func background(m: Main, at: Vector2) -> Array:
var list: Array = []
list.append({"text": "Main menu", "do": m.screens.show.bind(MainScreens.MENU), "tip": "Spreads, Sheets, Settings and Quit"})
list.append({"sep": ""})
if m.mode == Main.Mode.BUILD:
var kinds: Array = []
for i in MainEditing.ADD_KINDS.size():
var k: Array = MainEditing.ADD_KINDS[i]
kinds.append({"text": str(k[0]), "do": func() -> void: m.editing.add_table(str(k[1]), str(k[2]), at)})
for item: Dictionary in CardCatalog.ITEMS:
kinds.append({"text": str(item["label"]), "tip": str(item["tip"]),
"do": func() -> void: m.editing.add_table(str(item["kind"]), str(item["sub"]), at, str(item["variant"]))})
list.append({"text": "New card", "sub": kinds})
list.append({"text": "New card from template…", "do": m.templating.open_template_picker})
var picked := m.selection.size()
list.append({"text": "Group the selection Ctrl+G", "do": m.grouping.group_selection, "disabled": picked == 0 and m.selecting.groups.is_empty(),
"tip": "Select cards first: drag a box around them"})
list.append({"text": "Save selection as template…", "do": m.templating.save_selection_as_template, "disabled": picked == 0,
"tip": "Select cards first: drag a box around them"})
list.append({"sep": ""})
else:
list.append(BuildModeHint.menu_item())
@ -183,7 +189,9 @@ static func background(m: Main, at: Vector2) -> Array:
list.append({"text": "Shuffle all decks", "do": m.local_state.reshuffle_all, "disabled": not has_decks(m),
"tip": "Put every Deck-mode card's results back"})
list.append({"text": "Fit spread", "do": m.board.fit})
list.append({"text": "Hide the list" if m.list_view.visible else "List view", "do": m.list_view.toggle,
list.append({"text": "Hide the card palette" if m.left_dock.showing(LeftDock.CARDS) else "Card palette", "do": m.left_dock.toggle_tab.bind(LeftDock.CARDS),
"tip": "Every kind of card and your templates, to click or drag onto the spread"})
list.append({"text": "Hide the list" if m.list_view.shown() else "List view", "do": m.list_view.toggle,
"tip": "The cards as a list with their groups"})
list.append({"text": "Close the Lore Index" if m.book.visible else "Lore Index", "do": m.book.toggle,
"tip": "Reusable results (Lore Entries) to drag onto tables"})

View file

@ -1,25 +1,23 @@
class_name BookPanel
extends PanelContainer
## The Lore Index (Book in code): the spread's reusable results, its Lore
## Entries (BookPage), docked beside the spread; in Build it is a tab beside
## the inspector (SideTabs).
## A searchable list (name, text and tags) above the page editor. Drag a page
## onto a result to link it there, or onto a card to add it as a new result.
## The Lore Index (Book in code) docked beside the spread: its Lore Entries
## (BookPage) on two levels, This spread and My library (LoreList). In Build
## it is a tab beside the inspector (SideTabs); in Play it opens on its own.
## Drag an entry onto a result to link it there, or onto a card to add it as
## a new result (a My library entry is copied into the spread first).
## Open from View ▾, ☰ or right-clicking the spread; × closes it.
const WIDTH := 340.0
const SETTING := "book"
var m: Main
## The shared list, search and editor.
var lore: LoreList
var list: ItemList
var editor: PageEditor
var splitter: PanelSplitter
var _search: LineEdit
var _ids: Array[String] = []
var _rev := -1
var _dragging := ""
var _tabs: Control
var _title: Label
func setup(p_main: Main) -> void:
@ -30,78 +28,25 @@ func setup(p_main: Main) -> void:
add_child(col)
_tabs = SideTabs.make_row(m, SideTabs.LORE)
col.add_child(_tabs)
var head := HBoxContainer.new()
head.add_theme_constant_override("separation", 6)
col.add_child(head)
_title = Style.make_label("Lore Index", Style.display(), 20, Style.ON_BG)
_title.size_flags_horizontal = SIZE_EXPAND_FILL
head.add_child(_title)
var add := Style.bar_button("+ Lore Entry")
add.tooltip_text = "A new Lore Entry: a result you can reuse on any table"
add.pressed.connect(new_page)
head.add_child(add)
var close := Style.bar_button("×")
close.tooltip_text = "Close the Lore Index"
close.pressed.connect(func() -> void: set_shown(false))
head.add_child(close)
_search = LineEdit.new()
_search.placeholder_text = "Search Lore Entries and tags"
_search.clear_button_enabled = true
ModalCard.style_line_edit(_search)
_search.text_changed.connect(func(_s: String) -> void: refresh())
col.add_child(_search)
list = ItemList.new()
list.custom_minimum_size = Vector2(0, 170)
list.add_theme_stylebox_override("panel", Style.box(Style.CARD, 6, [6, 6, 6, 6]))
list.add_theme_color_override("font_color", Style.INK)
list.add_theme_color_override("font_selected_color", Style.INK)
list.add_theme_stylebox_override("selected", Style.box(Style.LIT, 4))
list.add_theme_stylebox_override("selected_focus", Style.box(Style.LIT, 4))
list.item_selected.connect(func(i: int) -> void: editor.show_page(m.data.get_page(_ids[i])))
list.set_drag_forwarding(_drag, Callable(), Callable())
col.add_child(list)
var scroll := ScrollContainer.new()
scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
scroll.size_flags_vertical = SIZE_EXPAND_FILL
col.add_child(scroll)
editor = PageEditor.new(m)
editor.size_flags_horizontal = SIZE_EXPAND_FILL
scroll.add_child(editor)
editor.show_page(null)
func _process(_delta: float) -> void:
if visible and m.data and m.edit_rev != _rev:
_rev = m.edit_rev
refresh()
lore = LoreList.new()
lore.size_flags_vertical = SIZE_EXPAND_FILL
lore.setup(m, func() -> void: set_shown(false))
lore.dropped.connect(func(page: BookPage, level: LoreLevel, at: Vector2) -> void: drop_page(page.id, at, level))
lore.open_sheet = func(id: String) -> void: m.sheet_links.open_sheet(id)
col.add_child(lore)
list = lore.list
editor = lore.editor
_search = lore.search
## Refills the list (search applied), keeping the selection.
func refresh() -> void:
var keep := editor.page.id if editor.page else ""
var q := _search.text.strip_edges().to_lower()
list.clear()
_ids.clear()
for p in m.data.book:
var hay := (p.label() + " " + Formatter.strip_tags(p.text) + " " + " ".join(p.tags)).to_lower()
if q != "" and not hay.contains(q):
continue
var i := list.add_item(p.label())
list.set_item_tooltip(i, ("Tags: " + ", ".join(p.tags) + "\n" if not p.tags.is_empty() else "") + "Drag onto a result to use it")
_ids.append(p.id)
if p.id == keep:
list.select(i)
if keep != "" and m.data.get_page(keep) == null:
editor.show_page(null)
lore.refresh()
## After undo or redo: the page in the editor is shown again from the
## restored spread, so its fields show the undone text at once.
## After undo or redo: shows the entry in the editor again.
func reload_page() -> void:
if editor == null or editor.page == null:
return
editor.show_page(m.data.get_page(editor.page.id))
refresh()
lore.reload_page()
func set_width(px: float) -> void:
@ -112,7 +57,6 @@ func set_shown(on: bool) -> void:
visible = on
if splitter:
splitter.visible = on
_rev = -1
if m.state:
m.state.set_setting(SETTING, on)
m.state.save()
@ -126,73 +70,50 @@ func toggle() -> void:
## Build shows the Inspector | Lore Index tabs in place of the title.
func show_tabs(on: bool) -> void:
_tabs.visible = on
_title.visible = not on
lore.title.visible = not on
func new_page() -> BookPage:
m.undo_redo._begin_edit()
var p := m.data.add_page("New Lore Entry")
m.mark_dirty()
m.undo_redo._end_edit()
if not visible:
set_shown(true)
refresh()
select_page(p.id)
return p
return lore.new_page()
## Adds a result's text and details to the Book and links the result to it.
## Adds a result's text and details to the spread's Lore Index and links the result to it.
func save_result(t: RollTable, e: TableEntry) -> BookPage:
m.undo_redo._begin_edit()
var p := m.data.add_page(e.text, e.details)
p.image = e.image
e.page = p.id
m.inspector_edited(t.id)
m.mark_dirty()
m.undo_redo._end_edit()
# Lambdas copy local variables, so the page comes back in an Array.
var made: Array[BookPage] = []
lore.levels[LoreLevel.SPREAD].edit(func() -> void:
var added := m.data.add_page(e.text, e.details)
added.image = e.image
e.page = added.id
m.inspector_edited(t.id)
made.append(added))
var p := made[0]
set_shown(true)
refresh()
lore.set_level(LoreLevel.SPREAD)
select_page(p.id)
m.toast("Saved “%s” to the Lore Index" % p.label())
return p
func select_page(pid: String) -> void:
var i := _ids.find(pid)
if i >= 0:
list.select(i)
editor.show_page(m.data.get_page(pid))
if lore.level.key != LoreLevel.SPREAD and m.data.get_page(pid):
lore.set_level(LoreLevel.SPREAD)
lore.select_page(pid)
func _drag(at: Vector2) -> Variant:
var i := list.get_item_at_position(at, true)
if i < 0:
return null
_dragging = _ids[i]
var l := Style.make_label(list.get_item_text(i), Style.body_bold(), 15, Style.INK)
var pc := PanelContainer.new()
pc.add_theme_stylebox_override("panel", Style.box(Style.LIT, 6, [8, 4, 8, 4]))
pc.add_child(l)
list.set_drag_preview(pc)
return {"book_page": _dragging}
## Nothing took the drop (cards' text fields don't), so the Book places it.
func _notification(what: int) -> void:
if what == NOTIFICATION_DRAG_END and _dragging != "":
var pid := _dragging
_dragging = ""
if not get_viewport().gui_is_drag_successful():
drop_page(pid, get_global_mouse_position())
## Drops a page at a screen point: onto a result links it there; onto a card
## (not a result) adds it as a new result. True when it landed somewhere.
func drop_page(pid: String, at: Vector2) -> bool:
## Drops an entry at a screen point: onto a result links it there; onto a card
## (not a result) adds it as a new result. An entry from `from_level` My
## library is copied into the spread first (one undo step). True when it landed.
func drop_page(pid: String, at: Vector2, from_level: LoreLevel = null) -> bool:
for c: TableCard in m.cards.values():
if not c.is_visible_in_tree() or not c.get_global_rect().has_point(at) or c.table.kind == RollTable.KIND_VARIABLE:
continue
var linked := pid
m.undo_redo._begin_edit()
if from_level and from_level.key == LoreLevel.LIBRARY:
linked = lore.levels[LoreLevel.SPREAD].copy_raw(from_level.get_page(pid)).id
var target: TableEntry = null
for eid: String in c.rows:
var row: Control = c.rows[eid]
@ -201,10 +122,11 @@ func drop_page(pid: String, at: Vector2) -> bool:
if target == null:
m.editing.add_entry(c.table.id)
target = c.table.entries[c.table.entries.size() - 1]
m.data.link_page(target, pid)
m.data.link_page(target, linked)
m.inspector_edited(c.table.id)
m.mark_dirty()
m.undo_redo._end_edit()
m.toast("“%s” now shows on %s" % [m.data.get_page(pid).label(), Formatter.strip_tags(c.table.name)])
m.toast("“%s” now shows on %s" % [m.data.get_page(linked).label(), Formatter.strip_tags(c.table.name)])
return true
return false

View file

@ -1,23 +1,15 @@
class_name BuildModeHint
extends RefCounted
## Play mode tells new players that Build mode exists: a greyed "+ Card"
## button in the top bar and a greyed "New card" in the ☰ menu. Clicking the
## button explains, offers "Switch to Build" and makes the Build switch pulse.
## Play mode tells new players that Build mode exists: the card palette is
## greyed under a notice with "Switch to Build" (CardPalette), and the ☰ menu
## has a greyed "New card". Clicking a greyed palette item explains, offers
## "Switch to Build" and makes the Build switch pulse.
const MESSAGE := "Cards are added and edited in Build mode."
const PALETTE_MESSAGE := "Cards are added in Build mode."
const TIP := "Switch to Build mode (top left) to add and edit cards"
## The greyed "+ Card" shown in Play in place of the real one.
static func make_button(m: Main) -> Button:
var b := Style.bar_button("+ Card")
b.modulate.a = 0.5
b.tooltip_text = TIP
b.focus_mode = Control.FOCUS_NONE
b.pressed.connect(func() -> void: explain(m))
return b
## The ☰ menu's greyed "New card" in Play (Actions.background).
static func menu_item() -> Dictionary:
return {"text": "New card", "disabled": true, "tip": TIP}
@ -36,3 +28,21 @@ static func pulse(b: Control) -> void:
for i in 3:
tween.tween_property(b, "modulate", Color(1.6, 1.4, 0.8), 0.18)
tween.tween_property(b, "modulate", Color.WHITE, 0.22)
## The notice over a greyed palette in Play: the message and a button that
## switches to Build (`to_build`). Shared by the card and field palettes.
static func make_notice(_m: Main, to_build: Callable, message: String = PALETTE_MESSAGE) -> PanelContainer:
var box := PanelContainer.new()
box.add_theme_stylebox_override("panel", Style.bordered(Style.box(Style.CARD, 8, [10, 8, 10, 8]), 2, Style.TRIM))
var col := VBoxContainer.new()
col.add_theme_constant_override("separation", 6)
box.add_child(col)
var text := Style.make_label(message, Style.body_bold(), 14, Style.INK)
text.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
col.add_child(text)
var go := ModalCard.make_button("Switch to Build", "primary")
go.name = "SwitchToBuild"
go.pressed.connect(to_build)
col.add_child(go)
return box

89
ui/card_catalog.gd Normal file
View file

@ -0,0 +1,89 @@
class_name CardCatalog
extends RefCounted
## Every kind of card you can add, in one list: the card palette (CardPalette),
## right-click › New card (Actions.background) and the new card's starting name
## (MainEditing.add_table) all read it.
## `variant` gives the same kind different start settings: "dice" makes a
## ranged dice table, "deck" turns on Deck mode.
const GROUP_TABLES := "Tables"
const GROUP_ASK := "Ask the player"
const GROUP_LOGIC := "Logic"
const GROUP_VALUES := "Values"
const GROUP_SHEETS := "Sheets"
const GROUP_TEMPLATES := "Templates"
const GROUP_OTHER := "Other"
const VARIANT_DICE := "dice"
const VARIANT_DECK := "deck"
## Each item: label, group, kind, sub, variant, the new card's name, a tip and
## extra search words.
const ITEMS := [
{"label": "Roll table", "group": GROUP_TABLES, "kind": RollTable.KIND_ROLL, "sub": "", "variant": "",
"name": "New table", "tip": "Pick a result at random, by weight", "words": "random weight results"},
{"label": "Dice table", "group": GROUP_TABLES, "kind": RollTable.KIND_ROLL, "sub": "", "variant": VARIANT_DICE,
"name": "New dice table", "tip": "Results on number ranges, rolled with dice (1d100)", "words": "ranged d100 d20 d6 range"},
{"label": "Deck", "group": GROUP_TABLES, "kind": RollTable.KIND_ROLL, "sub": "", "variant": VARIANT_DECK,
"name": "New deck", "tip": "Draw results like cards: each comes up once until you shuffle", "words": "draw shuffle cards no repeats"},
{"label": "Check", "group": GROUP_TABLES, "kind": RollTable.KIND_CHECK, "sub": "", "variant": "",
"name": "Check", "tip": "Roll against a target: success or failure", "words": "target skill test success failure"},
{"label": "Which option", "group": GROUP_ASK, "kind": RollTable.KIND_CHOICE, "sub": "pick", "variant": "",
"name": "New choice", "tip": "The player picks one of a few options", "words": "choice pick question"},
{"label": "How many", "group": GROUP_ASK, "kind": RollTable.KIND_CHOICE, "sub": "number", "variant": "",
"name": "How many?", "tip": "The player types a number", "words": "choice number question count"},
{"label": "Open answer", "group": GROUP_ASK, "kind": RollTable.KIND_CHOICE, "sub": "text", "variant": "",
"name": "What is it?", "tip": "The player types any answer, like a name", "words": "choice text question name"},
{"label": "Branch", "group": GROUP_LOGIC, "kind": RollTable.KIND_ROUTER, "sub": "", "variant": "",
"name": "Branch", "tip": "If / else if / otherwise: go one way or another", "words": "if else condition router"},
{"label": "Repeat", "group": GROUP_LOGIC, "kind": RollTable.KIND_LOOP, "sub": "times", "variant": "",
"name": "Repeat", "tip": "Do the next cards several times", "words": "loop times while"},
{"label": "Variable", "group": GROUP_VALUES, "kind": RollTable.KIND_VARIABLE, "sub": "number", "variant": "",
"name": "New variable", "tip": "A value that rolls can read and change, like @gold", "words": "value number text @"},
{"label": "Ledger", "group": GROUP_VALUES, "kind": RollTable.KIND_VARIABLE, "sub": RollTable.VAR_COLLECTION, "variant": "",
"name": "Skills", "tip": "A named list of values: skills, contacts…", "words": "collection list skills contacts"},
{"label": "Scale", "group": GROUP_VALUES, "kind": RollTable.KIND_VARIABLE, "sub": RollTable.VAR_SCALE, "variant": "",
"name": "New scale", "tip": "Ordered steps that move up or down", "words": "steps ladder ordered"},
{"label": "New sheet", "group": GROUP_SHEETS, "kind": RollTable.KIND_SHEET, "sub": "", "variant": "",
"name": "Sheet", "tip": "A new sheet on the spread (open it to add fields)", "words": "character summary text"},
]
## The item for a kind, sub and variant: an exact match first, then the first
## item of that kind (a choice card also needs its sub to match). {} if none.
static func find(kind: String, sub: String = "", variant: String = "") -> Dictionary:
for item: Dictionary in ITEMS:
if item["kind"] == kind and item["sub"] == sub and item["variant"] == variant:
return item
for item: Dictionary in ITEMS:
if item["kind"] != kind or item["variant"] != variant:
continue
if kind == RollTable.KIND_CHOICE and sub != "":
continue
if item["sub"] == RollTable.VAR_COLLECTION:
continue
return item
return {}
## The group names in palette order (the templates group sits before Other).
static func groups() -> Array[String]:
var out: Array[String] = []
for item: Dictionary in ITEMS:
if not out.has(item["group"]):
out.append(item["group"])
return out
## Gives a new card its variant's start settings.
static func apply_variant(t: RollTable, variant: String) -> void:
match variant:
VARIANT_DICE:
TableSettingsRules.assign_ranges(t)
VARIANT_DECK:
t.card_mode = true
# "sheet:<sheet id>:<prefix>": a Sheet card showing that sheet (MainSheetLinks.add_card).
if variant.begins_with("sheet:"):
t.sheet_id = variant.get_slice(":", 1)
t.sheet_prefix = variant.get_slice(":", 2)
t.width = 340

1
ui/card_catalog.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b5xhhmmdaceqg

111
ui/card_palette.gd Normal file
View file

@ -0,0 +1,111 @@
class_name CardPalette
extends VBoxContainer
## The Cards tab of the left dock: every kind of card (CardCatalog) and your
## templates in a PaletteList. Click an item to add it in the middle of the
## view; drag it to place it on the spread.
## In Play the items are greyed under a notice with "Switch to Build"
## (BuildModeHint), so players learn where cards are added.
## Palette-only items that aren't card kinds.
const GROUP_ITEM := {"label": "Empty group", "group": CardCatalog.GROUP_OTHER,
"tip": "A new, empty group. Drag cards onto it.", "words": "group frame folder"}
const ALL_TEMPLATES := {"label": "All templates…", "group": CardCatalog.GROUP_TEMPLATES,
"tip": "Search, import, rename and delete templates", "words": "import manage"}
var m: Main
var list: PaletteList
var search: LineEdit
var notice: PanelContainer
var _templates: Array[Dictionary] = []
var _sheets: Array[Dictionary] = []
func setup(p_main: Main) -> void:
m = p_main
add_theme_constant_override("separation", 8)
notice = BuildModeHint.make_notice(m, func() -> void: m.set_mode(Main.Mode.BUILD))
add_child(notice)
list = PaletteList.new()
list.setup("Search cards and templates", "Drag onto the spread, or click to add", "Add a card", "“dice”, “choice” or “if”")
list.size_flags_vertical = SIZE_EXPAND_FILL
list.sections_for = _sections
list.can_use = func() -> bool: return m.mode == Main.Mode.BUILD
list.on_blocked = BuildModeHint.explain.bind(m)
list.drop_at = drop_at
list.after_use = func() -> void:
if m.mobile:
m.mobile.show_list(false)
add_child(list)
search = list.search
list.rebuild()
func _process(_delta: float) -> void:
notice.visible = m.mode != Main.Mode.BUILD
## Reads the template list again (it lives in files, so not on every keystroke).
func refresh_templates() -> void:
_templates = m.templating.templates().list() if m.templating else []
_sheets.clear()
if m.screens:
_sheets = m.screens.sheets.store.list()
list.rebuild()
func _sections(query: String) -> Array:
var out: Array = []
for group in CardCatalog.groups():
var entries: Array = []
for item: Dictionary in CardCatalog.ITEMS:
if item["group"] == group and PaletteList.matches(item, query):
entries.append([item, _add_card.bind(item)])
if group == CardCatalog.GROUP_SHEETS:
entries.append_array(_sheet_entries(query))
out.append([group, entries])
var templates: Array = []
for row: Dictionary in _templates:
var item := {"label": row["name"], "group": CardCatalog.GROUP_TEMPLATES, "tip": row.get("description", ""), "words": "template"}
if PaletteList.matches(item, query):
templates.append([item, _add_template.bind(str(row["id"]))])
if PaletteList.matches(ALL_TEMPLATES, query):
templates.append([ALL_TEMPLATES, func(_at: Vector2) -> void: m.templating.open_template_picker()])
out.append([CardCatalog.GROUP_TEMPLATES, templates])
out.append([CardCatalog.GROUP_OTHER, [[GROUP_ITEM, _add_group_card]] if PaletteList.matches(GROUP_ITEM, query) else []])
return out
## Your sheets, to place on the spread as Sheet cards.
func _sheet_entries(query: String) -> Array:
var out: Array = []
for row: Dictionary in _sheets:
var item := {"label": row["name"], "group": CardCatalog.GROUP_SHEETS, "tip": "Place this sheet on the spread; tables can then use its boxes", "words": "sheet character"}
if PaletteList.matches(item, query):
out.append([item, func(at: Vector2) -> void: m.sheet_links.add_card(str(row["id"]), at)])
return out
## Adds through `on_add` with its top-left corner under a screen point on the spread.
func drop_at(on_add: Callable, screen_point: Vector2) -> bool:
var board := m.board
if not board.is_visible_in_tree() or not board.get_global_rect().has_point(screen_point):
return false
var world := board.screen_to_world(screen_point - board.global_position)
list.use(on_add, (world - Vector2(128, 20)).round())
return true
func _add_card(at: Vector2, item: Dictionary) -> void:
m.editing.add_table(str(item["kind"]), str(item["sub"]), at, str(item["variant"]))
func _add_template(at: Vector2, id: String) -> void:
var tpl := m.templating.templates().get_template(id)
if tpl.is_empty():
m.toast("Couldn't read that template")
return
m.templating.begin_template_insert(tpl, at)
func _add_group_card(at: Vector2) -> void:
m.list_view.new_group(at)

1
ui/card_palette.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://d3kx4jf3q4ukx

View file

@ -26,8 +26,10 @@ func open(key: String) -> void:
_return_id = m.data.id
_was_saving = m._saving_enabled
m._saving_enabled = false
m.collections._show_collection(DemoSpreads.build(key))
# The bar first: while it shows, the demo counts as open (old Sheet cards
# in a demo aren't migrated to sheet files, MainSheetLinks.migrate).
_show_bar(str(DemoSpreads.TITLES[key]))
m.collections._show_collection(DemoSpreads.build(key))
func back() -> void:

View file

@ -257,6 +257,8 @@ func show_meta(owner: Control, meta: String) -> void:
show_table(owner, arg)
"var":
_show_var(owner, arg)
"lore":
SheetLoreLinks.show_hover(main, owner, arg)
"missing":
show_for(owner, "Missing table", "There's no table called [b]%s[/b]. Check the spelling, or add a table with that name." % RichText.plain(arg))
"unset":

57
ui/field_palette.gd Normal file
View file

@ -0,0 +1,57 @@
class_name FieldPalette
extends VBoxContainer
## The sheet editor's field palette: every kind of box (SheetKinds) in a
## PaletteList, like the spread's card palette. Click adds a box in the middle
## of the canvas; drag drops it where you let go. Greyed in Play under a
## notice with Switch to Build.
const MESSAGE := "Fields are added in Build mode."
var ed: SheetEditor
var list: PaletteList
var notice: PanelContainer
func setup(p_editor: SheetEditor) -> void:
ed = p_editor
add_theme_constant_override("separation", 8)
notice = BuildModeHint.make_notice(ed.m, func() -> void: ed.set_mode(Main.Mode.BUILD), MESSAGE)
add_child(notice)
list = PaletteList.new()
list.setup("Search fields", "Drag onto the sheet, or click to add", "Add a field", "“number”, “text” or “title”")
list.size_flags_vertical = SIZE_EXPAND_FILL
list.sections_for = _sections
list.can_use = ed.building
list.on_blocked = func() -> void: ed.m.toast(MESSAGE)
list.drop_at = drop_at
add_child(list)
list.rebuild()
func _process(_delta: float) -> void:
notice.visible = ed.doc != null and not ed.building()
func _sections(query: String) -> Array:
var out: Array = []
for group in SheetKinds.groups():
var entries: Array = []
for item: Dictionary in SheetKinds.ITEMS:
if item["group"] == group and PaletteList.matches(item, query):
entries.append([item, _add.bind(str(item["id"]))])
out.append([group, entries])
return out
func drop_at(on_add: Callable, screen_point: Vector2) -> bool:
var at := ed.canvas.drop_point(screen_point)
if at == Vector2.INF:
return false
list.use(on_add, at)
return true
func _add(at: Vector2, kind: String) -> void:
if ed.phone:
ed.phone.palette_open = false
ed.add_box(kind, at)

1
ui/field_palette.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ckih504bs1mr4

View file

@ -51,14 +51,19 @@ static func _add_to(field: Control) -> void:
menu.set_meta("format_menu", true)
menu.add_separator("Format")
_add_items(menu, STYLES, FIRST_ID, field)
var colours: Array = []
for preset: Array in ColorChoice.PRESETS:
colours.append([preset[0], "[color=%s]" % preset[1], "[/color]"])
_submenu(menu, "Colour", colours, FIRST_ID + 100, field)
_submenu(menu, "Colour", colours(), FIRST_ID + 100, field)
_submenu(menu, "Size", SIZES, FIRST_ID + 200, field)
_submenu(menu, "Effect", EFFECTS, FIRST_ID + 300, field)
## The colour presets as [label, open tag, close tag], like STYLES.
static func colours() -> Array:
var out: Array = []
for preset: Array in ColorChoice.PRESETS:
out.append([preset[0], "[color=%s]" % preset[1], "[/color]"])
return out
static func _submenu(menu: PopupMenu, label: String, items: Array, first_id: int, field: Control) -> void:
var sub := PopupMenu.new()
ModalCard.style_popup(sub)
@ -88,16 +93,21 @@ static func wrap_selection(field: Control, open: String, close_tag: String) -> v
line.text_changed.emit(line.text)
elif field is TextEdit:
var edit := field as TextEdit
var sel := Vector2i(_offset(edit, edit.get_caret_line(), edit.get_caret_column()), 0)
sel.y = sel.x
if edit.has_selection():
sel = Vector2i(_offset(edit, edit.get_selection_from_line(), edit.get_selection_from_column()),
_offset(edit, edit.get_selection_to_line(), edit.get_selection_to_column()))
var result := TableSettingsRules.wrap_text(edit.text, sel, open, close_tag)
var result := TableSettingsRules.wrap_text(edit.text, selection(edit), open, close_tag)
edit.text = str(result["text"])
edit.text_changed.emit()
## A TextEdit's selection as character offsets (from, to); both are the caret
## when nothing is selected.
static func selection(edit: TextEdit) -> Vector2i:
if edit.has_selection():
return Vector2i(_offset(edit, edit.get_selection_from_line(), edit.get_selection_from_column()),
_offset(edit, edit.get_selection_to_line(), edit.get_selection_to_column()))
var caret := _offset(edit, edit.get_caret_line(), edit.get_caret_column())
return Vector2i(caret, caret)
## The character offset of a line and column in a TextEdit.
static func _offset(edit: TextEdit, line: int, column: int) -> int:
var offset := 0

View file

@ -341,7 +341,31 @@ static func add_member(insp: Inspector, t: RollTable) -> String:
# ---------- Sheet ----------
## A Sheet card showing a sheet file: open it, and the prefix tables use.
static func _linked_sheet(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var links := insp.main.sheet_links
var doc := links.load_doc(t.sheet_id)
box.add_child(InspectorKit.note("Shows the sheet “%s”. Its boxes with Use in tables on are values tables can read and change." % (doc.name if doc else t.sheet_id), Style.MUTED, 13))
var open := ModalCard.make_button("Open sheet", "primary")
open.pressed.connect(links.open.bind(t.id))
box.add_child(open)
var prefix := LineEdit.new()
prefix.name = "SheetPrefix"
prefix.text = t.sheet_prefix
prefix.placeholder_text = "blank = plain @name"
ModalCard.style_line_edit(prefix)
prefix.text_submitted.connect(func(text: String) -> void: links.set_prefix(t.id, text))
prefix.focus_exited.connect(func() -> void:
if prefix.text != t.sheet_prefix:
links.set_prefix(t.id, prefix.text))
box.add_child(InspectorKit.field("Prefix for tables", prefix))
box.add_child(InspectorKit.note("With a prefix like brin, tables use @brin_str: two characters on one spread. A roll that reaches this card shows the sheet in the tray.", Style.MUTED, 12))
static func _sheet(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
if t.sheet_id != "":
_linked_sheet(insp, box, t)
return
var tpl := InspectorKit.text_box(t.entries[0].text if not t.entries.is_empty() else "", "[b]{@name}[/b]\nStrength {@str}", 120.0)
InspectorKit.code(tpl)
InspectorKit.tag(tpl, "card.template")

View file

@ -60,7 +60,7 @@ static func _options(insp: Inspector, card: RollTable, plain: bool, err: Label)
else:
var first := _first_source(main.data)
if first == "":
InspectorKit.show_error(err, "Add a ledger (+ Card ▾ → Ledger) or a list value first, then pick it here.")
InspectorKit.show_error(err, "Add a ledger (Cards tab → Values → Ledger) or a list value first, then pick it here.")
return
InspectorKit.show_error(err, set_options(insp, first, ""))
)

View file

@ -1,6 +1,6 @@
class_name IoMenu
extends MenuButton
## The Build-mode "Board ▾" menu (test, reset, arrange, import, export) plus the import and
## The Build-mode "Spread ▾" menu (test, reset, arrange, import, export) plus the import and
## export logic as static functions, so it can be tested without a window.
const ID_RESET := 1

108
ui/left_dock.gd Normal file
View file

@ -0,0 +1,108 @@
class_name LeftDock
extends PanelContainer
## The left-hand dock with two tabs, "Cards | List" (the same tab style as the
## right dock's "Inspector | Lore Index", SideTabs.tab_row). Cards is the card
## palette (CardPalette); List is List view (ListView). On phones the dock
## fills the screen and swaps with the spread (MobileLayout).
## The local setting `left_dock` keeps the open tab ("" = closed).
const WIDTH := 320.0
const MIN_WIDTH := 220.0
const SETTING := "left_dock"
const CARDS := "cards"
const LIST := "list"
var m: Main
var splitter: PanelSplitter
var palette: CardPalette
var list: ListView
var close_button: Button
var tab := CARDS
var _tabs: HBoxContainer
func setup(p_main: Main) -> void:
m = p_main
add_theme_stylebox_override("panel", Style.panel_box([10, 10, 10, 10]))
var col := VBoxContainer.new()
col.add_theme_constant_override("separation", 8)
add_child(col)
var head := HBoxContainer.new()
head.add_theme_constant_override("separation", 6)
col.add_child(head)
_tabs = SideTabs.tab_row([[CARDS, "Cards"], [LIST, "List"]], tab, show_tab)
_tabs.size_flags_horizontal = SIZE_EXPAND_FILL
head.add_child(_tabs)
close_button = Style.bar_button("×")
close_button.tooltip_text = "Close this panel (View ▾ opens it again)"
close_button.pressed.connect(hide_dock)
head.add_child(close_button)
palette = CardPalette.new()
palette.setup(m)
palette.size_flags_vertical = SIZE_EXPAND_FILL
col.add_child(palette)
list = ListView.new()
list.setup(m)
list.size_flags_vertical = SIZE_EXPAND_FILL
col.add_child(list)
func set_width(px: float) -> void:
custom_minimum_size.x = px
## The tab open when the app starts. First run: Cards, so new players see where
## cards come from. Older settings that only kept "List view on" open List.
func restore() -> void:
var saved: Variant = m.state.get_setting(SETTING, null) if m.state else null
if saved == null:
var old_list := m.state != null and bool(m.state.get_setting(ListView.SETTING, false))
saved = LIST if old_list else CARDS
if str(saved) == "":
_show(false, tab)
else:
_show(true, LIST if str(saved) == LIST else CARDS)
## True when the dock is open on `which`.
func showing(which: String) -> bool:
return visible and tab == which
func show_tab(which: String) -> void:
_show(true, which)
_remember()
func hide_dock() -> void:
_show(false, tab)
_remember()
## Opens `which`, or closes the dock when it is already showing.
func toggle_tab(which: String) -> void:
if showing(which):
hide_dock()
else:
show_tab(which)
func _show(on: bool, which: String) -> void:
tab = which
visible = on
if splitter:
splitter.visible = on and not (m.mobile != null)
palette.visible = which == CARDS
list.visible = which == LIST
SideTabs.press(_tabs, which)
list._rev = -1
if on and which == CARDS:
palette.refresh_templates()
if m.top_bar.palette_button:
m.top_bar.palette_button.set_pressed_no_signal(showing(CARDS))
func _remember() -> void:
if m.state and m.mobile == null:
m.state.set_setting(SETTING, tab if visible else "")
m.state.save()

1
ui/left_dock.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cl2g0ahh2j70a

View file

@ -1,90 +1,79 @@
class_name ListView
extends PanelContainer
## List view: the spread's cards as a plain list, docked on the left (or
## filling the window on phones). Groups show as nested rows; rows roll, select
## (Build) and show where their threads go. It has its own search and
## "+ Group". Shown from View ▾, ☰ or right-clicking the spread.
extends VBoxContainer
## List view: the spread's cards as a plain list, the List tab of the left dock
## (LeftDock; it fills the window on phones). Groups show as nested rows; rows
## roll, select (Build) and show where their threads go. It has its own search
## and "+ Group". Shown from View ▾, ☰ or right-clicking the spread.
const WIDTH := 320.0
const MIN_WIDTH := 220.0
## The old "List view on" setting; LeftDock.restore reads it once.
const SETTING := "list_view"
var m: Main
var tree: ListTree
var splitter: PanelSplitter
var _search: LineEdit
var close_button: Button
var _rev := -1
func setup(p_main: Main) -> void:
m = p_main
add_theme_stylebox_override("panel", Style.panel_box([10, 10, 10, 10]))
var col := VBoxContainer.new()
col.add_theme_constant_override("separation", 8)
add_child(col)
add_theme_constant_override("separation", 8)
var head := HBoxContainer.new()
head.add_theme_constant_override("separation", 6)
col.add_child(head)
var title := Style.make_label("List", Style.display(), 20, Style.ON_BG)
title.size_flags_horizontal = SIZE_EXPAND_FILL
head.add_child(title)
var group := Style.bar_button("+ Group")
group.tooltip_text = "A new, empty group on the spread. Drag cards onto it."
group.pressed.connect(new_group)
head.add_child(group)
close_button = Style.bar_button("×")
var close := close_button
close.tooltip_text = "Close the list"
close.pressed.connect(func() -> void: set_shown(false))
head.add_child(close)
add_child(head)
_search = LineEdit.new()
_search.placeholder_text = "Search the list"
_search.clear_button_enabled = true
_search.size_flags_horizontal = SIZE_EXPAND_FILL
ModalCard.style_line_edit(_search)
_search.text_changed.connect(func(s: String) -> void:
tree.filter = s.strip_edges().to_lower()
tree.rebuild())
col.add_child(_search)
head.add_child(_search)
var group := Style.bar_button("+ Group")
group.tooltip_text = "A new, empty group on the spread. Drag cards onto it."
group.pressed.connect(new_group)
head.add_child(group)
tree = ListTree.new(m)
tree.size_flags_vertical = SIZE_EXPAND_FILL
col.add_child(tree)
add_child(tree)
var hint := Style.make_label("Drag to reorder or into a group. Double-click shows the card on the spread.", Style.body(), 12, Style.ON_BG_MUTED)
hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
col.add_child(hint)
add_child(hint)
func _process(_delta: float) -> void:
if visible and m.data and m.edit_rev != _rev:
if is_visible_in_tree() and m.data and m.edit_rev != _rev:
_rev = m.edit_rev
tree.rebuild()
func set_width(px: float) -> void:
custom_minimum_size.x = px
## Shows or hides the list and remembers it.
## Shows or hides the list (the left dock's List tab).
func set_shown(on: bool) -> void:
visible = on
if splitter:
splitter.visible = on
_rev = -1
if m.state:
m.state.set_setting(SETTING, on)
m.state.save()
if on:
m.left_dock.show_tab(LeftDock.LIST)
elif m.left_dock.showing(LeftDock.LIST):
m.left_dock.hide_dock()
func toggle() -> void:
set_shown(not visible)
m.left_dock.toggle_tab(LeftDock.LIST)
## A new, empty group in the middle of the view.
func new_group() -> void:
## True when the list is on screen.
func shown() -> bool:
return m.left_dock.showing(LeftDock.LIST)
## A new, empty group in the middle of the view, or with its top-left corner
## at `at` (world coordinates).
func new_group(at: Vector2 = Vector2.INF) -> void:
m.undo_redo._begin_edit()
var g := m.data.add_group(m.grouping._free_group_name(), [])
var c := m.board.screen_to_world(m.board.size / 2.0)
g.position = (c - g.size / 2.0).round()
if at == Vector2.INF:
var c := m.board.screen_to_world(m.board.size / 2.0)
g.position = (c - g.size / 2.0).round()
else:
g.position = at
m.grouping._groups_changed()
m.mark_dirty()
m.undo_redo._end_edit()

39
ui/lore_entry_actions.gd Normal file
View file

@ -0,0 +1,39 @@
class_name LoreEntryActions
extends RefCounted
## The buttons under a Lore Entry in the page editor: copy it to the other
## Lore Index level (This spread ↔ My library), and its item sheet: "Make a
## sheet for this entry" (SheetItems.make_sheet) or "Open its sheet".
static func make(lore: LoreList, page: BookPage) -> Control:
var row := HFlowContainer.new()
row.add_theme_constant_override("h_separation", 6)
row.add_theme_constant_override("v_separation", 6)
var other_key := LoreLevel.LIBRARY if lore.level.key == LoreLevel.SPREAD else LoreLevel.SPREAD
var other: LoreLevel = lore.levels[other_key]
var copy := Style.bar_button("Copy to %s" % other.title())
copy.name = "CopyToLevel"
copy.tooltip_text = "My library is shared by every spread and sheet" if other_key == LoreLevel.LIBRARY else "Add a copy to this spread's Lore Index"
copy.pressed.connect(func() -> void: copy_to(lore, page, other))
row.add_child(copy)
var sheet := Style.bar_button("Open its sheet" if page.sheet != "" else "Make a sheet for this entry")
sheet.name = "ItemSheet"
sheet.tooltip_text = "Its item sheet, e.g. Damage, Charges and Notes. Drag the entry into a character's inventory to take it along."
sheet.pressed.connect(func() -> void: open_or_make_sheet(lore, page))
row.add_child(sheet)
return row
static func copy_to(lore: LoreList, page: BookPage, other: LoreLevel) -> BookPage:
var added := other.add_copy(page)
lore.m.toast("Copied “%s” to %s" % [page.label(), other.title()])
return added
## Opens the entry's item sheet, making one first when it has none.
static func open_or_make_sheet(lore: LoreList, page: BookPage) -> void:
if page.sheet == "" or lore.m.screens.sheets.store.load_sheet(page.sheet) == null:
lore.level.edit(func() -> void: SheetItems.make_sheet(lore.m.screens.sheets.store, page))
lore.refresh()
if lore.open_sheet.is_valid():
lore.open_sheet.call(page.sheet)

View file

@ -0,0 +1 @@
uid://c3q4uuqo4thag

91
ui/lore_level.gd Normal file
View file

@ -0,0 +1,91 @@
class_name LoreLevel
extends RefCounted
## One level of the Lore Index, as the Lore Index panels (LoreList,
## PageEditor) see it: "This spread" (SpreadLoreLevel) or the shared
## "My library" (LibraryLoreLevel). The panels call these and never touch
## the spread or the library file themselves.
const SPREAD := "spread"
const LIBRARY := "library"
var m: Main
## SPREAD or LIBRARY.
var key := SPREAD
func _init(p_main: Main) -> void:
m = p_main
## The level's name on its tab and in buttons.
func title() -> String:
return "This spread"
func pages() -> Array[BookPage]:
return []
func get_page(_id: String) -> BookPage:
return null
## Runs `change` as one step (one undo step for the spread) and keeps it.
func edit(change: Callable) -> void:
change.call()
## After the page editor changed `page`: keep it and update what shows it.
func changed(_page: BookPage) -> void:
pass
## A new entry in this level, as one step.
func add_page(text: String, details: String = "") -> BookPage:
# Lambdas copy local variables, so the result comes back in an Array.
var made: Array[BookPage] = []
edit(func() -> void: made.append(_add_raw(text, details)))
return made[0]
## Adds an entry without making a step (add_page and add_copy wrap it).
func _add_raw(_text: String, _details: String) -> BookPage:
return null
func remove_page(_id: String) -> void:
pass
## Goes up when the entries change, so an open list knows to refresh.
func revision() -> int:
return 0
## The line under the editor: where the entry is used.
func uses_note(_page: BookPage) -> String:
return ""
## What a sheet link to `page` holds after "lore:" (SheetLoreLinks).
func ref(page: BookPage) -> String:
return page.id
## Adds a copy of `page` (from another level) here and returns it. Its item
## sheet is copied too, so the two don't share one. Pictures belong to a
## spread, so only a copy into the spread keeps one.
func add_copy(page: BookPage) -> BookPage:
var made: Array[BookPage] = []
edit(func() -> void: made.append(copy_raw(page)))
return made[0]
## add_copy without making a step, for a caller that already has one open.
func copy_raw(page: BookPage) -> BookPage:
var added := _add_raw(page.text, page.details)
added.name = page.name
added.tags = page.tags.duplicate()
added.image = page.image if key == SPREAD else ""
added.sheet = SheetItems.copy_sheet(m.screens.sheets.store, page.sheet)
return added

1
ui/lore_level.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ct5ild7jamk7t

54
ui/lore_level_library.gd Normal file
View file

@ -0,0 +1,54 @@
class_name LibraryLoreLevel
extends LoreLevel
## "My library": the shared Lore Entries (LoreLibrary), the same in every
## spread and sheet. Saved at once; there is no undo for it.
func _init(p_main: Main) -> void:
super(p_main)
key = LIBRARY
func title() -> String:
return "My library"
func library() -> LoreLibrary:
return SheetLoreLinks.library(m)
func pages() -> Array[BookPage]:
return library().pages if library() else ([] as Array[BookPage])
func get_page(id: String) -> BookPage:
return library().get_page(id) if library() else null
func edit(change: Callable) -> void:
change.call()
library().save()
func changed(_page: BookPage) -> void:
library().save()
func _add_raw(text: String, details: String) -> BookPage:
return library().add_page(text, details)
func remove_page(id: String) -> void:
library().remove_page(id)
func revision() -> int:
return library().revision if library() else 0
func uses_note(_page: BookPage) -> String:
return "In My library: every spread and sheet can use it. Drag it onto a result to copy it into this spread."
func ref(page: BookPage) -> String:
return SheetLoreLinks.LIBRARY + page.id

View file

@ -0,0 +1 @@
uid://oep0hvvp2j83

48
ui/lore_level_spread.gd Normal file
View file

@ -0,0 +1,48 @@
class_name SpreadLoreLevel
extends LoreLevel
## "This spread": the open spread's Lore Entries (TowerBoard.book). Changes
## go through the spread's undo, and linked results follow (TowerBoard.sync_page).
func _init(p_main: Main) -> void:
super(p_main)
key = SPREAD
func pages() -> Array[BookPage]:
return m.data.book if m.data else ([] as Array[BookPage])
func get_page(id: String) -> BookPage:
return m.data.get_page(id) if m.data else null
func edit(change: Callable) -> void:
m.undo_redo._begin_edit()
change.call()
m.mark_dirty()
m.undo_redo._end_edit()
func changed(page: BookPage) -> void:
for table_id in m.data.sync_page(page.id):
m.inspector_edited(table_id)
m.mark_dirty()
func _add_raw(text: String, details: String) -> BookPage:
return m.data.add_page(text, details)
func remove_page(id: String) -> void:
edit(func() -> void: m.data.remove_page(id))
func revision() -> int:
return m.edit_rev
func uses_note(page: BookPage) -> String:
var n := m.data.page_uses(page.id)
return "Used by %d %s. Drag the Lore Entry from the list onto a result to use it there." % [n, "result" if n == 1 else "results"]

View file

@ -0,0 +1 @@
uid://bifofg6rfhmum

63
ui/lore_link_picker.gd Normal file
View file

@ -0,0 +1,63 @@
class_name LoreLinkPicker
extends ModalCard
## "Link a Lore Entry": a search box over the Lore Entries a sheet can link to
## (SheetLoreLinks.entries), each with the start of its text. Clicking one
## calls on_pick(page) and closes; Enter picks the first one shown.
var main: Main
var search: LineEdit
var _on_pick: Callable
var _list: VBoxContainer
var _first: BookPage
func _init(p_main: Main, on_pick: Callable) -> void:
super("Link a Lore Entry", 460.0)
main = p_main
_on_pick = on_pick
search = LineEdit.new()
search.name = "Search"
search.placeholder_text = "Search Lore Entries and tags"
search.clear_button_enabled = true
search.text_changed.connect(func(_text: String) -> void: fill())
search.text_submitted.connect(func(_text: String) -> void:
if _first:
choose(_first))
body.add_child(search)
_list = VBoxContainer.new()
_list.name = "Entries"
_list.add_theme_constant_override("separation", 4)
body.add_child(_list)
body.add_child(ModalCard.note("From this spread's Lore Index. The selected words become the link; with none, the entry's name is added."))
add_button("Cancel", "plain", close)
fill()
func _ready() -> void:
super()
search.grab_focus()
## Lists the entries matching the search.
func fill() -> void:
for child in _list.get_children():
_list.remove_child(child)
child.queue_free()
var found := SheetLoreLinks.search(main, search.text)
_first = found[0] if not found.is_empty() else null
if found.is_empty():
var empty := "No Lore Entries yet. Add some in the spread's Lore Index." if SheetLoreLinks.entries(main).is_empty() else "Nothing matches “%s”." % search.text.strip_edges()
_list.add_child(ModalCard.note(empty))
for page in found:
var button := ModalCard.make_button(page.label(), "plain")
button.name = page.id.validate_node_name()
button.alignment = HORIZONTAL_ALIGNMENT_LEFT
button.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
button.tooltip_text = SheetLoreLinks.excerpt(page)
button.pressed.connect(choose.bind(page))
_list.add_child(button)
func choose(page: BookPage) -> void:
_on_pick.call(page)
close()

View file

@ -0,0 +1 @@
uid://d0injuj4i7wnx

156
ui/lore_list.gd Normal file
View file

@ -0,0 +1,156 @@
class_name LoreList
extends VBoxContainer
## The Lore Index's shared part: the title with "+ Lore Entry" and ×, the
## "This spread | My library" switch (LoreLevel), a search box (name, text
## and tags), the list and the page editor (PageEditor). The spread's dock
## (BookPanel) and the sheet editor's (SheetLoreDock) both show one.
## Dragging an entry that nothing takes ends in `dropped`: the host places it
## (on a spread card, or into a sheet box).
## A drag from the list ended where no control took it.
signal dropped(page: BookPage, level: LoreLevel, at: Vector2)
var m: Main
var level: LoreLevel
var levels := {}
var title: Label
var level_tabs: HBoxContainer
var search: LineEdit
var list: ItemList
var editor: PageEditor
## Opens an entry's item sheet (sheet id); set by the host.
var open_sheet: Callable
var _ids: Array[String] = []
var _rev := -1
var _dragging := ""
## `on_close` runs when × is pressed.
func setup(p_main: Main, on_close: Callable) -> void:
m = p_main
levels = {LoreLevel.SPREAD: SpreadLoreLevel.new(m), LoreLevel.LIBRARY: LibraryLoreLevel.new(m)}
level = levels[LoreLevel.SPREAD]
add_theme_constant_override("separation", 8)
var head := HBoxContainer.new()
head.add_theme_constant_override("separation", 6)
add_child(head)
title = Style.make_label("Lore Index", Style.display(), 20, Style.ON_BG)
title.size_flags_horizontal = SIZE_EXPAND_FILL
head.add_child(title)
var add := Style.bar_button("+ Lore Entry")
add.name = "NewEntry"
add.tooltip_text = "A new Lore Entry: a result you can reuse on any table"
add.pressed.connect(new_page)
head.add_child(add)
var close := Style.bar_button("×")
close.tooltip_text = "Close the Lore Index"
close.pressed.connect(on_close)
head.add_child(close)
level_tabs = SideTabs.tab_row([[LoreLevel.SPREAD, "This spread"], [LoreLevel.LIBRARY, "My library"]], level.key, set_level)
level_tabs.name = "LoreLevels"
level_tabs.tooltip_text = "This spread's Lore Entries, or My library: shared by every spread and sheet"
add_child(level_tabs)
search = LineEdit.new()
search.placeholder_text = "Search Lore Entries and tags"
search.clear_button_enabled = true
ModalCard.style_line_edit(search)
search.text_changed.connect(func(_s: String) -> void: refresh())
add_child(search)
list = ItemList.new()
list.custom_minimum_size = Vector2(0, 170)
list.add_theme_stylebox_override("panel", Style.box(Style.CARD, 6, [6, 6, 6, 6]))
list.add_theme_color_override("font_color", Style.INK)
list.add_theme_color_override("font_selected_color", Style.INK)
list.add_theme_stylebox_override("selected", Style.box(Style.LIT, 4))
list.add_theme_stylebox_override("selected_focus", Style.box(Style.LIT, 4))
list.item_selected.connect(func(i: int) -> void: editor.show_page(level.get_page(_ids[i])))
list.set_drag_forwarding(_drag, Callable(), Callable())
add_child(list)
var scroll := ScrollContainer.new()
scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
scroll.size_flags_vertical = SIZE_EXPAND_FILL
add_child(scroll)
editor = PageEditor.new(self)
editor.size_flags_horizontal = SIZE_EXPAND_FILL
scroll.add_child(editor)
editor.show_page(null)
func _process(_delta: float) -> void:
if is_visible_in_tree() and m.data and level.revision() != _rev:
_rev = level.revision()
refresh()
## Shows level `key` (LoreLevel.SPREAD or LIBRARY).
func set_level(key: String) -> void:
level = levels[key]
SideTabs.press(level_tabs, key)
editor.show_page(null)
refresh()
## Refills the list (search applied), keeping the selection.
func refresh() -> void:
_rev = level.revision()
var keep := editor.page.id if editor.page else ""
var query := search.text.strip_edges().to_lower()
list.clear()
_ids.clear()
for page in level.pages():
var hay := (page.label() + " " + Formatter.strip_tags(page.text) + " " + " ".join(page.tags)).to_lower()
if query != "" and not hay.contains(query):
continue
var i := list.add_item(page.label() + (" ▤" if page.sheet != "" else ""))
list.set_item_tooltip(i, ("Tags: " + ", ".join(page.tags) + "\n" if not page.tags.is_empty() else "") + ("Has an item sheet\n" if page.sheet != "" else "") + "Drag onto a result or a sheet box to use it")
_ids.append(page.id)
if page.id == keep:
list.select(i)
if keep != "" and level.get_page(keep) == null:
editor.show_page(null)
## After undo or redo: the entry in the editor is shown again from the
## restored spread, so its fields show the undone text at once.
func reload_page() -> void:
if editor.page == null:
return
editor.show_page(level.get_page(editor.page.id))
refresh()
func new_page() -> BookPage:
var page := level.add_page("New Lore Entry")
refresh()
select_page(page.id)
return page
func select_page(id: String) -> void:
var i := _ids.find(id)
if i >= 0:
list.select(i)
editor.show_page(level.get_page(id))
func _drag(at: Vector2) -> Variant:
var i := list.get_item_at_position(at, true)
if i < 0:
return null
_dragging = _ids[i]
var label := Style.make_label(list.get_item_text(i), Style.body_bold(), 15, Style.INK)
var chip := PanelContainer.new()
chip.add_theme_stylebox_override("panel", Style.box(Style.LIT, 6, [8, 4, 8, 4]))
chip.add_child(label)
list.set_drag_preview(chip)
return {"book_page": _dragging, "lore_level": level.key}
## Nothing took the drop (cards' and boxes' fields don't), so the host places it.
func _notification(what: int) -> void:
if what == NOTIFICATION_DRAG_END and _dragging != "":
var id := _dragging
_dragging = ""
var page := level.get_page(id)
if page and not get_viewport().gui_is_drag_successful():
dropped.emit(page, level, get_global_mouse_position())

1
ui/lore_list.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bmwxcnge60bo6

View file

@ -46,6 +46,12 @@ var selection: Dictionary = {}
var selecting: MainSelection
## The List view panel (left dock).
var list_view: ListView
## The left dock: Cards (the card palette) | List (list_view).
var left_dock: LeftDock
## Main menu, spread or Sheets (MainScreens).
var screens: MainScreens
## Sheets placed on the spread and their @variables (MainSheetLinks).
var sheet_links: MainSheetLinks
## The phone layout, when it is on (MobileLayout.wanted).
var mobile: MobileLayout
## The Book panel (reusable results).
@ -92,6 +98,7 @@ var card_refresh: CardRefreshQueue
func _init() -> void:
layout = MainLayout.new(self)
sheet_links = MainSheetLinks.new(self)
card_refresh = CardRefreshQueue.new(self)
top_bar = MainTopBar.new(self)
editing = MainEditing.new(self)
@ -146,14 +153,19 @@ func _ready() -> void:
await get_tree().process_frame
await get_tree().process_frame
board.fit()
screens.start(args)
cli._run_cli(args)
WelcomeDialog.maybe_show(self)
if screens.showing(MainScreens.SPREAD):
WelcomeDialog.maybe_show(self)
func _exit_tree() -> void:
# A roll still animating must not go on after this scene is freed (a theme
# change mid-roll reloads it).
rolling._token += 1
_save_now()
if screens:
screens.sheets.leave()
Roller.sheet_text = Callable()
# ---------- Cards ----------
@ -171,6 +183,7 @@ func is_entry_lit(tid: String, eid: String) -> bool:
func refresh_live() -> void:
for card in cards.values():
(card as TableCard).refresh_live()
sheet_links.refresh_previews()
func _add_modal(d: ModalCard) -> void:
add_child(d)

View file

@ -8,12 +8,15 @@ var m: Main
var _build: MainCliBuild
## The --perf timings (MainCliPerf).
var _perf: MainCliPerf
## The sheet and Lore flags (MainCliSheets).
var _sheets: MainCliSheets
func _init(p_main: Main) -> void:
m = p_main
_build = MainCliBuild.new(p_main)
_perf = MainCliPerf.new(p_main)
_sheets = MainCliSheets.new(p_main)
# ---------- Command line (used for screenshots and checks) ----------
@ -116,8 +119,7 @@ func _run_shell_cli(args: PackedStringArray) -> void:
if menu == "add":
# The Build tools were only just shown; let them lay out first.
await m.get_tree().process_frame
await m.get_tree().process_frame
m.editing._add_menu.show_popup()
m.left_dock.show_tab(LeftDock.CARDS)
# ----- Logic-card screenshot flags -----
@ -259,6 +261,7 @@ func _run_nav_cli(args: PackedStringArray) -> void:
m.demo.open(demo)
if args.has("--book"):
m.book.set_shown(true)
_sheets.run(args)
if args.has("--list"):
m.list_view.set_shown(true)
if args.has("--pack"):
@ -303,3 +306,4 @@ func _run_undo_cli(args: PackedStringArray) -> void:
ev.global_position = ev.position
m.get_viewport().push_input(ev)
await m.get_tree().process_frame

85
ui/main_cli_sheets.gd Normal file
View file

@ -0,0 +1,85 @@
class_name MainCliSheets
extends RefCounted
## The sheet command-line flags, for screenshots and checks (see
## docs/DESIGN.md §5). MainCli uses it; only automation needs this file.
# --sheet-demo the example sheet in the Sheets screen
# [--sheet-build] [--sheet-tab=N] [--sheet-select=TITLE] [--sheet-lore]
# [--sheet-edit=TITLE] [--sheet-lore-index] (the Lore Index beside the sheet)
# --sheet-node the example sheet placed on the spread
# --new-sheet the New sheet dialog, with a template
var m: Main
func _init(p_main: Main) -> void:
m = p_main
func run(args: PackedStringArray) -> void:
if args.has("--sheet-demo"):
# The example sheet in the Sheets screen; --sheet-build opens it in Build.
m.screens.show(MainScreens.SHEETS)
var sheet := SheetDemo.create()
m.screens.sheets.store.save(sheet)
m.screens.sheets.open_doc(sheet)
if args.has("--sheet-build"):
m.screens.sheets.editor.set_mode(Main.Mode.BUILD)
var sheet_tab := MainCli._arg_value(args, "--sheet-tab")
if sheet_tab != "":
m.screens.sheets.editor.show_tab(str(sheet.tabs[clampi(sheet_tab.to_int(), 0, sheet.tabs.size() - 1)]["id"]))
var select := MainCli._arg_value(args, "--sheet-select")
for tab in sheet.tabs:
for b: SheetBox in tab["boxes"]:
if select != "" and b.title == select:
m.screens.sheets.editor.select(b.id) if args.has("--sheet-build") else m.screens.sheets.editor.show_details(b.id, 0)
if args.has("--sheet-lore"):
# A Lore Entry linked from the Oath box, open in the side panel.
var page := m.data.add_page("Abbey of Vel", "A ruined abbey on the moor. The monks left in a hurry; the bell still rings at night.")
var oath := box_titled(m.screens.sheets.editor.doc, "Oath")
oath.value = str(oath.value).replace("the abbey", "the [url=lore:%s]abbey[/url]" % page.id)
m.screens.sheets.editor.refresh()
m.screens.sheets.editor.details.open_lore(page.id)
if args.has("--sheet-lore-index"):
show_lore_items(m.screens.sheets.editor)
var edit_title := MainCli._arg_value(args, "--sheet-edit")
if edit_title != "":
# Opens that text box for editing, with its toolbar.
var view: SheetBoxView = m.screens.sheets.editor.canvas.views.get(box_titled(m.screens.sheets.editor.doc, edit_title).id)
var click := InputEventMouseButton.new()
click.button_index = MOUSE_BUTTON_LEFT
click.pressed = true
(view.find_child("Shown", true, false) as Control).gui_input.emit(click)
if args.has("--sheet-node"):
# The example sheet placed on the spread, as a Sheet card.
var placed := SheetDemo.create()
m.screens.sheets.store.save(placed)
m.sheet_links.add_card(placed.id, m.board.screen_to_world(m.board.size * Vector2(0.62, 0.3)))
if args.has("--new-sheet"):
m.screens.show(MainScreens.SHEETS)
m.screens.sheets.store.save_as_template(SheetDemo.create(), "OSR Character")
m.screens.sheets.refresh()
m.screens.sheets.open_new_sheet()
## The box called `title` on any tab of `doc` (CLI flags name boxes by title).
static func box_titled(doc: SheetDoc, title: String) -> SheetBox:
for tab in doc.tabs:
for box: SheetBox in tab["boxes"]:
if box.title == title:
return box
return null
## --sheet-lore-index: the Lore Index beside the sheet on My library, with an
## entry that has an item sheet, dropped linked into the Inventory and copied into Talents.
func show_lore_items(ed: SheetEditor) -> void:
ed.set_lore_shown(true)
var lore := ed.lore_dock.lore
lore.set_level(LoreLevel.LIBRARY)
var blade := lore.level.add_page("[b]Ashen Blade[/b]", "Burns what it cuts. Three charges; a spent charge returns at dawn.")
blade.name = "Ashen Blade"
lore.level.edit(func() -> void: SheetItems.make_sheet(ed.screen.store, blade))
SheetLoreDrop.add(ed, box_titled(ed.doc, "Inventory"), blade, lore.level.ref(blade), true)
SheetLoreDrop.add(ed, box_titled(ed.doc, "Talents"), blade, lore.level.ref(blade), false)
lore.refresh()
lore.select_page(blade.id)

View file

@ -0,0 +1 @@
uid://rcuoo7x8ofv1

View file

@ -9,90 +9,32 @@ var _link_from: Dictionary = {}
## Tests only: the card a link drop lands on, instead of the one under the mouse.
var _card_under_mouse_override: TableCard = null
var _drop_card: TableCard
var _add_menu: MenuButton
var _sel_bar: PanelContainer
var _sel_label: Label
## The "+ Card ▾" kinds: [label, kind, sub, default name].
const ADD_KINDS := [
["Roll table", RollTable.KIND_ROLL, "", "New table"],
["Check card: roll against a target", RollTable.KIND_CHECK, "", "Check"],
["Choice: which option", RollTable.KIND_CHOICE, "pick", "New choice"],
["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"],
["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"],
["Repeat", RollTable.KIND_LOOP, "times", "Repeat"],
["Branch: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Branch"],
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
["Ledger (Skills, Contacts…)", RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION, "Skills"],
["Scale (ordered steps)", RollTable.KIND_VARIABLE, RollTable.VAR_SCALE, "New scale"],
["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
]
const MENU_FROM_TEMPLATE := 100
const MENU_GROUP := 101
## How close (screen pixels) a dragged thread must be to a card's input dot to drop on it.
const LINK_DROP_RADIUS := 24.0
const MENU_SAVE_SELECTION := 102
func _init(p_main: Main) -> void:
m = p_main
func _make_add_menu() -> MenuButton:
var mb := Style.menu_button("+ Card ▾", true)
mb.tooltip_text = "Add a roll table or a logic card"
var pm := mb.get_popup()
ModalCard.style_popup(pm)
for i in ADD_KINDS.size():
if i == 1:
pm.add_separator("Logic cards")
pm.add_item(str(ADD_KINDS[i][0]), i)
pm.add_separator("Groups and templates")
pm.add_item("From template…", MENU_FROM_TEMPLATE)
pm.add_item("Group the selection Ctrl+G", MENU_GROUP)
pm.add_item("Save selection as template…", MENU_SAVE_SELECTION)
pm.about_to_popup.connect(func() -> void:
pm.set_item_disabled(pm.get_item_index(MENU_GROUP), m.selection.is_empty() and m.selecting.groups.is_empty())
pm.set_item_disabled(pm.get_item_index(MENU_SAVE_SELECTION), m.selection.is_empty())
)
pm.id_pressed.connect(func(id: int) -> void:
match id:
MENU_FROM_TEMPLATE:
m.templating.open_template_picker()
MENU_GROUP:
m.grouping.group_selection()
MENU_SAVE_SELECTION:
m.templating.save_selection_as_template()
_:
var k: Array = ADD_KINDS[id]
add_table(str(k[1]), str(k[2]))
)
return mb
## Adds a card of any kind (RollTable.create) in the middle of the view, or
## with its top-left corner at `at` (world coordinates).
func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "", at: Vector2 = Vector2.INF) -> RollTable:
## with its top-left corner at `at` (world coordinates). `variant` gives it a
## CardCatalog variant's start settings ("dice", "deck").
func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "", at: Vector2 = Vector2.INF, variant: String = "", card_name: String = "") -> RollTable:
m.undo_redo._begin_edit()
var center := m.board.screen_to_world(m.board.size / 2.0) if at == Vector2.INF else at + Vector2(128, 120)
var name := "New table"
var found := false
for k: Array in ADD_KINDS:
if k[1] == kind and k[2] == sub:
name = str(k[3])
found = true
break
if not found:
for k: Array in ADD_KINDS:
if k[1] == kind and (sub == "" or kind != RollTable.KIND_CHOICE) and k[2] != RollTable.VAR_COLLECTION:
name = str(k[3])
break
var item := CardCatalog.find(kind, sub, variant.get_slice(":", 0))
var name := card_name if card_name != "" else str(item.get("name", "New table"))
var t := RollTable.create(kind, TowerBoard.new_id("t"), name, sub)
if kind == RollTable.KIND_ROLL or kind == RollTable.KIND_CHECK:
for e in t.entries:
e.id = TowerBoard.new_id("e")
if kind == RollTable.KIND_VARIABLE:
t.var_name = _free_var_name(t.var_name)
CardCatalog.apply_variant(t, variant)
t.position = Vector2(roundf(center.x - 128.0), roundf(center.y - 120.0))
m.data.tables.append(t)
var card := TableCard.new()

View file

@ -51,18 +51,17 @@ func _build_ui() -> void:
middle.add_theme_constant_override("separation", 0)
middle.size_flags_vertical = Control.SIZE_EXPAND_FILL
root.add_child(middle)
m.list_view = ListView.new()
m.list_view.setup(m)
var lside := PanelSplitter.new(m, false, "list_width", ListView.WIDTH, ListView.MIN_WIDTH)
m.left_dock = LeftDock.new()
m.left_dock.setup(m)
m.list_view = m.left_dock.list
var lside := PanelSplitter.new(m, false, "list_width", LeftDock.WIDTH, LeftDock.MIN_WIDTH)
lside.before = true
lside.size_changed.connect(m.list_view.set_width)
m.list_view.splitter = lside
m.list_view.set_width(lside.size_px)
middle.add_child(m.list_view)
lside.size_changed.connect(m.left_dock.set_width)
m.left_dock.splitter = lside
m.left_dock.set_width(lside.size_px)
middle.add_child(m.left_dock)
middle.add_child(lside)
var list_on := m.state != null and bool(m.state.get_setting(ListView.SETTING, false))
m.list_view.visible = list_on
lside.visible = list_on
m.left_dock.restore()
m.board = BoardView.new()
m.board.setup(m)
m.board.size_flags_horizontal = Control.SIZE_EXPAND_FILL
@ -99,6 +98,8 @@ func _build_ui() -> void:
m.tray.set_height(foot.size_px)
root.add_child(foot)
root.add_child(m.tray)
m.screens = MainScreens.new(m)
m.screens.setup(root)
m.top_bar._build_toast()
m.undo_redo._build_edit_timer()
@ -117,6 +118,8 @@ func _build_ui() -> void:
## _apply_group_visibility. Called from outside an edit (a board loaded or
## replaced), it also takes the board as the edit history's new baseline.
func _rebuild_cards() -> void:
# Old Sheet cards get their sheet file before the edit history takes the board.
m.sheet_links.migrate()
if not m.undo_redo._keep_history:
m.undo_redo._sync_history()
for c in m.board.cards.get_children():
@ -157,7 +160,6 @@ func set_mode(new_mode: Main.Mode) -> void:
m.top_bar._hint.tooltip_text = Main.HINTS[new_mode]
m.top_bar._hint.custom_minimum_size.x = 60.0 if new_mode == Main.Mode.PLAY else 0.0
m.top_bar._build_tools.visible = new_mode == Main.Mode.BUILD
m.top_bar.play_add_button.visible = new_mode == Main.Mode.PLAY
m.board.pipes.hover_key = ""
m.clear_selection()
SideTabs.sync(m)
@ -168,12 +170,16 @@ func set_mode(new_mode: Main.Mode) -> void:
(n as GroupCard).rebuild()
m.top_bar._update_endless_chip()
m.nav._nav_mode_changed()
m.sheet_links.refresh_previews()
## What every change to the board needs: a save soon, fresh caches and redraws.
func _board_changed() -> void:
if m._saving_enabled:
m._save_timer.start()
# A Sheet card that came in from a template or an import gets its sheet.
if m.sheet_links.migrate():
m.card_refresh.rebuild_all()
m.local_state._ref_cache.clear()
m.view_rev += 1
m.edit_rev += 1
@ -258,6 +264,11 @@ func _shortcut_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed:
return
if m.screens and not m.screens.showing(MainScreens.SPREAD):
# Other screens take their own keys; the hidden spread takes none.
if m.screens.showing(MainScreens.SHEETS) and m.screens.sheets.editor.shortcut(k):
m.get_viewport().set_input_as_handled()
return
if m.undo_redo._history_shortcut(k):
m.get_viewport().set_input_as_handled()
return
@ -281,6 +292,8 @@ func _unhandled_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed or k.echo or m.mode != Main.Mode.BUILD:
return
if m.screens and not m.screens.showing(MainScreens.SPREAD):
return
if k.keycode == KEY_G and (k.ctrl_pressed or k.meta_pressed):
m.grouping.group_selection()
m.get_viewport().set_input_as_handled()

233
ui/main_menu.gd Normal file
View file

@ -0,0 +1,233 @@
class_name MainMenu
extends Control
## The main menu, laid out like the mockup (docs/SHEETS.md): on the theme's
## spread background, the app's name over Spreads (first: the app's main job),
## Sheets, then Settings and Quit side by side, titles only (the user's pick,
## 2026-11-29). Beside them Morgan and "Pick up where you left off". A footer
## names the theme.
var m: Main
var buttons: Dictionary = {} # label -> Button
var recent_rows: VBoxContainer
var row: BoxContainer
var _backdrop: BoardBackdrop
var _theme_label: Label
func setup(p_main: Main) -> void:
m = p_main
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
_backdrop = BoardBackdrop.new(ThemeStore.current)
draw.connect(func() -> void: _backdrop.draw(self, Rect2(Vector2.ZERO, size)))
resized.connect(queue_redraw)
var page := VBoxContainer.new()
page.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
page.add_theme_constant_override("separation", 0)
add_child(page)
var center := CenterContainer.new()
center.size_flags_vertical = SIZE_EXPAND_FILL
page.add_child(center)
# Side by side; a narrow window (a phone) stacks them (_fit_columns).
row = BoxContainer.new()
row.add_theme_constant_override("separation", 64)
resized.connect(_fit_columns)
center.add_child(row)
row.add_child(_left_column())
row.add_child(_right_column())
page.add_child(_footer())
func _fit_columns() -> void:
row.vertical = size.x < 920.0
func _left_column() -> VBoxContainer:
var col := VBoxContainer.new()
col.custom_minimum_size = Vector2(420, 0)
col.add_theme_constant_override("separation", 28)
var names := VBoxContainer.new()
names.add_theme_constant_override("separation", 2)
names.add_child(Style.make_label("RANDOM TABLES & SHEETS", Style.caps(), 13, Style.ON_BG_MUTED))
names.add_child(Style.make_label("Table Tarot", Style.display(), 72, Style.ACCENT))
col.add_child(names)
var nav := VBoxContainer.new()
nav.add_theme_constant_override("separation", 10)
col.add_child(nav)
nav.add_child(_big_button("Spreads", MenuIcons.SPREAD, true, func() -> void: m.screens.show(MainScreens.SPREAD)))
nav.add_child(_big_button("Sheets", MenuIcons.SHEET, false, func() -> void: m.screens.show(MainScreens.SHEETS)))
var pair := GridContainer.new()
pair.columns = 2
pair.add_theme_constant_override("h_separation", 10)
nav.add_child(pair)
pair.add_child(_small_button("Settings", MenuIcons.SETTINGS, open_settings))
pair.add_child(_small_button("Quit", MenuIcons.QUIT, quit))
return col
func _right_column() -> VBoxContainer:
var col := VBoxContainer.new()
col.custom_minimum_size = Vector2(380, 0)
col.add_theme_constant_override("separation", 20)
var mark := _mascot()
if mark:
col.add_child(mark)
var recent := VBoxContainer.new()
recent.add_theme_constant_override("separation", 8)
recent.add_child(Style.make_label("PICK UP WHERE YOU LEFT OFF", Style.caps(), 12, Style.ON_BG_MUTED))
recent_rows = VBoxContainer.new()
recent_rows.add_theme_constant_override("separation", 8)
recent.add_child(recent_rows)
col.add_child(recent)
visibility_changed.connect(func() -> void:
if visible:
refresh_recent())
return col
## Morgan (or the theme's logo) drawn large and sharp.
func _mascot() -> Control:
if Style.LOGO == "fortune_teller" or Style.LOGO == "mascot":
var tr := TextureRect.new()
tr.texture = MascotArt.texture(ThemeStore.current, 512)
tr.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
tr.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
tr.texture_filter = CanvasItem.TEXTURE_FILTER_LINEAR_WITH_MIPMAPS
tr.custom_minimum_size = Vector2(380, 280)
return tr
var mark := MainTopBar.logo()
if mark:
mark.custom_minimum_size = Vector2(380, 200)
return mark
func _footer() -> PanelContainer:
var bar := PanelContainer.new()
bar.add_theme_stylebox_override("panel", Style.box(Style.BG_DEEP, 0, [32, 12, 32, 12]))
_theme_label = Style.make_label("Theme: %s" % str(ThemeStore.current.get("name", "")), Style.body(), 13, Style.ON_BG_MUTED)
bar.add_child(_theme_label)
return bar
## A tall menu button: an icon and a big title. `primary` fills it with the accent.
func _big_button(text: String, icon: String, primary: bool, on_press: Callable) -> Button:
var b := Button.new()
b.name = text
b.custom_minimum_size = Vector2(0, 66)
b.focus_mode = Control.FOCUS_NONE
var fg := Style.INK if primary else Style.ON_BG
var margins := [64, 14, 20, 14]
var normal := Style.bordered(Style.box(Style.ACCENT if primary else Color(1, 1, 1, 0.05), 10, margins), 1, Style.ACCENT if primary else Color(1, 1, 1, 0.18))
var hover := Style.bordered(Style.box(Style.ACCENT.lightened(0.12) if primary else Color(1, 1, 1, 0.1), 10, margins), 1, Style.ACCENT if primary else Color(1, 1, 1, 0.3))
Style.skin_button(b, normal, hover, hover, fg)
b.text = text
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
b.add_theme_font_override("font", Style.display())
b.add_theme_font_size_override("font_size", 28)
var icon_box := MenuIcons.make(icon, fg, 28)
icon_box.position = Vector2(22, 19)
b.add_child(icon_box)
b.pressed.connect(on_press)
buttons[text] = b
return b
func _small_button(text: String, icon: String, on_press: Callable) -> Button:
var b := Button.new()
b.name = text
b.custom_minimum_size = Vector2(0, 52)
b.size_flags_horizontal = SIZE_EXPAND_FILL
b.focus_mode = Control.FOCUS_NONE
var margins := [50, 12, 16, 12]
var normal := Style.bordered(Style.box(Color(1, 1, 1, 0.05), 10, margins), 1, Color(1, 1, 1, 0.18))
var hover := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 10, margins), 1, Color(1, 1, 1, 0.3))
Style.skin_button(b, normal, hover, hover, Style.ON_BG)
b.text = text
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
b.add_theme_font_size_override("font_size", 18)
var icon_box := MenuIcons.make(icon, Style.ON_BG, 20)
icon_box.position = Vector2(18, 16)
b.add_child(icon_box)
b.pressed.connect(on_press)
buttons[text] = b
return b
## The open spread and your newest sheets, newest first (at most three rows).
func refresh_recent() -> void:
for c in recent_rows.get_children():
recent_rows.remove_child(c)
c.queue_free()
if m.data:
var n := m.data.tables.size()
recent_rows.add_child(_recent_row(m.data.name, "Spread · %d %s" % [n, "card" if n == 1 else "cards"], "",
func() -> void: m.screens.show(MainScreens.SPREAD)))
var sheets := m.screens.sheets
for row: Dictionary in sheets.store.list().slice(0, 2):
var id := str(row["id"])
recent_rows.add_child(_recent_row(str(row["name"]), "Sheet", _ago(int(row["modified"])), func() -> void:
m.screens.show(MainScreens.SHEETS)
sheets.open_sheet(id)))
func _recent_row(title: String, sub: String, when: String, on_press: Callable) -> Button:
var b := Button.new()
b.name = title.validate_node_name()
b.focus_mode = Control.FOCUS_NONE
b.custom_minimum_size = Vector2(0, 58)
var normal := Style.box(Style.CARD, 8, [14, 10, 14, 10])
var hover := Style.box(Style.CARD_HOVER, 8, [14, 10, 14, 10])
Style.skin_button(b, normal, hover, hover, Style.INK)
var h := HBoxContainer.new()
h.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
h.offset_left = 14
h.offset_right = -14
h.mouse_filter = Control.MOUSE_FILTER_IGNORE
b.add_child(h)
var text := VBoxContainer.new()
text.size_flags_horizontal = SIZE_EXPAND_FILL
text.alignment = BoxContainer.ALIGNMENT_CENTER
text.add_theme_constant_override("separation", 0)
text.mouse_filter = Control.MOUSE_FILTER_IGNORE
h.add_child(text)
text.add_child(Style.make_label(title, Style.body_bold(), 15, Style.INK))
text.add_child(Style.make_label(sub, Style.body(), 13, Style.MUTED))
var w := Style.make_label(when, Style.body(), 13, Style.MUTED)
w.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(w)
b.pressed.connect(on_press)
return b
static func _ago(unix: int) -> String:
var secs := int(Time.get_unix_time_from_system()) - unix
if secs < 90:
return "just now"
if secs < 3600:
return "%d min ago" % (secs / 60)
if secs < 86400:
return "%d h ago" % (secs / 3600)
return "%d d ago" % (secs / 86400)
## The app-wide settings that live outside a spread: theme and sound.
func open_settings() -> void:
var d := ModalCard.new("Settings", 420.0)
var theme_button := ModalCard.make_button("Theme…", "plain")
theme_button.pressed.connect(func() -> void:
d.close()
m.add_child(ThemeDialog.new(m)))
d.body.add_child(theme_button)
if m.sound:
var sound_button := ModalCard.make_button("Sound…", "plain")
sound_button.pressed.connect(func() -> void:
SoundPanel.open(m, sound_button.get_global_rect().get_center()))
d.body.add_child(sound_button)
d.add_button("Done", "primary", d.close)
m._add_modal(d)
func quit() -> void:
if m._save_timer and not m._save_timer.is_stopped():
m._save_now()
m.screens.sheets.leave()
m.get_tree().quit()

1
ui/main_menu.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dkpay4ypdgpse

View file

@ -67,6 +67,8 @@ func start_roll(tid: String, fast: bool = false) -> void:
for c in m.cards.values():
(c as TableCard).set_rolling(false)
(c as TableCard).clear_flick()
# Sheets on the spread lend their boxes as @variables (MainSheetLinks).
m.sheet_links.before_roll(Formatter.strip_tags(t.name))
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
ctx.prompt = _prompt_for.bind(run)
m.rolling_ctx = ctx

78
ui/main_screens.gd Normal file
View file

@ -0,0 +1,78 @@
class_name MainScreens
extends RefCounted
## Which full-window screen shows: the main menu (MainMenu), the spread
## editor (Main's own top bar, board and tray) or Sheets (SheetsScreen).
## Real use starts on the main menu; tests, --sample and screenshots start
## on the spread unless --menu or --sheets is given.
const MENU := "menu"
const SPREAD := "spread"
const SHEETS := "sheets"
var m: Main
var spread_root: Control
var menu: MainMenu
var sheets: SheetsScreen
var current := SPREAD
## Kept across a theme change (which reloads the app): the screen to come back
## to and the sheet that was open. Empty = start as usual.
static var resume := {}
func _init(p_main: Main) -> void:
m = p_main
## Called once the spread editor is built (`root` is its top-level box).
func setup(root: Control) -> void:
spread_root = root
menu = MainMenu.new()
menu.setup(m)
menu.visible = false
m.add_child(menu)
sheets = SheetsScreen.new()
sheets.setup(m)
sheets.visible = false
m.add_child(sheets)
func show(which: String) -> void:
if which == current:
return
if current == SHEETS:
sheets.leave()
current = which
spread_root.visible = which == SPREAD
menu.visible = which == MENU
sheets.visible = which == SHEETS
if which == SHEETS:
sheets.enter()
if which == SPREAD:
m.sheet_links.refresh_previews()
func showing(which: String) -> bool:
return current == which
## Where the app opens: back where it was after a theme change; otherwise the
## main menu in real use, the spread for tests and screenshots (--menu and
## --sheets pick a screen).
func start(args: PackedStringArray) -> void:
if not resume.is_empty():
var back := resume
resume = {}
show(str(back.get("screen", MENU)))
if str(back.get("sheet", "")) != "":
sheets.open_sheet(str(back["sheet"]))
return
if args.has("--sheets"):
show(SHEETS)
elif args.has("--menu") or m._saving_enabled:
show(MENU)
## Remembers the screen (and open sheet) before the app reloads for a theme.
func keep_for_reload() -> void:
sheets.leave()
resume = {"screen": current, "sheet": sheets.editor.doc.id if current == SHEETS and sheets.editor.doc else ""}

1
ui/main_screens.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b5upfp7bn4u2b

208
ui/main_sheet_links.gd Normal file
View file

@ -0,0 +1,208 @@
class_name MainSheetLinks
extends RefCounted
## Sheets on the open spread. A Sheet card shows a sheet file
## (RollTable.sheet_id) as a small picture of its first tab (SheetPreview);
## threads can lead into it like any card, and a roll that reaches it shows
## the sheet's text (SheetText via Roller.sheet_text). Old template-only
## Sheet cards are migrated: their text becomes a text box in a new sheet.
## Around each roll it runs the variable bridge (SheetLinks): linked boxes
## become @variables, changed values go back into the boxes.
var m: Main
## sheet id -> {box id: "from <table>"}: boxes the last roll wrote.
var recent: Dictionary = {}
var _given: Dictionary = {}
var _roll_label := ""
func _init(p_main: Main) -> void:
m = p_main
Roller.sheet_text = func(t: RollTable) -> String:
if not is_instance_valid(m) or not m.is_inside_tree():
return t.entries[0].text
var doc := load_doc(t.sheet_id)
return SheetText.summary(doc, t.sheet_prefix) if doc else t.entries[0].text
func store() -> SheetStore:
return m.screens.sheets.store if m.screens else null
## The sheet with `id`: the editor's copy when it is open there.
func load_doc(id: String) -> SheetDoc:
if m.screens == null or id == "":
return null
var ed := m.screens.sheets.editor
if ed.doc and ed.doc.id == id:
return ed.doc
return store().load_sheet(id)
## Old Sheet cards (a BBCode template, no sheet file) get a sheet whose one
## text box holds the template; it keeps showing spread values like {@name}.
## The file id comes from the spread and card, so doing it again (after an
## undo) links the same file. True when any card changed.
func migrate() -> bool:
if m.data == null or store() == null:
return false
# Help demos save nothing: their old Sheet cards stay as they are there
# ("Keep a copy" makes a real spread, which migrates when it opens).
if m.demo and m.demo.active():
return false
var changed := false
for t in m.data.tables:
if t.kind != RollTable.KIND_SHEET or t.sheet_id != "":
continue
var id := LibraryStore.slugify("%s-%s" % [m.data.id, t.id])
if store().load_sheet(id) == null:
var doc := SheetDoc.new(id, Formatter.strip_tags(t.name).strip_edges() if Formatter.strip_tags(t.name).strip_edges() != "" else "Sheet")
var box := SheetKinds.make_box(SheetKinds.TEXT, doc.new_box_id(), Vector2(16, 16))
box.title = ""
box.w = 24 * SheetKinds.GRID
box.h = 14 * SheetKinds.GRID
box.value = t.entries[0].text if not t.entries.is_empty() else ""
doc.tabs[0]["boxes"].append(box)
store().save(doc)
t.sheet_id = id
changed = true
return changed
## True when a Sheet card on the open spread shows sheet `id`.
func on_spread(id: String) -> bool:
return m.data != null and SheetLinks.sheet_cards(m.data).any(func(t: RollTable) -> bool: return t.sheet_id == id)
## Fills in {@name} in a sheet's text: the sheet's own boxes first, then (when
## the sheet is on the open spread) the spread's values, such as an answer a
## choice card saved.
func expand(doc: SheetDoc, text: String) -> String:
if not text.contains("{@"):
return text
var values := SheetValues.vars(doc)
if on_spread(doc.id):
for name: String in m.persistent_vars:
if not values.has(name):
var entry: Variant = m.persistent_vars[name]
values[name] = (entry as Dictionary).get("value", "") if entry is Dictionary else entry
for name: String in values:
text = text.replace("{@%s}" % name, "[b]%s[/b]" % SheetValues.show(values[name]))
return text
## Redraws the sheet pictures on the cards (after a roll or a sheet edit).
func refresh_previews() -> void:
for t in SheetLinks.sheet_cards(m.data) if m.data else []:
var card: TableCard = m.card_for(t.id)
var preview: SheetPreview = card.find_child("SheetPreview", true, false) if card else null
if preview:
preview.reload()
## Places sheet `sheet_id` on the spread as a Sheet card, top-left at `at`
## (INF = view centre). A second sheet gets a prefix from its name so their
## @names don't clash.
func add_card(sheet_id: String, at: Vector2 = Vector2.INF) -> RollTable:
var doc := load_doc(sheet_id)
if doc == null:
m.toast("Couldn't read that sheet")
return null
var prefix := ""
if not SheetLinks.sheet_cards(m.data).is_empty():
prefix = LibraryStore.slugify(doc.name.get_slice(" ", 0)).replace("-", "_")
return m.editing.add_table(RollTable.KIND_SHEET, "", at, "sheet:%s:%s" % [sheet_id, prefix], doc.name)
func set_prefix(card_id: String, prefix: String) -> void:
var t := m.data.get_table(card_id)
if t == null:
return
m.undo_redo._begin_edit()
t.sheet_prefix = LibraryStore.slugify(prefix).replace("-", "_")
m.mark_dirty()
m.undo_redo._end_edit("Sheet prefix")
m.inspector_edited(card_id)
refresh_previews()
## Opens the card's sheet in the sheet editor, in the spread's mode, with a
## way back to the spread.
func open(card_id: String) -> void:
var t := m.data.get_table(card_id)
open_sheet(t.sheet_id if t else "", "That sheet is gone. Delete the card, or link another sheet.")
## Opens sheet `id` (a card's, or a Lore Entry's item sheet) with a way back to the spread.
func open_sheet(id: String, gone: String = "That sheet is gone.") -> void:
var doc := load_doc(id)
if doc == null:
m.toast(gone)
return
m.screens.show(MainScreens.SHEETS)
m.screens.sheets.open_doc(doc)
m.screens.sheets.editor.open_from_spread(m.data.name)
## Right-click items for a linked Sheet card (Actions.card).
func menu_items(t: RollTable) -> Array:
return [
{"text": "Open sheet", "do": open.bind(t.id)},
{"text": "Prefix for tables…", "do": ask_prefix.bind(t.id), "disabled": m.mode != Main.Mode.BUILD,
"tip": "With a prefix like brin, tables use @brin_str. Blank = plain @str."},
]
func ask_prefix(card_id: String) -> void:
var t := m.data.get_table(card_id)
m._add_modal(ModalCard.ask_text("Prefix for tables", "Tables read this sheet's boxes as @prefix_name. Blank = plain @name.",
t.sheet_prefix, "Save", func(text: String) -> void: set_prefix(card_id, text), true))
# ---------- The variable bridge around a roll ----------
## Before a roll: every linked box becomes a spread variable.
func before_roll(table_name: String) -> void:
_given = {}
_roll_label = table_name
if m.data == null or m.screens == null:
return
_given = SheetLinks.inject(m.data, m.persistent_vars, load_doc)
## After a roll: values it changed go into their boxes (one undo step when
## the sheet is open in the editor); locked boxes keep theirs.
func after_roll() -> void:
if _given.is_empty():
return
var found := SheetLinks.changes(_given, m.persistent_vars)
var by_sheet := {}
for c: Dictionary in found:
if not by_sheet.has(c["sheet"]):
by_sheet[c["sheet"]] = []
(by_sheet[c["sheet"]] as Array).append(c)
var said: Array[String] = []
for sheet_id: String in by_sheet:
var doc := load_doc(sheet_id)
if doc == null:
continue
var marks := {}
var write := func() -> void:
for c: Dictionary in by_sheet[sheet_id]:
var box := doc.find_box(c["box"])
if box and SheetLinks.write(box, c["value"]):
marks[box.id] = "from %s" % _roll_label
said.append("%s: %s → %s" % [doc.name, box.title, SheetText._value(doc, box)])
else:
var g: Dictionary = _given[c["name"]]
m.persistent_vars[c["name"]] = {"value": g["value"], "source": "locked on %s" % doc.name}
var ed := m.screens.sheets.editor
if ed.doc == doc:
ed.edit("Roll: %s" % _roll_label, write)
else:
write.call()
store().save(doc)
recent[sheet_id] = marks
_given = {}
refresh_previews()
if not said.is_empty():
m.toast(" · ".join(said))

View file

@ -0,0 +1 @@
uid://ccqediupnuimv

View file

@ -54,6 +54,8 @@ func load_local_state() -> void:
## After a roll: saves the decks, any changed persistent variables and the
## history record.
func _store_roll(ctx: RollContext) -> void:
# Values the roll changed go back into the sheets on the spread first.
m.sheet_links.after_roll()
if m.state == null:
return
_store_decks()

View file

@ -54,7 +54,7 @@ func store_template(out: Dictionary) -> void:
if id == "":
m.toast("Couldn't save the template")
else:
m.toast("Saved template “%s”. Insert it from + Card ▾ → From template…" % out["name"])
m.toast("Saved template “%s”. Insert it from the Cards tab (Templates)" % out["name"])
## The selection as a template; groups whose cards are all selected come along.
@ -86,21 +86,24 @@ func open_template_picker() -> TemplatePicker:
## Asks for the template's parameters (if it has any), then inserts it.
func begin_template_insert(tpl: Dictionary) -> void:
## `at`: its top-left corner in world coordinates (INF = the view centre).
func begin_template_insert(tpl: Dictionary, at: Vector2 = Vector2.INF) -> void:
if (tpl.get("params", []) as Array).is_empty():
insert_template(tpl, {})
insert_template(tpl, {}, at)
return
m._add_modal(TemplateForms.params_dialog(tpl, func(values: Dictionary) -> void: insert_template(tpl, values)))
m._add_modal(TemplateForms.params_dialog(tpl, func(values: Dictionary) -> void: insert_template(tpl, values, at)))
## Inserts a template at the view centre: parameters substituted, fresh ids,
## outside pipes relinked by name (or dropped and reported). Returns
## TemplateKit.instantiate's result.
func insert_template(tpl: Dictionary, values: Dictionary) -> Dictionary:
## Inserts a template, centred in the view or with its top-left corner at
## `at` (world coordinates): parameters substituted, fresh ids, outside pipes
## relinked by name (or dropped and reported). Returns TemplateKit.instantiate's result.
func insert_template(tpl: Dictionary, values: Dictionary, at: Vector2 = Vector2.INF) -> Dictionary:
m.undo_redo._begin_edit()
var ext := TemplateKit.extent(tpl)
var center := m.board.screen_to_world(m.board.size / 2.0)
var origin := (center - ext / 2.0).round()
var origin := at
if at == Vector2.INF:
var ext := TemplateKit.extent(tpl)
var center := m.board.screen_to_world(m.board.size / 2.0)
origin = (center - ext / 2.0).round()
var r := TemplateKit.insert(tpl, values, m.data, origin)
for t: RollTable in r["tables"]:
if t.kind == RollTable.KIND_VARIABLE and t.var_name == "":

View file

@ -24,9 +24,9 @@ var _toast_label: Label
var _toast_undo: Button
## The toast button's own action (toast_action), or empty for Undo.
var _toast_do := Callable()
## Play mode's greyed "+ Card" (BuildModeHint).
var play_add_button: Button
var _toast_timer: Timer
## Build only: opens or closes the card palette (lit while it shows).
var palette_button: Button
## The undo step the toast's Undo button undoes (EditHistory serial), or -1.
var _toast_serial := -1
var _endless_chip: PanelContainer
@ -40,7 +40,7 @@ func _init(p_main: Main) -> void:
## The theme's logo (Style.LOGO): its mascot (Morgan Fortuna, the fortune
## teller, by default; recoloured by MascotArt), the old tower mark, or none.
func _logo() -> Control:
static func logo() -> Control:
match Style.LOGO:
"fortune_teller", "mascot":
var tr := TextureRect.new()
@ -67,15 +67,8 @@ func _build_top_bar() -> Control:
h.add_theme_constant_override("separation", 10)
bar.add_child(h)
var brand := HBoxContainer.new()
brand.add_theme_constant_override("separation", 9)
var mark := _logo()
if mark:
brand.add_child(mark)
var title := Style.make_label("Table Tarot", Style.display(), 23, Style.ON_BG)
brand_title = title
title.size_flags_vertical = Control.SIZE_SHRINK_CENTER
brand.add_child(title)
var brand := make_brand(func() -> void: m.screens.show(MainScreens.MENU))
brand_title = brand.get_child(brand.get_child_count() - 1)
h.add_child(brand)
var seg := PanelContainer.new()
@ -85,8 +78,8 @@ func _build_top_bar() -> Control:
seg_row.add_theme_constant_override("separation", 0)
seg.add_child(seg_row)
var group := ButtonGroup.new()
_play_button = _seg_button("Play", group)
_build_button = _seg_button("Build", group)
_play_button = seg_button("Play", group)
_build_button = seg_button("Build", group)
_play_button.button_pressed = true
_play_button.pressed.connect(func() -> void: m.set_mode(Main.Mode.PLAY))
_build_button.pressed.connect(func() -> void: m.set_mode(Main.Mode.BUILD))
@ -117,9 +110,13 @@ func _build_top_bar() -> Control:
var tools := HBoxContainer.new()
tools.add_theme_constant_override("separation", 6)
_build_tools = tools
palette_button = Style.bar_button("Card palette")
palette_button.toggle_mode = true
palette_button.tooltip_text = "Show or hide the card palette: every kind of card and your templates"
palette_button.focus_mode = Control.FOCUS_NONE
palette_button.pressed.connect(func() -> void: m.left_dock.toggle_tab(LeftDock.CARDS))
tools.add_child(palette_button)
m.undo_redo._make_history_buttons(tools)
m.editing._add_menu = m.editing._make_add_menu()
tools.add_child(m.editing._add_menu)
_board_menu = IoMenu.new()
_board_menu.setup(true, m.collections_enabled())
_board_menu.reset_requested.connect(m.editing.reset_sample)
@ -130,8 +127,6 @@ func _build_top_bar() -> Control:
tools.add_child(_board_menu)
tools.visible = false
h.add_child(tools)
play_add_button = BuildModeHint.make_button(m)
h.add_child(play_add_button)
_endless_chip = _make_endless_chip()
h.add_child(_endless_chip)
@ -161,7 +156,29 @@ func _build_top_bar() -> Control:
return bar
func _seg_button(text: String, group: ButtonGroup) -> Button:
## The logo and "Table Tarot" in the accent colour, at the left of every top
## bar (spread and sheet). Clicking it runs `on_click` (the main menu).
static func make_brand(on_click: Callable) -> HBoxContainer:
var brand := HBoxContainer.new()
brand.add_theme_constant_override("separation", 9)
var mark := logo()
if mark:
brand.add_child(mark)
brand.mouse_filter = Control.MOUSE_FILTER_STOP
brand.tooltip_text = "Main menu"
brand.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
brand.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.pressed and mb.button_index == MOUSE_BUTTON_LEFT:
on_click.call())
var title := Style.make_label("Table Tarot", Style.display(), 23, Style.ACCENT)
title.size_flags_vertical = Control.SIZE_SHRINK_CENTER
brand.add_child(title)
return brand
## One half of the Play | Build switch (also used by the sheet editor).
static func seg_button(text: String, group: ButtonGroup) -> Button:
var b := Button.new()
b.text = text
b.toggle_mode = true

56
ui/menu_icons.gd Normal file
View file

@ -0,0 +1,56 @@
class_name MenuIcons
extends RefCounted
## Small line icons drawn in code (no image files), for the main menu and the
## palettes. Each paints into a 24×24 box scaled to `size`.
const SHEET := "sheet"
const SPREAD := "spread"
const SETTINGS := "settings"
const QUIT := "quit"
const SEARCH := "search"
## A Control that draws icon `kind` in `color`, `size` pixels square.
static func make(kind: String, color: Color, size: float = 24.0) -> Control:
var c := Control.new()
c.custom_minimum_size = Vector2(size, size)
c.mouse_filter = Control.MOUSE_FILTER_IGNORE
c.size_flags_vertical = Control.SIZE_SHRINK_CENTER
c.draw.connect(func() -> void: paint(c, kind, color, size / 24.0))
return c
static func paint(c: CanvasItem, kind: String, color: Color, k: float) -> void:
var w := 2.0 * k
var line := func(a: Vector2, b: Vector2) -> void: c.draw_line(a * k, b * k, color, w, true)
var rect := func(r: Rect2) -> void: c.draw_rect(Rect2(r.position * k, r.size * k), color, false, w, true)
match kind:
SHEET:
rect.call(Rect2(4, 3, 16, 18))
line.call(Vector2(8, 8), Vector2(16, 8))
line.call(Vector2(8, 12), Vector2(11, 12))
line.call(Vector2(13, 12), Vector2(16, 12))
line.call(Vector2(8, 16), Vector2(16, 16))
SPREAD:
rect.call(Rect2(3, 4, 7, 9))
rect.call(Rect2(14, 11, 7, 9))
var pts := PackedVector2Array()
for i in 9:
var t := i / 8.0
pts.append(Vector2(10 + 4 * t, 8 + 6 * t * t) * k)
c.draw_polyline(pts, color, w, true)
SETTINGS:
c.draw_arc(Vector2(12, 12) * k, 3.0 * k, 0.0, TAU, 20, color, w, true)
for i in 8:
var dir := Vector2.RIGHT.rotated(i * TAU / 8.0)
line.call(Vector2(12, 12) + dir * 6.5, Vector2(12, 12) + dir * 9.5)
QUIT:
line.call(Vector2(15, 4), Vector2(19, 4))
line.call(Vector2(19, 4), Vector2(19, 20))
line.call(Vector2(19, 20), Vector2(15, 20))
line.call(Vector2(6, 12), Vector2(16, 12))
line.call(Vector2(10, 8), Vector2(6, 12))
line.call(Vector2(10, 16), Vector2(6, 12))
SEARCH:
c.draw_arc(Vector2(10.5, 10.5) * k, 6.0 * k, 0.0, TAU, 24, color, w, true)
line.call(Vector2(15, 15), Vector2(20, 20))

1
ui/menu_icons.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dnra7pi4l3erh

View file

@ -1,7 +1,8 @@
class_name MobileLayout
extends RefCounted
## The phone layout (Android, or --mobile on a desktop to try it): the List
## fills the screen and a Spread/List button swaps it with the spread; the
## The phone layout (Android, or --mobile on a desktop to try it): the left
## dock (List, or the card palette from "+") fills the screen and a Spread/List
## button swaps it with the spread; the
## top bar drops its hint and zoom control; everything scales to the screen's
## density. Touch gestures come from TouchInput (added on every platform, so
## touch screens on laptops work too).
@ -9,6 +10,7 @@ extends RefCounted
var m: Main
var showing_list := true
var swap: Button
var add_button: Button
func _init(p_main: Main) -> void:
@ -30,22 +32,37 @@ func apply() -> void:
c.visible = false
m.tray.side_panel.visible = false
m.tray.compact = true
m.list_view.close_button.visible = false
m.list_view.splitter.visible = false
m.list_view.size_flags_horizontal = Control.SIZE_EXPAND_FILL
m.left_dock.close_button.visible = false
m.left_dock.splitter.visible = false
m.left_dock.size_flags_horizontal = Control.SIZE_EXPAND_FILL
m.left_dock.show_tab(LeftDock.LIST)
m.board.minimap.visible = false
swap = Style.bar_button("Spread")
swap.tooltip_text = "Swap between the list and the spread"
swap.pressed.connect(func() -> void: show_list(not showing_list))
bar.actions_menu.get_parent().add_child(swap)
bar.actions_menu.get_parent().move_child(swap, bar.actions_menu.get_index())
# "+" opens the card palette full screen; picking a card goes back to the spread.
add_button = Style.bar_button("+")
add_button.tooltip_text = "Add a card"
add_button.custom_minimum_size = Vector2(44, 44)
add_button.pressed.connect(open_palette)
bar.actions_menu.get_parent().add_child(add_button)
bar.actions_menu.get_parent().move_child(add_button, swap.get_index())
show_list(true)
m.screens.sheets.editor.use_phone_layout()
## The list or the spread fills the screen.
func show_list(on: bool) -> void:
showing_list = on
m.list_view.visible = on
m.left_dock.visible = on
m.list_view._rev = -1
m.board.visible = not on
swap.text = "Spread" if on else "List"
## The card palette fills the screen (the left dock's Cards tab).
func open_palette() -> void:
m.left_dock.show_tab(LeftDock.CARDS)
show_list(true)

136
ui/new_sheet_dialog.gd Normal file
View file

@ -0,0 +1,136 @@
class_name NewSheetDialog
extends ModalCard
## "+ New sheet", like the mockup: a name, then a grid of starts drawn as small
## pictures: a blank canvas (a grid) or one of your sheet templates (its tint
## and a few boxes). The Create button names the pick. Calls
## on_create(name, template_id) ("" = blank). "Import a sheet file…" in the
## footer closes it and calls on_import (when given).
var store: SheetStore
var name_edit: LineEdit
var create_button: Button
var _choice := ""
var _choices: Dictionary = {} # template id ("" = blank) -> Button
var _names: Dictionary = {} # template id -> name
var _on_create: Callable
func _init(p_store: SheetStore, template_id: String, on_create: Callable, on_import: Callable = Callable()) -> void:
super._init("New sheet", 720.0)
store = p_store
_on_create = on_create
_choice = template_id
var label := Style.make_label("Name", Style.body_bold(), 15, Style.INK)
body.add_child(label)
name_edit = LineEdit.new()
name_edit.placeholder_text = "e.g. Brin Hollowmere, The Rusty Mule"
ModalCard.style_line_edit(name_edit)
name_edit.text_submitted.connect(func(_s: String) -> void: _create())
body.add_child(name_edit)
var grid := GridContainer.new()
grid.columns = 3
grid.add_theme_constant_override("h_separation", 10)
grid.add_theme_constant_override("v_separation", 10)
body.add_child(grid)
var group := ButtonGroup.new()
grid.add_child(_option(group, "", "Blank canvas", "One Main tab, a snap grid, nothing else", ""))
for row: Dictionary in store.list(true):
var tpl := store.load_sheet(str(row["id"]), true)
if tpl == null:
continue
_names[tpl.id] = tpl.name
var n := tpl.tabs.size()
grid.add_child(_option(group, tpl.id, tpl.name, "Your template · %d %s" % [n, "tab" if n == 1 else "tabs"], tpl.tint))
if on_import.is_valid():
var import_button := add_button("Import a sheet file…", "plain", func() -> void:
close()
on_import.call())
import_button.name = "Import"
var hint := Style.make_label("Templates: in a sheet, Save as template…", Style.body(), 13, Style.MUTED)
hint.size_flags_horizontal = SIZE_EXPAND_FILL
hint.size_flags_vertical = SIZE_SHRINK_CENTER
footer.add_child(hint)
add_button("Cancel", "plain", close)
create_button = add_button("", "primary", _create)
_update_create()
ready.connect(func() -> void: name_edit.grab_focus())
## One start in the grid: a small picture, a title and a line under it.
func _option(group: ButtonGroup, id: String, title: String, sub: String, tint: String) -> Button:
var b := Button.new()
b.name = ("Blank" if id == "" else id).validate_node_name()
b.toggle_mode = true
b.button_group = group
b.focus_mode = Control.FOCUS_NONE
b.custom_minimum_size = Vector2(200, 172)
b.size_flags_horizontal = SIZE_EXPAND_FILL
var normal := Style.bordered(Style.box(Style.CARD, 10, [12, 12, 12, 12]), 2, Style.RULE)
var hover := Style.bordered(Style.box(Style.CARD_SOFT, 10, [12, 12, 12, 12]), 2, Style.DASH)
var on := Style.bordered(Style.box(Style.CARD_SOFT, 10, [12, 12, 12, 12]), 2, Style.TRIM)
Style.skin_button(b, normal, hover, on, Style.INK)
b.button_pressed = id == _choice
b.pressed.connect(func() -> void:
_choice = id
_update_create())
var col := VBoxContainer.new()
col.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
col.offset_left = 12
col.offset_top = 12
col.offset_right = -12
col.offset_bottom = -12
col.add_theme_constant_override("separation", 6)
col.mouse_filter = Control.MOUSE_FILTER_IGNORE
b.add_child(col)
var thumb := Control.new()
thumb.custom_minimum_size.y = 72
thumb.mouse_filter = Control.MOUSE_FILTER_IGNORE
thumb.draw.connect(func() -> void: _draw_thumb(thumb, id == "", tint))
col.add_child(thumb)
col.add_child(Style.make_label(title, Style.body_bold(), 15, Style.INK))
var line := Style.make_label(sub, Style.body(), 13, Style.MUTED)
line.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
col.add_child(line)
_choices[id] = b
return b
## Blank: a card with grid lines. Template: its tint (or the cloth) with three boxes.
static func _draw_thumb(c: Control, blank: bool, tint: String) -> void:
var r := Rect2(Vector2.ZERO, c.size)
if blank:
c.draw_rect(r, Style.CARD_SOFT)
var x := 0.0
while x < r.size.x:
c.draw_line(Vector2(x, 0), Vector2(x, r.size.y), Style.RULE, 1.0)
x += 12.0
var y := 0.0
while y < r.size.y:
c.draw_line(Vector2(0, y), Vector2(r.size.x, y), Style.RULE, 1.0)
y += 12.0
return
c.draw_rect(r, Color(tint).darkened(0.45) if tint != "" else Style.BG)
var box := Style.CARD if tint == "" else Style.CARD.lerp(Color(tint), 0.15)
c.draw_rect(Rect2(8, 8, r.size.x * 0.38, r.size.y * 0.5), box)
c.draw_rect(Rect2(r.size.x * 0.56 - 8, 8, r.size.x * 0.44, r.size.y * 0.3), box)
c.draw_rect(Rect2(r.size.x * 0.56 - 8, r.size.y * 0.7 - 8, r.size.x * 0.44, r.size.y * 0.3), box)
func _update_create() -> void:
create_button.text = "Create blank sheet" if _choice == "" else "Create from %s" % _names.get(_choice, "template")
## Picks a start (tests use it).
func choose(id: String) -> void:
if _choices.has(id):
(_choices[id] as Button).button_pressed = true
_choice = id
_update_create()
func _create() -> void:
var name := name_edit.text.strip_edges()
if name == "":
name = "New %s" % _names[_choice] if _choice != "" else "Untitled sheet"
close()
_on_create.call(name, _choice)

View file

@ -0,0 +1 @@
uid://bha1qn2tgtllt

View file

@ -1,17 +1,21 @@
class_name PageEditor
extends VBoxContainer
## The Book's editor for one Page: its name in the list, the result text (with
## BBCode and a live preview), the details tooltip and tags. Every change goes
## to all results linked to the page at once (TowerBoard.sync_page).
## The Lore Index's editor for one Lore Entry (BookPage): its name in the
## list, the result text (with BBCode and a live preview), the details
## tooltip, picture (spread only) and tags, then LoreEntryActions (copy to the
## other level, item sheet). Changes go through the list's level (LoreLevel):
## for the spread, to all results linked to the entry at once (TowerBoard.sync_page).
var m: Main
var lore: LoreList
var page: BookPage
var _preview: RichTextLabel
var _uses: Label
func _init(p_main: Main) -> void:
m = p_main
func _init(p_lore: LoreList) -> void:
lore = p_lore
m = p_lore.m
add_theme_constant_override("separation", 8)
@ -52,9 +56,10 @@ func show_page(p: BookPage) -> void:
p.details = det.text
_changed())
add_child(_field("Details", det))
add_child(_field("Picture", ImageField.new(m, p.image, func(id: String) -> void:
p.image = id
_changed())))
if lore.level.key == LoreLevel.SPREAD:
add_child(_field("Picture", ImageField.new(m, p.image, func(id: String) -> void:
p.image = id
_changed())))
var tags := _line(", ".join(p.tags), "e.g. weapon, holy", func(s: String) -> void:
var list: Array[String] = []
for t in s.split(","):
@ -65,29 +70,25 @@ func show_page(p: BookPage) -> void:
_uses = _note("")
add_child(_uses)
_refresh_uses()
add_child(LoreEntryActions.make(lore, p))
var del := Style.bar_button("Delete Lore Entry")
del.tooltip_text = "Results using it keep their text and stop following the Lore Entry"
del.size_flags_horizontal = SIZE_SHRINK_BEGIN
del.pressed.connect(func() -> void:
m.undo_redo._begin_edit()
m.data.remove_page(p.id)
m.mark_dirty()
m.undo_redo._end_edit()
show_page(null))
lore.level.remove_page(p.id)
show_page(null)
lore.refresh())
add_child(del)
## Copies the page onto its results and redraws their cards.
## Keeps the change (for the spread: onto its results, redrawing their cards).
func _changed() -> void:
for tid in m.data.sync_page(page.id):
m.inspector_edited(tid)
m.mark_dirty()
lore.level.changed(page)
_refresh_uses()
func _refresh_uses() -> void:
var n := m.data.page_uses(page.id)
_uses.text = "Used by %d %s. Drag the Lore Entry from the list onto a result to use it there." % [n, "result" if n == 1 else "results"]
_uses.text = lore.level.uses_note(page)
func _line(text: String, placeholder: String, on_change: Callable) -> LineEdit:

Some files were not shown because too many files have changed in this diff Show more