TableTower/ui/sheet_export.gd
RobinFiredrake 317cac7a78 Sheets phase E: export/import, text toolbar and Lore links, Lore library and items, phone view
- E1: Export ▾ (share file with embedded pictures, print/PDF web page,
  PNG of the tab); Import a sheet file from Sheets and New sheet.
- E2: formatting toolbar (FormatMenu) in sheet text boxes; Lore links
  ([url=lore:ID]) with hover excerpt and the details panel.
- E3: Lore Index in Play and in sheets (shared LoreList); This spread |
  My library; item sheets on Lore Entries; drag entries into lists,
  slots and notes (copy, Shift keeps linked).
- E4: phone stacked view in phone order, Stacked | Canvas switch, 44 px
  touch sizes, bottom panels; sheet CLI flags split out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:25:09 -06:00

99 lines
4.4 KiB
GDScript

class_name SheetExport
extends RefCounted
## Saving a result (or its sheet) as a file to use outside the app: plain
## Text, Markdown, or a Web page (HTML, which any browser can print to PDF).
## Works from the result's BBCode: bold, italics, underline, colour and
## sizes come across where the format has them; anything else is dropped.
const FORMATS := [
{"key": "txt", "label": "Text", "filter": "*.txt ; Text"},
{"key": "md", "label": "Markdown", "filter": "*.md ; Markdown"},
{"key": "html", "label": "Web page (print it to PDF)", "filter": "*.html ; Web page"},
]
## The current roll as a document: its sheet when it reached one, else one
## line per result. `title` heads the document.
static func document(m: Main, format: String) -> String:
var steps: Array = m.current.get("all", [])
var title := Formatter.strip_tags(str(m.current.get("root_name", "Result")))
var body := ""
var sheet := ""
for s: Dictionary in steps:
if str(s.get("kind", "")) == RollTable.KIND_SHEET and not s.get("stop", false):
sheet = str(s.get("text", ""))
title = Formatter.strip_tags(str(s.get("table", title)))
if sheet != "":
body = sheet
else:
var lines := PackedStringArray()
for s: Dictionary in steps:
if s.get("inline", false) or s.get("dropped", false):
continue
lines.append("[b]%s:[/b] %s" % [str(s.get("table", "")), str(s.get("text", ""))])
body = "\n".join(lines)
return as_format(Formatter.to_export_bbcode(body), title, format)
static func as_format(bbcode: String, title: String, format: String) -> String:
match format:
"md":
return "# %s\n\n%s\n" % [title, to_markdown(bbcode)]
"html":
return HTML_HEAD % [_esc(title), _esc(title)] + to_html(bbcode) + "\n</body></html>\n"
return "%s\n%s\n\n%s\n" % [title, "=".repeat(title.length()), Formatter.strip_tags(bbcode)]
static func to_markdown(b: String) -> String:
var s := b
for pair: Array in [["[b]", "**"], ["[/b]", "**"], ["[i]", "*"], ["[/i]", "*"], ["[u]", ""], ["[/u]", ""], ["[s]", "~~"], ["[/s]", "~~"]]:
s = s.replace(pair[0], pair[1])
return Formatter.strip_tags(s).replace("\n", " \n")
static func to_html(b: String) -> String:
var s := _esc(b)
for pair: Array in [["[b]", "<b>"], ["[/b]", "</b>"], ["[i]", "<i>"], ["[/i]", "</i>"], ["[u]", "<u>"], ["[/u]", "</u>"],
["[s]", "<s>"], ["[/s]", "</s>"], ["[/color]", "</span>"], ["[/font_size]", "</span>"], ["[center]", "<div style=\"text-align:center\">"], ["[/center]", "</div>"]]:
s = s.replace(pair[0], pair[1])
var re := RegEx.create_from_string("\\[color=([#a-zA-Z0-9]+)\\]")
s = re.sub(s, "<span style=\"color:$1\">", true)
re = RegEx.create_from_string("\\[font_size=(\\d+)\\]")
s = re.sub(s, "<span style=\"font-size:$1px\">", true)
# Any other tag goes; line breaks become <br>.
re = RegEx.create_from_string("\\[/?[a-z_]+[^\\]]*\\]")
s = re.sub(s, "", true)
return "<p>" + s.replace("\n\n", "</p><p>").replace("\n", "<br>\n") + "</p>"
static func _esc(s: String) -> String:
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
const HTML_HEAD := """<!doctype html><html><head><meta charset="utf-8"><title>%s</title>
<style>body{font-family:Georgia,serif;max-width:42em;margin:2em auto;padding:0 1em;line-height:1.5;color:#1c0329}
h1{font-size:1.6em;border-bottom:2px solid #823d08;padding-bottom:.2em}
h2{font-size:1.25em;color:#823d08}section+section{break-before:page}</style></head><body>
<h1>%s</h1>
"""
## A whole sheet as a web page to print to PDF: one section per tab (each
## printed on its own page), boxes as "Title: value" lines (SheetText).
## `expand` fills in {@name} in text boxes (MainSheetLinks.expand).
static func sheet_html(doc: SheetDoc, expand: Callable) -> String:
var out := HTML_HEAD % [_esc(doc.name), _esc(doc.name)]
for tab in doc.tabs:
var text := str(expand.call(doc, SheetText.tab_text(doc, tab, "", false)))
out += "<section>\n<h2>%s</h2>\n%s\n</section>\n" % [_esc(str(tab["name"])), to_html(Formatter.to_export_bbcode(text))]
return out + "</body></html>\n"
## The tray's "Save as…" submenu entry: asks where, then writes the file.
static func save(m: Main, format_index: int) -> void:
if m.current.is_empty():
m.toast("Roll something first")
return
var f: Dictionary = FORMATS[format_index]
var name := LibraryStore.slugify(Formatter.strip_tags(str(m.current.get("root_name", "result")))) + "." + str(f["key"])
m.export_dialog("Save the result", str(f["filter"]), name, func() -> String: return document(m, str(f["key"])))