Skip to content

A platform for community discussion. Free, open, simple.

FEAT: Allow image resize by width or height

Penar Musaraj2a007bafa218
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
<p><img src="http://png.com/my.png" alt width="110" height="50"><br>
<img src="http://png.com/my.png" alt width="110" height="50"><br>
+ <img src="http://png.com/my.png" alt width="110" height="50"><br>
+ <img src="http://png.com/my.png" alt width="150" height="68"><br>
<img src="http://png.com/my.png" alt width="110" height="50"></p>
HTML