TableTower/core/lore_library.gd

78 lines
1.9 KiB
GDScript3
Raw Permalink Normal View History

class_name LoreLibrary
extends RefCounted
## "My library": the shared Lore Index level, kept outside every spread in
## <root>/lore_library.json ({"book": [BookPage dicts]}). Any spread and any
## sheet can use its Lore Entries. Links to it in sheet text say so:
## [url=lore:lib:ID] (SheetLoreLinks). There is no undo here; every change is
## saved at once (save()).
const FILE := "lore_library.json"
var root := "user://"
var pages: Array[BookPage] = []
## Goes up on every change, so open lists know to refresh.
var revision := 0
func _init(p_root: String = "user://") -> void:
root = p_root
load_file()
func path() -> String:
return root.path_join(FILE)
func load_file() -> void:
pages.clear()
if not FileAccess.file_exists(path()):
return
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path()))
if parsed is Dictionary and parsed.get("book") is Array:
for v: Variant in parsed["book"]:
if v is Dictionary:
var page := BookPage.from_dict(v)
if page.id == "":
page.id = TowerBoard.new_id("lib")
pages.append(page)
func save() -> Error:
revision += 1
DirAccess.make_dir_recursive_absolute(root)
var list: Array = []
for page in pages:
list.append(page.to_dict())
return BoardFileIO.write_text_atomic(path(), JSON.stringify({"book": list}, "\t"))
func get_page(id: String) -> BookPage:
for page in pages:
if page.id == id:
return page
return null
func add_page(text: String, details: String = "") -> BookPage:
var page := BookPage.new()
page.id = TowerBoard.new_id("lib")
page.text = text
page.details = details
pages.append(page)
save()
return page
## Adds a copy of `page` (a new id) and returns it.
func add_copy(page: BookPage) -> BookPage:
var added := page.copy()
added.id = TowerBoard.new_id("lib")
pages.append(added)
save()
return added
func remove_page(id: String) -> void:
pages = pages.filter(func(page: BookPage) -> bool: return page.id != id)
save()