"""Loss-aware editing of core typography inside an otherwise arbitrary stylesheet. The authored CSS is authoritative. Only unconditional, known object selectors and representable values map to controls/Word. Other rules remain CSS verbatim. """ from __future__ import annotations from dataclasses import dataclass, field from copy import deepcopy import re import tinycss2 as css from tinycss2.color3 import parse_color from .document_style import (STYLE_TARGETS, normalize_rule, css_declarations, build_document_style_css, fmt, font_points, resolved_rules) SELECTORS = {key: selector for key, _, selector in STYLE_TARGETS} LABELS = {key: label for key, label, _ in STYLE_TARGETS} GROUPS = { "fonts": ("chinese_font_family", "english_font_family"), "size": ("font_size", "font_size_unit"), "bold": ("bold",), "italic": ("italic",), "color": ("font_color",), "tracking": ("letter_spacing",), "align": ("alignment",), "line": ("line_spacing_mode", "line_height_value"), "indent": ("indent_mode", "indent_value"), **{side: (f"{side}_indent_value", f"{side}_indent_unit") for side in ("left", "right")}, **{side: (f"space_{side}_value", f"space_{side}_unit") for side in ("before", "after")}, **{name: (name,) for name in ("contextual_spacing", "keep_with_next", "keep_lines_together", "page_break_before", "widow_control")}, } PROPERTIES = { "fonts": {"font-family", "--mdhelper-font-chinese", "--mdhelper-font-english"}, "size": {"font-size"}, "bold": {"font-weight"}, "italic": {"font-style"}, "color": {"color"}, "tracking": {"letter-spacing"}, "align": {"text-align"}, "line": {"line-height", "--mdhelper-line-spacing-mode"}, "indent": {"text-indent"}, **{side: {f"margin-{side}"} for side in ("left", "right")}, "before": {"margin-top"}, "after": {"margin-bottom"}, "contextual_spacing": {"--mdhelper-contextual-spacing"}, "keep_with_next": {"break-after", "page-break-after"}, "keep_lines_together": {"break-inside", "page-break-inside"}, "page_break_before": {"break-before", "page-break-before"}, "widow_control": {"widows", "orphans"}, } CORE_PROPERTIES = set().union(*PROPERTIES.values()) def _normalize_selector_text(value): value = re.sub(r"\s+", " ", value.strip()) value = re.sub(r"\s*,\s*", ",", value) return re.sub(r"\s+\)", ")", re.sub(r"\(\s+", "(", value)) ALIASES = {"p": "paragraph", **{f"h{i}": f"h{i}" for i in range(1, 7)}, "li": "list", "blockquote": "blockquote", "blockquote p": "blockquote", ".admonition p": "blockquote", "pre": "code", "code": "code", "table": "table", "th": "table", "td": "table"} ALIASES.update({".reader " + key: target for key, target in list(ALIASES.items())}) ALIASES[_normalize_selector_text(SELECTORS["paragraph"])] = "paragraph" FONT_VARIABLES = {"chinese_font_family": "--mdhelper-font-chinese", "english_font_family": "--mdhelper-font-english"} FONT_EXPRESSION = "var(--mdhelper-font-english, var(--mdhelper-font-chinese, var(--reader-font-family))), var(--mdhelper-font-chinese, sans-serif)" @dataclass class Analysis: rules: dict = field(default_factory=dict) errors: list[str] = field(default_factory=list) notes: list[str] = field(default_factory=list) def _text(tokens) -> str: return css.serialize(tokens).strip() def _split(tokens, delimiter=","): parts, current = [], [] for token in tokens: if token.type == "literal" and token.value == delimiter: parts.append(current) current = [] else: current.append(token) return parts + [current] def _selector(tokens): return _normalize_selector_text(_text([t for t in tokens if t.type != "comment"])) def _property(declaration): # Custom property names are case-sensitive in CSS. return declaration.name if declaration.name.startswith("--") else declaration.lower_name def _specificity(selector): # Only aliases in the allow-list reach this function. :where has zero weight. selector = re.sub(r":not\(:where\(.*\)\)", "", selector) return selector.count("."), len(re.findall(r"(?:^|\s)(?:p|h[1-6]|li|blockquote|pre|code|table|th|td)\b", selector)) def _balanced(source): stack, index = [], 0 while index < len(source): char = source[index] if source.startswith("/*", index): end = source.find("*/", index + 2) if end < 0: return "CSS 注释尚未结束(缺少 */)。" index = end + 2 continue if char in "\"'": quote = char index += 1 while index < len(source): if source[index] == "\\": index += 2 elif source[index] == quote: break else: index += 1 if index >= len(source): return "CSS 字符串尚未结束(缺少引号)。" elif char == "\\": index += 1 elif char in "{([": stack.append(char) elif char in "})]": if not stack or stack.pop() != {"}": "{", ")": "(", "]": "["}[char]: return f"CSS 括号不匹配:{char}。" index += 1 return "CSS 规则尚未结束(缺少右括号)。" if stack else "" def _declaration(name, value, important=False): return css.parse_declaration_list(f"{name}: {value}{' !important' if important else ''};", skip_whitespace=True)[0] def _expand(declaration): """Expand margins while keeping individual tokens (including calc/var).""" if declaration.type == "declaration" and declaration.lower_name == "font": tokens = [t for t in declaration.value if t.type not in ("whitespace", "comment")] size_index = next((i for i, t in enumerate(tokens) if t.type == "dimension" and t.lower_unit in ("pt", "px")), None) if size_index is None: return [declaration] prefix = [_text([t]).lower() for t in tokens[:size_index]] if any(value not in ("normal", "italic", "bold", "400", "700") for value in prefix): return [declaration] end = size_index + 1 line = "normal" if end < len(tokens) and tokens[end].type == "literal" and tokens[end].value == "/": if end + 1 >= len(tokens): return [declaration] line, end = _text([tokens[end + 1]]), end + 2 # Preserve whitespace inside unquoted family names. family_token = tokens[end] if end < len(tokens) else None if family_token is None: return [declaration] family = _text(declaration.value[declaration.value.index(family_token):]) try: _font_names(family) except ValueError: return [declaration] values = {"font-size": _text([tokens[size_index]]), "line-height": line, "font-family": family, "font-weight": "bold" if any(v in prefix for v in ("bold", "700")) else "normal", "font-style": "italic" if "italic" in prefix else "normal"} return [_declaration(prop, value, declaration.important) for prop, value in values.items()] if declaration.type != "declaration" or declaration.lower_name != "margin": return [declaration] values = [t for t in declaration.value if t.type not in ("whitespace", "comment")] if not 1 <= len(values) <= 4: return [declaration] top = values[0] right = values[1] if len(values) > 1 else top bottom = values[2] if len(values) > 2 else top left = values[3] if len(values) > 3 else right return [_declaration("margin-" + side, _text([value]), declaration.important) for side, value in zip(("top", "right", "bottom", "left"), (top, right, bottom, left))] def _length(value, units=("pt", "px", "cm", "em", "lh"), negative=False): tokens = css.parse_component_value_list(value, skip_comments=True) tokens = [t for t in tokens if t.type != "whitespace"] if len(tokens) != 1: raise ValueError token = tokens[0] if token.type == "number" and token.value == 0: amount, unit = 0, "pt" elif token.type == "dimension" and token.lower_unit in units: amount, unit = token.value, token.lower_unit else: raise ValueError if not negative and amount < 0: raise ValueError return amount, unit def _font_names(value): names = [] for part in _split(css.parse_component_value_list(value)): tokens = [t for t in part if t.type not in ("whitespace", "comment")] if len(tokens) == 1 and tokens[0].type == "string": names.append(tokens[0].value) elif tokens and all(t.type == "ident" for t in tokens): names.append(" ".join(t.value for t in tokens)) else: raise ValueError return names def analyze_css(source: str, font_size_px: float = 16) -> Analysis: result = Analysis() balance = _balanced(source) if balance: result.errors.append(balance) return result winners = {target: {} for target in SELECTORS} for order, node in enumerate(css.parse_stylesheet(source, skip_comments=False, skip_whitespace=False)): if node.type == "error": result.errors.append(f"第 {node.source_line} 行:{node.message}") continue if node.type == "at-rule": result.notes.append("条件规则、@规则保留在 CSS 中") continue if node.type != "qualified-rule": continue targets = {} for part in _split(node.prelude): selector = _selector(part) target = ALIASES.get(selector) if target: targets[target] = max(targets.get(target, (0, 0)), _specificity(selector)) else: result.notes.append("其他选择器保留在 CSS 中") declarations = css.parse_blocks_contents(node.content, skip_comments=False, skip_whitespace=False) for position, raw in enumerate(declarations): if raw.type == "error": result.errors.append(f"第 {raw.source_line} 行:{raw.message}") continue if raw.type == "declaration" and not raw.name.startswith("--") and not _text(raw.value): result.errors.append(f"第 {raw.source_line} 行:{raw.name} 缺少属性值。") continue expanded = _expand(raw) if raw.type in ("qualified-rule", "at-rule"): result.notes.append("嵌套规则保留在 CSS 中") if raw.type == "declaration" and raw.lower_name == "font" and len(expanded) == 1: # A shorthand resets all five longhands, even if its value cannot # be represented. Do not show stale, overridden control values. expanded += [_declaration(prop, "var(--unsupported-font-shorthand)", raw.important) for prop in ("font-family", "font-size", "font-weight", "font-style", "line-height")] for declaration in expanded: if declaration.type != "declaration": continue prop = _property(declaration) if prop == "font": result.notes.append("font 简写保留在 CSS 中;核心字体请使用 font-family/font-size 等属性") if prop not in CORE_PROPERTIES: continue for target, specificity in targets.items(): rank = (declaration.important, specificity, order, position) if prop not in winners[target] or rank >= winners[target][prop][0]: winners[target][prop] = (rank, _text(declaration.value)) for target, entries in winners.items(): props = {key: value[1] for key, value in entries.items()} rule = {} def read(prop, convert): if prop not in props or props[prop].lower() in ("inherit", "unset", "revert"): return try: convert(props[prop]) except (ValueError, KeyError, TypeError): result.notes.append(f"{LABELS[target]}的 {prop}: {props[prop]} 仅保留为 CSS") def choice(prop, key, options): read(prop, lambda value: rule.update({key: options[value.lower()]})) def sized(value): amount, unit = _length(value, ("pt", "px")) if not 0 < amount <= 200: raise ValueError rule.update(font_size=amount, font_size_unit=unit) read("font-size", sized) def families(value): if re.sub(r"\s+", "", value) == re.sub(r"\s+", "", FONT_EXPRESSION): for key, variable in FONT_VARIABLES.items(): if variable in props: rule[key] = _font_names(props[variable])[0] else: names = _font_names(value) rule.update(english_font_family=names[0], chinese_font_family=names[1] if len(names) > 1 and names[1] not in ("serif", "sans-serif", "monospace") else names[0]) read("font-family", families) choice("font-weight", "bold", {"bold": True, "700": True, "normal": False, "400": False}) choice("font-style", "italic", {"italic": True, "normal": False}) choice("text-align", "alignment", {name: name for name in ("left", "center", "right", "justify")}) def color(value): if value.lower() in ("currentcolor", "var(--reader-text-color, #23272f)"): rule["font_color"] = "auto" return rgba = parse_color(value) if rgba is None or isinstance(rgba, str) or rgba.alpha != 1: raise ValueError rule["font_color"] = "#" + "".join(f"{round(v * 255):02x}" for v in rgba[:3]) read("color", color) def tracking(value): amount, unit = (0, "pt") if value == "normal" else _length(value, ("pt", "px"), negative=True) amount *= .75 if unit == "px" else 1 if abs(amount) > 100: raise ValueError rule["letter_spacing"] = amount read("letter-spacing", tracking) def line(value): if value == "normal": amount, mode = 1, "multiple" elif re.fullmatch(r"(?:\d+(?:\.\d*)?|\.\d+)%?", value): amount = float(value.rstrip("%")) / (100 if value.endswith("%") else 1) mode = "multiple" else: amount, unit = _length(value, ("pt", "px")) amount *= .75 if unit == "px" else 1 mode = "at_least" if props.get("--mdhelper-line-spacing-mode") == "at-least" else "exact" if not .1 <= amount <= 500: raise ValueError rule.update(line_height_value=amount, line_spacing_mode=mode) read("line-height", line) for side, prefix in (("left", "left_indent"), ("right", "right_indent"), ("top", "space_before"), ("bottom", "space_after")): def margin(value, prefix=prefix): amount, unit = _length(value, ("em", "pt", "px", "cm") if "indent" in prefix else ("em", "pt", "px", "lh", "cm")) if unit == "px": amount, unit = amount * .75, "pt" if unit == "cm" and "indent" not in prefix: amount, unit = amount * 72 / 2.54, "pt" if amount > (200 if "indent" in prefix else 1000): raise ValueError rule.update({prefix + "_value": amount, prefix + "_unit": "line" if unit == "lh" else unit}) read("margin-" + side, margin) def indent(value): amount, unit = _length(value, ("em", "pt", "px"), negative=True) if unit != "em": points = font_points({**resolved_rules({}, font_size_px=font_size_px)[target], **rule}) amount = amount * (.75 if unit == "px" else 1) / points if abs(amount) > 100: raise ValueError rule.update(indent_mode="none" if not amount else "first" if amount > 0 else "hanging", indent_value=abs(amount)) read("text-indent", indent) for field, modern, legacy, yes in (("keep_with_next", "break-after", "page-break-after", ("avoid", "avoid-page")), ("keep_lines_together", "break-inside", "page-break-inside", ("avoid", "avoid-page")), ("page_break_before", "break-before", "page-break-before", ("page", "always"))): candidates = [name for name in (modern, legacy) if name in entries] if candidates: prop = max(candidates, key=lambda name: entries[name][0]) choice(prop, field, {**{v: True for v in yes}, "auto": False}) widow_values = [props[p] for p in ("widows", "orphans") if p in props] if widow_values: if all(v == "1" for v in widow_values) or all(v == "2" for v in widow_values): rule["widow_control"] = widow_values[0] == "2" else: result.notes.append(f"{LABELS[target]}的 widows/orphans 仅保留为 CSS") choice("--mdhelper-contextual-spacing", "contextual_spacing", {"true": True, "false": False}) if rule: result.rules[target] = rule result.notes = list(dict.fromkeys(result.notes)) return result def _core_declarations(rule): declarations = [d for d in css_declarations(rule) if not d.startswith(("font-family:", "padding-left:"))] if any(rule.get(key) for key in FONT_VARIABLES): for key, variable in FONT_VARIABLES.items(): if rule.get(key): name = str(rule[key]).replace("\\", "\\\\").replace('"', '\\"') declarations.append(f'{variable}: "{name}";') declarations.append(f"font-family: {FONT_EXPRESSION};") if "line_spacing_mode" in rule: declarations.append(f"--mdhelper-line-spacing-mode: {rule['line_spacing_mode'].replace('_', '-')};") if "contextual_spacing" in rule: declarations.append(f"--mdhelper-contextual-spacing: {str(rule['contextual_spacing']).lower()};") return declarations def source_from_payload(payload: dict) -> str: if payload.get("css_sync_version") == 1: return str(payload.get("css") or "") rules = payload.get("rules") if isinstance(rules, dict) and rules: blocks = [] for target, _, selector in STYLE_TARGETS: declarations = _core_declarations(normalize_rule(rules.get(target))) if declarations: blocks.append(selector + " {\n " + "\n ".join(declarations) + "\n}") return "\n\n".join(blocks + [str(payload.get("extra_css") or "")]).strip() return str(payload.get("extra_css") or payload.get("css") or "") def patch_core(source: str, target: str, before: dict, after: dict, *, reset=False) -> str: """Change only edited groups, preserving comments, extensions and conditions.""" changed = set(GROUPS) if reset else {group for group, keys in GROUPS.items() if any(before.get(key) != after.get(key) for key in keys)} if not changed: return source affected = set().union(*(PROPERTIES[group] for group in changed)) important = set() output = [] for node in css.parse_stylesheet(source, skip_whitespace=False, skip_comments=False): if node.type != "qualified-rule": output.append(node) continue selectors = _split(node.prelude) selected = [p for p in selectors if ALIASES.get(_selector(p)) == target] if not selected: output.append(node) continue others = [p for p in selectors if ALIASES.get(_selector(p)) != target] declarations = css.parse_blocks_contents(node.content, skip_comments=False, skip_whitespace=False) kept = [] touched = False for raw in declarations: expanded = _expand(raw) relevant = [d for d in expanded if d.type == "declaration" and _property(d) in affected] if reset and raw.type == "declaration" and raw.lower_name == "font": touched = True continue if not relevant: kept.append(raw) if raw.type == "declaration" and raw.lower_name == "font" and raw.important: important.update(changed & {"fonts", "size", "bold", "italic", "line"}) continue touched = True for declaration in expanded: if declaration.type == "declaration" and _property(declaration) in affected: if declaration.important: important.update(group for group in changed if _property(declaration) in PROPERTIES[group]) else: kept.append(declaration) if not touched: output.append(node) continue if others: original = deepcopy(node) original.prelude = css.parse_component_value_list(", ".join(_text(p) for p in others) + " ") output.append(original) has_replacement = any(key in after for group in changed for key in GROUPS[group]) if has_replacement or any(d.type not in ("whitespace",) for d in kept): node.prelude = css.parse_component_value_list(", ".join(_text(p) for p in selected) + " ") node.content = css.parse_component_value_list(css.serialize(kept)) output.append(node) fragment = {key: value for group in changed for key in GROUPS[group] if (value := after.get(key)) is not None} declarations = _core_declarations(fragment) marked = [] for text in declarations: prop = text.split(":", 1)[0] if any(prop in PROPERTIES[group] for group in important): text = text.rstrip(";") + " !important;" marked.append(text) # Reuse an existing block for this object, retaining its authored selector. # This also avoids expanding a simple .reader p rule into a second block. if marked: canonical = next((node for node in reversed(output) if node.type == "qualified-rule" and all(ALIASES.get(_selector(part)) == target for part in _split(node.prelude))), None) if canonical is not None: content = css.serialize(canonical.content).rstrip() + "\n " + "\n ".join(marked) + "\n" canonical.content = css.parse_component_value_list(content) marked = [] result = css.serialize(output).rstrip() if marked: result += ("\n\n" if result else "") + SELECTORS[target] + " {\n " + "\n ".join(marked) + "\n}" return result def render_css(source: str, rules: dict) -> str: """Materialize the few core features which need companion reader rules.""" contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if rule.get("contextual_spacing")} helpers = build_document_style_css(contextual) paragraph = rules.get("paragraph", {}) if paragraph.get("font_size"): helpers += f"\n.reader {{ --reader-math-font-size: {fmt(paragraph['font_size'])}{paragraph.get('font_size_unit', 'px')}; }}" if rules.get("list"): helpers += "\n.reader li > p { margin: 0; text-indent: inherit; }" return (helpers.strip() + "\n\n" + source).strip() def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_px=16) -> dict: source = source_from_payload(payload) result = analyze_css(source, font_size_px) return {"name": str(payload.get("name") or fallback_name).strip() or fallback_name, "css_sync_version": 1, "css": source, "rules": result.rules if not result.errors else deepcopy(payload.get("rules") or {})}