diff --git a/content/assets/test.jpg b/content/assets/test.jpg new file mode 100644 index 0000000..5a44109 Binary files /dev/null and b/content/assets/test.jpg differ diff --git a/content/index.md b/content/index.md index 241dbf0..c9f0f2d 100644 --- a/content/index.md +++ b/content/index.md @@ -1 +1,9 @@ # Content + +Before image + +![Content](./assets/test.jpg) + +After image + +![Image](https://theorangeone.net/images/ml7eDl0dfJcNa0gb78bceOAZA2Y=/1/width-1200/header.jpg) diff --git a/hooks/images.py b/hooks/images.py new file mode 100644 index 0000000..c71365a --- /dev/null +++ b/hooks/images.py @@ -0,0 +1,60 @@ +from bs4 import BeautifulSoup +from mkdocs.structure.files import Files +from typing import NamedTuple +from mkdocs.utils import copy_file +import os +from functools import partial + +class Resize(NamedTuple): + source_path: str + url: str + width: int + + def get_resize_url(self): + return f"/_resized/w/{self.width}/{self.url}" + + def get_dest_path(self): + return self.get_resize_url().lstrip("/") + +RESIZES = set() + +def on_pre_build(config): + RESIZES.clear() + +def on_page_content(html, page, config, files: Files): + soup = BeautifulSoup(html, "html.parser") + + for tag in soup.find_all("img", src=True): + src = tag.get("src") + source_file = files.get_file_from_path(src) + if source_file is None: + continue + + resize = Resize(source_file.abs_src_path, source_file.url, 1000) + RESIZES.add(resize) + + tag["src"] = resize.get_resize_url() + + return str(soup) + +def resize_image(files: Files, image, width): + source_file = files.get_file_from_path(image) + if source_file is None: + return None + + resize = Resize(source_file.abs_src_path, source_file.url, width) + RESIZES.add(resize) + + return resize.get_resize_url() + +def on_env(env, config, files): + env.filters["resize_image"] = partial(resize_image, files) + + return env + + +def on_post_build(config): + output_path = config["site_dir"] + for resize in RESIZES: + # TODO: Actually resize + copy_file(resize.source_path, os.path.join(output_path, resize.get_dest_path())) diff --git a/mkdocs.yml b/mkdocs.yml index 1782718..eba1bec 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -9,3 +9,7 @@ theme: hooks: - hooks/nav.py - hooks/tags.py + - hooks/images.py + +markdown_extensions: + - attr_list diff --git a/theme/main.html b/theme/main.html index ecc2871..54eb461 100644 --- a/theme/main.html +++ b/theme/main.html @@ -12,3 +12,5 @@ Children: {{ page|children }} {% set tag_1_page = get_page('tags/tag1.md') %} Found page: {{ tag_1_page }} + +Image resized: {{ "./assets/test.jpg"|resize_image(1500) }}