Ledger entries are saved on the card and editable on the spread

The entries were only saved values of the spread, so copies, exports and
imports lost them. Now a Ledger card lists its entries (name and starting
value) in the spread file; current values stay saved values. Build mode
edits them on the card too. Older spreads take in the entries made on the
card when they open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-14 13:36:03 -06:00
parent d9638500ba
commit edb49fce27
20 changed files with 346 additions and 55 deletions

View file

@ -323,7 +323,11 @@ static func _reset(target: String, ctx: RollContext, facts: Variant = null) -> D
static func reset_one(name: String, ctx: RollContext) -> String: static func reset_one(name: String, ctx: RollContext) -> String:
var card := ctx.declared(name) var card := ctx.declared(name)
if card == null: if card == null:
ctx.erase("@" + name) var ledger_entry := LedgerMembers.find(ctx.board, name)
if not ledger_entry.is_empty():
ctx.save("@" + name, ledger_entry["start"], (ledger_entry["card"] as RollTable).id)
else:
ctx.erase("@" + name)
return "" return ""
var r := card.initial_value(ctx) var r := card.initial_value(ctx)
ctx.save("@" + name, r["value"], card.id) ctx.save("@" + name, r["value"], card.id)

115
core/ledger_members.gd Normal file
View file

@ -0,0 +1,115 @@
class_name LedgerMembers
extends RefCounted
## A Ledger card's entries (in code: a collection variable card's `members`).
## The card lists each entry's name and starting value, so they are saved in
## the spread file and travel with copies, exports and imports. The entry's
## current value is a saved value of the spread, @<stem>_<name>, like any
## other value: these functions keep the two in step.
##
## A member is {"name": "climbing", "start": "0"}: the name is a slug (no
## spaces) and the start is text (a number or words).
## Cleans a "members" value from JSON or the UI: blank and repeated names are
## dropped, names become slugs, starts become text.
static func clean(value: Variant) -> Array:
var out: Array = []
if not (value is Array):
return out
var seen := {}
for item: Variant in value:
if not (item is Dictionary):
continue
var member_name := JsonIO.slug(str(item.get("name", "")), "")
if member_name == "" or seen.has(member_name):
continue
seen[member_name] = true
var start: Variant = item.get("start", "0")
out.append({"name": member_name, "start": "" if start == null else Expr.format_value(start)})
return out
## The saved-value name of a card's member: "skill_climbing".
static func value_name(card: RollTable, member_name: String) -> String:
return "%s_%s" % [card.var_name, member_name]
## Index of the member called `member_name` on `card`, or -1.
static func index_of(card: RollTable, member_name: String) -> int:
for i in card.members.size():
if str(card.members[i]["name"]) == member_name:
return i
return -1
## The starting value of a member, as a number when it looks like one.
static func start_value(start: String) -> Variant:
return Expr.to_value(start) if Expr.is_number(start) else start
## The Ledger card that lists the saved value `name` ("skill_climbing" or
## "@skill_climbing") and the entry's starting value: {"card", "start"}, or
## {} when no Ledger card lists it.
static func find(board: TowerBoard, name: String) -> Dictionary:
if board == null:
return {}
var bare := name.strip_edges().trim_prefix("@")
for card in board.tables:
if not card.is_collection() or card.var_name == "":
continue
for member: Dictionary in card.members:
if value_name(card, str(member["name"])) == bare:
return {"card": card, "start": start_value(str(member["start"]))}
return {}
## Older spreads kept a Ledger's entries only as saved values. A Ledger card
## with no members takes in the saved values that were made on it (source =
## the card), with their current value as the start. Values that rolls added
## (another source) are left as they are. Returns true when a card changed.
static func adopt(board: TowerBoard, persistent: Dictionary) -> bool:
if board == null:
return false
var changed := false
for card in board.tables:
if not card.is_collection() or card.var_name == "" or not card.members.is_empty():
continue
var prefix := card.var_name + "_"
var names: Array = persistent.keys()
names.sort_custom(func(left: String, right: String) -> bool: return left.naturalnocasecmp_to(right) < 0)
for saved_name: String in names:
var saved: Variant = persistent[saved_name]
if not saved_name.begins_with(prefix) or saved_name.length() <= prefix.length():
continue
if not (saved is Dictionary) or str(saved.get("source", "")) != card.id:
continue
card.members.append({"name": saved_name.substr(prefix.length()), "start": Expr.format_value(saved.get("value"))})
changed = true
return changed
## Brings the saved values in line with the Ledger cards: a member with no
## saved value gets its start, and a value made on the card (source = the
## card) whose member is gone is removed. Returns true when anything changed.
static func sync(board: TowerBoard, persistent: Dictionary) -> bool:
if board == null:
return false
var changed := false
for card in board.tables:
if not card.is_collection() or card.var_name == "":
continue
var listed := {}
for member: Dictionary in card.members:
var saved_name := value_name(card, str(member["name"]))
listed[saved_name] = true
if not persistent.has(saved_name):
persistent[saved_name] = {"value": start_value(str(member["start"])), "source": card.id}
changed = true
if card.members.is_empty():
continue
for saved_name: String in persistent.keys():
var saved: Variant = persistent[saved_name]
if saved_name.begins_with(card.var_name + "_") and not listed.has(saved_name) and saved is Dictionary and str(saved.get("source", "")) == card.id:
persistent.erase(saved_name)
changed = true
return changed

View file

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

View file

@ -9,13 +9,19 @@ extends RefCounted
## A variable card that says "starts at …" gives its variable that value ## A variable card that says "starts at …" gives its variable that value
## the first time a roll needs it: before a top-level roll, each declared ## the first time a roll needs it: before a top-level roll, each declared
## variable that isn't set yet and has a starting value is set to it (and ## variable that isn't set yet and has a starting value is set to it (and
## saved like any other change). Variables with no starting value stay unset, ## saved like any other change). Variables with no starting value stay unset.
## and collections are left alone. ## Ledger entries that aren't set get their starting value the same way.
static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void: static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void:
if board == null: if board == null:
return return
for table in board.tables: for table in board.tables:
if table.kind != RollTable.KIND_VARIABLE or table.is_collection() or table.var_name == "": if table.is_collection() and table.var_name != "":
for member: Dictionary in table.members:
var member_value := "@" + LedgerMembers.value_name(table, str(member["name"]))
if ctx.get_value(member_value) == null:
ctx.save(member_value, LedgerMembers.start_value(str(member["start"])), table.id)
continue
if table.kind != RollTable.KIND_VARIABLE or table.var_name == "":
continue continue
if table.initial.strip_edges() == "" or ctx.get_value("@" + table.var_name) != null: if table.initial.strip_edges() == "" or ctx.get_value("@" + table.var_name) != null:
continue continue

View file

@ -120,6 +120,8 @@ var var_type: String = "number"
var initial: String = "" var initial: String = ""
## Scale variables: the ordered steps, lowest first. ## Scale variables: the ordered steps, lowest first.
var steps: Array[String] = [] var steps: Array[String] = []
## Ledger cards: the entries, [{name, start}] (LedgerMembers).
var members: Array = []
## Check cards: the dice, the modifier and the target (expressions) and the ## Check cards: the dice, the modifier and the target (expressions) and the
## comparison ("ge" or "le"). entries[0] is Success, entries[1] Failure. ## comparison ("ge" or "le"). entries[0] is Success, entries[1] Failure.
var check_dice: String = CHECK_DEFAULT_DICE var check_dice: String = CHECK_DEFAULT_DICE

View file

@ -72,6 +72,8 @@ static func to_dict(t: RollTable) -> Dictionary:
d["initial"] = t.initial d["initial"] = t.initial
if t.var_type == RollTable.VAR_SCALE and not t.steps.is_empty(): if t.var_type == RollTable.VAR_SCALE and not t.steps.is_empty():
d["steps"] = t.steps.duplicate() d["steps"] = t.steps.duplicate()
if t.is_collection() and not t.members.is_empty():
d["members"] = t.members.duplicate(true)
elif t.kind == RollTable.KIND_CHECK: elif t.kind == RollTable.KIND_CHECK:
if t.check_dice != RollTable.CHECK_DEFAULT_DICE: if t.check_dice != RollTable.CHECK_DEFAULT_DICE:
d["check_dice"] = t.check_dice d["check_dice"] = t.check_dice
@ -135,6 +137,7 @@ static func from_dict(d: Dictionary) -> RollTable:
t.var_type = vt if RollTable.VAR_TYPES.has(vt) else "number" t.var_type = vt if RollTable.VAR_TYPES.has(vt) else "number"
t.initial = RollTable.expr_text(d.get("initial", ""), "") t.initial = RollTable.expr_text(d.get("initial", ""), "")
t.steps = Scales.clean(d.get("steps", [])) t.steps = Scales.clean(d.get("steps", []))
t.members = LedgerMembers.clean(d.get("members", []))
t.check_dice = RollTable.expr_text(d.get("check_dice", RollTable.CHECK_DEFAULT_DICE), RollTable.CHECK_DEFAULT_DICE).strip_edges() t.check_dice = RollTable.expr_text(d.get("check_dice", RollTable.CHECK_DEFAULT_DICE), RollTable.CHECK_DEFAULT_DICE).strip_edges()
if t.check_dice == "": if t.check_dice == "":
t.check_dice = RollTable.CHECK_DEFAULT_DICE t.check_dice = RollTable.CHECK_DEFAULT_DICE

View file

@ -378,6 +378,11 @@ when the expression has modifiers.
label members by the rest of their name ("Gun Combat") and the group by the card's name. label members by the rest of their name ("Gun Combat") and the group by the card's name.
`RollTable.create("variable", id, "Skills", "collection")` gives the stem `skill` (the name's `RollTable.create("variable", id, "Skills", "collection")` gives the stem `skill` (the name's
slug without a final "s"). Its live display lists the set members. slug without a final "s"). Its live display lists the set members.
The card's `members` ([{name, start}], `LedgerMembers`, since 2026-11-14) are its entries, saved
in the spread file: each gets its start the first time it's needed (like a variable's
`initial`), and `reset` puts it back to the start. Members added by rules (another source)
stay saved values only. Older spreads: a Ledger card with no `members` takes in the saved
values whose source is the card when the spread opens.
- **Results saved into a list.** A thread's or column's "save as", a choice's `save_as` and - **Results saved into a list.** A thread's or column's "save as", a choice's `save_as` and
an inline `[[Table -> @x]]` normally replace the value. When a list card (`var_type: an inline `[[Table -> @x]]` normally replace the value. When a list card (`var_type:
"list"`) declares it, the saved text is **added** as an item instead (each item once, "list"`) declares it, the saved text is **added** as an item instead (each item once,

View file

@ -52,7 +52,8 @@ than". `>= N` reads "is N or more" when it sits after a value name.
- **Collection** is a variable card with `var_type: "collection"`. Its `var_name` is the stem - **Collection** is a variable card with `var_type: "collection"`. Its `var_name` is the stem
(e.g. `skill`), its name is the label ("Skills"), and its members are the board values (e.g. `skill`), its name is the label ("Skills"), and its members are the board values
`@<stem>_<item>`. `@<stem>_<item>`.
- On the board it shows a list editor: members with their values, plus "+ Add". - In Build the card shows its entries as fields (name, starting value, ×) plus "+ Add";
Play shows the live values. Entries are saved on the card (`members`, LOGIC.md).
- `options_from: "@skill_*"` reads "your Skills". - `options_from: "@skill_*"` reads "your Skills".
- `count("skill_")` and `{@skill_*}` work as before. - `count("skill_")` and `{@skill_*}` work as before.
- `Describe` uses the collection to label its members. - `Describe` uses the collection to label its members.

View file

@ -128,7 +128,7 @@ An option can have [b]Show only if[/b], so it's offered only when a condition is
A spread can remember [b]values[/b] between rolls, such as Luck, Gold or the current town. In rules a value is written with @: `@luck`. A spread can remember [b]values[/b] between rolls, such as Luck, Gold or the current town. In rules a value is written with @: `@luck`.
- Any result can have [b]changes[/b] that happen when it comes up: [b]Add 1 to Luck[/b], [b]Subtract 3 from Gold[/b], [b]Set Town to …[/b]. Edit them in the inspector as rows, or with Edit as text. - Any result can have [b]changes[/b] that happen when it comes up: [b]Add 1 to Luck[/b], [b]Subtract 3 from Gold[/b], [b]Set Town to …[/b]. Edit them in the inspector as rows, or with Edit as text.
- A [b]Variable[/b] card gives a value a name, a type and a starting value, and shows what it is now. The sample's [b]Luck[/b] card starts at 0. - A [b]Variable[/b] card gives a value a name, a type and a starting value, and shows what it is now. The sample's [b]Luck[/b] card starts at 0.
- A [b]Ledger[/b] card groups related values, such as Skills, so they can be listed and picked from together. - A [b]Ledger[/b] card groups related values, such as Skills, so they can be listed and picked from together. In Build mode, add and rename its entries right on the card; each entry's number is where it starts.
- The tray's [b]Variables[/b] tab shows every value, and lets you clear or reset them. [b]Reset all…[/b] puts every value back to its start. - The tray's [b]Variables[/b] tab shows every value, and lets you clear or reset them. [b]Reset all…[/b] puts every value back to its start.
## Writing changes as text ## Writing changes as text

View file

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

View file

@ -350,6 +350,22 @@ func _test_collection() -> void:
InspectorCard.remove_member(insp, t, "gun_combat") InspectorCard.remove_member(insp, t, "gun_combat")
_eq(insp.members(t), [["pilot", "2"]], "× removes a member") _eq(insp.members(t), [["pilot", "2"]], "× removes a member")
_eq(Describe.label("@skill_pilot", main.data), "Pilot", "(members are labelled through the spread)") _eq(Describe.label("@skill_pilot", main.data), "Pilot", "(members are labelled through the spread)")
_eq(t.members, [{"name": "pilot", "start": "2"}], "the entries are saved on the card")
var copy := RollTable.from_dict(t.to_dict())
_eq(copy.members, t.members, "and survive a save and load (copies, exports)")
main.persistent_vars["skill_pilot"] = {"value": 5, "source": "roll"}
main.reset_variable("skill_pilot")
_eq(main.persistent_vars.get("skill_pilot", {}).get("value"), 2, "Reset puts an entry back to its start")
main.undo_redo.undo()
_eq(t.members, [{"name": "pilot", "start": "2"}, {"name": "gun_combat", "start": "0"}], "undo brings a removed entry back")
_eq(main.persistent_vars.get("skill_gun_combat", {}).get("value"), 0, "with its value")
main.undo_redo.redo()
var old := RollTable.create(RollTable.KIND_VARIABLE, "old_ledger", "Feats", RollTable.VAR_COLLECTION)
var made := {"feat_dodge": {"value": 3, "source": "old_ledger"}, "feat_luck": {"value": 1, "source": "a_roll"}}
var board := TowerBoard.new()
board.tables.append(old)
_check(LedgerMembers.adopt(board, made), "an older Ledger takes in the entries made on it")
_eq(old.members, [{"name": "dodge", "start": "3"}], "but not values that rolls added")
await _frames() await _frames()

View file

@ -379,8 +379,11 @@ func _test_build_rows() -> void:
var adds := _with_meta(main.card_for("skills"), "collection_add") var adds := _with_meta(main.card_for("skills"), "collection_add")
_check(adds.size() == 1 and (adds[0] as Button).text == "+ Add skill", "the spread card has + Add skill in Build") _check(adds.size() == 1 and (adds[0] as Button).text == "+ Add skill", "the spread card has + Add skill in Build")
if adds.size() == 1: if adds.size() == 1:
var before: int = main.data.get_table("skills").members.size()
(adds[0] as Button).emit_signal("pressed") (adds[0] as Button).emit_signal("pressed")
_eq(main.get("picked").back(), ["card", "skills"], "+ Add selects the card for the inspector") _eq(main.data.get_table("skills").members.size(), before + 1, "+ Add adds an entry right on the card")
var fields := _with_meta(main.card_for("skills"), "ledger_name")
_check(fields.size() == before + 1, "each entry is a name field on the card in Build")
_check(_has(main.card_for("loot"), "Input Tier · starts at 1"), "the inputs box shows in Build too") _check(_has(main.card_for("loot"), "Input Tier · starts at 1"), "the inputs box shows in Build too")
main.set_mode(Main.Mode.PLAY) main.set_mode(Main.Mode.PLAY)
await process_frame await process_frame

View file

@ -1,8 +1,8 @@
class_name InspectorCollection class_name InspectorCollection
extends RefCounted extends RefCounted
## The ledger (collection) card's part of the inspector: the name its members ## The Ledger (collection) card's part of the inspector: the name its entries
## share, and the list of members with their values, which you can rename, ## share, and the entries with their starting values, which you can rename,
## change, remove or add to. InspectorCard.build() calls build() for ledgers. ## change, remove or add to (LedgerEdits). InspectorCard.build() calls build() for ledgers.
static func build(insp: Inspector, box: VBoxContainer, card: RollTable) -> void: static func build(insp: Inspector, box: VBoxContainer, card: RollTable) -> void:
@ -13,29 +13,27 @@ static func build(insp: Inspector, box: VBoxContainer, card: RollTable) -> void:
box.add_child(InspectorKit.note("Each member is the value @%s_<name>, e.g. @%s_pilot. Choices can offer “one of your %s”." % [card.var_name, card.var_name, Inspector._title_of(card.name, "members")], Style.MUTED, 13)) box.add_child(InspectorKit.note("Each member is the value @%s_<name>, e.g. @%s_pilot. Choices can offer “one of your %s”." % [card.var_name, card.var_name, Inspector._title_of(card.name, "members")], Style.MUTED, 13))
var column := InspectorKit.vbox(5) var column := InspectorKit.vbox(5)
var list := insp.members(card) insp.fields["members"] = insp.members(card)
insp.fields["members"] = list if card.members.is_empty():
if list.is_empty(): column.add_child(InspectorKit.note("No entries yet.", Style.MUTED, 14))
column.add_child(InspectorKit.note("No members yet.", Style.MUTED, 14))
var grid := GridContainer.new() var grid := GridContainer.new()
grid.columns = 3 grid.columns = 3
grid.add_theme_constant_override("h_separation", 6) grid.add_theme_constant_override("h_separation", 6)
grid.add_theme_constant_override("v_separation", 5) grid.add_theme_constant_override("v_separation", 5)
for pair: Array in list: for member: Dictionary in card.members:
_member_row(insp, card, grid, pair) _member_row(insp, card, grid, member)
column.add_child(grid) column.add_child(grid)
var add := InspectorKit.link("+ Add member") var add := InspectorKit.link("+ Add entry")
add.pressed.connect(func() -> void: add_member(insp, card)) add.pressed.connect(func() -> void: add_member(insp, card))
column.add_child(add) column.add_child(add)
column.add_child(InspectorKit.note("Members are saved values of this spread, like the Variables panel shows; they aren't part of undo.", Style.MUTED, 12)) column.add_child(InspectorKit.note("Each entry's number here is where it starts. Rolls change the current value; Reset puts it back.", Style.MUTED, 12))
box.add_child(InspectorKit.field("Members", column)) box.add_child(InspectorKit.field("Entries", column))
box.add_child(err) box.add_child(err)
## Adds one member's name field, value field and remove button to `grid`. ## Adds one entry's name field, starting-value field and remove button to `grid`.
## `pair` is [item, value]. static func _member_row(insp: Inspector, card: RollTable, grid: GridContainer, member: Dictionary) -> void:
static func _member_row(insp: Inspector, card: RollTable, grid: GridContainer, pair: Array) -> void: var item := str(member["name"])
var item := str(pair[0])
var name_field := InspectorKit.line(RollContext.pretty_name(item), item, 0.0) var name_field := InspectorKit.line(RollContext.pretty_name(item), item, 0.0)
name_field.size_flags_horizontal = Control.SIZE_EXPAND_FILL name_field.size_flags_horizontal = Control.SIZE_EXPAND_FILL
name_field.tooltip_text = "@%s_%s" % [card.var_name, item] name_field.tooltip_text = "@%s_%s" % [card.var_name, item]
@ -48,47 +46,36 @@ static func _member_row(insp: Inspector, card: RollTable, grid: GridContainer, p
name_field.text_submitted.connect(func(_text: String) -> void: commit_name.call()) name_field.text_submitted.connect(func(_text: String) -> void: commit_name.call())
name_field.focus_exited.connect(commit_name) name_field.focus_exited.connect(commit_name)
grid.add_child(name_field) grid.add_child(name_field)
var value_field := InspectorKit.amount(str(pair[1]), "0") var value_field := InspectorKit.amount(str(member["start"]), "0")
value_field.tooltip_text = "Where this entry starts"
InspectorKit.tag(value_field, "member.%s.value" % item) InspectorKit.tag(value_field, "member.%s.value" % item)
var commit_value := func() -> void: var commit_value := func() -> void:
if value_field.text.strip_edges() != str(pair[1]): set_member(insp, card, item, value_field.text)
set_member(insp, card, item, value_field.text.strip_edges())
value_field.text_submitted.connect(func(_text: String) -> void: commit_value.call()) value_field.text_submitted.connect(func(_text: String) -> void: commit_value.call())
value_field.focus_exited.connect(commit_value) value_field.focus_exited.connect(commit_value)
grid.add_child(value_field) grid.add_child(value_field)
var remove_button := InspectorKit.xbutton("Remove this member") var remove_button := InspectorKit.xbutton("Remove this entry")
remove_button.pressed.connect(func() -> void: remove_member(insp, card, item)) remove_button.pressed.connect(func() -> void: remove_member(insp, card, item))
grid.add_child(remove_button) grid.add_child(remove_button)
static func set_member(insp: Inspector, card: RollTable, item: String, value: String) -> void: static func set_member(insp: Inspector, card: RollTable, item: String, value: String) -> void:
insp.main.set_collection_member(card, item, value) LedgerEdits.set_start(insp.main, card, item, value)
insp.rebuild() insp.rebuild()
static func rename_member(insp: Inspector, card: RollTable, old_item: String, new_item: String) -> void: static func rename_member(insp: Inspector, card: RollTable, old_item: String, new_item: String) -> void:
var current: Variant = insp.main.persistent_vars.get("%s_%s" % [card.var_name, old_item]) LedgerEdits.rename(insp.main, card, old_item, new_item)
var value := Expr.format_value(current.get("value") if current is Dictionary else current)
insp.main.remove_collection_member(card, old_item)
insp.main.set_collection_member(card, new_item, value)
insp.rebuild() insp.rebuild()
static func remove_member(insp: Inspector, card: RollTable, item: String) -> void: static func remove_member(insp: Inspector, card: RollTable, item: String) -> void:
insp.main.remove_collection_member(card, item) LedgerEdits.remove(insp.main, card, item)
insp.rebuild() insp.rebuild()
static func add_member(insp: Inspector, card: RollTable) -> String: static func add_member(insp: Inspector, card: RollTable) -> String:
var used := {} var item := LedgerEdits.add(insp.main, card)
for pair: Array in insp.members(card):
used[str(pair[0])] = true
var item := "new"
var number := 2
while used.has(item):
item = "new_%d" % number
number += 1
insp.main.set_collection_member(card, item, "0")
insp.rebuild() insp.rebuild()
var name_field := InspectorKit.find_tagged(insp, "member.%s.name" % item) as LineEdit var name_field := InspectorKit.find_tagged(insp, "member.%s.name" % item) as LineEdit
if name_field and name_field.is_inside_tree(): if name_field and name_field.is_inside_tree():

67
ui/ledger_card_rows.gd Normal file
View file

@ -0,0 +1,67 @@
class_name LedgerCardRows
extends RefCounted
## A Ledger card's entries in Build mode, on the spread: a name field, a
## starting-value field and × for each entry, so the entries can be edited on
## the card as well as in the inspector. Edits go through LedgerEdits.
## Fills `box` with one editable row per entry of the card's table.
static func fill(card: TableCard, box: VBoxContainer) -> void:
var table := card.table
if table.members.is_empty():
var none := Style.make_label("No entries yet", Style.body_italic(true), 14, Style.MUTED)
none.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(none)
return
for member: Dictionary in table.members:
box.add_child(_row(card, str(member["name"]), str(member["start"])))
static func _row(card: TableCard, member_name: String, start: String) -> HBoxContainer:
var main := card.main
var table := card.table
var row := TableCard.hbox(6)
row.custom_minimum_size = Vector2(0, 30)
row.set_meta("member", "@" + LedgerMembers.value_name(table, member_name))
var name_field := InspectorKit.line(RollContext.pretty_name(member_name), member_name, 0.0)
name_field.size_flags_horizontal = Control.SIZE_EXPAND_FILL
name_field.tooltip_text = "@" + LedgerMembers.value_name(table, member_name)
name_field.set_meta("ledger_name", member_name)
var commit_name := func() -> void:
LedgerEdits.rename(main, table, member_name, name_field.text)
name_field.text_submitted.connect(func(_text: String) -> void: commit_name.call())
name_field.focus_exited.connect(commit_name)
row.add_child(name_field)
var start_field := InspectorKit.amount(start, "0")
start_field.tooltip_text = "Where this entry starts"
var commit_start := func() -> void:
LedgerEdits.set_start(main, table, member_name, start_field.text)
start_field.text_submitted.connect(func(_text: String) -> void: commit_start.call())
start_field.focus_exited.connect(commit_start)
row.add_child(start_field)
var remove_button := InspectorKit.xbutton("Remove this entry")
remove_button.pressed.connect(func() -> void: LedgerEdits.remove(main, table, member_name))
row.add_child(remove_button)
return row
## Adds an entry to the card's table and puts the cursor in its name field.
static func add_and_focus(main: Main, table: RollTable) -> void:
var member_name := LedgerEdits.add(main, table)
var card := main.card_for(table.id)
if card == null:
return
var field := _find_name_field(card, member_name)
if field and field.is_inside_tree():
field.grab_focus()
field.select_all()
static func _find_name_field(node: Node, member_name: String) -> LineEdit:
for child in node.get_children():
if child is LineEdit and str(child.get_meta("ledger_name", "")) == member_name:
return child
var found := _find_name_field(child, member_name)
if found:
return found
return null

View file

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

61
ui/ledger_edits.gd Normal file
View file

@ -0,0 +1,61 @@
class_name LedgerEdits
extends RefCounted
## Build-mode edits to a Ledger card's entries, shared by the inspector and
## the card on the spread. Each edit changes the card (so it is saved with
## the spread and can be undone) and the entry's current value together.
## The entries themselves: LedgerMembers.
## Adds an entry called "new" (or "new_2", …) starting at 0. Returns its name.
static func add(main: Main, card: RollTable) -> String:
var member_name := "new"
var number := 2
while LedgerMembers.index_of(card, member_name) >= 0 or main.persistent_vars.has(LedgerMembers.value_name(card, member_name)):
member_name = "new_%d" % number
number += 1
card.members.append({"name": member_name, "start": "0"})
main.persistent_vars[LedgerMembers.value_name(card, member_name)] = {"value": 0, "source": card.id}
_done(main, card, "Add a Ledger entry")
return member_name
## Renames an entry; its current value moves with it. `new_name` is made a
## slug; nothing happens if it's empty or already used.
static func rename(main: Main, card: RollTable, old_name: String, new_name: String) -> void:
var slug := JsonIO.slug(new_name, "")
var at := LedgerMembers.index_of(card, old_name)
if at < 0 or slug == "" or slug == old_name or LedgerMembers.index_of(card, slug) >= 0:
return
card.members[at]["name"] = slug
var old_value_name := LedgerMembers.value_name(card, old_name)
var saved: Variant = main.persistent_vars.get(old_value_name)
main.persistent_vars.erase(old_value_name)
if saved != null:
main.persistent_vars[LedgerMembers.value_name(card, slug)] = saved
_done(main, card, "Rename a Ledger entry")
## Sets an entry's starting value, and its current value to match.
static func set_start(main: Main, card: RollTable, member_name: String, start: String) -> void:
var at := LedgerMembers.index_of(card, member_name)
var text := start.strip_edges()
if at < 0 or text == str(card.members[at]["start"]):
return
card.members[at]["start"] = text
main.persistent_vars[LedgerMembers.value_name(card, member_name)] = {"value": LedgerMembers.start_value(text), "source": card.id}
_done(main, card, "Change a Ledger entry")
## Removes an entry and its current value.
static func remove(main: Main, card: RollTable, member_name: String) -> void:
var at := LedgerMembers.index_of(card, member_name)
if at >= 0:
card.members.remove_at(at)
main.persistent_vars.erase(LedgerMembers.value_name(card, member_name))
_done(main, card, "Remove a Ledger entry")
static func _done(main: Main, card: RollTable, label: String) -> void:
main.inspector_edited(card.id)
main.mark_dirty(label)
main.local_state._variables_changed()

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

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

View file

@ -209,6 +209,7 @@ func _apply_history(e: Dictionary, verb: String) -> void:
m._rebuild_cards() m._rebuild_cards()
_keep_history = false _keep_history = false
_restoring = false _restoring = false
m.local_state._sync_ledgers()
m._board_changed() m._board_changed()
m._refresh_lit() m._refresh_lit()
m.tray.render() m.tray.render()

View file

@ -27,9 +27,12 @@ func load_local_state() -> void:
m.lit_texts.clear() m.lit_texts.clear()
m.lit_columns.clear() m.lit_columns.clear()
_ref_cache.clear() _ref_cache.clear()
if m.data != null and m.state == null:
LedgerMembers.sync(m.data, m.persistent_vars)
if m.state == null or m.data == null: if m.state == null or m.data == null:
return return
m.persistent_vars = m.state.get_variables(m.data.id) m.persistent_vars = m.state.get_variables(m.data.id)
_sync_ledgers()
for t in m.data.tables: for t in m.data.tables:
var d := m.state.get_deck(m.data.id, t.id) var d := m.state.get_deck(m.data.id, t.id)
if not d.is_empty(): if not d.is_empty():
@ -219,8 +222,21 @@ func reset_all_variables() -> void:
m.toast("Reset every variable") m.toast("Reset every variable")
## Older spreads: Ledger cards take in the entries kept only as saved values
## (and the spread is saved with them). Then every Ledger entry gets a saved
## value. See LedgerMembers.
func _sync_ledgers() -> void:
if LedgerMembers.adopt(m.data, m.persistent_vars) and m.library and m.state:
m.library.save(m.data)
if LedgerMembers.sync(m.data, m.persistent_vars):
_store_variables()
if m.state:
m.state.save()
## Saves the variables and re-renders what shows them. ## Saves the variables and re-renders what shows them.
func _variables_changed() -> void: func _variables_changed() -> void:
LedgerMembers.sync(m.data, m.persistent_vars)
_store_variables() _store_variables()
if m.state: if m.state:
m.state.save() m.state.save()

View file

@ -13,6 +13,8 @@ var steps_cache := ""
## Collection cards: the member list, refilled by refresh(). ## Collection cards: the member list, refilled by refresh().
var members_box: VBoxContainer var members_box: VBoxContainer
var members_cache := "" var members_cache := ""
## Collection cards in Build: the entries show as fields you can edit.
var members_editable := false
func _init(p_card: TableCard) -> void: func _init(p_card: TableCard) -> void:
@ -27,6 +29,7 @@ func clear() -> void:
steps_cache = "" steps_cache = ""
members_box = null members_box = null
members_cache = "" members_cache = ""
members_editable = false
## A variable card's body: its live value, big, and in Build its starting value ## A variable card's body: its live value, big, and in Build its starting value
@ -78,9 +81,8 @@ func make_variable_body(build: bool) -> Control:
return wrap return wrap
## A collection card's body: its members with their live values (refilled by ## A collection (Ledger) card's body: its entries with their live values
## refresh()), and in Build "+ Add …", which selects the card so the ## (refilled by refresh()); in Build, fields to edit them and "+ Add …".
## inspector can add a member.
func make_collection_body(build: bool) -> Control: func make_collection_body(build: bool) -> Control:
var table := card.table var table := card.table
var main := card.main var main := card.main
@ -92,19 +94,15 @@ func make_collection_body(build: bool) -> Control:
wrap.add_theme_constant_override("margin_bottom", 10) wrap.add_theme_constant_override("margin_bottom", 10)
var v := TableCard.vbox(6) var v := TableCard.vbox(6)
wrap.add_child(v) wrap.add_child(v)
members_box = TableCard.vbox(0) members_box = TableCard.vbox(4 if build else 0)
members_editable = build
v.add_child(members_box) v.add_child(members_box)
if build: if build:
var add := TableCardEditing.footer_button("+ Add " + Describe._singular(Formatter.strip_tags(table.name).strip_edges().to_lower()), Style.INK) var add := TableCardEditing.footer_button("+ Add " + Describe._singular(Formatter.strip_tags(table.name).strip_edges().to_lower()), Style.INK)
add.size_flags_horizontal = Control.SIZE_FILL add.size_flags_horizontal = Control.SIZE_FILL
add.tooltip_text = "Add a member in the inspector" add.tooltip_text = "Add an entry to this Ledger"
add.set_meta("collection_add", true) add.set_meta("collection_add", true)
add.pressed.connect(func() -> void: add.pressed.connect(func() -> void: LedgerCardRows.add_and_focus(main, table))
if main.has_method("select_card"):
main.call("select_card", table.id)
else:
main.request_table_settings(table.id)
)
v.add_child(add) v.add_child(add)
return wrap return wrap
@ -136,13 +134,16 @@ static func collection_members(t: RollTable, board: TowerBoard, vars: Dictionary
func _refresh_members() -> void: func _refresh_members() -> void:
var plain := card.plain var plain := card.plain
var list := collection_members(card.table, card.main.data, card.main.persistent_vars) var list := collection_members(card.table, card.main.data, card.main.persistent_vars)
var key := var_to_str(list) + str(plain) var key := (var_to_str(card.table.members) + "build") if members_editable else var_to_str(list) + str(plain)
if key == members_cache: if key == members_cache:
return return
members_cache = key members_cache = key
for c in members_box.get_children(): for c in members_box.get_children():
members_box.remove_child(c) members_box.remove_child(c)
c.queue_free() c.queue_free()
if members_editable:
LedgerCardRows.fill(card, members_box)
return
if list.is_empty(): if list.is_empty():
var none := Style.make_label("No members yet", Style.body_italic(true), 14, Style.MUTED) var none := Style.make_label("No members yet", Style.body_italic(true), 14, Style.MUTED)
none.mouse_filter = Control.MOUSE_FILTER_IGNORE none.mouse_filter = Control.MOUSE_FILTER_IGNORE