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 2206dbd
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
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
21 changes: 21 additions & 0 deletions lib/kitabu/markdown.rb
Expand Up @@ -61,6 +61,27 @@ 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(: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
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)

expect(html).to have_tag(
"figure>img[alt='ALT'][title='TITLE']+figcaption",
"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 2206dbd

Please sign in to comment.