lib.itmens/journal/models/renderers.py

53 lines
1 KiB
Python
Raw Normal View History

import re
2023-01-30 17:15:24 -05:00
from typing import cast
import mistune
2023-01-31 10:24:57 -05:00
from django.utils.html import escape
_mistune_plugins = [
"url",
"strikethrough",
"footnotes",
"table",
"mark",
"superscript",
"subscript",
"math",
"spoiler",
2023-01-30 22:11:47 -05:00
"ruby",
]
_markdown = mistune.create_markdown(plugins=_mistune_plugins)
2023-07-20 21:59:49 -04:00
def convert_leading_space_in_md(body: str) -> str:
2023-06-03 13:47:45 -04:00
body = re.sub(r"^\s+$", "", body, flags=re.MULTILINE)
body = re.sub(
r"^(\u2003*)( +)",
lambda s: "\u2003" * ((len(s[2]) + 1) // 2 + len(s[1])),
body,
flags=re.MULTILINE,
)
return body
2023-07-20 21:59:49 -04:00
def render_md(s: str) -> str:
2023-01-30 17:15:24 -05:00
return cast(str, _markdown(s))
2023-07-20 21:59:49 -04:00
def _spolier(s: str) -> str:
2023-01-31 10:24:57 -05:00
l = s.split(">!", 1)
if len(l) == 1:
return escape(s)
r = l[1].split("!<", 1)
return (
escape(l[0])
+ '<span class="spoiler" _="on click toggle .revealed on me">'
2023-01-31 10:24:57 -05:00
+ escape(r[0])
+ "</span>"
+ (_spolier(r[1]) if len(r) == 2 else "")
)
2023-07-20 21:59:49 -04:00
def render_text(s: str) -> str:
2023-01-31 10:24:57 -05:00
return _spolier(s)