fix: preserve style edits and cross-surface inheritance
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
"""Cross-surface regressions found in the 0.5.1 style audit."""
|
||||
import json
|
||||
from PySide6.QtCore import Qt, QSettings
|
||||
import pytest
|
||||
from mdhelper import main_window
|
||||
from mdhelper.style_dialog import DocumentStyleEditorDialog
|
||||
from mdhelper.style_sync import normalize_payload, analyze_css
|
||||
from mdhelper.document_style import resolved_rules
|
||||
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||
from mdhelper.docx_style import W, NS, child
|
||||
from docx_assertions import effective_document
|
||||
from test_style_regressions import browser, parts
|
||||
|
||||
ENGINES = ['builtin', 'python-docx', 'pandoc']
|
||||
REPEATED_SOURCE = '**Outer *middle **Deep** middle* outer**'
|
||||
REPEATED_RULES = {'strong': {'font_color': '#ff0000'}, 'emphasis': {'font_color': '#0000ff'}}
|
||||
ABSOLUTE_PAYLOAD = {'css_sync_version': 1,
|
||||
'css': '.reader h1 {font-size:20pt;} .reader h2 {text-indent:24pt;}',
|
||||
'rules': {'_metadata': {'h2': {'based_on': 'h1'}}}}
|
||||
|
||||
|
||||
def text_run(document, word):
|
||||
return next(r for r in document.iter(W + 'r') if word in ''.join(r.itertext()))
|
||||
|
||||
|
||||
def test_unrelated_controls_preserve_css_values_outside_ui_range(qt_application):
|
||||
source = '.reader table, .reader th, .reader td {padding:150pt; border-width:30pt; letter-spacing:1.2345pt;}'
|
||||
dialog = DocumentStyleEditorDialog({'css': source})
|
||||
try:
|
||||
dialog.select_target('table')
|
||||
dialog.bool_boxes['italic'].setCheckState(Qt.CheckState.Checked)
|
||||
payload = dialog.style_payload()
|
||||
assert payload['rules']['table'] == dict(italic=True, cell_padding=150, border_width=30, letter_spacing=1.2345)
|
||||
assert 'padding:150pt' in payload['css'] and 'letter-spacing:1.2345pt' in payload['css']
|
||||
dialog.cell_padding_spin.setValue(80)
|
||||
rule = dialog.style_payload()['rules']['table']
|
||||
assert rule['cell_padding'] == 80 and rule['border_width'] == 30
|
||||
finally: dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_preset_copy_roundtrip_keeps_word_defaults(qt_application, tmp_path, monkeypatch, engine):
|
||||
monkeypatch.setattr(main_window, 'QSettings', lambda *_: QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat))
|
||||
window = main_window.MainWindow(None, app_root=tmp_path)
|
||||
dialog = DocumentStyleEditorDialog(window._style_payload_for_id('serif'), parent=window)
|
||||
try:
|
||||
dialog.select_target('link')
|
||||
dialog.bool_boxes['strike'].setCheckState(Qt.CheckState.Checked)
|
||||
payload = normalize_payload(json.loads(json.dumps(dialog.style_payload())))
|
||||
assert payload['rules']['_preset'] == 'serif'
|
||||
before = resolved_rules({}, preset='serif')['paragraph']
|
||||
after = resolved_rules(payload['rules'], preset='custom:copy')['paragraph']
|
||||
assert after == before
|
||||
path = export_markdown_to_docx('BookText', tmp_path / 'book.docx', engine=engine,
|
||||
style_rules=payload['rules'], preset='custom:copy')
|
||||
doc, styles = parts(path)
|
||||
run = text_run(effective_document(doc, styles), 'BookText')
|
||||
assert run.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Georgia'
|
||||
assert run.find('w:rPr/w:rFonts', NS).get(W + 'eastAsia') == 'SimSun'
|
||||
assert styles.find("w:style[@w:styleId='MDHelperParagraph']/w:pPr/w:spacing", NS).get(W + 'line') == '437'
|
||||
finally: dialog.close(); window.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('detached', [False, True])
|
||||
def test_code_block_overrides_legacy_inner_code_rules(qt_application, tmp_path, detached):
|
||||
rules = {'code': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt', 'english_font_family': 'Arial'}}
|
||||
if detached: rules['_metadata'] = {'code_block': {'based_on': ''}}
|
||||
else: rules['code_block'] = {'font_color': '#0000ff', 'font_size': 10, 'font_size_unit': 'pt', 'english_font_family': 'Consolas'}
|
||||
payload = normalize_payload({'rules': rules})
|
||||
values = browser(qt_application, tmp_path, payload, '```python\nprint("CodeText")\n```',
|
||||
"[...document.querySelectorAll('pre,pre code,pre code span')].map(e=>{const s=getComputedStyle(e);return [s.color,s.fontSize,s.fontFamily]})")
|
||||
assert all(item == values[0] for item in values)
|
||||
assert values[0][0] == ('rgb(35, 39, 47)' if detached else 'rgb(0, 0, 255)')
|
||||
# A legacy style without a semantic override keeps its former appearance.
|
||||
legacy = normalize_payload({'rules': {'code': rules['code']}})
|
||||
assert browser(qt_application, tmp_path, legacy, '```text\nOld\n```',
|
||||
"getComputedStyle(document.querySelector('pre code')).color") == 'rgb(255, 0, 0)'
|
||||
|
||||
|
||||
def test_dark_theme_defaults_do_not_override_explicit_style_colors(qt_application, tmp_path):
|
||||
payload = normalize_payload({'rules': {'h1': {'font_color': '#ff0000'}, 'link': {'font_color': '#ff0000'},
|
||||
'code_block': {'background_color': '#ffff00'}}})
|
||||
values = browser(qt_application, tmp_path, payload, '# Header\n\n[Link](https://example.com)\n\n```text\nCode\n```',
|
||||
"(()=>{document.documentElement.dataset.theme='dark';return [getComputedStyle(document.querySelector('h1')).color,getComputedStyle(document.querySelector('a')).color,getComputedStyle(document.querySelector('pre')).backgroundColor,getComputedStyle(document.documentElement).colorScheme]})()")
|
||||
assert values == ['rgb(255, 0, 0)', 'rgb(255, 0, 0)', 'rgb(255, 255, 0)', 'dark']
|
||||
defaults = browser(qt_application, tmp_path, normalize_payload({}), '# Header\n\n[Link](#header)',
|
||||
"(()=>{document.documentElement.dataset.theme='dark';return [getComputedStyle(document.querySelector('h1')).color,getComputedStyle(document.querySelector('a')).color]})()")
|
||||
assert defaults == ['rgb(244, 247, 251)', 'rgb(121, 184, 255)']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_repeated_nested_character_style_keeps_innermost_precedence(tmp_path, engine):
|
||||
path = export_markdown_to_docx(REPEATED_SOURCE, tmp_path / 'repeated.docx', engine=engine, style_rules=REPEATED_RULES)
|
||||
doc, styles = parts(path)
|
||||
run = text_run(effective_document(doc, styles), 'Deep')
|
||||
assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000'
|
||||
assert run.find('w:rPr/w:b', NS).get(W + 'val') == '1'
|
||||
assert run.find('w:rPr/w:i', NS).get(W + 'val') == '1'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_nested_list_inherits_right_and_hanging_indent_edits(tmp_path, engine):
|
||||
path = export_markdown_to_docx('- OuterList\n - InnerList', tmp_path / 'list.docx', engine=engine)
|
||||
doc, styles = parts(path)
|
||||
nested = styles.find("w:style[@w:styleId='MDHelperListBulletLevel2']/w:pPr/w:ind", NS)
|
||||
assert set(nested.attrib) == {W + 'left', W + 'leftChars'}
|
||||
base = child(styles.find("w:style[@w:styleId='MDHelperListBullet']/w:pPr", NS), 'ind')
|
||||
base.set(W + 'right', '400'); base.set(W + 'rightChars', '0')
|
||||
base.set(W + 'hangingChars', '200')
|
||||
rendered = effective_document(doc, styles)
|
||||
inner = next(p for p in rendered.iter(W + 'p') if 'InnerList' in ''.join(p.itertext()))
|
||||
assert inner.find('w:pPr/w:ind', NS).get(W + 'right') == '400'
|
||||
assert inner.find('w:pPr/w:ind', NS).get(W + 'hangingChars') == '200'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_absolute_first_indent_survives_inherited_font_and_gui_roundtrip(qt_application, tmp_path, engine):
|
||||
payload = normalize_payload(ABSOLUTE_PAYLOAD)
|
||||
dialog = DocumentStyleEditorDialog(payload)
|
||||
try:
|
||||
dialog.select_target('h2')
|
||||
assert dialog.indent_unit_combo.currentData() == 'pt' and dialog.indent_spin.value() == 24
|
||||
dialog.bool_boxes['italic'].setCheckState(Qt.CheckState.Checked)
|
||||
payload = normalize_payload(dialog.style_payload())
|
||||
assert payload['rules']['h2']['indent_value'] == 24 and payload['rules']['h2']['indent_unit'] == 'pt'
|
||||
path = export_markdown_to_docx('## Indented', tmp_path / 'indent.docx', engine=engine, style_rules=payload['rules'])
|
||||
doc, styles = parts(path)
|
||||
ind = effective_document(doc, styles).find('.//w:pPr/w:ind', NS)
|
||||
assert ind.get(W + 'firstLine') == '480' and ind.get(W + 'firstLineChars') == '0'
|
||||
finally: dialog.close()
|
||||
@@ -12,6 +12,8 @@ from test_word_named_styles import SOURCE
|
||||
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||
from mdhelper.style_catalog import style_name
|
||||
from test_style_regressions import PARTIAL_RULES, UNIT_RULES, NESTED_SOURCE, NESTED_RULES
|
||||
from test_style_revision_052 import REPEATED_SOURCE, REPEATED_RULES, ABSOLUTE_PAYLOAD
|
||||
from mdhelper.style_sync import normalize_payload
|
||||
folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-'))
|
||||
rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}}
|
||||
for engine in ('builtin', 'python-docx', 'pandoc'):
|
||||
@@ -19,6 +21,10 @@ for engine in ('builtin', 'python-docx', 'pandoc'):
|
||||
export_markdown_to_docx('# Parent\n\n## Child', folder / (engine + '-partial.docx'), engine=engine, style_rules=PARTIAL_RULES)
|
||||
export_markdown_to_docx('# Parent\n\n## ChildUnits', folder / (engine + '-units.docx'), engine=engine, style_rules=UNIT_RULES)
|
||||
export_markdown_to_docx(NESTED_SOURCE, folder / (engine + '-nested.docx'), engine=engine, style_rules=NESTED_RULES)
|
||||
export_markdown_to_docx(REPEATED_SOURCE, folder / (engine + '-repeated.docx'), engine=engine, style_rules=REPEATED_RULES)
|
||||
export_markdown_to_docx('- OuterList\n - InnerList', folder / (engine + '-list.docx'), engine=engine)
|
||||
export_markdown_to_docx('## Indented', folder / (engine + '-absolute.docx'), engine=engine, style_rules=normalize_payload(ABSOLUTE_PAYLOAD)['rules'])
|
||||
export_markdown_to_docx('BookText', folder / (engine + '-preset.docx'), engine=engine, style_rules={'_preset': 'serif'}, preset='custom:copy')
|
||||
(folder / 'names.json').write_text(json.dumps({key: 'MDHelper ' + style_name(key) for key in ('paragraph', 'strong', 'link', 'h1')}), encoding='utf-8')
|
||||
print(folder)
|
||||
'@ | & $Python -B -).Trim()
|
||||
@@ -81,6 +87,28 @@ print(folder)
|
||||
if ($link.Font.Color -ne 65280 -or $bold.Font.Color -ne 255) { throw "$engine lost shared link style or inner override." }
|
||||
Write-Output "$engine passed: child units, nested colors and shared style updates."
|
||||
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
|
||||
foreach ($case in @('repeated', 'list', 'absolute', 'preset')) {
|
||||
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine-$case.docx"), $false, $true)
|
||||
try {
|
||||
$text = switch ($case) { 'repeated' { 'Deep' }; 'list' { 'OuterList' }; 'absolute' { 'Indented' }; 'preset' { 'BookText' } }
|
||||
$range = $doc.Content.Duplicate
|
||||
if (-not $range.Find.Execute($text)) { throw "Missing $case text" }
|
||||
switch ($case) {
|
||||
'repeated' { if ($range.Font.Color -ne 255) { throw "$engine lost innermost repeated style." } }
|
||||
'absolute' { if ($range.ParagraphFormat.FirstLineIndent -ne 24) { throw "$engine changed absolute indentation." } }
|
||||
'preset' { if ($range.Font.NameAscii -ne 'Georgia') { throw "$engine lost copied preset." } }
|
||||
'list' {
|
||||
$base = $doc.Styles.Item($range.Style.NameLocal)
|
||||
$base.ParagraphFormat.CharacterUnitRightIndent = 0
|
||||
$base.ParagraphFormat.RightIndent = 20
|
||||
$base.ParagraphFormat.CharacterUnitFirstLineIndent = -2
|
||||
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('InnerList')
|
||||
if ($range.ParagraphFormat.RightIndent -ne 20 -or $range.ParagraphFormat.CharacterUnitFirstLineIndent -ne -2) { throw "$engine froze nested list inheritance." }
|
||||
}
|
||||
}
|
||||
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
|
||||
}
|
||||
Write-Output "$engine passed: repeated inline styles, nested list edits, absolute indents and copied presets."
|
||||
}
|
||||
} finally {
|
||||
if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }
|
||||
|
||||
Reference in New Issue
Block a user