fix: preserve nested CSS, color inputs and Word code inheritance
This commit is contained in:
@@ -97,6 +97,12 @@ class WordStyles:
|
||||
return ' '.join([identifier] + [reference(s, 'name') for s in self.chain(identifier)]).lower()
|
||||
|
||||
def new(self, identifier, kind, name, base=''):
|
||||
# Some converters use our reserved IDs for temporary code styles.
|
||||
# Retain their detached nodes in original for classification, but emit
|
||||
# exactly one definition for each final Word style ID.
|
||||
original = self.original.get(identifier)
|
||||
if original is not None and original.getparent() is self.styles:
|
||||
self.styles.remove(original)
|
||||
if name in self.used_names: name += ' [' + identifier + ']'
|
||||
self.used_names.add(name)
|
||||
style = ET.SubElement(self.styles, W + 'style', {W + 'type': kind, W + 'customStyle': '1', W + 'styleId': identifier})
|
||||
@@ -153,6 +159,28 @@ class WordStyles:
|
||||
self.characters[key] = rule
|
||||
return self.characters[key]
|
||||
|
||||
def paragraph_character(self, key):
|
||||
"""Link a paragraph's character counterpart and its entire base chain.
|
||||
|
||||
A flattened copy would stop following edits to ancestors in Word.
|
||||
Keep authored overrides only, just as for paragraph basedOn styles.
|
||||
"""
|
||||
identifier = style_id(key) + 'Char'
|
||||
if identifier not in self.created:
|
||||
base = parent_style(key, self.rules)
|
||||
base_id = self.paragraph_character(base) if base else ''
|
||||
paragraph_id = self.paragraph(key)
|
||||
style = self.new(identifier, 'character', 'MDHelper ' + style_name(key, self.rules) + '字符', base_id)
|
||||
val(style, 'link', paragraph_id)
|
||||
val(self.created[paragraph_id], 'link', identifier)
|
||||
props = child(style, 'rPr')
|
||||
_run_properties(props, self.explicit[key])
|
||||
if base:
|
||||
old = ET.Element(W + 'rPr')
|
||||
_run_properties(old, self.explicit[base])
|
||||
_delta(props, old, normalize_rule(self.rules.get(key)))
|
||||
return identifier
|
||||
|
||||
def character(self, key):
|
||||
identifier = style_id(key)
|
||||
if identifier in self.created: return identifier
|
||||
@@ -161,13 +189,7 @@ class WordStyles:
|
||||
rule = self.character_rule(key)
|
||||
legacy = key == 'inline_code' and not base and legacy_base(key, self.rules)
|
||||
if legacy:
|
||||
base_id = 'MDHelperCodeChar'
|
||||
if base_id not in self.created:
|
||||
paragraph_id = self.paragraph('code')
|
||||
shared = self.new(base_id, 'character', 'MDHelper 代码基准字符')
|
||||
val(shared, 'link', paragraph_id)
|
||||
val(self.created[paragraph_id], 'link', base_id)
|
||||
_run_properties(child(shared, 'rPr'), self.explicit['code'])
|
||||
base_id = self.paragraph_character('code')
|
||||
# Word cannot clear one inherited character-style property. Preserve
|
||||
# the resolved remaining properties and inherit color from the text.
|
||||
base_rule = self.explicit['code'] if legacy else self.character_rule(base) if base else {}
|
||||
|
||||
@@ -81,12 +81,16 @@ def _decoration_variables(source):
|
||||
def visit(nodes):
|
||||
for node in nodes:
|
||||
if node.type=='at-rule' and node.content is not None and node.lower_at_keyword in ('media','supports','layer','container'):
|
||||
children=css.parse_stylesheet(node.content);visit(children)
|
||||
children=css.parse_blocks_contents(node.content);visit(children)
|
||||
node.content=css.parse_component_value_list(css.serialize(children))
|
||||
elif node.type=='qualified-rule':
|
||||
declarations=css.parse_declaration_list(node.content,skip_whitespace=False,skip_comments=False)
|
||||
declarations=css.parse_blocks_contents(node.content,skip_whitespace=False,skip_comments=False)
|
||||
visit(declarations)
|
||||
output=[]
|
||||
for declaration in declarations:
|
||||
# Invalid declarations have no serializable representation.
|
||||
# Keep valid siblings, including nested qualified rules.
|
||||
if declaration.type=='error': continue
|
||||
output.append(declaration)
|
||||
if declaration.type!='declaration':continue
|
||||
value=css.serialize(declaration.value).strip()
|
||||
|
||||
@@ -105,6 +105,8 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
layout.addLayout(name_row)
|
||||
layout.addWidget(self.tabs)
|
||||
layout.addWidget(button_row)
|
||||
for edit in (self.background_edit, self.border_color_edit, self.table_stripe_color_edit):
|
||||
edit.textChanged.connect(self._validate_colors)
|
||||
self._load_rule_to_widgets(self.rules.get(self._current_target, {}))
|
||||
self._sync_from_css()
|
||||
|
||||
@@ -117,6 +119,8 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
apply_title_bar_style(self, background, foreground, dark)
|
||||
|
||||
def style_payload(self) -> dict[str, object]:
|
||||
if not self._validate_colors():
|
||||
raise ValueError(self.color_error_label.text())
|
||||
if not self._sync_from_css():
|
||||
raise ValueError("CSS 尚未完成,请先修正提示的错误。")
|
||||
return {
|
||||
@@ -127,9 +131,19 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
}
|
||||
|
||||
def accept(self) -> None:
|
||||
if self._sync_from_css():
|
||||
if self._validate_colors() and self._sync_from_css():
|
||||
super().accept()
|
||||
|
||||
def _validate_colors(self, *_):
|
||||
if self._loading: return True
|
||||
invalid = [label for label, edit in (('底色', self.background_edit),
|
||||
('边框颜色', self.border_color_edit), ('隔行底色', self.table_stripe_color_edit))
|
||||
if edit.text().strip() and not re.fullmatch(r'#[0-9a-fA-F]{6}|transparent', edit.text().strip())]
|
||||
self.color_error_label.setText(('、'.join(invalid) + '无效:请输入 #RRGGBB 或 transparent;留空表示继承。原设置尚未改变。') if invalid else '')
|
||||
self.color_error_label.setVisible(bool(invalid))
|
||||
self.button_box.button(QDialogButtonBox.StandardButton.Ok).setEnabled(not invalid and self.tabs.isTabEnabled(0))
|
||||
return not invalid
|
||||
|
||||
@staticmethod
|
||||
def _combo(items: list[tuple[str, object]]) -> QComboBox:
|
||||
box = QComboBox()
|
||||
@@ -237,6 +251,9 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
self.table_rows.append(form.rowCount())
|
||||
form.addRow(label, widget)
|
||||
self.table_stripe_color_edit.editingFinished.connect(self._store_and_refresh)
|
||||
self.color_error_label = QLabel()
|
||||
self.color_error_label.setWordWrap(True)
|
||||
form.addRow(self.color_error_label)
|
||||
self.list_marker_box = self._combo([('继承', None), ('圆点', 'disc'), ('空心圆', 'circle'), ('方块', 'square'),
|
||||
('数字', 'decimal'), ('小写字母', 'lower-alpha'), ('大写字母', 'upper-alpha'), ('小写罗马', 'lower-roman'), ('大写罗马', 'upper-roman'), ('无', 'none')])
|
||||
self.marker_row = form.rowCount()
|
||||
@@ -366,6 +383,9 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
return True
|
||||
|
||||
def _tab_changed(self, *_: object) -> None:
|
||||
if not self._validate_colors():
|
||||
self.tabs.setCurrentIndex(0)
|
||||
return
|
||||
if self._css_dirty:
|
||||
self._sync_from_css()
|
||||
if self.tabs.currentIndex() == 2:
|
||||
@@ -590,6 +610,10 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
self.rules.pop(self._current_target, None)
|
||||
|
||||
def _change_target(self, current: QListWidgetItem, previous: QListWidgetItem | None) -> None:
|
||||
if previous is not None and not self._validate_colors():
|
||||
blocker = QSignalBlocker(self.target_list)
|
||||
self.target_list.setCurrentItem(previous)
|
||||
return
|
||||
if self._css_dirty:
|
||||
self._sync_from_css()
|
||||
self._current_target = current.data(Qt.ItemDataRole.UserRole)
|
||||
@@ -602,6 +626,7 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
|
||||
def _store_and_refresh(self, *_: object) -> None:
|
||||
if not self._loading:
|
||||
if not self._validate_colors(): return
|
||||
if self._css_dirty and not self._sync_from_css():
|
||||
return
|
||||
before = deepcopy(self.rules.get(self._current_target, {}))
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Regressions from the 0.5.4 rendering, synchronization and Word audit."""
|
||||
import pytest
|
||||
from PySide6.QtWidgets import QDialogButtonBox
|
||||
from mdhelper.style_dialog import DocumentStyleEditorDialog
|
||||
from mdhelper.style_sync import normalize_payload
|
||||
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')
|
||||
CODE_SOURCE = '# Parent\n\n`Inline`\n\n```text\nBlock\n```'
|
||||
CODE_RULES = {'h1': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt'},
|
||||
'_metadata': {'code': {'based_on': 'h1'}}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('nested', ['& strong {color:red}', '@media screen { & strong {color:red} }'])
|
||||
def test_nested_css_still_renders_with_decoration_cancellation(qt_application, tmp_path, nested):
|
||||
payload = normalize_payload({'css': 'em{text-decoration:none} .reader p {' + nested + '}'})
|
||||
assert browser(qt_application, tmp_path, payload, 'Body **Bold**',
|
||||
"getComputedStyle(document.querySelector('strong')).color") == 'rgb(255, 0, 0)'
|
||||
assert normalize_payload(payload) == payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize('target,field,widget', [('paragraph','background_color','background_edit'),
|
||||
('table','border_color','border_color_edit'), ('table','table_stripe_color','table_stripe_color_edit')])
|
||||
def test_invalid_color_does_not_erase_saved_style(qt_application, target, field, widget):
|
||||
dialog = DocumentStyleEditorDialog({'rules': {target: {field: '#ff0000'}}})
|
||||
try:
|
||||
dialog.select_target(target)
|
||||
before = dialog.style_payload()
|
||||
edit = getattr(dialog, widget)
|
||||
edit.setText('#gggggg'); edit.editingFinished.emit()
|
||||
assert dialog.rules == before['rules'] and dialog.extra_css_edit.toPlainText() == before['css']
|
||||
assert not dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
|
||||
assert '无效' in dialog.color_error_label.text()
|
||||
with pytest.raises(ValueError): dialog.style_payload()
|
||||
dialog.select_target('h1')
|
||||
assert dialog._current_target == target
|
||||
edit.setText('#00ff00'); edit.editingFinished.emit()
|
||||
assert dialog.style_payload()['rules'][target][field] == '#00ff00'
|
||||
assert dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
|
||||
edit.clear(); edit.editingFinished.emit()
|
||||
assert field not in dialog.style_payload()['rules'].get(target, {})
|
||||
finally: dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_word_code_keeps_editable_parent_chain(tmp_path, engine):
|
||||
doc, styles = parts(export_markdown_to_docx(CODE_SOURCE, tmp_path/'chain.docx', engine=engine, style_rules=CODE_RULES))
|
||||
identifiers = [s.get(W+'styleId') for s in styles.findall(W+'style')]
|
||||
assert len(identifiers) == len(set(identifiers))
|
||||
base = styles.find("w:style[@w:styleId='MDHelperH1Char']", NS)
|
||||
assert base.find('w:link', NS).get(W+'val') == 'MDHelperH1'
|
||||
code = styles.find("w:style[@w:styleId='MDHelperCodeChar']", NS)
|
||||
assert code.find('w:basedOn', NS).get(W+'val') == 'MDHelperH1Char'
|
||||
assert code.find('w:rPr/w:color', NS) is None
|
||||
base.find('w:rPr/w:color', NS).set(W+'val', '0000ff')
|
||||
base.find('w:rPr/w:sz', NS).set(W+'val', '56')
|
||||
run = next(r for r in effective_document(doc, styles).iter(W+'r') if ''.join(r.itertext())=='Inline')
|
||||
assert run.find('w:rPr/w:color', NS).get(W+'val') == '0000ff'
|
||||
assert run.find('w:rPr/w:sz', NS).get(W+'val') == '56'
|
||||
@@ -0,0 +1,34 @@
|
||||
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_055 import *
|
||||
folder=Path(tempfile.mkdtemp(prefix='MDHelper-055-Word-'))
|
||||
for engine in ENGINES:
|
||||
export_markdown_to_docx(CODE_SOURCE,folder/f'{engine}-code.docx',engine=engine,style_rules=CODE_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')) {
|
||||
$doc=$word.Documents.Open((Join-Path $folder "$engine-code.docx"),$false,$true)
|
||||
try {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Parent')
|
||||
$range.Style.Font.Color=16711680;$range.Style.Font.Size=28
|
||||
foreach($text in @('Inline','Block')) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($text)
|
||||
if($range.Font.Color -ne 16711680 -or $range.Font.Size -ne 28){throw "$engine $text does not follow ancestor: $($range.Font.Color), $($range.Font.Size)"}
|
||||
}
|
||||
Write-Output "$engine code ancestor edits 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