diff options
| author | Dennis Fink | 2026-11-11 19:57:38 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-11-11 19:57:38 +0100 |
| commit | e6215f84bf2cab0bbd8bb0a42ddae0ee6de3cfd6 (patch) | |
| tree | 83910d7fee66d210464318bc7ad568c713e25e2d | |
| parent | 8963ed31ce537a736ddba99baf68b31858b319b8 (diff) | |
| download | dennisfink.me-main.tar.gz dennisfink.me-main.zip | |
This adds the responsive-image plugin directly to the project, including
its source code, documentation, and tests, allowing it to be maintained
locally.
It also configures responsive image sizes, updates gallery images to use
srcset, and preserves original image URLs for full-resolution viewing.
Markdown images gain lazy loading while retaining compatibility with the
existing image viewer.
27 files changed, 1008 insertions, 6 deletions
diff --git a/assets/static/css/style.css b/assets/static/css/style.css index 22df240..f6126f0 100644 --- a/assets/static/css/style.css +++ b/assets/static/css/style.css @@ -1197,6 +1197,10 @@ article::after, .gallery { margin-block: 1rem; + a[data-original-image] { + display: block; + } + [data-direction] { display: flex; gap: var(--gap); diff --git a/configs/responsive-images.ini b/configs/responsive-images.ini new file mode 100644 index 0000000..4af4e23 --- /dev/null +++ b/configs/responsive-images.ini @@ -0,0 +1,5 @@ +[default] +widths = 360 480 720 1080 1600 1920 2400 +quality = 92 +default_width = 2400 +sizes = auto, 100vw 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") diff --git a/packages/responsive-image/.gitignore b/packages/responsive-image/.gitignore new file mode 100644 index 0000000..14990d7 --- /dev/null +++ b/packages/responsive-image/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +/.pdm-python +/dist/ +/.coverage +/.coverage.* diff --git a/packages/responsive-image/.pre-commit-config.yaml b/packages/responsive-image/.pre-commit-config.yaml new file mode 100644 index 0000000..4e2feaf --- /dev/null +++ b/packages/responsive-image/.pre-commit-config.yaml @@ -0,0 +1,38 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: check-yaml + - id: check-toml + - id: check-symlinks + - id: check-added-large-files + - id: check-vcs-permalinks + - id: debug-statements + - id: trailing-whitespace + exclude_types: ["image", "svg"] + - id: end-of-file-fixer + - id: mixed-line-ending + +- repo: https://github.com/pre-commit/pygrep-hooks + rev: 'v1.10.0' + hooks: + - id: python-check-blanket-noqa + - id: python-check-blanket-type-ignore + - id: python-use-type-annotations + +- repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.1.14 + hooks: + # Run the linter. + - id: ruff + args: [--fix] + # Run the formatter. + - id: ruff-format + +- repo: https://github.com/pdm-project/pdm + rev: '2.12.2' + hooks: + - id: pdm-lock-check diff --git a/packages/responsive-image/CHANGES.md b/packages/responsive-image/CHANGES.md new file mode 100644 index 0000000..ea8af2f --- /dev/null +++ b/packages/responsive-image/CHANGES.md @@ -0,0 +1,18 @@ +## Changelog + +### Release 1.0.0 (2024-01-24) + +There are no substantive code changes from release 1.0.0b1. + +- Test under python 3.12, drop testing under python 3.7. +- Use `pdm` for build and dev env management. +- Use `ruff` for style linting and formatting. + +### Release 1.0.0b1 (2023-04-20) + +We've dropped support for python < 3.7. +We now test under both Lektor 3.3.x and (now in pre-release) Lektor 3.4.x + +### Version 0.1a1 (2021-02-13) + +Split code into it's own git respository. diff --git a/packages/responsive-image/LICENSE b/packages/responsive-image/LICENSE new file mode 100644 index 0000000..5546e5d --- /dev/null +++ b/packages/responsive-image/LICENSE @@ -0,0 +1,20 @@ +Copyright © 2021 Geoffrey T. Dairiki + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/responsive-image/README.md b/packages/responsive-image/README.md new file mode 100644 index 0000000..8864df2 --- /dev/null +++ b/packages/responsive-image/README.md @@ -0,0 +1,86 @@ +# Lektor Responsive Images Plugin + +[](https://pypi.org/project/lektor-responsive-image/) +[](https://pypi.python.org/pypi/lektor-responsive-image/) +[](https://github.com/dairiki/lektor-responsive-image/blob/master/LICENSE) +[](https://github.com/dairiki/lektor-responsive-image/actions) +[](https://trackgit.com) + +This plugin hacks up Lektor’s Markdown renderer to support +multi-resolution responsive images in Markdown text. + +Local images will be resized to a variety of sizes, and `<img>` tags +will be rendered with `srcset` and (optionally) `sizes` attributes in +order to support the use of [responsive image +resolutions][mdn-responsive-images]. + +This plugin also registers a Jinja global function, `responsive_image`, +which can be used to render markup for multi-resolution images from +Jinja templates. + +[mdn-responsive-images]: <https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images> + "MDN: Responsive Images" + +## Configuration + +The plugin is configured through `configs/responsive-images.ini`. +Here is an annotated example: + +```ini +# Currently, only a section named "default" is used +[default] + +# Widths of images to generate. +# +# Images will be generated at these widths (but only up to the native +# width of the image.) +# +# (This is the default value.) +widths = 480 800 1200 2400 + +# Image quality for generating scaled images +# (This is the default value.) +# NOTE: the quality parameter will be ignored if running under lektor version +# before 3.1. +quality = 92 + +# Width of the image put into the `src` attribute of the `<img>` tag. +# (Though the orignal image is never up-scaled. If the original is narrower than +# this width, then the original image is used.) +# (This is the default value.) +default_width = 1200 + +# Value put into the `sizes` attribute of the `<img>` tag. +# The default is not to set a `sizes` attribute +sizes = (max-width: 576px) 95vw, (max-width: 992px) 65vw, 800px +``` + +## Usage + +In the common use case, you will want to adjust the CSS stylesheet for +your site so that images within Markdown text get either `display: +block` or `display: inline-block`, along with `max-width: 100%`, or +similar. + +## Jinja global function + +This plugin also registers a Jinja global function named `responsive_image`. +It expects a single argument, which should be an `Image` instance. +It returns an object which has an `.attr` attribute whose value is +a dict of attribute which could be set on an `<img>` tag to generate +markup for a multi-resolution image. E.g. + +```html+jinja +{% set image = this.attachments.get('figure.png') %} +{% set img_attrs = responsive_image(image).attrs %} +<figure class="figure"> + <img class="figure-img" {{ img_attrs|xmlattr }}> + <figcaption class="figure-caption text-center"> + {{- this.caption -}} + </figcaption> +</figure> +``` + +## Author + +Jeff Dairiki <dairiki@dairiki.org> diff --git a/packages/responsive-image/lektor_responsive_image.py b/packages/responsive-image/lektor_responsive_image.py new file mode 100644 index 0000000..d8cc2fd --- /dev/null +++ b/packages/responsive-image/lektor_responsive_image.py @@ -0,0 +1,182 @@ +import sys +from urllib.parse import urlparse + +import mistune +from lektor.context import get_ctx +from lektor.db import Image +from lektor.pluginsystem import get_plugin +from lektor.pluginsystem import Plugin +from lektor.utils import join_path +from markupsafe import escape +from werkzeug.utils import cached_property + +HAVE_MISTUNE0 = mistune.__version__.startswith("0.") + +try: + from lektor.markdown import controller_class +except ImportError: + # Lektor < 3.4 + from lektor.markdown import ImprovedRenderer + from lektor.markdown import MarkdownConfig +else: + # Lektor >= 3.4 + _mistune_module = sys.modules[controller_class.__module__] + ImprovedRenderer = _mistune_module.ImprovedRenderer + MarkdownConfig = _mistune_module.MarkdownConfig + + +def fmt_attrs(attrs): + """Format a dict to markup suitable for use as HTML tag attributes.""" + return " ".join( + f'{key}="{escape(val)}"' for key, val in attrs.items() if val is not None + ) + + +class ResponsiveImage: + """Helper class to compute attributes for multi-resolution responsive images.""" + + DEFAULT_CONFIG = { + "widths": [480, 800, 1200, 2400], + "quality": 92, + "default_width": 1200, + "sizes": None, + } + + def __init__(self, image, config=None, ctx=None): + if config is None: + config = self.DEFAULT_CONFIG.copy() + if ctx is None: + ctx = get_ctx() + self.config = config + self.image = image + self.ctx = ctx + + @property + def attrs(self): + attrs = self.default_image_attrs() + if self.srcset is not None: + attrs["srcset"] = self.srcset + if self.sizes is not None: + attrs["sizes"] = self.sizes + return attrs + + @cached_property + def srcset(self): + url_to = self.ctx.url_to + widths = list(self.iter_widths()) + if len(widths) > 1: + + def image_info(width): + image = self.resize_image(width) + return f"{url_to(image)} {width}w" + + return ", ".join(map(image_info, self.iter_widths())) + + @property + def sizes(self): + return self.config.get("sizes") + + def iter_widths(self): + image_width = self.image.width + widths = self.config.get("widths", []) + for w in widths: + if w < image_width: + yield w + else: + yield image_width + break + + def default_image_attrs(self): + default_width = self.config.get("default_width", 800) + default_image = self.resize_image(default_width) + return { + "src": self.ctx.url_to(default_image), + "width": default_image.width, + "height": default_image.height, + "loading": "lazy", + } + + def resize_image(self, width): + image = self.image + if width is None or width >= image.width: + return image + # We (should) never upscale. Upscale=True is passed here + # solely to avoid triggering a deprecation warning. + return self.image.thumbnail(width, quality=self.config["quality"], upscale=True) + + +def resolve_image(record, src): + """Resolve local image URL to Lektor Image record.""" + if record is None: + return None + url = urlparse(src) + if url.scheme or url.netloc: + return None + + path = url.path + if not path.startswith("/"): + assert record.path is not None # FIXME: better error reporting? + path = join_path(record.path, path) + source = record.pad.get(path) + if isinstance(source, Image): + return source + + +class ResponsiveImageMixin: + """Markdown renderer mixin to render local images at multiple resolutions.""" + + def image(self, src, *args): + # Under Lektor >= 3.4, the record is available at self.lektor.record. + # Prior to that, it's at self.record. + renderer_helper = getattr(self, "lektor", self) + record = renderer_helper.record + + image = resolve_image(record, src) + if image is not None and image.format in ("png", "gif", "jpeg"): + alt, title = reversed(args) if HAVE_MISTUNE0 else args + attrs = {"alt": alt, "title": title or None} + plugin = get_plugin("responsive-image", env=record.pad.env) + attrs.update(plugin.responsive_image(image).attrs) + return f"<img {fmt_attrs(attrs)}>" + else: + return super().image(src, *args) + + +class ResponsiveImagePlugin(Plugin): + name = "Responsive Image" + description = "Support for multi-resolution responsive images." + + def on_setup_env(self, **extra): + self.env.jinja_env.globals["responsive_image"] = self.responsive_image + + def on_markdown_config(self, config, **extra): + config.renderer_mixins.append(ResponsiveImageMixin) + + def responsive_image(self, image): + config = self.get_responsive_image_config() + return ResponsiveImage(image, config) + + def get_responsive_image_config(self): + inifile = self.get_config() + config = ResponsiveImage.DEFAULT_CONFIG.copy() + config.update(self._parse_ini(inifile)) + return config + + @staticmethod + def _parse_ini(inifile, section="default"): + data = inifile.section_as_dict(section) + config = {} + if "widths" in data: + try: + config["widths"] = list(map(int, data["widths"].split())) + except ValueError: + pass + for key in ("quality", "default_width"): + if key in data: + try: + config[key] = int(data[key]) + except ValueError: + pass + if "sizes" in data: + config["sizes"] = data["sizes"] + return config diff --git a/packages/responsive-image/pdm_build.py b/packages/responsive-image/pdm_build.py new file mode 100644 index 0000000..cc11e2d --- /dev/null +++ b/packages/responsive-image/pdm_build.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from pathlib import Path + +from pdm.backend.hooks import Context + +################################################################ +# +# Generate dynamic README +# + + +def pdm_build_initialize(context: Context) -> None: + """Generate README by concatenating README.md and CHANGES.md""" + metadata = context.config.metadata + if "readme" in metadata.get("dynamic", []): + metadata["dynamic"].remove("readme") + metadata["readme"] = { + "text": compute_readme(context.root), + "content-type": "text/markdown", + } + + +def compute_readme(root: Path) -> str: + readme = root / "README.md" + changes = root / "CHANGES.md" + return "\n".join( + file.read_text("utf-8").rstrip() + "\n" for file in (readme, changes) + ) diff --git a/packages/responsive-image/pyproject.toml b/packages/responsive-image/pyproject.toml new file mode 100644 index 0000000..c3f192c --- /dev/null +++ b/packages/responsive-image/pyproject.toml @@ -0,0 +1,107 @@ +[build-system] +requires = ["pdm-backend"] +build-backend = "pdm.backend" + +[project] +name = "lektor-responsive-image" +dynamic = ["version", "readme"] +description = "Lektor plugin to help with multi-resolution responsive images" +urls.Home = "https://github.com/dairiki/lektor-responsive-image" +keywords = [ + "Lektor plugin", + "responsive images", + "multi-resolution images", + "srcset", +] +license.file = "LICENSE" +authors = [ + {name = "Jeff Dairiki", email = "dairiki@dairiki.org"}, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Plugins", + "Environment :: Web Environment", + "Framework :: Lektor", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Text Processing :: Markup :: HTML", +] +requires-python = ">=3.8" + +[project.entry-points."lektor.plugins"] +responsive-image = "lektor_responsive_image:ResponsiveImagePlugin" + +[tool.pdm.build] +excludes = ["pdm_build.py"] +source-includes = ["CHANGES.md", "tests/", "tox.ini"] + +[tool.pdm.version] +source = "scm" + +[tool.pdm.dev-dependencies] +dev = [ + "lektor>=3.4.0a0", + "pytest>=7.4.4", + "ruff>=0.1.14", +] + +[tool.pdm.scripts] +tests = "pytest tests -ra" + +[tool.coverage.run] +parallel = true +source_pkgs = [ + "lektor_responsive_image", +] + +[tool.coverage.paths] +paths = [ + "lektor-responsive-image", + ".tox/py*/*/lektor-responsive-image", +] + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + '^\s*\.\.\.\s*$', + '^\s*raise\s+NotImplementedError\(\)\s*$', +] + +[tool.ruff] +extend-exclude = [".pdm-build"] +explicit-preview-rules = true +allowed-confusables = ["’", "–"] + +[tool.ruff.lint] +select = [ + "F", # pyflakes + "E", "W", # pycodestyle + "UP", # pyupgrade + "B", # flake8-bugbear + "Q", # flake8-quotes + "YTT", # flake8-2020 + "C4", # flake8-comprehensions + "T10", # flake8-debugger + "EM", # flake8-errmsg + "FA", # flake8-future-annotations + "T20", # flake8-print + "RSE", # flake8-raise + "I", # isort + "C90", # mccabe + "PGH", # pygrep-hooks + #"PL", # pylint +] + +[tool.ruff.lint.isort] +force-single-line = true +order-by-type = false +known-first-party = [ + "conftest", + "lektor_responsive_images", +] diff --git a/packages/responsive-image/setup.py b/packages/responsive-image/setup.py new file mode 100644 index 0000000..4f9de02 --- /dev/null +++ b/packages/responsive-image/setup.py @@ -0,0 +1,12 @@ +from setuptools import setup + +setup( + name="lektor-responsive-image", + version="0.1.0", + py_modules=["lektor_responsive_image"], + entry_points={ + "lektor.plugins": [ + "responsive-image = lektor_responsive_image:ResponsiveImagePlugin" + ] + }, +) diff --git a/packages/responsive-image/tests/conftest.py b/packages/responsive-image/tests/conftest.py new file mode 100644 index 0000000..f7a81df --- /dev/null +++ b/packages/responsive-image/tests/conftest.py @@ -0,0 +1,48 @@ +import os +from contextlib import ExitStack + +import pytest +from lektor.builder import Builder +from lektor.context import Context +from lektor.project import Project + + +@pytest.fixture +def lektor_env(): + site_path = os.path.join(os.path.dirname(__file__), "test-site") + return Project.from_path(site_path).make_env(load_plugins=False) + + +@pytest.fixture +def lektor_pad(lektor_env): + return lektor_env.new_pad() + + +@pytest.fixture +def lektor_builder(lektor_pad, tmp_path): + return Builder(lektor_pad, str(tmp_path)) + + +@pytest.fixture +def lektor_build_state(lektor_builder): + build_state = lektor_builder.new_build_state() + with ExitStack() as stack: + if hasattr(build_state, "__enter__"): + build_state = stack.enter_context(build_state) # lektor < 3.4 + yield build_state + + +@pytest.fixture +def lektor_source(lektor_pad): + return lektor_pad.root + + +@pytest.fixture +def lektor_artifact(lektor_build_state, lektor_source): + return lektor_build_state.new_artifact("test.html", source_obj=lektor_source) + + +@pytest.fixture +def lektor_context(lektor_artifact): + with Context(lektor_artifact) as ctx: + yield ctx diff --git a/packages/responsive-image/tests/test-site/Test Site.lektorproject b/packages/responsive-image/tests/test-site/Test Site.lektorproject new file mode 100644 index 0000000..ca7db53 --- /dev/null +++ b/packages/responsive-image/tests/test-site/Test Site.lektorproject @@ -0,0 +1,2 @@ +[project] +name = Test Site diff --git a/packages/responsive-image/tests/test-site/assets/static/style.css b/packages/responsive-image/tests/test-site/assets/static/style.css new file mode 100644 index 0000000..7ff6e0b --- /dev/null +++ b/packages/responsive-image/tests/test-site/assets/static/style.css @@ -0,0 +1,42 @@ +body { + font-family: 'Verdana', sans-serif; + margin: 50px 25px; +} + +a { + color: #2a99b6; +} + +a:hover { + color: #33bbdf; +} + +header, footer, div.page { + width: 760px; + margin: 0 auto; + background: #daeef3; + padding: 20px 30px; +} + +header h1 { + color: #169bbd; + margin: 0; + font-weight: normal; + font-size: 42px; +} + +header nav ul { + list-style: none; + margin: 0; + padding: 0; +} + +header nav ul li { + display: inline; + margin: 0 8px 0 0; + padding: 0; +} + +div.page { + background: #f1fbfe; +} diff --git a/packages/responsive-image/tests/test-site/content/about/contents.lr b/packages/responsive-image/tests/test-site/content/about/contents.lr new file mode 100644 index 0000000..9edb4d5 --- /dev/null +++ b/packages/responsive-image/tests/test-site/content/about/contents.lr @@ -0,0 +1,7 @@ +title: About this Website +--- +body: + +This is a website that was made with the Lektor quickstart. + +And it does not contain a lot of information. diff --git a/packages/responsive-image/tests/test-site/content/contents.lr b/packages/responsive-image/tests/test-site/content/contents.lr new file mode 100644 index 0000000..0492efe --- /dev/null +++ b/packages/responsive-image/tests/test-site/content/contents.lr @@ -0,0 +1,6 @@ +title: Welcome to Test Site! +--- +body: + +This is a basic demo website that shows how to use Lektor for a basic +website with some pages. diff --git a/packages/responsive-image/tests/test-site/content/dummy.pdf b/packages/responsive-image/tests/test-site/content/dummy.pdf Binary files differnew file mode 100644 index 0000000..774c2ea --- /dev/null +++ b/packages/responsive-image/tests/test-site/content/dummy.pdf diff --git a/packages/responsive-image/tests/test-site/content/projects/contents.lr b/packages/responsive-image/tests/test-site/content/projects/contents.lr new file mode 100644 index 0000000..f3658c6 --- /dev/null +++ b/packages/responsive-image/tests/test-site/content/projects/contents.lr @@ -0,0 +1,9 @@ +title: Projects +--- +body: + +This is a list of the projects: + +* Project 1 +* Project 2 +* Project 3 diff --git a/packages/responsive-image/tests/test-site/content/test.jpg b/packages/responsive-image/tests/test-site/content/test.jpg Binary files differnew file mode 100644 index 0000000..b9132f3 --- /dev/null +++ b/packages/responsive-image/tests/test-site/content/test.jpg diff --git a/packages/responsive-image/tests/test-site/models/page.ini b/packages/responsive-image/tests/test-site/models/page.ini new file mode 100644 index 0000000..dcddfe8 --- /dev/null +++ b/packages/responsive-image/tests/test-site/models/page.ini @@ -0,0 +1,11 @@ +[model] +name = Page +label = {{ this.title }} + +[fields.title] +label = Title +type = string + +[fields.body] +label = Body +type = markdown diff --git a/packages/responsive-image/tests/test-site/templates/layout.html b/packages/responsive-image/tests/test-site/templates/layout.html new file mode 100644 index 0000000..509426a --- /dev/null +++ b/packages/responsive-image/tests/test-site/templates/layout.html @@ -0,0 +1,28 @@ +<!doctype html> +<meta charset="utf-8"> +<link rel="stylesheet" href="{{ '/static/style.css'|url }}"> +<title>{% block title %}Welcome{% endblock %} — Test Site</title> +<body> + <header> + <h1>Test Site</h1> + <nav> + <ul class="nav navbar-nav"> + <li{% if this._path == '/' %} class="active"{% endif + %}><a href="{{ '/'|url }}">Welcome</a></li> + {% for href, title in [ + ['/projects', 'Projects'], + ['/about', 'About'] + ] %} + <li{% if this.is_child_of(href) %} class="active"{% endif + %}><a href="{{ href|url }}">{{ title }}</a></li> + {% endfor %} + </ul> + </nav> + </header> + <div class="page"> + {% block body %}{% endblock %} + </div> + <footer> + © Copyright 2020 by Jeff Dairiki. + </footer> +</body> diff --git a/packages/responsive-image/tests/test-site/templates/macros/pagination.html b/packages/responsive-image/tests/test-site/templates/macros/pagination.html new file mode 100644 index 0000000..077cc5a --- /dev/null +++ b/packages/responsive-image/tests/test-site/templates/macros/pagination.html @@ -0,0 +1,15 @@ +{% macro render_pagination(pagination) %} + <div class="pagination"> + {% if pagination.has_prev %} + <a href="{{ pagination.prev|url }}">« Previous</a> + {% else %} + <span class="disabled">« Previous</span> + {% endif %} + | {{ pagination.page }} | + {% if pagination.has_next %} + <a href="{{ pagination.next|url }}">Next »</a> + {% else %} + <span class="disabled">Next »</span> + {% endif %} + </div> +{% endmacro %} diff --git a/packages/responsive-image/tests/test-site/templates/page.html b/packages/responsive-image/tests/test-site/templates/page.html new file mode 100644 index 0000000..0430577 --- /dev/null +++ b/packages/responsive-image/tests/test-site/templates/page.html @@ -0,0 +1,6 @@ +{% extends "layout.html" %} +{% block title %}{{ this.title }}{% endblock %} +{% block body %} + <h2>{{ this.title }}</h2> + {{ this.body }} +{% endblock %} diff --git a/packages/responsive-image/tests/test_plugin.py b/packages/responsive-image/tests/test_plugin.py new file mode 100644 index 0000000..c1e68c4 --- /dev/null +++ b/packages/responsive-image/tests/test_plugin.py @@ -0,0 +1,220 @@ +import re +from contextlib import ExitStack + +import pytest +from inifile import IniFile + +from lektor_responsive_image import HAVE_MISTUNE0 +from lektor_responsive_image import ImprovedRenderer +from lektor_responsive_image import MarkdownConfig +from lektor_responsive_image import resolve_image +from lektor_responsive_image import ResponsiveImage +from lektor_responsive_image import ResponsiveImageMixin +from lektor_responsive_image import ResponsiveImagePlugin + +try: + from lektor.markdown.controller import RendererContext +except ModuleNotFoundError: + RendererContext = None + + +class DummyImage: + def __init__(self, width, height, format="jpeg", quality=None): + self.width = width + self.height = height + self.format = format + self.quality = quality + + def thumbnail(self, width, quality=None, upscale=None): + height = int(self.height * width / self.width + 0.5) + return DummyImage(width, height, format=self.format, quality=quality) + + +class DummyContext: + def url_to(self, image): + return f"img-{image.width}.jpg" + + +class TestResponsiveImage: + @pytest.fixture + def width(self): + return 2400 + + @pytest.fixture + def image(self, width): + height = int(3 * width / 4) + return DummyImage(width, height) + + @pytest.fixture + def sizes(self): + return None + + @pytest.fixture + def resp_image(self, image, sizes): + config = ResponsiveImage.DEFAULT_CONFIG.copy() + config["sizes"] = sizes + return ResponsiveImage(image, config, ctx=DummyContext()) + + def test_init_no_config(self, image): + resp_image = ResponsiveImage(image) + assert resp_image.config == ResponsiveImage.DEFAULT_CONFIG + assert resp_image.config is not ResponsiveImage.DEFAULT_CONFIG + + @pytest.mark.parametrize("width", [480]) + def test_attrs_no_srcset(self, resp_image): + assert "srcset" not in resp_image.attrs + + @pytest.mark.parametrize("width", [800]) + def test_attrs_srcset(self, resp_image): + srcset = resp_image.attrs["srcset"] + assert srcset == "img-480.jpg 480w, img-800.jpg 800w" + + @pytest.mark.parametrize("sizes", [None]) + def test_attrs_no_sizes(self, resp_image): + assert "sizes" not in resp_image.attrs + + @pytest.mark.parametrize("sizes", ["600px"]) + def test_attrs_sizes(self, resp_image, sizes): + assert resp_image.attrs["sizes"] == sizes + + @pytest.mark.parametrize("sizes", ["50vw", None]) + def test_sizes(self, resp_image, sizes): + assert resp_image.sizes == sizes + + @pytest.mark.parametrize( + "width, widths", + [ + (120, [120]), + (480, [480]), + (1024, [480, 800, 1024]), + (3600, [480, 800, 1200, 2400]), + ], + ) + def test_iter_widths(self, resp_image, widths): + assert list(resp_image.iter_widths()) == widths + + def test_default_image_attrs(self, resp_image): + assert resp_image.default_image_attrs() == { + "width": 1200, + "height": 900, + "src": "img-1200.jpg", + } + + def test_resize_image(self, resp_image, image): + assert resp_image.resize_image(image.width) is image + assert resp_image.resize_image(image.width + 1) is image + resized = resp_image.resize_image(image.width - 1) + assert resized.width == image.width - 1 + assert resized.quality == 92 + + +class Test_resolve_image: + def test_no_record(self): + assert resolve_image(None, "test.jpg") is None + + def test_external_url(self, lektor_pad): + assert resolve_image(lektor_pad.root, "http://example.com/test.jpg") is None + + def test_not_image(self, lektor_pad): + assert resolve_image(lektor_pad.root, "dummy.pdf") is None + + def test_resolve(self, lektor_pad): + image = resolve_image(lektor_pad.root, "test.jpg") + assert image.path == "/test.jpg" + assert image.width == 800 + + def test_resolve_absolute(self, lektor_pad): + about = lektor_pad.get("/about") + image = resolve_image(about, "/test.jpg") + assert image.path == "/test.jpg" + + def test_resolve_relative(self, lektor_pad): + about = lektor_pad.get("/about") + image = resolve_image(about, "../test.jpg") + assert image.path == "/test.jpg" + + +@pytest.fixture +def load_plugin(lektor_env): + lektor_env.plugin_controller.instanciate_plugin( + "responsive-image", ResponsiveImagePlugin + ) + + +class RendererWithMixin(ResponsiveImageMixin, ImprovedRenderer): + pass + + +class TestResponsiveImageMixin: + @pytest.fixture + def record(self, lektor_pad): + return lektor_pad.root + + @pytest.fixture + def mixin(self, record): + with ExitStack() as stack: + renderer = RendererWithMixin() + if RendererContext is not None: + stack.enter_context(RendererContext(record, meta={}, field_options={})) + else: # lektor < 3.4 + renderer.record = record + yield renderer + + @pytest.mark.usefixtures("load_plugin", "lektor_context") + def test(self, mixin): + args = ("TITLE", "ALT") if HAVE_MISTUNE0 else ("ALT", "TITLE") + img = mixin.image("test.jpg", *args) + assert re.match(r"<img.*>", img) + assert 'alt="ALT"' in img + assert "srcset=" in img + + @pytest.mark.usefixtures("load_plugin", "lektor_context") + def test_not_resolvable(self, mixin): + args = ("TITLE", "ALT") if HAVE_MISTUNE0 else ("ALT", "TITLE") + img = mixin.image("foo.jpg", *args) + assert re.match(r"<img.*>", img) + assert 'alt="ALT"' in img + assert "srcset=" not in img + + +class TestResponsiveImagePlugin: + @pytest.fixture + def plugin(self, lektor_env): + return ResponsiveImagePlugin(lektor_env, "responsive-image") + + def test_on_setup_env(self, plugin, lektor_env): + plugin.on_setup_env() + jinja_globals = lektor_env.jinja_env.globals + assert "responsive_image" in jinja_globals + + def test_on_markdown_config(self, plugin): + config = MarkdownConfig() + plugin.on_markdown_config(config) + assert config.renderer_mixins == [ResponsiveImageMixin] + + def test_get_responsive_image_config(self, plugin): + config = plugin.get_responsive_image_config() + assert config == ResponsiveImage.DEFAULT_CONFIG + assert config is not ResponsiveImage.DEFAULT_CONFIG + + @pytest.fixture + def inifile(self, config, tmp_path): + ini = IniFile(str(tmp_path / "test.ini")) + for key, value in config.items(): + ini["default." + key] = value + ini.save() + return ini + + @pytest.mark.parametrize( + "config, expected", + [ + ({"widths": "10 20 "}, {"widths": [10, 20]}), + ({"widths": "10-20"}, {}), + ({"quality": "12"}, {"quality": 12}), + ({"quality": "twelve"}, {}), + ({"default_width": "10"}, {"default_width": 10}), + ({"sizes": "60vw"}, {"sizes": "60vw"}), + ], + ) + def test__parse_ini(self, plugin, inifile, expected): + assert plugin._parse_ini(inifile) == expected diff --git a/packages/responsive-image/tox.ini b/packages/responsive-image/tox.ini new file mode 100644 index 0000000..f3bde27 --- /dev/null +++ b/packages/responsive-image/tox.ini @@ -0,0 +1,54 @@ +[tox] +minversion = 3 +envlist = + cover-{clean,report} + py{38,39,310,311,312}{,-lektor33,-mistune0} + lint +labels = + cover = py311{,-lektor33,-mistune0}, cover-{clean,report} + +[gh-actions] +python = + 3.8: py38, cover + 3.9: py39, cover + 3.10: py310, cover + 3.11: py311, cover + 3.12: py312, cover, lint + +[testenv] +deps = + pytest + pytest-cov + !lektor33: lektor>=3.4.0a1 + lektor33: lektor<3.4 + mistune0: mistune<1 +commands = + coverage run -m pytest {posargs: tests} +depends = + py{38,39,310,311,312}: cover-clean + cover-report: py{38,39,310,311,312}{,-lektor33,-mistune0} + +# workaround for pip cache contention under `tox p` with older pips +download = true + +[testenv:cover-clean] +deps = coverage[toml] +skip_install = true +commands = coverage erase + +[testenv:cover-report] +deps = coverage[toml] +skip_install = true +commands = + -coverage combine --append + coverage html + coverage report --fail-under 100 + +[testenv:lint] +skip_install = True +deps = + build + twine +commands = + python -m build -s --outdir {envtmpdir}/dist {toxinidir} + twine check {envtmpdir}/dist/* diff --git a/templates/blocks/gallery-image.html b/templates/blocks/gallery-image.html index 44a8e93..b786bbc 100644 --- a/templates/blocks/gallery-image.html +++ b/templates/blocks/gallery-image.html @@ -1,9 +1,15 @@ {% set image = record.attachments.get(this["image"]) %} {% if image %} - <img src="{{ image | url }}" - width="{{ image.width }}" - height="{{ image.height }}" - alt="{{ this["alt"] }}" - loading="lazy" - decoding="async"> + {% set responsive = responsive_image(image).attrs %} + <a href="{{ image | url }}" data-original-image> + <img src="{{ responsive.src }}" + {% if responsive.srcset %}srcset="{{ responsive.srcset }}"{% endif %} + sizes="(max-width: 500px) 100vw, (max-width: 1100px) 60vw, 50vw" + width="{{ image.width }}" + height="{{ image.height }}" + data-fullsize="{{ image | url }}" + alt="{{ this["alt"] }}" + loading="lazy" + decoding="async"> + </a> {% endif %} |
