TableTower/io/mermaid_exporter.gd

72 lines
2.8 KiB
GDScript3
Raw Normal View History

class_name MermaidExporter
extends RefCounted
## Mermaid flowchart export (renders in Forgejo and GitHub Markdown).
## One node per table, solid arrows for pipes, dashed arrows for inline
## [[references]]. Pipes to tables that don't exist point at a red dashed
## "missing" node.
const MAX_EDGE_TEXT := 32
## Mermaid source ("graph LR ...") for a collection Dictionary.
static func export_mermaid(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var lines: Array[String] = ["graph LR"]
var node_of := {} # table id -> mermaid node id
var tables: Array = c["tables"]
for i in tables.size():
var t: Dictionary = tables[i]
node_of[t["id"]] = "t%d" % i
var label := JsonIO.strip_bbcode(str(t["name"]))
if t.has("dice"):
label += " (%s)" % t["dice"]
lines.append("\tt%d[\"%s\"]" % [i, escape_label(label)])
var missing := {} # target name -> mermaid node id
var edges: Array[String] = []
for link in JsonIO.links(c):
var target: String
if link["target"] != "":
target = node_of[link["target"]]
else:
var mkey: String = str(link["target_name"]).to_lower()
if not missing.has(mkey):
missing[mkey] = "m%d" % missing.size()
target = missing[mkey]
var from: String = node_of[link["from_table"]]
var text := _short(str(link["entry_text"]))
var extra := str(link["label"])
if link["kind"] == "pipe":
var label2 := text if extra == "" else "%s · %s" % [text, extra]
edges.append("\t%s -->|\"%s\"| %s" % [from, escape_label(label2), target])
else:
edges.append("\t%s -.->|\"%s\"| %s" % [from, escape_label("%s · %s" % [text, extra]), target])
for key in missing:
var shown := "missing: " + _name_for_missing(c, key)
lines.append("\t%s[\"%s\"]:::missing" % [missing[key], escape_label(shown)])
lines.append_array(edges)
if not missing.is_empty():
lines.append("\tclassDef missing stroke:#d33,stroke-dasharray:4 3,color:#d33")
return "\n".join(lines) + "\n"
## Makes text safe inside a double-quoted Mermaid label using entity codes.
static func escape_label(text: String) -> String:
var s := text.replace("\r", " ").replace("\n", " ")
s = s.replace("#", "#35;")
for pair in [["\"", "#quot;"], ["&", "#38;"], ["<", "#lt;"], [">", "#gt;"], ["[", "#91;"], ["]", "#93;"], ["{", "#123;"], ["}", "#125;"], ["|", "#124;"], ["`", "#96;"], ["\\", "#92;"]]:
s = s.replace(pair[0], pair[1])
return s
static func _short(text: String) -> String:
var t := text.replace("\n", " ").strip_edges()
return t if t.length() <= MAX_EDGE_TEXT else t.substr(0, MAX_EDGE_TEXT - 1) + "…"
## The first spelling of a missing target (keys are lower-cased).
static func _name_for_missing(c: Dictionary, key: String) -> String:
for link in JsonIO.links(c):
if link["target"] == "" and str(link["target_name"]).to_lower() == key:
return str(link["target_name"])
return key