feat: complete typography settings and preserve Word styles
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
"""Shared, JSON-serializable typography rules for the reader and Word export.
|
||||
|
||||
Missing keys mean inherit. Zero and False are explicit values. Legacy files
|
||||
used pixels for font size and em for paragraph spacing labelled 'multiple'.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
STYLE_TARGETS = (
|
||||
("paragraph", "正文段落", ".reader p:not(:where(li p, blockquote p, .admonition p, th p, td p))"),
|
||||
*((f"h{i}", f"{label}级标题", f".reader h{i}") for i, label in enumerate("一二三四五六", 1)),
|
||||
("list", "列表项", ".reader li"),
|
||||
("blockquote", "引用段落", ".reader blockquote p, .reader .admonition p"),
|
||||
("code", "代码块", ".reader pre, .reader code"),
|
||||
("table", "表格", ".reader table, .reader th, .reader td"),
|
||||
)
|
||||
BOOL_FIELDS = ("bold", "italic", "keep_with_next", "keep_lines_together", "page_break_before", "widow_control", "contextual_spacing")
|
||||
|
||||
|
||||
def number(value: object, fallback: float = 0) -> float:
|
||||
try:
|
||||
result = float(value)
|
||||
return result if math.isfinite(result) else fallback
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
|
||||
|
||||
def normalize_rule(value: object) -> dict[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
rule = dict(value)
|
||||
if "font_family" in rule and "chinese_font_family" not in rule:
|
||||
rule["chinese_font_family"] = rule["font_family"]
|
||||
for key in ("font_family", "first_line_indent_chars", "first_line_indent", "hanging_indent_chars", "hanging_indent", "line_height", "space_before", "space_after"):
|
||||
rule.pop(key, None)
|
||||
if "indent_mode" not in value:
|
||||
first = number(value.get("first_line_indent_chars", value.get("first_line_indent")))
|
||||
hanging = number(value.get("hanging_indent_chars", value.get("hanging_indent")))
|
||||
if hanging or first:
|
||||
rule.update(indent_mode="hanging" if hanging else "first", indent_value=hanging or first)
|
||||
if hanging and "left_indent_value" not in rule:
|
||||
# Older styles used padding for hanging indents. Migrate that
|
||||
# offset to Word's left-indent coordinate without moving text.
|
||||
rule.update(left_indent_value=hanging, left_indent_unit="em")
|
||||
if "line_height" in value and "line_height_value" not in value:
|
||||
rule["line_height_value"] = value["line_height"]
|
||||
if "line_height_value" in rule and "line_spacing_mode" not in rule:
|
||||
rule["line_spacing_mode"] = "exact" if rule.get("line_height_unit") == "pt" else "multiple"
|
||||
for field in ("space_before", "space_after"):
|
||||
if field in value and field + "_value" not in value:
|
||||
rule[field + "_value"] = value[field]
|
||||
if field + "_value" in rule:
|
||||
unit = rule.get(field + "_unit", "multiple")
|
||||
rule[field + "_unit"] = "em" if unit == "multiple" else unit
|
||||
for key in BOOL_FIELDS:
|
||||
if key in rule and not isinstance(rule[key], bool):
|
||||
rule.pop(key)
|
||||
if "font_color" in rule and not re.fullmatch(r"auto|#[0-9a-fA-F]{6}", str(rule["font_color"])):
|
||||
rule.pop("font_color")
|
||||
for key, allowed in {"alignment": {"left", "center", "right", "justify"},
|
||||
"indent_mode": {"none", "first", "hanging"},
|
||||
"line_spacing_mode": {"multiple", "exact", "at_least"}}.items():
|
||||
if key in rule and rule[key] not in allowed:
|
||||
rule.pop(key)
|
||||
return rule
|
||||
|
||||
|
||||
def font_points(rule: dict, default: float = 12) -> float:
|
||||
size = number(rule.get("font_size"))
|
||||
return size * (0.75 if rule.get("font_size_unit", "px") == "px" else 1) if size > 0 else default
|
||||
|
||||
|
||||
def length_points(value: object, unit: str, font_pt: float, line_pt: float | None = None) -> float:
|
||||
return number(value) * {"pt": 1, "px": .75, "cm": 72 / 2.54, "em": font_pt, "multiple": font_pt, "line": line_pt or font_pt}.get(unit, 1)
|
||||
|
||||
|
||||
def line_points(rule: dict, font_pt: float) -> float:
|
||||
val = number(rule.get("line_height_value"), 1.72)
|
||||
mode = rule.get("line_spacing_mode", "multiple")
|
||||
if mode == "at_least":
|
||||
return max(val, font_pt * 1.2)
|
||||
return val if mode == "exact" else font_pt * val
|
||||
|
||||
|
||||
def resolved_rules(rules: dict | None, font_family: str = "", font_size_px: float = 16, preset: str = "default") -> dict[str, dict]:
|
||||
"""Reader defaults, not Word's theme-dependent defaults."""
|
||||
base = dict(chinese_font_family=font_family or "Microsoft YaHei UI", english_font_family=font_family or "Microsoft YaHei UI",
|
||||
font_size=font_size_px, font_size_unit="px", bold=False, italic=False,
|
||||
font_color="auto", line_spacing_mode="multiple", line_height_value=1.72,
|
||||
space_before_value=.74, space_before_unit="em", space_after_value=.74, space_after_unit="em",
|
||||
alignment="left", left_indent_value=0, left_indent_unit="em", right_indent_value=0, right_indent_unit="em",
|
||||
indent_mode="none", indent_value=0, letter_spacing=0, contextual_spacing=False,
|
||||
keep_with_next=False, keep_lines_together=False, page_break_before=False, widow_control=True)
|
||||
if preset == "compact":
|
||||
base.update(line_height_value=1.58, space_before_value=.42, space_after_value=.42)
|
||||
elif preset == "serif":
|
||||
base.update(chinese_font_family="SimSun", english_font_family="Georgia", line_height_value=1.82)
|
||||
elif preset in {"wide", "focus"}:
|
||||
base["line_height_value"] = 1.65 if preset == "wide" else 1.78
|
||||
result = {}
|
||||
for target, _, _ in STYLE_TARGETS:
|
||||
rule = dict(base)
|
||||
if target.startswith("h"):
|
||||
level = int(target[1:])
|
||||
scale = [2.05, 1.48, 1.2, 1, .83, .67][level - 1]
|
||||
if preset == "compact" and level == 1:
|
||||
scale = 1.78
|
||||
rule.update(font_size=font_size_px * scale, bold=True, line_height_value=1.32,
|
||||
space_before_value=0 if level == 1 else 1.35, space_after_value=.55, keep_with_next=True)
|
||||
if preset == "focus" and level == 1:
|
||||
rule["alignment"] = "center"
|
||||
elif target == "code":
|
||||
rule.update(english_font_family="Consolas", font_size=font_size_px * .95, space_before_value=0, space_after_value=0)
|
||||
elif target == "blockquote":
|
||||
rule.update(left_indent_value=1, right_indent_value=1)
|
||||
elif target == "list":
|
||||
rule.update(left_indent_value=2, indent_mode="hanging", indent_value=1)
|
||||
elif target == "table":
|
||||
rule.update(space_before_value=0, space_after_value=0)
|
||||
rule.update(normalize_rule((rules or {}).get(target, {})))
|
||||
result[target] = rule
|
||||
return result
|
||||
|
||||
|
||||
def fmt(value: object) -> str:
|
||||
return f"{number(value):.4f}".rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def css_length(value: object, unit: str) -> str:
|
||||
return fmt(value) + {"pt": "pt", "cm": "cm", "px": "px", "em": "em", "multiple": "em", "line": "lh"}.get(unit, "em")
|
||||
|
||||
|
||||
def css_declarations(value: dict) -> list[str]:
|
||||
r = normalize_rule(value)
|
||||
out = []
|
||||
fonts = [r.get("english_font_family"), r.get("chinese_font_family")]
|
||||
fonts = list(dict.fromkeys(str(f).replace("\\", "\\\\").replace('"', '\\"') for f in fonts if f))
|
||||
if fonts:
|
||||
out.append("font-family: " + ", ".join(f'"{f}"' for f in fonts) + ", sans-serif;")
|
||||
if number(r.get("font_size")) > 0:
|
||||
out.append(f"font-size: {css_length(r['font_size'], r.get('font_size_unit', 'px'))};")
|
||||
for key, prop, yes, no in (("bold", "font-weight", "700", "400"), ("italic", "font-style", "italic", "normal")):
|
||||
if key in r:
|
||||
out.append(f"{prop}: {yes if r[key] else no};")
|
||||
if "font_color" in r:
|
||||
out.append(f"color: {r['font_color'] if r['font_color'] != 'auto' else 'var(--reader-text-color, #23272f)'};")
|
||||
if "letter_spacing" in r:
|
||||
out.append(f"letter-spacing: {fmt(r['letter_spacing'])}pt;")
|
||||
if r.get("alignment") in {"left", "center", "right", "justify"}:
|
||||
out.append(f"text-align: {r['alignment']};")
|
||||
if number(r.get("line_height_value")) > 0:
|
||||
mode = r.get("line_spacing_mode", "multiple")
|
||||
# CSS line boxes naturally expand for taller inline content (Word atLeast).
|
||||
out.append(f"line-height: {fmt(r['line_height_value'])}{'' if mode == 'multiple' else 'pt'};")
|
||||
for side in ("left", "right"):
|
||||
if side + "_indent_value" in r:
|
||||
out.append(f"margin-{side}: {css_length(r[side + '_indent_value'], r.get(side + '_indent_unit', 'em'))};")
|
||||
mode, indent = r.get("indent_mode"), number(r.get("indent_value"))
|
||||
if mode in {"none", "first", "hanging"}:
|
||||
out.append(f"text-indent: {fmt(-indent if mode == 'hanging' else indent if mode == 'first' else 0)}em;")
|
||||
out.append("padding-left: 0em;")
|
||||
for field, side in (("space_before", "top"), ("space_after", "bottom")):
|
||||
if field + "_value" in r:
|
||||
out.append(f"margin-{side}: {css_length(r[field + '_value'], r.get(field + '_unit', 'pt'))};")
|
||||
for field, prop, yes in (("keep_with_next", "break-after", "avoid-page"), ("keep_lines_together", "break-inside", "avoid-page"), ("page_break_before", "break-before", "page")):
|
||||
if field in r:
|
||||
out.append(f"{prop}: {yes if r[field] else 'auto'};")
|
||||
if "widow_control" in r:
|
||||
out.extend(f"{prop}: {2 if r['widow_control'] else 1};" for prop in ("widows", "orphans"))
|
||||
return out
|
||||
|
||||
|
||||
def build_document_style_css(rules: dict | None, extra_css: str = "") -> str:
|
||||
parts = []
|
||||
rules = rules if isinstance(rules, dict) else {}
|
||||
p = normalize_rule(rules.get("paragraph"))
|
||||
if number(p.get("font_size")) > 0:
|
||||
parts.append(f".reader {{ --reader-math-font-size: {css_length(p['font_size'], p.get('font_size_unit', 'px'))}; }}")
|
||||
for target, _, selector in STYLE_TARGETS:
|
||||
rule = normalize_rule(rules.get(target))
|
||||
declarations = css_declarations(rule)
|
||||
if declarations:
|
||||
parts.append(selector + " {\n " + "\n ".join(declarations) + "\n}")
|
||||
if target == "list":
|
||||
# Loose Markdown lists contain p elements; spacing belongs to li.
|
||||
parts.append(".reader li > p { margin: 0; text-indent: inherit; }")
|
||||
if rule.get("contextual_spacing"):
|
||||
# Match adjacent elements of the same paragraph type, not p + h1.
|
||||
contexts = {"paragraph": (("", "p:not(:where(li p, blockquote p, .admonition p, th p, td p))"),),
|
||||
"list": (("", "li"),), "blockquote": (("blockquote > ", "p"), (".admonition > ", "p")),
|
||||
"code": (("", "pre"),), "table": (("th > ", "p"), ("td > ", "p"))}
|
||||
for scope, tag in contexts.get(target, (("", target),)):
|
||||
parts.append(f".reader {scope}{tag} + {tag} {{ margin-top: 0; }}\n.reader {scope}{tag}:has(+ {tag}) {{ margin-bottom: 0; }}")
|
||||
if extra_css.strip():
|
||||
parts.append(extra_css.strip())
|
||||
return "\n\n".join(parts)
|
||||
Reference in New Issue
Block a user