"""Draw semantic decorations on text, where an inner style can turn them off. CSS decorations on an ancestor cannot be cancelled by a descendant. Inline text spans keep normal wrapping while inherited custom properties carry each 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): class TextLeaves(HTMLParser): def __init__(self): super().__init__(convert_charrefs=False) self.output, self.blocked = [], [] self.depth = 0 def handle_starttag(self, tag, attrs): self.output.append(self.get_starttag_text()) if tag in ('area','base','br','col','embed','hr','img','input','link','meta','param','source','track','wbr'): return self.depth += 1 classes = dict(attrs).get('class','') or '' if tag in ('script','style','textarea','svg','math','pre') or 'data-mdh-text' in dict(attrs) or set(classes.split()) & {'mermaid','math-inline','math-block','math-display'}: self.blocked.append(self.depth) def handle_startendtag(self, tag, attrs): self.output.append(self.get_starttag_text()) def handle_endtag(self, tag): self.output.append(f'') if self.blocked and self.blocked[-1] == self.depth: self.blocked.pop() self.depth = max(0,self.depth-1) def handle_data(self, text): self.output.append(text if self.blocked or not text.strip() else ''+text+'') def handle_entityref(self, name): self.handle_data('&'+name+';') def handle_charref(self, name): self.handle_data('&#'+name+';') def handle_comment(self, data): self.output.append('') def handle_decl(self, data): self.output.append('') parser=TextLeaves();parser.feed(body);parser.close() return ''.join(parser.output) def decoration_css(rules, inherited, selectors, source): from .style_catalog import CHARACTER_DEFAULTS, CATALOG if not any(CATALOG.get(key) and CATALOG[key].kind == 'character' and any(rule.get(field) is False for field in ('underline','strike')) for key,rule in {key: {**inherited.get(key, {}), **rules.get(key, {})} for key in CATALOG}.items()): 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. if key == 'code': selector='.reader code:not(:where(pre code))' own={**inherited.get(key,{}), **rules.get(key,{})} defaults=CHARACTER_DEFAULTS.get(key,{}) rule={**defaults, **own} fields=[(field,token) for field,token in (('underline','underline'),('strike','line-through')) if field in rule] if not fields: continue # Reader-only companion rules; the original CSS remains editable. suppress.append(selector.replace('.reader',root)) for field,token in fields: # 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-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. 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); } }') return '\n'.join(parts) 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, _split dynamic = False def visit(nodes): nonlocal dynamic output=[] for declaration in nodes: if declaration.type=='error': continue if declaration.type=='qualified-rule' or (declaration.type=='at-rule' and declaration.content is not None and declaration.lower_at_keyword in ('media','supports','layer','container')): children=css.parse_blocks_contents(declaration.content,skip_whitespace=False,skip_comments=False) declaration.content=css.parse_component_value_list(css.serialize(visit(children))) output.append(declaration) if declaration.type == 'qualified-rule': children = css.parse_blocks_contents(declaration.content) if any(d.type == 'declaration' and d.lower_name in ('text-decoration','text-decoration-line') and not _invalid_core_value(d.lower_name, d.value) for d in children): # Suppress the ancestor at the same specificity and in the # same cascade layer as its authored rule. A global helper # cannot outrank an ID selector with !important. selectors = [css.serialize(part).strip() for part in _split(declaration.prelude)] selectors = [s + ':not(:where([data-mdh-text], pre, pre *))' for s in selectors if s and '::' not in s] if selectors: output.extend(css.parse_stylesheet(', '.join(selectors) + '{text-decoration-line:none!important;}')) if declaration.type!='declaration': continue value=css.serialize(declaration.value).strip() suffix=' !important' if declaration.important else '' 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-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'} 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={**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.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':'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 result = css.serialize(visit(css.parse_stylesheet(source))) return (DYNAMIC_MARKER+'\n' if dynamic else '') + result