fix: preserve nested CSS, color inputs and Word code inheritance

This commit is contained in:
2026-11-05 09:32:49 +08:00
parent b3d8f6e26a
commit d0f95d277a
5 changed files with 157 additions and 10 deletions
+62
View File
@@ -0,0 +1,62 @@
"""Regressions from the 0.5.4 rendering, synchronization and Word audit."""
import pytest
from PySide6.QtWidgets import QDialogButtonBox
from mdhelper.style_dialog import DocumentStyleEditorDialog
from mdhelper.style_sync import normalize_payload
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')
CODE_SOURCE = '# Parent\n\n`Inline`\n\n```text\nBlock\n```'
CODE_RULES = {'h1': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt'},
'_metadata': {'code': {'based_on': 'h1'}}}
@pytest.mark.parametrize('nested', ['& strong {color:red}', '@media screen { & strong {color:red} }'])
def test_nested_css_still_renders_with_decoration_cancellation(qt_application, tmp_path, nested):
payload = normalize_payload({'css': 'em{text-decoration:none} .reader p {' + nested + '}'})
assert browser(qt_application, tmp_path, payload, 'Body **Bold**',
"getComputedStyle(document.querySelector('strong')).color") == 'rgb(255, 0, 0)'
assert normalize_payload(payload) == payload
@pytest.mark.parametrize('target,field,widget', [('paragraph','background_color','background_edit'),
('table','border_color','border_color_edit'), ('table','table_stripe_color','table_stripe_color_edit')])
def test_invalid_color_does_not_erase_saved_style(qt_application, target, field, widget):
dialog = DocumentStyleEditorDialog({'rules': {target: {field: '#ff0000'}}})
try:
dialog.select_target(target)
before = dialog.style_payload()
edit = getattr(dialog, widget)
edit.setText('#gggggg'); edit.editingFinished.emit()
assert dialog.rules == before['rules'] and dialog.extra_css_edit.toPlainText() == before['css']
assert not dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
assert '无效' in dialog.color_error_label.text()
with pytest.raises(ValueError): dialog.style_payload()
dialog.select_target('h1')
assert dialog._current_target == target
edit.setText('#00ff00'); edit.editingFinished.emit()
assert dialog.style_payload()['rules'][target][field] == '#00ff00'
assert dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
edit.clear(); edit.editingFinished.emit()
assert field not in dialog.style_payload()['rules'].get(target, {})
finally: dialog.close()
@pytest.mark.parametrize('engine', ENGINES)
def test_word_code_keeps_editable_parent_chain(tmp_path, engine):
doc, styles = parts(export_markdown_to_docx(CODE_SOURCE, tmp_path/'chain.docx', engine=engine, style_rules=CODE_RULES))
identifiers = [s.get(W+'styleId') for s in styles.findall(W+'style')]
assert len(identifiers) == len(set(identifiers))
base = styles.find("w:style[@w:styleId='MDHelperH1Char']", NS)
assert base.find('w:link', NS).get(W+'val') == 'MDHelperH1'
code = styles.find("w:style[@w:styleId='MDHelperCodeChar']", NS)
assert code.find('w:basedOn', NS).get(W+'val') == 'MDHelperH1Char'
assert code.find('w:rPr/w:color', NS) is None
base.find('w:rPr/w:color', NS).set(W+'val', '0000ff')
base.find('w:rPr/w:sz', NS).set(W+'val', '56')
run = next(r for r in effective_document(doc, styles).iter(W+'r') if ''.join(r.itertext())=='Inline')
assert run.find('w:rPr/w:color', NS).get(W+'val') == '0000ff'
assert run.find('w:rPr/w:sz', NS).get(W+'val') == '56'
+34
View File
@@ -0,0 +1,34 @@
param([string]$Python = (Join-Path $PSScriptRoot '..\mdhelper_env\mdhelper_env\Scripts\python.exe'))
$ErrorActionPreference='Stop'
Push-Location (Join-Path $PSScriptRoot '..')
$word=$null
try {
$folder = (@'
import sys,tempfile
from pathlib import Path
sys.path.insert(0,str(Path('tests').resolve()))
from test_style_revision_055 import *
folder=Path(tempfile.mkdtemp(prefix='MDHelper-055-Word-'))
for engine in ENGINES:
export_markdown_to_docx(CODE_SOURCE,folder/f'{engine}-code.docx',engine=engine,style_rules=CODE_RULES)
print(folder)
'@ | & $Python -B -).Trim()
if ($LASTEXITCODE -ne 0) {throw 'Fixture generation failed'}
$word=New-Object -ComObject Word.Application
$word.Visible=$false;$word.DisplayAlerts=0
foreach($engine in @('builtin','python-docx','pandoc')) {
$doc=$word.Documents.Open((Join-Path $folder "$engine-code.docx"),$false,$true)
try {
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Parent')
$range.Style.Font.Color=16711680;$range.Style.Font.Size=28
foreach($text in @('Inline','Block')) {
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($text)
if($range.Font.Color -ne 16711680 -or $range.Font.Size -ne 28){throw "$engine $text does not follow ancestor: $($range.Font.Color), $($range.Font.Size)"}
}
Write-Output "$engine code ancestor edits passed"
} finally {$doc.Close(0);[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc)}
}
} finally {
if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)}
Pop-Location
}