feat: refine table presentation and editable Word export

This commit is contained in:
2026-11-04 15:40:52 +08:00
parent 31d0ccfde5
commit 3bb2cc5438
15 changed files with 337 additions and 58 deletions
+1 -1
View File
@@ -22,7 +22,7 @@ def test_sample_media_and_code_rendering() -> None:
renderer = MarkdownRenderer(project_root)
html = renderer.render_file(project_root / "sample.md")
assert "<table>" in html
assert '<table data-mdh-table="">' in html
assert "<audio controls" in html
assert "media-player-link" in html
assert "用内置播放器打开" in html
+102
View File
@@ -0,0 +1,102 @@
"""Table appearance, editable settings, and all three Word export engines."""
import pytest
from mdhelper.style_sync import normalize_payload
from mdhelper.style_catalog import 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 mdhelper.table_style import TABLE_OPTIONS, HEADER_COLOR
from test_style_regressions import browser, parts
SOURCE = '| Stage | Description |\n|---|---|\n| A | First |\n| B | Second |\n| C | Third |'
RULE = {'table_border_mode': 'horizontal', 'table_banded_rows': True, 'table_stripe_color': '#eaf3fa',
'table_repeat_header': False, 'table_allow_row_split': True, 'cell_padding': 6,
'border_color': '#aabbcc', 'border_width': .75}
def test_table_controls_css_roundtrip_and_legacy_values(qt_application):
legacy = {'table': {'cell_padding': 0, 'border_color': '#123456', 'font_size': 20, 'font_size_unit': 'pt'}}
assert normalize_payload({'rules': legacy})['rules'] == legacy
dialog = DocumentStyleEditorDialog({'rules': legacy})
try:
dialog.select_target('table')
for field, box in (('table_border_mode', dialog.table_border_mode_box), ('table_banded_rows', dialog.table_banded_rows_box),
('table_repeat_header', dialog.table_repeat_header_box), ('table_allow_row_split', dialog.table_allow_row_split_box)):
box.setCurrentIndex(box.findData(RULE[field]))
dialog.table_stripe_color_edit.setText(RULE['table_stripe_color'])
dialog.table_stripe_color_edit.editingFinished.emit()
payload = dialog.style_payload()
assert payload['rules']['table'] == {**legacy['table'], **{k: v for k, v in RULE.items() if k in TABLE_OPTIONS}}
assert normalize_payload(payload) == payload
assert not (set(TABLE_OPTIONS) & explicit_rules(payload['rules'])['table_cell'].keys())
dialog.extra_css_edit.setPlainText(payload['css'].replace('horizontal', 'none').replace('table-repeat-header: false', 'table-repeat-header: true'))
dialog._sync_from_css()
assert dialog.table_border_mode_box.currentData() == 'none'
assert dialog.table_repeat_header_box.currentData() is True
finally:
dialog.close()
@pytest.mark.parametrize('mode', ['grid', 'horizontal', 'none'])
def test_table_borders_stripes_and_header_in_browser(qt_application, tmp_path, mode):
payload = normalize_payload({'rules': {'table': {**RULE, 'table_border_mode': mode}}})
actual = browser(qt_application, tmp_path, payload, SOURCE, """(()=>{
const cells = [...document.querySelectorAll('tbody td:first-child')];
const s = getComputedStyle(cells[0]);
return [s.borderLeftStyle, s.borderTopStyle, cells.map(c=>getComputedStyle(c).backgroundColor),
getComputedStyle(document.querySelector('th')).backgroundColor];
})()""")
assert actual[0] == ('solid' if mode == 'grid' else 'none')
assert actual[1] == ('none' if mode == 'none' else 'solid')
assert actual[2] == ['rgba(0, 0, 0, 0)', 'rgb(234, 243, 250)', 'rgba(0, 0, 0, 0)']
assert actual[3] == 'rgb(241, 245, 249)'
def test_table_small_width_long_content_and_copy_button(qt_application, tmp_path):
source = SOURCE + '\n\n| URL |\n|---|\n| https://example.com/' + 'longword' * 30 + ' |'
actual = browser(qt_application, tmp_path, normalize_payload({}), source, """(()=>{
const reader=document.querySelector('.reader'); reader.style.width='280px'; reader.style.padding='0';
const button=document.querySelector('.copy-table-button'); button.focus();
const table=document.querySelector('table'), scroll=document.querySelector('.table-scroll');
const tools=document.querySelector('.table-tools');
return {widths:[...document.querySelectorAll('.table-scroll')].map(e=>[e.clientWidth,e.scrollWidth]),
opacity:getComputedStyle(tools).opacity, outside:button.getBoundingClientRect().bottom<=table.getBoundingClientRect().top,
toolbarSpace:scroll.getBoundingClientRect().top-table.closest('.table-wrapper').getBoundingClientRect().top};
})()""")
assert all(width <= 281 and scroll <= width + 1 for width, scroll in actual['widths'])
assert actual['opacity'] == '1' and actual['outside'] and actual['toolbarSpace'] == 0
def test_explicit_cell_background_and_dark_default_stripes(qt_application, tmp_path):
payload = normalize_payload({'rules': {'table': {'table_banded_rows': True}, 'table_cell': {'background_color': '#ffeecc'}}})
assert browser(qt_application, tmp_path, payload, SOURCE,
"getComputedStyle(document.querySelector('tbody tr:nth-child(2) td')).backgroundColor") == 'rgb(255, 238, 204)'
payload = normalize_payload({'rules': {'table': {'table_banded_rows': True}}})
assert browser(qt_application, tmp_path, payload, SOURCE,
"(()=>{document.documentElement.dataset.theme='dark';return getComputedStyle(document.querySelector('tbody tr:nth-child(2) td')).backgroundColor})()") == 'rgb(37, 44, 55)'
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
@pytest.mark.parametrize('custom', [False, True])
def test_word_table_styles_pagination_and_editable_backgrounds(tmp_path, engine, custom):
rules = {'table': RULE, 'table_head': {'background_color': '#ddeeff'}} if custom else {}
doc, styles = parts(export_markdown_to_docx(SOURCE, tmp_path / 'table.docx', engine=engine, style_rules=rules))
style = styles.find("w:style[@w:styleId='MDHelperTable']", NS)
assert style is not None
assert style.find('w:tblPr/w:tblStyleRowBandSize', NS).get(W+'val') == '1'
rows = doc.findall('.//w:tbl/w:tr', NS)
assert [r.find('w:trPr/w:tblHeader', NS).get(W+'val') for r in rows] == (['0']*4 if custom else ['1','0','0','0'])
assert all(r.find('w:trPr/w:cantSplit', NS).get(W+'val') == ('0' if custom else '1') for r in rows)
borders = style.find('w:tblPr/w:tblBorders', NS)
assert borders.find(W+'insideV').get(W+'val') == ('none' if custom else 'single')
assert borders.find(W+'insideH').get(W+'val') == 'single'
header = style.find("w:tblStylePr[@w:type='firstRow']/w:tcPr/w:shd", NS)
assert header.get(W+'fill') == ('ddeeff' if custom else HEADER_COLOR[1:])
stripe = style.find("w:tblStylePr[@w:type='band2Horz']/w:tcPr/w:shd", NS)
assert (stripe is not None) == custom
if custom: assert stripe.get(W+'fill') == 'eaf3fa'
assert not doc.findall('.//w:tcPr/w:shd', NS)
assert not doc.findall('.//w:tblPr/w:tblBorders', NS)
assert styles.find("w:style[@w:styleId='MDHelperTableHead']/w:pPr/w:shd", NS) is None
assert doc.find('.//w:tblPr/w:tblLayout', NS).get(W+'type') == 'autofit'
assert all(tc.get(W+'type') == 'auto' for tc in doc.findall('.//w:tcPr/w:tcW', NS))
+49
View File
@@ -0,0 +1,49 @@
param([string]$Python = (Join-Path $PSScriptRoot '..\mdhelper_env\mdhelper_env\Scripts\python.exe'))
$ErrorActionPreference = 'Stop'
Push-Location (Join-Path $PSScriptRoot '..')
$word = $null
try {
$testDirectory = (@'
import json, tempfile, sys
from pathlib import Path
sys.path.insert(0, str(Path('tests').resolve()))
from test_table_presentation import SOURCE, RULE
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.style_catalog import style_name
folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Tables-'))
for engine in ('builtin', 'python-docx', 'pandoc'):
for custom in (False, True):
rules = {'table': RULE, 'table_head': {'background_color': '#ddeeff'}} if custom else {}
export_markdown_to_docx(SOURCE, folder / f'{engine}-{int(custom)}.docx', engine=engine, style_rules=rules)
(folder / 'names.json').write_text(json.dumps({'table': 'MDHelper ' + style_name('table')}), encoding='utf-8')
print(folder)
'@ | & $Python -B -).Trim()
if ($LASTEXITCODE -ne 0) { throw 'Fixture generation failed.' }
$names = Get-Content -LiteralPath (Join-Path $testDirectory 'names.json') -Raw -Encoding UTF8 | ConvertFrom-Json
$word = New-Object -ComObject Word.Application
$word.Visible = $false
$word.DisplayAlerts = 0
foreach ($engine in @('builtin', 'python-docx', 'pandoc')) {
foreach ($custom in @(0, 1)) {
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine-$custom.docx"), $false, $true)
try {
$table = $doc.Tables.Item(1)
if (-not $table.AllowAutoFit) { throw "$engine disabled automatic column sizing." }
$header = if ($custom) {0} else {-1}
if ($table.Rows.Item(1).HeadingFormat -ne $header) { throw "$engine header repetition differs from settings." }
if ([bool]$table.Rows.AllowBreakAcrossPages -ne [bool]$custom) { throw "$engine row splitting differs from settings." }
if ($custom -and $table.Borders.Item(-6).LineStyle -ne 0) { throw "$engine horizontal layout retains vertical borders." }
$style = $doc.Styles.Item($names.table)
$expectedHeader = if ($custom) {16772829} else {16381425}
if ($table.Cell(1,1).Shading.BackgroundPatternColor -ne $expectedHeader) { throw "$engine lost header background: $($table.Cell(1,1).Shading.BackgroundPatternColor)." }
if ($custom -and $table.Cell(3,1).Shading.BackgroundPatternColor -ne 16446442) { throw "$engine lost alternating row background: $($table.Cell(3,1).Shading.BackgroundPatternColor)." }
$style.Table.Condition(0).Shading.BackgroundPatternColor = 255
if ($table.Cell(1,1).Shading.BackgroundPatternColor -ne 255) { throw "$engine direct formatting blocks table style edits." }
Write-Output "$engine case $custom passed: layout, pagination, backgrounds and shared style edits."
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
}
}
} finally {
if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }
Pop-Location
}