fix: align contextual CSS rendering and Word styles

This commit is contained in:
2026-10-30 13:12:05 +08:00
parent cc4f91899e
commit f9bf62b71c
17 changed files with 313 additions and 53 deletions
+63 -9
View File
@@ -63,6 +63,7 @@ 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
@@ -211,9 +212,40 @@ def _font_names(value):
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: return False
token = tokens[0]
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'},
**{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
return False
def _collect_cascade(source: str, result: Analysis):
"""Choose core declarations by importance, specificity and source order."""
winners = {target: {} for target in SELECTORS}
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}")
@@ -228,7 +260,11 @@ def _collect_cascade(source: str, result: Analysis):
selector = _selector(part)
target = ALIASES.get(selector)
if target:
targets[target] = max(targets.get(target, (0, 0)), _specificity(selector))
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)
@@ -240,6 +276,11 @@ def _collect_cascade(source: str, result: Analysis):
result.errors.append(f"第 {raw.source_line} 行:{raw.name} 缺少属性值。")
continue
expanded = _expand(raw)
if any(d.type == 'declaration' and _property(d) in CORE_PROPERTIES 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:
@@ -255,8 +296,8 @@ def _collect_cascade(source: str, result: Analysis):
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)
for target, (direct, specificity) in targets.items():
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))
return winners
@@ -340,7 +381,9 @@ class _CoreRuleReader:
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'):
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])
@@ -367,7 +410,10 @@ class _CoreRuleReader:
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)'):
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)
@@ -420,7 +466,7 @@ def analyze_css(source: str, font_size_px: float = 16) -> Analysis:
return result
winners = _collect_cascade(source, result)
for target, entries in winners.items():
rule = _CoreRuleReader(target, entries, result, font_size_px).parse()
rule = _CoreRuleReader('paragraph' if target == LIST_PARAGRAPH else target, entries, result, font_size_px).parse()
if rule:
result.rules[target] = rule
result.notes = list(dict.fromkeys(result.notes))
@@ -522,7 +568,9 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal
# 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)
all(ALIASES.get(_selector(part)) == target 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)
@@ -556,6 +604,12 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl
for key, rule in inherited.items():
declarations = _core_declarations(rule)
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 <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', {})}
@@ -598,7 +652,7 @@ def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_
if metadata:
result.rules['_metadata'] = metadata
from .style_presets import DOCUMENT_STYLE_PRESETS
if supplied_rules.get('_preset') in 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,