From dd0323c53fe5fc9872d15f3c54b3423f37976bf8 Mon Sep 17 00:00:00 2001 From: RobinFiredrake Date: Sun, 29 Nov 2026 16:28:04 -0600 Subject: [PATCH] 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 --- core/sheet_demo.gd | 67 ++++++--- core/sheet_kinds.gd | 170 +++++++++++++++++++---- core/sheet_store.gd | 16 +++ core/sheet_values.gd | 135 ++++++++++++++++++ core/sheet_values.gd.uid | 1 + docs/SHEETS.md | 7 +- help/topics.txt | 5 +- tests/test_sheet_editor.gd | 90 ++++++++++++ tests/test_sheets.gd | 32 +++++ ui/field_palette.gd | 2 +- ui/main_cli.gd | 8 ++ ui/sheet_box_view.gd | 13 +- ui/sheet_canvas.gd | 110 +++++++++++++-- ui/sheet_detail_panel.gd | 98 +++++++++++++ ui/sheet_detail_panel.gd.uid | 1 + ui/sheet_editor.gd | 38 ++++- ui/sheet_field_views.gd | 189 +++++++++++++++++++------ ui/sheet_fields_list.gd | 209 ++++++++++++++++++++++++++++ ui/sheet_fields_list.gd.uid | 1 + ui/sheet_fields_niche.gd | 238 ++++++++++++++++++++++++++++++++ ui/sheet_fields_niche.gd.uid | 1 + ui/sheet_fields_smart.gd | 58 ++++++++ ui/sheet_fields_smart.gd.uid | 1 + ui/sheet_fields_trackers.gd | 182 ++++++++++++++++++++++++ ui/sheet_fields_trackers.gd.uid | 1 + ui/sheet_inspector.gd | 6 +- ui/sheet_kind_settings.gd | 189 +++++++++++++++++++++++++ ui/sheet_kind_settings.gd.uid | 1 + 28 files changed, 1754 insertions(+), 115 deletions(-) create mode 100644 core/sheet_values.gd create mode 100644 core/sheet_values.gd.uid create mode 100644 ui/sheet_detail_panel.gd create mode 100644 ui/sheet_detail_panel.gd.uid create mode 100644 ui/sheet_fields_list.gd create mode 100644 ui/sheet_fields_list.gd.uid create mode 100644 ui/sheet_fields_niche.gd create mode 100644 ui/sheet_fields_niche.gd.uid create mode 100644 ui/sheet_fields_smart.gd create mode 100644 ui/sheet_fields_smart.gd.uid create mode 100644 ui/sheet_fields_trackers.gd create mode 100644 ui/sheet_fields_trackers.gd.uid create mode 100644 ui/sheet_kind_settings.gd create mode 100644 ui/sheet_kind_settings.gd.uid diff --git a/core/sheet_demo.gd b/core/sheet_demo.gd index 528ed07..362cfdc 100644 --- a/core/sheet_demo.gd +++ b/core/sheet_demo.gd @@ -1,35 +1,66 @@ class_name SheetDemo extends RefCounted -## A small example sheet (an OSR knight) for screenshots (--sheet-demo) and -## tests. Uses only the kinds built so far. +## 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 boxes: Array = doc.tabs[0]["boxes"] - var title := _add(doc, boxes, SheetKinds.HEADING, "Brin Hollowmere", Vector2(16, 16), Vector2(28, 3), null) + 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, boxes, SheetKinds.NUMBER, stat[0], Vector2(16 + col * 144, 80), Vector2(8, 5), stat[2]) + 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 hp := _add(doc, boxes, SheetKinds.NUMBER, "Hit points", Vector2(16, 176), Vector2(8, 5), 6) - hp.color = "#b8382c" - _add(doc, boxes, SheetKinds.TEXT, "Background", Vector2(464, 80), Vector2(18, 8), - "[b]Hedge knight[/b] from the river marches. Strength {@str}.") - _add(doc, boxes, SheetKinds.TEXT, "Notes", Vector2(160, 176), Vector2(18, 7), - "Owes the ferryman two silver.") - doc.add_tab("Spells") - doc.add_tab("Notes") + 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, kind: String, title: String, at: Vector2, grid_size: Vector2, value: Variant) -> SheetBox: - var b := SheetKinds.make_box(kind, doc.new_box_id(), at) +static func _add(doc: SheetDoc, boxes: Array, item_id: String, title: String, gx: int, gy: int, gw: int, gh: int) -> SheetBox: + var b := SheetKinds.make_box(item_id, doc.new_box_id(), Vector2(gx, gy) * SheetKinds.GRID) b.title = title - b.w = grid_size.x * SheetKinds.GRID - b.h = grid_size.y * SheetKinds.GRID - b.value = value + b.w = gw * SheetKinds.GRID + b.h = gh * SheetKinds.GRID boxes.append(b) return b diff --git a/core/sheet_kinds.gd b/core/sheet_kinds.gd index 0c62e73..3bf5c3a 100644 --- a/core/sheet_kinds.gd +++ b/core/sheet_kinds.gd @@ -1,57 +1,171 @@ 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 and value, and search all read it (the -## sheet's version of CardCatalog). More kinds come in later phases -## (docs/SHEETS.md §4 C). +## 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 HEADING := "heading" -const TEXT := "text" 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" -## Each item: kind, label, group, tip, search words, start size (w, h in grid -## steps), title and value. +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 := [ - {"kind": NUMBER, "label": "Number", "group": GROUP_BASICS, "tip": "A stat or count, like Strength 14 or Gold 30", - "words": "stat score value count", "w": 8, "h": 4, "title": "Number", "value": 0}, - {"kind": TEXT, "label": "Text box", "group": GROUP_BASICS, "tip": "Notes or a description, with formatting and live values like {@str}", - "words": "notes description bbcode long", "w": 14, "h": 8, "title": "Notes", "value": ""}, - {"kind": HEADING, "label": "Heading", "group": GROUP_LAYOUT, "tip": "A title to label part of the sheet", - "words": "title label section", "w": 14, "h": 3, "title": "Heading", "value": null}, + {"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": ""}, ] -static func find(kind: String) -> Dictionary: - for item: Dictionary in ITEMS: - if item["kind"] == kind: - return item +## 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 item: Dictionary in ITEMS: - if not out.has(item["group"]): - out.append(item["group"]) + for it: Dictionary in ITEMS: + if not out.has(it["group"]): + out.append(it["group"]) return out -## A new box of `kind` with its start size, title and value, top-left at `at`. -static func make_box(kind: String, id: String, at: Vector2) -> SheetBox: - var item := find(kind) - var box := SheetBox.new(id, kind) - box.title = str(item.get("title", "")) +## 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(item.get("w", 12)) * GRID - box.h = float(item.get("h", 6)) * GRID - var start: Variant = item.get("value", null) + 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 diff --git a/core/sheet_store.gd b/core/sheet_store.gd index b5f5a70..a3294bf 100644 --- a/core/sheet_store.gd +++ b/core/sheet_store.gd @@ -78,6 +78,22 @@ func free_id(name: String, templates: bool = false) -> String: 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: + var bytes := FileAccess.get_file_as_bytes(path) + if bytes.is_empty(): + return "" + var dir := dir_for(false).path_join("pictures") + DirAccess.make_dir_recursive_absolute(dir) + var kept := dir.path_join("%s.%s" % [str(hash(bytes)).replace("-", "n"), path.get_extension().to_lower()]) + var f := FileAccess.open(kept, FileAccess.WRITE) + if f == null: + return "" + f.store_buffer(bytes) + return kept + + ## A new sheet, blank or copied from a template, saved and returned. func create(name: String, template_id: String = "") -> SheetDoc: var doc: SheetDoc = null diff --git a/core/sheet_values.gd b/core/sheet_values.gd new file mode 100644 index 0000000..a1f70ec --- /dev/null +++ b/core/sheet_values.gd @@ -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} diff --git a/core/sheet_values.gd.uid b/core/sheet_values.gd.uid new file mode 100644 index 0000000..023a57b --- /dev/null +++ b/core/sheet_values.gd.uid @@ -0,0 +1 @@ +uid://c88b3omlh3rka diff --git a/docs/SHEETS.md b/docs/SHEETS.md index b9958f0..af4e8a5 100644 --- a/docs/SHEETS.md +++ b/docs/SHEETS.md @@ -55,7 +55,12 @@ an old sheet card becomes a sheet with one text box. `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:** basics → trackers → computed and dice → niche kinds. +- **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 (E). - **D. Spread integration:** sheet node (first-tab preview), variables read/write, locks, replace and migrate `KIND_SHEET`, document tabs. - **E. Lore Index library + items, export (PDF, PNG, share file), phone stacked view.** diff --git a/help/topics.txt b/help/topics.txt index 23f3779..c24f938 100644 --- a/help/topics.txt +++ b/help/topics.txt @@ -280,7 +280,10 @@ The app opens on the [b]main menu[/b]: Spreads, Sheets, Settings and Quit. To co - 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). -- Give a box a name under [b]Use in tables[/b] and a text box can show it with {@name}. +- 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. +- 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. - [b]Sheet ▾ → Save as template…[/b] keeps the layout to start new sheets from. # Spreads, import and export diff --git a/tests/test_sheet_editor.gd b/tests/test_sheet_editor.gd index cff8187..ad6e933 100644 --- a/tests/test_sheet_editor.gd +++ b/tests/test_sheet_editor.gd @@ -13,6 +13,7 @@ func run() -> void: await _test_boxes() await _test_tabs() await _test_keys() + await _test_kinds() finish() @@ -71,6 +72,20 @@ func _test_boxes() -> void: 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") + 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() @@ -118,6 +133,81 @@ func _test_keys() -> void: 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() + + +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 diff --git a/tests/test_sheets.gd b/tests/test_sheets.gd index a327177..479430d 100644 --- a/tests/test_sheets.gd +++ b/tests/test_sheets.gd @@ -12,6 +12,7 @@ func run() -> void: _test_boxes() _test_store() _test_history() + _test_values() _wipe(ROOT) finish() @@ -82,3 +83,34 @@ func _test_history() -> void: _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 diff --git a/ui/field_palette.gd b/ui/field_palette.gd index 586e341..ea01b74 100644 --- a/ui/field_palette.gd +++ b/ui/field_palette.gd @@ -38,7 +38,7 @@ func _sections(query: String) -> Array: 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["kind"]))]) + entries.append([item, _add.bind(str(item["id"]))]) out.append([group, entries]) return out diff --git a/ui/main_cli.gd b/ui/main_cli.gd index 691b237..37da93b 100644 --- a/ui/main_cli.gd +++ b/ui/main_cli.gd @@ -266,6 +266,14 @@ func _run_nav_cli(args: PackedStringArray) -> void: m.screens.sheets.open_doc(sheet) if args.has("--sheet-build"): m.screens.sheets.editor.set_mode(Main.Mode.BUILD) + var sheet_tab := _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 := _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("--new-sheet"): m.screens.show(MainScreens.SHEETS) m.screens.sheets.store.save_as_template(SheetDemo.create(), "OSR Character") diff --git a/ui/sheet_box_view.gd b/ui/sheet_box_view.gd index 51e33f1..1b1ef62 100644 --- a/ui/sheet_box_view.gd +++ b/ui/sheet_box_view.gd @@ -18,6 +18,8 @@ var _from := Vector2.ZERO var _start := Rect2() var _before: Dictionary = {} var _selected := false +## How far the canvas scrolled during this drag (it scrolls near the edges). +var _scrolled := Vector2.ZERO ## The box's colours: card, band, border, ink and muted ink. A colour tints @@ -48,10 +50,11 @@ func setup(p_editor: SheetEditor, p_box: SheetBox) -> void: col.add_theme_constant_override("separation", 0) col.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) add_child(col) - var banded := box.kind != SheetKinds.HEADING and not box.frameless and box.title != "" + var untitled := box.kind == SheetKinds.HEADING or box.kind == SheetKinds.DIVIDER + var banded := not untitled and not box.frameless and box.title != "" if banded: col.add_child(_band()) - elif box.kind != SheetKinds.HEADING and box.title != "": + elif not untitled and box.title != "": var caption := Style.make_label(box.title.to_upper(), Style.caps(), 11, colors["muted"]) caption.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS var pad := MarginContainer.new() @@ -62,7 +65,7 @@ func setup(p_editor: SheetEditor, p_box: SheetBox) -> void: body.size_flags_vertical = SIZE_EXPAND_FILL _margins(body, 10, 6, 10, 8) col.add_child(body) - body.add_child(SheetFieldViews.make(ed, box, colors["ink"])) + body.add_child(SheetFieldViews.make(ed, box, colors)) if ed.building(): mouse_filter = Control.MOUSE_FILTER_STOP _ignore_mouse(col) @@ -136,6 +139,7 @@ func _build_input(ev: InputEvent) -> void: _from = mb.global_position _start = box.rect() _before = ed.doc.to_dict() + _scrolled = Vector2.ZERO elif _drag != "": end_drag() ed.canvas._fit_area() @@ -143,7 +147,8 @@ func _build_input(ev: InputEvent) -> void: return var mm := ev as InputEventMouseMotion if mm and _drag != "": - drag_to(mm.global_position - _from, Input.is_key_pressed(KEY_ALT)) + _scrolled += ed.canvas.edge_scroll(mm.global_position) + drag_to(mm.global_position - _from + _scrolled, Input.is_key_pressed(KEY_ALT)) accept_event() diff --git a/ui/sheet_canvas.gd b/ui/sheet_canvas.gd index 01fb6d2..c438e13 100644 --- a/ui/sheet_canvas.gd +++ b/ui/sheet_canvas.gd @@ -1,10 +1,11 @@ class_name SheetCanvas extends ScrollContainer ## The open tab's canvas: the theme's spread background (BoardBackdrop) with -## a free layout of boxes (SheetBoxView) centred on it, scrolling when the -## boxes reach past the window. In Build it shows the snap grid as dots; -## clicking empty space clears the selection. The field palette drops new -## boxes here (drop_point). +## a free layout of boxes (SheetBoxView). The page is centred when a tab opens +## and then stays put, with a screen of room past its boxes to drag into. +## Drag empty space (or middle-drag) to pan; a box dragged near an edge +## scrolls the canvas. In Build it shows the snap grid as dots; clicking empty +## space clears the selection. The field palette drops new boxes here. ## Room kept around the boxes, and below them to place more. const MARGIN := 16.0 @@ -17,6 +18,11 @@ var holder: Control var area: Control var views: Dictionary = {} # box id -> SheetBoxView var _backdrop: BoardBackdrop +## The page's left edge, set when a tab opens (recentre) and kept after. +var _origin_x := -1.0 +var _panning := false +var _pan_from := Vector2.ZERO +var _pan_scroll := Vector2.ZERO func setup(p_editor: SheetEditor) -> void: @@ -45,7 +51,35 @@ func rebuild() -> void: area.add_child(view) views[box.id] = view paint_selection() - _fit_area() + if _origin_x < 0.0: + _fit_area.call_deferred() + else: + _fit_area() + + +## Centres the page again the next time the canvas is laid out (a sheet or a +## tab was opened) and scrolls back to the top. +func recentre() -> void: + _origin_x = -1.0 + scroll_horizontal = 0 + scroll_vertical = 0 + + +## Redraws every box but `keep_id` (the one being typed in), so formulas and +## live text follow the change. +func rebuild_except(keep_id: String) -> void: + for box: SheetBox in ed.current_tab()["boxes"]: + if box.id == keep_id or not views.has(box.id): + continue + var old: SheetBoxView = views[box.id] + var view := SheetBoxView.new() + view.setup(ed, box) + area.add_child(view) + area.move_child(view, old.get_index()) + area.remove_child(old) + old.queue_free() + views[box.id] = view + view.paint(box.id == ed.selected) func paint_selection() -> void: @@ -53,21 +87,46 @@ func paint_selection() -> void: (views[id] as SheetBoxView).paint(id == ed.selected) -## Sizes the page to its boxes (plus room below), centres it across, and -## grows the scroll area to hold it. +## Sizes the page to its boxes plus a screen of room right and below, keeps +## its left edge where the tab opened it (centred then), and grows the scroll +## area to hold it. func _fit_area() -> void: var page := Vector2.ZERO for view: SheetBoxView in views.values(): page = page.max(view.position + view.size) - page += Vector2(MARGIN, ROOM) var view_size := size - var x := maxf(MARGIN, floorf((view_size.x - page.x) / 2.0)) - area.position = Vector2(x, MARGIN) - area.size = Vector2(maxf(page.x, view_size.x - x - MARGIN), maxf(page.y, view_size.y - MARGIN * 2)) - holder.custom_minimum_size = (area.position + area.size + Vector2(MARGIN, MARGIN)).max(view_size) + if _origin_x < 0.0 and view_size.x > 0.0: + _origin_x = maxf(MARGIN, floorf((view_size.x - page.x - MARGIN) / 2.0)) + area.position = Vector2(maxf(_origin_x, MARGIN), MARGIN) + area.size = page + view_size + holder.custom_minimum_size = (area.position + area.size).max(view_size) holder.queue_redraw() +## While a box is dragged near an edge, scrolls toward it. Returns how far +## the view moved, so the box can follow. +func edge_scroll(screen_point: Vector2) -> Vector2: + var r := get_global_rect() + var step := Vector2.ZERO + const EDGE := 40.0 + const SPEED := 12.0 + if screen_point.x > r.end.x - EDGE: + step.x = SPEED + elif screen_point.x < r.position.x + EDGE: + step.x = -SPEED + if screen_point.y > r.end.y - EDGE: + step.y = SPEED + elif screen_point.y < r.position.y + EDGE: + step.y = -SPEED + if step == Vector2.ZERO: + return step + var before := Vector2(scroll_horizontal, scroll_vertical) + _fit_area() + scroll_horizontal = int(before.x + step.x) + scroll_vertical = int(before.y + step.y) + return Vector2(scroll_horizontal, scroll_vertical) - before + + func _draw_back() -> void: _backdrop.draw(holder, Rect2(Vector2.ZERO, holder.size)) if ed.doc and ed.doc.tint != "": @@ -92,10 +151,33 @@ func _draw_grid() -> void: y += step +## Empty space: a click clears the selection; a left- or middle-drag pans. func _area_input(ev: InputEvent) -> void: var mb := ev as InputEventMouseButton - if mb and mb.pressed and mb.button_index == MOUSE_BUTTON_LEFT and ed.selected != "": - ed.select("") + if mb and (mb.button_index == MOUSE_BUTTON_LEFT or mb.button_index == MOUSE_BUTTON_MIDDLE): + if mb.pressed: + if mb.button_index == MOUSE_BUTTON_LEFT and ed.selected != "": + ed.select("") + _panning = true + _pan_from = mb.global_position + _pan_scroll = Vector2(scroll_horizontal, scroll_vertical) + holder.mouse_default_cursor_shape = Control.CURSOR_DRAG + else: + _panning = false + holder.mouse_default_cursor_shape = Control.CURSOR_ARROW + holder.accept_event() + return + var mm := ev as InputEventMouseMotion + if mm and _panning: + pan_to(_pan_scroll - (mm.global_position - _pan_from)) + holder.accept_event() + + +## Scrolls to `at` (scroll pixels), growing the canvas when needed. +func pan_to(at: Vector2) -> void: + _fit_area() + scroll_horizontal = int(maxf(at.x, 0)) + scroll_vertical = int(maxf(at.y, 0)) ## The middle of what is on screen, in page coordinates. diff --git a/ui/sheet_detail_panel.gd b/ui/sheet_detail_panel.gd new file mode 100644 index 0000000..b0605b6 --- /dev/null +++ b/ui/sheet_detail_panel.gd @@ -0,0 +1,98 @@ +class_name SheetDetailPanel +extends PanelContainer +## The side panel that opens when you click a list entry's ⓘ or a chip: the +## box's name as a caps label, the entry's name, its other columns as small +## tags, and its full details text (editable). An in-app panel, not a window. + +const WIDTH := 340.0 + +var ed: SheetEditor +var box_id := "" +var index := -1 +var _col: VBoxContainer + + +func setup(p_editor: SheetEditor) -> void: + ed = p_editor + custom_minimum_size.x = WIDTH + var sb := Style.box(Style.CARD_SOFT, 0, [18, 18, 18, 18]) + sb.border_color = Style.DASH + sb.border_width_left = 1 + add_theme_stylebox_override("panel", sb) + _col = VBoxContainer.new() + _col.add_theme_constant_override("separation", 12) + add_child(_col) + visible = false + + +func open(p_box_id: String, p_index: int) -> void: + box_id = p_box_id + index = p_index + rebuild() + + +func close() -> void: + box_id = "" + index = -1 + visible = false + + +func rebuild() -> void: + for c in _col.get_children(): + _col.remove_child(c) + c.queue_free() + var box := ed.doc.find_box(box_id) if ed.doc and box_id != "" else null + var rows: Array = box.value if box and box.value is Array else [] + if box == null or index < 0 or index >= rows.size(): + visible = false + return + visible = true + var entry: Dictionary = rows[index] + var cols := SheetFieldsList.columns(box) + var head := HBoxContainer.new() + var names := VBoxContainer.new() + names.size_flags_horizontal = SIZE_EXPAND_FILL + names.add_theme_constant_override("separation", 2) + names.add_child(Style.make_label(box.title.to_upper(), Style.caps(), 11, Style.TRIM)) + var title := Style.make_label(str(entry.get(str(cols[0]["name"]), "")), Style.display(), 26, Style.INK) + title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + names.add_child(title) + head.add_child(names) + var close_button := ModalCard.make_button("×", "plain") + close_button.name = "Close" + close_button.tooltip_text = "Close the details" + close_button.pressed.connect(close) + head.add_child(close_button) + _col.add_child(head) + var tags := HFlowContainer.new() + tags.add_theme_constant_override("h_separation", 6) + for k in range(1, cols.size()): + var key := str(cols[k]["name"]) + if str(entry.get(key, "")) != "": + tags.add_child(_tag("%s %s" % [key, SheetValues.show(entry[key])])) + if tags.get_child_count() > 0: + _col.add_child(tags) + _col.add_child(Style.make_label("Details", Style.body_bold(), 14, Style.INK)) + var text := TextEdit.new() + text.name = "DetailsText" + text.text = str(entry.get("details", "")) + text.placeholder_text = "What it does, in full. Hovering the entry shows the start of this." + text.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY + text.custom_minimum_size.y = 220 + text.size_flags_vertical = SIZE_EXPAND_FILL + ModalCard.style_text_edit(text) + var key_box := box + var at := index + text.text_changed.connect(func() -> void: + var next := SheetFieldsList.entries(key_box) + if at < next.size(): + next[at]["details"] = text.text + ed.edit_value(key_box, next, "")) + _col.add_child(text) + + +func _tag(text: String) -> PanelContainer: + var p := PanelContainer.new() + p.add_theme_stylebox_override("panel", Style.box(Style.VALUE_BG, 5, [8, 2, 8, 2])) + p.add_child(Style.make_label(text, Style.body_bold(), 13, Style.VALUE_INK)) + return p diff --git a/ui/sheet_detail_panel.gd.uid b/ui/sheet_detail_panel.gd.uid new file mode 100644 index 0000000..a44db1f --- /dev/null +++ b/ui/sheet_detail_panel.gd.uid @@ -0,0 +1 @@ +uid://c345pxfo0lejv diff --git a/ui/sheet_editor.gd b/ui/sheet_editor.gd index ecaf019..156f269 100644 --- a/ui/sheet_editor.gd +++ b/ui/sheet_editor.gd @@ -24,6 +24,8 @@ var palette: FieldPalette var tabs_bar: SheetTabsBar var canvas: SheetCanvas var inspector: SheetInspector +## The side panel for a list entry's full details. +var details: SheetDetailPanel var status_label: Label var undo_label: Label var _save_timer: Timer @@ -55,6 +57,9 @@ func setup(p_main: Main, p_screen: SheetsScreen) -> void: inspector = SheetInspector.new() inspector.setup(self) middle.add_child(inspector) + details = SheetDetailPanel.new() + details.setup(self) + middle.add_child(details) add_child(_make_status_strip()) _save_timer = Timer.new() _save_timer.one_shot = true @@ -112,6 +117,7 @@ func open(p_doc: SheetDoc) -> void: _merge_key = "" tab_id = str(doc.tabs[0]["id"]) selected = "" + canvas.recentre() var empty := doc.tabs.all(func(t: Dictionary) -> bool: return (t["boxes"] as Array).is_empty()) set_mode(Main.Mode.BUILD if empty else Main.Mode.PLAY) @@ -154,6 +160,8 @@ func set_palette_shown(on: bool) -> void: func show_tab(id: String) -> void: + if id != tab_id: + canvas.recentre() tab_id = id selected = "" refresh() @@ -179,6 +187,8 @@ func refresh() -> void: canvas.rebuild() inspector.visible = building() inspector.rebuild() + if details.box_id != "": + details.rebuild() update_status() @@ -200,9 +210,29 @@ func edit(label: String, change: Callable, merge_key: String = "", redraw: bool update_status() -## A player's value change from inside a box (no redraw, so typing keeps focus). -func edit_value(box: SheetBox, value: Variant) -> void: +## A player's value change from inside a box while typing: the box itself +## isn't redrawn (it keeps focus), the boxes that may show it are. Typing +## elsewhere (the details panel) passes keep_id "" so the box redraws too. +func edit_value(box: SheetBox, value: Variant, keep_id: String = "-") -> void: edit("Change %s" % (box.title if box.title != "" else "a value"), func() -> void: box.value = value, "value:" + box.id, false) + canvas.rebuild_except(box.id if keep_id == "-" else keep_id) + + +## A value change from a click (a tick, a chip, + Add): one undo step, all redrawn. +func set_value(box: SheetBox, value: Variant) -> void: + edit("Change %s" % (box.title if box.title != "" else "a value"), func() -> void: box.value = value) + + +## A settings change from the inspector: one undo step per setting while +## typing; the boxes are redrawn but the inspector keeps focus. +func edit_config(box: SheetBox, label: String, change: Callable) -> void: + edit(label, change, "config:%s:%s" % [box.id, label], false) + canvas.rebuild_except("") + + +## Opens a list entry's details in the side panel. +func show_details(box_id: String, index: int) -> void: + details.open(box_id, index) ## Records `before` (taken at the start of a drag) when the drag changed something. @@ -236,12 +266,12 @@ func _step(state: Dictionary, verb: String) -> void: m.toast("%s: %s" % [verb, label]) -## Adds a box of `kind` with its top-left at `at` on the open tab (INF = the +## Adds a box from palette item (or kind) `kind` with its top-left at `at` on the open tab (INF = the ## middle of the visible canvas) and selects it. func add_box(kind: String, at: Vector2 = Vector2.INF) -> SheetBox: var spot := canvas.visible_center() - Vector2(96, 48) if at == Vector2.INF else at var box := SheetKinds.make_box(kind, doc.new_box_id(), spot.max(Vector2.ZERO)) - edit("Add %s" % SheetKinds.find(kind).get("label", "box"), func() -> void: current_tab()["boxes"].append(box)) + edit("Add %s" % SheetKinds.label_of(box), func() -> void: current_tab()["boxes"].append(box)) select(box.id) return box diff --git a/ui/sheet_field_views.gd b/ui/sheet_field_views.gd index 4b263ab..1a86840 100644 --- a/ui/sheet_field_views.gd +++ b/ui/sheet_field_views.gd @@ -1,18 +1,38 @@ class_name SheetFieldViews extends RefCounted ## The inside of a sheet box, by kind (SheetKinds): what the player sees and -## changes in Play. Changes go through SheetEditor.edit_value. More kinds come -## with phase C (docs/SHEETS.md). +## changes in Play. This file has the basic kinds and shared helpers; the +## others live in SheetFieldsTrackers, SheetFieldsSmart, SheetFieldsList and +## SheetFieldsNiche. Changes go through SheetEditor.edit_value (typing) or +## set_value (clicks), so they can be undone. -static func make(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: +static func make(ed: SheetEditor, box: SheetBox, look: Dictionary) -> Control: + var ink: Color = look["ink"] match box.kind: SheetKinds.HEADING: return _heading(box, ink) SheetKinds.NUMBER: return _number(ed, box, ink) - _: - return _text(ed, box, ink) + SheetKinds.SHORT_TEXT: + return _short_text(ed, box, ink) + SheetKinds.CHECKBOX: + return _checkbox(ed, box, ink) + SheetKinds.DROPDOWN: + return _dropdown(ed, box, ink) + SheetKinds.DIVIDER: + return _divider(ink) + SheetKinds.PICTURE: + return _picture(ed, box, look) + SheetKinds.RESOURCE, SheetKinds.TICKS, SheetKinds.CLOCK, SheetKinds.DOTS, SheetKinds.STEP_DIE, SheetKinds.USAGE_DIE, SheetKinds.LADDER: + return SheetFieldsTrackers.make(ed, box, look) + SheetKinds.FORMULA, SheetKinds.DICE: + return SheetFieldsSmart.make(ed, box, look) + SheetKinds.LIST: + return SheetFieldsList.make(ed, box, look) + SheetKinds.SLOTS, SheetKinds.CONDITIONS, SheetKinds.SPELL_SLOTS, SheetKinds.XP, SheetKinds.CURRENCY: + return SheetFieldsNiche.make(ed, box, look) + return _text(ed, box, ink) static func _heading(box: SheetBox, ink: Color) -> Control: @@ -22,6 +42,12 @@ static func _heading(box: SheetBox, ink: Color) -> Control: return l +static func _divider(ink: Color) -> Control: + var c := Control.new() + c.draw.connect(func() -> void: c.draw_line(Vector2(0, c.size.y / 2.0), Vector2(c.size.x, c.size.y / 2.0), Color(ink, 0.5), 2.0)) + return c + + ## A number with − and + beside it; type to set it. static func _number(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: var row := HBoxContainer.new() @@ -29,7 +55,7 @@ static func _number(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: row.add_theme_constant_override("separation", 4) var value := LineEdit.new() value.name = "Value" - value.text = _num_text(box.value) + value.text = SheetValues.show(SheetValues.number(box.value)) value.alignment = HORIZONTAL_ALIGNMENT_CENTER value.size_flags_horizontal = Control.SIZE_EXPAND_FILL value.custom_minimum_size.x = 24 @@ -39,19 +65,18 @@ static func _number(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: value.add_theme_font_size_override("font_size", 26) value.add_theme_color_override("font_color", ink) var commit := func(text: String) -> void: - var n: Variant = _parse(text, box.value) - value.text = _num_text(n) - if n != _as_number(box.value): + var n: Variant = clamp_number(box, SheetValues.number(parse_number(text, box.value))) + value.text = SheetValues.show(n) + if SheetValues.number(n) != SheetValues.number(box.value): ed.edit_value(box, n) value.text_submitted.connect(commit) value.focus_exited.connect(func() -> void: commit.call(value.text)) for step: int in [-1, 1]: - var b := _step_button("−" if step < 0 else "+", ink) + var b := step_button("−" if step < 0 else "+", ink) b.name = "Minus" if step < 0 else "Plus" - b.focus_mode = Control.FOCUS_NONE b.pressed.connect(func() -> void: - var n: Variant = _as_number(box.value) + step - value.text = _num_text(n) + var n: Variant = clamp_number(box, SheetValues.number(box.value) + step) + value.text = SheetValues.show(n) ed.edit_value(box, n)) row.add_child(b) if step < 0: @@ -59,32 +84,100 @@ static func _number(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: return row -## A small − or + button drawn in the box's own ink colour. -static func _step_button(text: String, ink: Color) -> Button: - var b := Button.new() - b.text = text - b.custom_minimum_size = Vector2(26, 26) - b.size_flags_vertical = Control.SIZE_SHRINK_CENTER - b.focus_mode = Control.FOCUS_NONE - b.add_theme_font_override("font", Style.body_bold()) - b.add_theme_font_size_override("font_size", 16) - var normal := Style.bordered(Style.box(Color(ink, 0.04), 6, [4, 0, 4, 0]), 1, Color(ink, 0.35)) - var hover := Style.bordered(Style.box(Color(ink, 0.12), 6, [4, 0, 4, 0]), 1, Color(ink, 0.6)) - Style.skin_button(b, normal, hover, hover, ink, ink, ink) +## Keeps a number inside the box's min and max settings (when set). +static func clamp_number(box: SheetBox, n: float) -> Variant: + if str(box.config.get("min", "")) != "": + n = maxf(n, SheetValues.number(box.config["min"])) + if str(box.config.get("max", "")) != "": + n = minf(n, SheetValues.number(box.config["max"])) + return int(n) if n == floorf(n) else n + + +static func _short_text(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var e := LineEdit.new() + e.name = "Value" + e.text = str(box.value if box.value != null else "") + e.placeholder_text = "Type here" + e.flat = true + e.size_flags_vertical = Control.SIZE_SHRINK_CENTER + e.add_theme_font_size_override("font_size", 17) + e.add_theme_color_override("font_color", ink) + e.add_theme_color_override("font_placeholder_color", Color(ink, 0.4)) + e.text_changed.connect(func(text: String) -> void: ed.edit_value(box, text)) + return e + + +static func _checkbox(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var c := CheckBox.new() + c.name = "Value" + c.text = "Yes" if bool(box.value) else "No" + c.button_pressed = bool(box.value) + for key in ["font_color", "font_hover_color", "font_pressed_color", "font_hover_pressed_color"]: + c.add_theme_color_override(key, ink) + c.toggled.connect(func(on: bool) -> void: + c.text = "Yes" if on else "No" + ed.edit_value(box, on)) + return c + + +static func _dropdown(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var o := OptionButton.new() + o.name = "Value" + var options: Array = box.config.get("options", []) + for i in options.size(): + o.add_item(str(options[i])) + if str(options[i]) == str(box.value): + o.select(i) + o.size_flags_vertical = Control.SIZE_SHRINK_CENTER + o.add_theme_color_override("font_color", ink) + o.item_selected.connect(func(i: int) -> void: ed.edit_value(box, str(options[i]))) + return o + + +## The picture from its file, or a button to pick one (Play). +static func _picture(ed: SheetEditor, box: SheetBox, look: Dictionary) -> Control: + var path := str(box.value if box.value != null else "") + var tex: Texture2D = null + if path != "" and FileAccess.file_exists(path): + var img := Image.load_from_file(path) + if img: + tex = ImageTexture.create_from_image(img) + if tex: + var tr := TextureRect.new() + tr.texture = tex + tr.expand_mode = TextureRect.EXPAND_IGNORE_SIZE + tr.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED + tr.tooltip_text = "Double-click to change the picture" + tr.gui_input.connect(func(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb and mb.double_click and not ed.building(): + pick_picture(ed, box)) + return tr + var b := step_button("Choose a picture…", look["ink"]) + b.name = "Choose" + b.pressed.connect(pick_picture.bind(ed, box)) return b +static func pick_picture(ed: SheetEditor, box: SheetBox) -> void: + ed.m.layout.file_dialog("Choose a picture", ["*.png, *.jpg, *.jpeg, *.webp ; Pictures"], FileDialog.FILE_MODE_OPEN_FILE, func(path: String) -> void: + var kept := ed.screen.store.keep_picture(path) + if kept == "": + ed.m.toast("Couldn't read that picture") + else: + ed.set_value(box, kept)) + + ## Shows the formatted text; click (Play) to edit it as BBCode, click away to see it again. static func _text(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: var stack := Control.new() var shown := RichTextLabel.new() shown.bbcode_enabled = true - shown.fit_content = false shown.scroll_active = true shown.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) shown.add_theme_color_override("default_color", ink) shown.add_theme_font_override("normal_font", Style.body()) - shown.text = _expand(ed, str(box.value if box.value != null else "")) + shown.text = expand(ed, str(box.value if box.value != null else "")) if shown.text == "" and not ed.building(): shown.text = "[i]Click to write…[/i]" stack.add_child(shown) @@ -105,35 +198,47 @@ static func _text(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: edit.text_changed.connect(func() -> void: ed.edit_value(box, edit.text)) edit.focus_exited.connect(func() -> void: edit.visible = false - shown.text = _expand(ed, edit.text) + shown.text = expand(ed, edit.text) shown.visible = true) return stack ## Live values: {@name} shows the value of the box used in tables as @name. -static func _expand(ed: SheetEditor, text: String) -> String: +static func expand(ed: SheetEditor, text: String) -> String: if not text.contains("{@"): return text - for tab in ed.doc.tabs: - for other: SheetBox in tab["boxes"]: - if other.var_name != "": - text = text.replace("{@%s}" % other.var_name, _num_text(other.value) if other.kind == SheetKinds.NUMBER else str(other.value)) + var values := SheetValues.vars(ed.doc) + for name: String in values: + text = text.replace("{@%s}" % name, "[b]%s[/b]" % SheetValues.show(values[name])) return text -static func _as_number(v: Variant) -> float: - return float(v) if v is int or v is float or (v is String and (v as String).is_valid_float()) else 0.0 - - -static func _parse(text: String, fallback: Variant) -> Variant: +static func parse_number(text: String, fallback: Variant) -> Variant: var t := text.strip_edges() if t.is_valid_int(): return t.to_int() if t.is_valid_float(): return t.to_float() - return _as_number(fallback) + return SheetValues.number(fallback) -static func _num_text(v: Variant) -> String: - var n := _as_number(v) - return str(int(n)) if n == floorf(n) else str(n) +## A small button drawn in the box's own ink colour. +static func step_button(text: String, ink: Color) -> Button: + var b := Button.new() + b.text = text + b.custom_minimum_size = Vector2(26, 26) + b.size_flags_vertical = Control.SIZE_SHRINK_CENTER + b.focus_mode = Control.FOCUS_NONE + b.add_theme_font_override("font", Style.body_bold()) + b.add_theme_font_size_override("font_size", 15) + var normal := Style.bordered(Style.box(Color(ink, 0.04), 6, [6, 0, 6, 0]), 1, Color(ink, 0.35)) + var hover := Style.bordered(Style.box(Color(ink, 0.12), 6, [6, 0, 6, 0]), 1, Color(ink, 0.6)) + Style.skin_button(b, normal, hover, hover, ink, ink, ink) + return b + + +## A muted label in the box's ink. +static func note(text: String, ink: Color, size: int = 13) -> Label: + var l := Style.make_label(text, Style.body(), size, Color(ink, 0.7)) + l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + return l diff --git a/ui/sheet_fields_list.gd b/ui/sheet_fields_list.gd new file mode 100644 index 0000000..f3d4e31 --- /dev/null +++ b/ui/sheet_fields_list.gd @@ -0,0 +1,209 @@ +class_name SheetFieldsList +extends RefCounted +## A list box ("repeating section" in other sheet tools): many entries in one +## box, shown as compact rows, a mini table or chips (config "style"). Entries +## are Dictionaries keyed by column name, plus an optional "details" text. +## Hovering an entry shows a short excerpt of its details; ⓘ opens them in +## the side panel (SheetDetailPanel). With a point pool (config "pool") the +## cost column's total comes off the pool; going over is allowed and shows red. + +const EXCERPT := 110 + + +static func make(ed: SheetEditor, box: SheetBox, look: Dictionary) -> Control: + var ink: Color = look["ink"] + var col := VBoxContainer.new() + col.add_theme_constant_override("separation", 4) + var pool_label: Label = null + if SheetValues.number(box.config.get("pool", 0)) > 0: + pool_label = Style.make_label("", Style.body_bold(), 13, ink) + pool_label.name = "Pool" + col.add_child(pool_label) + _show_pool(box, pool_label, ink) + var scroll := ScrollContainer.new() + scroll.size_flags_vertical = Control.SIZE_EXPAND_FILL + scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + col.add_child(scroll) + var style := str(box.config.get("style", "rows")) + if style == "chips": + scroll.add_child(_chips(ed, box, ink)) + else: + scroll.add_child(_rows(ed, box, ink, style == "table", pool_label)) + return col + + +static func entries(box: SheetBox) -> Array: + return (box.value as Array).duplicate(true) if box.value is Array else [] + + +static func columns(box: SheetBox) -> Array: + var cols: Array = box.config.get("columns", []) + return cols if not cols.is_empty() else [{"name": "Name", "type": "text"}] + + +## "Pool 20 · spent 17 · left 3", red with "over by 1: allowed" below zero. +static func _show_pool(box: SheetBox, label: Label, ink: Color) -> void: + var p := SheetValues.pool(box) + var left := float(p["left"]) + label.text = "Pool %s · spent %s · left %s" % [SheetValues.show(p["total"]), SheetValues.show(p["spent"]), SheetValues.show(left)] + if left < 0: + label.text += " · over by %s: allowed" % SheetValues.show(-left) + label.add_theme_color_override("font_color", Style.DANGER_INK if left < 0 else ink) + + +## Rows (label left, value right) or a mini table (a header and a cell per column). +static func _rows(ed: SheetEditor, box: SheetBox, ink: Color, table: bool, pool_label: Label) -> VBoxContainer: + var list := VBoxContainer.new() + list.size_flags_horizontal = Control.SIZE_EXPAND_FILL + list.add_theme_constant_override("separation", 2) + var cols := columns(box) + if table: + var head := HBoxContainer.new() + for c: Dictionary in cols: + var h := Style.make_label(str(c["name"]).to_upper(), Style.caps(), 10, Color(ink, 0.6)) + _size_cell(h, c) + head.add_child(h) + head.add_child(_spacer(48)) + list.add_child(head) + var rows := entries(box) + for i in rows.size(): + list.add_child(_row(ed, box, ink, cols, rows, i, table, pool_label)) + if not ed.building(): + var add := SheetFieldViews.step_button("+ Add", ink) + add.name = "Add" + add.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN + add.pressed.connect(func() -> void: + var next := entries(box) + var blank := {} + for c: Dictionary in cols: + blank[c["name"]] = 0 if c.get("type", "text") == "number" else "" + next.append(blank) + ed.set_value(box, next)) + list.add_child(add) + return list + + +static func _row(ed: SheetEditor, box: SheetBox, ink: Color, cols: Array, rows: Array, i: int, table: bool, pool_label: Label) -> HBoxContainer: + var row := HBoxContainer.new() + row.name = "Row%d" % i + row.add_theme_constant_override("separation", 4) + var entry: Dictionary = rows[i] + row.tooltip_text = excerpt(entry, cols) + row.mouse_filter = Control.MOUSE_FILTER_PASS + for k in cols.size(): + var c: Dictionary = cols[k] + var key := str(c["name"]) + var number: bool = c.get("type", "text") == "number" + var cell := LineEdit.new() + cell.name = key.validate_node_name() + cell.text = SheetValues.show(entry.get(key, 0)) if number else str(entry.get(key, "")) + cell.flat = true + cell.tooltip_text = row.tooltip_text + cell.add_theme_constant_override("minimum_character_width", 1) + cell.add_theme_color_override("font_color", ink) + cell.add_theme_font_override("font", Style.body_bold() if k == 0 else Style.body()) + cell.add_theme_font_size_override("font_size", 14) + if number: + cell.alignment = HORIZONTAL_ALIGNMENT_RIGHT + if table: + _size_cell(cell, c) + else: + cell.size_flags_horizontal = Control.SIZE_EXPAND_FILL if k == 0 else Control.SIZE_SHRINK_END + if k > 0: + cell.custom_minimum_size.x = 44 + cell.text_changed.connect(func(text: String) -> void: + var next := entries(box) + next[i][key] = SheetFieldViews.parse_number(text, 0) if number else text + ed.edit_value(box, next) + if pool_label: + _show_pool(box, pool_label, ink)) + row.add_child(cell) + row.add_child(_info_button(ed, box, i, ink)) + if not ed.building(): + var remove := SheetFieldViews.step_button("×", ink) + remove.name = "Remove" + remove.tooltip_text = "Remove this entry" + remove.pressed.connect(func() -> void: + var next := entries(box) + next.remove_at(i) + ed.set_value(box, next)) + row.add_child(remove) + return row + + +## ⓘ: opens the entry's details in the side panel. +static func _info_button(ed: SheetEditor, box: SheetBox, i: int, ink: Color) -> Button: + var b := SheetFieldViews.step_button("ⓘ", ink) + b.name = "Details" + b.tooltip_text = "Details: what it does, in full" + b.pressed.connect(func() -> void: ed.show_details(box.id, i)) + return b + + +static func _size_cell(c: Control, col: Dictionary) -> void: + if col.get("type", "text") == "number": + c.custom_minimum_size.x = 44 + c.size_flags_horizontal = Control.SIZE_SHRINK_END + else: + c.size_flags_horizontal = Control.SIZE_EXPAND_FILL + c.custom_minimum_size.x = 40 + + +static func _spacer(w: float) -> Control: + var s := Control.new() + s.custom_minimum_size.x = w + return s + + +## Short entries side by side: "Name value"; click one for details, + adds. +static func _chips(ed: SheetEditor, box: SheetBox, ink: Color) -> HFlowContainer: + var flow := HFlowContainer.new() + flow.size_flags_horizontal = Control.SIZE_EXPAND_FILL + flow.add_theme_constant_override("h_separation", 5) + flow.add_theme_constant_override("v_separation", 5) + var cols := columns(box) + var rows := entries(box) + for i in rows.size(): + var entry: Dictionary = rows[i] + var parts: Array = [] + for c: Dictionary in cols: + parts.append(SheetValues.show(entry.get(c["name"], "")) if c.get("type", "text") == "number" else str(entry.get(c["name"], ""))) + var chip := SheetFieldViews.step_button(" ".join(parts).strip_edges(), ink) + chip.name = "Chip%d" % i + chip.tooltip_text = excerpt(entry, cols) + "\nClick for details · right-click to remove" + var index := i + chip.pressed.connect(func() -> void: ed.show_details(box.id, index)) + chip.gui_input.connect(func(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb and mb.pressed and mb.button_index == MOUSE_BUTTON_RIGHT and not ed.building(): + var next := entries(box) + next.remove_at(index) + ed.set_value(box, next)) + flow.add_child(chip) + if not ed.building(): + var add := LineEdit.new() + add.name = "AddChip" + add.placeholder_text = "+ add" + add.custom_minimum_size.x = 80 + add.flat = true + add.add_theme_color_override("font_color", ink) + add.add_theme_color_override("font_placeholder_color", Color(ink, 0.5)) + add.text_submitted.connect(func(text: String) -> void: + if text.strip_edges() == "": + return + var next := entries(box) + next.append({str(cols[0]["name"]): text.strip_edges()}) + ed.set_value(box, next)) + flow.add_child(add) + return flow + + +## The hover text: the entry's name and the start of its details, cut with "…". +static func excerpt(entry: Dictionary, cols: Array) -> String: + var name := str(entry.get(str(cols[0]["name"]), "")) + var details := str(entry.get("details", "")).strip_edges() + if details == "": + return name + "\nⓘ to add details" + if details.length() > EXCERPT: + details = details.left(EXCERPT).strip_edges() + "…" + return "%s\n%s" % [name, details] diff --git a/ui/sheet_fields_list.gd.uid b/ui/sheet_fields_list.gd.uid new file mode 100644 index 0000000..9e9a91e --- /dev/null +++ b/ui/sheet_fields_list.gd.uid @@ -0,0 +1 @@ +uid://d26sqk6js6gfo diff --git a/ui/sheet_fields_niche.gd b/ui/sheet_fields_niche.gd new file mode 100644 index 0000000..4e7fe13 --- /dev/null +++ b/ui/sheet_fields_niche.gd @@ -0,0 +1,238 @@ +class_name SheetFieldsNiche +extends RefCounted +## Boxes from popular RPGs: slot inventory with encumbrance (Knave, Cairn, +## Mausritter), condition chips, spell slots per level, XP with levels, and +## currency with exchange rates. + + +static func make(ed: SheetEditor, box: SheetBox, look: Dictionary) -> Control: + var ink: Color = look["ink"] + match box.kind: + SheetKinds.SLOTS: + return _slots(ed, box, ink) + SheetKinds.CONDITIONS: + return _conditions(ed, box, ink) + SheetKinds.SPELL_SLOTS: + return _spell_slots(ed, box, ink) + SheetKinds.XP: + return _xp(ed, box, ink) + return _currency(ed, box, ink) + + +static func _items(box: SheetBox) -> Array: + return (box.value as Array).duplicate(true) if box.value is Array else [] + + +## A grid of slots; items fill them in order (big items take more). Click an +## item for Bigger / Smaller / Remove; type below to add. Warns when full. +static func _slots(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var col := VBoxContainer.new() + col.add_theme_constant_override("separation", 6) + var total := maxi(1, int(SheetValues.number(box.config.get("slots", 10)))) + var items := _items(box) + var used := 0 + for it: Dictionary in items: + used += maxi(1, int(SheetValues.number(it.get("size", 1)))) + var status := Style.make_label("%d / %d slots%s" % [used, total, " · Pack full" if used >= total else ""], Style.body_bold(), 13, + Style.DANGER_INK if used > total else ink) + status.name = "SlotStatus" + col.add_child(status) + var grid := GridContainer.new() + grid.columns = clampi(int((box.w - 20) / 74.0), 2, 8) + grid.add_theme_constant_override("h_separation", 4) + grid.add_theme_constant_override("v_separation", 4) + col.add_child(grid) + var cell := 0 + for i in items.size(): + var it: Dictionary = items[i] + var size := maxi(1, int(SheetValues.number(it.get("size", 1)))) + for k in size: + var b := SheetFieldViews.step_button(str(it.get("name", "")) if k == 0 else "↳", ink) + b.name = "Item%d_%d" % [i, k] + b.custom_minimum_size = Vector2(0, 26) + b.size_flags_horizontal = Control.SIZE_EXPAND_FILL + b.clip_text = true + b.tooltip_text = "%s · %d %s · click to change" % [it.get("name", ""), size, "slot" if size == 1 else "slots"] + var index := i + b.pressed.connect(func() -> void: _item_menu(ed, box, index, b)) + grid.add_child(b) + cell += 1 + while cell < total: + var empty := PanelContainer.new() + empty.custom_minimum_size = Vector2(0, 26) + empty.size_flags_horizontal = Control.SIZE_EXPAND_FILL + empty.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(0, 0, 0, 0), 6), 1, Color(ink, 0.25))) + grid.add_child(empty) + cell += 1 + if not ed.building(): + var add := LineEdit.new() + add.name = "AddItem" + add.placeholder_text = "+ add an item (Enter)" + add.flat = true + add.add_theme_color_override("font_color", ink) + add.add_theme_color_override("font_placeholder_color", Color(ink, 0.5)) + add.text_submitted.connect(func(text: String) -> void: + if text.strip_edges() == "": + return + var next := _items(box) + next.append({"name": text.strip_edges(), "size": 1}) + ed.set_value(box, next)) + col.add_child(add) + return col + + +static func _item_menu(ed: SheetEditor, box: SheetBox, index: int, at: Control) -> void: + if ed.building(): + return + var change := func(delta: int) -> void: + var next := _items(box) + next[index]["size"] = maxi(1, int(SheetValues.number(next[index].get("size", 1))) + delta) + ed.set_value(box, next) + Actions.popup_at(ed.m, [ + {"text": "Bigger (one more slot)", "do": change.bind(1)}, + {"text": "Smaller", "do": change.bind(-1)}, + {"text": "Remove", "do": func() -> void: + var next := _items(box) + next.remove_at(index) + ed.set_value(box, next)}, + ], at.get_global_rect().get_center()) + + +## Chips for each condition: lit when it applies; click to switch it. +static func _conditions(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var flow := HFlowContainer.new() + flow.add_theme_constant_override("h_separation", 5) + flow.add_theme_constant_override("v_separation", 5) + var active: Array = box.value if box.value is Array else [] + var names: Array = (box.config.get("options", []) as Array).duplicate() + for a: Variant in active: + if not names.has(a): + names.append(a) + for n: Variant in names: + var on := active.has(n) + var chip := Button.new() + chip.name = str(n).validate_node_name() + chip.text = str(n) + chip.focus_mode = Control.FOCUS_NONE + var sb := Style.bordered(Style.box(ink if on else Color(0, 0, 0, 0), 6, [8, 3, 8, 3]), 1, Color(ink, 0.7 if on else 0.35)) + var fg := Style.CARD if on and ink.get_luminance() < 0.5 else (Style.INK if on else Color(ink, 0.75)) + Style.skin_button(chip, sb, sb, sb, fg, fg, fg) + chip.add_theme_font_size_override("font_size", 13) + chip.pressed.connect(func() -> void: + var next := active.duplicate() + if on: + next.erase(n) + else: + next.append(n) + ed.set_value(box, next)) + flow.add_child(chip) + return flow + + +## A row per spell level: its name and a box per slot to mark as used. +static func _spell_slots(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var col := VBoxContainer.new() + col.add_theme_constant_override("separation", 4) + var levels: Array = box.config.get("levels", []) + var used: Array = (box.value as Array).duplicate() if box.value is Array else [] + while used.size() < levels.size(): + used.append(0) + for i in levels.size(): + var lv: Dictionary = levels[i] + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 5) + var name := Style.make_label(str(lv.get("name", "")), Style.body_bold(), 14, ink) + name.custom_minimum_size.x = 40 + row.add_child(name) + var marked := int(SheetValues.number(used[i])) + for k in int(SheetValues.number(lv.get("max", 0))): + var b := Button.new() + b.name = "Slot%d_%d" % [i, k + 1] + b.focus_mode = Control.FOCUS_NONE + b.custom_minimum_size = Vector2(18, 18) + var on := k < marked + var sb := Style.bordered(Style.box(ink if on else Color(0, 0, 0, 0), 9), 2, ink if on else Color(ink, 0.55)) + Style.skin_button(b, sb, sb, sb, ink) + var n := k + 1 + var level := i + b.pressed.connect(func() -> void: + var next := used.duplicate() + next[level] = n - 1 if n == marked else n + ed.set_value(box, next)) + row.add_child(b) + col.add_child(row) + return col + + +## XP you type, the level it reaches and a bar to the next level. +static func _xp(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var col := VBoxContainer.new() + col.add_theme_constant_override("separation", 4) + var info := SheetValues.xp_level(box) + var row := HBoxContainer.new() + var value := LineEdit.new() + value.name = "Value" + value.text = SheetValues.show(SheetValues.number(box.value)) + value.flat = true + value.custom_minimum_size.x = 70 + value.add_theme_font_override("font", Style.display()) + value.add_theme_font_size_override("font_size", 22) + value.add_theme_color_override("font_color", ink) + value.text_submitted.connect(func(text: String) -> void: ed.set_value(box, SheetFieldViews.parse_number(text, box.value))) + value.focus_exited.connect(func() -> void: + if SheetFieldViews.parse_number(value.text, box.value) != SheetValues.number(box.value): + ed.set_value(box, SheetFieldViews.parse_number(value.text, box.value))) + row.add_child(value) + var level := Style.make_label("Level %d" % int(info["level"]), Style.body_bold(), 15, ink) + level.name = "Level" + level.size_flags_horizontal = Control.SIZE_EXPAND_FILL + level.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT + row.add_child(level) + col.add_child(row) + var next := float(info["next"]) + var bar := Control.new() + bar.custom_minimum_size.y = 8 + var share := 1.0 if next < 0 else clampf((SheetValues.number(box.value) - float(info["prev"])) / maxf(1.0, next - float(info["prev"])), 0, 1) + bar.draw.connect(func() -> void: + bar.draw_style_box(Style.box(Color(ink, 0.15), 4), Rect2(Vector2.ZERO, bar.size)) + bar.draw_style_box(Style.box(Style.ACCENT_DARK if ink.get_luminance() < 0.5 else Style.ACCENT, 4), Rect2(Vector2.ZERO, Vector2(bar.size.x * share, bar.size.y)))) + col.add_child(bar) + col.add_child(SheetFieldViews.note("Top level" if next < 0 else "%s to level %d" % [SheetValues.show(next - SheetValues.number(box.value)), int(info["level"]) + 1], ink, 12)) + return col + + +## A field per coin and the total in the first coin. +static func _currency(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var col := VBoxContainer.new() + col.add_theme_constant_override("separation", 4) + var coins: Array = box.config.get("coins", []) + var flow := HFlowContainer.new() + flow.add_theme_constant_override("h_separation", 10) + col.add_child(flow) + var held: Dictionary = (box.value as Dictionary).duplicate() if box.value is Dictionary else {} + var total := Style.make_label("", Style.body_bold(), 14, ink) + total.name = "Total" + var show_total := func() -> void: + total.text = "Total %s %s" % [SheetValues.show(SheetValues.currency_total(box)), str(coins[0].get("name", "")) if not coins.is_empty() else ""] + for coin: Dictionary in coins: + var name := str(coin.get("name", "")) + var pair := HBoxContainer.new() + var e := LineEdit.new() + e.name = name.validate_node_name() + e.text = SheetValues.show(SheetValues.number(held.get(name, 0))) + e.alignment = HORIZONTAL_ALIGNMENT_RIGHT + e.custom_minimum_size.x = 56 + e.flat = true + e.add_theme_color_override("font_color", ink) + e.add_theme_font_override("font", Style.body_bold()) + e.text_changed.connect(func(text: String) -> void: + var next: Dictionary = (box.value as Dictionary).duplicate() if box.value is Dictionary else {} + next[name] = SheetFieldViews.parse_number(text, 0) + ed.edit_value(box, next) + show_total.call()) + pair.add_child(e) + pair.add_child(Style.make_label(name, Style.body(), 14, Color(ink, 0.7))) + flow.add_child(pair) + show_total.call() + col.add_child(total) + return col diff --git a/ui/sheet_fields_niche.gd.uid b/ui/sheet_fields_niche.gd.uid new file mode 100644 index 0000000..c86dfa8 --- /dev/null +++ b/ui/sheet_fields_niche.gd.uid @@ -0,0 +1 @@ +uid://kp1xia5mnjci diff --git a/ui/sheet_fields_smart.gd b/ui/sheet_fields_smart.gd new file mode 100644 index 0000000..aad5c94 --- /dev/null +++ b/ui/sheet_fields_smart.gd @@ -0,0 +1,58 @@ +class_name SheetFieldsSmart +extends RefCounted +## Smart boxes: a formula worked out from other boxes (the rule language with +## the sheet's values as @names, SheetValues), and a dice button that rolls +## its dice with them and shows the result. + + +static func make(ed: SheetEditor, box: SheetBox, look: Dictionary) -> Control: + var ink: Color = look["ink"] + if box.kind == SheetKinds.FORMULA: + return _formula(ed, box, ink) + return _dice(ed, box, ink) + + +static func _formula(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var result := SheetValues.formula(ed.doc, box) + var col := VBoxContainer.new() + col.alignment = BoxContainer.ALIGNMENT_CENTER + var value := Style.make_label(SheetValues.show(result["value"]) if result["error"] == "" else "?", Style.display(), 26, ink) + value.name = "Value" + value.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + col.add_child(value) + var expr := str(box.config.get("expr", "")) + var line := SheetFieldViews.note(str(result["error"]) if result["error"] != "" else "ƒ " + expr, ink, 12) + line.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + line.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS + line.autowrap_mode = TextServer.AUTOWRAP_OFF + col.add_child(line) + col.tooltip_text = "Worked out from: %s" % expr + return col + + +## [Roll], then the dice and the last result under it. +static func _dice(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var col := VBoxContainer.new() + col.alignment = BoxContainer.ALIGNMENT_CENTER + col.add_theme_constant_override("separation", 4) + var dice := str(box.config.get("dice", "1d20")) + var b := SheetFieldViews.step_button("Roll", ink) + b.tooltip_text = "Roll %s" % dice + b.name = "Roll" + b.custom_minimum_size.y = 32 + b.size_flags_horizontal = Control.SIZE_SHRINK_CENTER + col.add_child(b) + var last := SheetFieldViews.note("%s · %s" % [dice, str(box.value) if box.value != null else "not rolled yet"], ink, 12) + last.name = "Last" + last.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + col.add_child(last) + b.pressed.connect(func() -> void: + var r := SheetValues.evaluate(ed.doc, dice, 0, ed.m.rng) + if r["error"] != "": + ed.m.toast("%s: %s" % [box.title, r["error"]]) + return + var text := "Rolled %s" % SheetValues.show(r["value"]) + last.text = "%s · %s" % [dice, text] + ed.m.toast("%s: %s (%s)" % [box.title, SheetValues.show(r["value"]), dice]) + ed.edit_value(box, text)) + return col diff --git a/ui/sheet_fields_smart.gd.uid b/ui/sheet_fields_smart.gd.uid new file mode 100644 index 0000000..e28cc2f --- /dev/null +++ b/ui/sheet_fields_smart.gd.uid @@ -0,0 +1 @@ +uid://u8e2fsopoau0 diff --git a/ui/sheet_fields_trackers.gd b/ui/sheet_fields_trackers.gd new file mode 100644 index 0000000..55db943 --- /dev/null +++ b/ui/sheet_fields_trackers.gd @@ -0,0 +1,182 @@ +class_name SheetFieldsTrackers +extends RefCounted +## Tracker boxes: current / max bars, tick boxes, clocks, dot ratings, step +## dice, usage dice and word ladders. Clicks change the value through +## SheetEditor.set_value (one undo step each). + + +static func make(ed: SheetEditor, box: SheetBox, look: Dictionary) -> Control: + var ink: Color = look["ink"] + match box.kind: + SheetKinds.RESOURCE: + return _resource(ed, box, ink) + SheetKinds.TICKS: + return _marks(ed, box, ink, int(box.config.get("count", 5)), false) + SheetKinds.DOTS: + return _marks(ed, box, ink, int(box.config.get("max", 5)), true) + SheetKinds.CLOCK: + return _clock(ed, box, ink) + SheetKinds.STEP_DIE: + return _step_die(ed, box, ink) + SheetKinds.USAGE_DIE: + return _usage_die(ed, box, ink) + return _ladder(ed, box, ink) + + +## − [bar] + and "6 / 10". +static func _resource(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var v: Dictionary = box.value if box.value is Dictionary else {"cur": 0, "max": 10} + var cur := SheetValues.number(v.get("cur", 0)) + var top := maxf(1.0, SheetValues.number(v.get("max", 10))) + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 6) + row.size_flags_vertical = Control.SIZE_SHRINK_CENTER + var set_cur := func(n: float) -> void: + var next := v.duplicate() + next["cur"] = int(clampf(n, 0, top)) + ed.set_value(box, next) + var minus := SheetFieldViews.step_button("−", ink) + minus.name = "Minus" + minus.pressed.connect(func() -> void: set_cur.call(cur - 1)) + row.add_child(minus) + var bar := Control.new() + bar.custom_minimum_size = Vector2(40, 14) + bar.size_flags_horizontal = Control.SIZE_EXPAND_FILL + bar.size_flags_vertical = Control.SIZE_SHRINK_CENTER + var fill := Color(str(box.config.get("color", "#a33a2c"))) + bar.draw.connect(func() -> void: + var r := Rect2(Vector2.ZERO, bar.size) + bar.draw_style_box(Style.box(Color(ink, 0.15), 7), r) + if cur > 0: + bar.draw_style_box(Style.box(fill, 7), Rect2(r.position, Vector2(r.size.x * clampf(cur / top, 0, 1), r.size.y)))) + row.add_child(bar) + var plus := SheetFieldViews.step_button("+", ink) + plus.name = "Plus" + plus.pressed.connect(func() -> void: set_cur.call(cur + 1)) + row.add_child(plus) + row.add_child(Style.make_label("%s / %s" % [SheetValues.show(cur), SheetValues.show(top)], Style.body_bold(), 15, ink)) + return row + + +## A row of boxes (ticks) or dots: click the n-th to mark up to it, click the +## last marked one to clear it. +static func _marks(ed: SheetEditor, box: SheetBox, ink: Color, count: int, round: bool) -> Control: + var flow := HFlowContainer.new() + flow.add_theme_constant_override("h_separation", 5) + flow.add_theme_constant_override("v_separation", 5) + var marked := int(SheetValues.number(box.value)) + for i in count: + var b := Button.new() + b.name = "Mark%d" % (i + 1) + b.focus_mode = Control.FOCUS_NONE + b.custom_minimum_size = Vector2(18, 18) + var on := i < marked + var radius := 9 if round else 3 + var sb := Style.bordered(Style.box(ink if on else Color(0, 0, 0, 0), radius), 2, ink if on else Color(ink, 0.55)) + Style.skin_button(b, sb, sb, sb, ink) + var n := i + 1 + b.pressed.connect(func() -> void: ed.set_value(box, n - 1 if n == marked else n)) + flow.add_child(b) + return flow + + +## A round clock in segments: click to fill the next one, right-click to empty one. +static func _clock(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var segments := maxi(2, int(box.config.get("segments", 6))) + var filled := int(SheetValues.number(box.value)) + var c := Control.new() + c.name = "Clock" + c.custom_minimum_size = Vector2(48, 48) + c.tooltip_text = "%d of %d · click to fill, right-click to empty" % [filled, segments] + c.draw.connect(func() -> void: + var center := c.size / 2.0 + var r := minf(c.size.x, c.size.y) / 2.0 - 3.0 + for i in segments: + var a0 := -PI / 2.0 + TAU * i / segments + var a1 := -PI / 2.0 + TAU * (i + 1) / segments + if i < filled: + var pts := PackedVector2Array([center]) + for k in 9: + pts.append(center + Vector2.from_angle(lerpf(a0, a1, k / 8.0)) * r) + c.draw_colored_polygon(pts, Color(ink, 0.85)) + c.draw_line(center, center + Vector2.from_angle(a0) * r, Color(ink, 0.6), 1.5, true) + c.draw_arc(center, r, 0, TAU, 48, ink, 2.0, true)) + c.gui_input.connect(func(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb and mb.pressed and not ed.building(): + if mb.button_index == MOUSE_BUTTON_LEFT: + ed.set_value(box, mini(filled + 1, segments)) + elif mb.button_index == MOUSE_BUTTON_RIGHT: + ed.set_value(box, maxi(filled - 1, 0))) + return c + + +## ◀ d8 ▶: steps down or up through d4 … d12. +static func _step_die(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var i := maxi(0, SheetKinds.DIE_STEPS.find(str(box.value))) + var row := HBoxContainer.new() + row.alignment = BoxContainer.ALIGNMENT_CENTER + row.add_theme_constant_override("separation", 8) + var down := SheetFieldViews.step_button("◀", ink) + down.name = "Down" + down.disabled = i == 0 + down.pressed.connect(func() -> void: ed.set_value(box, SheetKinds.DIE_STEPS[i - 1])) + row.add_child(down) + row.add_child(Style.make_label(SheetKinds.DIE_STEPS[i], Style.display(), 26, ink)) + var up := SheetFieldViews.step_button("▶", ink) + up.name = "Up" + up.disabled = i == SheetKinds.DIE_STEPS.size() - 1 + up.pressed.connect(func() -> void: ed.set_value(box, SheetKinds.DIE_STEPS[i + 1])) + row.add_child(up) + return row + + +## "d8 [Use]": rolls the die; on a 1 or 2 it shrinks a step (d4 runs out). +static func _usage_die(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var die := str(box.value) + var row := HBoxContainer.new() + row.alignment = BoxContainer.ALIGNMENT_CENTER + row.add_theme_constant_override("separation", 10) + var gone := die == "" or die == "out" + row.add_child(Style.make_label("Out" if gone else die, Style.display(), 26, ink)) + var use := SheetFieldViews.step_button("Refill" if gone else "Use", ink) + use.name = "Use" + use.pressed.connect(func() -> void: + if gone: + ed.set_value(box, "d8") + return + var sides := die.trim_prefix("d").to_int() + var rolled := ed.m.rng.randi_range(1, maxi(sides, 1)) + var i := SheetKinds.DIE_STEPS.find(die) + var next := die + if rolled <= 2: + next = SheetKinds.DIE_STEPS[i - 1] if i > 0 else "out" + ed.m.toast("%s: rolled %d on %s%s" % [box.title, rolled, die, (" · now %s" % ("out" if next == "out" else next)) if next != die else " · it holds"]) + if next != die: + ed.set_value(box, next)) + row.add_child(use) + return row + + +## ◀ Fair (+2) ▶ through the box's word steps (the Fate ladder by default). +static func _ladder(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: + var steps: Array = box.config.get("steps", SheetKinds.FATE_LADDER) + var i := clampi(int(SheetValues.number(box.value)), 0, maxi(steps.size() - 1, 0)) + var row := HBoxContainer.new() + row.alignment = BoxContainer.ALIGNMENT_CENTER + row.add_theme_constant_override("separation", 8) + var down := SheetFieldViews.step_button("◀", ink) + down.name = "Down" + down.disabled = i == 0 + down.pressed.connect(func() -> void: ed.set_value(box, i - 1)) + row.add_child(down) + var word := Style.make_label(str(steps[i]) if not steps.is_empty() else "—", Style.display(), 22, ink) + word.size_flags_horizontal = Control.SIZE_EXPAND_FILL + word.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + row.add_child(word) + var up := SheetFieldViews.step_button("▶", ink) + up.name = "Up" + up.disabled = i >= steps.size() - 1 + up.pressed.connect(func() -> void: ed.set_value(box, i + 1)) + row.add_child(up) + return row diff --git a/ui/sheet_fields_trackers.gd.uid b/ui/sheet_fields_trackers.gd.uid new file mode 100644 index 0000000..188b136 --- /dev/null +++ b/ui/sheet_fields_trackers.gd.uid @@ -0,0 +1 @@ +uid://47yieu0dij4f diff --git a/ui/sheet_inspector.gd b/ui/sheet_inspector.gd index 8d28b40..8e4cfbb 100644 --- a/ui/sheet_inspector.gd +++ b/ui/sheet_inspector.gd @@ -68,10 +68,12 @@ func _group(label: String, controls: Array) -> void: func _box_section(box: SheetBox) -> void: - _head("Box · %s" % SheetKinds.find(box.kind).get("label", box.kind), box.title if box.title != "" else "Untitled") + _head("Box · %s" % SheetKinds.label_of(box), box.title if box.title != "" else "Untitled") _group("Title", [_line("Title", box.title, func(text: String) -> void: ed.edit("Rename box", func() -> void: box.title = text, "title:" + box.id, false) ed.canvas.rebuild())]) + for g: Array in SheetKindSettings.groups(ed, box): + _group(str(g[0]), g[1]) var frameless := _check("Frameless (no card, sits on the cloth)", box.frameless, func(on: bool) -> void: ed.edit("Box frame", func() -> void: box.frameless = on)) frameless.name = "Frameless" @@ -89,7 +91,7 @@ func _box_section(box: SheetBox) -> void: order_row.add_child(order) order_row.add_child(_note("0 = auto: top to bottom, then left to right")) _group("Phone order", [order_row]) - if box.kind == SheetKinds.HEADING: + if box.kind in [SheetKinds.HEADING, SheetKinds.DIVIDER, SheetKinds.PICTURE, SheetKinds.DICE]: _delete_button() return _col.add_child(_divider()) diff --git a/ui/sheet_kind_settings.gd b/ui/sheet_kind_settings.gd new file mode 100644 index 0000000..03a2a7e --- /dev/null +++ b/ui/sheet_kind_settings.gd @@ -0,0 +1,189 @@ +class_name SheetKindSettings +extends RefCounted +## The settings each kind of box has in the inspector (Build): number limits, +## dropdown options, bar maximum, clock segments, the formula, the dice, a +## list's style, columns and point pool, slots, spell levels, XP levels, +## coins. Lists of things are typed one per line, in plain words. +## groups() returns [[label, [controls]], …] for SheetInspector. + + +static func groups(ed: SheetEditor, box: SheetBox) -> Array: + var cfg := func(label: String, change: Callable) -> void: ed.edit_config(box, label, change) + match box.kind: + SheetKinds.NUMBER: + return [["Limits", [_pair( + _line("Lowest", str(box.config.get("min", "")), func(t: String) -> void: cfg.call("Lowest", func() -> void: _set_or_clear(box, "min", t))), + _line("Highest", str(box.config.get("max", "")), func(t: String) -> void: cfg.call("Highest", func() -> void: _set_or_clear(box, "max", t))))]]] + SheetKinds.DROPDOWN, SheetKinds.CONDITIONS: + return [["Options, one per line", [_lines(box.config.get("options", []), func(rows: Array) -> void: + cfg.call("Options", func() -> void: box.config["options"] = rows))]]] + SheetKinds.RESOURCE: + var v: Dictionary = box.value if box.value is Dictionary else {"cur": 0, "max": 10} + return [["Maximum", [_line("10", SheetValues.show(v.get("max", 10)), func(t: String) -> void: + cfg.call("Maximum", func() -> void: + var next := v.duplicate() + next["max"] = maxi(1, int(SheetValues.number(t))) + next["cur"] = mini(int(SheetValues.number(next.get("cur", 0))), next["max"]) + box.value = next))]], + ["Bar colour", [ColorChoice.new(str(box.config.get("color", "")), func(hex: String) -> void: + cfg.call("Bar colour", func() -> void: box.config["color"] = hex if hex != "" else "#a33a2c"))]]] + SheetKinds.TICKS: + return [["Boxes", [_spin(ed, box, "count", 1, 40)]]] + SheetKinds.DOTS: + return [["Dots", [_spin(ed, box, "max", 1, 20)]]] + SheetKinds.CLOCK: + return [["Segments", [_spin(ed, box, "segments", 2, 24)]]] + SheetKinds.SLOTS: + return [["Slots", [_spin(ed, box, "slots", 1, 60)]]] + SheetKinds.LADDER: + return [["Steps, lowest first, one per line", [_lines(box.config.get("steps", SheetKinds.FATE_LADDER), func(rows: Array) -> void: + cfg.call("Steps", func() -> void: box.config["steps"] = rows))]]] + SheetKinds.FORMULA: + var result := SheetValues.formula(ed.doc, box) + return [["Formula", [_line("(@str - 10) / 2", str(box.config.get("expr", "")), func(t: String) -> void: + cfg.call("Formula", func() -> void: box.config["expr"] = t)), + _note("Use other boxes by their name in tables, like @str. Now: %s" % (result["error"] if result["error"] != "" else SheetValues.show(result["value"])))]]] + SheetKinds.DICE: + return [["Dice", [_line("1d20 + @str", str(box.config.get("dice", "")), func(t: String) -> void: + cfg.call("Dice", func() -> void: box.config["dice"] = t)), + _note("Dice like 2d6 plus any box by its name in tables, like @str.")]]] + SheetKinds.LIST: + return _list_groups(ed, box) + SheetKinds.SPELL_SLOTS: + var rows: Array = [] + for lv: Dictionary in box.config.get("levels", []): + rows.append("%s: %d" % [lv.get("name", ""), int(SheetValues.number(lv.get("max", 0)))]) + return [["Levels, one per line (name: slots)", [_lines(rows, func(lines: Array) -> void: + cfg.call("Spell levels", func() -> void: box.config["levels"] = _parse_pairs(lines, ":", "max")))]]] + SheetKinds.XP: + var levels: Array = box.config.get("levels", []) + return [["XP for each level, from level 1", [_line("0, 2000, 4000", ", ".join(levels.map(func(n: Variant) -> String: return SheetValues.show(n))), func(t: String) -> void: + cfg.call("XP levels", func() -> void: + var out: Array = [] + for part in t.split(",", false): + out.append(int(SheetValues.number(part))) + box.config["levels"] = out if not out.is_empty() else [0]))]]] + SheetKinds.CURRENCY: + var rows: Array = [] + for coin: Dictionary in box.config.get("coins", []): + rows.append("%s = %s" % [coin.get("name", ""), SheetValues.show(coin.get("rate", 1))]) + return [["Coins, one per line (name = worth in the first coin)", [_lines(rows, func(lines: Array) -> void: + cfg.call("Coins", func() -> void: box.config["coins"] = _parse_pairs(lines, "=", "rate")))]]] + SheetKinds.PICTURE: + var choose := ModalCard.make_button("Choose a picture…", "plain") + choose.pressed.connect(SheetFieldViews.pick_picture.bind(ed, box)) + return [["Picture", [choose]]] + return [] + + +## A list's style (Rows | Mini table | Chips), its columns and its point pool. +static func _list_groups(ed: SheetEditor, box: SheetBox) -> Array: + var seg := HBoxContainer.new() + seg.name = "ListStyle" + seg.add_theme_constant_override("separation", 3) + for pair: Array in [["rows", "Rows"], ["table", "Mini table"], ["chips", "Chips"]]: + var on: bool = str(box.config.get("style", "rows")) == pair[0] + var b := Button.new() + b.name = str(pair[0]) + b.text = pair[1] + b.focus_mode = Control.FOCUS_NONE + b.size_flags_horizontal = Control.SIZE_EXPAND_FILL + b.add_theme_font_override("font", Style.body_bold()) + b.add_theme_font_size_override("font_size", 13) + var bg := Style.box(Style.INK if on else Style.CARD_HEAD, 6, [4, 6, 4, 6]) + Style.skin_button(b, bg, bg, bg, Style.CARD if on else Style.INK) + var style: String = pair[0] + b.pressed.connect(func() -> void: ed.edit("List style", func() -> void: box.config["style"] = style)) + seg.add_child(b) + var helps := {"rows": "One thin row per entry: name on the left, value on the right.", + "table": "A row per entry, a cell per column.", "chips": "Short entries side by side, like tags."} + var col_lines: Array = [] + for c: Dictionary in SheetFieldsList.columns(box): + col_lines.append("%s (number)" % c["name"] if c.get("type", "text") == "number" else str(c["name"])) + var pool := _line("0 = no pool", SheetValues.show(box.config.get("pool", 0)), func(t: String) -> void: + ed.edit_config(box, "Point pool", func() -> void: box.config["pool"] = int(SheetValues.number(t)))) + pool.name = "PoolTotal" + var cost := _line("Cost", str(box.config.get("cost_column", "Cost")), func(t: String) -> void: + ed.edit_config(box, "Cost column", func() -> void: box.config["cost_column"] = t.strip_edges())) + return [["Style", [seg, _note(str(helps.get(str(box.config.get("style", "rows")), "")))]], + ["Columns, one per line (add “(number)” for numbers)", [_lines(col_lines, func(lines: Array) -> void: + ed.edit_config(box, "Columns", func() -> void: box.config["columns"] = _parse_columns(lines)))]], + ["Point pool", [_pair(pool, cost), _note("Each entry's cost comes off the pool. Going over is allowed and shows red.")]]] + + +static func _parse_columns(lines: Array) -> Array: + var out: Array = [] + for line: String in lines: + var number := line.to_lower().contains("(number)") + var name := line.replacen("(number)", "").strip_edges() + if name != "": + out.append({"name": name, "type": "number" if number else "text"}) + return out if not out.is_empty() else [{"name": "Name", "type": "text"}] + + +## "1st: 4" lines → [{"name": "1st", key: 4}]. +static func _parse_pairs(lines: Array, sep: String, key: String) -> Array: + var out: Array = [] + for line: String in lines: + var parts := line.split(sep, false, 1) + if parts.size() == 2 and parts[0].strip_edges() != "": + out.append({"name": parts[0].strip_edges(), key: SheetValues.number(parts[1].strip_edges())}) + return out + + +static func _set_or_clear(box: SheetBox, key: String, text: String) -> void: + if text.strip_edges() == "": + box.config.erase(key) + else: + box.config[key] = SheetFieldViews.parse_number(text, 0) + + +static func _spin(ed: SheetEditor, box: SheetBox, key: String, lo: int, hi: int) -> SpinBox: + var s := SpinBox.new() + s.name = key.capitalize() + s.min_value = lo + s.max_value = hi + s.value = SheetValues.number(box.config.get(key, lo)) + s.value_changed.connect(func(v: float) -> void: + ed.edit_config(box, key.capitalize(), func() -> void: box.config[key] = int(v))) + return s + + +static func _line(placeholder: String, text: String, on_change: Callable) -> LineEdit: + var e := LineEdit.new() + e.placeholder_text = placeholder + e.text = text + ModalCard.style_line_edit(e) + e.text_changed.connect(on_change) + return e + + +static func _lines(rows: Array, on_change: Callable) -> TextEdit: + var t := TextEdit.new() + t.name = "Lines" + t.text = "\n".join(rows.map(func(r: Variant) -> String: return str(r))) + t.custom_minimum_size.y = 96 + ModalCard.style_text_edit(t) + t.text_changed.connect(func() -> void: + var out: Array = [] + for line in t.text.split("\n", false): + if line.strip_edges() != "": + out.append(line.strip_edges()) + on_change.call(out)) + return t + + +static func _pair(a: Control, b: Control) -> HBoxContainer: + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 6) + a.size_flags_horizontal = Control.SIZE_EXPAND_FILL + b.size_flags_horizontal = Control.SIZE_EXPAND_FILL + row.add_child(a) + row.add_child(b) + return row + + +static func _note(text: String) -> Label: + var l := Style.make_label(text, Style.body(), 13, Style.MUTED) + l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + return l diff --git a/ui/sheet_kind_settings.gd.uid b/ui/sheet_kind_settings.gd.uid new file mode 100644 index 0000000..3bdf63c --- /dev/null +++ b/ui/sheet_kind_settings.gd.uid @@ -0,0 +1 @@ +uid://cq730h71f77dd