From 0a9aeb6aa3daa38b39ef7a78ded6bbfb83552e70 Mon Sep 17 00:00:00 2001 From: shen Date: Thu, 5 Nov 2026 11:10:56 +0800 Subject: [PATCH] fix: preserve CSS resets and independent variable decorations --- mdhelper/markdown_renderer.py | 6 +- mdhelper/reader_decoration.py | 41 +++++++-- mdhelper/resources/reader_decorations.js | 54 +++++++++++ mdhelper/style_sync.py | 49 +++++++--- tests/test_css_revision_056.py | 110 +++++++++++++++++++++++ 5 files changed, 238 insertions(+), 22 deletions(-) create mode 100644 mdhelper/resources/reader_decorations.js create mode 100644 tests/test_css_revision_056.py diff --git a/mdhelper/markdown_renderer.py b/mdhelper/markdown_renderer.py index 979207f..571accb 100644 --- a/mdhelper/markdown_renderer.py +++ b/mdhelper/markdown_renderer.py @@ -752,11 +752,15 @@ class MarkdownRenderer: font_size = max(12, min(int(document_font_size or fallback_font_size), 28)) font_family = self._css_font_family(document_font_family) escaped_font_family = html.escape(font_family, quote=False) - from .reader_decoration import MARKER, wrap_decoration_text + from .reader_decoration import MARKER, DYNAMIC_MARKER, wrap_decoration_text leaf_decorations = MARKER in document_style_css if leaf_decorations: body = wrap_decoration_text(body) reader_shell = self._reader_shell_html(body) if leaf_decorations: reader_shell = reader_shell.replace('
diff --git a/mdhelper/reader_decoration.py b/mdhelper/reader_decoration.py index fd2b33f..400e73d 100644 --- a/mdhelper/reader_decoration.py +++ b/mdhelper/reader_decoration.py @@ -7,6 +7,7 @@ independent decoration to the final text. Raw markup and entities are retained. from html.parser import HTMLParser MARKER = '/* mdhelper:leaf-decorations */' +DYNAMIC_MARKER = '/* mdhelper:dynamic-decorations */' def wrap_decoration_text(body): @@ -51,6 +52,10 @@ def decoration_css(rules, inherited, selectors, source): return source root='.reader[data-mdh-leaf-decoration]' parts=[MARKER, root+' { --mdh-line-underline: ; --mdh-line-strike: ; }'] + # CSS revert uses user-agent decoration defaults, not our authored theme. + parts.extend([':where('+root+' *) { --mdh-default-underline: ; --mdh-default-strike: ; }', + ':where('+root+' a:any-link, '+root+' u) { --mdh-default-underline: underline; }', + ':where('+root+' s, '+root+' del) { --mdh-default-strike: line-through; }']) suppress=[] for key,selector in selectors.items(): if key == 'code_block': continue # Code blocks have no Markdown inline nesting. @@ -66,13 +71,14 @@ def decoration_css(rules, inherited, selectors, source): # Defaults have zero specificity; authored conditional selectors # can continue to change decorations (including hover effects). scope=selector if field in own else ':where('+selector+')' - parts.append(scope+' { --mdh-decoration-mode: initial; --mdh-decoration-raw: initial; --mdh-line-'+field+': '+(token if rule[field] else '')+'; }') + parts.append(scope+' { --mdh-line-'+field+': '+(token if rule[field] else '')+ + '; --mdh-override-'+field+': '+str(rule[field]).lower()+'; }') parts.append(_decoration_variables(source)) parts.append(', '.join(suppress)+' { text-decoration-line: none !important; }') parts.append(':where('+root+' p, '+root+' strong, '+root+' em, '+root+' a, '+root+' s, '+root+' del, '+root+' code) { text-decoration-color: inherit; text-decoration-style: inherit; text-decoration-thickness: inherit; }') # A variable may contain a complete shorthand (including color/style). - # Let the browser resolve it on text leaves; an inner core rule resets - # the inherited mode so it can still cancel decorations independently. + # Let the browser resolve it on text leaves. Independent core overrides + # are applied after the browser parses variable shorthand values. leaf=root+' [data-mdh-text]' parts.append(leaf+' { text-decoration-line: var(--mdh-decoration-raw, var(--mdh-line-underline) var(--mdh-line-strike)); text-decoration-color: inherit; text-decoration-style: inherit; text-decoration-thickness: inherit; }') parts.append('@container style(--mdh-decoration-mode: raw) { '+leaf+' { text-decoration: var(--mdh-decoration-shorthand); } }') @@ -83,7 +89,9 @@ def _decoration_variables(source): """Keep authored selectors, conditions, priority and decoration appearance.""" import tinycss2 as css from .style_sync import DECORATION_EXPRESSION, _invalid_core_value + dynamic = False def visit(nodes): + nonlocal dynamic output=[] for declaration in nodes: if declaration.type=='error': continue @@ -98,22 +106,37 @@ def _decoration_variables(source): if declaration.name in ('--mdhelper-underline','--mdhelper-strike') and value in ('true','false'): field=declaration.name.removeprefix('--mdhelper-') token=('underline' if field=='underline' else 'line-through') if value=='true' else '' - output.extend(css.parse_declaration_list(f'--mdh-decoration-mode:initial{suffix};--mdh-decoration-raw:initial{suffix};--mdh-line-{field}:{token}{suffix};')) + output.extend(css.parse_declaration_list(f'--mdh-line-{field}:{token}{suffix};--mdh-override-{field}:{value}{suffix};')) continue if declaration.lower_name not in ('text-decoration','text-decoration-line'):continue if value==DECORATION_EXPRESSION:continue if _invalid_core_value(declaration.lower_name, declaration.value): continue tokens=[t.lower_value for t in declaration.value if t.type=='ident'] lines=set(tokens)&{'none','underline','line-through','overline'} - if declaration.lower_name=='text-decoration' and any(t.type=='function' for t in declaration.value): + reset = {'--mdh-decoration-mode':'initial', '--mdh-decoration-raw':'initial', + '--mdh-decoration-shorthand':'initial', '--mdh-override-underline':'initial', '--mdh-override-strike':'initial'} + if value.lower() in ('inherit', 'revert-layer'): + values = {key:value.lower() for key in (*reset, '--mdh-line-underline', '--mdh-line-strike')} + elif value.lower() in ('initial','unset','revert'): + values = {**reset, '--mdh-line-underline':'', '--mdh-line-strike':''} + if value.lower() == 'revert': + values.update({'--mdh-line-'+field:'var(--mdh-default-'+field+')' for field in ('underline','strike')}) + elif declaration.lower_name=='text-decoration' and any(t.type=='function' for t in declaration.value): values={'--mdh-decoration-mode':'raw','--mdh-decoration-shorthand':value} elif lines and not ('none' in lines and len(lines)>1): - values={'--mdh-decoration-mode':'initial','--mdh-decoration-raw':'initial','--mdh-line-underline':'underline' if 'underline' in lines else '', + values={**reset, '--mdh-line-underline':'underline' if 'underline' in lines else '', '--mdh-line-strike':'line-through' if 'line-through' in lines else ''} - if 'overline' in lines:values['--mdh-decoration-raw']=' '.join(x for x in ('underline','line-through','overline') if x in lines) + if 'overline' in lines: + values.update({'--mdh-decoration-mode':'raw-line', '--mdh-decoration-raw':' '.join(x for x in ('underline','line-through','overline') if x in lines)}) elif declaration.lower_name=='text-decoration-line' and any(t.type=='function' for t in declaration.value): - values={'--mdh-decoration-mode':'initial','--mdh-decoration-raw':value} + values={'--mdh-decoration-mode':'raw-line','--mdh-decoration-raw':value} + elif declaration.lower_name=='text-decoration': + values={**reset, '--mdh-line-underline':'', '--mdh-line-strike':''} else:continue + if values.get('--mdh-decoration-mode') in ('raw','raw-line'): + dynamic = True + values.update({'--mdh-override-underline':'initial', '--mdh-override-strike':'initial'}) output.extend(css.parse_declaration_list(''.join(f'{prop}:{val}{suffix};' for prop,val in values.items()))) return output - return css.serialize(visit(css.parse_stylesheet(source))) + result = css.serialize(visit(css.parse_stylesheet(source))) + return (DYNAMIC_MARKER+'\n' if dynamic else '') + result diff --git a/mdhelper/resources/reader_decorations.js b/mdhelper/resources/reader_decorations.js new file mode 100644 index 0000000..70430ca --- /dev/null +++ b/mdhelper/resources/reader_decorations.js @@ -0,0 +1,54 @@ +// CSS cannot extract an individual line from a var()-supplied shorthand. +// Ask the browser's CSS parser, then apply only the explicitly toggled lines. +// This file is included only for documents that need dynamic decorations. +(() => { + const reader = document.querySelector('[data-mdh-leaf-decoration]'); + if (!reader) return; + const parser = document.createElement('span').style; + const applied = new WeakMap(); + let pending = false; + const refresh = () => { + pending = false; + const changes = []; + // Read first, write second to avoid a layout flush for each text span. + for (const leaf of reader.querySelectorAll('[data-mdh-text]')) { + const style = getComputedStyle(leaf); + const mode = style.getPropertyValue('--mdh-decoration-mode').trim(); + const masks = ['underline', 'strike'].map(field => style.getPropertyValue('--mdh-override-' + field).trim()); + let line = ''; + if ((mode === 'raw' || mode === 'raw-line') && masks.some(value => value === 'true' || value === 'false')) { + parser.cssText = ''; + parser.setProperty(mode === 'raw' ? 'text-decoration' : 'text-decoration-line', + style.getPropertyValue(mode === 'raw' ? '--mdh-decoration-shorthand' : '--mdh-decoration-raw').trim()); + const lines = new Set(parser.textDecorationLine.split(/\s+/).filter(value => value && value !== 'none')); + ['underline', 'line-through'].forEach((token, index) => { + if (masks[index] === 'true') lines.add(token); + if (masks[index] === 'false') lines.delete(token); + }); + line = ['underline', 'overline', 'line-through', 'blink'].filter(token => lines.has(token)).join(' ') || 'none'; + } + if ((applied.get(leaf) || '') !== line) changes.push([leaf, line]); + } + for (const [leaf, line] of changes) { + if (line) leaf.style.setProperty('text-decoration-line', line, 'important'); + else leaf.style.removeProperty('text-decoration-line'); + applied.set(leaf, line); + } + }; + const schedule = () => { + // Offscreen previews and PDF pages may not receive animation frames. + // Coalesce DOM changes in the same turn without waiting for a visible view. + if (!pending) { pending = true; queueMicrotask(refresh); } + }; + // Run before the initial paint, and synchronously before HTML/PDF printing. + refresh(); + window.mdhelperRefreshDecorations = refresh; + window.addEventListener('beforeprint', refresh); + window.addEventListener('resize', schedule); + for (const event of ['pointerover', 'pointerout', 'pointerdown', 'pointerup', 'focusin', 'focusout']) { + reader.addEventListener(event, schedule, {passive: true}); + } + new MutationObserver(records => { + if (records.some(record => record.type !== 'attributes' || !record.target.hasAttribute('data-mdh-text'))) schedule(); + }).observe(document.documentElement, {subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['style', 'class']}); +})(); diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py index 9803ac5..d3cfb0b 100644 --- a/mdhelper/style_sync.py +++ b/mdhelper/style_sync.py @@ -174,6 +174,7 @@ def _declaration(name, value, important=False): def _expand(declaration): """Expand margins while keeping individual tokens (including calc/var).""" if declaration.type == "declaration" and declaration.lower_name == "font": + if _invalid_core_value('font', declaration.value): return [declaration] tokens = [t for t in declaration.value if t.type not in ("whitespace", "comment")] size_index = next((i for i, t in enumerate(tokens) if t.type == "dimension" and t.lower_unit in ("pt", "px")), None) if size_index is None: @@ -274,11 +275,22 @@ def _invalid_core_value(prop, tokens): prefix_names = {'normal','italic','oblique','small-caps','bold','bolder','lighter', 'ultra-condensed','extra-condensed','condensed','semi-condensed', 'semi-expanded','expanded','extra-expanded','ultra-expanded'} - for token in tokens[:size_index]: - if token.type=='ident' and token.lower_value in prefix_names: continue - if token.type=='number' and 1 <= token.value <= 1000: continue - if token.type=='dimension' and token.lower_unit in ('deg','grad','rad','turn'): continue - return True + groups, normal = set(), 0 + for index, token in enumerate(tokens[:size_index]): + if token.type == 'ident' and token.lower_value == 'normal': + normal += 1; continue + if token.type == 'ident' and token.lower_value in prefix_names: + name = token.lower_value + group = 'style' if name in ('italic','oblique') else 'variant' if name == 'small-caps' else 'weight' if name in ('bold','bolder','lighter') else 'stretch' + elif token.type == 'number' and 1 <= token.value <= 1000: + group = 'weight' + elif token.type == 'dimension' and token.lower_unit in ('deg','grad','rad','turn'): + if not index or getattr(tokens[index-1], 'lower_value', '') != 'oblique': return True + continue + else: return True + if group in groups: return True + groups.add(group) + if len(groups) + normal > 4: return True end = size_index + 1 if end < len(tokens) and tokens[end].type=='literal' and tokens[end].value=='/': end += 2 @@ -297,14 +309,21 @@ def _invalid_core_value(prop, tokens): selected = [name for name in names if name in lines] if 'none' in selected and len(selected)>1 or len(selected)!=len(set(selected)): return True if prop == 'text-decoration-line': return any(t.type!='ident' or t.lower_value not in lines for t in tokens) + groups = set() for token in tokens: - if token.type=='ident' and token.lower_value in lines | {'solid','double','dotted','dashed','wavy','auto','from-font'}: continue - if token.type=='function': - if _invalid_core_value('color', [token]): return True - continue # Includes variable colors/thickness. - if parse_color(token) is not None: continue - if token.type in ('dimension','percentage','number') and not _invalid_core_value('font-size',[token]): continue - return True + if token.type=='ident' and token.lower_value in lines: continue + if token.type=='ident' and token.lower_value in {'solid','double','dotted','dashed','wavy'}: + group = 'style' + elif token.type=='ident' and token.lower_value in {'auto','from-font'}: + group = 'thickness' + elif token.type=='function': + group = 'thickness' if token.lower_name in ('calc','min','max','clamp') else 'color' + if _invalid_core_value('font-size' if group == 'thickness' else 'color', [token]): return True + elif parse_color(token) is not None: group = 'color' + elif token.type in ('dimension','percentage','number') and not _invalid_core_value('font-size',[token]): group = 'thickness' + else: return True + if group in groups: return True + groups.add(group) if len(tokens) != 1: return False token = tokens[0] if token.type == 'string' and prop != 'font-family' and not prop.startswith('--'): return True @@ -455,6 +474,12 @@ class _CoreRuleReader: return self.rule def decoration(self, value): + if value.lower() in ('initial', 'unset'): + self.rule.update(underline=False, strike=False) + return + if value.lower() == 'revert': + self.rule.update(underline=self.target == 'link', strike=self.target == 'strike') + return if re.sub(r'\s+', '', value) == re.sub(r'\s+', '', DECORATION_EXPRESSION): for key in ('underline', 'strike'): self.choice('--mdhelper-' + key, key, {'true': True, 'false': False}) diff --git a/tests/test_css_revision_056.py b/tests/test_css_revision_056.py new file mode 100644 index 0000000..bf45aa2 --- /dev/null +++ b/tests/test_css_revision_056.py @@ -0,0 +1,110 @@ +"""CSS grammar, resets and independent controls over variable decorations.""" +import pytest +from mdhelper.style_sync import normalize_payload, patch_core, analyze_css +from mdhelper.style_dialog import DocumentStyleEditorDialog +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 + +LEAF_LINES = "[...document.querySelectorAll('[data-mdh-text]')].map(e=>getComputedStyle(e).textDecorationLine)" + + +@pytest.mark.parametrize('invalid', ['italic italic 30pt Arial', 'bold 700 30pt Arial', + 'italic oblique 30pt Arial', 'normal normal normal normal normal 30pt Arial']) +def test_invalid_font_shorthand_does_not_replace_valid_core_values(qt_application, tmp_path, invalid): + payload = normalize_payload({'css': 'p{font-size:12pt;font-style:normal;font:'+invalid+'}'}) + assert payload['rules']['paragraph']['font_size'] == 12 + assert payload['rules']['paragraph']['italic'] is False + assert any('已忽略无效' in note for note in analyze_css(payload['css']).notes) + assert browser(qt_application, tmp_path, payload, 'Text', + "[getComputedStyle(document.querySelector('p')).fontSize,getComputedStyle(document.querySelector('p')).fontStyle]") == ['16px', 'normal'] + dialog = DocumentStyleEditorDialog(payload) + try: + assert dialog.font_size_spin.value() == 12 + assert normalize_payload(dialog.style_payload())['rules']['paragraph']['font_size'] == 12 + finally: dialog.close() + + +@pytest.mark.parametrize('engine', ['builtin','python-docx','pandoc']) +def test_invalid_font_fallback_is_kept_in_word(tmp_path, engine): + rules = normalize_payload({'css':'p{font-size:12pt;font-style:normal;font:italic italic 30pt Arial}'})['rules'] + doc,styles = parts(export_markdown_to_docx('Text',tmp_path/'invalid.docx',engine=engine,style_rules=rules)) + run = next(r for r in effective_document(doc,styles).iter(W+'r') if ''.join(r.itertext()) == 'Text') + assert run.find('w:rPr/w:sz',NS).get(W+'val') == '24' + assert run.find('w:rPr/w:i',NS).get(W+'val') == '0' + + +@pytest.mark.parametrize('invalid', ['underline red blue','underline solid wavy','underline 1px 2px', + 'underline red rgb(0,0,255)','underline auto from-font']) +def test_invalid_decoration_components_keep_previous_line(qt_application, tmp_path, invalid): + payload = normalize_payload({'css':'em{text-decoration:none} strong{text-decoration:line-through;text-decoration:'+invalid+'}'}) + assert browser(qt_application,tmp_path,payload,'**Text**',LEAF_LINES) == ['line-through'] + + +@pytest.mark.parametrize('reset,line', [('initial','none'),('unset','none'),('revert','underline'),('wavy red','none')]) +def test_decoration_reset_clears_previous_line(qt_application,tmp_path,reset,line): + payload=normalize_payload({'css':'em{text-decoration:none} a{text-decoration:line-through;text-decoration:'+reset+'}'}) + assert browser(qt_application,tmp_path,payload,'[Link](#link)',LEAF_LINES) == [line] + assert normalize_payload(payload) == payload + + +def test_decoration_inherit_uses_parent_lines(qt_application,tmp_path): + payload=normalize_payload({'css':'em{text-decoration:none} strong{text-decoration:line-through} a{text-decoration:underline;text-decoration:inherit}'}) + assert browser(qt_application,tmp_path,payload,'**[Link](#link)**',LEAF_LINES) == ['line-through'] + + +@pytest.mark.parametrize('declaration', ['text-decoration:var(--line)', 'text-decoration-line:var(--line)']) +@pytest.mark.parametrize('field,expected', [('underline','line-through'),('strike','underline')]) +def test_graphical_toggle_preserves_other_variable_line(qt_application,tmp_path,declaration,field,expected): + css='a{--line:underline line-through;'+declaration+'}' + css=patch_core(css,'emphasis',{}, {field:False}) + payload=normalize_payload({'css':css}) + assert payload['rules']['emphasis'][field] is False + assert normalize_payload(payload) == payload + assert browser(qt_application,tmp_path,payload,'[Outer *Inner*](#link)',LEAF_LINES) == ['underline line-through',expected] + + +def test_variable_masks_preserve_overline_style_color_and_dynamic_changes(qt_application,tmp_path): + css='a{--line:underline overline line-through wavy red;text-decoration:var(--line)}' + css=patch_core(css,'emphasis',{}, {'underline':False}) + payload=normalize_payload({'css':css}) + result=browser(qt_application,tmp_path,payload,'[Outer *Inner*](#link)',"""(()=>{ + const a=document.querySelector('a'), leaf=document.querySelector('em [data-mdh-text]'); + const snapshot=()=>{const s=getComputedStyle(leaf);return [s.textDecorationLine,s.textDecorationStyle,s.textDecorationColor]}; + const before=snapshot();a.style.setProperty('--line','underline line-through dotted blue'); + window.dispatchEvent(new Event('beforeprint'));return [before,snapshot()]; + })()""") + assert result == [['overline line-through','wavy','rgb(255, 0, 0)'],['line-through','dotted','rgb(0, 0, 255)']] + + +def test_css_variable_changes_refresh_without_reloading_page(qt_application,tmp_path): + import time + from PySide6.QtWebEngineCore import QWebEnginePage + from mdhelper.markdown_renderer import MarkdownRenderer + from mdhelper.style_sync import render_css + css=patch_core('a{--line:underline line-through;text-decoration:var(--line)}','emphasis',{}, {'underline':False}) + payload=normalize_payload({'css':css}) + page=QWebEnginePage(); page.setVisible(True); loaded=[] + try: + page.loadFinished.connect(loaded.append) + page.setHtml(MarkdownRenderer(tmp_path).render_source('[Outer *Inner*](#link)',tmp_path/'test.md', + document_style_css=render_css(payload['css'],payload['rules']))) + deadline=time.monotonic()+15 + while not loaded and time.monotonic()