114 lines
6.8 KiB
Python
114 lines
6.8 KiB
Python
"""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'</{tag}>')
|
|
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 '<span data-mdh-text>'+text+'</span>')
|
|
|
|
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('<!--'+data+'-->')
|
|
def handle_decl(self, data): self.output.append('<!'+data+'>')
|
|
|
|
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 rules.items() if isinstance(rule,dict)):
|
|
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-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; }')
|
|
parts.append(root+' [data-mdh-text] { 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; }')
|
|
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
|
|
def visit(nodes):
|
|
for node in nodes:
|
|
if node.type=='at-rule' and node.content is not None and node.lower_at_keyword in ('media','supports','layer','container'):
|
|
children=css.parse_stylesheet(node.content);visit(children)
|
|
node.content=css.parse_component_value_list(css.serialize(children))
|
|
elif node.type=='qualified-rule':
|
|
declarations=css.parse_declaration_list(node.content,skip_whitespace=False,skip_comments=False)
|
|
output=[]
|
|
for declaration in declarations:
|
|
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-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
|
|
tokens=[t.lower_value for t in declaration.value if t.type=='ident']
|
|
lines=set(tokens)&{'none','underline','line-through','overline'}
|
|
if lines and not ('none' in lines and len(lines)>1):
|
|
values={'--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-raw':value}
|
|
else:continue
|
|
output.extend(css.parse_declaration_list(''.join(f'{prop}:{val}{suffix};' for prop,val in values.items())))
|
|
node.content=css.parse_component_value_list(css.serialize(output))
|
|
nodes=css.parse_stylesheet(source);visit(nodes)
|
|
return css.serialize(nodes)
|