feat: define semantic style identities and compatible inheritance
This commit is contained in:
@@ -87,6 +87,8 @@ def line_points(rule: dict, font_pt: float) -> float:
|
||||
|
||||
def resolved_rules(rules: dict | None, font_family: str = "", font_size_px: float = 16, preset: str = "default") -> dict[str, dict]:
|
||||
"""Reader defaults, not Word's theme-dependent defaults."""
|
||||
from .style_catalog import explicit_rules
|
||||
rules = explicit_rules(rules)
|
||||
base = dict(chinese_font_family=font_family or "Microsoft YaHei UI", english_font_family=font_family or "Microsoft YaHei UI",
|
||||
font_size=font_size_px, font_size_unit="px", bold=False, italic=False,
|
||||
font_color="auto", line_spacing_mode="multiple", line_height_value=1.72,
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Semantic style identities, inheritance and Markdown usage, independent of widgets."""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StyleDefinition:
|
||||
key: str
|
||||
name: str
|
||||
kind: str
|
||||
syntax: str
|
||||
base: str = ''
|
||||
|
||||
|
||||
DEFINITIONS = (
|
||||
StyleDefinition('paragraph', '正文', 'paragraph', '普通段落'),
|
||||
*(StyleDefinition(f'h{i}', f'标题 {i}', 'paragraph', '#' * i + ' 标题') for i in range(1, 7)),
|
||||
StyleDefinition('list', '列表基准', 'paragraph', '所有列表项'),
|
||||
StyleDefinition('blockquote', '引用', 'paragraph', '> 引用'),
|
||||
StyleDefinition('code', '代码基准', 'paragraph', '兼容原代码设置'),
|
||||
StyleDefinition('table', '表格基准', 'table', 'Markdown 表格'),
|
||||
StyleDefinition('list_bullet', '无序列表', 'paragraph', '- 列表', 'list'),
|
||||
StyleDefinition('list_ordered', '有序列表', 'paragraph', '1. 列表', 'list'),
|
||||
StyleDefinition('list_task', '任务列表', 'paragraph', '- [ ] 任务', 'list'),
|
||||
StyleDefinition('code_block', '代码块', 'paragraph', '围栏代码 / 缩进代码', 'code'),
|
||||
StyleDefinition('table_head', '表头文字', 'paragraph', '表格表头'),
|
||||
StyleDefinition('table_cell', '单元格文字', 'paragraph', '表格单元格'),
|
||||
StyleDefinition('strong', '加粗', 'character', '**文字**'),
|
||||
StyleDefinition('emphasis', '强调', 'character', '*文字*'),
|
||||
StyleDefinition('strike', '删除线', 'character', '~~文字~~'),
|
||||
StyleDefinition('link', '超链接', 'character', '[文字](地址)'),
|
||||
StyleDefinition('inline_code', '行内代码', 'character', '`代码`'),
|
||||
)
|
||||
CATALOG = {item.key: item for item in DEFINITIONS}
|
||||
KINDS = {'paragraph': '段落', 'character': '字符', 'table': '表格'}
|
||||
CHARACTER_FIELDS = {'chinese_font_family', 'english_font_family', 'font_size', 'font_size_unit',
|
||||
'bold', 'italic', 'font_color', 'letter_spacing', 'underline', 'strike', 'background_color'}
|
||||
CHARACTER_DEFAULTS = {'strong': {'bold': True}, 'emphasis': {'italic': True}, 'strike': {'strike': True},
|
||||
'link': {'font_color': '#0563c1', 'underline': True},
|
||||
'inline_code': {'english_font_family': 'Consolas'}}
|
||||
|
||||
|
||||
def normalize_metadata(value):
|
||||
result = {}
|
||||
if not isinstance(value, dict): return result
|
||||
for key, item in value.items():
|
||||
if key not in CATALOG or not isinstance(item, dict): continue
|
||||
clean = {}
|
||||
if isinstance(item.get('name'), str) and item['name'].strip(): clean['name'] = item['name'].strip()[:80]
|
||||
base = item.get('based_on')
|
||||
if base == '' or isinstance(base, str) and base in CATALOG and CATALOG[base].kind == CATALOG[key].kind and base != key:
|
||||
clean['based_on'] = base
|
||||
if clean: result[key] = clean
|
||||
# Imported cycles are repaired without throwing away independent formatting.
|
||||
for key in list(result):
|
||||
seen, current = set(), key
|
||||
while current:
|
||||
if current in seen:
|
||||
result[key]['based_on'] = ''
|
||||
break
|
||||
seen.add(current)
|
||||
current = result.get(current, {}).get('based_on', CATALOG[current].base)
|
||||
return result
|
||||
|
||||
|
||||
def style_name(key, rules=None):
|
||||
return normalize_metadata((rules or {}).get('_metadata')).get(key, {}).get('name', CATALOG[key].name)
|
||||
|
||||
|
||||
def parent_style(key, rules):
|
||||
return normalize_metadata(rules.get('_metadata')).get(key, {}).get('based_on', CATALOG[key].base)
|
||||
|
||||
|
||||
def explicit_rules(rules):
|
||||
"""Resolve authored declarations only; absent character fields inherit their paragraph."""
|
||||
rules = rules if isinstance(rules, dict) else {}
|
||||
metadata = normalize_metadata(rules.get('_metadata'))
|
||||
result = {}
|
||||
def resolve(key):
|
||||
if key in result: return result[key]
|
||||
base = metadata.get(key, {}).get('based_on', CATALOG[key].base)
|
||||
own = rules.get(key, {})
|
||||
own = own if isinstance(own, dict) else {}
|
||||
inherited = dict(resolve(base)) if base else {}
|
||||
if key in ('table_head', 'table_cell') and not base:
|
||||
inherited.update({k: v for k, v in rules.get('table', {}).items() if k not in {'border_color', 'border_width', 'cell_padding'}})
|
||||
if key == 'inline_code' and not base:
|
||||
inherited.update({k: v for k, v in rules.get('code', {}).items() if k in CHARACTER_FIELDS})
|
||||
inherited.update(own)
|
||||
if CATALOG[key].kind == 'character': inherited = {k: v for k, v in inherited.items() if k in CHARACTER_FIELDS}
|
||||
result[key] = inherited
|
||||
return inherited
|
||||
for key in CATALOG: resolve(key)
|
||||
return result
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StyleRegion:
|
||||
start: int
|
||||
end: int
|
||||
style: str
|
||||
characters: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def token_regions(tokens):
|
||||
regions, used, stack = [], set(), []
|
||||
inline_styles = {'strong_open': 'strong', 'em_open': 'emphasis', 's_open': 'strike',
|
||||
'link_open': 'link', 'code_inline': 'inline_code'}
|
||||
for index, token in enumerate(tokens):
|
||||
if token.nesting == -1:
|
||||
if stack: stack.pop()
|
||||
continue
|
||||
contexts = [kind for kind, _ in stack]
|
||||
target = None
|
||||
if token.type == 'heading_open': target = token.tag
|
||||
elif token.type in ('fence', 'code_block'): target = 'code_block'
|
||||
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(
|
||||
('list_ordered' if kind == 'ordered_list_open' else 'list_bullet' for kind, _ in reversed(stack)
|
||||
if kind in ('ordered_list_open', 'bullet_list_open')), 'list_bullet')
|
||||
elif token.type == 'paragraph_open':
|
||||
target = next((style for _, style in reversed(stack) if style in ('list_bullet', 'list_ordered', 'list_task', 'table_head', 'table_cell')), None)
|
||||
target = target or ('blockquote' if 'blockquote_open' in contexts else 'paragraph')
|
||||
if token.nesting == 1: stack.append((token.type, target))
|
||||
if target:
|
||||
used.add(target)
|
||||
children = tokens[index + 1].children if index + 1 < len(tokens) and tokens[index + 1].type == 'inline' else []
|
||||
characters = tuple(dict.fromkeys(inline_styles[c.type] for c in children or [] if c.type in inline_styles))
|
||||
used.update(characters)
|
||||
if token.map: regions.append(StyleRegion(token.map[0], token.map[1], target, characters))
|
||||
return regions, used
|
||||
|
||||
|
||||
def document_styles(source):
|
||||
from .markdown_renderer import MarkdownRenderer
|
||||
from pathlib import Path
|
||||
return token_regions(MarkdownRenderer(Path.cwd()).markdown.parse(source, {}))
|
||||
@@ -290,7 +290,10 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
self.css_status_label.setText("尚未同步:" + ";".join(result.errors[:3]))
|
||||
return False
|
||||
self._css_dirty = False
|
||||
metadata = self.rules.get('_metadata')
|
||||
self.rules = result.rules
|
||||
if metadata:
|
||||
self.rules['_metadata'] = deepcopy(metadata)
|
||||
if update_widgets:
|
||||
self._load_rule_to_widgets(self.rules.get(self._current_target, {}))
|
||||
else:
|
||||
|
||||
@@ -505,6 +505,10 @@ def render_css(source: str, rules: dict) -> str:
|
||||
def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_px=16) -> dict:
|
||||
source = source_from_payload(payload)
|
||||
result = analyze_css(source, font_size_px)
|
||||
from .style_catalog import normalize_metadata
|
||||
metadata = normalize_metadata((payload.get('rules') or {}).get('_metadata'))
|
||||
if metadata:
|
||||
result.rules['_metadata'] = metadata
|
||||
return {"name": str(payload.get("name") or fallback_name).strip() or fallback_name,
|
||||
"css_sync_version": 1, "css": source,
|
||||
"rules": result.rules if not result.errors else deepcopy(payload.get("rules") or {})}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from mdhelper.style_catalog import explicit_rules, normalize_metadata, document_styles
|
||||
from mdhelper.style_sync import normalize_payload
|
||||
from mdhelper.document_style import resolved_rules
|
||||
|
||||
|
||||
def test_inheritance_keeps_explicit_false_zero_and_rejects_cycles():
|
||||
rules = {'h1': {'font_size': 24, 'bold': True}, 'h2': {'bold': False, 'space_after_value': 0},
|
||||
'_metadata': {'h2': {'name': '章节标题', 'based_on': 'h1'}}}
|
||||
effective = resolved_rules(rules)
|
||||
assert effective['h2']['font_size'] == 24 and effective['h2']['bold'] is False
|
||||
assert effective['h2']['space_after_value'] == 0
|
||||
metadata = normalize_metadata({'h1': {'based_on': 'h2'}, 'h2': {'based_on': 'h1'}, 'strong': {'based_on': 'h1'}})
|
||||
assert 'based_on' not in metadata.get('strong', {})
|
||||
assert explicit_rules({'_metadata': metadata})['h1'] == {}
|
||||
|
||||
|
||||
def test_old_config_and_metadata_roundtrip():
|
||||
old = {'name': 'Old', 'rules': {'paragraph': {'font_size': 18}, '_metadata': {'h2': {'based_on': 'paragraph'}}}}
|
||||
current = normalize_payload(old)
|
||||
assert normalize_payload(current) == current
|
||||
assert current['rules']['paragraph']['font_size'] == 18
|
||||
assert current['rules']['_metadata']['h2']['based_on'] == 'paragraph'
|
||||
assert explicit_rules({'code': {'font_size': 15, 'alignment': 'center'}})['inline_code'] == {'font_size': 15}
|
||||
|
||||
|
||||
def test_semantic_styles_ignore_fenced_examples_and_include_nesting():
|
||||
source = '# Head **bold** [link](target)\n\n- [ ] Task *em*\n\n> Quote `code`\n\n```\n~~not a deletion~~\n```\n'
|
||||
regions, used = document_styles(source)
|
||||
assert {'h1', 'strong', 'link', 'list_task', 'emphasis', 'blockquote', 'inline_code', 'code_block'} <= used
|
||||
assert 'strike' not in used
|
||||
assert regions[0].characters == ('strong', 'link')
|
||||
Reference in New Issue
Block a user