Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .claude/rules/data-layer.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ Global audio playback state injected via `@Environment`. Available everywhere. M
## Multi-platform

- **watchOS (`WatchApp/`)** — Minimal feed reader: `FeedMainViewModel` fetches news via `FeedLibrary`, simple list with detail views.
- **iOS Widget (`Widget/`)** — Timeline provider fetches latest posts, renders with `WidgetView`. Live Activities via `MacMagazineWidgetLiveActivity`.
- **iOS Widget (`Widget/`)** — Timeline provider fetches latest posts (15 s deadline), downloads only the thumbnails the family shows in parallel (10 s timeout each) and downscales them with `WidgetImageDownscaler`, renders with `WidgetView`. Refreshes every 30 min (15 min after a failed or empty fetch, via `WidgetRefreshSchedule`) and falls back to the last good posts cached per family (`WidgetPostsCache`, Caches directory). Live Activities via `MacMagazineWidgetLiveActivity`.
- **watchOS Widget (`WatchWidget/`)** — Separate widget extension.
- **Widget data model** — `WidgetData` (postId, title, thumbnail, pubDate, link).
- macOS and visionOS via `#if os()` where needed. Primary targets: iOS and watchOS.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Foundation
import ImageIO
import UniformTypeIdentifiers

/// Shrinks widget thumbnails so timeline entries stay well inside WidgetKit's memory limits.
public enum WidgetImageDownscaler {
public static let compressionQuality = 0.8

/// Downscales image data to a compact JPEG whose shorter side is at least `targetPixelSize`.
///
/// The aspect ratio is kept and images already at or below the target are re-encoded, never upscaled.
/// - Returns: JPEG data, or `nil` when the input can't be decoded.
public static func downscale(_ data: Data, targetPixelSize: Int) -> Data? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
let width = properties[kCGImagePropertyPixelWidth] as? Int,
let height = properties[kCGImagePropertyPixelHeight] as? Int,
width > 0, height > 0 else {
return nil
}

let shorterSide = min(width, height)
let longerSide = max(width, height)
let maxPixelSize = shorterSide <= targetPixelSize
? longerSide
: Int((Double(targetPixelSize) * Double(longerSide) / Double(shorterSide)).rounded(.up))

let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize
]
guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {
return nil
}

let output = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else {
return nil
}
let destinationOptions: [CFString: Any] = [kCGImageDestinationLossyCompressionQuality: compressionQuality]
CGImageDestinationAddImage(destination, image, destinationOptions as CFDictionary)
guard CGImageDestinationFinalize(destination) else { return nil }
return output as Data
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Foundation

/// Keeps the last successfully fetched widget posts on disk so a failed refresh doesn't blank the widget.
public struct WidgetPostsCache: Sendable {
public let fileURL: URL

public init(fileURL: URL) {
self.fileURL = fileURL
}

/// Returns the cached posts, or an empty array when the file is missing or can't be decoded.
public func load() -> [WidgetData] {
guard let data = try? Data(contentsOf: fileURL),
let posts = try? JSONDecoder().decode([WidgetData].self, from: data) else {
return []
}
return posts
}

/// Overwrites the cache with `posts`. An empty array is ignored so the last good posts survive.
public func save(_ posts: [WidgetData]) throws {
guard !posts.isEmpty else { return }
let data = try JSONEncoder().encode(posts)
try data.write(to: fileURL, options: .atomic)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import Foundation

/// When the widget timeline asks WidgetKit to reload next.
public enum WidgetRefreshSchedule {
public static let successInterval: TimeInterval = 30 * 60
public static let failureInterval: TimeInterval = 15 * 60

/// Returns the next refresh date: `successInterval` after a fetch with posts, `failureInterval` otherwise.
public static func nextRefresh(after now: Date, succeeded: Bool) -> Date {
now.addingTimeInterval(succeeded ? successInterval : failureInterval)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import CoreGraphics
@testable import FeedLibrary
import Foundation
import ImageIO
import Testing
import UniformTypeIdentifiers

@Suite("WidgetImageDownscaler Tests")
struct WidgetImageDownscalerTests {

// MARK: - Downscaling Tests

@Test("Large landscape image is downscaled to fill the target")
func downscalesLargeLandscapeImage() throws {
// Given
let input = try makePNG(width: 2000, height: 1000)

// When
let output = try #require(WidgetImageDownscaler.downscale(input, targetPixelSize: 500))

// Then
let size = try pixelSize(of: output)
let shorterSide = min(size.width, size.height)
#expect(shorterSide >= 500)
#expect(shorterSide < 1000)
let ratio = Double(size.width) / Double(size.height)
#expect(abs(ratio - 2.0) / 2.0 < 0.01)
#expect(try imageType(of: output) == UTType.jpeg.identifier)
}

@Test("Small image is re-encoded but not upscaled")
func doesNotUpscaleSmallImage() throws {
// Given
let input = try makePNG(width: 100, height: 50)

// When
let output = try #require(WidgetImageDownscaler.downscale(input, targetPixelSize: 500))

// Then
let size = try pixelSize(of: output)
#expect(size.width == 100)
#expect(size.height == 50)
#expect(try imageType(of: output) == UTType.jpeg.identifier)
}

@Test("Undecodable data returns nil")
func undecodableDataReturnsNil() {
// Given
let input = Data("not an image".utf8)

// When
let output = WidgetImageDownscaler.downscale(input, targetPixelSize: 500)

// Then
#expect(output == nil)
}

@Test("Empty data returns nil")
func emptyDataReturnsNil() {
#expect(WidgetImageDownscaler.downscale(Data(), targetPixelSize: 500) == nil)
}
}

// MARK: - Helpers

private extension WidgetImageDownscalerTests {
struct FixtureError: Error {}

func makePNG(width: Int, height: Int) throws -> Data {
guard let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else { throw FixtureError() }
context.setFillColor(CGColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1))
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let image = context.makeImage() else { throw FixtureError() }

let output = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(output, UTType.png.identifier as CFString, 1, nil) else {
throw FixtureError()
}
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else { throw FixtureError() }
return output as Data
}

func pixelSize(of data: Data) throws -> (width: Int, height: Int) {
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
let width = properties[kCGImagePropertyPixelWidth] as? Int,
let height = properties[kCGImagePropertyPixelHeight] as? Int else {
throw FixtureError()
}
return (width, height)
}

func imageType(of data: Data) throws -> String {
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
let type = CGImageSourceGetType(source) else {
throw FixtureError()
}
return type as String
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
@testable import FeedLibrary
import Foundation
import Testing

@Suite("WidgetPostsCache Tests")
struct WidgetPostsCacheTests {
private let directory: URL
private let cache: WidgetPostsCache

init() throws {
directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
cache = WidgetPostsCache(fileURL: directory.appending(path: "widget-posts-systemSmall.json"))
}

private let posts = [
WidgetData(
postId: "1",
title: "First",
thumbnail: "https://example.com/1.jpg",
pubDate: Date(timeIntervalSince1970: 1_700_000_000),
link: "https://example.com/1",
imageData: Data([0xFF, 0xD8, 0xFF])
),
WidgetData(
postId: "2",
title: "Second",
thumbnail: "https://example.com/2.jpg",
pubDate: Date(timeIntervalSince1970: 1_700_000_100),
link: "https://example.com/2"
)
]

@Test("Saved posts load back unchanged")
func roundTrip() throws {
try cache.save(posts)

#expect(cache.load() == posts)
}

@Test("Missing file loads as empty")
func missingFileLoadsEmpty() {
#expect(cache.load().isEmpty)
}

@Test("Corrupt file loads as empty")
func corruptFileLoadsEmpty() throws {
try Data("not json".utf8).write(to: cache.fileURL)

#expect(cache.load().isEmpty)
}

@Test("Saving an empty array keeps the existing posts")
func savingEmptyKeepsExistingPosts() throws {
try cache.save(posts)

try cache.save([])

#expect(cache.load() == posts)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
@testable import FeedLibrary
import Foundation
import Testing

@Suite("WidgetRefreshSchedule Tests")
struct WidgetRefreshScheduleTests {
private let now = Date(timeIntervalSince1970: 1_700_000_000)

@Test("Successful fetch refreshes after 30 minutes")
func successRefreshesAfterThirtyMinutes() {
let next = WidgetRefreshSchedule.nextRefresh(after: now, succeeded: true)

#expect(next == now.addingTimeInterval(30 * 60))
#expect(WidgetRefreshSchedule.successInterval == 30 * 60)
}

@Test("Failed or empty fetch refreshes after 15 minutes")
func failureRefreshesAfterFifteenMinutes() {
let next = WidgetRefreshSchedule.nextRefresh(after: now, succeeded: false)

#expect(next == now.addingTimeInterval(15 * 60))
#expect(WidgetRefreshSchedule.failureInterval == 15 * 60)
}
}
Loading
Loading