"""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 */' 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: ; }'] 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-decoration-mode: initial; --mdh-decoration-raw: initial; --mdh-line-'+field+': '+(token if rule[field] else '')+'; }') 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. 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 def visit(nodes): 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!='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-decoration-mode:initial{suffix};--mdh-decoration-raw:initial{suffix};--mdh-line-{field}:{token}{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): 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 '', '--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) 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} else:continue 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)))