Skip to content

Commit ddac472

Browse files
committed
feat: add the image serialization plugin api
1 parent a793448 commit ddac472

25 files changed

+769
-181
lines changed

Package.swift

+12-1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ let package = Package(
1919
name: "SnapshotTestingPlugin",
2020
targets: ["SnapshotTestingPlugin"]
2121
),
22+
.library(
23+
name: "ImageSerializationPlugin",
24+
targets: ["ImageSerializationPlugin"]
25+
),
2226
.library(
2327
name: "InlineSnapshotTesting",
2428
targets: ["InlineSnapshotTesting"]
@@ -30,9 +34,16 @@ let package = Package(
3034
targets: [
3135
.target(
3236
name: "SnapshotTesting",
33-
dependencies: ["SnapshotTestingPlugin"]
37+
dependencies: [
38+
"ImageSerializationPlugin",
39+
"SnapshotTestingPlugin"
40+
]
3441
),
3542
.target(name: "SnapshotTestingPlugin"),
43+
.target(
44+
name: "ImageSerializationPlugin",
45+
dependencies: ["SnapshotTestingPlugin"]
46+
),
3647
.target(
3748
name: "InlineSnapshotTesting",
3849
dependencies: [

README.md

+13-1
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ targets: [
230230
[available-strategies]: https://swiftpackageindex.com/pointfreeco/swift-snapshot-testing/main/documentation/snapshottesting/snapshotting
231231
[defining-strategies]: https://swiftpackageindex.com/pointfreeco/swift-snapshot-testing/main/documentation/snapshottesting/customstrategies
232232

233-
## Plug-ins
233+
## Strategies / Plug-ins
234234

235235
- [AccessibilitySnapshot](https://github.com/cashapp/AccessibilitySnapshot) adds easy regression
236236
testing for iOS accessibility.
@@ -273,6 +273,18 @@ targets: [
273273
- [SnapshotVision](https://github.com/gregersson/swift-snapshot-testing-vision) adds snapshot
274274
strategy for text recognition on views and images. Uses Apples Vision framework.
275275

276+
- [Image Serialization Plugin - HEIC](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
277+
strategy that create image as output to store them in `.heic` storage format which reduces file sizes
278+
in comparison to PNG.
279+
280+
- [Image Serialization Plugin - WEBP](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
281+
strategy that create image as output to store them in `.webp` storage format which reduces file sizes
282+
in comparison to PNG.
283+
284+
- [Image Serialization Plugin - JXL](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
285+
strategy that create image as output to store them in `.jxl` storage format which reduces file sizes
286+
in comparison to PNG.
287+
276288
Have you written your own SnapshotTesting plug-in?
277289
[Add it here](https://github.com/pointfreeco/swift-snapshot-testing/edit/master/README.md) and
278290
submit a pull request!
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#if canImport(SwiftUI)
2+
import Foundation
3+
import SnapshotTestingPlugin
4+
5+
#if canImport(UIKit)
6+
import UIKit.UIImage
7+
/// A type alias for `UIImage` when UIKit is available.
8+
public typealias SnapImage = UIImage
9+
#elseif canImport(AppKit)
10+
import AppKit.NSImage
11+
/// A type alias for `NSImage` when AppKit is available.
12+
public typealias SnapImage = NSImage
13+
#endif
14+
15+
/// A type alias that combines `ImageSerialization` and `SnapshotTestingPlugin` protocols.
16+
///
17+
/// `ImageSerializationPlugin` is a convenient alias used to conform to both `ImageSerialization` and `SnapshotTestingPlugin` protocols.
18+
/// This allows for image serialization plugins that also support snapshot testing, leveraging the Objective-C runtime while maintaining image serialization capabilities.
19+
public typealias ImageSerializationPlugin = ImageSerialization & SnapshotTestingPlugin
20+
21+
// TODO: async throws will be added later to encodeImage and decodeImage
22+
/// A protocol that defines methods for encoding and decoding images in various formats.
23+
///
24+
/// The `ImageSerialization` protocol is intended for classes that provide functionality to serialize (encode) and deserialize (decode) images.
25+
/// Implementing this protocol allows a class to specify the image format it supports and to handle image data conversions.
26+
/// This protocol is designed to be used in environments where SwiftUI is available and supports platform-specific image types via `SnapImage`.
27+
public protocol ImageSerialization {
28+
29+
/// The image format that the serialization plugin supports.
30+
///
31+
/// Each conforming class must specify the format it handles, using the `ImageSerializationFormat` enum. This property helps the `ImageSerializer`
32+
/// determine which plugin to use for a given format during image encoding and decoding.
33+
static var imageFormat: ImageSerializationFormat { get }
34+
35+
/// Encodes a `SnapImage` into a data representation.
36+
///
37+
/// This method converts the provided image into the appropriate data format. It may eventually support asynchronous operations and error handling using `async throws`.
38+
///
39+
/// - Parameter image: The image to be encoded.
40+
/// - Returns: The encoded image data, or `nil` if encoding fails.
41+
func encodeImage(_ image: SnapImage) -> Data?
42+
43+
/// Decodes image data into a `SnapImage`.
44+
///
45+
/// This method converts the provided data back into an image. It may eventually support asynchronous operations and error handling using `async throws`.
46+
///
47+
/// - Parameter data: The image data to be decoded.
48+
/// - Returns: The decoded image, or `nil` if decoding fails.
49+
func decodeImage(_ data: Data) -> SnapImage?
50+
}
51+
#endif
52+
53+
/// An enumeration that defines the image formats supported by the `ImageSerialization` protocol.
54+
///
55+
/// The `ImageSerializationFormat` enum is used to represent various image formats. It includes a predefined case for PNG images and a flexible case for plugins,
56+
/// allowing for the extension of formats via plugins identified by unique string values.
57+
public enum ImageSerializationFormat: RawRepresentable, Sendable, Equatable {
58+
59+
public static let defaultValue: ImageSerializationFormat = .png
60+
61+
/// Represents the default image format aka PNG.
62+
case png
63+
64+
/// Represents a custom image format provided by a plugin.
65+
///
66+
/// This case allows for the extension of image formats beyond the predefined ones by using a unique string identifier.
67+
case plugins(String)
68+
69+
/// Initializes an `ImageSerializationFormat` instance from a raw string value.
70+
///
71+
/// This initializer converts a string value into an appropriate `ImageSerializationFormat` case.
72+
///
73+
/// - Parameter rawValue: The string representation of the image format.
74+
public init?(rawValue: String) {
75+
switch rawValue {
76+
case "png": self = .png
77+
default: self = .plugins(rawValue)
78+
}
79+
}
80+
81+
/// The raw string value of the `ImageSerializationFormat`.
82+
///
83+
/// This computed property returns the string representation of the current image format.
84+
public var rawValue: String {
85+
switch self {
86+
case .png: return "png"
87+
case let .plugins(value): return value
88+
}
89+
}
90+
}

Sources/SnapshotTesting/AssertSnapshot.swift

+38
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,49 @@
11
import XCTest
2+
import ImageSerializationPlugin
23

34
#if canImport(Testing)
45
// NB: We are importing only the implementation of Testing because that framework is not available
56
// in Xcode UI test targets.
67
@_implementationOnly import Testing
78
#endif
89

10+
/// Whether or not to change the default output image format to something else.
11+
@available(
12+
*,
13+
deprecated,
14+
message:
15+
"Use 'withSnapshotTesting' to customize the image output format. See the documentation for more information."
16+
)
17+
public var imageFormat: ImageSerializationFormat {
18+
get {
19+
_imageFormat
20+
}
21+
set { _imageFormat = newValue }
22+
}
23+
24+
@_spi(Internals)
25+
public var _imageFormat: ImageSerializationFormat {
26+
get {
27+
#if canImport(Testing)
28+
if let test = Test.current {
29+
for trait in test.traits.reversed() {
30+
if let diffTool = (trait as? _SnapshotsTestTrait)?.configuration.imageFormat {
31+
return diffTool
32+
}
33+
}
34+
}
35+
#endif
36+
return __imageFormat
37+
}
38+
set {
39+
__imageFormat = newValue
40+
}
41+
}
42+
43+
@_spi(Internals)
44+
public var __imageFormat: ImageSerializationFormat = .defaultValue
45+
46+
947
/// Enhances failure messages with a command line diff tool expression that can be copied and pasted
1048
/// into a terminal.
1149
@available(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Image Serialization Plugin
2+
3+
Image Serialization Plugin is a plugin based on the PluginAPI, it provides support for encoding and decoding images. It leverages the plugin architecture to extend its support for different image formats without needing to modify the core system.
4+
5+
Plugins that conform to the `ImageSerializationPlugin` protocol can be registered into the `PluginRegistry` and used to encode or decode images in different formats, such as PNG, JPEG, WebP, HEIC, and more.
6+
7+
When a plugin supporting a specific image format is available, the `ImageSerializer` can dynamically choose the correct plugin based on the image format required, ensuring modularity and scalability in image handling.
8+
9+
10+
# Image Serialization Plugin
11+
12+
The **Image Serialization Plugin** extends the functionality of the SnapshotTesting library by enabling support for multiple image formats through a plugin architecture. This PluginAPI allows image encoding and decoding to be easily extended without modifying the core logic of the system.
13+
14+
## Overview
15+
16+
The **Image Serialization Plugin** provides an interface for encoding and decoding images in various formats. By conforming to both the `ImageSerialization` and `SnapshotTestingPlugin` protocols, it integrates with the broader plugin system, allowing for the seamless addition of new image formats. The default implementation supports PNG, but this architecture allows users to define custom plugins for other formats.
17+
18+
### Image Serialization Plugin Architecture
19+
20+
The **Image Serialization Plugin** relies on the PluginAPI that is a combination of protocols and a centralized registry to manage and discover plugins. The architecture allows for dynamic registration of image serialization plugins, which can be automatically discovered at runtime using the Objective-C runtime. This makes the system highly extensible, with plugins being automatically registered without the need for manual intervention.
21+
22+
#### Key Components:
23+
24+
1. **`ImageSerialization` Protocol**:
25+
- Defines the core methods for encoding and decoding images.
26+
- Requires plugins to specify the image format they support using the `ImageSerializationFormat` enum.
27+
- Provides methods for encoding (`encodeImage`) and decoding (`decodeImage`) images.
28+
29+
2. **`ImageSerializationFormat` Enum**:
30+
- Represents supported image formats.
31+
- Includes predefined formats such as `.png` and extensible formats through the `.plugins(String)` case, allowing for custom formats to be introduced via plugins.
32+
33+
3. **`ImageSerializer` Class**:
34+
- Responsible for encoding and decoding images using the registered plugins.
35+
- Retrieves available plugins from the `PluginRegistry` and uses the first matching plugin for the requested image format.
36+
- Provides default implementations for PNG encoding and decoding if no plugin is available for a given format.
37+
38+
#### Example Plugin Flow:
39+
40+
1. **Plugin Discovery**:
41+
- Plugins are automatically discovered at runtime through the Objective-C runtime, which identifies classes that conform to both the `ImageSerialization` and `SnapshotTestingPlugin` protocols.
42+
43+
2. **Plugin Registration**:
44+
- Each plugin registers itself with the `PluginRegistry`, allowing it to be retrieved when needed for image serialization.
45+
46+
3. **Image Encoding/Decoding**:
47+
- When an image needs to be serialized, the `ImageSerializer` checks the available plugins for one that supports the requested format.
48+
- If no plugin is found, it defaults to the built-in PNG encoding/decoding methods.
49+
50+
#### Extensibility
51+
52+
The plugin architecture allows developers to introduce new image formats without modifying the core SnapshotTesting library. By creating a new plugin that conforms to `ImageSerializationPlugin`, you can easily add support for additional image formats.
53+
54+
Here are a few example plugins demonstrating how to extend the library with new image formats:
55+
56+
- **[Image Serialization Plugin - HEIC](https://github.com/mackoj/swift-snapshot-testing-plugin-heic)**: Enables storing images in the `.heic` format, which reduces file sizes compared to PNG.
57+
- **[Image Serialization Plugin - WEBP](https://github.com/mackoj/swift-snapshot-testing-plugin-webp)**: Allows storing images in the `.webp` format, which offers better compression than PNG.
58+
- **[Image Serialization Plugin - JXL](https://github.com/mackoj/swift-snapshot-testing-plugin-jxl)**: Facilitates storing images in the `.jxl` format, which provides superior compression and quality compared to PNG.
59+
60+
## Usage
61+
62+
For example, if you want to use JPEG XL as a new image format for your snapshots, you can follow these steps. This approach applies to any image format as long as you have a plugin that conforms to `ImageSerializationPlugin`.
63+
64+
1. **Add the Dependency**: Include the appropriate image serialization plugin as a dependency in your `Package.swift` file. For JPEG XL, it would look like this:
65+
66+
```swift
67+
.package(url: "https://github.com/mackoj/swift-snapshot-testing-plugin-jxl.git", revision: "0.0.1"),
68+
```
69+
70+
2. **Link to Your Test Target**: Add the image serialization plugin to your test target's dependencies:
71+
72+
```swift
73+
.product(name: "JXLImageSerializer", package: "swift-snapshot-testing-plugin-jxl"),
74+
```
75+
76+
3. **Import and Set Up**: In your test file, import the serializer and configure the image format in the `setUp()` method:
77+
78+
```swift
79+
import JXLImageSerializer
80+
81+
override class func setUp() {
82+
SnapshotTesting.imageFormat = JXLImageSerializer.imageFormat
83+
}
84+
```
85+
86+
Alternatively, you can specify the image format for individual assertions:
87+
88+
```swift
89+
assertSnapshot(of: label, as: .image(precision: 0.9, format: JXLImageSerializer.imageFormat))
90+
```
91+
92+
This setup demonstrates how to integrate a specific image format plugin. Replace `JXLImageSerializer` with the appropriate plugin and format for other image formats.

Sources/SnapshotTesting/Documentation.docc/SnapshotTesting.md

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ Powerfully flexible snapshot testing.
2626
### Plugins
2727

2828
- <doc:Plugins>
29+
- <doc:ImageSerializationPlugin>
2930

3031
### Deprecations
3132

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#if canImport(SwiftUI)
2+
import Foundation
3+
import ImageSerializationPlugin
4+
5+
#if canImport(UIKit)
6+
import UIKit
7+
#elseif canImport(AppKit)
8+
import AppKit
9+
#endif
10+
11+
/// A class responsible for encoding and decoding images using various image serialization plugins.
12+
///
13+
/// The `ImageSerializer` class leverages plugins that conform to the `ImageSerialization` protocol to encode and decode images in different formats.
14+
/// It automatically retrieves all available image serialization plugins from the `PluginRegistry` and uses them based on the specified `ImageSerializationFormat`.
15+
/// If no plugin is found for the requested format, it defaults to using PNG encoding/decoding.
16+
class ImageSerializer {
17+
18+
/// A collection of plugins that conform to the `ImageSerialization` protocol.
19+
private let plugins: [ImageSerialization]
20+
21+
init() {
22+
self.plugins = PluginRegistry.allPlugins()
23+
}
24+
25+
// TODO: async throws will be added later
26+
/// Encodes a given image into the specified image format using the appropriate plugin.
27+
///
28+
/// This method attempts to encode the provided `SnapImage` into the desired format using the first plugin that supports the specified `ImageSerializationFormat`.
29+
/// If no plugin is found for the format, it defaults to encoding the image as PNG.
30+
///
31+
/// - Parameters:
32+
/// - image: The `SnapImage` to encode.
33+
/// - imageFormat: The format in which to encode the image.
34+
/// - Returns: The encoded image data, or `nil` if encoding fails.
35+
func encodeImage(_ image: SnapImage, imageFormat: ImageSerializationFormat = .defaultValue) -> Data? {
36+
for plugin in self.plugins {
37+
if type(of: plugin).imageFormat == imageFormat {
38+
return plugin.encodeImage(image)
39+
}
40+
}
41+
// Default to PNG
42+
return encodePNG(image)
43+
}
44+
45+
// TODO: async throws will be added later
46+
/// Decodes image data into a `SnapImage` using the appropriate plugin based on the specified image format.
47+
///
48+
/// This method attempts to decode the provided data into a `SnapImage` using the first plugin that supports the specified `ImageSerializationFormat`.
49+
/// If no plugin is found for the format, it defaults to decoding the data as PNG.
50+
///
51+
/// - Parameters:
52+
/// - data: The image data to decode.
53+
/// - imageFormat: The format in which the image data is encoded.
54+
/// - Returns: The decoded `SnapImage`, or `nil` if decoding fails.
55+
func decodeImage(_ data: Data, imageFormat: ImageSerializationFormat = .defaultValue) -> SnapImage? {
56+
for plugin in self.plugins {
57+
if type(of: plugin).imageFormat == imageFormat {
58+
return plugin.decodeImage(data)
59+
}
60+
}
61+
// Default to PNG
62+
return decodePNG(data)
63+
}
64+
65+
// MARK: - Actual default Image Serializer
66+
67+
/// Encodes a `SnapImage` as PNG data.
68+
///
69+
/// This method provides a default implementation for encoding images as PNG. It is used as a fallback if no suitable plugin is found for the requested format.
70+
///
71+
/// - Parameter image: The `SnapImage` to encode.
72+
/// - Returns: The encoded PNG data, or `nil` if encoding fails.
73+
private func encodePNG(_ image: SnapImage) -> Data? {
74+
#if canImport(UIKit)
75+
return image.pngData()
76+
#elseif canImport(AppKit)
77+
guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
78+
return nil
79+
}
80+
let bitmapRep = NSBitmapImageRep(cgImage: cgImage)
81+
return bitmapRep.representation(using: .png, properties: [:])
82+
#endif
83+
}
84+
85+
/// Decodes PNG data into a `SnapImage`.
86+
///
87+
/// This method provides a default implementation for decoding PNG data into a `SnapImage`. It is used as a fallback if no suitable plugin is found for the requested format.
88+
///
89+
/// - Parameter data: The PNG data to decode.
90+
/// - Returns: The decoded `SnapImage`, or `nil` if decoding fails.
91+
private func decodePNG(_ data: Data) -> SnapImage? {
92+
#if canImport(UIKit)
93+
return UIImage(data: data)
94+
#elseif canImport(AppKit)
95+
return NSImage(data: data)
96+
#endif
97+
}
98+
}
99+
#endif

0 commit comments

Comments
 (0)