fix: preserve nested CSS, color inputs and Word code inheritance
This commit is contained in:
1 parent
b3d8f6e26a
commit
d0f95d277a
5 files changed
+157
-10
No files matched your search
@@ -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, {}))
|
||||
|
||||