Add [[primary_image]] tag to article renderer. Replaced with div containing best guess at primary image from feed that is not otherwise included in the article HTML. (Comes from Media RSS, for instance.)

This commit is contained in:
Brent Simmons committed 2026-11-08 18:05:06 -08:00
1 parent f3a0102c39
commit 1d8ae6abec
6 files changed
+225 -44

No files matched your search

@@ -7,6 +7,7 @@
import Foundation
import RSCore
import RSParser
import Articles
/// HTML for the `[[enclosures]]` substitution: players for audio and video, and images.
@@ -15,32 +16,42 @@ extension ArticleRenderer {
private static let secondsPerMinute = 60
private static let secondsPerHour = 3600
private static let visualElementTags = ["<img", "<picture", "<video", "<iframe"]
/// Empty when there’s nothing to show. Skips attachments whose URLs already appear
/// in the body, since feeds often embed the same image they list as an enclosure.
/// `imageURL` (the article’s image, else its thumbnail) is shown only when nothing
/// else visual is — no image or video enclosure, and no image or video in the body.
static func enclosuresHTML(attachments: [Attachment]?, body: String, imageURL: String?) -> String {
var enclosures = [String]()
var hasVisualEnclosure = false
for attachment in attachments ?? [] where !bodyContainsURL(body, attachment.url) {
if let enclosure = enclosureHTML(attachment, posterURL: imageURL) {
enclosures.append(enclosure)
hasVisualEnclosure = hasVisualEnclosure || isVisual(attachment)
}
}
if !hasVisualEnclosure, let imageURL, !imageURL.isEmpty, !bodyContainsVisualElement(body), !bodyContainsURL(body, imageURL) {
let image = "<div class=\"nnw-enclosure nnw-enclosure-image\"><img src=\"\(imageURL.escapingSpecialXMLCharacters)\" alt=\"\"></div>"
enclosures.insert(image, at: 0)
}
/// A WordPress resized copy’s suffix, as in `heron-1024x683.jpg`.
private static let wordPressSizeSuffix = #/-\d+x\d+(?=\.[A-Za-z0-9]+$)/#
/// Empty when there’s nothing to show. Skips attachments already in the body, including resized copies,
/// since feeds often embed the same image they list as an enclosure.
/// `posterURL` is the poster for video enclosures.
static func enclosuresHTML(attachments: [Attachment]?, body: String, bodyImageIdentities: Set<String>, posterURL: String?) -> String {
let enclosures = (attachments ?? []).filter { !bodyContains($0.url, body: body, bodyImageIdentities: bodyImageIdentities) }.compactMap { enclosureHTML($0, posterURL: posterURL) }
guard !enclosures.isEmpty else {
return ""
}
return "<div class=\"nnw-enclosures\">\n\(enclosures.joined(separator: "\n"))\n</div>"
}
static func dimensionAttributes(_ attachment: Attachment) -> String {
guard let width = attachment.width, let height = attachment.height else {
return ""
}
return " width=\"\(width)\" height=\"\(height)\""
}
/// The `imageIdentity` of each of the body’s images, for spotting resized copies.
static func bodyImageIdentities(_ body: String, baseURL: URL?) -> Set<String> {
Set(HTMLImageParser.significantImageURLStrings(html: body, baseURL: baseURL, maximumCount: Int.max).compactMap(imageIdentity))
}
/// True when the body has `url`, or a resized copy of the image at `url`.
static func bodyContains(_ url: String, body: String, bodyImageIdentities: Set<String>) -> Bool {
if bodyContainsURL(body, url) {
return true
}
guard let identity = imageIdentity(url) else {
return false
}
return bodyImageIdentities.contains(identity)
}
}
private extension ArticleRenderer {
@@ -102,13 +113,6 @@ private extension ArticleRenderer {
return components.joined(separator: " · ")
}
static func dimensionAttributes(_ attachment: Attachment) -> String {
guard let width = attachment.width, let height = attachment.height else {
return ""
}
return " width=\"\(width)\" height=\"\(height)\""
}
static func durationString(_ durationInSeconds: Int) -> String {
let hours = durationInSeconds / secondsPerHour
let minutes = (durationInSeconds % secondsPerHour) / secondsPerMinute
@@ -126,19 +130,23 @@ private extension ArticleRenderer {
return lastPathComponent.removingPercentEncoding ?? lastPathComponent
}
static func isVisual(_ attachment: Attachment) -> Bool {
if ArticleRenderingSpecialCases.youTubeEmbedURL(forAttachmentURL: attachment.url) != nil {
return true
}
return attachment.displayMedium == .image || attachment.displayMedium == .video
}
static func bodyContainsVisualElement(_ body: String) -> Bool {
visualElementTags.contains { body.range(of: $0, options: .caseInsensitive) != nil }
}
/// Body HTML escapes `&` in attributes, so check both forms of the URL.
static func bodyContainsURL(_ body: String, _ url: String) -> Bool {
body.contains(url) || body.contains(url.escapingSpecialXMLCharacters)
}
/// The last two path components, lowercased, without a WordPress size suffix.
/// Two components, since some sites name every image `original.jpg` in its own folder.
/// Ignores the host and query, since resized copies are often served through a resizing service.
static func imageIdentity(_ urlString: String) -> String? {
guard let url = URL(string: urlString) else {
return nil
}
let pathComponents = url.pathComponents.filter { $0 != "/" }
guard let fileName = pathComponents.last else {
return nil
}
let folderName = pathComponents.dropLast().suffix(1)
return (folderName + [fileName.replacing(wordPressSizeSuffix, with: "")]).joined(separator: "/").lowercased()
}
}
@@ -0,0 +1,65 @@
//
// ArticleRenderer+PrimaryImage.swift
// NetNewsWire
//
// Created by Brent Simmons on 11/8/26.
//
import Foundation
import RSCore
import Articles
/// The article’s main image, for the `[[primary_image]]` substitution.
extension ArticleRenderer {
/// The article image (JSON Feed `image`, `itunes:image`, or a sync service’s image), else the first image attachment.
/// Nil when the body already has the image, or a resized copy of it at a different URL.
/// An attachment with the same URL supplies the dimensions and title.
static func primaryImage(imageLink: String?, attachments: [Attachment]?, body: String, bodyImageIdentities: Set<String>) -> Attachment? {
let attachments = attachments ?? []
let image: Attachment?
if let imageLink, !imageLink.isEmpty {
image = attachments.first { $0.url == imageLink } ?? Attachment(url: imageLink, mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: .image)
} else {
image = attachments.first { $0.displayMedium == .image }
}
guard let image, !bodyContains(image.url, body: body, bodyImageIdentities: bodyImageIdentities) else {
return nil
}
return image
}
/// No caption when the image’s title is the same as the article’s.
static func primaryImageHTML(_ image: Attachment, articleTitle: String?) -> String {
var attributes = "src=\"\(image.url.escapingSpecialXMLCharacters)\""
var caption = ""
if let title = image.title, !title.isEmpty {
let escapedTitle = title.escapingSpecialXMLCharacters
attributes += " alt=\"\(escapedTitle)\" title=\"\(escapedTitle)\""
if !isSameTitle(title, articleTitle) {
caption = "<div class=\"nnw-primary-image-caption\">\(escapedTitle)</div>"
}
} else {
attributes += " alt=\"\""
}
attributes += dimensionAttributes(image)
return "<div class=\"nnw-primary-image\"><img \(attributes)>\(caption)</div>"
}
}
private extension ArticleRenderer {
static func isSameTitle(_ imageTitle: String, _ articleTitle: String?) -> Bool {
guard let articleTitle else {
return false
}
return collapsingWhitespace(imageTitle).caseInsensitiveCompare(collapsingWhitespace(articleTitle)) == .orderedSame
}
/// Each run of whitespace, including non-breaking spaces, becomes one space, and the ends are trimmed.
/// Apple Newsroom puts non-breaking spaces in image titles (“MacBook Pro”) but not in article titles.
static func collapsingWhitespace(_ s: String) -> String {
s.split(whereSeparator: \.isWhitespace).joined(separator: " ")
}
}
+23 -3
View File
@@ -47,6 +47,11 @@ import Images
private let baseURL: URL?
private let routesThumbnailImages: Bool
private static let primaryImageKey = "primary_image"
private static let primaryImageMacro = "[[primary_image]]"
private static let enclosuresKey = "enclosures"
private static let enclosuresMacro = "[[enclosures]]"
private static let longDateTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
@@ -270,16 +275,31 @@ private extension ArticleRenderer {
d["external_link"] = ""
}
// Templates without [[primary_image]] get the primary image in the enclosures.
let bodyImageIdentities = Self.bodyImageIdentities(body, baseURL: baseURL)
var attachments = article.attachments ?? []
var primaryImageHTML = ""
if let primaryImage = Self.primaryImage(imageLink: article.imageLink, attachments: attachments, body: body, bodyImageIdentities: bodyImageIdentities) {
if template().contains(Self.primaryImageMacro) {
primaryImageHTML = Self.primaryImageHTML(primaryImage, articleTitle: article.title)
attachments.removeAll { $0.url == primaryImage.url }
} else if !attachments.contains(primaryImage) {
attachments.insert(primaryImage, at: 0)
}
}
// Templates without [[enclosures]] get them at the end of the body.
var enclosures = Self.enclosuresHTML(attachments: article.attachments, body: body, imageURL: article.imageLink ?? article.thumbnailLink)
var enclosures = Self.enclosuresHTML(attachments: attachments, body: body, bodyImageIdentities: bodyImageIdentities, posterURL: article.imageLink ?? article.thumbnailLink)
var body = body
if routesThumbnailImages, let thumbnailMode = AppDefaults.timelineThumbnailsDisplay.thumbnailMode, let thumbnailURL = ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) {
body = Self.routingThumbnailImages(body, thumbnailURL: thumbnailURL, baseURL: baseURL)
enclosures = Self.routingThumbnailImages(enclosures, thumbnailURL: thumbnailURL, baseURL: baseURL)
primaryImageHTML = Self.routingThumbnailImages(primaryImageHTML, thumbnailURL: thumbnailURL, baseURL: baseURL)
}
if template().contains("[[enclosures]]") {
d[Self.primaryImageKey] = primaryImageHTML
if template().contains(Self.enclosuresMacro) {
d["body"] = body
d["enclosures"] = enclosures
d[Self.enclosuresKey] = enclosures
} else if enclosures.isEmpty {
d["body"] = body
} else {
+15
View File
@@ -63,6 +63,21 @@ img.twemoji, img.emoji {
width: auto;
}
/* Primary image: the article’s main image, from the feed */
.nnw-primary-image {
margin: 1em 0;
}
.nnw-primary-image img {
height: auto;
}
.nnw-primary-image-caption {
margin: 0.5em 0 0;
font-size: 0.9em;
}
/* Enclosures: audio and video players and images after the article body */
.nnw-enclosures {
+2
View File
@@ -27,6 +27,7 @@ time_short: Long version of the publish time.
text_size_class: The size class that the user has selected in Preferences for article text.
body: The body of the article.
primary_image: The primary image as specified in the feed (possibly via an enclosure or Media RSS). Adds a div wrapper (class: nnw-primary-image). Does not appear if the image is already in the text of the article. This image, if it appears, does not then appear in the enclosures element.
enclosures: Audio and video players and images from the article’s enclosures. If a template doesn’t include this, they’re added to the end of the body.
-->
@@ -44,6 +45,7 @@ enclosures: Audio and video players and images from the article’s enclosures.
<div class="articleTitle"><h1><a href="[[preferred_link]]">[[title]]</a></h1></div>
<div class="[[dateline_style]]"><a href="[[preferred_link]]">[[datetime_medium]]</a></div>
<div class="externalLink">[[external_link_label]] <a href="[[external_link]]">[[external_link_stripped]]</a></div>
[[primary_image]]
<div id="bodyContainer" class="articleBody [[text_size_class]]">[[body]]</div>
[[enclosures]]
</article>
@@ -19,11 +19,71 @@ import Articles
let body = "<ul><li>Facebook’s Onavo scam</li><li>Apple’s FaceTime bug</li></ul>"
let artworkURL = "http://static1.squarespace.com/static/513abd71e4b0fe58c655c105/t/52c45a37e4b0a77a5034aa84/1388599866232/1500w/Artwork.jpg"
let html = ArticleRenderer.enclosuresHTML(attachments: [attachment], body: body, imageURL: artworkURL)
let primaryImage = try #require(ArticleRenderer.primaryImage(imageLink: artworkURL, attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil)))
let primaryImageHTML = ArticleRenderer.primaryImageHTML(primaryImage, articleTitle: nil)
let html = ArticleRenderer.enclosuresHTML(attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil), posterURL: artworkURL)
#expect(primaryImageHTML == "<div class=\"nnw-primary-image\"><img src=\"\(artworkURL)\" alt=\"\"></div>")
#expect(html.contains("<audio controls preload=\"none\" src=\"http://traffic.libsyn.com/atpfm/atp311.mp3\"></audio>"))
#expect(html.contains("atp311.mp3 · 1:54:09 · "))
#expect(html.contains("<img src=\"\(artworkURL)\" alt=\"\">"))
}
// JSON Feed `image` that’s also listed as an attachment, which supplies the dimensions and title.
@Test func primaryImageUsesMatchingAttachment() throws {
let imageURL = "https://example.com/uploads/2026/11/heron.jpg"
let attachment = try #require(Attachment(url: imageURL, mimeType: "image/jpeg", title: "Great blue heron at Green Lake", sizeInBytes: nil, durationInSeconds: nil, width: 1200, height: 800, medium: nil))
let body = "<p>Spotted this morning on the north shore.</p>"
let primaryImage = try #require(ArticleRenderer.primaryImage(imageLink: imageURL, attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil)))
#expect(ArticleRenderer.primaryImageHTML(primaryImage, articleTitle: nil) == "<div class=\"nnw-primary-image\"><img src=\"\(imageURL)\" alt=\"Great blue heron at Green Lake\" title=\"Great blue heron at Green Lake\" width=\"1200\" height=\"800\"><div class=\"nnw-primary-image-caption\">Great blue heron at Green Lake</div></div>")
}
// A feed that titles the image with the article’s title.
@Test func primaryImageCaptionDroppedWhenSameAsArticleTitle() throws {
let imageURL = "https://example.com/uploads/2026/11/heron.jpg"
let image = try #require(Attachment(url: imageURL, mimeType: "image/jpeg", title: "Great Blue Heron at Green Lake", sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: nil))
let html = ArticleRenderer.primaryImageHTML(image, articleTitle: "Great blue heron at Green Lake ")
#expect(html == "<div class=\"nnw-primary-image\"><img src=\"\(imageURL)\" alt=\"Great Blue Heron at Green Lake\" title=\"Great Blue Heron at Green Lake\"></div>")
}
// Apple Newsroom: the image title has a non-breaking space in “MacBook Pro”, and the article title has a regular space and a trailing newline.
@Test func primaryImageCaptionDroppedWhenSameAsArticleTitleExceptNonBreakingSpace() throws {
let imageURL = "https://www.apple.com/newsroom/images/2026/10/apple-unveils-groundbreaking-macbook-pro-with-proled-xdr-display/tile/Apple-MacBook-Pro-with-PROLED-XDR-Display-Touch-experience-261028-lp.jpg.og.jpg"
let image = try #require(Attachment(url: imageURL, mimeType: "image/jpeg", title: "Apple unveils groundbreaking MacBook\u{00A0}Pro with PROLED XDR Display", sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: nil))
let html = ArticleRenderer.primaryImageHTML(image, articleTitle: "Apple unveils groundbreaking MacBook Pro with PROLED XDR Display\n")
#expect(!html.contains("nnw-primary-image-caption"))
}
// The body has a WordPress resized copy of the image.
@Test func primaryImageSkippedWhenBodyHasResizedCopy() {
let imageURL = "https://example.com/uploads/2026/11/heron.jpg"
let body = "<p><img src=\"https://example.com/uploads/2026/11/heron-1024x683.jpg\"></p>"
#expect(ArticleRenderer.primaryImage(imageLink: imageURL, attachments: nil, body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil)) == nil)
}
// The Atlantic’s “The Democrats’ Fight Over Israel Is Just Beginning”: every image is `original.jpg` in its own folder,
// and the body’s photos are different ones from the media:content image.
@Test func primaryImageShownWhenBodyHasDifferentImages() throws {
let imageURL = "https://cdn.theatlantic.com/thumbor/B7c5YtilnEF096Q7ZAci_1k_NF8=/media/img/mt/2026/11/2026_11_05_michigan_senate_4/original.jpg"
let attachment = try #require(Attachment(url: imageURL, mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: nil))
let body = "<figure class=\"full-width\"><img src=\"https://cdn.theatlantic.com/thumbor/0ETPM-UWHuoYrFvGb63KD7sdkg8=/https://cdn.theatlantic.com/media/img/posts/2026/11/2026_11_05_michigan_senate_5/original.jpg\" width=\"982\" height=\"737\" alt=\"people talk at a dinner at a restaurant\"></figure>"
#expect(ArticleRenderer.primaryImage(imageLink: nil, attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil))?.url == imageURL)
}
// The Atlantic’s “Can Beauty Make Us Good?”: a YouTube embed in the body, and the artwork in media:content.
@Test func primaryImageShownWhenBodyHasOnlyVideoEmbed() throws {
let imageURL = "https://cdn.theatlantic.com/thumbor/s_Z10FAOXCdfHK2Nt6l15hAJjZM=/0x25:1919x1104/media/img/mt/2026/11/Elaine_Scarry_Permanent_Questions_Ollie_Artwork_/original.jpg"
let attachment = try #require(Attachment(url: imageURL, mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: nil))
let body = "<p><iframe allowfullscreen=\"\" height=\"315\" src=\"https://www.youtube.com/embed/oymND7-uO-o?si=1WXJG8rZ_IaHorMQ\" title=\"YouTube video player\" width=\"560\"></iframe></p>"
#expect(ArticleRenderer.primaryImage(imageLink: nil, attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil))?.url == imageURL)
}
// The body embeds the enclosure image, with `&` escaped in the src attribute.
@@ -32,7 +92,18 @@ import Articles
let attachment = try #require(Attachment(url: imageURL, mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: 1000, height: 500, medium: .image))
let body = "<p><img src=\"https://storage.googleapis.com/gweb-cloudblog-publish/images/hero.max-1000x1000.png?w=1000&amp;h=500\"></p>"
let html = ArticleRenderer.enclosuresHTML(attachments: [attachment], body: body, imageURL: imageURL)
let html = ArticleRenderer.enclosuresHTML(attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil), posterURL: nil)
#expect(html.isEmpty)
}
// The Atlantic’s “Look Closer: A Mysterious Pair of Mittens”: the media:content image is a crop of the body’s photo.
@Test func imageEnclosureCopyInBodyIsSkipped() throws {
let imageURL = "https://cdn.theatlantic.com/thumbor/uIb4bjseN9GStI6B22iXaQrrOQU=/0x936:2400x2287/media/img/2026/11/Mittens_hi_res/original.jpg"
let attachment = try #require(Attachment(url: imageURL, mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: nil))
let body = "<figure><img src=\"https://cdn.theatlantic.com/thumbor/XHxMrVONnyavd9kLpZD6DGfTxbo=/https://cdn.theatlantic.com/media/img/posts/2026/11/Mittens_hi_res/original.jpg\" alt=\"a pair of mittens\"></figure>"
let html = ArticleRenderer.enclosuresHTML(attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil), posterURL: nil)
#expect(html.isEmpty)
}