LibWeb: Make Markdown images shrink-to-fit by default

This inserts some CSS and JS to make images in Markdown documents which
are wider than the viewport, become shrink-to-fit. Clicking on these
toggles them between shrink-to-fit and full size.

Anyone who displays Markdown documents using LibWeb gets this
functionality for free! That's Browser, Help, and Welcome's README
display.
This commit is contained in:
Sam Atkins 2022-09-27 11:36:43 +01:00 committed by Linus Groh
parent aea4fbdd7b
commit 36c5dd78b1
Notes: sideshowbarker 2024-07-17 10:10:18 +09:00

View file

@ -52,7 +52,50 @@ static bool build_markdown_document(DOM::Document& document, ByteBuffer const& d
if (!markdown_document)
return false;
auto parser = HTML::HTMLParser::create(document, markdown_document->render_to_html(), "utf-8");
auto extra_head_contents = R"~~~(
<style>
.zoomable {
cursor: zoom-in;
max-width: 100%;
}
.zoomable.zoomed-in {
cursor: zoom-out;
max-width: none;
}
</style>
<script>
function imageClickEventListener(event) {
let image = event.target;
if (image.classList.contains("zoomable")) {
image.classList.toggle("zoomed-in");
}
}
function processImages() {
let images = document.querySelectorAll("img");
let windowWidth = window.innerWidth;
images.forEach((image) => {
if (image.naturalWidth > windowWidth) {
image.classList.add("zoomable");
} else {
image.classList.remove("zoomable");
image.classList.remove("zoomed-in");
}
image.addEventListener("click", imageClickEventListener);
});
}
document.addEventListener("load", () => {
processImages();
});
window.addEventListener("resize", () => {
processImages();
});
</script>
)~~~"sv;
auto parser = HTML::HTMLParser::create(document, markdown_document->render_to_html(extra_head_contents), "utf-8");
parser->run(document.url());
return true;
}