diff options
Diffstat (limited to '')
| -rw-r--r-- | packages/markdown-figure/lektor_markdown_figure.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/packages/markdown-figure/lektor_markdown_figure.py b/packages/markdown-figure/lektor_markdown_figure.py index 173535c..648110f 100644 --- a/packages/markdown-figure/lektor_markdown_figure.py +++ b/packages/markdown-figure/lektor_markdown_figure.py @@ -17,9 +17,13 @@ from __future__ import annotations import html import re from typing import Any +from urllib.parse import urlparse import mistune +from lektor.context import get_ctx +from lektor.db import Image from lektor.pluginsystem import Plugin +from lektor.utils import join_path FIGURE_PATTERN = re.compile( r" {0,3}:::figure(?:[ \t]+(?P<classes>[^\n]*?))?[ \t]*\n" @@ -66,6 +70,40 @@ def _split_figure(match: re.Match[str]) -> tuple[str, str, str]: return classes, image_source, caption_source +class FullsizeImageMixin: + """Remember the original attachment URL on resized Markdown images. + + Lektor’s responsive-image plugin replaces ``src`` with a thumbnail; the + image viewer needs the unmodified attachment to show the full resolution. + This mixin must run outside the other image renderer mixins so existing + Markdown image attributes still work. + """ + + def image(self, src: str, *args: Any, **kwargs: Any) -> str: + markup = super().image(src, *args, **kwargs) # type: ignore[misc] + parsed = urlparse(src) + if parsed.scheme or parsed.netloc or not parsed.path: + return markup + + renderer = getattr(self, "lektor", self) + record = getattr(renderer, "record", None) + if record is None or record.path is None: + return markup + + path = parsed.path + if not path.startswith("/"): + path = join_path(record.path, path) + attachment = record.pad.get(path) + if not isinstance(attachment, Image): + return markup + + original_url = get_ctx().url_to(attachment) + original_attr = html.escape(original_url, quote=True) + return markup.replace( + "<img ", f'<img loading="lazy" data-fullsize="{original_attr}" ', 1 + ) + + # --------------------------------------------------------------------------- # Mistune 0.8 support (used by Lektor 3.3.x) # --------------------------------------------------------------------------- @@ -197,6 +235,10 @@ class MarkdownFigurePlugin(Plugin): ) def on_markdown_config(self, config: Any, **extra: Any) -> None: + # Run outside the responsive-image and image-attrs renderer mixins. + if FullsizeImageMixin not in config.renderer_mixins: + config.renderer_mixins.insert(0, FullsizeImageMixin) + # Newer Lektor controller using Mistune 2. if hasattr(config, "parser_options"): print("Using mistune 2") |
