react-native-nitro-image-pipeline 1.3.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +103 -11
  2. package/android/CMakeLists.txt +4 -0
  3. package/android/src/main/cpp/GaussianBlur.cpp +165 -0
  4. package/android/src/main/cpp/GaussianBlur.hpp +52 -0
  5. package/android/src/main/cpp/GaussianBlurJni.cpp +50 -0
  6. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/HybridNitroImagePipeline.kt +153 -74
  7. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/PipelineImageLoader.kt +177 -0
  8. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/transform/BlurTransformation.kt +36 -81
  9. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/transform/HardwareBitmapTransformation.kt +45 -0
  10. package/ios/GaussianBlur.swift +48 -9
  11. package/ios/HybridNitroImagePipeline.swift +79 -33
  12. package/ios/PipelineImageLoader.swift +195 -0
  13. package/ios/RoundedCornersProcessor.swift +5 -0
  14. package/lib/commonjs/NativePipelineImage.js +71 -0
  15. package/lib/commonjs/NativePipelineImage.js.map +1 -0
  16. package/lib/commonjs/index.js +14 -0
  17. package/lib/commonjs/index.js.map +1 -1
  18. package/lib/commonjs/usePipelineImageLoader.js +69 -0
  19. package/lib/commonjs/usePipelineImageLoader.js.map +1 -0
  20. package/lib/module/NativePipelineImage.js +67 -0
  21. package/lib/module/NativePipelineImage.js.map +1 -0
  22. package/lib/module/index.js +2 -0
  23. package/lib/module/index.js.map +1 -1
  24. package/lib/module/usePipelineImageLoader.js +65 -0
  25. package/lib/module/usePipelineImageLoader.js.map +1 -0
  26. package/lib/typescript/src/NativePipelineImage.d.ts +66 -0
  27. package/lib/typescript/src/NativePipelineImage.d.ts.map +1 -0
  28. package/lib/typescript/src/index.d.ts +3 -1
  29. package/lib/typescript/src/index.d.ts.map +1 -1
  30. package/lib/typescript/src/specs/nitro-image-toolkit.nitro.d.ts +54 -1
  31. package/lib/typescript/src/specs/nitro-image-toolkit.nitro.d.ts.map +1 -1
  32. package/lib/typescript/src/usePipelineImageLoader.d.ts +15 -0
  33. package/lib/typescript/src/usePipelineImageLoader.d.ts.map +1 -0
  34. package/nitrogen/generated/android/c++/JHybridNitroImagePipelineSpec.cpp +17 -0
  35. package/nitrogen/generated/android/c++/JHybridNitroImagePipelineSpec.hpp +2 -0
  36. package/nitrogen/generated/android/c++/JViewOptions.hpp +77 -0
  37. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroimagepipeline/HybridNitroImagePipelineSpec.kt +9 -0
  38. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroimagepipeline/ViewOptions.kt +66 -0
  39. package/nitrogen/generated/ios/NitroImagePipeline-Swift-Cxx-Bridge.cpp +10 -0
  40. package/nitrogen/generated/ios/NitroImagePipeline-Swift-Cxx-Bridge.hpp +53 -0
  41. package/nitrogen/generated/ios/NitroImagePipeline-Swift-Cxx-Umbrella.hpp +8 -0
  42. package/nitrogen/generated/ios/c++/HybridNitroImagePipelineSpecSwift.hpp +20 -0
  43. package/nitrogen/generated/ios/swift/HybridNitroImagePipelineSpec.swift +2 -0
  44. package/nitrogen/generated/ios/swift/HybridNitroImagePipelineSpec_cxx.swift +26 -0
  45. package/nitrogen/generated/ios/swift/ViewOptions.swift +101 -0
  46. package/nitrogen/generated/shared/c++/HybridNitroImagePipelineSpec.cpp +2 -0
  47. package/nitrogen/generated/shared/c++/HybridNitroImagePipelineSpec.hpp +8 -0
  48. package/nitrogen/generated/shared/c++/ViewOptions.hpp +104 -0
  49. package/package.json +4 -3
  50. package/src/NativePipelineImage.tsx +103 -0
  51. package/src/index.ts +7 -0
  52. package/src/specs/nitro-image-toolkit.nitro.ts +56 -1
  53. package/src/usePipelineImageLoader.ts +82 -0
@@ -29,25 +29,30 @@ enum GaussianBlur {
29
29
  // Normalise to premultiplied ARGB8888 — vImageBoxConvolve_ARGB8888
30
30
  // needs four 8-bit channels, and premultiplied alpha is what keeps
31
31
  // transparent edges from bleeding dark halos into the blur.
32
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
33
+ let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
32
34
  guard var format = vImage_CGImageFormat(
33
35
  bitsPerComponent: 8,
34
36
  bitsPerPixel: 32,
35
- colorSpace: CGColorSpaceCreateDeviceRGB(),
36
- bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue),
37
+ colorSpace: colorSpace,
38
+ bitmapInfo: bitmapInfo,
37
39
  renderingIntent: .defaultIntent
38
40
  ) else { return nil }
39
41
 
42
+ // Both buffers are freed on exit, except the one handed over to the
43
+ // result CGImage below (`handedOver`), which is freed with the image.
44
+ var handedOver: UnsafeMutableRawPointer?
40
45
  var source = vImage_Buffer()
41
46
  guard vImageBuffer_InitWithCGImage(
42
47
  &source, &format, nil, cgImage, vImage_Flags(kvImageNoFlags)
43
48
  ) == kvImageNoError else { return nil }
44
- defer { free(source.data) }
49
+ defer { if source.data != handedOver { free(source.data) } }
45
50
 
46
51
  var scratch = vImage_Buffer()
47
52
  guard vImageBuffer_Init(
48
53
  &scratch, source.height, source.width, 32, vImage_Flags(kvImageNoFlags)
49
54
  ) == kvImageNoError else { return nil }
50
- defer { free(scratch.data) }
55
+ defer { if scratch.data != handedOver { free(scratch.data) } }
51
56
 
52
57
  // kvImageEdgeExtend clamps at the borders instead of sampling
53
58
  // transparent black, so the image keeps its edges instead of fading
@@ -75,12 +80,46 @@ enum GaussianBlur {
75
80
  swap(&input, &output)
76
81
  }
77
82
 
78
- var error = vImage_Error(kvImageNoError)
79
- guard let blurred = vImageCreateCGImageFromBuffer(
80
- &input, &format, nil, nil, vImage_Flags(kvImageNoFlags), &error
81
- )?.takeRetainedValue(), error == kvImageNoError else { return nil }
83
+ // Ownership of the result buffer moves to the CGImage (no copy);
84
+ // `handedOver` keeps the exits above from freeing it a second time.
85
+ return makeImage(from: input, colorSpace: colorSpace, bitmapInfo: bitmapInfo, handedOver: &handedOver)
86
+ }
87
+
88
+ /// Wraps `buffer` in a CGImage instead of copying it (one full-bitmap
89
+ /// memcpy less per blur). Ownership is explicit: once the data provider
90
+ /// exists, it frees the buffer — together with the image, or right away
91
+ /// if creating the image fails and the provider is released — so
92
+ /// `handedOver` is set to the buffer's data as soon as that is the case.
93
+ /// (vImageCreateCGImageFromBuffer with kvImageNoAllocate would do the
94
+ /// same, but leaves unspecified whether its free callback runs when the
95
+ /// call fails.)
96
+ private static func makeImage(
97
+ from buffer: vImage_Buffer,
98
+ colorSpace: CGColorSpace,
99
+ bitmapInfo: CGBitmapInfo,
100
+ handedOver: inout UnsafeMutableRawPointer?
101
+ ) -> CGImage? {
102
+ guard let provider = CGDataProvider(
103
+ dataInfo: nil,
104
+ data: buffer.data,
105
+ size: buffer.rowBytes * Int(buffer.height),
106
+ releaseData: { _, data, _ in free(UnsafeMutableRawPointer(mutating: data)) }
107
+ ) else { return nil }
108
+ handedOver = buffer.data
82
109
 
83
- return blurred
110
+ return CGImage(
111
+ width: Int(buffer.width),
112
+ height: Int(buffer.height),
113
+ bitsPerComponent: 8,
114
+ bitsPerPixel: 32,
115
+ bytesPerRow: buffer.rowBytes,
116
+ space: colorSpace,
117
+ bitmapInfo: bitmapInfo,
118
+ provider: provider,
119
+ decode: nil,
120
+ shouldInterpolate: true,
121
+ intent: .defaultIntent
122
+ )
84
123
  }
85
124
 
86
125
  /// Widths for the three box-blur passes that approximate a Gaussian of
@@ -12,7 +12,7 @@ import Nuke
12
12
 
13
13
  import UIKit
14
14
 
15
- private class HybridImage: HybridImageSpec, NativeImage {
15
+ class HybridImage: HybridImageSpec, NativeImage {
16
16
  let uiImage: UIImage
17
17
 
18
18
  // PNG encoding is expensive; encode once and reuse for both
@@ -21,26 +21,22 @@ private class HybridImage: HybridImageSpec, NativeImage {
21
21
  // doesn't pin its encoding forever.
22
22
  private let pngLock = NSLock()
23
23
  private var cachedPngData: Data?
24
+ // Registered only once there is encoded data to drop: most images are
25
+ // only ever displayed, and an observer per image is wasted work in a
26
+ // list of hundreds. Guarded by `pngLock` like the data it protects.
24
27
  private var memoryWarningObserver: (any NSObjectProtocol)?
25
28
 
26
29
  init(uiImage: UIImage) {
27
30
  self.uiImage = uiImage
28
31
  super.init()
29
- memoryWarningObserver = NotificationCenter.default.addObserver(
30
- forName: UIApplication.didReceiveMemoryWarningNotification,
31
- object: nil,
32
- queue: nil
33
- ) { [weak self] _ in
34
- guard let self else { return }
35
- self.pngLock.lock()
36
- self.cachedPngData = nil
37
- self.pngLock.unlock()
38
- }
39
32
  }
40
33
 
41
34
  deinit {
42
- if let memoryWarningObserver {
43
- NotificationCenter.default.removeObserver(memoryWarningObserver)
35
+ pngLock.lock()
36
+ let observer = memoryWarningObserver
37
+ pngLock.unlock()
38
+ if let observer {
39
+ NotificationCenter.default.removeObserver(observer)
44
40
  }
45
41
  }
46
42
 
@@ -52,6 +48,18 @@ private class HybridImage: HybridImageSpec, NativeImage {
52
48
  }
53
49
  let data = uiImage.pngData()
54
50
  cachedPngData = data
51
+ if data != nil, memoryWarningObserver == nil {
52
+ memoryWarningObserver = NotificationCenter.default.addObserver(
53
+ forName: UIApplication.didReceiveMemoryWarningNotification,
54
+ object: nil,
55
+ queue: nil
56
+ ) { [weak self] _ in
57
+ guard let self else { return }
58
+ self.pngLock.lock()
59
+ self.cachedPngData = nil
60
+ self.pngLock.unlock()
61
+ }
62
+ }
55
63
  return data
56
64
  }
57
65
 
@@ -89,7 +97,7 @@ class HybridNitroImagePipeline: HybridNitroImagePipelineSpec {
89
97
  // users in the host app are left untouched, and repeated instantiation
90
98
  // (e.g. Metro reloads) never puts two DataCache instances on the same
91
99
  // directory.
92
- private static let sharedPipeline: ImagePipeline = {
100
+ static let sharedPipeline: ImagePipeline = {
93
101
  var configuration = ImagePipeline.Configuration.withDataCache
94
102
  // Store processed (blurred/rounded) variants on disk in addition to
95
103
  // the original download, so they survive memory eviction and
@@ -105,6 +113,15 @@ class HybridNitroImagePipeline: HybridNitroImagePipelineSpec {
105
113
  configuration.imageCache = ImageCache(
106
114
  costLimit: min(ImageCache.defaultCostLimit, 128 * 1024 * 1024)
107
115
  )
116
+ // Nuke decodes on a serial queue by default, so a screenful of new
117
+ // list cells is decoded one image at a time however many cores the
118
+ // device has. Decode in parallel instead — capped so a burst of
119
+ // full-resolution decodes (no `resize`) can't multiply peak memory
120
+ // by the core count. Processing stays at Nuke's default of 2: the
121
+ // blur allocates several full-size buffers per image.
122
+ configuration.imageDecodingQueue.maxConcurrentOperationCount = min(
123
+ 4, max(1, ProcessInfo.processInfo.activeProcessorCount)
124
+ )
108
125
  return ImagePipeline(configuration: configuration)
109
126
  }()
110
127
 
@@ -181,36 +198,49 @@ class HybridNitroImagePipeline: HybridNitroImagePipelineSpec {
181
198
  return processors
182
199
  }
183
200
 
201
+ /// The `ImageRequest` for `url` with `options` applied — shared by
202
+ /// `loadImage` and `PipelineImageLoader` so both hit the same caches with
203
+ /// identical cache keys.
204
+ static func makeRequest(url: URL, options: Options?) -> ImageRequest {
205
+ var imgRequest = ImageRequest(
206
+ url: url,
207
+ processors: processors(for: options),
208
+ options: cacheOptions(for: options?.cache)
209
+ )
210
+ // With a target size known, decode near it (aspect-fill, so the
211
+ // decoded image always covers the target) instead of at full
212
+ // resolution — a 48 MP photo displayed as a 300 pt card would
213
+ // otherwise decompress to ~190 MB before Resize shrinks it.
214
+ // Matches Android, where the request's size() drives subsampling;
215
+ // the exact size and crop still come from the Resize processor.
216
+ if let size = resizeSize(for: options) {
217
+ imgRequest.thumbnail = ImageRequest.ThumbnailOptions(
218
+ size: size,
219
+ unit: .pixels,
220
+ contentMode: .aspectFill
221
+ )
222
+ }
223
+ return imgRequest
224
+ }
225
+
184
226
  func loadImage(url: String, options: Options?) throws -> Promise<any HybridImageSpec> {
185
227
  return Promise.async {
186
228
  guard let imageUrl = URL(string: url) else {
187
229
  throw RuntimeError.error(withMessage: "Invalid URL: \(url)")
188
230
  }
189
231
 
190
- var imgRequest = ImageRequest(
191
- url: imageUrl,
192
- processors: Self.processors(for: options),
193
- options: Self.cacheOptions(for: options?.cache)
194
- )
195
- // With a target size known, decode near it (aspect-fill, so the
196
- // decoded image always covers the target) instead of at full
197
- // resolution — a 48 MP photo displayed as a 300 pt card would
198
- // otherwise decompress to ~190 MB before Resize shrinks it.
199
- // Matches Android, where the request's size() drives subsampling;
200
- // the exact size and crop still come from the Resize processor.
201
- if let size = Self.resizeSize(for: options) {
202
- imgRequest.thumbnail = ImageRequest.ThumbnailOptions(
203
- size: size,
204
- unit: .pixels,
205
- contentMode: .aspectFill
206
- )
207
- }
208
-
232
+ let imgRequest = Self.makeRequest(url: imageUrl, options: options)
209
233
  let image = try await self.pipeline.image(for: imgRequest)
210
234
  return HybridImage(uiImage: image)
211
235
  }
212
236
  }
213
237
 
238
+ func createImageLoader(url: String, options: ViewOptions?) throws -> any HybridImageLoaderSpec {
239
+ // An unparseable URL fails at load time, not here — matching Android,
240
+ // where Coil validates the URL only when the request runs.
241
+ return PipelineImageLoader(url: url, options: options)
242
+ }
243
+
214
244
  func preLoadImage(url: String) throws -> Promise<Void> {
215
245
  return Promise.async {
216
246
  guard let imageUrl = URL(string: url) else {
@@ -228,6 +258,22 @@ class HybridNitroImagePipeline: HybridNitroImagePipelineSpec {
228
258
  }
229
259
  }
230
260
 
261
+ func setMemoryCacheLimit(bytes: Double) throws {
262
+ guard bytes >= 0, bytes.isFinite else {
263
+ throw RuntimeError.error(
264
+ withMessage: "Memory cache limit must be a non-negative, finite number of bytes (got \(bytes))"
265
+ )
266
+ }
267
+ guard let cache = pipeline.configuration.imageCache as? ImageCache else { return }
268
+ // Double(Int.max) rounds up to 2^63, so Int(_:) of the clamped value
269
+ // would trap; branch instead of min-ing.
270
+ let limit = bytes >= Double(Int.max) ? Int.max : Int(bytes)
271
+ cache.costLimit = limit
272
+ // Setting the limit only affects future inserts; evict down to it now
273
+ // so the call frees memory immediately.
274
+ cache.trim(toCost: limit)
275
+ }
276
+
231
277
  func clearCache() throws -> Promise<Void> {
232
278
  return Promise.async {
233
279
  self.pipeline.cache.removeAll()
@@ -0,0 +1,195 @@
1
+ //
2
+ // PipelineImageLoader.swift
3
+ // NitroImagePipeline
4
+ //
5
+
6
+ import Foundation
7
+ import NitroImage
8
+ import NitroModules
9
+ import Nuke
10
+ import UIKit
11
+
12
+ /// An `ImageLoader` (react-native-nitro-image) backed by the shared pipeline.
13
+ ///
14
+ /// `<NativeNitroImage image={loader} />` drives it entirely natively: the view
15
+ /// calls `requestImage` when it attaches to a window and `dropImage` when it
16
+ /// detaches. The load runs at the view's laid-out size (× screen scale) with
17
+ /// no JS round trips, and detaching cancels the request and releases the
18
+ /// bitmap — the decoded image stays in the shared memory/disk caches, so
19
+ /// re-attaching (list recycling) is instant.
20
+ ///
21
+ /// `ViewOptions` values are in points; this class converts them to the
22
+ /// pixel-based `Options` of the shared request builder using the view's
23
+ /// display scale, so cache keys match an equivalent `loadImage` call.
24
+ class PipelineImageLoader: HybridImageLoaderSpec {
25
+ private let url: String
26
+ private let options: ViewOptions?
27
+
28
+ // Per-view in-flight work, keyed by the view's identity, so a loader
29
+ // shared between several views cancels only the right request. Confined
30
+ // to the main thread — every access happens inside a main-queue block.
31
+ private var tasks: [ObjectIdentifier: Task<Void, Never>] = [:]
32
+ private var pendingLayouts: [ObjectIdentifier: NSKeyValueObservation] = [:]
33
+
34
+ init(url: String, options: ViewOptions?) {
35
+ self.url = url
36
+ self.options = options
37
+ }
38
+
39
+ private var pipeline: ImagePipeline { HybridNitroImagePipeline.sharedPipeline }
40
+
41
+ /// visionOS has no `UIScreen.main`; there UIKit reports 2.0 as the
42
+ /// display scale of trait environments.
43
+ private static var fallbackScale: CGFloat {
44
+ #if os(visionOS)
45
+ return 2.0
46
+ #else
47
+ return UIScreen.main.scale
48
+ #endif
49
+ }
50
+
51
+ private static func displayScale(of view: UIView) -> CGFloat {
52
+ let scale = view.traitCollection.displayScale
53
+ // 0 means "unspecified" (view not in a hierarchy yet).
54
+ return scale > 0 ? scale : fallbackScale
55
+ }
56
+
57
+ /// The point-based `ViewOptions` as pixel-based `Options`, resolved
58
+ /// against `scale` and the target size in pixels.
59
+ private func pixelOptions(scale: CGFloat, sizePx: CGSize?) -> Options {
60
+ let cornerRadius = options?.cornerRadius.map { radius -> Variant_Double_CornerRadii in
61
+ switch radius {
62
+ case .first(let uniform):
63
+ return .first(uniform * scale)
64
+ case .second(let radii):
65
+ return .second(CornerRadii(
66
+ topLeft: radii.topLeft.map { $0 * scale },
67
+ topRight: radii.topRight.map { $0 * scale },
68
+ bottomLeft: radii.bottomLeft.map { $0 * scale },
69
+ bottomRight: radii.bottomRight.map { $0 * scale }
70
+ ))
71
+ }
72
+ }
73
+ return Options(
74
+ blur: options?.blur.map { $0 * scale },
75
+ cache: options?.cache,
76
+ cornerRadius: cornerRadius,
77
+ resize: sizePx.map { ResizeOptions(width: Double($0.width), height: Double($0.height)) }
78
+ )
79
+ }
80
+
81
+ /// An explicit `resize` override (pixels), when set and valid.
82
+ private var explicitResize: CGSize? {
83
+ guard let resize = options?.resize, resize.width > 0, resize.height > 0 else {
84
+ return nil
85
+ }
86
+ return CGSize(width: resize.width, height: resize.height)
87
+ }
88
+
89
+ // MARK: - ImageLoader
90
+
91
+ func loadImage() throws -> Promise<any HybridImageSpec> {
92
+ return Promise.async {
93
+ guard let imageUrl = URL(string: self.url) else {
94
+ throw RuntimeError.error(withMessage: "Invalid URL: \(self.url)")
95
+ }
96
+ // No view to measure here: use the explicit resize if given, and
97
+ // the main screen's scale for the point-based options.
98
+ let scale = await MainActor.run { Self.fallbackScale }
99
+ let request = HybridNitroImagePipeline.makeRequest(
100
+ url: imageUrl,
101
+ options: self.pixelOptions(scale: scale, sizePx: self.explicitResize)
102
+ )
103
+ let image = try await self.pipeline.image(for: request)
104
+ return HybridImage(uiImage: image)
105
+ }
106
+ }
107
+
108
+ func requestImage(forView view: any HybridNitroImageViewSpec) throws {
109
+ guard let nativeView = view as? NativeImageView else { return }
110
+ let key = ObjectIdentifier(view)
111
+ // Always hop (asynchronously) to main: `requestImage` fires while the
112
+ // view is being mounted, and only after the current mounting
113
+ // transaction finishes is its final frame guaranteed to be set.
114
+ DispatchQueue.main.async {
115
+ self.load(into: nativeView.imageView, key: key)
116
+ }
117
+ }
118
+
119
+ func dropImage(forView view: any HybridNitroImageViewSpec) throws {
120
+ guard let nativeView = view as? NativeImageView else { return }
121
+ let key = ObjectIdentifier(view)
122
+ // Same queue as `requestImage`, so rapid attach/detach sequences
123
+ // (list recycling) replay in call order.
124
+ DispatchQueue.main.async {
125
+ self.cancel(key: key)
126
+ nativeView.imageView.image = nil
127
+ }
128
+ }
129
+
130
+ // MARK: - Main-thread loading
131
+
132
+ private func cancel(key: ObjectIdentifier) {
133
+ tasks[key]?.cancel()
134
+ tasks[key] = nil
135
+ // Releasing the observation invalidates it.
136
+ pendingLayouts[key] = nil
137
+ }
138
+
139
+ private func load(into imageView: UIImageView, key: ObjectIdentifier) {
140
+ cancel(key: key)
141
+
142
+ if let sizePx = explicitResize {
143
+ start(into: imageView, key: key, sizePx: sizePx)
144
+ return
145
+ }
146
+
147
+ let bounds = imageView.bounds.size
148
+ if bounds.width > 0, bounds.height > 0 {
149
+ let scale = Self.displayScale(of: imageView)
150
+ start(into: imageView, key: key, sizePx: CGSize(
151
+ width: bounds.width * scale,
152
+ height: bounds.height * scale
153
+ ))
154
+ } else {
155
+ // Mounted at zero size (e.g. a flex child before its container
156
+ // grows): wait for real bounds. Observed on the layer — CALayer
157
+ // properties are KVO-compliant, UIView's are not.
158
+ pendingLayouts[key] = imageView.layer.observe(\.bounds) { [weak self, weak imageView] layer, _ in
159
+ guard layer.bounds.width > 0, layer.bounds.height > 0 else { return }
160
+ DispatchQueue.main.async {
161
+ guard let self, let imageView else { return }
162
+ guard self.pendingLayouts[key] != nil else { return }
163
+ self.load(into: imageView, key: key)
164
+ }
165
+ }
166
+ }
167
+ }
168
+
169
+ private func start(into imageView: UIImageView, key: ObjectIdentifier, sizePx: CGSize) {
170
+ guard let imageUrl = URL(string: url) else { return }
171
+ let scale = Self.displayScale(of: imageView)
172
+ let request = HybridNitroImagePipeline.makeRequest(
173
+ url: imageUrl,
174
+ options: pixelOptions(scale: scale, sizePx: sizePx)
175
+ )
176
+ let pipeline = self.pipeline
177
+ // A memory-cache hit is served synchronously. Going through
178
+ // `pipeline.image(for:)` would resume on Nuke's queue and then hop
179
+ // back to the main actor, so a recycled cell (whose image `dropImage`
180
+ // just cleared) would show empty for a frame or two even though the
181
+ // bitmap is already in memory. The subscript honours the request's
182
+ // `.disableMemoryCacheReads`, so `cache: 'disk'`/`'none'` still miss.
183
+ if !request.options.contains(.disableMemoryCacheReads), let cached = pipeline.cache[request] {
184
+ imageView.image = cached.image
185
+ return
186
+ }
187
+ // Cancelling the Task cancels Nuke's request; a finished task stays in
188
+ // the map (cancelling it is a no-op) until `cancel` replaces it.
189
+ tasks[key] = Task { @MainActor [weak imageView] in
190
+ guard let image = try? await pipeline.image(for: request) else { return }
191
+ guard !Task.isCancelled else { return }
192
+ imageView?.image = image
193
+ }
194
+ }
195
+ }
@@ -48,6 +48,11 @@ struct RoundedCornersProcessor: ImageProcessing {
48
48
  let format = UIGraphicsImageRendererFormat()
49
49
  format.scale = image.scale
50
50
  format.opaque = false
51
+ // `.automatic` picks the extended (16-bit-per-channel) range on
52
+ // wide-gamut displays, which doubles the bytes of this bitmap — the
53
+ // one that ends up in the memory cache and on screen — for an 8-bit
54
+ // sRGB source that gains nothing from it.
55
+ format.preferredRange = .standard
51
56
 
52
57
  let rect = CGRect(origin: .zero, size: size)
53
58
  return UIGraphicsImageRenderer(size: size, format: format).image { context in
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.NativePipelineImage = void 0;
7
+ var _react = require("react");
8
+ var _reactNativeNitroImage = require("react-native-nitro-image");
9
+ var _resizeForStyle = require("./resizeForStyle");
10
+ var _usePipelineImageLoader = require("./usePipelineImageLoader");
11
+ var _jsxRuntime = require("react/jsx-runtime");
12
+ /**
13
+ * The instance `<NativePipelineImage>` exposes through its `ref` — the
14
+ * underlying `NativeNitroImage` host view, with the usual native-view
15
+ * methods (`measure`, …).
16
+ */
17
+
18
+ /**
19
+ * The fully native-driven variant of `PipelineImage`: after the first render
20
+ * there is **zero JS work per image**. The native view starts the request
21
+ * when it attaches to the window — at its own laid-out size, so nothing
22
+ * waits for an `onLayout` round trip — and cancels it (releasing the bitmap)
23
+ * when it detaches, which makes off-screen list cells free. Loads go through
24
+ * the same pipeline and caches as `useImage`/`preLoadImage`.
25
+ *
26
+ * Compared to `PipelineImage`:
27
+ * - No `onLoad`/`onError` callbacks — the loaded `Image` never crosses into
28
+ * JS. Use `PipelineImage` (or `useImage`) when you need them.
29
+ * - The bitmap is loaded once at the size the view first has; if the view is
30
+ * resized later, the bitmap scales with it instead of reloading.
31
+ * @example
32
+ * ```tsx
33
+ * <NativePipelineImage
34
+ * url="https://example.com/photo.jpg"
35
+ * style={{ width: 300, height: 200, borderRadius: 24 }}
36
+ * blur={4}
37
+ * />
38
+ * ```
39
+ */
40
+ const NativePipelineImage = exports.NativePipelineImage = /*#__PURE__*/(0, _react.forwardRef)(function NativePipelineImage({
41
+ url,
42
+ blur,
43
+ cornerRadius,
44
+ cache,
45
+ resize,
46
+ style,
47
+ ...viewProps
48
+ }, ref) {
49
+ // Same precedence as PipelineImage: an explicit prop wins over style.
50
+ const effectiveCornerRadius = cornerRadius ?? (0, _resizeForStyle.cornerRadiusForStyle)(style);
51
+ const loader = (0, _usePipelineImageLoader.usePipelineImageLoader)(url, {
52
+ blur,
53
+ cornerRadius: effectiveCornerRadius,
54
+ cache,
55
+ resize
56
+ });
57
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNativeNitroImage.NativeNitroImage
58
+ // Before the spread so a caller-provided recyclingKey wins.
59
+ , {
60
+ recyclingKey: url,
61
+ ...viewProps,
62
+ ref: ref,
63
+ style: style,
64
+ image: loader
65
+ });
66
+ });
67
+
68
+ // Reanimated and DevTools read the display name; the forwardRef wrapper
69
+ // would otherwise report as anonymous.
70
+ NativePipelineImage.displayName = 'NativePipelineImage';
71
+ //# sourceMappingURL=NativePipelineImage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_react","require","_reactNativeNitroImage","_resizeForStyle","_usePipelineImageLoader","_jsxRuntime","NativePipelineImage","exports","forwardRef","url","blur","cornerRadius","cache","resize","style","viewProps","ref","effectiveCornerRadius","cornerRadiusForStyle","loader","usePipelineImageLoader","jsx","NativeNitroImage","recyclingKey","image","displayName"],"sourceRoot":"../../src","sources":["NativePipelineImage.tsx"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAEA,IAAAC,sBAAA,GAAAD,OAAA;AAEA,IAAAE,eAAA,GAAAF,OAAA;AAMA,IAAAG,uBAAA,GAAAH,OAAA;AAAkE,IAAAI,WAAA,GAAAJ,OAAA;AAKlE;AACA;AACA;AACA;AACA;;AA+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMK,mBAAmB,GAAAC,OAAA,CAAAD,mBAAA,gBAAG,IAAAE,iBAAU,EAG3C,SAASF,mBAAmBA,CAC5B;EAAEG,GAAG;EAAEC,IAAI;EAAEC,YAAY;EAAEC,KAAK;EAAEC,MAAM;EAAEC,KAAK;EAAE,GAAGC;AAAU,CAAC,EAC/DC,GAAG,EACH;EACA;EACA,MAAMC,qBAAqB,GAAGN,YAAY,IAAI,IAAAO,oCAAoB,EAACJ,KAAK,CAAC;EACzE,MAAMK,MAAM,GAAG,IAAAC,8CAAsB,EAACX,GAAG,EAAE;IACzCC,IAAI;IACJC,YAAY,EAAEM,qBAAqB;IACnCL,KAAK;IACLC;EACF,CAAC,CAAC;EAEF,oBACE,IAAAR,WAAA,CAAAgB,GAAA,EAACnB,sBAAA,CAAAoB;EACC;EAAA;IACAC,YAAY,EAAEd,GAAI;IAAA,GACdM,SAAS;IACbC,GAAG,EAAEA,GAAI;IACTF,KAAK,EAAEA,KAAM;IACbU,KAAK,EAAEL;EAAO,CACf,CAAC;AAEN,CAAC,CAAC;;AAEF;AACA;AACAb,mBAAmB,CAACmB,WAAW,GAAG,qBAAqB","ignoreList":[]}
@@ -3,6 +3,12 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ Object.defineProperty(exports, "NativePipelineImage", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _NativePipelineImage.NativePipelineImage;
10
+ }
11
+ });
6
12
  Object.defineProperty(exports, "NitroImagePipeline", {
7
13
  enumerable: true,
8
14
  get: function () {
@@ -39,8 +45,16 @@ Object.defineProperty(exports, "useImage", {
39
45
  return _useImage.useImage;
40
46
  }
41
47
  });
48
+ Object.defineProperty(exports, "usePipelineImageLoader", {
49
+ enumerable: true,
50
+ get: function () {
51
+ return _usePipelineImageLoader.usePipelineImageLoader;
52
+ }
53
+ });
54
+ var _NativePipelineImage = require("./NativePipelineImage");
42
55
  var _NitroImagePipeline = require("./NitroImagePipeline");
43
56
  var _PipelineImage = require("./PipelineImage");
44
57
  var _resizeForStyle = require("./resizeForStyle");
45
58
  var _useImage = require("./useImage");
59
+ var _usePipelineImageLoader = require("./usePipelineImageLoader");
46
60
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_NitroImagePipeline","require","_PipelineImage","_resizeForStyle","_useImage"],"sourceRoot":"../../src","sources":["index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,mBAAA,GAAAC,OAAA;AACA,IAAAC,cAAA,GAAAD,OAAA;AAKA,IAAAE,eAAA,GAAAF,OAAA;AAWA,IAAAG,SAAA,GAAAH,OAAA","ignoreList":[]}
1
+ {"version":3,"names":["_NativePipelineImage","require","_NitroImagePipeline","_PipelineImage","_resizeForStyle","_useImage","_usePipelineImageLoader"],"sourceRoot":"../../src","sources":["index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,oBAAA,GAAAC,OAAA;AAKA,IAAAC,mBAAA,GAAAD,OAAA;AACA,IAAAE,cAAA,GAAAF,OAAA;AAKA,IAAAG,eAAA,GAAAH,OAAA;AAYA,IAAAI,SAAA,GAAAJ,OAAA;AACA,IAAAK,uBAAA,GAAAL,OAAA","ignoreList":[]}
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.usePipelineImageLoader = usePipelineImageLoader;
7
+ var _react = require("react");
8
+ var _NitroImagePipeline = require("./NitroImagePipeline");
9
+ /**
10
+ * Creates (and memoizes) an {@linkcode ImageLoader} for `url` to pass to
11
+ * `<NativeNitroImage image={...} />`. The view drives it entirely natively:
12
+ * the request starts when the view attaches — at the view's laid-out size,
13
+ * with no JS round trips — and is cancelled when it detaches. See
14
+ * {@linkcode NitroImagePipeline.createImageLoader}.
15
+ *
16
+ * `blur`/`cornerRadius` are in **points** (unlike `useImage`, where they are
17
+ * bitmap pixels); the screen scale is applied natively. Inline object
18
+ * literals are fine — options are compared by value, not identity.
19
+ */
20
+ function usePipelineImageLoader(url, options) {
21
+ // Split the options into primitives (like useImage does) so an inline
22
+ // literal — a new identity every render — doesn't recreate the loader;
23
+ // recreating it would re-trigger the native load.
24
+ const blur = options?.blur;
25
+ const cache = options?.cache;
26
+ const cornerRadius = options?.cornerRadius;
27
+ const isUniformRadius = typeof cornerRadius === 'number';
28
+ const uniformRadius = isUniformRadius ? cornerRadius : 0;
29
+ const hasCornerObject = !isUniformRadius && cornerRadius !== undefined;
30
+ const {
31
+ topLeft = 0,
32
+ topRight = 0,
33
+ bottomLeft = 0,
34
+ bottomRight = 0
35
+ } = isUniformRadius || cornerRadius === undefined ? {} : cornerRadius;
36
+ const resizeWidth = options?.resize?.width;
37
+ const resizeHeight = options?.resize?.height;
38
+ return (0, _react.useMemo)(() => {
39
+ const cornerRadiusOption = isUniformRadius ? uniformRadius : hasCornerObject ? {
40
+ topLeft,
41
+ topRight,
42
+ bottomLeft,
43
+ bottomRight
44
+ } : undefined;
45
+ const stableOptions = {
46
+ blur,
47
+ cache,
48
+ cornerRadius: cornerRadiusOption,
49
+ resize: resizeWidth !== undefined && resizeHeight !== undefined ? {
50
+ width: resizeWidth,
51
+ height: resizeHeight
52
+ } : undefined
53
+ };
54
+ const loader = _NitroImagePipeline.NitroImagePipeline.createImageLoader(url, stableOptions);
55
+ // `NativeNitroImage` needs a way to tell two loader instances apart when
56
+ // diffing its `image` prop; tag the loader with what it will load (the
57
+ // same convention react-native-nitro-image's own loaders use).
58
+ Object.defineProperty(loader, '__source', {
59
+ enumerable: true,
60
+ configurable: true,
61
+ value: {
62
+ url,
63
+ options: stableOptions
64
+ }
65
+ });
66
+ return loader;
67
+ }, [url, blur, cache, isUniformRadius, uniformRadius, hasCornerObject, topLeft, topRight, bottomLeft, bottomRight, resizeWidth, resizeHeight]);
68
+ }
69
+ //# sourceMappingURL=usePipelineImageLoader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_react","require","_NitroImagePipeline","usePipelineImageLoader","url","options","blur","cache","cornerRadius","isUniformRadius","uniformRadius","hasCornerObject","undefined","topLeft","topRight","bottomLeft","bottomRight","resizeWidth","resize","width","resizeHeight","height","useMemo","cornerRadiusOption","stableOptions","loader","NitroImagePipeline","createImageLoader","Object","defineProperty","enumerable","configurable","value"],"sourceRoot":"../../src","sources":["usePipelineImageLoader.ts"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAGA,IAAAC,mBAAA,GAAAD,OAAA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASE,sBAAsBA,CACpCC,GAAW,EACXC,OAAqB,EACR;EACb;EACA;EACA;EACA,MAAMC,IAAI,GAAGD,OAAO,EAAEC,IAAI;EAC1B,MAAMC,KAAK,GAAGF,OAAO,EAAEE,KAAK;EAC5B,MAAMC,YAAY,GAAGH,OAAO,EAAEG,YAAY;EAC1C,MAAMC,eAAe,GAAG,OAAOD,YAAY,KAAK,QAAQ;EACxD,MAAME,aAAa,GAAGD,eAAe,GAAGD,YAAY,GAAG,CAAC;EACxD,MAAMG,eAAe,GAAG,CAACF,eAAe,IAAID,YAAY,KAAKI,SAAS;EACtE,MAAM;IACJC,OAAO,GAAG,CAAC;IACXC,QAAQ,GAAG,CAAC;IACZC,UAAU,GAAG,CAAC;IACdC,WAAW,GAAG;EAChB,CAAC,GAAGP,eAAe,IAAID,YAAY,KAAKI,SAAS,GAAG,CAAC,CAAC,GAAGJ,YAAY;EACrE,MAAMS,WAAW,GAAGZ,OAAO,EAAEa,MAAM,EAAEC,KAAK;EAC1C,MAAMC,YAAY,GAAGf,OAAO,EAAEa,MAAM,EAAEG,MAAM;EAE5C,OAAO,IAAAC,cAAO,EAAC,MAAM;IACnB,MAAMC,kBAAoD,GAAGd,eAAe,GACxEC,aAAa,GACbC,eAAe,GACb;MAAEE,OAAO;MAAEC,QAAQ;MAAEC,UAAU;MAAEC;IAAY,CAAC,GAC9CJ,SAAS;IACf,MAAMY,aAA0B,GAAG;MACjClB,IAAI;MACJC,KAAK;MACLC,YAAY,EAAEe,kBAAkB;MAChCL,MAAM,EACJD,WAAW,KAAKL,SAAS,IAAIQ,YAAY,KAAKR,SAAS,GACnD;QAAEO,KAAK,EAAEF,WAAW;QAAEI,MAAM,EAAED;MAAa,CAAC,GAC5CR;IACR,CAAC;IACD,MAAMa,MAAM,GAAGC,sCAAkB,CAACC,iBAAiB,CAACvB,GAAG,EAAEoB,aAAa,CAAC;IACvE;IACA;IACA;IACAI,MAAM,CAACC,cAAc,CAACJ,MAAM,EAAE,UAAU,EAAE;MACxCK,UAAU,EAAE,IAAI;MAChBC,YAAY,EAAE,IAAI;MAClBC,KAAK,EAAE;QAAE5B,GAAG;QAAEC,OAAO,EAAEmB;MAAc;IACvC,CAAC,CAAC;IACF,OAAOC,MAAM;EACf,CAAC,EAAE,CACDrB,GAAG,EACHE,IAAI,EACJC,KAAK,EACLE,eAAe,EACfC,aAAa,EACbC,eAAe,EACfE,OAAO,EACPC,QAAQ,EACRC,UAAU,EACVC,WAAW,EACXC,WAAW,EACXG,YAAY,CACb,CAAC;AACJ","ignoreList":[]}