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).
This commit is contained in:
Penar Musaraj 2019-02-07 15:04:09 -05:00
parent c0ccf21970
commit 2a007bafa2
2 changed files with 23 additions and 4 deletions

View File

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

View File

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