From 3f950a756acf71ee245bed882c71a90b3ba3a949 Mon Sep 17 00:00:00 2001 From: Sam Date: Tue, 11 Jul 2017 12:13:03 -0400 Subject: [PATCH] FEATURE: support image dimensions via Markdown image --- .../engines/discourse-markdown-it.js.es6 | 45 +++++++++++++++++++ spec/components/pretty_text_spec.rb | 24 ++++++++++ 2 files changed, 69 insertions(+) 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 9b9a9718283..4029171cef3 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 @@ -99,6 +99,50 @@ function setupHoister(md) { md.renderer.rules.html_raw = renderHoisted; } +const IMG_SIZE_REGEX = /^([1-9]+[0-9]*)x([1-9]+[0-9]*)(,([1-9][0-9]?)%)?$/; +function renderImage(tokens, idx, options, env, slf) { + var token = tokens[idx]; + + let alt = slf.renderInlineAsText(token.children, options, env); + + let split = alt.split('|'); + if (split.length > 1) { + let match; + let info = split.splice(split.length-1)[0]; + + if (match = info.match(IMG_SIZE_REGEX)) { + if (match[1] && match[2]) { + alt = split.join('|'); + + let width = match[1]; + let height = match[2]; + + if (match[4]) { + let percent = parseFloat(match[4]) / 100.0; + width = parseInt(width * percent); + height = parseInt(height * percent); + } + + if (token.attrIndex('width') === -1) { + token.attrs.push(['width', width]); + } + + if (token.attrIndex('height') === -1) { + token.attrs.push(['height', height]); + } + } + + } + } + + token.attrs[token.attrIndex('alt')][1] = alt; + return slf.renderToken(tokens, idx, options); +} + +function setupImageDimensions(md) { + md.renderer.rules.image = renderImage; +} + export function setup(opts, siteSettings, state) { if (opts.setup) { return; @@ -160,6 +204,7 @@ export function setup(opts, siteSettings, state) { setupUrlDecoding(opts.engine); setupHoister(opts.engine); + setupImageDimensions(opts.engine); setupBlockBBCode(opts.engine); setupInlineBBCode(opts.engine); diff --git a/spec/components/pretty_text_spec.rb b/spec/components/pretty_text_spec.rb index 7b7b7036fae..3c4089d058f 100644 --- a/spec/components/pretty_text_spec.rb +++ b/spec/components/pretty_text_spec.rb @@ -890,5 +890,29 @@ HTML expect(PrettyText.cook("")).to eq "" end + # custom rule used to specify image dimensions via alt tags + describe "image dimensions" do + it "allows title plus dimensions" do + cooked = PrettyText.cook <<~MD + ![title with | title|220x100](http://png.com/my.png) + ![](http://png.com/my.png) + ![|220x100](http://png.com/my.png) + ![stuff](http://png.com/my.png) + ![|220x100,50%](http://png.com/my.png) + MD + + html = <<~HTML +

title with | title
+
+
+ stuff
+

+ HTML + puts cooked + + expect(cooked).to eq(html.strip) + end + end + end