260 lines
14 KiB
Python
260 lines
14 KiB
Python
"""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
|
|
from .table_style import TABLE_OPTIONS, TABLE_BOOL_FIELDS
|
|
|
|
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"),
|
|
*((key, name, f'.reader [data-mdh-style="{key}"]') for key, name in (
|
|
('list_bullet', '无序列表'), ('list_ordered', '有序列表'), ('list_task', '任务列表'),
|
|
('code_block', '代码块(独立)'), ('table_head', '表头文字'), ('table_cell', '单元格文字'))),
|
|
('strong', '加粗', '.reader strong'), ('emphasis', '强调', '.reader em'),
|
|
('strike', '删除线', '.reader s'), ('link', '超链接', '.reader a'),
|
|
('inline_code', '行内代码', '.reader code[data-mdh-style="inline_code"]'),
|
|
)
|
|
BOOL_FIELDS = ("bold", "italic", "underline", "strike", "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, *TABLE_BOOL_FIELDS):
|
|
if key in rule and not isinstance(rule[key], bool):
|
|
rule.pop(key)
|
|
for key in ('font_color', 'background_color', 'border_color', 'table_stripe_color'):
|
|
if key in rule and not re.fullmatch(r"auto|transparent|inherit|#[0-9a-fA-F]{6}", str(rule[key])):
|
|
rule.pop(key)
|
|
for key, allowed in {"alignment": {"left", "center", "right", "justify"},
|
|
'table_border_mode': {'grid', 'horizontal', 'none'},
|
|
"border_style": {'none','hidden','solid','dotted','dashed','double','groove','ridge','inset','outset'},
|
|
"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."""
|
|
from .style_catalog import explicit_rules, parent_style, CATALOG
|
|
authored = rules if isinstance(rules, dict) else {}
|
|
preset = authored.get('_preset', preset)
|
|
rules = explicit_rules(authored)
|
|
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 re.fullmatch('h[1-6]', target):
|
|
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 in ("code", 'code_block', 'inline_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 in ("list", 'list_bullet', 'list_ordered', 'list_task'):
|
|
rule.update(left_indent_value=2, indent_mode="hanging", indent_value=1)
|
|
elif target in ("table", 'table_head', 'table_cell'):
|
|
rule.update(space_before_value=0, space_after_value=0)
|
|
if target == 'table_head': rule['bold'] = True
|
|
from .style_catalog import CHARACTER_DEFAULTS
|
|
rule.update(CHARACTER_DEFAULTS.get(target, {}))
|
|
rule.update(normalize_rule((rules or {}).get(target, {})))
|
|
result[target] = rule
|
|
# An explicitly selected base inherits its defaults as well as declarations.
|
|
# Implicit legacy bases keep the same defaults as earlier releases.
|
|
inherited = {}
|
|
def resolve(target):
|
|
if target in inherited: return inherited[target]
|
|
parent = parent_style(target, authored)
|
|
if parent and CATALOG[target].kind != 'character':
|
|
value = dict(resolve(parent))
|
|
value.update(normalize_rule(authored.get(target, {})))
|
|
else:
|
|
value = result[target]
|
|
inherited[target] = value
|
|
return value
|
|
for target in result: resolve(target)
|
|
from .style_catalog import character_declarations
|
|
for target, declarations in character_declarations(authored, inherited).items():
|
|
inherited[target].update(normalize_rule(declarations))
|
|
return inherited
|
|
|
|
|
|
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 'underline' in r or 'strike' in r:
|
|
decoration = ' '.join(name for key, name in (('underline', 'underline'), ('strike', 'line-through')) if r.get(key)) or 'none'
|
|
out.append(f'text-decoration-line: {decoration};')
|
|
if 'background_color' in r:
|
|
out.append(f"background-color: {r['background_color']};")
|
|
if 'border_color' in r:
|
|
out.append(f"border-color: {r['border_color']};")
|
|
if 'border_width' in r:
|
|
out.append(f"border-width: {fmt(r['border_width'])}pt;")
|
|
if 'border_style' not in r: out.append('border-style: solid;')
|
|
if 'border_style' in r:
|
|
out.append(f"border-style: {r['border_style']};")
|
|
if 'cell_padding' in r:
|
|
out.append(f"padding: {fmt(r['cell_padding'])}pt;")
|
|
for field, prop in TABLE_OPTIONS.items():
|
|
if field in r:
|
|
value = str(r[field]).lower() if field in TABLE_BOOL_FIELDS else r[field]
|
|
out.append(f'{prop}: {value};')
|
|
if 'list_marker' in r:
|
|
out.append(f"list-style-type: {r['list_marker']};")
|
|
if 'level_indent' in r:
|
|
out.append(f"--mdhelper-list-level-indent: {fmt(r['level_indent'])}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: {css_length(-indent if mode == 'hanging' else indent if mode == 'first' else 0, r.get('indent_unit', '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 = "", *, reset_list_paragraphs=True) -> 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 reset_list_paragraphs and target in ("list", 'list_bullet', 'list_ordered', 'list_task'):
|
|
# Loose Markdown lists contain p elements; spacing belongs to li.
|
|
parts.append(".reader li > p { margin: 0; text-indent: inherit; }")
|
|
if 'level_indent' in rule:
|
|
parts.append(selector + f" > :is(ul, ol) {{ padding-left: {fmt(rule['level_indent'])}pt; }}")
|
|
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"))}
|
|
if target in ('list_bullet', 'list_ordered', 'list_task', 'code_block', 'table_head', 'table_cell'):
|
|
contexts[target] = (("", f'[data-mdh-style="{target}"]'),)
|
|
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)
|