@onekeyfe/react-native-image 3.0.157 → 3.0.159

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.
@@ -0,0 +1,119 @@
1
+ package com.margelo.nitro.onekeyimage
2
+
3
+ import kotlin.math.max
4
+ import kotlin.math.min
5
+
6
+ internal data class OneKeyImageMemoryFamilyKey(
7
+ val rawUrl: String,
8
+ val headersDigest: String?,
9
+ ) {
10
+ companion object {
11
+ fun from(rawUrl: String, headersJson: String?): OneKeyImageMemoryFamilyKey =
12
+ OneKeyImageMemoryFamilyKey(
13
+ rawUrl = rawUrl,
14
+ headersDigest = OneKeyImageModel.remoteHeadersDigest(
15
+ OneKeyImageModel.headers(headersJson),
16
+ ),
17
+ )
18
+ }
19
+ }
20
+
21
+ internal data class OneKeyImageMemoryVariant(
22
+ val requestUrl: String,
23
+ val width: Int,
24
+ val height: Int,
25
+ val round: Boolean,
26
+ ) {
27
+ val area: Long
28
+ get() = width.toLong() * height.toLong()
29
+ }
30
+
31
+ /**
32
+ * A bounded index of size-specific Glide resources that may still be in memory.
33
+ *
34
+ * Glide remains the source of truth. Entries are only hints used to reproduce a
35
+ * candidate EngineKey; a synchronous cache miss removes the stale hint.
36
+ */
37
+ internal object OneKeyImageMemoryVariantRegistry {
38
+ private const val MAX_FAMILIES = 1024
39
+ private const val MAX_VARIANTS_PER_FAMILY = 8
40
+ private const val MAX_ASPECT_RATIO_DRIFT = 1.1
41
+
42
+ private val variantsByFamily =
43
+ LinkedHashMap<OneKeyImageMemoryFamilyKey, MutableList<OneKeyImageMemoryVariant>>(
44
+ 16,
45
+ 0.75f,
46
+ true,
47
+ )
48
+
49
+ @Synchronized
50
+ fun record(family: OneKeyImageMemoryFamilyKey, variant: OneKeyImageMemoryVariant) {
51
+ if (variant.width <= 0 || variant.height <= 0) return
52
+ val variants = variantsByFamily.getOrPut(family) { mutableListOf() }
53
+ variants.remove(variant)
54
+ variants.add(variant)
55
+ while (variants.size > MAX_VARIANTS_PER_FAMILY) variants.removeAt(0)
56
+ while (variantsByFamily.size > MAX_FAMILIES) {
57
+ val eldest = variantsByFamily.entries.firstOrNull()?.key ?: break
58
+ variantsByFamily.remove(eldest)
59
+ }
60
+ }
61
+
62
+ @Synchronized
63
+ fun remove(family: OneKeyImageMemoryFamilyKey, variant: OneKeyImageMemoryVariant) {
64
+ val variants = variantsByFamily[family] ?: return
65
+ variants.remove(variant)
66
+ if (variants.isEmpty()) variantsByFamily.remove(family)
67
+ }
68
+
69
+ @Synchronized
70
+ fun candidates(
71
+ family: OneKeyImageMemoryFamilyKey,
72
+ target: OneKeyImageMemoryVariant,
73
+ ): List<OneKeyImageMemoryVariant> = orderedCandidates(
74
+ variants = variantsByFamily[family].orEmpty(),
75
+ target = target,
76
+ )
77
+
78
+ @Synchronized
79
+ fun clear() {
80
+ variantsByFamily.clear()
81
+ }
82
+
83
+ internal fun orderedCandidates(
84
+ variants: List<OneKeyImageMemoryVariant>,
85
+ target: OneKeyImageMemoryVariant,
86
+ ): List<OneKeyImageMemoryVariant> {
87
+ val compatible = variants
88
+ .asSequence()
89
+ .filter { it != target }
90
+ .filter { candidate -> target.round || !candidate.round }
91
+ .filter { candidate -> aspectRatioIsCompatible(candidate, target) }
92
+ .distinct()
93
+ .toList()
94
+
95
+ val larger = compatible
96
+ .filter { it.width >= target.width && it.height >= target.height }
97
+ .minWithOrNull(
98
+ compareBy<OneKeyImageMemoryVariant> { it.area }
99
+ .thenBy { if (it.round == target.round) 0 else 1 },
100
+ )
101
+ val smaller = compatible
102
+ .filter { it.width <= target.width && it.height <= target.height }
103
+ .maxWithOrNull(
104
+ compareBy<OneKeyImageMemoryVariant> { it.area }
105
+ .thenByDescending { if (it.round == target.round) 0 else 1 },
106
+ )
107
+ return listOfNotNull(larger, smaller).distinct()
108
+ }
109
+
110
+ private fun aspectRatioIsCompatible(
111
+ candidate: OneKeyImageMemoryVariant,
112
+ target: OneKeyImageMemoryVariant,
113
+ ): Boolean {
114
+ val candidateRatio = candidate.width.toDouble() / candidate.height.toDouble()
115
+ val targetRatio = target.width.toDouble() / target.height.toDouble()
116
+ return max(candidateRatio, targetRatio) / min(candidateRatio, targetRatio) <=
117
+ MAX_ASPECT_RATIO_DRIFT
118
+ }
119
+ }
@@ -0,0 +1,149 @@
1
+ package com.margelo.nitro.onekeyimage
2
+
3
+ import com.bumptech.glide.load.engine.DiskCacheStrategy
4
+ import com.bumptech.glide.request.RequestOptions
5
+ import org.junit.Assert.assertEquals
6
+ import org.junit.Assert.assertFalse
7
+ import org.junit.Assert.assertSame
8
+ import org.junit.Assert.assertTrue
9
+ import org.junit.Test
10
+
11
+ class OneKeyImageMemoryVariantsTest {
12
+ @Test
13
+ fun choosesNearestLargerThenNearestSmallerVariant() {
14
+ val target = variant(96)
15
+ val candidates = OneKeyImageMemoryVariantRegistry.orderedCandidates(
16
+ variants = listOf(variant(48), variant(72), variant(120), variant(144)),
17
+ target = target,
18
+ )
19
+
20
+ assertEquals(listOf(variant(120), variant(72)), candidates)
21
+ }
22
+
23
+ @Test
24
+ fun ignoresExactAndIncompatibleAspectRatios() {
25
+ val target = variant(96)
26
+ val candidates = OneKeyImageMemoryVariantRegistry.orderedCandidates(
27
+ variants = listOf(
28
+ target,
29
+ OneKeyImageMemoryVariant("wide", 120, 60, round = false),
30
+ variant(120),
31
+ ),
32
+ target = target,
33
+ )
34
+
35
+ assertEquals(listOf(variant(120)), candidates)
36
+ }
37
+
38
+ @Test
39
+ fun roundTargetCanPreviewUntransformedResourceButSquareTargetCannotUseRoundResource() {
40
+ val untransformed = variant(120, round = false)
41
+ val transformed = variant(120, round = true)
42
+
43
+ assertEquals(
44
+ listOf(untransformed),
45
+ OneKeyImageMemoryVariantRegistry.orderedCandidates(
46
+ variants = listOf(untransformed),
47
+ target = variant(96, round = true),
48
+ ),
49
+ )
50
+ assertEquals(
51
+ emptyList<OneKeyImageMemoryVariant>(),
52
+ OneKeyImageMemoryVariantRegistry.orderedCandidates(
53
+ variants = listOf(transformed),
54
+ target = variant(96, round = false),
55
+ ),
56
+ )
57
+ }
58
+
59
+ @Test
60
+ fun crossSizeCenterPreviewUsesTemporaryScaling() {
61
+ assertTrue(
62
+ shouldScaleCenterMemoryPreview(
63
+ contentFit = OneKeyImageContentFit.CENTER,
64
+ candidate = variant(48),
65
+ target = variant(96),
66
+ ),
67
+ )
68
+ assertTrue(
69
+ shouldScaleCenterMemoryPreview(
70
+ contentFit = OneKeyImageContentFit.CENTER,
71
+ candidate = variant(144),
72
+ target = variant(96),
73
+ ),
74
+ )
75
+ assertFalse(
76
+ shouldScaleCenterMemoryPreview(
77
+ contentFit = OneKeyImageContentFit.CENTER,
78
+ candidate = variant(96),
79
+ target = variant(96),
80
+ ),
81
+ )
82
+ assertFalse(
83
+ shouldScaleCenterMemoryPreview(
84
+ contentFit = OneKeyImageContentFit.COVER,
85
+ candidate = variant(48),
86
+ target = variant(96),
87
+ ),
88
+ )
89
+ }
90
+
91
+ @Test
92
+ fun missingPreviewDrawableAllowsSameFamilyProbeRetry() {
93
+ assertTrue(
94
+ shouldProbeMemoryPreview(
95
+ hasTarget = true,
96
+ sameFamily = true,
97
+ hasDrawable = false,
98
+ ),
99
+ )
100
+ assertFalse(
101
+ shouldProbeMemoryPreview(
102
+ hasTarget = true,
103
+ sameFamily = true,
104
+ hasDrawable = true,
105
+ ),
106
+ )
107
+ }
108
+
109
+ @Test
110
+ fun replacingMemoryPreviewSkipsWholeViewFade() {
111
+ assertFalse(
112
+ shouldAnimateLoadedImageTransition(
113
+ cacheType = OneKeyImageCacheType.DISK,
114
+ fadeDelayElapsed = true,
115
+ animationsEnabled = true,
116
+ replacingMemoryPreview = true,
117
+ ),
118
+ )
119
+ assertTrue(
120
+ shouldAnimateLoadedImageTransition(
121
+ cacheType = OneKeyImageCacheType.DISK,
122
+ fadeDelayElapsed = true,
123
+ animationsEnabled = true,
124
+ replacingMemoryPreview = false,
125
+ ),
126
+ )
127
+ }
128
+
129
+ @Test
130
+ fun memoryProbeKeepsMemoryEnabledAndDisablesDiskReads() {
131
+ val options = memoryProbeRequestOptions(
132
+ RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC),
133
+ )
134
+
135
+ assertSame(DiskCacheStrategy.NONE, options.diskCacheStrategy)
136
+ assertTrue(options.onlyRetrieveFromCache)
137
+ assertTrue(options.isMemoryCacheable)
138
+ }
139
+
140
+ private fun variant(
141
+ size: Int,
142
+ round: Boolean = false,
143
+ ) = OneKeyImageMemoryVariant(
144
+ requestUrl = "https://example.com/image-$size.png",
145
+ width = size,
146
+ height = size,
147
+ round = round,
148
+ )
149
+ }
@@ -98,6 +98,7 @@ private final class OneKeyImageSkeletonIndicator: NSObject, SDWebImageIndicator
98
98
 
99
99
  final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
100
100
  private enum DisplayState { case loading, image, error, fallback }
101
+ private enum MemoryProbeResult { case miss, preview, exact }
101
102
  private static let fadeDelayThreshold: CFTimeInterval = 0.1
102
103
  private static let fadeDuration: TimeInterval = 0.14
103
104
 
@@ -115,6 +116,11 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
115
116
  private var requestActive = false
116
117
  private var isResetting = false
117
118
  private var displayState = DisplayState.loading
119
+ /// `.loading` with the previous image kept on screen as the placeholder
120
+ /// (see `showLoading(preservedImage:)`).
121
+ private var isPreservingDisplayedImage = false
122
+ private var isShowingMemoryPreview = false
123
+ private var scalesCenterMemoryPreview = false
118
124
  private var requestStartedAt: CFTimeInterval?
119
125
 
120
126
  var view: UIView { hostView }
@@ -204,8 +210,8 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
204
210
  // Fabric can reset `round` before clearing `sourceUri` while removing a view.
205
211
  // Apply the shape once per committed prop batch so the outgoing frame keeps
206
212
  // its clipping, while mounted and recycled views still receive the new value.
207
- if let sourceUri, !sourceUri.isEmpty {
208
- hostView.round = round == true
213
+ if let sourceUri, !sourceUri.isEmpty, let round {
214
+ hostView.round = round
209
215
  }
210
216
  scheduleLoad()
211
217
  }
@@ -251,7 +257,7 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
251
257
  self.cancelCurrentRequest(invalidateGeneration: true)
252
258
  self.lastRequestSignature = nil
253
259
  if let source = self.sourceUri, !source.isEmpty {
254
- if !self.showMemoryCachedImageIfAvailable(requestIsActive: false) {
260
+ if self.showMemoryCachedImageIfAvailable(requestIsActive: false) == .miss {
255
261
  self.showLoading(requestIsActive: false, letLibraryStartIndicator: false)
256
262
  }
257
263
  } else {
@@ -307,7 +313,7 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
307
313
  requestStartedAt = CACurrentMediaTime()
308
314
  onLoadStart?()
309
315
  guard Self.isCurrentRequestGeneration(generation, current: requestGeneration) else { return }
310
- if showMemoryCachedImageIfAvailable(requestIsActive: true) { return }
316
+ if showMemoryCachedImageIfAvailable(requestIsActive: true) == .exact { return }
311
317
  // The pre-layout probe may have shown this identity from another thumbnail
312
318
  // key (a preload's, or an earlier layout size). Keep it on screen as the
313
319
  // placeholder while the exact rendition loads: blanking to a skeleton and
@@ -337,8 +343,11 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
337
343
  }
338
344
 
339
345
  let hasCustomIdentity = OneKeyImageRequestContext.headers(from: sourceHeadersJson) != nil
340
- let displaySize = resizeWidth.flatMap { $0.isFinite && $0 > 0 ? CGFloat($0) : nil }
341
- ?? max(hostView.bounds.width, hostView.bounds.height)
346
+ let displaySize = OneKeyImageDecodeSizing.tosDisplaySize(
347
+ bounds: hostView.bounds.size,
348
+ resizeWidth: resizeWidth,
349
+ resizeHeight: resizeHeight
350
+ ) ?? 0
342
351
  let requestURL =
343
352
  (optimizeTos ?? true)
344
353
  ? OneKeyTosURL.optimized(
@@ -429,21 +438,43 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
429
438
  url: rawURL,
430
439
  rawURL: rawURL,
431
440
  generation: generation,
432
- mayFallbackToRaw: false
441
+ mayFallbackToRaw: false,
442
+ placeholderImage: self.hostView.image
433
443
  )
434
444
  return
435
445
  }
436
446
  self.finishWithError(safetyViolation ?? error, generation: generation)
437
447
  return
438
448
  }
449
+ if let image,
450
+ Self.canUseAsMemoryPreview(image),
451
+ let thumbnailPixelSize,
452
+ self.cachePolicy == .memory || self.cachePolicy == .memoryDisk || self.cachePolicy == nil
453
+ {
454
+ OneKeyImageMemoryVariantRegistry.shared.record(
455
+ OneKeyImageMemoryVariant(
456
+ requestURL: url,
457
+ thumbnailPixelSize: thumbnailPixelSize
458
+ ),
459
+ for: OneKeyImageMemoryFamilyKey(
460
+ rawURL: rawURL,
461
+ headersJson: self.sourceHeadersJson
462
+ )
463
+ )
464
+ }
439
465
  guard self.claimTerminal(generation) else { return }
466
+ let replacesMemoryPreview = self.clearMemoryPreviewPresentation()
440
467
  self.requestActive = false
441
468
  self.displayState = .image
469
+ self.isPreservingDisplayedImage = false
442
470
  self.skeletonIndicator.stopAnimatingIndicator()
443
471
  self.fallbackLayer.isHidden = true
444
472
  self.hostView.backgroundColor = .clear
445
473
  let resolvedCacheType = Self.cacheType(cacheType)
446
- self.applyLoadedImageTransition(cacheType: resolvedCacheType)
474
+ self.applyLoadedImageTransition(
475
+ cacheType: resolvedCacheType,
476
+ replacingMemoryPreview: replacesMemoryPreview
477
+ )
447
478
  self.applyAutoplay()
448
479
  let onLoad = self.onLoad
449
480
  let onLoadEnd = self.onLoadEnd
@@ -547,6 +578,7 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
547
578
  optimizeTos = true
548
579
  round = false
549
580
  resizeWidth = nil
581
+ resizeHeight = nil
550
582
  overscan = 1.1
551
583
  loadingStrategy = .static
552
584
  placeholderColor = nil
@@ -577,6 +609,9 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
577
609
  guard Self.isCurrentRequestGeneration(generation, current: requestGeneration) else {
578
610
  return
579
611
  }
612
+ // Also the placeholder write path (SDWebImage hands the preserved image
613
+ // back through setImageBlock when the load starts), so the preservation
614
+ // flag is NOT touched here; it ends with the terminal callbacks.
580
615
  hostView.image = image
581
616
  }
582
617
 
@@ -592,11 +627,20 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
592
627
  if let preservedImage {
593
628
  // Same identity, different thumbnail key: the image already on screen
594
629
  // stands in for the placeholder, so no blank frame and no indicator.
630
+ // The indicator is unmounted, not just stopped: SDWebImage restarts a
631
+ // mounted `sd_imageIndicator` when the load begins, and `applyVariant`
632
+ // must not reinstall it while this state lasts.
633
+ isPreservingDisplayedImage = true
595
634
  hostView.image = preservedImage
596
635
  skeletonIndicator.stopAnimatingIndicator()
636
+ if hostView.sd_imageIndicator != nil {
637
+ hostView.sd_imageIndicator = nil
638
+ }
597
639
  hostView.backgroundColor = .clear
598
640
  return
599
641
  }
642
+ clearMemoryPreviewPresentation()
643
+ isPreservingDisplayedImage = false
600
644
  hostView.image = nil
601
645
  applyLoadingAppearance(letLibraryStartIndicator: letLibraryStartIndicator)
602
646
  }
@@ -608,7 +652,7 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
608
652
  isShowingImage && hasImage
609
653
  }
610
654
 
611
- private func showMemoryCachedImageIfAvailable(requestIsActive: Bool) -> Bool {
655
+ private func showMemoryCachedImageIfAvailable(requestIsActive: Bool) -> MemoryProbeResult {
612
656
  // JS leaves `cachePolicy` unset for the common case and Fabric then hands
613
657
  // Nitro a nil, which the request path already treats as memory-disk; the
614
658
  // probe must agree, otherwise a nil policy skips the memory lookup entirely
@@ -618,13 +662,16 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
618
662
  guard effectivePolicy == .memory || effectivePolicy == .memoryDisk,
619
663
  let sourceUri,
620
664
  let rawURL = URL(string: sourceUri) else {
621
- return false
665
+ return .miss
622
666
  }
623
667
  let rawScreenScale: CGFloat = hostView.window?.screen.scale ?? UIScreen.main.scale
624
668
  let screenScale = min(max(rawScreenScale, 1), 3)
625
669
  let hasCustomIdentity = OneKeyImageRequestContext.headers(from: sourceHeadersJson) != nil
626
- let displaySize = resizeWidth.flatMap { $0.isFinite && $0 > 0 ? CGFloat($0) : nil }
627
- ?? max(hostView.bounds.width, hostView.bounds.height)
670
+ let displaySize = OneKeyImageDecodeSizing.tosDisplaySize(
671
+ bounds: hostView.bounds.size,
672
+ resizeWidth: resizeWidth,
673
+ resizeHeight: resizeHeight
674
+ ) ?? 0
628
675
  let requestURL =
629
676
  (optimizeTos ?? true)
630
677
  ? OneKeyTosURL.optimized(
@@ -664,32 +711,100 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
664
711
  }
665
712
  return cache.imageFromMemoryCache(forKey: key)
666
713
  }
667
- func memoryCachedImage(for url: URL) -> UIImage? {
668
- for thumbnailPixelSize in thumbnailCandidates {
669
- if let image = memoryCachedImage(for: url, thumbnailPixelSize: thumbnailPixelSize) {
670
- return image
714
+
715
+ var exactProbes: [(variant: OneKeyImageMemoryVariant?, url: URL, size: CGSize?)] = []
716
+ for url in requestURL == rawURL ? [requestURL] : [requestURL, rawURL] {
717
+ for size in thumbnailCandidates {
718
+ exactProbes.append(
719
+ (
720
+ variant: size.map {
721
+ OneKeyImageMemoryVariant(requestURL: url, thumbnailPixelSize: $0)
722
+ },
723
+ url: url,
724
+ size: size
725
+ )
726
+ )
727
+ }
728
+ }
729
+ let family = OneKeyImageMemoryFamilyKey(rawURL: rawURL, headersJson: sourceHeadersJson)
730
+ let exactVariants = Set(exactProbes.compactMap(\.variant))
731
+ for probe in exactProbes {
732
+ guard let image = memoryCachedImage(for: probe.url, thumbnailPixelSize: probe.size) else {
733
+ if let variant = probe.variant {
734
+ OneKeyImageMemoryVariantRegistry.shared.remove(variant, for: family)
671
735
  }
736
+ continue
672
737
  }
673
- return nil
738
+ if let variant = probe.variant, Self.canUseAsMemoryPreview(image) {
739
+ OneKeyImageMemoryVariantRegistry.shared.record(variant, for: family)
740
+ }
741
+ displayMemoryCachedImage(
742
+ image,
743
+ requestIsActive: requestIsActive,
744
+ terminal: true,
745
+ scalesCenterPreview: false
746
+ )
747
+ return .exact
674
748
  }
675
- guard let image = memoryCachedImage(for: requestURL)
676
- ?? (requestURL == rawURL ? nil : memoryCachedImage(for: rawURL)) else {
677
- return false
749
+
750
+ if let target = exactProbes.compactMap(\.variant).first {
751
+ let candidates = OneKeyImageMemoryVariantRegistry.shared.candidates(
752
+ for: family,
753
+ target: target,
754
+ excluding: exactVariants
755
+ )
756
+ for candidate in candidates {
757
+ guard
758
+ let image = memoryCachedImage(
759
+ for: candidate.requestURL,
760
+ thumbnailPixelSize: candidate.thumbnailPixelSize
761
+ ),
762
+ Self.canUseAsMemoryPreview(image)
763
+ else {
764
+ OneKeyImageMemoryVariantRegistry.shared.remove(candidate, for: family)
765
+ continue
766
+ }
767
+ displayMemoryCachedImage(
768
+ image,
769
+ requestIsActive: false,
770
+ terminal: false,
771
+ scalesCenterPreview: Self.shouldScaleCenterMemoryPreview(
772
+ contentFit: contentFit ?? .cover,
773
+ candidate: candidate,
774
+ target: target
775
+ )
776
+ )
777
+ OneKeyImageMemoryVariantRegistry.shared.record(candidate, for: family)
778
+ return .preview
779
+ }
678
780
  }
781
+ return .miss
782
+ }
783
+
784
+ private func displayMemoryCachedImage(
785
+ _ image: UIImage,
786
+ requestIsActive: Bool,
787
+ terminal: Bool,
788
+ scalesCenterPreview: Bool
789
+ ) {
679
790
  let generation = requestGeneration
680
- if requestIsActive, !claimTerminal(generation) { return true }
791
+ if terminal, requestIsActive, !claimTerminal(generation) { return }
792
+ isShowingMemoryPreview = !terminal
793
+ self.scalesCenterMemoryPreview = !terminal && scalesCenterPreview
794
+ applyContentFit()
681
795
  displayState = .image
796
+ isPreservingDisplayedImage = false
682
797
  requestActive = false
683
798
  skeletonIndicator.stopAnimatingIndicator()
684
799
  fallbackLayer.isHidden = true
685
800
  resetImageTransition()
686
801
  applyDisplayedImage(image, generation: generation)
687
802
  hostView.backgroundColor = .clear
688
- if requestIsActive {
689
- applyLoadedImageTransition(cacheType: .memory)
803
+ if terminal, requestIsActive {
804
+ applyLoadedImageTransition(cacheType: .memory, replacingMemoryPreview: false)
690
805
  }
691
806
  applyAutoplay()
692
- if requestIsActive {
807
+ if terminal, requestIsActive {
693
808
  let onLoad = onLoad
694
809
  let onLoadEnd = onLoadEnd
695
810
  Self.deliverTerminalCallbacks(
@@ -698,11 +813,32 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
698
813
  },
699
814
  onLoadEnd: { onLoadEnd?() }
700
815
  )
701
- guard requestGeneration == generation else { return true }
816
+ guard requestGeneration == generation else { return }
702
817
  pendingDisplayGeneration = generation
703
818
  schedulePendingDisplayIfNeeded()
704
819
  }
705
- return true
820
+ }
821
+
822
+ private static func canUseAsMemoryPreview(_ image: UIImage) -> Bool {
823
+ !(image is SDAnimatedImage) && image.images == nil
824
+ }
825
+
826
+ static func shouldScaleCenterMemoryPreview(
827
+ contentFit: OneKeyImageContentFit,
828
+ candidate: OneKeyImageMemoryVariant,
829
+ target: OneKeyImageMemoryVariant
830
+ ) -> Bool {
831
+ guard case .center = contentFit else { return false }
832
+ return candidate.pixelWidth != target.pixelWidth || candidate.pixelHeight != target.pixelHeight
833
+ }
834
+
835
+ @discardableResult
836
+ private func clearMemoryPreviewPresentation() -> Bool {
837
+ let wasShowingMemoryPreview = isShowingMemoryPreview
838
+ isShowingMemoryPreview = false
839
+ scalesCenterMemoryPreview = false
840
+ applyContentFit()
841
+ return wasShowingMemoryPreview
706
842
  }
707
843
 
708
844
  private func showError() {
@@ -716,6 +852,8 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
716
852
  private func showTerminalState(_ state: DisplayState) {
717
853
  displayState = state
718
854
  requestActive = false
855
+ isPreservingDisplayedImage = false
856
+ clearMemoryPreviewPresentation()
719
857
  skeletonIndicator.stopAnimatingIndicator()
720
858
  resetImageTransition()
721
859
  hostView.image = nil
@@ -733,6 +871,9 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
733
871
  case .image:
734
872
  break
735
873
  case .loading:
874
+ // A preserved image is the placeholder; re-applying the loading look
875
+ // would cover it with the skeleton / placeholder color again.
876
+ if isPreservingDisplayedImage { break }
736
877
  applyLoadingAppearance(letLibraryStartIndicator: false)
737
878
  case .error, .fallback:
738
879
  let hidesTerminalState = loadingStrategy == .none
@@ -808,12 +949,28 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
808
949
  return [base, highlight]
809
950
  }
810
951
 
811
- private func applyLoadedImageTransition(cacheType: OneKeyImageCacheType) {
952
+ static func shouldAnimateLoadedImageTransition(
953
+ cacheType: OneKeyImageCacheType,
954
+ requestDuration: CFTimeInterval?,
955
+ reduceMotionEnabled: Bool,
956
+ replacingMemoryPreview: Bool
957
+ ) -> Bool {
958
+ !replacingMemoryPreview && cacheType != .memory
959
+ && (requestDuration ?? 0) >= fadeDelayThreshold && !reduceMotionEnabled
960
+ }
961
+
962
+ private func applyLoadedImageTransition(
963
+ cacheType: OneKeyImageCacheType,
964
+ replacingMemoryPreview: Bool
965
+ ) {
812
966
  resetImageTransition()
813
- guard cacheType != .memory,
814
- let requestStartedAt,
815
- CACurrentMediaTime() - requestStartedAt >= Self.fadeDelayThreshold,
816
- !UIAccessibility.isReduceMotionEnabled else {
967
+ let requestDuration = requestStartedAt.map { CACurrentMediaTime() - $0 }
968
+ guard Self.shouldAnimateLoadedImageTransition(
969
+ cacheType: cacheType,
970
+ requestDuration: requestDuration,
971
+ reduceMotionEnabled: UIAccessibility.isReduceMotionEnabled,
972
+ replacingMemoryPreview: replacingMemoryPreview
973
+ ) else {
817
974
  return
818
975
  }
819
976
  hostView.alpha = 0
@@ -858,6 +1015,10 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
858
1015
  }
859
1016
 
860
1017
  private func applyContentFit() {
1018
+ if scalesCenterMemoryPreview, case .center = contentFit ?? .cover {
1019
+ hostView.contentMode = .scaleAspectFit
1020
+ return
1021
+ }
861
1022
  switch contentFit ?? .cover {
862
1023
  case .cover: hostView.contentMode = .scaleAspectFill
863
1024
  case .contain: hostView.contentMode = .scaleAspectFit