fix: preserve scoped CSS and editable Word inheritance
This commit is contained in:
@@ -78,6 +78,7 @@ class WordStyles:
|
||||
self.created = {}
|
||||
self.characters = {}
|
||||
self.number_overrides = {}
|
||||
self.style_numbering = {}
|
||||
for key in CATALOG:
|
||||
if CATALOG[key].kind == 'character': self.character(key)
|
||||
elif CATALOG[key].kind == 'paragraph': self.paragraph(key)
|
||||
@@ -167,8 +168,12 @@ class WordStyles:
|
||||
keys = ordered_styles(keys)
|
||||
if not keys: return ''
|
||||
merged = {}
|
||||
owners = {}
|
||||
for key in keys:
|
||||
merged.update({field: value for field, value in self.character_rule(key).items() if not (field == 'font_color' and value == 'inherit')})
|
||||
for field, value in self.character_rule(key).items():
|
||||
if field == 'font_color' and value == 'inherit': continue
|
||||
merged[field] = value
|
||||
owners[field] = key
|
||||
identifier = self.character(keys[0]) if len(keys) == 1 else 'MDHelperMix' + ''.join(style_id(key)[8:] for key in keys)
|
||||
if identifier not in self.created:
|
||||
base = 'link' if 'link' in keys else keys[0]
|
||||
@@ -176,7 +181,7 @@ class WordStyles:
|
||||
props, old = child(style, 'rPr'), ET.Element(W + 'rPr')
|
||||
_run_properties(props, merged)
|
||||
_run_properties(old, self.character_rule(base))
|
||||
_delta(props, old)
|
||||
_delta(props, old, {field: value for field, value in merged.items() if owners[field] != base})
|
||||
return identifier
|
||||
|
||||
def syntax_style(self, run_id, target):
|
||||
@@ -207,6 +212,34 @@ class WordStyles:
|
||||
abstract = self.numbering.find(f"w:abstractNum[@w:abstractNumId='{abstract_id}']", NS)
|
||||
return level, abstract.find(f"w:lvl[@w:ilvl='{level}']", NS) if abstract is not None else None
|
||||
|
||||
def inherit_list_indents(self, numpr):
|
||||
"""Numbering owns the marker; named paragraph styles own indentation."""
|
||||
original = reference(numpr, 'numId')
|
||||
if not original: return
|
||||
if original not in self.style_numbering:
|
||||
_, level = self.list_level(numpr)
|
||||
if level is None: return
|
||||
num = deepcopy(self.numbering.find(f"w:num[@w:numId='{original}']", NS))
|
||||
abstract = deepcopy(level.getparent())
|
||||
num_id = 1 + max(int(n.get(W + 'numId')) for n in self.numbering.findall(W + 'num'))
|
||||
abstract_id = 1 + max(int(n.get(W + 'abstractNumId')) for n in self.numbering.findall(W + 'abstractNum'))
|
||||
num.set(W + 'numId', str(num_id)); val(num, 'abstractNumId', abstract_id)
|
||||
abstract.set(W + 'abstractNumId', str(abstract_id))
|
||||
self.identify_numbering(abstract, abstract_id)
|
||||
for root in (num, abstract):
|
||||
for props in root.iter(W + 'pPr'): remove_fields(props, ('ind', 'tabs'))
|
||||
self.numbering.extend((abstract, num))
|
||||
self.style_numbering[original] = str(num_id)
|
||||
val(numpr, 'numId', self.style_numbering[original])
|
||||
|
||||
def identify_numbering(self, abstract, identifier):
|
||||
# Word coalesces definitions with the same nsid, even when their XML
|
||||
# ids differ. A modified clone must have its own list identity.
|
||||
used = {reference(node, 'nsid') for node in self.numbering.findall(W + 'abstractNum')}
|
||||
candidate = (0x4d440000 + identifier) & 0xffffffff
|
||||
while f'{candidate:08X}' in used: candidate = (candidate + 1) & 0xffffffff
|
||||
val(abstract, 'nsid', f'{candidate:08X}')
|
||||
|
||||
def classify(self, paragraph, original_id):
|
||||
names = self.names(original_id)
|
||||
heading = re.search(r'heading\s*([1-6])', names)
|
||||
@@ -288,6 +321,7 @@ class WordStyles:
|
||||
abstract_id = 1 + max(int(n.get(W + 'abstractNumId')) for n in self.numbering.findall(W + 'abstractNum'))
|
||||
num.set(W + 'numId', str(num_id)); val(num, 'abstractNumId', abstract_id)
|
||||
abstract.set(W + 'abstractNumId', str(abstract_id))
|
||||
self.identify_numbering(abstract, abstract_id)
|
||||
self.numbering.extend((abstract, num))
|
||||
self.number_overrides[key] = str(num_id)
|
||||
val(numpr, 'numId', self.number_overrides[key])
|
||||
@@ -359,6 +393,7 @@ class WordStyles:
|
||||
identifier = self.paragraph(target)
|
||||
if target.startswith('list_'):
|
||||
numpr = ppr.find(W + 'numPr')
|
||||
self.inherit_list_indents(numpr)
|
||||
level, _ = self.list_level(numpr)
|
||||
if level: identifier = self.nested_list(target, level)
|
||||
marker = self.effective[target].get('list_marker')
|
||||
|
||||
@@ -34,6 +34,7 @@ def _order_properties(root):
|
||||
# numbering, bookmarks, tracked changes) while inserting ours in that order.
|
||||
orders = {
|
||||
'numbering': 'numPicBullet abstractNum num numIdMacAtCleanup',
|
||||
'abstractNum': 'nsid multiLevelType tmpl name styleLink numStyleLink lvl',
|
||||
'style': 'name aliases basedOn next link autoRedefine hidden uiPriority semiHidden unhideWhenUsed qFormat locked personal personalCompose personalReply rsid pPr rPr tblPr trPr tcPr tblStylePr',
|
||||
'tblPr': 'tblStyle tblpPr tblOverlap bidiVisual tblStyleRowBandSize tblStyleColBandSize tblW jc tblCellSpacing tblInd tblBorders shd tblLayout tblCellMar tblLook tblCaption tblDescription tblPrChange',
|
||||
'tcPr': 'cnfStyle tcW gridSpan hMerge vMerge tcBorders shd noWrap tcMar textDirection tcFitText vAlign hideMark cellIns cellDel cellMerge tcPrChange',
|
||||
|
||||
@@ -360,7 +360,7 @@ td code {
|
||||
color: #cccccc;
|
||||
}
|
||||
|
||||
pre.highlight {
|
||||
pre:where(.highlight) {
|
||||
margin: 0;
|
||||
padding: 1em;
|
||||
overflow-x: auto;
|
||||
@@ -368,7 +368,7 @@ pre.highlight {
|
||||
color: #000000;
|
||||
}
|
||||
|
||||
:where(html[data-theme="dark"]) pre.highlight {
|
||||
:where(html[data-theme="dark"]) pre:where(.highlight) {
|
||||
background: #1e1e1e;
|
||||
color: #d4d4d4;
|
||||
}
|
||||
|
||||
+50
-7
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user