From 2a007bafa218afde0b3f6032917571a574d3d1ce Mon Sep 17 00:00:00 2001 From: Penar Musaraj Date: Thu, 7 Feb 2019 15:04:09 -0500 Subject: [PATCH] FEAT: Allow image resize by width or height `|150x` resizes to 150px wide + auto-height. `x150` resizes to 150px tall and auto-width. Resize value can be from 1 to 999 (incl. for percentages). --- .../engines/discourse-markdown-it.js.es6 | 21 ++++++++++++++++--- spec/components/pretty_text_spec.rb | 6 +++++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/app/assets/javascripts/pretty-text/engines/discourse-markdown-it.js.es6 b/app/assets/javascripts/pretty-text/engines/discourse-markdown-it.js.es6 index 5a77beb33a3..9708f5a94b3 100644 --- a/app/assets/javascripts/pretty-text/engines/discourse-markdown-it.js.es6 +++ b/app/assets/javascripts/pretty-text/engines/discourse-markdown-it.js.es6 @@ -122,7 +122,7 @@ function setupHoister(md) { md.renderer.rules.html_raw = renderHoisted; } -const IMG_SIZE_REGEX = /^([1-9]+[0-9]*)x([1-9]+[0-9]*)(\s*,\s*([1-9][0-9]?)%)?$/; +const IMG_SIZE_REGEX = /^([1-9]+[0-9]*)x([1-9]+[0-9]*)(\s*,\s*(x?)([1-9][0-9]{0,2}?)([%x]?))?$/; function renderImage(tokens, idx, options, env, slf) { var token = tokens[idx]; @@ -140,12 +140,27 @@ function renderImage(tokens, idx, options, env, slf) { let width = match[1]; let height = match[2]; - if (match[4]) { - let percent = parseFloat(match[4]) / 100.0; + // calculate using percentage + if (match[5] && match[6] && match[6] === "%") { + let percent = parseFloat(match[5]) / 100.0; width = parseInt(width * percent); height = parseInt(height * percent); } + // calculate using only given width + if (match[5] && match[6] && match[6] === "x") { + let wr = parseFloat(match[5]) / width; + width = parseInt(match[5]); + height = parseInt(height * wr); + } + + // calculate using only given height + if (match[5] && match[4] && match[4] === "x" && !match[6]) { + let hr = parseFloat(match[5]) / height; + height = parseInt(match[5]); + width = parseInt(width * hr); + } + if (token.attrIndex("width") === -1) { token.attrs.push(["width", width]); } diff --git a/spec/components/pretty_text_spec.rb b/spec/components/pretty_text_spec.rb index 1490e38b3ac..6088a7d16e4 100644 --- a/spec/components/pretty_text_spec.rb +++ b/spec/components/pretty_text_spec.rb @@ -1228,16 +1228,20 @@ HTML expect(cooked).to eq(html.strip) end - it "allows whitespace before the percent scaler" do + it "ignores whitespace and allows scaling by percent, width, height" do cooked = PrettyText.cook <<~MD ![|220x100, 50%](http://png.com/my.png) ![|220x100 , 50%](http://png.com/my.png) ![|220x100 ,50%](http://png.com/my.png) + ![|220x100,150x](http://png.com/my.png) + ![|220x100, x50](http://png.com/my.png) MD html = <<~HTML



+
+

HTML