Initial MDHelper implementation
This commit is contained in:
@@ -0,0 +1,381 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
from markdown_it import MarkdownIt
|
||||
from markdown_it.token import Token
|
||||
from pygments import highlight
|
||||
from pygments.formatters import HtmlFormatter
|
||||
from pygments.lexers import TextLexer, get_lexer_by_name
|
||||
from pygments.util import ClassNotFound
|
||||
|
||||
from .markdown_utils import slugify_heading
|
||||
from .media import media_kind, media_mime_type
|
||||
|
||||
|
||||
class MarkdownRenderer:
|
||||
def __init__(self, project_root: Path) -> None:
|
||||
self.project_root = project_root
|
||||
self.resources_dir = Path(__file__).resolve().parent / "resources"
|
||||
self.formatter = HtmlFormatter(nowrap=True)
|
||||
self.markdown = MarkdownIt(
|
||||
"commonmark",
|
||||
{
|
||||
"html": True,
|
||||
"typographer": False,
|
||||
"breaks": False,
|
||||
},
|
||||
).enable(["table", "strikethrough"])
|
||||
|
||||
self.markdown.renderer.rules["fence"] = self._render_fence
|
||||
self.markdown.renderer.rules["code_block"] = self._render_code_block
|
||||
self.markdown.renderer.rules["image"] = self._render_image
|
||||
self.markdown.renderer.rules["link_open"] = self._render_link_open
|
||||
self.markdown.core.ruler.push("mdhelper_heading_ids", self._add_heading_ids)
|
||||
self.markdown.core.ruler.push("mdhelper_admonitions", self._convert_admonitions)
|
||||
self.markdown.core.ruler.push("mdhelper_task_lists", self._convert_task_lists)
|
||||
|
||||
def render_file(self, markdown_path: Path, theme: str = "light", font_scale: float = 1.0) -> str:
|
||||
source = markdown_path.read_text(encoding="utf-8")
|
||||
body = self.markdown.render(source, {"path": str(markdown_path)})
|
||||
return self._wrap_html(
|
||||
body=body,
|
||||
title=markdown_path.name,
|
||||
theme=theme,
|
||||
font_scale=font_scale,
|
||||
)
|
||||
|
||||
def wrap_body_for_display(self, body: str, title: str, theme: str = "light", font_scale: float = 1.0) -> str:
|
||||
return self._wrap_html(body=body, title=title, theme=theme, font_scale=font_scale)
|
||||
|
||||
def _render_fence(
|
||||
self,
|
||||
tokens: list[Token],
|
||||
idx: int,
|
||||
options: dict[str, Any],
|
||||
env: dict[str, Any],
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
language = token.info.strip().split(maxsplit=1)[0] if token.info else ""
|
||||
language_class = f" language-{html.escape(language)}" if language else ""
|
||||
code = self._highlight_code(token.content, language)
|
||||
label = html.escape(language or "text")
|
||||
return (
|
||||
f'<div class="code-block">'
|
||||
f'<div class="code-title">{label}</div>'
|
||||
f'<pre class="highlight{language_class}"><code>{code}</code></pre>'
|
||||
f"</div>\n"
|
||||
)
|
||||
|
||||
def _render_code_block(
|
||||
self,
|
||||
tokens: list[Token],
|
||||
idx: int,
|
||||
options: dict[str, Any],
|
||||
env: dict[str, Any],
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
return (
|
||||
'<div class="code-block">'
|
||||
'<pre class="highlight language-text"><code>'
|
||||
f"{html.escape(token.content)}"
|
||||
"</code></pre>"
|
||||
"</div>\n"
|
||||
)
|
||||
|
||||
def _render_image(
|
||||
self,
|
||||
tokens: list[Token],
|
||||
idx: int,
|
||||
options: dict[str, Any],
|
||||
env: dict[str, Any],
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
src = token.attrGet("src") or ""
|
||||
title = token.attrGet("title") or ""
|
||||
alt = token.content or title or Path(src).name
|
||||
kind = media_kind(src)
|
||||
resolved_src = self._resolve_local_media_src(src, env)
|
||||
|
||||
escaped_src = html.escape(resolved_src, quote=True)
|
||||
escaped_alt = html.escape(alt, quote=True)
|
||||
mime_type = media_mime_type(src)
|
||||
source_type = f' type="{html.escape(mime_type, quote=True)}"' if mime_type else ""
|
||||
caption = f"<figcaption>{html.escape(alt)}</figcaption>" if alt else ""
|
||||
|
||||
if kind == "audio":
|
||||
return (
|
||||
f'<figure class="media-block media-audio" data-media-src="{escaped_src}">'
|
||||
f'<audio controls preload="metadata">'
|
||||
f'<source src="{escaped_src}"{source_type}>'
|
||||
"当前环境无法播放此音频。"
|
||||
"</audio>"
|
||||
f"{caption}</figure>"
|
||||
)
|
||||
if kind == "video":
|
||||
return (
|
||||
f'<figure class="media-block media-video" data-media-src="{escaped_src}">'
|
||||
f'<video controls preload="metadata" playsinline>'
|
||||
f'<source src="{escaped_src}"{source_type}>'
|
||||
"当前环境无法播放此视频。"
|
||||
"</video>"
|
||||
f"{caption}</figure>"
|
||||
)
|
||||
if kind == "gif":
|
||||
return (
|
||||
'<figure class="media-block media-image media-gif">'
|
||||
f'<img src="{escaped_src}" alt="{escaped_alt}" loading="lazy">'
|
||||
f"{caption}</figure>"
|
||||
)
|
||||
return f'<img src="{escaped_src}" alt="{escaped_alt}" loading="lazy">'
|
||||
|
||||
def _render_link_open(
|
||||
self,
|
||||
tokens: list[Token],
|
||||
idx: int,
|
||||
options: dict[str, Any],
|
||||
env: dict[str, Any],
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
href = token.attrGet("href") or ""
|
||||
resolved_href = self._resolve_local_href(href, env)
|
||||
if resolved_href != href:
|
||||
token.attrSet("href", resolved_href)
|
||||
return self.markdown.renderer.renderToken(tokens, idx, options, env)
|
||||
|
||||
def _resolve_local_media_src(self, src: str, env: dict[str, Any]) -> str:
|
||||
parsed = urlsplit(src)
|
||||
if parsed.scheme or parsed.path.startswith("#"):
|
||||
return src
|
||||
|
||||
markdown_path_value = env.get("path")
|
||||
if not markdown_path_value:
|
||||
return src
|
||||
|
||||
local_path = (Path(str(markdown_path_value)).parent / unquote(parsed.path)).resolve()
|
||||
if not local_path.exists():
|
||||
return src
|
||||
|
||||
uri = local_path.as_uri()
|
||||
if parsed.fragment:
|
||||
uri = f"{uri}#{parsed.fragment}"
|
||||
return uri
|
||||
|
||||
def _resolve_local_href(self, href: str, env: dict[str, Any]) -> str:
|
||||
parsed = urlsplit(href)
|
||||
if parsed.scheme or parsed.path.startswith("#"):
|
||||
return href
|
||||
|
||||
markdown_path_value = env.get("path")
|
||||
if not markdown_path_value:
|
||||
return href
|
||||
|
||||
local_path = (Path(str(markdown_path_value)).parent / unquote(parsed.path)).resolve()
|
||||
if not local_path.exists():
|
||||
return href
|
||||
|
||||
uri = local_path.as_uri()
|
||||
if parsed.fragment:
|
||||
uri = f"{uri}#{parsed.fragment}"
|
||||
return uri
|
||||
|
||||
def _highlight_code(self, code: str, language: str) -> str:
|
||||
normalized = language.lower()
|
||||
if normalized in {"pseudocode", "pseudo"}:
|
||||
return self._highlight_pseudocode(code)
|
||||
|
||||
try:
|
||||
lexer = get_lexer_by_name(normalized) if normalized else TextLexer()
|
||||
except ClassNotFound:
|
||||
lexer = TextLexer()
|
||||
return highlight(code, lexer, self.formatter)
|
||||
|
||||
def _highlight_pseudocode(self, code: str) -> str:
|
||||
escaped = html.escape(code)
|
||||
keywords = (
|
||||
"BEGIN",
|
||||
"END",
|
||||
"SET",
|
||||
"FOR",
|
||||
"TO",
|
||||
"DO",
|
||||
"IF",
|
||||
"THEN",
|
||||
"ELSE",
|
||||
"RETURN",
|
||||
"WHILE",
|
||||
"REPEAT",
|
||||
"UNTIL",
|
||||
)
|
||||
|
||||
def replace_keyword(match: re.Match[str]) -> str:
|
||||
return f'<span class="pseudo-keyword">{match.group(0)}</span>'
|
||||
|
||||
pattern = r"\b(" + "|".join(keywords) + r")\b"
|
||||
return re.sub(pattern, replace_keyword, escaped)
|
||||
|
||||
def _add_heading_ids(self, state: Any) -> None:
|
||||
seen: dict[str, int] = {}
|
||||
tokens = state.tokens
|
||||
|
||||
for index, token in enumerate(tokens):
|
||||
if token.type != "heading_open" or index + 1 >= len(tokens):
|
||||
continue
|
||||
|
||||
inline = tokens[index + 1]
|
||||
if inline.type != "inline":
|
||||
continue
|
||||
|
||||
slug = slugify_heading(inline.content)
|
||||
if not slug:
|
||||
continue
|
||||
|
||||
count = seen.get(slug, 0)
|
||||
seen[slug] = count + 1
|
||||
if count:
|
||||
slug = f"{slug}-{count + 1}"
|
||||
|
||||
token.attrSet("id", slug)
|
||||
|
||||
def _convert_admonitions(self, state: Any) -> None:
|
||||
labels = {
|
||||
"NOTE": "注意",
|
||||
"TIP": "提示",
|
||||
"IMPORTANT": "重要",
|
||||
"WARNING": "警告",
|
||||
"CAUTION": "小心",
|
||||
}
|
||||
tokens = state.tokens
|
||||
|
||||
for index, token in enumerate(tokens):
|
||||
if token.type != "blockquote_open":
|
||||
continue
|
||||
|
||||
inline_index = self._first_inline_in_blockquote(tokens, index)
|
||||
if inline_index is None:
|
||||
continue
|
||||
|
||||
inline = tokens[inline_index]
|
||||
marker = re.match(
|
||||
r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*([^\n]*)(?:\n(.*))?$",
|
||||
inline.content,
|
||||
re.DOTALL,
|
||||
)
|
||||
if not marker:
|
||||
continue
|
||||
|
||||
kind = marker.group(1)
|
||||
title = marker.group(2).strip() or labels[kind]
|
||||
rest = (marker.group(3) or "").lstrip()
|
||||
close_index = self._matching_close_index(tokens, index, "blockquote_close")
|
||||
if close_index is None:
|
||||
continue
|
||||
|
||||
token.tag = "aside"
|
||||
token.attrJoin("class", f"admonition admonition-{kind.lower()}")
|
||||
tokens[close_index].tag = "aside"
|
||||
|
||||
title_node = Token("html_inline", "", 0)
|
||||
title_node.content = f'<span class="admonition-title">{html.escape(title)}</span>'
|
||||
children = [title_node]
|
||||
if rest:
|
||||
break_node = Token("html_inline", "", 0)
|
||||
break_node.content = "<br>"
|
||||
text = Token("text", "", 0)
|
||||
text.content = rest
|
||||
children.extend([break_node, text])
|
||||
|
||||
inline.content = f"{title}\n{rest}" if rest else title
|
||||
inline.children = children
|
||||
|
||||
def _convert_task_lists(self, state: Any) -> None:
|
||||
tokens = state.tokens
|
||||
|
||||
for index, token in enumerate(tokens):
|
||||
if token.type != "inline" or not token.children:
|
||||
continue
|
||||
|
||||
first_child = token.children[0]
|
||||
if first_child.type != "text":
|
||||
continue
|
||||
|
||||
marker = re.match(r"^\[([ xX])\]\s+", first_child.content)
|
||||
if not marker:
|
||||
continue
|
||||
|
||||
list_item = self._nearest_open_token(tokens, index, "list_item_open")
|
||||
if list_item is None:
|
||||
continue
|
||||
|
||||
bullet_list = self._nearest_open_token(tokens, index, "bullet_list_open")
|
||||
if bullet_list is not None:
|
||||
bullet_list.attrJoin("class", "task-list")
|
||||
|
||||
checked = marker.group(1).lower() == "x"
|
||||
list_item.attrJoin("class", "task-list-item")
|
||||
checkbox = Token("html_inline", "", 0)
|
||||
checked_attr = " checked" if checked else ""
|
||||
checkbox.content = (
|
||||
'<input class="task-list-item-checkbox" type="checkbox"'
|
||||
f"{checked_attr} disabled> "
|
||||
)
|
||||
first_child.content = first_child.content[marker.end() :]
|
||||
token.children.insert(0, checkbox)
|
||||
|
||||
def _first_inline_in_blockquote(self, tokens: list[Token], start_index: int) -> int | None:
|
||||
start_level = tokens[start_index].level
|
||||
for index in range(start_index + 1, len(tokens)):
|
||||
token = tokens[index]
|
||||
if token.type == "blockquote_close" and token.level == start_level:
|
||||
return None
|
||||
if token.type == "inline":
|
||||
return index
|
||||
return None
|
||||
|
||||
def _matching_close_index(self, tokens: list[Token], start_index: int, close_type: str) -> int | None:
|
||||
start_level = tokens[start_index].level
|
||||
for index in range(start_index + 1, len(tokens)):
|
||||
token = tokens[index]
|
||||
if token.type == close_type and token.level == start_level:
|
||||
return index
|
||||
return None
|
||||
|
||||
def _nearest_open_token(self, tokens: list[Token], start_index: int, token_type: str) -> Token | None:
|
||||
inline_level = tokens[start_index].level
|
||||
for token in reversed(tokens[:start_index]):
|
||||
if token.type == token_type and token.level < inline_level:
|
||||
return token
|
||||
return None
|
||||
|
||||
def _wrap_html(self, body: str, title: str, theme: str, font_scale: float) -> str:
|
||||
css = (self.resources_dir / "reader.css").read_text(encoding="utf-8")
|
||||
js = (self.resources_dir / "reader.js").read_text(encoding="utf-8")
|
||||
pygments_css = HtmlFormatter().get_style_defs(".highlight")
|
||||
escaped_title = html.escape(title)
|
||||
escaped_theme = html.escape(theme, quote=True)
|
||||
font_percent = int(max(0.8, min(font_scale, 1.6)) * 100)
|
||||
|
||||
return f"""<!doctype html>
|
||||
<html lang="zh-CN" data-theme="{escaped_theme}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{escaped_title}</title>
|
||||
<style>
|
||||
:root {{ --reader-font-scale: {font_percent}%; }}
|
||||
{pygments_css}
|
||||
{css}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="reader">
|
||||
{body}
|
||||
</main>
|
||||
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
|
||||
<script>{js}</script>
|
||||
</body>
|
||||
</html>"""
|
||||
Reference in New Issue
Block a user