"""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'}}} 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} }']) 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, {}) edit.setText('#bad-color'); edit.editingFinished.emit() dialog._reset_current_rule() assert not dialog.color_error_label.text() assert dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled() 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' @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()getComputedStyle(tr.cells[0]).backgroundColor))",values.append) while not values and time.monotonic()=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()