From b5ee628fadcb3bbef5faa2e3ec01eee8853fef0f Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Fri, 2 Feb 2024 22:20:49 -0800 Subject: [PATCH] Render figure element when images have title. --- CHANGELOG.md | 1 + lib/kitabu/markdown.rb | 22 ++++++++++++++++++++++ spec/kitabu/markdown_spec.rb | 25 +++++++++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cee3c6..3459c8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ in any system. - Update all templates to use h1 as the root heading. - Remove inline alignment from tables. +- Render `
` for images with title. ## v3.1.0 diff --git a/lib/kitabu/markdown.rb b/lib/kitabu/markdown.rb index fd50af6..eea52c1 100644 --- a/lib/kitabu/markdown.rb +++ b/lib/kitabu/markdown.rb @@ -61,6 +61,28 @@ def table(header, body) HTML end + + def image(src, title, alt) + html = Nokogiri::HTML.fragment("") + img = html.css("img").first + img.set_attribute(:src, src) + img.set_attribute(:srcset, "#{src} 2x") + img.set_attribute(:alt, alt) + img.set_attribute(:title, title) if title + + return html.to_s unless title + + html = Nokogiri::HTML.fragment <<~HTML +
+ #{img} +
+
+ HTML + + html.css("figcaption").first.content = title + + html.to_s + end end class << self diff --git a/spec/kitabu/markdown_spec.rb b/spec/kitabu/markdown_spec.rb index 8d2e6c0..2b641c8 100644 --- a/spec/kitabu/markdown_spec.rb +++ b/spec/kitabu/markdown_spec.rb @@ -118,4 +118,29 @@ class User expect(html).to have_tag("table>tbody>tr>td.align-center", "Positive") expect(html).to have_tag("table>tbody>tr>td:not([class*='align'])", "N/A") end + + it "replaces images with titles with figure" do + html = Kitabu::Markdown.render <<~TEXT + ![ALT](image.png "TITLE") + TEXT + + html = Nokogiri::HTML(html) + + selector = "figure>img[src='image.png'][srcset='image.png 2x']" \ + "[alt='ALT'][title='TITLE']+figcaption" + + expect(html).to have_tag(selector, "TITLE") + end + + it "keeps images without titles as it is" do + html = Kitabu::Markdown.render <<~TEXT + ![This is the alt](image.png) + TEXT + + html = Nokogiri::HTML(html) + + expect(html).to have_tag("img[alt='This is the alt']") + expect(html).not_to have_tag("figure") + expect(html).not_to have_tag("figcaption") + end end