Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion Sources/Ink/Internal/Image.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,34 @@
* MIT license, see LICENSE file for details
*/


internal struct Image: Fragment {
var modifierTarget: Modifier.Target { .images }

private var link: Link
private var caption: String?

static func read(using reader: inout Reader) throws -> Image {
try reader.read("!")
return try Image(link: .read(using: &reader))
let _link = try Link.read(using: &reader)
let currentIndex = reader.currentIndex
let white = String(reader.readUntilEndOfLine())
guard white.trimmingCharacters(in: .whitespacesAndNewlines) == "" else {
reader.moveToIndex(currentIndex)
return Image(link: _link, caption: nil)
}
guard !reader.didReachEnd && reader.currentCharacter == "*" else {
reader.moveToIndex(currentIndex)
return Image(link: _link, caption: nil)
}
reader.advanceIndex()
do {
let _caption = try reader.read(until: "*")
return Image(link: _link,caption: String(_caption))
} catch {
reader.moveToIndex(currentIndex)
return Image(link: _link, caption: nil)
}
}

func html(usingURLs urls: NamedURLCollection,
Expand All @@ -23,6 +43,9 @@ internal struct Image: Fragment {
alt = " alt=\"\(alt)\""
}

if let figCaption = caption {
return "<figure><img src=\"\(url)\"\(alt)/> <figcaption>\(figCaption)</figcaption></figure>"
}
return "<img src=\"\(url)\"\(alt)/>"
}

Expand Down
9 changes: 9 additions & 0 deletions Tests/InkTests/ImageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ final class ImageTests: XCTestCase {
let html = MarkdownParser().html(from: "![Alt text](url)")
XCTAssertEqual(html, #"<img src="url" alt="Alt text"/>"#)
}

func testImageWithURLAltTextAndCaption() {
let html = MarkdownParser().html(from: """
![Alt text](url)
*caption*
""")
XCTAssertEqual(html, #"<figure><img src="url" alt="Alt text"/> <figcaption>caption</figcaption></figure>"#)
}

func testImageWithReferenceAndAltText() {
let html = MarkdownParser().html(from: """
Expand All @@ -48,6 +56,7 @@ extension ImageTests {
("testImageWithURL", testImageWithURL),
("testImageWithReference", testImageWithReference),
("testImageWithURLAndAltText", testImageWithURLAndAltText),
("testImageWithURLAltTextAndCaption",testImageWithURLAltTextAndCaption),
("testImageWithReferenceAndAltText", testImageWithReferenceAndAltText),
("testImageWithinParagraph", testImageWithinParagraph)
]
Expand Down