fix: preserve per-property inheritance and semantic emphasis
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
import json
|
||||
import time
|
||||
import zipfile
|
||||
from lxml import etree as ET
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWebEngineCore import QWebEnginePage
|
||||
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||
from mdhelper.docx_style import W, NS, val
|
||||
from mdhelper.style_dialog import DocumentStyleEditorDialog
|
||||
from mdhelper.style_sync import normalize_payload, render_css
|
||||
from mdhelper.markdown_renderer import MarkdownRenderer
|
||||
from docx_assertions import effective_document
|
||||
|
||||
PARTIAL_RULES = {
|
||||
'h1': {'chinese_font_family': 'SimSun', 'english_font_family': 'Arial', 'font_size': 12, 'font_size_unit': 'pt',
|
||||
'space_after_value': 8, 'space_after_unit': 'pt', 'line_height_value': 1.5, 'line_spacing_mode': 'multiple',
|
||||
'left_indent_value': 24, 'left_indent_unit': 'pt'},
|
||||
'h2': {'english_font_family': 'Courier New', 'space_before_value': 12, 'space_before_unit': 'pt',
|
||||
'right_indent_value': 8, 'right_indent_unit': 'pt'},
|
||||
'_metadata': {'h2': {'based_on': 'h1'}},
|
||||
}
|
||||
|
||||
|
||||
def parts(path):
|
||||
with zipfile.ZipFile(path) as z:
|
||||
return ET.fromstring(z.read('word/document.xml')), ET.fromstring(z.read('word/styles.xml'))
|
||||
|
||||
|
||||
def browser(qapp, tmp_path, payload, source, expression):
|
||||
page = QWebEnginePage(); loaded = []; result = []
|
||||
def wait(predicate):
|
||||
end = time.monotonic() + 12
|
||||
while not predicate() and time.monotonic() < end: qapp.processEvents(); time.sleep(.01)
|
||||
assert predicate(), 'WebEngine timed out'
|
||||
try:
|
||||
page.loadFinished.connect(loaded.append)
|
||||
page.setHtml(MarkdownRenderer(tmp_path).render_source(source, tmp_path / 'test.md',
|
||||
document_style_css=render_css(payload['css'], payload['rules'])))
|
||||
wait(lambda: loaded)
|
||||
page.runJavaScript('JSON.stringify(' + expression + ')', result.append)
|
||||
wait(lambda: result)
|
||||
return json.loads(result[0])
|
||||
finally: page.deleteLater(); qapp.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
||||
def test_word_inherits_other_attributes_when_one_attribute_is_explicit(tmp_path, engine):
|
||||
path = export_markdown_to_docx('# Parent\n\n## Child', tmp_path / 'partial.docx', engine=engine, style_rules=PARTIAL_RULES)
|
||||
doc, styles = parts(path)
|
||||
base = styles.find("w:style[@w:styleId='MDHelperH1']", NS)
|
||||
child = styles.find("w:style[@w:styleId='MDHelperH2']", NS)
|
||||
assert child.find('w:rPr/w:rFonts', NS).get(W + 'eastAsia') is None
|
||||
assert child.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Courier New'
|
||||
assert set(child.find('w:pPr/w:spacing', NS).attrib) == {W + 'before'}
|
||||
assert set(child.find('w:pPr/w:ind', NS).attrib) == {W + 'right'}
|
||||
base.find('w:rPr/w:rFonts', NS).set(W + 'eastAsia', 'KaiTi')
|
||||
base.find('w:pPr/w:spacing', NS).set(W + 'after', '480')
|
||||
rendered = effective_document(doc, styles)
|
||||
paragraph = next(p for p in rendered.iter(W + 'p') if 'Child' in ''.join(p.itertext()))
|
||||
assert paragraph.find('.//w:rFonts', NS).get(W + 'eastAsia') == 'KaiTi'
|
||||
assert paragraph.find('w:pPr/w:spacing', NS).get(W + 'after') == '480'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
||||
def test_word_semantic_emphasis_survives_paragraph_style_changes(tmp_path, engine):
|
||||
path = export_markdown_to_docx('Plain **StrongText** *ItalicText* ~~Deleted~~\n\n# Title **HeadingStrong**', tmp_path / 'emphasis.docx', engine=engine)
|
||||
doc, styles = parts(path)
|
||||
base = styles.find("w:style[@w:styleId='MDHelperParagraph']/w:rPr", NS)
|
||||
for tag in ('b', 'i', 'strike'): val(base, tag, 1)
|
||||
val(styles.find("w:style[@w:styleId='MDHelperH1']/w:rPr", NS), 'b', 0)
|
||||
rendered = effective_document(doc, styles)
|
||||
for text, tag in (('StrongText', 'b'), ('HeadingStrong', 'b'), ('ItalicText', 'i'), ('Deleted', 'strike')):
|
||||
run = next(r for r in rendered.iter(W + 'r') if text in ''.join(r.itertext()))
|
||||
assert run.find('w:rPr/w:' + tag, NS).get(W + 'val') == '1'
|
||||
for run in doc.iter(W + 'r'):
|
||||
assert run.find('w:rPr/w:sz', NS) is None
|
||||
assert run.find('w:rPr/w:rFonts', NS) is None
|
||||
assert run.find('w:rPr/w:color', NS) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('key,changed,source,selector', [('strike', 'underline', '~~Text~~', 's'), ('link', 'strike', '[Text](#text)', 'p a')])
|
||||
def test_graphical_decoration_preserves_inherited_counterpart(qt_application, tmp_path, key, changed, source, selector):
|
||||
dialog = DocumentStyleEditorDialog({})
|
||||
try:
|
||||
dialog.select_target(key)
|
||||
dialog.bool_boxes[changed].setCheckState(Qt.CheckState.Checked)
|
||||
payload = dialog.style_payload()
|
||||
assert payload['rules'][key] == {changed: True}
|
||||
assert normalize_payload(payload)['rules'][key] == {changed: True}
|
||||
actual = browser(qt_application, tmp_path, payload, source, f'getComputedStyle(document.querySelector("{selector}")).textDecorationLine')
|
||||
assert set(actual.split()) == {'underline', 'line-through'}
|
||||
# Explicitly switching the other property off is still respected.
|
||||
other = 'strike' if changed == 'underline' else 'underline'
|
||||
dialog.bool_boxes[other].setCheckState(Qt.CheckState.Unchecked)
|
||||
assert dialog.style_payload()['rules'][key][other] is False
|
||||
finally: dialog.close()
|
||||
@@ -29,7 +29,8 @@ def test_shared_named_styles_without_direct_format_overrides(tmp_path, engine):
|
||||
assert ppr.find(W + 'pStyle').get(W + 'val') in by_id
|
||||
for run in doc.iter(W + 'r'):
|
||||
rpr = run.find(W + 'rPr')
|
||||
assert all(rpr.find(W + field) is None for field in RUN_FIELDS)
|
||||
protected = {'b', 'bCs', 'i', 'iCs', 'strike'}
|
||||
assert all(rpr.find(W + field) is None for field in set(RUN_FIELDS) - protected)
|
||||
ref = rpr.find(W + 'rStyle')
|
||||
if ref is not None: assert ref.get(W + 'val') in by_id
|
||||
paragraph_ids = {p.find('w:pPr/w:pStyle', NS).get(W + 'val') for p in doc.iter(W + 'p')}
|
||||
|
||||
@@ -11,10 +11,12 @@ sys.path.insert(0, str(Path('tests').resolve()))
|
||||
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
|
||||
folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-'))
|
||||
rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}}
|
||||
for engine in ('builtin', 'python-docx', 'pandoc'):
|
||||
export_markdown_to_docx(SOURCE + '\n\n## Child title', folder / (engine + '.docx'), engine=engine, style_rules=rules)
|
||||
export_markdown_to_docx('# Parent\n\n## Child', folder / (engine + '-partial.docx'), engine=engine, style_rules=PARTIAL_RULES)
|
||||
(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()
|
||||
@@ -44,8 +46,25 @@ print(folder)
|
||||
if ($range.Font.Bold -ne 0) { throw "$engine explicit child-style bold=False did not override its base." }
|
||||
$doc.Styles.Item($names.h1).Font.Size = 30
|
||||
if ($range.Font.Size -ne 30) { throw "$engine base-style change does not reach child heading." }
|
||||
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('strong second')
|
||||
$doc.Styles.Item($names.paragraph).Font.Bold = -1
|
||||
if ($range.Font.Bold -ne -1) { throw "$engine paragraph bold inverted semantic emphasis." }
|
||||
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('bold title')
|
||||
$doc.Styles.Item($names.h1).Font.Bold = 0
|
||||
if ($range.Font.Bold -ne -1) { throw "$engine heading edit removed semantic emphasis." }
|
||||
Write-Output "$engine passed: Word opened document, heading emphasis, body and character edits, mixed links, base-style inheritance."
|
||||
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
|
||||
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine-partial.docx"), $false, $true)
|
||||
try {
|
||||
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('Child')
|
||||
$base = $doc.Styles.Item($names.h1)
|
||||
$base.Font.NameFarEast = 'KaiTi'; $base.ParagraphFormat.SpaceAfter = 24
|
||||
$base.ParagraphFormat.LineSpacingRule = 0; $base.ParagraphFormat.LeftIndent = 40
|
||||
if ($range.Font.NameFarEast -ne $base.Font.NameFarEast -or $range.ParagraphFormat.SpaceAfter -ne 24 -or $range.ParagraphFormat.LineSpacingRule -ne 0 -or $range.ParagraphFormat.LeftIndent -ne 40) {
|
||||
throw "$engine partial overrides froze unrelated inherited properties."
|
||||
}
|
||||
Write-Output "$engine passed: partial overrides preserve inheritance of fonts, spacing and indents."
|
||||
} 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