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
+83
View File
@@ -0,0 +1,83 @@
"""Regressions from the 0.5.2 cross-surface style audit."""
import zipfile
from lxml import etree as ET
import pytest
from mdhelper.style_sync import normalize_payload, analyze_css
from mdhelper.style_dialog import DocumentStyleEditorDialog
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS
from test_style_regressions import browser, parts
from docx_assertions import effective_document
ENGINES = ('builtin', 'python-docx', 'pandoc')
SEPARATE_CSS = '.reader th {color:red;font-size:20pt;} .reader td {color:blue;font-size:12pt;} pre {color:green;} code {font-size:11pt;}'
TABLE_SOURCE = '| Header |\n|---|\n| Cell |'
MIX_SOURCE = '**[LinkInner](https://example.com)** and [**BoldInner**](https://example.com)'
MIX_RULES = {'strong': {'font_color': '#ff0000'}, 'link': {'font_color': '#ff0000'}}
LIST_RULES = {'list_bullet': {'indent_mode': 'first', 'indent_value': 18, 'indent_unit': 'pt'}}
def test_legacy_css_keeps_separate_element_scopes_and_gui_edits(qt_application, tmp_path):
payload = normalize_payload({'css': SEPARATE_CSS})
assert normalize_payload(payload) == payload
assert payload['rules']['table_head']['font_color'] == '#ff0000'
assert payload['rules']['table_cell']['font_color'] == '#0000ff'
assert payload['rules']['code_block']['font_color'] == '#008000'
assert 'font_color' not in payload['rules']['code']
actual = browser(qt_application, tmp_path, payload, TABLE_SOURCE + '\n\n`Inline`\n\n```text\nBlock\n```',
"[...document.querySelectorAll('th,td,code')].map(e=>[e.textContent.trim(),getComputedStyle(e).color,parseFloat(getComputedStyle(e).fontSize)])")
assert actual[:2] == [['Header','rgb(255, 0, 0)',pytest.approx(20*4/3,.001)],['Cell','rgb(0, 0, 255)',16]]
assert actual[2][1] != 'rgb(0, 128, 0)' and actual[3][1] == 'rgb(0, 128, 0)'
dialog = DocumentStyleEditorDialog(payload)
try:
dialog.select_target('table_head'); dialog.font_size_spin.setValue(22)
updated = dialog.style_payload()
assert updated['rules']['table_head']['font_size'] == 22
assert updated['rules']['table_cell']['font_size'] == 12
finally: dialog.close()
def test_old_baseline_groups_keep_inheritance_and_importance():
original = {'table': {'font_color':'#ff0000','cell_padding':5}, 'code':{'font_size':15,'font_size_unit':'pt'}}
payload = normalize_payload({'rules':original})
assert payload['rules'] == original
result = analyze_css('table,th,td {color:red !important;} th {color:blue;}')
assert result.rules['table']['font_color'] == '#ff0000'
assert 'font_color' not in result.rules.get('table_head', {})
@pytest.mark.parametrize('engine', ENGINES)
def test_independent_css_scopes_reach_word(tmp_path, engine):
payload = normalize_payload({'css':SEPARATE_CSS})
path = export_markdown_to_docx(TABLE_SOURCE+'\n\n`Inline`\n\n```text\nBlock\n```',tmp_path/'scopes.docx',engine=engine,style_rules=payload['rules'])
doc,styles = parts(path); rendered=effective_document(doc,styles)
colors={''.join(r.itertext()).strip():r.find('w:rPr/w:color',NS).get(W+'val') for r in rendered.iter(W+'r') if r.find('w:rPr/w:color',NS) is not None}
assert colors['Header']=='ff0000' and colors['Cell']=='0000ff'
assert colors['Block']=='008000' and colors['Inline']!='008000'
@pytest.mark.parametrize('engine', ENGINES)
def test_equal_initial_colors_keep_inner_explicit_override(tmp_path, engine):
path=export_markdown_to_docx(MIX_SOURCE,tmp_path/'mix.docx',engine=engine,style_rules=MIX_RULES)
doc,styles=parts(path)
styles.find("w:style[@w:styleId='MDHelperLink']/w:rPr/w:color",NS).set(W+'val','0000ff')
rendered=effective_document(doc,styles)
colors={''.join(r.itertext()):r.find('w:rPr/w:color',NS).get(W+'val') for r in rendered.iter(W+'r') if 'Inner' in ''.join(r.itertext())}
assert colors=={'LinkInner':'0000ff','BoldInner':'ff0000'}
@pytest.mark.parametrize('engine', ENGINES)
@pytest.mark.parametrize('source', ['- First\n- Second','- First\n\n- Second','- First\n - Second'])
def test_numbering_does_not_override_named_list_indents(tmp_path, engine, source):
path=export_markdown_to_docx(source,tmp_path/'list.docx',engine=engine,style_rules=LIST_RULES)
with zipfile.ZipFile(path) as package:
doc=ET.fromstring(package.read('word/document.xml')); numbering=ET.fromstring(package.read('word/numbering.xml'))
for numpr in doc.findall('.//w:pPr/w:numPr',NS):
num_id=numpr.find(W+'numId').get(W+'val')
num=numbering.find(f"w:num[@w:numId='{num_id}']",NS)
abstract_id=num.find(W+'abstractNumId').get(W+'val')
abstract=numbering.find(f"w:abstractNum[@w:abstractNumId='{abstract_id}']",NS)
assert abstract.find('.//w:pPr/w:ind',NS) is None
assert num.find('.//w:pPr/w:ind',NS) is None
identity=abstract.find(W+'nsid').get(W+'val')
assert sum(n.find(W+'nsid') is not None and n.find(W+'nsid').get(W+'val')==identity for n in numbering.findall(W+'abstractNum'))==1
+20
View File
@@ -13,10 +13,13 @@ from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.style_catalog import style_name
from test_style_regressions import PARTIAL_RULES, UNIT_RULES, NESTED_SOURCE, NESTED_RULES
from test_style_revision_052 import REPEATED_SOURCE, REPEATED_RULES, ABSOLUTE_PAYLOAD, SCOPED_SOURCE, SCOPED_CSS
from test_style_revision_053 import MIX_SOURCE, MIX_RULES, LIST_RULES
from mdhelper.style_sync import normalize_payload
folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-'))
rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}}
for engine in ('builtin', 'python-docx', 'pandoc'):
export_markdown_to_docx(MIX_SOURCE, folder / (engine + '-equal-mix.docx'), engine=engine, style_rules=MIX_RULES)
export_markdown_to_docx('- FirstItem\n\n- SecondItem', folder / (engine + '-list-first.docx'), engine=engine, style_rules=LIST_RULES)
export_markdown_to_docx(SOURCE + '\n\n## Child title', folder / (engine + '.docx'), engine=engine, style_rules=rules)
export_markdown_to_docx('# Parent\n\n## Child', folder / (engine + '-partial.docx'), engine=engine, style_rules=PARTIAL_RULES)
export_markdown_to_docx('# Parent\n\n## ChildUnits', folder / (engine + '-units.docx'), engine=engine, style_rules=UNIT_RULES)
@@ -39,6 +42,23 @@ print(folder)
$word.Visible = $false
$word.DisplayAlerts = 0
foreach ($engine in @('builtin', 'python-docx', 'pandoc')) {
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine-equal-mix.docx"), $false, $true)
try {
$doc.Styles.Item($names.link).Font.Color = 16711680
foreach ($text in @('LinkInner','BoldInner')) {
$range = $doc.Content.Duplicate; [void]$range.Find.Execute($text)
$expected = if ($text -eq 'BoldInner') {255} else {16711680}
if ($range.Font.Color -ne $expected) { throw "$engine lost explicit inner color when values initially matched." }
}
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine-list-first.docx"), $false, $true)
try {
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('FirstItem')
if ($range.ParagraphFormat.FirstLineIndent -ne 18) { throw "$engine numbering overrides first-line indentation." }
$style = $range.Style; $style.ParagraphFormat.FirstLineIndent = 24
if ($range.ParagraphFormat.FirstLineIndent -ne 24) { throw "$engine numbering blocks Word style edits." }
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
Write-Output "$engine passed: explicit equal-value overrides and list indentation style edits."
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine.docx"), $false, $true)
try {
$range = $doc.Content.Duplicate