fix: preserve list context and nested CSS decoration behavior
This commit is contained in:
@@ -152,13 +152,15 @@ def test_nested_quoted_lists_keep_depth_numbering_and_emphasis(tmp_path,engine):
|
||||
values={}
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
text=''.join(p.itertext()); props=p.find(W+'pPr')
|
||||
values[text]=props.find(W+'ind').get(W+'leftChars')
|
||||
# Absolute indents are needed when the quote and list use different
|
||||
# font sizes. Compare the resulting distance, not its storage unit.
|
||||
values[text]=int(props.find(W+'ind').get(W+'left'))
|
||||
assert props.find(W+'numPr') is not None
|
||||
if text in ('OuterQuote','NestedQuote'):
|
||||
run=next(r for r in p.iter(W+'r') if ''.join(r.itertext())==text)
|
||||
assert run.find('w:rPr/w:b',NS).get(W+'val')=='1'
|
||||
assert run.find('w:rPr/w:color',NS).get(W+'val')=='ff0000'
|
||||
assert int(values['NestedQuote'])>int(values['OuterQuote'])
|
||||
assert values['NestedQuote']-values['OuterQuote']==36*20
|
||||
|
||||
|
||||
def test_graphical_quote_edit_overrides_important_broad_p(qt_application,tmp_path):
|
||||
|
||||
@@ -12,6 +12,11 @@ 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'}}}
|
||||
ORDERED = '1. First\n\n Continuation\n\n2. Second'
|
||||
TASK = '- [ ] First\n\n Continuation\n\n- [x] Second'
|
||||
QUOTED = '> - Outer\n>\n> - Inner\n>\n> - NestedSecond\n>\n> - Second'
|
||||
MARGINS = 'p {margin-left:12pt;} li {margin-left:24pt;}'
|
||||
MIXED = 'li {font-size:12pt;margin-left:24pt;text-indent:-1em;} p {font-size:20pt;margin-left:12pt;}'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('nested', ['& strong {color:red}', '@media screen { & strong {color:red} }'])
|
||||
@@ -60,3 +65,97 @@ def test_word_code_keeps_editable_parent_chain(tmp_path, engine):
|
||||
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'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
@pytest.mark.parametrize('source,target', [(ORDERED,'list_ordered'), (TASK,'list_task')])
|
||||
def test_word_continuation_preserves_semantic_list_type(tmp_path, engine, source, target):
|
||||
rules = {target: {'font_color': '#ff0000'}, 'list_bullet': {'font_color': '#0000ff'}}
|
||||
doc, styles = parts(export_markdown_to_docx(source,tmp_path/'continuation.docx',engine=engine,style_rules=rules))
|
||||
assert not any(a.startswith('{urn:mdhelper:source}') for p in doc.iter(W+'p') for a in p.attrib)
|
||||
from mdhelper.docx_semantic import style_id
|
||||
base = styles.find(f"w:style[@w:styleId='{style_id(target)}']",NS)
|
||||
base.find('w:rPr/w:color',NS).set(W+'val','008000')
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
for run in p.iter(W+'r'):
|
||||
if ''.join(run.itertext()).strip(): assert run.find('w:rPr/w:color',NS).get(W+'val')=='008000'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_quoted_list_keeps_additive_nested_indents(tmp_path, engine):
|
||||
doc, styles = parts(export_markdown_to_docx(QUOTED,tmp_path/'quoted.docx',engine=engine,style_rules=normalize_payload({'css':MARGINS})['rules']))
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
text=''.join(p.itertext())
|
||||
if text in ('Outer','Inner'):
|
||||
ind=p.find('w:pPr/w:ind',NS)
|
||||
assert int(ind.get(W+'left'))/20 == (36 if text=='Outer' else 72)
|
||||
assert ind.get(W+'hangingChars','0')=='0'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_inherited_list_hanging_uses_container_font(tmp_path, engine):
|
||||
doc,styles=parts(export_markdown_to_docx('- Outer\n\n- Second',tmp_path/'hanging.docx',engine=engine,style_rules=normalize_payload({'css':MIXED})['rules']))
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
assert p.find('w:pPr/w:ind',NS).get(W+'hanging') == '240'
|
||||
|
||||
|
||||
def test_legacy_code_can_cancel_outer_decoration(qt_application,tmp_path):
|
||||
payload=normalize_payload({'rules':{'strong':{'underline':True},'code':{'underline':False}}})
|
||||
result=browser(qt_application,tmp_path,payload,'**Outer `Inner` outer**',
|
||||
"[document.querySelector('strong'),document.querySelector('strong > [data-mdh-text]'),document.querySelector('code [data-mdh-text]')].map(e=>getComputedStyle(e).textDecorationLine)")
|
||||
assert result==['none','underline','none']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad',['color:rgb(nope)','color:rgba(1,2)','color:hsl(nope)','font:bold garbage','font:italic 12pt','font:bold nonsense 20pt Arial'])
|
||||
def test_invalid_function_and_font_keep_valid_core_values(qt_application,tmp_path,bad):
|
||||
payload=normalize_payload({'css':'p{color:red;font-size:20pt;'+bad+'}'})
|
||||
assert payload['rules']['paragraph']['font_color']=='#ff0000'
|
||||
assert payload['rules']['paragraph']['font_size']==20
|
||||
assert normalize_payload(payload)==payload
|
||||
assert browser(qt_application,tmp_path,payload,'Fallback',"getComputedStyle(document.querySelector('p')).color")=='rgb(255, 0, 0)'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid', ['underline nonsense','underline rgb(nope)'])
|
||||
def test_invalid_decoration_does_not_draw_an_extra_line(qt_application,tmp_path,invalid):
|
||||
payload=normalize_payload({'css':'em{text-decoration:none} strong{text-decoration:line-through;text-decoration:'+invalid+'}'})
|
||||
assert browser(qt_application,tmp_path,payload,'**Text**',"getComputedStyle(document.querySelector('strong [data-mdh-text]')).textDecorationLine")=='line-through'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value,line,style,color', [('line-through','line-through','solid','rgb(23, 105, 170)'),
|
||||
('underline line-through wavy red','underline line-through','wavy','rgb(255, 0, 0)')])
|
||||
def test_variable_decoration_shorthand_keeps_browser_effect(qt_application,tmp_path,value,line,style,color):
|
||||
payload=normalize_payload({'css':'em{text-decoration:none} a{text-decoration:var(--custom-line);--custom-line:'+value+'}'})
|
||||
assert browser(qt_application,tmp_path,payload,'[Link](#link)',"(()=>{const s=getComputedStyle(document.querySelector('a [data-mdh-text]'));return [s.textDecorationLine,s.textDecorationStyle,s.textDecorationColor]})()") == [line,style,color]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scope', ['a { %s }','a { @media screen { %s } }','@supports (display:grid) { a { %s } }'])
|
||||
def test_variable_decorations_survive_nested_conditions(qt_application,tmp_path,scope):
|
||||
payload=normalize_payload({'css':'em{text-decoration:none} '+scope % 'text-decoration:var(--line);--line:line-through wavy red;'})
|
||||
actual=browser(qt_application,tmp_path,payload,'[Outer *Inner*](#link)',
|
||||
"[...document.querySelectorAll('a [data-mdh-text]')].map(e=>getComputedStyle(e).textDecorationLine)")
|
||||
assert actual==['line-through','none']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('css', ['color:rgb(255 0 0 / .5)', 'color:rgb(from red r g b)', 'color:rgb(calc(255 / 2) 0 0)', 'font:italic 2em Arial'])
|
||||
def test_valid_advanced_values_remain_css_only(css):
|
||||
from mdhelper.style_sync import analyze_css
|
||||
result=analyze_css('p{color:blue;font-size:20pt;'+css+'}')
|
||||
assert not result.errors and not any('已忽略无效' in note for note in result.notes)
|
||||
|
||||
|
||||
def test_actual_table_preview_shows_alternating_rows(qt_application):
|
||||
import json,time
|
||||
dialog=DocumentStyleEditorDialog({'rules':{'table':{'table_banded_rows':True,'table_stripe_color':'#ff0000'}}})
|
||||
try:
|
||||
dialog.tabs.setCurrentIndex(2)
|
||||
values=[]
|
||||
end=time.monotonic()+20
|
||||
while time.monotonic()<end:
|
||||
values.clear()
|
||||
dialog.actual_preview.page().runJavaScript("JSON.stringify([...document.querySelectorAll('tbody tr')].map(tr=>getComputedStyle(tr.cells[0]).backgroundColor))",values.append)
|
||||
while not values and time.monotonic()<end: qt_application.processEvents();time.sleep(.01)
|
||||
if values and values[0] and len(json.loads(values[0]))>=3: break
|
||||
qt_application.processEvents();time.sleep(.01)
|
||||
colors=json.loads(values[0])
|
||||
assert len(colors)>=3 and colors[1]=='rgb(255, 0, 0)' and colors[0]!=colors[1] and colors[2]!=colors[1]
|
||||
finally: dialog.close()
|
||||
|
||||
@@ -10,23 +10,60 @@ 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)
|
||||
for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),
|
||||
('ordered',ORDERED,{'list_ordered':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}}),
|
||||
('task',TASK,{'list_task':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}}),
|
||||
('quoted',QUOTED,normalize_payload({'css':MARGINS})['rules']),
|
||||
('hanging','- Outer\n\n- Second',normalize_payload({'css':MIXED})['rules']),
|
||||
('invalid','Fallback',normalize_payload({'css':'p{color:red;color:rgb(nope);font-size:20pt;font:bold garbage;}'})['rules']),
|
||||
('legacy','**Outer `Inner` outer**',{'strong':{'underline':True},'code':{'underline':False}})]:
|
||||
export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine,style_rules=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)
|
||||
foreach($case in @('code','ordered','task','quoted','hanging','invalid','legacy')) {
|
||||
$doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true)
|
||||
try {
|
||||
if($case -eq 'code') {
|
||||
$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"
|
||||
} elseif($case -in @('ordered','task')) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('First')
|
||||
$name=if($case -eq 'ordered'){'MDHelper 有序列表'}else{'MDHelper 任务列表'}
|
||||
$base=$doc.Styles.Item($name)
|
||||
$base.Font.Color=65280
|
||||
foreach($text in @('First','Continuation','Second')) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($text)
|
||||
if($range.Font.Color -ne 65280){throw "$engine $case $text lost editable list base: $($range.Font.Color)"}
|
||||
if($text -eq 'Continuation' -and $range.ListFormat.ListString.Trim() -ne ''){throw "$engine continuation consumed a marker"}
|
||||
}
|
||||
} elseif($case -eq 'quoted') {
|
||||
foreach($pair in @(@('Outer',36),@('Inner',72))) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
|
||||
if([Math]::Abs($range.ParagraphFormat.LeftIndent-$pair[1]) -gt 0.1){throw "$engine quoted $($pair[0]) indent: $($range.ParagraphFormat.LeftIndent)"}
|
||||
}
|
||||
} elseif($case -eq 'hanging') {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Outer')
|
||||
if($range.ParagraphFormat.FirstLineIndent -ne -12 -or $range.Font.Size -ne 20){throw "$engine inherited hanging indent resized: $($range.ParagraphFormat.FirstLineIndent), font $($range.Font.Size)"}
|
||||
} 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){throw "$engine invalid CSS discarded valid fallback"}
|
||||
} elseif($case -eq 'legacy') {
|
||||
foreach($pair in @(@('Outer',1),@('Inner',0))) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
|
||||
if($range.Font.Underline -ne $pair[1] -or $range.Font.Bold -ne -1){throw "$engine legacy decoration or emphasis changed"}
|
||||
}
|
||||
}
|
||||
Write-Output "$engine $case passed"
|
||||
} finally {$doc.Close(0);[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc)}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)}
|
||||
|
||||
Reference in New Issue
Block a user