"""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 tinycss2.color4 import parse_color as parse_modern_color from .document_style import (STYLE_TARGETS, normalize_rule, css_declarations, build_document_style_css, fmt, font_points, resolved_rules) from .table_style import TABLE_OPTIONS, TABLE_BOOL_FIELDS, TABLE_ONLY_FIELDS, table_helper_css 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",), 'decoration': ('underline', 'strike'), 'background': ('background_color',), 'border_color': ('border_color',), 'border_width': ('border_width',), 'border_style': ('border_style',), 'padding': ('cell_padding',), 'marker': ('list_marker',), 'level_indent': ('level_indent',), "line": ("line_spacing_mode", "line_height_value"), "indent": ("indent_mode", "indent_value", "indent_unit"), **{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")}, **{name: (name,) for name in TABLE_OPTIONS}, } 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"}, 'decoration': {'text-decoration', 'text-decoration-line', '--mdhelper-underline', '--mdhelper-strike'}, 'background': {'background-color'}, 'border_color': {'border-color'}, 'border_width': {'border-width'}, 'border_style': {'border-style'}, 'padding': {'padding'}, 'marker': {'list-style-type'}, 'level_indent': {'--mdhelper-list-level-indent'}, "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"}, **{name: {prop} for name, prop in TABLE_OPTIONS.items()}, } 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_block", "code": "code", "table": "table", "th": "table_head", "td": "table_cell", "pre code": "code_block", "pre > code": "code_block"} ALIASES.update({".reader " + key: target for key, target in list(ALIASES.items())}) ALIASES.update({selector: key for key, selector in SELECTORS.items() if ',' not in selector}) ALIASES.update({'strong': 'strong', 'em': 'emphasis', 's': 'strike', 'del': 'strike', '.reader del': 'strike', 'a': 'link'}) 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)" DECORATION_EXPRESSION = 'var(--mdhelper-text-decoration, none)' LIST_PARAGRAPH = '_list_paragraph' @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 _rule_aliases(parts): """Keep old generated baseline groups, but never merge independent objects.""" aliases = {_selector(part): ALIASES.get(_selector(part)) for part in parts} for prefix in ('', '.reader '): for base, names in (('code', ('pre', 'code')), ('table', ('table', 'th', 'td'))): group = {prefix + name for name in names} if group <= aliases.keys(): for selector in group: aliases[selector] = base return aliases def _owned_fields(entries, target): """A winning baseline declaration must remain inherited by its child.""" fields = set() variables = {value: (key,) for key, value in FONT_VARIABLES.items()} variables.update({'--mdhelper-underline': ('underline',), '--mdhelper-strike': ('strike',)}) for prop, entry in entries.items(): if entry[2] != target: continue if prop == 'font-family' and re.sub(r'\s+', '', entry[1]) == re.sub(r'\s+', '', FONT_EXPRESSION): continue if prop == 'text-decoration-line' and entry[1] == DECORATION_EXPRESSION: continue if prop in variables: fields.update(variables[prop]); continue for group, properties in PROPERTIES.items(): if prop in properties: fields.update(GROUPS[group]) return fields 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(".") + selector.count('['), len(re.findall(r"(?:^|\s)(?:p|h[1-6]|li|blockquote|pre|code|table|th|td|strong|em|s|a)\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": if _invalid_core_value('font', declaration.value): return [declaration] 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 _invalid_core_value(prop, tokens): """Reject definite invalid values; retain valid unsupported expressions.""" tokens = [t for t in tokens if t.type not in ('whitespace', 'comment')] if not tokens or any(t.type == 'error' for t in tokens): return True if len(tokens)==1 and tokens[0].type=='ident' and tokens[0].lower_value in ('inherit','initial','unset','revert','revert-layer'): return False # Variables may expand to otherwise valid token sequences, including empty # fragments. Do not misclassify them as invalid syntax before substitution. if any(t.type == 'function' and t.lower_name in ('var','env') for t in tokens): return False if prop in ('color','background-color','border-color') and len(tokens) == 1: token=tokens[0] if token.type != 'function': return parse_color(token) is None if token.lower_name in ('rgb','rgba','hsl','hsla','hwb','lab','lch','oklab','oklch','color'): # Relative colors and math are valid browser expressions that the # scalar color parser cannot evaluate. Preserve those as CSS. if not any(t.type=='function' or t.type=='ident' and t.lower_value=='from' for t in token.arguments): try: return parse_modern_color(token) is None except (ValueError, TypeError): return True if prop == 'font-style' and len(tokens) > 1: return not (len(tokens)==2 and tokens[0].type=='ident' and tokens[0].lower_value=='oblique' and tokens[1].type=='dimension' and tokens[1].lower_unit in ('deg','grad','rad','turn')) if prop == 'font': if len(tokens)==1: return not (tokens[0].type=='ident' and tokens[0].lower_value in ('caption','icon','menu','message-box','small-caption','status-bar')) size_index = next((i for i,t in enumerate(tokens) if t.type in ('dimension','percentage','function') and not (t.type=='dimension' and t.lower_unit in ('deg','grad','rad','turn')) or t.type=='number' and t.value==0 or t.type=='ident' and t.lower_value in ('xx-small','x-small','small','medium','large','x-large','xx-large','xxx-large','smaller','larger')), None) if size_index is None or _invalid_core_value('font-size', [tokens[size_index]]): return True prefix_names = {'normal','italic','oblique','small-caps','bold','bolder','lighter', 'ultra-condensed','extra-condensed','condensed','semi-condensed', 'semi-expanded','expanded','extra-expanded','ultra-expanded'} groups, normal = set(), 0 for index, token in enumerate(tokens[:size_index]): if token.type == 'ident' and token.lower_value == 'normal': normal += 1; continue if token.type == 'ident' and token.lower_value in prefix_names: name = token.lower_value group = 'style' if name in ('italic','oblique') else 'variant' if name == 'small-caps' else 'weight' if name in ('bold','bolder','lighter') else 'stretch' elif token.type == 'number' and 1 <= token.value <= 1000: group = 'weight' elif token.type == 'dimension' and token.lower_unit in ('deg','grad','rad','turn'): if not index or getattr(tokens[index-1], 'lower_value', '') != 'oblique': return True continue else: return True if group in groups: return True groups.add(group) if len(groups) + normal > 4: return True end = size_index + 1 if end < len(tokens) and tokens[end].type=='literal' and tokens[end].value=='/': end += 2 if end > len(tokens) or _invalid_core_value('line-height', [tokens[end-1]]): return True if end >= len(tokens): return True try: _font_names(_text(tokens[end:])) except ValueError: return True # Retain valid, unsupported prefixes and relative sizes as CSS. return False scalar = {'font-size','line-height','letter-spacing','text-indent','font-weight','color','background-color','text-align', 'margin-top','margin-bottom','margin-left','margin-right'} if len(tokens) != 1 and prop in scalar: return True lines = {'none','underline','overline','line-through','blink'} if prop in ('text-decoration','text-decoration-line'): names = [t.lower_value for t in tokens if t.type == 'ident'] selected = [name for name in names if name in lines] if 'none' in selected and len(selected)>1 or len(selected)!=len(set(selected)): return True if prop == 'text-decoration-line': return any(t.type!='ident' or t.lower_value not in lines for t in tokens) groups = set() for token in tokens: if token.type=='ident' and token.lower_value in lines: continue if token.type=='ident' and token.lower_value in {'solid','double','dotted','dashed','wavy'}: group = 'style' elif token.type=='ident' and token.lower_value in {'auto','from-font'}: group = 'thickness' elif token.type=='function': group = 'thickness' if token.lower_name in ('calc','min','max','clamp') else 'color' if _invalid_core_value('font-size' if group == 'thickness' else 'color', [token]): return True elif parse_color(token) is not None: group = 'color' elif token.type in ('dimension','percentage','number') and not _invalid_core_value('font-size',[token]): group = 'thickness' else: return True if group in groups: return True groups.add(group) if len(tokens) != 1: return False token = tokens[0] if token.type == 'string' and prop != 'font-family' and not prop.startswith('--'): return True wide = {'inherit', 'initial', 'unset', 'revert', 'revert-layer'} if token.type == 'ident' and token.lower_value in wide: return False lengths = {'font-size', 'line-height', 'letter-spacing', 'text-indent', 'padding', 'border-width', 'margin-top', 'margin-bottom', 'margin-left', 'margin-right'} keywords = { 'font-size': {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'xxx-large', 'larger', 'smaller', 'math'}, 'line-height': {'normal'}, 'letter-spacing': {'normal'}, 'border-width': {'thin', 'medium', 'thick'}, 'font-weight': {'normal', 'bold', 'bolder', 'lighter'}, 'font-style': {'normal', 'italic', 'oblique'}, 'text-align': {'left','right','center','justify','start','end','match-parent','justify-all'}, 'border-style': {'none','hidden','solid','dotted','dashed','double','groove','ridge','inset','outset'}, **{f'margin-{side}': {'auto'} for side in ('top', 'bottom', 'left', 'right')}, } if token.type == 'ident': if prop in ('color', 'background-color', 'border-color'): return parse_color(token) is None if prop in lengths or prop in keywords: return token.lower_value not in keywords.get(prop, set()) if prop in lengths and token.type in ('dimension', 'number', 'percentage'): if token.value < 0 and prop not in ('letter-spacing', 'text-indent') and not prop.startswith('margin-'): return True if token.type == 'number': return prop != 'line-height' and token.value != 0 if token.type == 'percentage': return prop not in ('font-size', 'line-height', 'text-indent', 'padding') and not prop.startswith('margin-') units = {'px', 'pt', 'pc', 'in', 'cm', 'mm', 'q', 'em', 'rem', 'ex', 'rex', 'ch', 'rch', 'cap', 'rcap', 'ic', 'ric', 'lh', 'rlh', 'vw', 'vh', 'vi', 'vb', 'vmin', 'vmax', 'cqw', 'cqh', 'cqi', 'cqb', 'cqmin', 'cqmax'} units.update(prefix + unit for prefix in ('s', 'l', 'd') for unit in ('vw', 'vh', 'vi', 'vb', 'vmin', 'vmax')) return token.lower_unit not in units if prop == 'font-weight' and token.type == 'number': return not 1 <= token.value <= 1000 if prop == 'font-weight' and token.type in ('dimension','percentage'): return True if prop in ('font-style','text-align','border-style') and token.type in ('dimension','percentage','number'): return True return False def _collect_cascade(source: str, result: Analysis): """Choose core declarations by importance, specificity and source order.""" winners = {target: {} for target in (*SELECTORS, LIST_PARAGRAPH)} 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 = {} aliases = _rule_aliases(_split(node.prelude)) for part in _split(node.prelude): selector = _selector(part) target = aliases.get(selector) if target: direct = int(target != 'blockquote' or selector.endswith(' p')) targets[target] = max(targets.get(target, (0, (0, 0))), (direct, _specificity(selector))) if selector in ('p', '.reader p'): for context in ('blockquote', LIST_PARAGRAPH): targets[context] = max(targets.get(context, (0, (0, 0))), (1, _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 any(d.type == 'declaration' and (_property(d) in CORE_PROPERTIES or _property(d)=='font') and _invalid_core_value(_property(d), d.value) for d in expanded): # One invalid component invalidates the entire shorthand. result.notes.append(f'已忽略无效的 {raw.lower_name}: {_text(raw.value)},沿用前面的有效声明') continue 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 bindings = [(target, target, direct, specificity) for target, (direct, specificity) in targets.items()] # Old baseline groups directly select their child elements too. for selector, origin in aliases.items(): child = {'th': 'table_head', 'td': 'table_cell', 'code': 'code_block', 'pre': 'code_block'}.get(selector.removeprefix('.reader ')) if child and origin in ('table', 'code'): if origin == 'table' and prop in PROPERTIES['border_color'] | PROPERTIES['border_width'] | PROPERTIES['border_style'] | PROPERTIES['padding'] | set(TABLE_OPTIONS.values()): continue bindings.append((child, origin, 1, _specificity(selector))) character_props = set().union(*(PROPERTIES[g] for g in ('fonts','size','bold','italic','color','tracking','decoration'))) for target, origin, direct, specificity in bindings: if target == 'code_block' and prop in character_props: # Plain pre typography is inherited by the inner code. direct = 0 if all(s in ('pre', '.reader pre') for s, t in aliases.items() if t == origin) else 1 rank = (direct, declaration.important, specificity, order, position) if prop not in winners[target] or rank >= winners[target][prop][0]: winners[target][prop] = (rank, _text(declaration.value), origin) return winners class _CoreRuleReader: """Convert one target's winning CSS values to editable/Word style fields.""" def __init__(self, target, entries, result, font_size_px): self.target, self.entries, self.result = target, entries, result self.font_size_px = font_size_px self.props = {key: value[1] for key, value in entries.items()} self.rule = {} def parse(self): self.read('font-size', self.sized) self.read('font-family', self.families) self.choice('font-weight', 'bold', {'bold': True, '700': True, 'normal': False, '400': False}) self.choice('font-style', 'italic', {'italic': True, 'normal': False}) self.choice('text-align', 'alignment', {name: name for name in ('left', 'center', 'right', 'justify')}) self.read('color', self.color) self.read('letter-spacing', self.tracking) decorations = [prop for prop in ('text-decoration', 'text-decoration-line') if prop in self.entries] if decorations: self.read(max(decorations, key=lambda prop: self.entries[prop][0]), self.decoration) for prop, field in (('background-color', 'background_color'), ('border-color', 'border_color')): self.read(prop, lambda value, field=field: self.effect_color(value, field)) for prop, field in (('border-width', 'border_width'), ('padding', 'cell_padding'), ('--mdhelper-list-level-indent', 'level_indent')): self.read(prop, lambda value, field=field: self.effect_length(value, field)) self.choice('border-style','border_style',{name:name for name in ('none','hidden','solid','dotted','dashed','double','groove','ridge','inset','outset')}) self.choice(TABLE_OPTIONS['table_border_mode'], 'table_border_mode', {name: name for name in ('grid', 'horizontal', 'none')}) for field in TABLE_BOOL_FIELDS: self.choice(TABLE_OPTIONS[field], field, {'true': True, 'false': False}) self.read(TABLE_OPTIONS['table_stripe_color'], lambda value: self.effect_color(value, 'table_stripe_color')) self.choice('list-style-type', 'list_marker', {x: x for x in ('none', 'disc', 'circle', 'square', 'decimal', 'lower-alpha', 'upper-alpha', 'lower-roman', 'upper-roman')}) self.read('line-height', self.line) for side, prefix in (('left', 'left_indent'), ('right', 'right_indent'), ('top', 'space_before'), ('bottom', 'space_after')): self.read('margin-' + side, lambda value, prefix=prefix: self.margin(value, prefix)) self.read('text-indent', self.indent) self.pagination() self.choice('--mdhelper-contextual-spacing', 'contextual_spacing', {'true': True, 'false': False}) from .style_catalog import CATALOG, CHARACTER_FIELDS unsupported = set() if self.target != 'table': unsupported.update(TABLE_ONLY_FIELDS) if not self.target.startswith('list'): unsupported.update(('list_marker', 'level_indent')) if CATALOG[self.target].kind == 'character': unsupported.update(set(self.rule) - CHARACTER_FIELDS) for field in sorted(unsupported & self.rule.keys()): self.rule.pop(field) self.result.notes.append(f'{LABELS[self.target]}的 {field} 仅保留为 CSS(不适用于该 Word 样式类型)') return self.rule def decoration(self, value): if value.lower() in ('initial', 'unset'): self.rule.update(underline=False, strike=False) return if value.lower() == 'revert': self.rule.update(underline=self.target == 'link', strike=self.target == 'strike') return if re.sub(r'\s+', '', value) == re.sub(r'\s+', '', DECORATION_EXPRESSION): for key in ('underline', 'strike'): self.choice('--mdhelper-' + key, key, {'true': True, 'false': False}) return parts = value.split() if not parts or not set(parts) <= {'none', 'underline', 'line-through'}: raise ValueError self.rule.update(underline='underline' in parts, strike='line-through' in parts) def effect_color(self, value, field): if value == 'transparent': self.rule[field] = value; return color = parse_color(value) if color is None or color == 'currentColor' or color.alpha != 1: raise ValueError self.rule[field] = '#' + ''.join(f'{round(v * 255):02x}' for v in color[:3]) def effect_length(self, value, field): amount, unit = _length(value, ('pt', 'px')) self.rule[field] = amount * (.75 if unit == 'px' else 1) def pagination(self): breaks = ( ('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')), ) for field, modern, legacy, yes in breaks: candidates = [name for name in (modern, legacy) if name in self.entries] if candidates: prop = max(candidates, key=lambda name: self.entries[name][0]) self.choice(prop, field, {**{v: True for v in yes}, 'auto': False}) widow_values = [self.props[p] for p in ('widows', 'orphans') if p in self.props] if widow_values: if all((v == '1' for v in widow_values)) or all((v == '2' for v in widow_values)): self.rule['widow_control'] = widow_values[0] == '2' else: self.result.notes.append(f'{LABELS[self.target]}的 widows/orphans 仅保留为 CSS') def read(self, prop, convert): if prop not in self.props: return if self.props[prop].lower() in ('inherit', 'unset', 'revert') and prop != 'color': return try: convert(self.props[prop]) except (ValueError, KeyError, TypeError): self.result.notes.append(f'{LABELS[self.target]}的 {prop}: {self.props[prop]} 仅保留为 CSS') def choice(self, prop, key, options): self.read(prop, lambda value: self.rule.update({key: options[value.lower()]})) def sized(self, value): amount, unit = _length(value, ('pt', 'px')) if not 0 < amount <= 200: raise ValueError self.rule.update(font_size=amount, font_size_unit=unit) def families(self, value): if re.sub('\\s+', '', value) == re.sub('\\s+', '', FONT_EXPRESSION): for key, variable in FONT_VARIABLES.items(): if variable in self.props: self.rule[key] = _font_names(self.props[variable])[0] else: names = _font_names(value) chinese = names[1] if len(names) > 1 and names[1] not in ('serif', 'sans-serif', 'monospace') else names[0] self.rule.update(english_font_family=names[0], chinese_font_family=chinese) def color(self, value): if value.lower() in ('currentcolor', 'inherit', 'unset'): self.rule['font_color'] = 'inherit' return if value.lower() == 'var(--reader-text-color, #23272f)': self.rule['font_color'] = 'auto' return rgba = parse_color(value) if rgba is None or isinstance(rgba, str) or rgba.alpha != 1: raise ValueError self.rule['font_color'] = '#' + ''.join((f'{round(v * 255):02x}' for v in rgba[:3])) def tracking(self, value): amount, unit = (0, 'pt') if value == 'normal' else _length(value, ('pt', 'px'), negative=True) amount *= 0.75 if unit == 'px' else 1 if abs(amount) > 100: raise ValueError self.rule['letter_spacing'] = amount def line(self, value): if value == 'normal': amount, mode = (1, 'multiple') elif re.fullmatch('(?:\\d+(?:\\.\\d*)?|\\.\\d+)%?', value): amount = float(value.rstrip('%')) / (100 if value.endswith('%') else 1) mode = 'multiple' else: amount, unit = _length(value, ('pt', 'px')) amount *= 0.75 if unit == 'px' else 1 mode = 'at_least' if self.props.get('--mdhelper-line-spacing-mode') == 'at-least' else 'exact' if not 0.1 <= amount <= 500: raise ValueError self.rule.update(line_height_value=amount, line_spacing_mode=mode) def indent(self, value): amount, unit = _length(value, ('em', 'pt', 'px'), negative=True) self.rule.update(indent_mode='none' if not amount else 'first' if amount > 0 else 'hanging', indent_value=abs(amount)) if amount and unit != 'em': self.rule['indent_unit'] = unit def margin(self, value, 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 * 0.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 self.rule.update({prefix + '_value': amount, prefix + '_unit': 'line' if unit == 'lh' else unit}) 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 = _collect_cascade(source, result) for target, entries in winners.items(): rule = _CoreRuleReader('paragraph' if target == LIST_PARAGRAPH else target, entries, result, font_size_px).parse() owned = _owned_fields(entries, target) rule = {field: value for field, value in rule.items() if field in owned} if rule: result.rules[target] = rule if target == 'blockquote': container = {prop: entry for prop, entry in entries.items() if not entry[0][0]} inherited = _CoreRuleReader(target, container, result, font_size_px).parse() if inherited: result.rules['_quote_container'] = inherited 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:", 'text-decoration-line:'))] if 'underline' in rule or 'strike' in rule: declarations.extend(f'--mdhelper-{key}: {str(rule[key]).lower()};' for key in ('underline', 'strike') if key in rule) declarations.append(f'text-decoration-line: {DECORATION_EXPRESSION};') 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)) winners = _collect_cascade(source, Analysis()).get(target, {}) important = {group for group in changed for prop in PROPERTIES[group] if prop in winners and winners[prop][0][1]} 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) aliases = _rule_aliases(selectors) 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} if 'border_width' in fragment and 'border_style' in after: fragment['border_style'] = after['border_style'] 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(_rule_aliases(_split(node.prelude)).get(_selector(part)) == target and (target != 'code_block' or 'data-mdh-style' in _selector(part)) and (target != 'blockquote' or _selector(part).endswith(' p')) 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, font_family: str = '', font_size_px: float = 16, preset: str = 'default') -> str: """Materialize the few core features which need companion reader rules.""" from .style_catalog import explicit_rules, character_declarations, normalize_metadata, CATALOG inherited = explicit_rules(rules) from .document_style import resolved_rules effective = resolved_rules(rules, font_family, font_size_px, preset) inherited.update(character_declarations(rules, effective)) winners = _collect_cascade(source, Analysis()) def priority(declarations, entries): important_groups = {g for g, props in PROPERTIES.items() if any(p in entries and entries[p][0][1] for p in props)} return [d.rstrip(';')+' !important;' if any(d.split(':',1)[0] in PROPERTIES[g] for g in important_groups) else d for d in declarations] for key, metadata in normalize_metadata(rules.get('_metadata')).items(): detached_legacy = key in ('inline_code','table_head','table_cell') and metadata.get('based_on') == '' if 'based_on' in metadata and (CATALOG[key].kind != 'character' or detached_legacy): inherited[key] = dict(effective[key]) if detached_legacy: inherited[key].update(underline=False, strike=False) if key == 'inline_code': inherited[key]['background_color'] = 'transparent' elif 'background_color' in rules.get('table', {}): inherited[key]['background_color'] = ('var(--reader-table-header, #f1f5f9)' if key == 'table_head' else 'var(--mdhelper-cell-fill, transparent)') if not metadata['based_on'] and CATALOG[key].base: legacy = rules.get(CATALOG[key].base, {}) defaults = {'underline': False, 'strike': False, 'background_color': 'transparent', 'list_marker': 'decimal' if key == 'list_ordered' else 'none' if key == 'list_task' else 'disc', 'level_indent': 36} inherited[key].update({field: value for field, value in defaults.items() if field in legacy and field not in rules.get(key, {})}) inherited = {key: {field: value for field, value in rule.items() if field not in rules.get(key, {})} for key, rule in inherited.items()} contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if isinstance(rule, dict) and rule.get("contextual_spacing")} helpers = build_document_style_css(contextual, reset_list_paragraphs=False) helpers += '\n' + table_helper_css(rules.get('table', {}), any( winners['table'].get(p, ((False,False),))[0][1] for p in PROPERTIES['border_style'])) # Emit the same font variables as the authored rules; a child's Chinese # font declaration must not shadow an inherited English font declaration. for key, rule in inherited.items(): declarations = _core_declarations(rule) if str(rule.get('background_color', '')).startswith('var('): declarations.append('background-color: '+rule['background_color']+';') entries = winners.get(key, {}) if key == 'inline_code': entries = {**winners.get('code', {}), **entries} declarations = priority(declarations, entries) if declarations: helpers += '\n' + SELECTORS[key] + ' { ' + ' '.join(declarations) + ' }' for key in ('table_head', 'table_cell'): rule = {**inherited.get(key, {}), **rules.get(key, {})} margins = {field: value for field, value in rule.items() if field.startswith(('space_before_', 'space_after_', 'left_indent_', 'right_indent_'))} declarations = _core_declarations(margins) if declarations: helpers += '\n' + SELECTORS[key] + ' > .mdhelper-cell-paragraph { ' + ' '.join(declarations) + ' }' # The legacy code rule also selects the inner . Let the semantic # block own its typography instead of leaving that old child rule in charge. block = {**inherited.get('code_block', {}), **rules.get('code_block', {})} block_properties = { 'font-family': ('chinese_font_family', 'english_font_family'), 'font-size': ('font_size',), 'font-weight': ('bold',), 'font-style': ('italic',), 'color': ('font_color',), 'letter-spacing': ('letter_spacing',), 'text-decoration-line': ('underline', 'strike'), } propagated = [prop + ': inherit;' for prop, fields in block_properties.items() if any(field in block for field in fields)] if 'background_color' in block: propagated.append('background-color: transparent;') block_selector = SELECTORS['code_block'] + ' > code' if propagated: helpers += '\n' + block_selector + ' { ' + ' '.join(priority(propagated, winners.get('code_block', {}))) + ' }' token_properties = [prop + ': inherit;' for prop, field in (('color', 'font_color'), ('font-weight', 'bold'), ('font-style', 'italic')) if field in block] if token_properties: helpers += '\n' + block_selector + ' span { ' + ' '.join(token_properties) + ' }' layout_helpers = {} for key, rule in explicit_rules(rules).items(): materialized = {**inherited.get(key, {}), **rule} layout_helpers[key] = {field: materialized[field] for field in ('level_indent', 'contextual_spacing') if field in materialized} helpers += '\n' + build_document_style_css(layout_helpers, reset_list_paragraphs=False) # Independent flags retain their inherited counterpart. Literal CSS such as # text-decoration-line:none still wins over this opt-in variable expression. for key, rule in effective.items(): if any(field in rules.get(key, {}) or field in inherited.get(key, {}) for field in ('underline', 'strike')): decoration = ' '.join(token for field, token in (('underline', 'underline'), ('strike', 'line-through')) if rule.get(field)) or 'none' helpers += '\n' + SELECTORS[key] + ' { --mdhelper-text-decoration: ' + decoration + '; }' 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')}; }}" paragraph_overrides = rules.get(LIST_PARAGRAPH, {}) resets = [f'margin-{side}: 0;' for side, field in (('top','space_before_value'),('bottom','space_after_value'),('left','left_indent_value'),('right','right_indent_value')) if field not in paragraph_overrides] if 'indent_mode' not in paragraph_overrides: resets.append('text-indent: inherit;') for target in ('list','list_bullet','list_ordered','list_task'): if rules.get(target) and resets: helpers += '\n' + SELECTORS[target] + ' > p { ' + ' '.join(resets) + ' }' from .reader_decoration import decoration_css return decoration_css(rules, inherited, SELECTORS, (helpers.strip() + "\n\n" + source).strip()).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) from .style_catalog import normalize_metadata supplied_rules = payload.get('rules') if isinstance(payload.get('rules'), dict) else {} metadata = normalize_metadata(supplied_rules.get('_metadata')) if metadata: result.rules['_metadata'] = metadata from .style_presets import DOCUMENT_STYLE_PRESETS if isinstance(supplied_rules.get('_preset'), str) and supplied_rules['_preset'] in DOCUMENT_STYLE_PRESETS: result.rules['_preset'] = supplied_rules['_preset'] 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 {})}