From fefe4b70d9e69910a8e3acd6890497553b5eff2f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?J=C3=BCrgen=20Haas?= <juergen@paragon-es.de>
Date: Fri, 20 Jan 2017 17:21:39 +0100
Subject: Support explicit image sizes in markdown (#4803)

* Support explicit image sizes in markdown

* Cleanup code

* Add support for missing second dimension

* Overwrite height style attribute if available, use "auto" otherwise

* Fix syntax

* Do not set the height style if its value is auto

* Re-calculate width and height, if given height is bigger than max-height

* Make formulas more explicit
---
 webapp/utils/markdown.jsx | 34 ++++++++++++++++++++++++++++++++--
 1 file changed, 32 insertions(+), 2 deletions(-)

(limited to 'webapp/utils/markdown.jsx')

diff --git a/webapp/utils/markdown.jsx b/webapp/utils/markdown.jsx
index 8a0b9ef0a..9d4fdcb2e 100644
--- a/webapp/utils/markdown.jsx
+++ b/webapp/utils/markdown.jsx
@@ -8,7 +8,18 @@ import marked from 'marked';
 import katex from 'katex';
 
 function markdownImageLoaded(image) {
-    image.style.height = 'auto';
+    if (image.hasAttribute('height') && image.attributes.height.value !== 'auto') {
+        const maxHeight = parseInt(global.getComputedStyle(image).maxHeight, 10);
+
+        if (image.attributes.height.value > maxHeight) {
+            image.style.height = maxHeight + 'px';
+            image.style.width = ((maxHeight * image.attributes.width.value) / image.attributes.height.value) + 'px';
+        } else {
+            image.style.height = image.attributes.height.value + 'px';
+        }
+    } else {
+        image.style.height = 'auto';
+    }
 }
 global.markdownImageLoaded = markdownImageLoaded;
 
@@ -117,10 +128,29 @@ class MattermostMarkdownRenderer extends marked.Renderer {
     }
 
     image(href, title, text) {
-        let out = '<img src="' + href + '" alt="' + text + '"';
+        let src = href;
+        let dimensions = [];
+        const parts = href.split(' ');
+        if (parts.length > 1) {
+            const lastPart = parts.pop();
+            src = parts.join(' ');
+            if (lastPart[0] === '=') {
+                dimensions = lastPart.substr(1).split('x');
+                if (dimensions.length === 2 && dimensions[1] === '') {
+                    dimensions[1] = 'auto';
+                }
+            }
+        }
+        let out = '<img src="' + src + '" alt="' + text + '"';
         if (title) {
             out += ' title="' + title + '"';
         }
+        if (dimensions.length > 0) {
+            out += ' width="' + dimensions[0] + '"';
+        }
+        if (dimensions.length > 1) {
+            out += ' height="' + dimensions[1] + '"';
+        }
         out += ' onload="window.markdownImageLoaded(this)" onerror="window.markdownImageLoaded(this)" class="markdown-inline-img"';
         out += this.options.xhtml ? '/>' : '>';
         return out;
-- 
cgit v1.2.3-1-g7c22

