TableTower/ui/why_popover.gd

198 lines
6.4 KiB
GDScript3
Raw Normal View History

class_name WhyPopover
extends PanelContainer
## "Why this?" (docs/PLAIN.md §4.4, §6): a card-styled pop-over listing why a
## step of the last roll came out the way it did, one Describe.why() sentence
## per trace fact.
##
## A step's own facts (its inputs, roll or check, router cases, effects) come
## with the facts its parent step recorded about the pipe that led here: the
## "only if" / "otherwise" choices aimed at this card, and the parent's
## effects on the values those conditions read. Steps from old history
## records have no facts, so they get no button (has_why() is false).
##
## Opened by ResultTray's "Why this?" buttons; it sits above the button, closes
## on Esc, on a click outside it, or on the button again. The same lines show
## in hover pop-ups (DetailsPopup.why_bbcode()).
const WIDTH := 460.0
var _title: Label
var _list: RichTextLabel
## The control that opened it (a second press on it closes).
var opener: Control
## Lines shown, for tests.
var lines: PackedStringArray = []
func _init() -> void:
top_level = true
z_index = 90
mouse_filter = MOUSE_FILTER_STOP
var sb := Style.box(Style.CARD, 9, [14, 10, 14, 12])
Style.bordered(sb, 2, Style.ACCENT)
sb.shadow_color = Color(0, 0, 0, 0.4)
sb.shadow_size = 16
sb.shadow_offset = Vector2(0, 6)
add_theme_stylebox_override("panel", sb)
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 6)
v.mouse_filter = MOUSE_FILTER_IGNORE
add_child(v)
v.minimum_size_changed.connect(func() -> void: _place.call_deferred())
_title = Style.make_label("", Style.caps(), 12, Style.MUTED)
_title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_title.custom_minimum_size = Vector2(WIDTH, 0)
_title.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_title)
_list = RichText.label("", 15, Style.INK, false)
_list.custom_minimum_size = Vector2(WIDTH, 0)
_list.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_list)
hide()
## Shows the reasons for steps[index] above (or below) `at` (a global rect),
## or above `anchor` while it's on screen (it follows it as it moves).
func open(steps: Array, index: int, board: TowerBoard, plain: bool, at: Rect2, from: Control = null, anchor: Control = null) -> void:
opener = from
_anchor = anchor
lines = why_lines(steps, index, board, plain)
_title.text = title_for(steps[index]).to_upper()
_list.text = bbcode_list(lines)
_at = at
show()
_place()
# The list's height is known only after layout, so place it again then.
_place.call_deferred()
var _at := Rect2()
var _anchor: Control
func _place() -> void:
if not visible:
return
reset_size()
if _anchor != null and is_instance_valid(_anchor) and _anchor.is_visible_in_tree():
_at = _anchor.get_global_rect()
var view := get_viewport_rect().size
var p := Vector2(_at.position.x, _at.position.y - size.y - 8.0)
if p.y < 8.0:
p.y = _at.end.y + 8.0
p.x = clampf(p.x, 8.0, maxf(8.0, view.x - size.x - 8.0))
global_position = p
## Keeps it placed while its text settles (a RichTextLabel learns its height
## a frame or two after it's filled).
func _process(_delta: float) -> void:
if visible:
_place()
func close() -> void:
opener = null
_anchor = null
hide()
func _input(ev: InputEvent) -> void:
if not visible:
return
var k := ev as InputEventKey
if k and k.pressed and k.keycode == KEY_ESCAPE:
close()
get_viewport().set_input_as_handled()
return
var mb := ev as InputEventMouseButton
if mb and mb.pressed and not get_global_rect().has_point(mb.global_position):
if opener != null and is_instance_valid(opener) and opener.get_global_rect().has_point(mb.global_position):
return # the button toggles it itself
close()
# ---------- Content (static, testable) ----------
## "Why Loot · A curio"
static func title_for(step: Dictionary) -> String:
var t := Formatter.strip_tags(str(step.get("table", ""))).strip_edges()
var s := Formatter.strip_tags(str(step.get("text", ""))).strip_edges().replace("\n", " ")
if s.length() > 48:
s = s.substr(0, 47).strip_edges() + "…"
return "Why %s · %s" % [t, s] if s != "" else "Why " + t
## True when steps[index] has something to explain.
static func has_why(steps: Array, index: int) -> bool:
return not facts_for(steps, index).is_empty()
## The facts that explain steps[index]: [[fact, prefix], ...]. The parent's
## facts come first (pipe choices aimed at this step's card, and its effects
## on the values they read, prefixed with the parent's text), then the step's
## own.
static func facts_for(steps: Array, index: int) -> Array:
var out: Array = []
if index < 0 or index >= steps.size():
return out
var step: Dictionary = steps[index]
var tid := str(step.get("table_id", ""))
var d := int(step.get("depth", 0))
var parent: Dictionary = {}
if d > 0:
for k in range(index - 1, -1, -1):
var s: Dictionary = steps[k]
if int(s.get("depth", 0)) == d - 1:
parent = s
break
if not parent.is_empty() and parent.get("why") is Array:
var pipe_facts: Array = []
var read := {}
for f: Variant in parent["why"]:
if not (f is Dictionary):
continue
var ty := str(f.get("type", ""))
if (ty == "when" or ty == "otherwise") and str(f.get("to", "")) == tid:
pipe_facts.append(f)
if f.get("values") is Dictionary:
for nm: Variant in f["values"]:
read[str(nm)] = true
if not pipe_facts.is_empty():
var who := Formatter.strip_tags(str(parent.get("text", ""))).strip_edges().replace("\n", " ")
if who.length() > 40:
who = who.substr(0, 39).strip_edges() + "…"
for f: Variant in parent["why"]:
if f is Dictionary and str(f.get("type", "")) == "effect" and read.has(str(f.get("var", ""))):
out.append([f, who])
for f: Variant in pipe_facts:
out.append([f, ""])
if step.get("why") is Array:
for f: Variant in step["why"]:
if f is Dictionary:
out.append([f, ""])
return out
## One sentence per fact, ending in a full stop.
static func why_lines(steps: Array, index: int, board: TowerBoard, plain: bool) -> PackedStringArray:
var out := PackedStringArray()
for pair: Array in facts_for(steps, index):
var s := Describe.why(pair[0], board, plain).strip_edges()
if s == "":
continue
if str(pair[1]) != "":
s = "%s: %s" % [pair[1], s]
if plain and not (s.ends_with(".") or s.ends_with("…")):
s += "."
out.append(s)
return out
## The lines as a BBCode bullet list (text escaped).
static func bbcode_list(ls: PackedStringArray) -> String:
var parts := PackedStringArray()
for l in ls:
parts.append("• " + RichText.plain(l))
return "\n".join(parts)