fix: preserve scoped CSS and editable Word inheritance

This commit is contained in:
2026-10-30 14:29:42 +08:00
parent c6d008486e
commit 2d2ce27ec9
8 changed files with 199 additions and 11 deletions
+50 -7
View File
@@ -55,7 +55,8 @@ def _normalize_selector_text(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"}
"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'})
@@ -92,6 +93,32 @@ 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
@@ -256,9 +283,10 @@ def _collect_cascade(source: str, result: Analysis):
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)
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)))
@@ -296,10 +324,21 @@ 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, (direct, specificity) in targets.items():
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['padding']: 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))
winners[target][prop] = (rank, _text(declaration.value), origin)
return winners
@@ -467,6 +506,8 @@ def analyze_css(source: str, font_size_px: float = 16) -> Analysis:
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
result.notes = list(dict.fromkeys(result.notes))
@@ -518,11 +559,12 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal
output.append(node)
continue
selectors = _split(node.prelude)
selected = [p for p in selectors if ALIASES.get(_selector(p)) == target]
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]
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
@@ -568,7 +610,8 @@ 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 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: