Просмотр исходного кода

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.
Sam Atkins 2 лет назад
Родитель
Сommit
36c5dd78b1
1 измененных файлов с 44 добавлено и 1 удалено
  1. 44 1
      Userland/Libraries/LibWeb/Loader/FrameLoader.cpp

+ 44 - 1
Userland/Libraries/LibWeb/Loader/FrameLoader.cpp

@@ -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;
 }