"""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_catalog import document_styles, explicit_rules 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'}} ALIGN_SOURCE = '| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |' QUOTE_SOURCE = '> - QuoteItem\n>\n> - QuoteSecond\n\n- Outside' QUOTE_RULES = {'blockquote': {'font_color':'#ff0000','font_size':24,'font_size_unit':'pt'}} LOOSE_CSS = 'li {font-size:12pt;} p {margin-top:24pt; text-indent:18pt;}' BORDER_CSS = 'table,th,td {border-width:5pt;border-color:red;border-style:none;}' 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 @pytest.mark.parametrize('engine', ENGINES) def test_legacy_bases_can_be_restored_or_explicitly_detached(qt_application, tmp_path, engine): payload=normalize_payload({'rules':{'code':{'font_color':'#ff0000','font_size':20,'font_size_unit':'pt'},'table':{'font_color':'#ff0000'}}}) dialog=DocumentStyleEditorDialog(payload) try: for target in ('inline_code','table_head','table_cell'): dialog.select_target(target) assert dialog.based_on_box.currentData()=='__legacy__' dialog.style_name_edit.setText('Named '+target); dialog.style_name_edit.editingFinished.emit() assert 'based_on' not in dialog.rules['_metadata'][target] dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData('')) payload=dialog.style_payload() finally: dialog.close() for target in ('inline_code','table_head','table_cell'): assert 'font_color' not in explicit_rules(payload['rules'])[target] source='`Inline`\n\n'+TABLE_SOURCE assert all(color!='rgb(255, 0, 0)' for color in browser(qt_application,tmp_path,payload,source, "[...document.querySelectorAll('code,th,td')].map(e=>getComputedStyle(e).color)")) doc,styles=parts(export_markdown_to_docx(source,tmp_path/'detached.docx',engine=engine,style_rules=payload['rules'])) for identifier in ('MDHelperInlineCode','MDHelperTableHead','MDHelperTableCell'): assert styles.find(f"w:style[@w:styleId='{identifier}']/w:basedOn",NS) is None @pytest.mark.parametrize('engine', ENGINES) def test_table_column_alignment_is_a_shared_derived_style(tmp_path, engine): doc,styles=parts(export_markdown_to_docx(ALIGN_SOURCE,tmp_path/'columns.docx',engine=engine)) rendered=effective_document(doc,styles) assert [p.find('w:pPr/w:jc',NS).get(W+'val') for p in rendered.iter(W+'p')]==['left','center','right']*2 assert not doc.findall('.//w:pPr/w:jc',NS) props=styles.find("w:style[@w:styleId='MDHelperTableCell']/w:rPr",NS) color=props.find(W+'color') if color is None: color=ET.SubElement(props,W+'color') color.set(W+'val','ff0000') for p in effective_document(doc,styles).iter(W+'p'): if ''.join(p.itertext()) in ('A','B','C'): assert p.find('.//w:rPr/w:color',NS).get(W+'val')=='ff0000' @pytest.mark.parametrize('engine', ENGINES) def test_quoted_loose_list_retains_quote_typography_and_style_inheritance(qt_application,tmp_path,engine): payload=normalize_payload({'rules':QUOTE_RULES}) assert {'blockquote','list_bullet'} <= document_styles(QUOTE_SOURCE)[1] colors=browser(qt_application,tmp_path,payload,QUOTE_SOURCE,"[...document.querySelectorAll('blockquote p')].map(e=>getComputedStyle(e).color)") assert colors==['rgb(255, 0, 0)']*2 doc,styles=parts(export_markdown_to_docx(QUOTE_SOURCE,tmp_path/'quote.docx',engine=engine,style_rules=payload['rules'])) for p in effective_document(doc,styles).iter(W+'p'): if ''.join(p.itertext()).startswith('Quote'): assert p.find('.//w:rPr/w:color',NS).get(W+'val')=='ff0000' assert p.find('.//w:rPr/w:sz',NS).get(W+'val')=='48' styles.find("w:style[@w:styleId='MDHelperBlockquote']/w:rPr/w:color",NS).set(W+'val','0000ff') for p in effective_document(doc,styles).iter(W+'p'): if ''.join(p.itertext()).startswith('Quote'): assert p.find('.//w:rPr/w:color',NS).get(W+'val')=='0000ff' assert not any('MDHelperSource' in s.get(W+'styleId','') for s in styles) @pytest.mark.parametrize('engine', ENGINES) def test_nested_quoted_lists_keep_depth_numbering_and_emphasis(tmp_path,engine): source='> 3. **OuterQuote**\n>\n> - **NestedQuote**\n>\n> - NestedSecond\n>\n> 4. OuterSecond' doc,styles=parts(export_markdown_to_docx(source,tmp_path/'nested-quote.docx',engine=engine,style_rules=QUOTE_RULES)) 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') 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']) def test_graphical_quote_edit_overrides_important_broad_p(qt_application,tmp_path): dialog=DocumentStyleEditorDialog({'css':'p {color:red !important;}'}) try: dialog.select_target('blockquote'); dialog.color_button.setText('#008800'); dialog._store_and_refresh() payload=dialog.style_payload() assert payload['rules']['blockquote']['font_color']=='#008800' assert payload['rules']['paragraph']['font_color']=='#ff0000' assert browser(qt_application,tmp_path,payload,'> Quote',"getComputedStyle(document.querySelector('blockquote p')).color")=='rgb(0, 136, 0)' finally:dialog.close() def test_list_helpers_do_not_erase_explicit_p_spacing(qt_application,tmp_path): payload=normalize_payload({'css':LOOSE_CSS}) assert browser(qt_application,tmp_path,payload,'- First\n\n- Second', "[...document.querySelectorAll('li > p')].map(e=>[parseFloat(getComputedStyle(e).marginTop),parseFloat(getComputedStyle(e).textIndent)])")==[[32,24],[32,24]] @pytest.mark.parametrize('invalid',['font-size:10pt 20pt','color:red blue','font-weight:12pt','text-align:nope','text-decoration-line:none underline']) def test_invalid_extended_values_preserve_previous_valid_declaration(qt_application,tmp_path,invalid): css='p {font-size:20pt;color:green;font-weight:bold;text-align:center;text-decoration-line:line-through;'+invalid+';}' payload=normalize_payload({'css':css}); rule=payload['rules']['paragraph'] assert rule['font_size']==20 and rule['font_color']=='#008000' and rule['bold'] and rule['alignment']=='center' assert rule['strike'] and not rule['underline'] assert analyze_css(css).notes assert browser(qt_application,tmp_path,payload,'Valid',"getComputedStyle(document.querySelector('p')).textDecorationLine")=='line-through' @pytest.mark.parametrize('engine', ENGINES) def test_border_style_sync_and_word_export(qt_application,tmp_path,engine): dialog=DocumentStyleEditorDialog({'css':BORDER_CSS}) try: dialog.select_target('table'); assert dialog.border_style_combo.currentData()=='none' dialog.border_width_spin.setValue(3) payload=dialog.style_payload() assert payload['rules']['table']['border_style']=='none' assert browser(qt_application,tmp_path,payload,TABLE_SOURCE,"getComputedStyle(document.querySelector('td')).borderTopStyle")=='none' _,styles=parts(export_markdown_to_docx(TABLE_SOURCE,tmp_path/'border.docx',engine=engine,style_rules=payload['rules'])) assert all(b.get(W+'val')=='none' for b in styles.findall("w:style[@w:styleId='MDHelperTable']/w:tblPr/w:tblBorders/*",NS)) dialog.border_style_combo.setCurrentIndex(dialog.border_style_combo.findData('dashed')) assert dialog.style_payload()['rules']['table']['border_style']=='dashed' finally:dialog.close()