606 lines
32 KiB
Python
606 lines
32 KiB
Python
"""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",),
|
|
'decoration': ('underline', 'strike'), 'background': ('background_color',),
|
|
'border_color': ('border_color',), 'border_width': ('border_width',), '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")},
|
|
}
|
|
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'}, '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"},
|
|
}
|
|
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.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)'
|
|
|
|
|
|
@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(".") + 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":
|
|
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 _collect_cascade(source: str, result: Analysis):
|
|
"""Choose core declarations by importance, specificity and source order."""
|
|
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))
|
|
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('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(('border_color', 'border_width', 'cell_padding'))
|
|
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 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 or self.props[prop].lower() in ('inherit', 'unset', 'revert'):
|
|
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', '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(target, entries, result, font_size_px).parse()
|
|
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:", '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))
|
|
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, 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, normalize_metadata, CATALOG
|
|
inherited = explicit_rules(rules)
|
|
from .document_style import resolved_rules
|
|
effective = resolved_rules(rules, font_family, font_size_px, preset)
|
|
for key, metadata in normalize_metadata(rules.get('_metadata')).items():
|
|
if 'based_on' in metadata and CATALOG[key].kind != 'character':
|
|
inherited[key] = dict(effective[key])
|
|
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)
|
|
# 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 declarations: helpers += '\n' + SELECTORS[key] + ' { ' + ' '.join(declarations) + ' }'
|
|
# The legacy code rule also selects the inner <code>. 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(propagated) + ' }'
|
|
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)
|
|
# 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')}; }}"
|
|
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)
|
|
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 supplied_rules.get('_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 {})}
|