fix: align nested rendering CSS synchronization and Word style inheritance

This commit is contained in:
2026-11-04 16:42:10 +08:00
parent 6cc833183d
commit 06c5368b05
15 changed files with 408 additions and 42 deletions
+1 -1
View File
@@ -148,7 +148,7 @@ def test_reader_nested_list_indent_uses_own_core_setting(qt_application, tmp_pat
def test_decoration_shorthand_obeys_cascade_in_browser_controls_and_word(qt_application, tmp_path, css, expected):
payload = normalize_payload({'css': css})
assert payload['rules']['link']['underline'] is expected
actual = browser(qt_application, tmp_path, payload, '[Link](#link)', "getComputedStyle(document.querySelector('p a')).textDecorationLine")
actual = browser(qt_application, tmp_path, payload, '[Link](#link)', "getComputedStyle(document.querySelector('p a [data-mdh-text]') || document.querySelector('p a')).textDecorationLine")
assert ('underline' in actual) is expected
dialog = DocumentStyleEditorDialog(payload)
try:
+170
View File
@@ -7,6 +7,7 @@ from mdhelper.docx_style import W, NS
from mdhelper.style_sync import normalize_payload
from test_style_regressions import browser, parts
from docx_assertions import effective_document
from mdhelper.style_dialog import DocumentStyleEditorDialog
ENGINES = ('builtin', 'python-docx', 'pandoc')
TABLE = '| Head | Description |\n|---|---|\n| Alpha | First |\n| Beta | Second |'
@@ -74,3 +75,172 @@ def test_legacy_code_uses_linked_editable_word_base(tmp_path, engine):
inline = styles.find("w:style[@w:styleId='MDHelperInlineCode']",NS)
assert inline.find(W+'basedOn').get(W+'val') == 'MDHelperCodeChar'
assert inline.find('w:rPr/w:color',NS) is None
@pytest.mark.parametrize('engine',ENGINES)
def test_legacy_code_can_still_request_surrounding_color(tmp_path,engine):
rules={**CODE_RULES,'paragraph':{'font_color':'#008000'},'inline_code':{'font_color':'inherit'}}
doc,styles=parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/'context-code.docx',engine=engine,style_rules=rules))
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')=='008000'
assert styles.find("w:style[@w:styleId='MDHelperInlineCode']/w:basedOn",NS) is None
def test_graphical_table_layout_overrides_important_legacy_border(qt_application,tmp_path):
dialog=DocumentStyleEditorDialog({'css':'table,th,td {border-style:solid!important;border-width:2pt;border-color:red;}'})
try:
dialog.select_target('table')
for mode,expected in [('none',['none','none']),('horizontal',['none','solid']),('grid',['solid','solid'])]:
dialog.table_border_mode_box.setCurrentIndex(dialog.table_border_mode_box.findData(mode))
payload=dialog.style_payload()
assert normalize_payload(payload)==payload
assert browser(qt_application,tmp_path,payload,TABLE,"(()=>{const s=getComputedStyle(document.querySelector('td'));return [s.borderLeftStyle,s.borderTopStyle]})()") == expected
finally:dialog.close()
@pytest.mark.parametrize('background',['#ffeecc','transparent'])
def test_bare_cell_css_wins_over_optional_stripes(qt_application,tmp_path,background):
payload=normalize_payload({'css':f'table {{ --mdhelper-table-banded-rows:true; }} td {{background-color:{background};}}'})
colors=browser(qt_application,tmp_path,payload,TABLE,"[...document.querySelectorAll('tbody td')].map(e=>getComputedStyle(e).backgroundColor)")
assert len(set(colors))==1
for engine in ENGINES:
_,styles=parts(export_markdown_to_docx(TABLE,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules']))
for band in ('band1Horz','band2Horz'):
shade=styles.find(f"w:style[@w:styleId='MDHelperTable']/w:tblStylePr[@w:type='{band}']/w:tcPr/w:shd",NS)
assert shade.get(W+'fill') == ('auto' if background=='transparent' else background[1:])
@pytest.mark.parametrize('legacy',['','table,th,td {background-color:red!important;color:red!important;}'])
def test_detached_table_text_preserves_table_decoration(qt_application,tmp_path,legacy):
dialog=DocumentStyleEditorDialog({'css':legacy+' table {--mdhelper-table-banded-rows:true;}'})
try:
for target in ('table_head','table_cell'):
dialog.select_target(target);dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData(''))
payload=dialog.style_payload()
actual=browser(qt_application,tmp_path,payload,TABLE,"[...document.querySelectorAll('tr > :first-child')].map(e=>{const s=getComputedStyle(e);return [s.backgroundColor,s.color]})")
assert [r[0] for r in actual]==['rgb(241, 245, 249)','rgba(0, 0, 0, 0)','rgb(248, 250, 252)']
assert all(r[1]!='rgb(255, 0, 0)' for r in actual)
finally:dialog.close()
def test_important_code_css_respects_graphical_child_and_detachment(qt_application,tmp_path):
dialog=DocumentStyleEditorDialog({'css':'pre,code {color:red!important;}'})
try:
dialog.select_target('code_block');dialog.color_combo.setCurrentIndex(dialog.color_combo.findData('custom'))
dialog.color_button.setText('#0000ff');dialog._store_and_refresh()
dialog.select_target('inline_code');dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData(''))
payload=dialog.style_payload()
colors=browser(qt_application,tmp_path,payload,CODE_SOURCE,"[...document.querySelectorAll('code')].map(e=>getComputedStyle(e).color)")
assert colors[0]!='rgb(255, 0, 0)' and colors[1]=='rgb(0, 0, 255)'
for engine in ENGINES:
doc,styles=parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules']))
actual={''.join(p.itertext()):p.find('.//w:rPr/w:color',NS).get(W+'val') for p in effective_document(doc,styles).iter(W+'p')}
assert actual['Inline']!='ff0000' and actual['Block']=='0000ff'
finally:dialog.close()
@pytest.mark.parametrize('bad',['color:#gggggg','color:12pt','font-size:"10pt"','font-style:italic normal','font:garbage','text-align:"left"'])
def test_invalid_css_keeps_last_valid_core_values(qt_application,tmp_path,bad):
payload=normalize_payload({'css':'p {color:red;font-size:20pt;font-style:italic;text-align:center;'+bad+';}'})
rule=payload['rules']['paragraph']
assert rule['font_color']=='#ff0000' and rule['font_size']==20 and rule['italic'] and rule['alignment']=='center'
assert browser(qt_application,tmp_path,payload,'Fallback',"(()=>{const s=getComputedStyle(document.querySelector('p'));return [s.color,s.fontStyle,s.textAlign]})()") == ['rgb(255, 0, 0)','italic','center']
@pytest.mark.parametrize('engine',ENGINES)
def test_inner_quote_and_container_list_cascade(tmp_path,engine):
source='- Item\n\n > Quote\n\n- Second'
rules={'blockquote':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}}
doc,styles=parts(export_markdown_to_docx(source,tmp_path/'inner.docx',engine=engine,style_rules=rules))
actual={''.join(p.itertext()):p.find('.//w:rPr/w:color',NS).get(W+'val') for p in effective_document(doc,styles).iter(W+'p')}
assert actual=={'Item':'0000ff','Quote':'ff0000','Second':'0000ff'}
styles.find("w:style[@w:styleId='MDHelperBlockquote']/w:rPr/w:color",NS).set(W+'val','008000')
quote=next(p for p in effective_document(doc,styles).iter(W+'p') if ''.join(p.itertext())=='Quote')
assert quote.find('.//w:rPr/w:color',NS).get(W+'val')=='008000'
for css,color in [('blockquote {color:red;} li {color:blue;}','0000ff'),('blockquote p {color:red;} li {color:blue;}','ff0000')]:
payload=normalize_payload({'css':css})
doc,styles=parts(export_markdown_to_docx('> - First\n>\n> - Second',tmp_path/'outer.docx',engine=engine,style_rules=payload['rules']))
assert all(p.find('.//w:rPr/w:color',NS).get(W+'val')==color for p in effective_document(doc,styles).iter(W+'p'))
def test_nested_decoration_cancellation_and_wrapping(qt_application,tmp_path):
rules={'strong':{'underline':True,'strike':True},'emphasis':{'underline':False}}
payload=normalize_payload({'rules':rules})
source='**Outer *Inner words still wrap* outer**'
actual=browser(qt_application,tmp_path,payload,source,"""(()=>{
const p=document.querySelector('p');p.style.width='80px';
return {leaves:[...p.querySelectorAll('[data-mdh-text]')].map(e=>[e.textContent,getComputedStyle(e).textDecorationLine]),
outer:getComputedStyle(p.querySelector('strong')).textDecorationLine,
inner:getComputedStyle(p.querySelector('em')).textDecorationLine, width:p.scrollWidth};
})()""")
assert actual['outer']=='none' and actual['inner']=='none'
assert actual['leaves']==[['Outer ','underline line-through'],['Inner words still wrap','line-through'],[' outer','underline line-through']]
assert actual['width']<=81
for engine in ENGINES:
doc,styles=parts(export_markdown_to_docx(source,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules']))
run=next(r for r in effective_document(doc,styles).iter(W+'r') if ''.join(r.itertext())=='Inner words still wrap')
assert run.find('w:rPr/w:u',NS).get(W+'val')=='none'
assert run.find('w:rPr/w:strike',NS).get(W+'val')=='1'
def test_switching_builtin_preset_refreshes_style_panel(qt_application,tmp_path,monkeypatch):
from PySide6.QtCore import QSettings,Qt
from mdhelper import main_window
monkeypatch.setattr(main_window,'QSettings',lambda *_:QSettings(str(tmp_path/'settings.ini'),QSettings.Format.IniFormat))
window=main_window.MainWindow(None,app_root=tmp_path)
try:
window._set_document_style('default');window.show_style_panel();panel=window.style_panel;panel.refresh(force=True)
window._set_document_style('serif');panel.refresh()
item=next(panel.listing.item(i) for i in range(panel.listing.count()) if panel.listing.item(i).data(Qt.ItemDataRole.UserRole)=='paragraph')
assert item.font().family()=='SimSun'
finally:window.close()
def test_text_decoration_keeps_code_math_entities_and_raw_content(qt_application,tmp_path):
from mdhelper.reader_decoration import wrap_decoration_text
raw='<pre><code>&lt;x&gt;\nline 2</code></pre><span class="math-inline"><span>x &amp; y</span></span><script>let x=1<2;</script><div class="mermaid">A --&gt; B</div>'
assert wrap_decoration_text(raw)==raw
wrapped=wrap_decoration_text('<p>A &amp; B <em>C</em></p>')
assert wrap_decoration_text(wrapped)==wrapped
payload=normalize_payload({'rules':{'strong':{'underline':True},'emphasis':{'underline':False},'code_block':{'underline':True}}})
assert browser(qt_application,tmp_path,payload,'**Outer *Inner***\n\n```text\nCode\n```',
"getComputedStyle(document.querySelector('pre')).textDecorationLine")=='underline'
@pytest.mark.parametrize('conditional',[False,True])
def test_nested_decoration_preserves_advanced_css_effects(qt_application,tmp_path,conditional):
css='strong {text-decoration:underline;} em {text-decoration:none;} .reader a {text-decoration:line-through wavy red;}'
if conditional:css+=' @media screen {.reader a {text-decoration-line:underline;}}'
payload=normalize_payload({'css':css})
assert browser(qt_application,tmp_path,payload,'**Outer *Inner*** [Decor](#link)',
"(()=>{const s=getComputedStyle(document.querySelector('a [data-mdh-text]'));return [s.textDecorationLine,s.textDecorationStyle,s.textDecorationColor]})()") == ['underline' if conditional else 'line-through','wavy','rgb(255, 0, 0)']
@pytest.mark.parametrize('kind',['table','code','nested'])
@pytest.mark.parametrize('success',[False,True])
def test_copy_buttons_report_failure_and_copy_only_own_cells(qt_application,tmp_path,kind,success):
import json,time
from PySide6.QtWebEngineCore import QWebEnginePage
from mdhelper.markdown_renderer import MarkdownRenderer
page=QWebEnginePage();loaded=[]
def wait(condition):
end=time.monotonic()+15
while not condition() and time.monotonic()<end:qt_application.processEvents();time.sleep(.01)
assert condition()
def js(expression):
values=[];page.runJavaScript('JSON.stringify('+expression+')',values.append);wait(lambda:values);return json.loads(values[0])
source=CODE_SOURCE if kind=='code' else '<table><tr><td>Outer<table><tr><td>InnerA</td><td>InnerB</td></tr></table></td><td>Last</td></tr></table>' if kind=='nested' else TABLE
selector='.copy-code-button' if kind=='code' else '.copy-table-button'
try:
page.loadFinished.connect(loaded.append);page.setHtml(MarkdownRenderer(tmp_path).render_source(source,tmp_path/'copy.md'));wait(lambda:loaded)
js("(()=>{Object.defineProperty(navigator,'clipboard',{value:{writeText:async()=>{throw Error('denied')}}});document.execCommand=()=>{window.copied=document.querySelector('textarea').value;return "+str(success).lower()+"};document.querySelector('"+selector+"').click();return true})()")
wait(lambda:js("document.querySelector('"+selector+"').textContent") in ('已复制','复制失败,请重试'))
assert js("document.querySelector('"+selector+"').textContent")==('已复制' if success else '复制失败,请重试')
copied=js('window.copied')
if kind=='nested':
assert copied.count('InnerA')==1 and copied.count('InnerB')==1
assert len(copied.split('\n'))==1 and len(copied.split('\t'))==2
elif kind=='code':assert copied.strip()=='Block'
else:assert copied=='Head\tDescription\nAlpha\tFirst\nBeta\tSecond'
assert js("document.querySelectorAll('textarea').length")==0
finally:page.deleteLater()
+32 -3
View File
@@ -10,7 +10,14 @@ sys.path.insert(0,str(Path('tests').resolve()))
from test_style_revision_054 import *
folder=Path(tempfile.mkdtemp(prefix='MDHelper-054-Word-'))
for engine in ENGINES:
for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),('continuation',CONTINUATION_SOURCE,{}),('nested',NESTED_SOURCE,NESTED_RULES),('background',TABLE,BACKGROUND_RULES)]:
for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),('continuation',CONTINUATION_SOURCE,{}),('nested',NESTED_SOURCE,NESTED_RULES),('background',TABLE,BACKGROUND_RULES),
('inner-quote','- Item\n\n > Quote\n\n- Second',{'blockquote':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}}),
('container-quote','> - First\n>\n> - Second',normalize_payload({'css':'blockquote {color:red;} li {color:blue;}'})['rules']),
('decoration','**Outer *Inner* outer**',{'strong':{'underline':True,'strike':True},'emphasis':{'underline':False}}),
('invalid','Fallback',normalize_payload({'css':'p {color:red;font-size:20pt;font-style:italic;color:#gggggg;font-size:"10pt";font-style:italic normal;font:garbage;}'})['rules']),
('cell-fill',TABLE,normalize_payload({'css':'table {--mdhelper-table-banded-rows:true;} td {background-color:#ffeecc;}'})['rules']),
('detached',TABLE,{'table':{'table_banded_rows':True},'_metadata':{'table_head':{'based_on':''},'table_cell':{'based_on':''}}}),
('context-code',CODE_SOURCE,{**CODE_RULES,'paragraph':{'font_color':'#008000'},'inline_code':{'font_color':'inherit'}})]:
export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine,style_rules=rules)
print(folder)
'@ | & $Python -B -).Trim()
@@ -19,7 +26,7 @@ print(folder)
$word.Visible=$false
$word.DisplayAlerts=0
foreach($engine in @('builtin','python-docx','pandoc')) {
foreach($case in @('code','continuation','nested','background')) {
foreach($case in @('code','continuation','nested','background','inner-quote','container-quote','decoration','invalid','cell-fill','detached','context-code')) {
$doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true)
try {
if($case -eq 'code') {
@@ -40,7 +47,7 @@ print(folder)
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
if([Math]::Abs($range.ParagraphFormat.LeftIndent-$pair[1]) -gt 0.1){throw "$engine $($pair[0]) wrong indent: $($range.ParagraphFormat.LeftIndent)"}
}
} else {
} elseif($case -eq 'background') {
$table=$doc.Tables.Item(1)
$table.Style.Table.Condition(0).Shading.BackgroundPatternColor=65535
if($table.Cell(1,1).Shading.BackgroundPatternColor -ne 65535){throw "$engine table style cannot change header"}
@@ -48,6 +55,28 @@ print(folder)
$range=$table.Cell($row,1).Range.Duplicate;$range.End=$range.End-1
if($range.ParagraphFormat.Shading.BackgroundPatternColor -ne -16777216){throw "$engine inherited paragraph shading remains"}
}
} elseif($case -eq 'inner-quote') {
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Quote')
if($range.Font.Color -ne 255 -or $range.ListFormat.ListString.Trim() -ne ''){throw "$engine lost inner quote style or added a bullet"}
$range.Style.Font.Color=65280
if($range.Font.Color -ne 65280){throw "$engine quote style edit blocked"}
} elseif($case -eq 'container-quote') {
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('First')
if($range.Font.Color -ne 16711680){throw "$engine inherited container color overrides list color"}
} elseif($case -eq 'decoration') {
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Inner')
if($range.Font.Underline -ne 0 -or $range.Font.StrikeThrough -ne -1 -or $range.Font.Bold -ne -1 -or $range.Font.Italic -ne -1){throw "$engine nested decoration or protected emphasis changed"}
} elseif($case -eq 'invalid') {
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Fallback')
if($range.Font.Color -ne 255 -or $range.Font.Size -ne 20 -or $range.Font.Italic -ne -1){throw "$engine invalid CSS erased valid typography"}
} elseif($case -eq 'cell-fill') {
foreach($row in @(2,3)) {if($doc.Tables.Item(1).Cell($row,1).Shading.BackgroundPatternColor -ne 13430527){throw "$engine explicit cell background lost"}}
} elseif($case -eq 'detached') {
$table=$doc.Tables.Item(1)
if($table.Cell(1,1).Shading.BackgroundPatternColor -ne 16381425 -or $table.Cell(3,1).Shading.BackgroundPatternColor -ne 16579320){throw "$engine detached text lost table decorations"}
} elseif($case -eq 'context-code') {
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Inline')
if($range.Font.Color -ne 32768){throw "$engine inline code cannot use surrounding color"}
}
Write-Output "$engine $case passed"
} finally {$doc.Close(0);[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc)}