feat: add semantic character and container style controls with CSS sync
This commit is contained in:
@@ -16,8 +16,14 @@ STYLE_TARGETS = (
|
||||
("blockquote", "引用段落", ".reader blockquote p, .reader .admonition p"),
|
||||
("code", "代码块", ".reader pre, .reader code"),
|
||||
("table", "表格", ".reader table, .reader th, .reader td"),
|
||||
*((key, name, f'.reader [data-mdh-style="{key}"]') for key, name in (
|
||||
('list_bullet', '无序列表'), ('list_ordered', '有序列表'), ('list_task', '任务列表'),
|
||||
('code_block', '代码块(独立)'), ('table_head', '表头文字'), ('table_cell', '单元格文字'))),
|
||||
('strong', '加粗', '.reader strong'), ('emphasis', '强调', '.reader em'),
|
||||
('strike', '删除线', '.reader s'), ('link', '超链接', '.reader a'),
|
||||
('inline_code', '行内代码', '.reader code[data-mdh-style="inline_code"]'),
|
||||
)
|
||||
BOOL_FIELDS = ("bold", "italic", "keep_with_next", "keep_lines_together", "page_break_before", "widow_control", "contextual_spacing")
|
||||
BOOL_FIELDS = ("bold", "italic", "underline", "strike", "keep_with_next", "keep_lines_together", "page_break_before", "widow_control", "contextual_spacing")
|
||||
|
||||
|
||||
def number(value: object, fallback: float = 0) -> float:
|
||||
@@ -58,8 +64,9 @@ def normalize_rule(value: object) -> dict[str, Any]:
|
||||
for key in BOOL_FIELDS:
|
||||
if key in rule and not isinstance(rule[key], bool):
|
||||
rule.pop(key)
|
||||
if "font_color" in rule and not re.fullmatch(r"auto|#[0-9a-fA-F]{6}", str(rule["font_color"])):
|
||||
rule.pop("font_color")
|
||||
for key in ('font_color', 'background_color', 'border_color'):
|
||||
if key in rule and not re.fullmatch(r"auto|transparent|#[0-9a-fA-F]{6}", str(rule[key])):
|
||||
rule.pop(key)
|
||||
for key, allowed in {"alignment": {"left", "center", "right", "justify"},
|
||||
"indent_mode": {"none", "first", "hanging"},
|
||||
"line_spacing_mode": {"multiple", "exact", "at_least"}}.items():
|
||||
@@ -105,7 +112,7 @@ def resolved_rules(rules: dict | None, font_family: str = "", font_size_px: floa
|
||||
result = {}
|
||||
for target, _, _ in STYLE_TARGETS:
|
||||
rule = dict(base)
|
||||
if target.startswith("h"):
|
||||
if re.fullmatch('h[1-6]', target):
|
||||
level = int(target[1:])
|
||||
scale = [2.05, 1.48, 1.2, 1, .83, .67][level - 1]
|
||||
if preset == "compact" and level == 1:
|
||||
@@ -114,14 +121,16 @@ def resolved_rules(rules: dict | None, font_family: str = "", font_size_px: floa
|
||||
space_before_value=0 if level == 1 else 1.35, space_after_value=.55, keep_with_next=True)
|
||||
if preset == "focus" and level == 1:
|
||||
rule["alignment"] = "center"
|
||||
elif target == "code":
|
||||
elif target in ("code", 'code_block', 'inline_code'):
|
||||
rule.update(english_font_family="Consolas", font_size=font_size_px * .95, space_before_value=0, space_after_value=0)
|
||||
elif target == "blockquote":
|
||||
rule.update(left_indent_value=1, right_indent_value=1)
|
||||
elif target == "list":
|
||||
elif target in ("list", 'list_bullet', 'list_ordered', 'list_task'):
|
||||
rule.update(left_indent_value=2, indent_mode="hanging", indent_value=1)
|
||||
elif target == "table":
|
||||
elif target in ("table", 'table_head', 'table_cell'):
|
||||
rule.update(space_before_value=0, space_after_value=0)
|
||||
from .style_catalog import CHARACTER_DEFAULTS
|
||||
rule.update(CHARACTER_DEFAULTS.get(target, {}))
|
||||
rule.update(normalize_rule((rules or {}).get(target, {})))
|
||||
result[target] = rule
|
||||
return result
|
||||
@@ -151,6 +160,21 @@ def css_declarations(value: dict) -> list[str]:
|
||||
out.append(f"color: {r['font_color'] if r['font_color'] != 'auto' else 'var(--reader-text-color, #23272f)'};")
|
||||
if "letter_spacing" in r:
|
||||
out.append(f"letter-spacing: {fmt(r['letter_spacing'])}pt;")
|
||||
if 'underline' in r or 'strike' in r:
|
||||
decoration = ' '.join(name for key, name in (('underline', 'underline'), ('strike', 'line-through')) if r.get(key)) or 'none'
|
||||
out.append(f'text-decoration-line: {decoration};')
|
||||
if 'background_color' in r:
|
||||
out.append(f"background-color: {r['background_color']};")
|
||||
if 'border_color' in r:
|
||||
out.append(f"border-color: {r['border_color']};")
|
||||
if 'border_width' in r:
|
||||
out.extend((f"border-width: {fmt(r['border_width'])}pt;", 'border-style: solid;'))
|
||||
if 'cell_padding' in r:
|
||||
out.append(f"padding: {fmt(r['cell_padding'])}pt;")
|
||||
if 'list_marker' in r:
|
||||
out.append(f"list-style-type: {r['list_marker']};")
|
||||
if 'level_indent' in r:
|
||||
out.append(f"--mdhelper-list-level-indent: {fmt(r['level_indent'])}pt;")
|
||||
if r.get("alignment") in {"left", "center", "right", "justify"}:
|
||||
out.append(f"text-align: {r['alignment']};")
|
||||
if number(r.get("line_height_value")) > 0:
|
||||
@@ -186,9 +210,11 @@ def build_document_style_css(rules: dict | None, extra_css: str = "") -> str:
|
||||
declarations = css_declarations(rule)
|
||||
if declarations:
|
||||
parts.append(selector + " {\n " + "\n ".join(declarations) + "\n}")
|
||||
if target == "list":
|
||||
if target in ("list", 'list_bullet', 'list_ordered', 'list_task'):
|
||||
# Loose Markdown lists contain p elements; spacing belongs to li.
|
||||
parts.append(".reader li > p { margin: 0; text-indent: inherit; }")
|
||||
if 'level_indent' in rule:
|
||||
parts.append(selector + f" > :is(ul, ol) {{ padding-left: {fmt(rule['level_indent'])}pt; }}")
|
||||
if rule.get("contextual_spacing"):
|
||||
# Match adjacent elements of the same paragraph type, not p + h1.
|
||||
contexts = {"paragraph": (("", "p:not(:where(li p, blockquote p, .admonition p, th p, td p))"),),
|
||||
|
||||
@@ -67,17 +67,36 @@ class MarkdownRenderer:
|
||||
self.markdown.core.ruler.push("mdhelper_heading_ids", self._add_heading_ids)
|
||||
self.markdown.core.ruler.push("mdhelper_admonitions", self._convert_admonitions)
|
||||
self.markdown.core.ruler.push("mdhelper_task_lists", self._convert_task_lists)
|
||||
self.markdown.core.ruler.push("mdhelper_semantic_styles", self._mark_semantic_styles)
|
||||
self.markdown.core.ruler.push("mdhelper_source_lines", self._add_source_lines)
|
||||
for name in ("fence", "code_block", "math_block"):
|
||||
original = self.markdown.renderer.rules[name]
|
||||
def mapped(tokens, idx, options, env, render=original):
|
||||
output = render(tokens, idx, options, env)
|
||||
if tokens[idx].info.strip().lower() != 'mermaid':
|
||||
output = output.replace('<pre', '<pre data-mdh-style="code_block"', 1)
|
||||
mapping = tokens[idx].map
|
||||
if mapping and env.get("source_map"):
|
||||
output = output.replace("<div", f'<div data-source-line="{mapping[0]}" data-source-end="{mapping[1]}"', 1)
|
||||
return output
|
||||
self.markdown.renderer.rules[name] = mapped
|
||||
|
||||
@staticmethod
|
||||
def _mark_semantic_styles(state):
|
||||
lists = []
|
||||
for token in state.tokens:
|
||||
if token.type in ('ordered_list_open', 'bullet_list_open'):
|
||||
lists.append('list_ordered' if token.type == 'ordered_list_open' else 'list_bullet')
|
||||
elif token.type in ('ordered_list_close', 'bullet_list_close'):
|
||||
if lists: lists.pop()
|
||||
elif token.type == 'list_item_open':
|
||||
key = 'list_task' if 'task-list-item' in (token.attrGet('class') or '') else (lists[-1] if lists else 'list_bullet')
|
||||
token.attrSet('data-mdh-style', key)
|
||||
elif token.type in ('th_open', 'td_open'):
|
||||
token.attrSet('data-mdh-style', 'table_head' if token.type == 'th_open' else 'table_cell')
|
||||
for child in token.children or []:
|
||||
if child.type == 'code_inline': child.attrSet('data-mdh-style', 'inline_code')
|
||||
|
||||
@staticmethod
|
||||
def _add_source_lines(state: Any) -> None:
|
||||
if not state.env.get("source_map"):
|
||||
|
||||
@@ -115,6 +115,7 @@ def token_regions(tokens):
|
||||
target = None
|
||||
if token.type == 'heading_open': target = token.tag
|
||||
elif token.type in ('fence', 'code_block'): target = 'code_block'
|
||||
elif token.type == 'table_open': target = 'table'
|
||||
elif token.type in ('th_open', 'td_open'): target = 'table_head' if token.type == 'th_open' else 'table_cell'
|
||||
elif token.type == 'list_item_open':
|
||||
target = 'list_task' if 'task-list-item' in (token.attrGet('class') or '') else next(
|
||||
|
||||
@@ -35,6 +35,7 @@ from .document_style import (STYLE_TARGETS, normalize_rule, resolved_rules,
|
||||
|
||||
from .document_style import build_document_style_css
|
||||
from .style_sync import analyze_css, source_from_payload, patch_core
|
||||
from .style_catalog import CATALOG, CHARACTER_FIELDS
|
||||
|
||||
|
||||
class DocumentStyleEditorDialog(QDialog):
|
||||
@@ -160,6 +161,7 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
layout.addWidget(self.target_list)
|
||||
panel = QWidget()
|
||||
form = QFormLayout(panel)
|
||||
self.form = form
|
||||
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
|
||||
self.font_combo = QFontComboBox()
|
||||
self.chinese_font_combo = self.font_combo
|
||||
@@ -177,7 +179,7 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
("五号 10.5 磅", 10.5), ("小五 9 磅", 9), ("六号 7.5 磅", 7.5)])
|
||||
form.addRow("字号", self._row(self.font_size_spin, self.font_size_unit_combo, self.font_size_preset_combo))
|
||||
self.bool_boxes = {}
|
||||
for key, label in [("bold", "加粗"), ("italic", "斜体"), ("contextual_spacing", "同样式段落间不添加间距"),
|
||||
for key, label in [("bold", "加粗"), ("italic", "斜体"), ('underline', '下划线'), ('strike', '删除线'), ("contextual_spacing", "同样式段落间不添加间距"),
|
||||
("keep_with_next", "与下段同页"), ("keep_lines_together", "段中不分页"),
|
||||
("page_break_before", "段前分页"), ("widow_control", "孤行控制")]:
|
||||
box = QCheckBox(label)
|
||||
@@ -187,6 +189,29 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
self.bold_checkbox = self.bool_boxes["bold"]
|
||||
self.italic_checkbox = self.bool_boxes["italic"]
|
||||
form.addRow("字形", self._row(self.bold_checkbox, self.italic_checkbox))
|
||||
form.addRow('文字修饰', self._row(self.bool_boxes['underline'], self.bool_boxes['strike']))
|
||||
self.background_edit = QLineEdit()
|
||||
self.background_edit.setPlaceholderText('继承 / transparent / #RRGGBB')
|
||||
form.addRow('底色', self.background_edit)
|
||||
self.border_color_edit = QLineEdit()
|
||||
self.border_color_edit.setPlaceholderText('继承 / #RRGGBB')
|
||||
self.border_width_spin = self._spin(20)
|
||||
self.border_width_spin.setSuffix(' 磅')
|
||||
self.cell_padding_spin = self._spin(100)
|
||||
self.cell_padding_spin.setSuffix(' 磅')
|
||||
self.border_row = form.rowCount()
|
||||
form.addRow('边框颜色 / 宽度', self._row(self.border_color_edit, self.border_width_spin))
|
||||
self.padding_row = form.rowCount()
|
||||
form.addRow('内边距', self.cell_padding_spin)
|
||||
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()
|
||||
form.addRow('列表标记', self.list_marker_box)
|
||||
self.level_indent_spin = self._spin(200); self.level_indent_spin.setSuffix(' 磅')
|
||||
self.level_row = form.rowCount()
|
||||
form.addRow('每级列表缩进', self.level_indent_spin)
|
||||
for edit in (self.background_edit, self.border_color_edit):
|
||||
edit.editingFinished.connect(self._store_and_refresh)
|
||||
self.color_combo = self._combo([("继承", None), ("自动(随主题)", "auto"), ("自定义…", "custom")])
|
||||
self.color_button = QPushButton("#23272f")
|
||||
self.color_button.clicked.connect(self._choose_color)
|
||||
@@ -195,6 +220,7 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
self.character_spacing_spin = self._spin(100, False)
|
||||
self.character_spacing_spin.setSuffix(" 磅")
|
||||
form.addRow("字符间距", self._row(self.character_spacing_combo, self.character_spacing_spin))
|
||||
self.paragraph_row_start = form.rowCount()
|
||||
self.alignment_combo = self._combo([("继承", None), ("左对齐", "left"), ("居中", "center"), ("右对齐", "right"), ("两端对齐", "justify")])
|
||||
form.addRow("对齐方式", self.alignment_combo)
|
||||
for side, label in (("left", "左缩进"), ("right", "右缩进")):
|
||||
@@ -221,6 +247,7 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
form.addRow("段落间距", self.bool_boxes["contextual_spacing"])
|
||||
form.addRow("换行与分页", self._row(self.bool_boxes["keep_with_next"], self.bool_boxes["keep_lines_together"]))
|
||||
form.addRow("", self._row(self.bool_boxes["page_break_before"], self.bool_boxes["widow_control"]))
|
||||
self.paragraph_row_end = form.rowCount()
|
||||
note = QLabel("“继承”沿用文档默认样式;0 表示清零。复选框方块表示继承。")
|
||||
note.setWordWrap(True)
|
||||
form.addRow(note)
|
||||
@@ -258,7 +285,7 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
def _build_advanced_tab(self, css: str) -> QWidget:
|
||||
page = QWidget()
|
||||
layout = QVBoxLayout(page)
|
||||
label = QLabel("这里是完整自定义样式。修改常规对象规则中的核心属性会同步到图形设置及 Word;背景、边框、条件规则等扩展效果保留为 CSS。")
|
||||
label = QLabel("这里是完整样式集。已支持的字体、段落、文字修饰及底色/边框属性会同步到图形设置和 Word;复杂选择器、条件规则等保留为 CSS,并显示适用范围提示。")
|
||||
label.setWordWrap(True)
|
||||
layout.addWidget(label)
|
||||
self.extra_css_edit = QTextEdit()
|
||||
@@ -349,6 +376,18 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
|
||||
def _load_rule_to_widgets(self, rule: dict[str, Any]) -> None:
|
||||
self._loading = True
|
||||
character = CATALOG[self._current_target].kind == 'character'
|
||||
for row in range(self.paragraph_row_start, self.paragraph_row_end): self.form.setRowVisible(row, not character)
|
||||
self.form.setRowVisible(self.border_row, not character)
|
||||
self.form.setRowVisible(self.padding_row, not character)
|
||||
self.form.setRowVisible(self.marker_row, self._current_target.startswith('list'))
|
||||
self.form.setRowVisible(self.level_row, self._current_target.startswith('list'))
|
||||
self.background_edit.setText(rule.get('background_color', ''))
|
||||
self.border_color_edit.setText(rule.get('border_color', ''))
|
||||
self.border_width_spin.setValue(number(rule.get('border_width'), -1))
|
||||
self.cell_padding_spin.setValue(number(rule.get('cell_padding'), -1))
|
||||
self.level_indent_spin.setValue(number(rule.get('level_indent'), -1))
|
||||
self._select(self.list_marker_box, rule.get('list_marker'))
|
||||
rule = normalize_rule(rule)
|
||||
for key, box in (("chinese_font_family", self.font_combo), ("english_font_family", self.english_font_combo)):
|
||||
box.setCurrentText(str(rule.get(key) or "继承"))
|
||||
@@ -396,6 +435,12 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
put("font_size_unit", self.font_size_unit_combo.currentData() if size > 0 else None)
|
||||
for key, box in self.bool_boxes.items():
|
||||
put(key, None if box.checkState() == Qt.CheckState.PartiallyChecked else box.isChecked())
|
||||
for key, widget in (('background_color', self.background_edit), ('border_color', self.border_color_edit)):
|
||||
text = widget.text().strip()
|
||||
put(key, text if re.fullmatch(r'#[0-9a-fA-F]{6}|transparent', text) else None)
|
||||
for key, widget in (('border_width', self.border_width_spin), ('cell_padding', self.cell_padding_spin), ('level_indent', self.level_indent_spin)):
|
||||
put(key, widget.value() if widget.value() >= 0 else None)
|
||||
put('list_marker', self.list_marker_box.currentData())
|
||||
color = self.color_combo.currentData()
|
||||
put("font_color", self.color_button.text() if color == "custom" else color)
|
||||
direction = self.character_spacing_combo.currentData()
|
||||
@@ -414,6 +459,8 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
put("line_spacing_mode", "multiple" if mode in preset else mode)
|
||||
put("line_height_value", None if mode is None else preset.get(mode, self.line_height_spin.value()))
|
||||
rule.pop("line_height_unit", None)
|
||||
if CATALOG[self._current_target].kind == 'character':
|
||||
rule = {key: value for key, value in rule.items() if key in CHARACTER_FIELDS}
|
||||
if rule:
|
||||
self.rules[self._current_target] = rule
|
||||
else:
|
||||
@@ -482,6 +529,9 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
char.setFontPointSize(points)
|
||||
char.setFontWeight(QFont.Weight.Bold if rule["bold"] else QFont.Weight.Normal)
|
||||
char.setFontItalic(rule["italic"])
|
||||
char.setFontUnderline(rule.get('underline', False))
|
||||
char.setFontStrikeOut(rule.get('strike', False))
|
||||
if str(rule.get('background_color', '')).startswith('#'): char.setBackground(QColor(rule['background_color']))
|
||||
char.setForeground(QColor("#23272f" if rule["font_color"] == "auto" else rule["font_color"]))
|
||||
char.setFontLetterSpacingType(QFont.SpacingType.AbsoluteSpacing)
|
||||
char.setFontLetterSpacing(number(rule["letter_spacing"]) * scale)
|
||||
|
||||
+36
-2
@@ -21,6 +21,9 @@ GROUPS = {
|
||||
"fonts": ("chinese_font_family", "english_font_family"),
|
||||
"size": ("font_size", "font_size_unit"), "bold": ("bold",), "italic": ("italic",),
|
||||
"color": ("font_color",), "tracking": ("letter_spacing",), "align": ("alignment",),
|
||||
'decoration': ('underline', 'strike'), 'background': ('background_color',),
|
||||
'border_color': ('border_color',), 'border_width': ('border_width',), 'padding': ('cell_padding',),
|
||||
'marker': ('list_marker',), 'level_indent': ('level_indent',),
|
||||
"line": ("line_spacing_mode", "line_height_value"), "indent": ("indent_mode", "indent_value"),
|
||||
**{side: (f"{side}_indent_value", f"{side}_indent_unit") for side in ("left", "right")},
|
||||
**{side: (f"space_{side}_value", f"space_{side}_unit") for side in ("before", "after")},
|
||||
@@ -30,6 +33,9 @@ PROPERTIES = {
|
||||
"fonts": {"font-family", "--mdhelper-font-chinese", "--mdhelper-font-english"},
|
||||
"size": {"font-size"}, "bold": {"font-weight"}, "italic": {"font-style"}, "color": {"color"},
|
||||
"tracking": {"letter-spacing"}, "align": {"text-align"},
|
||||
'decoration': {'text-decoration', 'text-decoration-line'}, 'background': {'background-color'},
|
||||
'border_color': {'border-color'}, 'border_width': {'border-width', 'border-style'}, 'padding': {'padding'},
|
||||
'marker': {'list-style-type'}, 'level_indent': {'--mdhelper-list-level-indent'},
|
||||
"line": {"line-height", "--mdhelper-line-spacing-mode"}, "indent": {"text-indent"},
|
||||
**{side: {f"margin-{side}"} for side in ("left", "right")},
|
||||
"before": {"margin-top"}, "after": {"margin-bottom"},
|
||||
@@ -51,6 +57,8 @@ ALIASES = {"p": "paragraph", **{f"h{i}": f"h{i}" for i in range(1, 7)}, "li": "l
|
||||
"blockquote": "blockquote", "blockquote p": "blockquote", ".admonition p": "blockquote",
|
||||
"pre": "code", "code": "code", "table": "table", "th": "table", "td": "table"}
|
||||
ALIASES.update({".reader " + key: target for key, target in list(ALIASES.items())})
|
||||
ALIASES.update({selector: key for key, selector in SELECTORS.items() if ',' not in selector})
|
||||
ALIASES.update({'strong': 'strong', 'em': 'emphasis', 's': 'strike', 'del': 'strike', '.reader del': 'strike', 'a': 'link'})
|
||||
ALIASES[_normalize_selector_text(SELECTORS["paragraph"])] = "paragraph"
|
||||
FONT_VARIABLES = {"chinese_font_family": "--mdhelper-font-chinese", "english_font_family": "--mdhelper-font-english"}
|
||||
FONT_EXPRESSION = "var(--mdhelper-font-english, var(--mdhelper-font-chinese, var(--reader-font-family))), var(--mdhelper-font-chinese, sans-serif)"
|
||||
@@ -90,7 +98,7 @@ def _property(declaration):
|
||||
def _specificity(selector):
|
||||
# Only aliases in the allow-list reach this function. :where has zero weight.
|
||||
selector = re.sub(r":not\(:where\(.*\)\)", "", selector)
|
||||
return selector.count("."), len(re.findall(r"(?:^|\s)(?:p|h[1-6]|li|blockquote|pre|code|table|th|td)\b", selector))
|
||||
return selector.count(".") + selector.count('['), len(re.findall(r"(?:^|\s)(?:p|h[1-6]|li|blockquote|pre|code|table|th|td|strong|em|s|a)\b", selector))
|
||||
|
||||
|
||||
def _balanced(source):
|
||||
@@ -269,6 +277,13 @@ class _CoreRuleReader:
|
||||
self.choice('text-align', 'alignment', {name: name for name in ('left', 'center', 'right', 'justify')})
|
||||
self.read('color', self.color)
|
||||
self.read('letter-spacing', self.tracking)
|
||||
self.read('text-decoration', self.decoration)
|
||||
self.read('text-decoration-line', self.decoration)
|
||||
for prop, field in (('background-color', 'background_color'), ('border-color', 'border_color')):
|
||||
self.read(prop, lambda value, field=field: self.effect_color(value, field))
|
||||
for prop, field in (('border-width', 'border_width'), ('padding', 'cell_padding'), ('--mdhelper-list-level-indent', 'level_indent')):
|
||||
self.read(prop, lambda value, field=field: self.effect_length(value, field))
|
||||
self.choice('list-style-type', 'list_marker', {x: x for x in ('none', 'disc', 'circle', 'square', 'decimal', 'lower-alpha', 'upper-alpha', 'lower-roman', 'upper-roman')})
|
||||
self.read('line-height', self.line)
|
||||
for side, prefix in (('left', 'left_indent'), ('right', 'right_indent'), ('top', 'space_before'), ('bottom', 'space_after')):
|
||||
self.read('margin-' + side, lambda value, prefix=prefix: self.margin(value, prefix))
|
||||
@@ -277,6 +292,21 @@ class _CoreRuleReader:
|
||||
self.choice('--mdhelper-contextual-spacing', 'contextual_spacing', {'true': True, 'false': False})
|
||||
return self.rule
|
||||
|
||||
def decoration(self, value):
|
||||
parts = value.split()
|
||||
if not parts or not set(parts) <= {'none', 'underline', 'line-through'}: raise ValueError
|
||||
self.rule.update(underline='underline' in parts, strike='line-through' in parts)
|
||||
|
||||
def effect_color(self, value, field):
|
||||
if value == 'transparent': self.rule[field] = value; return
|
||||
color = parse_color(value)
|
||||
if color is None or color == 'currentColor' or color.alpha != 1: raise ValueError
|
||||
self.rule[field] = '#' + ''.join(f'{round(v * 255):02x}' for v in color[:3])
|
||||
|
||||
def effect_length(self, value, field):
|
||||
amount, unit = _length(value, ('pt', 'px'))
|
||||
self.rule[field] = amount * (.75 if unit == 'px' else 1)
|
||||
|
||||
def pagination(self):
|
||||
breaks = (
|
||||
('keep_with_next', 'break-after', 'page-break-after', ('avoid', 'avoid-page')),
|
||||
@@ -492,8 +522,12 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal
|
||||
|
||||
def render_css(source: str, rules: dict) -> str:
|
||||
"""Materialize the few core features which need companion reader rules."""
|
||||
contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if rule.get("contextual_spacing")}
|
||||
from .style_catalog import explicit_rules
|
||||
inherited = explicit_rules(rules)
|
||||
inherited = {key: {field: value for field, value in rule.items() if field not in rules.get(key, {})} for key, rule in inherited.items()}
|
||||
contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if isinstance(rule, dict) and rule.get("contextual_spacing")}
|
||||
helpers = build_document_style_css(contextual)
|
||||
helpers += '\n' + build_document_style_css(inherited)
|
||||
paragraph = rules.get("paragraph", {})
|
||||
if paragraph.get("font_size"):
|
||||
helpers += f"\n.reader {{ --reader-math-font-size: {fmt(paragraph['font_size'])}{paragraph.get('font_size_unit', 'px')}; }}"
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWebEngineCore import QWebEnginePage
|
||||
from mdhelper.style_sync import analyze_css, patch_core, normalize_payload, render_css
|
||||
from mdhelper.style_dialog import DocumentStyleEditorDialog
|
||||
from mdhelper.markdown_renderer import MarkdownRenderer
|
||||
|
||||
|
||||
def test_core_character_and_container_fields_roundtrip():
|
||||
rule = dict(font_color='#123456', underline=True, strike=True, background_color='#ffff00')
|
||||
source = patch_core('a:hover {color:red} /* retained */', 'link', {}, rule)
|
||||
assert analyze_css(source).rules['link'] == rule
|
||||
assert 'a:hover' in source and 'retained' in source
|
||||
source = patch_core(source, 'table', {}, {'border_color': '#123456', 'border_width': 1, 'cell_padding': 5})
|
||||
assert analyze_css(source).rules['table']['cell_padding'] == 5
|
||||
source = patch_core(source, 'list_ordered', {}, {'list_marker': 'upper-roman', 'level_indent': 20})
|
||||
assert analyze_css(source).rules['list_ordered']['level_indent'] == 20
|
||||
assert normalize_payload(normalize_payload({'css': source}))['css'] == source
|
||||
|
||||
|
||||
def test_character_dialog_hides_paragraph_controls_and_preserves_other_types(qt_application):
|
||||
dialog = DocumentStyleEditorDialog({'rules': {'paragraph': {'alignment': 'justify'}}})
|
||||
try:
|
||||
for index in range(dialog.target_list.count()):
|
||||
if dialog.target_list.item(index).data(Qt.ItemDataRole.UserRole) == 'link': dialog.target_list.setCurrentRow(index); break
|
||||
assert not dialog.form.isRowVisible(dialog.paragraph_row_start)
|
||||
dialog.bool_boxes['underline'].setChecked(True)
|
||||
dialog.background_edit.setText('#aabbcc'); dialog.background_edit.editingFinished.emit()
|
||||
rules = dialog.style_payload()['rules']
|
||||
assert rules['paragraph']['alignment'] == 'justify'
|
||||
assert rules['link']['underline'] and rules['link']['background_color'] == '#aabbcc'
|
||||
assert 'alignment' not in rules['link']
|
||||
finally: dialog.close()
|
||||
|
||||
|
||||
def test_browser_semantic_styles_and_contextual_character_inheritance(qt_application, tmp_path):
|
||||
renderer = MarkdownRenderer(tmp_path)
|
||||
payload = normalize_payload({'rules': {'h1': {'font_size': 30, 'font_size_unit': 'px'},
|
||||
'link': {'font_color': '#123456', 'underline': True}, 'inline_code': {'background_color': '#ffeecc'},
|
||||
'list_bullet': {'font_color': '#112233'}, 'list_ordered': {'font_color': '#445566'},
|
||||
'table_head': {'font_color': '#778899'}}})
|
||||
content = renderer.render_source('# Head **bold** [link](https://example.com)\n\n`code`\n\n- Bullet\n\n1. Number\n\n| Head |\n|---|\n| Cell |',
|
||||
tmp_path / 'note.md', document_style_css=render_css(payload['css'], payload['rules']))
|
||||
page = QWebEnginePage(); loaded = []
|
||||
page.loadFinished.connect(loaded.append); page.setHtml(content)
|
||||
def wait(condition):
|
||||
deadline = time.monotonic() + 10
|
||||
while not condition() and time.monotonic() < deadline: qt_application.processEvents(); time.sleep(.01)
|
||||
assert condition()
|
||||
try:
|
||||
wait(lambda: bool(loaded)); values = []
|
||||
page.runJavaScript('''JSON.stringify({h:getComputedStyle(document.querySelector('h1')).fontSize,
|
||||
a:getComputedStyle(document.querySelector('h1 a')).fontSize,
|
||||
strong:getComputedStyle(document.querySelector('h1 strong')).fontSize,
|
||||
color:getComputedStyle(document.querySelector('h1 a')).color,
|
||||
lists:[...document.querySelectorAll('li')].map(e=>getComputedStyle(e).color),
|
||||
code:document.querySelector('p code').getAttribute('data-mdh-style')})''', values.append)
|
||||
wait(lambda: bool(values)); result = json.loads(values[0])
|
||||
assert result['a'] == result['strong'] == result['h'] == '30px'
|
||||
assert result['color'] == 'rgb(18, 52, 86)' and result['lists'] == ['rgb(17, 34, 51)', 'rgb(68, 85, 102)']
|
||||
assert result['code'] == 'inline_code'
|
||||
finally: page.deleteLater(); qt_application.processEvents()
|
||||
Reference in New Issue
Block a user