Spaces:
Sleeping
Sleeping
File size: 5,374 Bytes
e66cfb4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | """
layout/page/loader.py
---------------------
JSON 資料載入與結構解析。
無任何 Dash / DMC 依賴,可獨立單元測試。
公開 API:
load_json(source) → {"blocks", "sections", "toc"}
norm_id_or_none(raw) → str | None
build_toc_titles(blocks, toc) → [{"id", "label", "level"}, ...]
"""
from __future__ import annotations
import os
import json
from typing import Any
# ---------------------------------------------------------------------------
# 檔案快取(process 層級,同一 JSON 只讀一次)
# ---------------------------------------------------------------------------
_cache: dict[str, dict] = {}
def _load_file_cached(path: str) -> dict:
"""讀取並快取 JSON 檔案,檔案未更動時直接回傳快取。"""
try:
mtime = os.path.getmtime(path)
except OSError:
return {}
cached = _cache.get(path)
if cached and cached.get("_mtime") == mtime:
return cached["_data"]
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
data = {}
_cache[path] = {"_mtime": mtime, "_data": data}
return data
# ---------------------------------------------------------------------------
# 錯誤佔位文件
# ---------------------------------------------------------------------------
def _err_doc(msg: str) -> dict[str, Any]:
return {"blocks": [{"type": "paragraph", "content": f"⚠ {msg}"}], "toc": []}
# ---------------------------------------------------------------------------
# 主要載入函式
# ---------------------------------------------------------------------------
def load_json(source: Any) -> dict[str, Any]:
"""
接受多種來源,統一回傳 {"blocks": [...], "sections": [...], "toc": [...]}。
source 可以是:
- list / dict:直接使用
- str / Path:當作檔案路徑讀取
"""
if isinstance(source, (list, dict)):
obj = source
else:
p = str(source or "").strip()
if not p:
return _err_doc("未提供 JSON 路徑")
if not os.path.exists(p):
return _err_doc(f"找不到 JSON:{p}")
try:
obj = _load_file_cached(p)
if not obj:
return _err_doc(f"讀取 JSON 失敗或為空:{p}")
except Exception as e:
return _err_doc(f"讀取 JSON 失敗:{e}")
if isinstance(obj, list):
return {"blocks": obj, "sections": [], "toc": []}
if isinstance(obj, dict):
blocks = obj.get("blocks") or obj.get("doc") or obj.get("content") or []
sections = obj.get("sections") or []
toc = obj.get("toc") or obj.get("TOC") or []
if sections and isinstance(sections, list):
return {"blocks": blocks, "sections": sections, "toc": toc}
return {"blocks": blocks, "sections": [], "toc": toc}
return _err_doc(f"不支援的 JSON 型別:{type(obj).__name__}")
# ---------------------------------------------------------------------------
# ID 正規化
# ---------------------------------------------------------------------------
def norm_id_or_none(raw: str | None) -> str | None:
"""
把 URL fragment 或帶前綴的 id 字串還原成純 id。
範例:
'頁面#h-CH4-P2_id2' → 'CH4-P2_id2'
'#h-foo' → 'foo'
'h-bar' → 'bar'
'' / None → None
"""
if not raw:
return None
s = str(raw).strip()
if not s:
return None
if "#" in s:
s = s.split("#", 1)[1].strip()
if s.startswith("h-"):
s = s[2:]
return s or None
# ---------------------------------------------------------------------------
# TOC 標題清單建立
# ---------------------------------------------------------------------------
def build_toc_titles(
blocks: list[dict[str, Any]],
raw_toc: list[Any],
) -> list[dict[str, Any]]:
"""
回傳給 make_toc() 使用的 titles 清單:
[{"id": str, "label": str, "level": int}, ...]
優先使用 JSON 內嵌的 toc;若無,則從 blocks 的 heading 自動產生。
"""
titles: list[dict[str, Any]] = []
# 優先:JSON 內嵌 toc
if isinstance(raw_toc, list) and raw_toc:
for it in raw_toc:
if not isinstance(it, dict):
continue
label = (
it.get("title") or it.get("text") or it.get("label") or ""
).strip()
nid = norm_id_or_none(
it.get("id") or it.get("href") or it.get("slug")
)
level = int(it.get("level") or 1)
if not label or not nid:
continue
titles.append({"id": nid, "label": label, "level": max(1, min(level, 6))})
return titles
# 退回:從 blocks heading 產生
for b in blocks or []:
if (b.get("type") or "").lower() != "heading":
continue
nid = norm_id_or_none(b.get("id"))
if not nid:
continue
label = (b.get("content") or "").strip()
level = int(b.get("level") or 3)
titles.append({
"id": nid,
"label": label or "(空白標題)",
"level": max(1, min(level, 6)),
})
return titles
|