fix: preserve table controls and editable Word list and code styles
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
"""Native pointer regression: reach and click the floating table copy button."""
|
||||
import os,sys,time,json,tempfile
|
||||
from pathlib import Path
|
||||
os.environ.pop('QT_QPA_PLATFORM',None)
|
||||
os.environ['QTWEBENGINE_CHROMIUM_FLAGS']='--log-level=3'
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from PySide6.QtWebEngineWidgets import QWebEngineView
|
||||
from PySide6.QtCore import QPoint,Qt
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtGui import QCursor
|
||||
from mdhelper.markdown_renderer import MarkdownRenderer
|
||||
|
||||
app=QApplication([])
|
||||
view=QWebEngineView();view.resize(850,450)
|
||||
view.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint,True)
|
||||
loaded=[];view.loadFinished.connect(loaded.append)
|
||||
|
||||
def wait(condition):
|
||||
end=time.monotonic()+20
|
||||
while not condition() and time.monotonic()<end:app.processEvents();time.sleep(.01)
|
||||
assert condition()
|
||||
|
||||
def js(expression):
|
||||
values=[];view.page().runJavaScript('JSON.stringify('+expression+')',values.append)
|
||||
wait(lambda:values);return json.loads(values[0])
|
||||
|
||||
try:
|
||||
root=Path(tempfile.gettempdir())
|
||||
view.setHtml(MarkdownRenderer(root).render_source('| A | B |\n|---|---|\n| X | Y |',root/'hover.md'))
|
||||
view.show();view.raise_();view.activateWindow()
|
||||
wait(lambda:loaded and loaded[-1]);QTest.qWait(500)
|
||||
bounds=js("(()=>{const t=document.querySelector('table').getBoundingClientRect(),b=document.querySelector('button').getBoundingClientRect();return {top:t.top,bottom:b.bottom,by:(b.top+b.bottom)/2,x:(b.left+b.right)/2}})()")
|
||||
target=view.windowHandle()
|
||||
js("(()=>{window.moves=[];document.addEventListener('mousemove',e=>window.moves.push([e.clientX,e.clientY,e.target.tagName]));return true})()")
|
||||
QCursor.setPos(target.mapToGlobal(QPoint(20,20)));QTest.qWait(150)
|
||||
for y in (bounds['top']+10,bounds['top']+1,(bounds['top']+bounds['bottom'])/2,bounds['by']):
|
||||
point=QPoint(round(bounds['x']),round(y))
|
||||
QCursor.setPos(target.mapToGlobal(point));QTest.mouseMove(target,point);QTest.qWait(400)
|
||||
assert js("getComputedStyle(document.querySelector('.table-tools')).opacity")=='1', (y, js("({moves:window.moves,hover:[...document.querySelectorAll(':hover')].map(e=>e.className),width:innerWidth,height:innerHeight})"), app.platformName(), target.size(), view.size())
|
||||
js("(()=>{window.copied=null;Object.defineProperty(navigator,'clipboard',{value:{writeText:async text=>{window.copied=text}}});return true})()")
|
||||
QTest.mouseClick(target,Qt.MouseButton.LeftButton,pos=QPoint(round(bounds['x']),round(bounds['by'])))
|
||||
QTest.qWait(200)
|
||||
assert js('window.copied')=='A\tB\nX\tY'
|
||||
print('Native hover and copy passed: continuous pointer path and expected table text.')
|
||||
finally:
|
||||
view.close()
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Regressions from the 0.5.3 style and table audit."""
|
||||
import pytest
|
||||
import zipfile
|
||||
from lxml import etree as ET
|
||||
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||
from mdhelper.docx_style import W, NS
|
||||
from mdhelper.style_sync import normalize_payload
|
||||
from test_style_regressions import browser, parts
|
||||
from docx_assertions import effective_document
|
||||
|
||||
ENGINES = ('builtin', 'python-docx', 'pandoc')
|
||||
TABLE = '| Head | Description |\n|---|---|\n| Alpha | First |\n| Beta | Second |'
|
||||
BACKGROUND_RULES = {'h1': {'background_color': '#ff0000'},
|
||||
'table_head': {'background_color': '#0000ff'}, 'table_cell': {'background_color': '#00ff00'},
|
||||
'_metadata': {'table_head': {'based_on': 'h1'}, 'table_cell': {'based_on': 'h1'}}}
|
||||
CONTINUATION_SOURCE = '1. First\n\n Continuation\n\n2. Second'
|
||||
NESTED_SOURCE = '- Outer\n\n - Inner\n\n - NestedSecond\n\n- Second'
|
||||
NESTED_RULES = normalize_payload({'css': 'p {margin-left:12pt;} li {margin-left:24pt;}'})['rules']
|
||||
CODE_SOURCE = '`Inline`\n\n```text\nBlock\n```'
|
||||
CODE_RULES = {'code': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt'}}
|
||||
|
||||
|
||||
def test_copy_button_has_continuous_pointer_path(qt_application, tmp_path):
|
||||
assert browser(qt_application, tmp_path, normalize_payload({}), TABLE, """(()=>{
|
||||
const button=document.querySelector('.copy-table-button');button.focus();
|
||||
const b=button.getBoundingClientRect(),t=document.querySelector('table').getBoundingClientRect();
|
||||
const tools=document.querySelector('.table-tools').getBoundingClientRect();
|
||||
return tools.bottom >= t.top && tools.top <= b.top;
|
||||
})()""")
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_table_background_cancels_paragraph_parent_shading(tmp_path, engine):
|
||||
doc, styles = parts(export_markdown_to_docx(TABLE,tmp_path/'shade.docx',engine=engine,style_rules=BACKGROUND_RULES))
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
assert p.find('w:pPr/w:shd',NS).get(W+'fill') == 'auto'
|
||||
for key, color in (('firstRow','0000ff'),('band1Horz','00ff00')):
|
||||
assert styles.find(f"w:style[@w:styleId='MDHelperTable']/w:tblStylePr[@w:type='{key}']/w:tcPr/w:shd",NS).get(W+'fill') == color
|
||||
assert not doc.findall('.//w:tcPr/w:shd',NS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_list_continuation_does_not_consume_a_number(tmp_path, engine):
|
||||
path=export_markdown_to_docx(CONTINUATION_SOURCE,tmp_path/'list.docx',engine=engine)
|
||||
doc, styles = parts(path)
|
||||
with zipfile.ZipFile(path) as z: numbering=ET.fromstring(z.read('word/numbering.xml'))
|
||||
numbered=[]
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
num=p.find('w:pPr/w:numPr',NS)
|
||||
if num is None: continue
|
||||
nid=num.find(W+'numId').get(W+'val')
|
||||
if nid=='0': continue
|
||||
aid=numbering.find(f"w:num[@w:numId='{nid}']/w:abstractNumId",NS).get(W+'val')
|
||||
level=num.find(W+'ilvl').get(W+'val')
|
||||
lvl=numbering.find(f"w:abstractNum[@w:abstractNumId='{aid}']/w:lvl[@w:ilvl='{level}']",NS)
|
||||
if lvl.find(W+'numFmt').get(W+'val')!='none' and lvl.find(W+'lvlText').get(W+'val').strip():
|
||||
numbered.append(''.join(p.itertext()))
|
||||
assert numbered == ['First','Second']
|
||||
assert not any('{urn:mdhelper:source}continuation' in p.attrib for p in doc.iter(W+'p'))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_loose_nested_list_adds_inner_paragraph_margin(tmp_path, engine):
|
||||
doc, styles = parts(export_markdown_to_docx(NESTED_SOURCE,tmp_path/'nested.docx',engine=engine,style_rules=NESTED_RULES))
|
||||
indents = {''.join(p.itertext()): int(p.find('w:pPr/w:ind',NS).get(W+'left'))/20 for p in effective_document(doc,styles).iter(W+'p')}
|
||||
assert indents['Outer'] == 36 and indents['Inner'] == 72
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_legacy_code_uses_linked_editable_word_base(tmp_path, engine):
|
||||
_, styles = parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/'code.docx',engine=engine,style_rules=CODE_RULES))
|
||||
assert styles.find("w:style[@w:styleId='MDHelperCode']/w:link",NS).get(W+'val') == 'MDHelperCodeChar'
|
||||
assert styles.find("w:style[@w:styleId='MDHelperCodeChar']/w:link",NS).get(W+'val') == 'MDHelperCode'
|
||||
inline = styles.find("w:style[@w:styleId='MDHelperInlineCode']",NS)
|
||||
assert inline.find(W+'basedOn').get(W+'val') == 'MDHelperCodeChar'
|
||||
assert inline.find('w:rPr/w:color',NS) is None
|
||||
@@ -0,0 +1,59 @@
|
||||
param([string]$Python = (Join-Path $PSScriptRoot '..\mdhelper_env\mdhelper_env\Scripts\python.exe'))
|
||||
$ErrorActionPreference='Stop'
|
||||
Push-Location (Join-Path $PSScriptRoot '..')
|
||||
$word=$null
|
||||
try {
|
||||
$folder = (@'
|
||||
import sys,tempfile
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path('tests').resolve()))
|
||||
from test_style_revision_054 import *
|
||||
folder=Path(tempfile.mkdtemp(prefix='MDHelper-054-Word-'))
|
||||
for engine in ENGINES:
|
||||
for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),('continuation',CONTINUATION_SOURCE,{}),('nested',NESTED_SOURCE,NESTED_RULES),('background',TABLE,BACKGROUND_RULES)]:
|
||||
export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine,style_rules=rules)
|
||||
print(folder)
|
||||
'@ | & $Python -B -).Trim()
|
||||
if ($LASTEXITCODE -ne 0) {throw 'Fixture generation failed'}
|
||||
$word=New-Object -ComObject Word.Application
|
||||
$word.Visible=$false
|
||||
$word.DisplayAlerts=0
|
||||
foreach($engine in @('builtin','python-docx','pandoc')) {
|
||||
foreach($case in @('code','continuation','nested','background')) {
|
||||
$doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true)
|
||||
try {
|
||||
if($case -eq 'code') {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Block')
|
||||
$base=$range.Style.BaseStyle
|
||||
$doc.Styles.Item($base).Font.Color=16711680
|
||||
foreach($text in @('Inline','Block')) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($text)
|
||||
if($range.Font.Color -ne 16711680){throw "$engine $text does not follow code base: $($range.Font.Color)"}
|
||||
}
|
||||
} elseif($case -eq 'continuation') {
|
||||
foreach($pair in @(@('First','1.'),@('Continuation',''),@('Second','2.'))) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
|
||||
if($range.ListFormat.ListString.Trim() -ne $pair[1]){throw "$engine $($pair[0]) wrong numbering: $($range.ListFormat.ListString)"}
|
||||
}
|
||||
} elseif($case -eq 'nested') {
|
||||
foreach($pair in @(@('Outer',36),@('Inner',72))) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
|
||||
if([Math]::Abs($range.ParagraphFormat.LeftIndent-$pair[1]) -gt 0.1){throw "$engine $($pair[0]) wrong indent: $($range.ParagraphFormat.LeftIndent)"}
|
||||
}
|
||||
} else {
|
||||
$table=$doc.Tables.Item(1)
|
||||
$table.Style.Table.Condition(0).Shading.BackgroundPatternColor=65535
|
||||
if($table.Cell(1,1).Shading.BackgroundPatternColor -ne 65535){throw "$engine table style cannot change header"}
|
||||
foreach($row in @(1,2)) {
|
||||
$range=$table.Cell($row,1).Range.Duplicate;$range.End=$range.End-1
|
||||
if($range.ParagraphFormat.Shading.BackgroundPatternColor -ne -16777216){throw "$engine inherited paragraph shading remains"}
|
||||
}
|
||||
}
|
||||
Write-Output "$engine $case passed"
|
||||
} finally {$doc.Close(0);[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc)}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)}
|
||||
Pop-Location
|
||||
}
|
||||
Reference in New Issue
Block a user