Skip to content

Commit

Permalink
Render figure element when images have title.
Browse files Browse the repository at this point in the history
  • Loading branch information
fnando committed Feb 3, 2024
1 parent c3622ad commit b5ee628
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
in any system.
- Update all templates to use h1 as the root heading.
- Remove inline alignment from tables.
- Render `<figure>` for images with title.

## v3.1.0

Expand Down
22 changes: 22 additions & 0 deletions lib/kitabu/markdown.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,28 @@ def table(header, body)
</table>
HTML
end

def image(src, title, alt)
html = Nokogiri::HTML.fragment("<img />")
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
<figure>
#{img}
<figcaption></figcaption>
</figure>
HTML

html.css("figcaption").first.content = title

html.to_s
end
end

class << self
Expand Down
25 changes: 25 additions & 0 deletions spec/kitabu/markdown_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit b5ee628

Please sign in to comment.