TableTower/ui/board_search.gd
RobinFiredrake 7dca1f2c3b Big-board navigation: search, focus_table, minimap, pack, lazy cards
- Search (top bar button and Ctrl+F): a card-styled pop-over with live
  results from names, result text, details, prompts, variables and group
  names (BBCode stripped, case and accents ignored, exact names first).
  Up/Down, Enter or click jump to a result, Esc closes.
- Main.focus_table(table_id, entry_id): opens a collapsed group (toast),
  expands the card for an entry, glides to it at a readable zoom, scrolls
  the long list and flashes rings around the card and the row.
- Minimap (Map toggle beside Fit, M key): tinted blocks, lit cards in
  brass, the view rect; click or drag to pan. Off by default in Play, on in
  Build, remembered per mode. Redraws only on change.
- Zoom goes down to 0.08 and Fit uses it; far out, cards draw as plain
  cards and group names show large.
- Build > Arrange > Pack collapsed groups closes the gaps collapsed blocks
  leave, in reading order, with undo. Expanding a group whose frame would
  cover its neighbours pushes them right/down to clear it, with undo.
- Performance: cards in collapsed groups aren't built until expanded; the
  pipe, port and card layers redraw only when the board's geometry
  changes; unlit pipes go in per-pipe canvas items so off-screen ones are
  culled; off-screen cards aren't rendered. 792-card board: open 5.0 s ->
  0.38 s, idle frame 36 ms -> 0.7 ms (all groups expanded: 313 ms -> 9 ms).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:16:32 -06:00

223 lines
7.4 KiB
GDScript

class_name BoardSearch
extends RefCounted
## Finds text on a board: table names, result text and details, choice
## prompts, variable names and effects, table details and group names. Text is
## matched as plain text (BBCode stripped with Formatter.strip_tags),
## case-insensitive and ignoring accents. Built once per board revision (the
## index), then queried as the player types.
##
## A result is a Dictionary:
## table_id, entry_id ("" for the card itself), group_id ("" unless the
## match is a group's name), field (FIELD_*), name (card or group name),
## kind (KIND label, e.g. "Table", "Choice", "Group"), group (the card's
## group name, or ""), snippet (one line of plain text around the match),
## hl_from / hl_len (the match inside snippet) and score.
const FIELD_NAME := "name"
const FIELD_GROUP := "group"
const FIELD_VARIABLE := "variable"
const FIELD_PROMPT := "prompt"
const FIELD_RESULT := "result"
const FIELD_EFFECTS := "effects"
const FIELD_DETAILS := "details"
## How much a match in each field counts, before the exact/prefix bonus.
const FIELD_WEIGHT := {
FIELD_NAME: 100, FIELD_GROUP: 90, FIELD_VARIABLE: 80, FIELD_PROMPT: 50,
FIELD_RESULT: 40, FIELD_EFFECTS: 30, FIELD_DETAILS: 20,
}
const KIND_LABELS := {
RollTable.KIND_ROLL: "Table", RollTable.KIND_CHOICE: "Choice", RollTable.KIND_LOOP: "Loop",
RollTable.KIND_VARIABLE: "Variable", RollTable.KIND_SHEET: "Sheet",
}
const SNIPPET_BEFORE := 28
const SNIPPET_AFTER := 60
## Accented letters and the plain letter each folds to (one for one, so
## positions in the folded text are positions in the original).
const _ACCENTS := {
"a": "àáâãäåāăąǎ", "c": "çćĉċč", "d": "ďđ", "e": "èéêëēĕėęě", "g": "ĝğġģ",
"h": "ĥħ", "i": "ìíîïĩīĭįı", "j": "ĵ", "k": "ķ", "l": "ĺļľŀł", "n": "ñńņňʼn",
"o": "òóôõöøōŏőǒ", "r": "ŕŗř", "s": "śŝşšș", "t": "ţťŧț", "u": "ùúûüũūŭůűųǔ",
"w": "ŵ", "y": "ýÿŷ", "z": "źżž",
}
static var _fold_map: Dictionary = {}
## [{table_id, entry_id, group_id, field, text, folded, order}]
var items: Array = []
var _names: Dictionary = {} # table id -> plain name
var _kinds: Dictionary = {} # table id -> kind label
var _groups: Dictionary = {} # table id -> plain group name
func _init(board: TowerBoard = null) -> void:
if board:
build(board)
## Lower case, accents removed; the same length as `s`.
static func fold(s: String) -> String:
if _fold_map.is_empty():
for plain: String in _ACCENTS:
var accented: String = _ACCENTS[plain]
for i in accented.length():
_fold_map[accented[i]] = plain
var low := s.to_lower()
if low.length() != s.length():
low = s # a lower-casing that changes the length; keep positions right
if low.to_utf8_buffer().size() == low.length():
return low # plain ASCII
var parts := PackedStringArray()
for i in low.length():
var ch := low[i]
parts.append(str(_fold_map.get(ch, ch)))
return "".join(parts)
## One-line plain text for an entry, detail or name.
static func plain(text: String) -> String:
if text == "":
return ""
var p := Formatter.strip_tags(text) if text.contains("[") else text
return p.replace("\n", " ").replace("\t", " ").strip_edges()
func build(board: TowerBoard) -> void:
items.clear()
_names.clear()
_kinds.clear()
_groups.clear()
for g in board.groups:
var gname := plain(g.name)
for tid in g.members:
_groups[tid] = gname
_add("", "", g.id, FIELD_GROUP, gname)
_add("", "", g.id, FIELD_DETAILS, plain(g.details))
for t in board.tables:
_names[t.id] = plain(t.name)
_kinds[t.id] = str(KIND_LABELS.get(t.kind, "Table"))
_add(t.id, "", "", FIELD_NAME, _names[t.id])
_add(t.id, "", "", FIELD_DETAILS, plain(t.details))
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "":
_add(t.id, "", "", FIELD_VARIABLE, "@" + t.var_name)
if t.kind == RollTable.KIND_CHOICE:
_add(t.id, "", "", FIELD_PROMPT, plain(t.prompt))
if t.save_as != "":
_add(t.id, "", "", FIELD_VARIABLE, t.save_as)
for e in t.entries:
_add(t.id, e.id, "", FIELD_RESULT, plain(e.text))
_add(t.id, e.id, "", FIELD_DETAILS, plain(e.details))
if e.effects != "":
_add(t.id, e.id, "", FIELD_EFFECTS, plain(e.effects))
for to: String in e.pipe_save:
var sv := str(e.pipe_save[to])
if sv != "":
_add(t.id, e.id, "", FIELD_VARIABLE, sv)
func _add(tid: String, eid: String, gid: String, field: String, text: String) -> void:
if text == "":
return
items.append({"table_id": tid, "entry_id": eid, "group_id": gid, "field": field,
"text": text, "folded": fold(text), "order": items.size()})
## The best matches for `query`, best first, at most `limit`. Every word of
## the query must appear in the one field; the whole query as typed ranks
## higher, and so do exact names and matches at the start of a word.
func find(query: String, limit: int = 50) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var q := fold(query.strip_edges())
if q == "":
return out
var words := q.split(" ", false)
var scored: Array = []
for it: Dictionary in items:
var f: String = it["folded"]
var at := f.find(q)
var hl_len := q.length()
var score := 0
if at >= 0:
if f == q:
score = 1000
elif at == 0:
score = 300
elif _word_start(f, at):
score = 150
else:
score = 0
elif words.size() > 1:
var all := true
for w in words:
if not f.contains(w):
all = false
break
if not all:
continue
at = f.find(words[0])
hl_len = words[0].length()
score = -10
else:
continue
score += int(FIELD_WEIGHT.get(it["field"], 0))
scored.append([score, f.length(), int(it["order"]), it, at, hl_len])
scored.sort_custom(func(a: Array, b: Array) -> bool:
if a[0] != b[0]:
return a[0] > b[0]
if a[1] != b[1]:
return a[1] < b[1]
return a[2] < b[2])
for i in mini(limit, scored.size()):
var s: Array = scored[i]
out.append(_result(s[3], int(s[4]), int(s[5]), int(s[0])))
return out
## How many items match `query` in all (find() stops at its limit).
func count(query: String) -> int:
return find(query, 1 << 30).size()
static func _word_start(f: String, at: int) -> bool:
if at <= 0:
return true
var prev := f.unicode_at(at - 1)
return not ((prev >= 97 and prev <= 122) or (prev >= 48 and prev <= 57))
func _result(it: Dictionary, at: int, hl_len: int, score: int) -> Dictionary:
var text: String = it["text"]
var from := maxi(0, at - SNIPPET_BEFORE)
var to := mini(text.length(), at + hl_len + SNIPPET_AFTER)
# Start and end at word breaks where that's close by.
if from > 0:
var sp := text.rfind(" ", from + 8)
if sp >= 0 and sp < at and sp > from - 12:
from = sp + 1
var snippet := text.substr(from, to - from)
var hl_from := at - from
if from > 0:
snippet = "…" + snippet
hl_from += 1
if to < text.length():
snippet += "…"
var tid: String = it["table_id"]
var gid: String = it["group_id"]
var r := {"table_id": tid, "entry_id": it["entry_id"], "group_id": gid, "field": it["field"],
"snippet": snippet, "hl_from": hl_from, "hl_len": hl_len, "score": score}
if gid != "":
r["name"] = text if it["field"] == FIELD_GROUP else _group_name(gid)
r["kind"] = "Group"
r["group"] = ""
else:
r["name"] = str(_names.get(tid, tid))
r["kind"] = str(_kinds.get(tid, "Table"))
r["group"] = str(_groups.get(tid, ""))
return r
func _group_name(gid: String) -> String:
for it: Dictionary in items:
if it["group_id"] == gid and it["field"] == FIELD_GROUP:
return it["text"]
return gid