From 7e4edcfae8a3c0e664b836ee7c5f28b47853a2f8 Mon Sep 17 00:00:00 2001 From: Vinoth Kannan Date: Sun, 27 Jan 2019 01:21:56 +0530 Subject: [PATCH] FIX: Convert lightbox html into proper image markdown --- .../javascripts/discourse/lib/to-markdown.js.es6 | 16 ++++++++++++---- test/javascripts/lib/to-markdown-test.js.es6 | 15 +++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/app/assets/javascripts/discourse/lib/to-markdown.js.es6 b/app/assets/javascripts/discourse/lib/to-markdown.js.es6 index 22fbd802732..ee3bd1e0e3e 100644 --- a/app/assets/javascripts/discourse/lib/to-markdown.js.es6 +++ b/app/assets/javascripts/discourse/lib/to-markdown.js.es6 @@ -8,6 +8,9 @@ const msoListClasses = [ "MsoListParagraphCxSpMiddle", "MsoListParagraphCxSpLast" ]; +const hasChild = (e, n) => { + return (e.children || []).some(c => c.name === n); +}; export class Tag { constructor(name, prefix = "", suffix = "", inline = false) { @@ -194,14 +197,19 @@ export class Tag { } decorate(text) { - const attr = this.element.attributes; + const e = this.element; + const attr = e.attributes; if (/^mention/.test(attr.class) && "@" === text[0]) { return text; - } - - if ("hashtag" === attr.class && "#" === text[0]) { + } else if ("hashtag" === attr.class && "#" === text[0]) { return text; + } else if ( + ["lightbox", "d-lazyload"].includes(attr.class) && + hasChild(e, "img") + ) { + text = attr.title || ""; + return "![" + text + "](" + attr.href + ")"; } if (attr.href && text !== attr.href) { diff --git a/test/javascripts/lib/to-markdown-test.js.es6 b/test/javascripts/lib/to-markdown-test.js.es6 index c79249c4d57..f63a004c263 100644 --- a/test/javascripts/lib/to-markdown-test.js.es6 +++ b/test/javascripts/lib/to-markdown-test.js.es6 @@ -352,3 +352,18 @@ QUnit.test("keeps emoji syntax for custom emoji", assert => { assert.equal(toMarkdown(html), markdown); }); + +QUnit.test("converts image lightboxes to markdown", assert => { + let html = ` + sherlock3_sig
+ sherlock3_sig.jpg5496×3664 2 MB +
+ `; + const markdown = `![sherlock3_sig.jpg](https://d11a6trkgmumsb.cloudfront.net/uploads/default/original/1X/8hkjhk7692f6afed3cb99d43ab2abd4e30aa8cba.jpeg)`; + + assert.equal(toMarkdown(html), markdown); + + html = `sherlock3_sig`; + + assert.equal(toMarkdown(html), markdown); +});