@onekeyfe/react-native-image 6.7.0-alpha.475 → 6.8.0-10

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 (32) hide show
  1. package/README.md +144 -86
  2. package/android/build.gradle +1 -0
  3. package/android/consumer-rules.pro +9 -0
  4. package/android/src/main/AndroidManifest.xml +12 -1
  5. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyIcon.kt +5 -1
  6. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImage.kt +240 -6
  7. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageCache.kt +4 -0
  8. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideModule.kt +17 -0
  9. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideRegistry.kt +1 -0
  10. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageSafety.kt +41 -0
  11. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageStartupPrewarm.kt +1106 -0
  12. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageStartupProvider.kt +54 -0
  13. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMainThreadDecode.kt +541 -0
  14. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMediaPreviewCache.kt +1 -1
  15. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyNamedSVG.kt +758 -61
  16. package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyStartupPrewarmTest.kt +600 -0
  17. package/ios/OneKeyAvatarImageLoader.swift +1 -1
  18. package/ios/OneKeyIcon.swift +6 -0
  19. package/ios/OneKeyImage.swift +85 -2
  20. package/ios/OneKeyImageCache.swift +2 -0
  21. package/ios/OneKeyImageCoderBridge.m +42 -1
  22. package/ios/OneKeyImageRequestContext.swift +16 -2
  23. package/ios/OneKeyImageStartupPrewarm.swift +602 -0
  24. package/ios/OneKeyMainThreadDecode.swift +338 -0
  25. package/ios/OneKeyMediaPreviewCache.swift +20 -12
  26. package/ios/OneKeyNamedSVG.swift +437 -9
  27. package/ios/tests/OneKeyIconTests.swift +238 -0
  28. package/ios/tests/OneKeyImageInfrastructureTests.swift +611 -0
  29. package/ios/tests/OneKeyMediaPreviewCacheTests.swift +49 -0
  30. package/lib/module/index.js +5 -1
  31. package/package.json +1 -1
  32. package/src/index.tsx +23 -2
package/README.md CHANGED
@@ -1,109 +1,167 @@
1
+ <div align="center">
2
+
1
3
  # @onekeyfe/react-native-image
2
4
 
3
- Nitro HybridView backed by SDWebImage on iOS and Glide on Android. It provides
4
- native loading placeholders, opt-in shared-renderer skeleton, fallback states,
5
- cache controls,
6
- and conservative OneKey TOS URL resizing without depending on Expo Image.
5
+ **Native image loading for OneKey apps — SDWebImage on iOS, Glide on Android, and a Nitro image view with cache control.**
6
+
7
+ [![npm](https://img.shields.io/npm/v/%40onekeyfe%2Freact-native-image?label=npm&color=4D6BFE)](https://www.npmjs.com/package/@onekeyfe/react-native-image)
8
+ [![license](https://img.shields.io/npm/l/%40onekeyfe%2Freact-native-image?label=license&color=4D6BFE)](LICENSE)
9
+ ![iOS](https://img.shields.io/badge/iOS-000000?logo=apple&logoColor=white)
10
+ ![Android](https://img.shields.io/badge/Android-3DDC84?logo=android&logoColor=white)
11
+ ![Web](https://img.shields.io/badge/Web-4285F4?logo=googlechrome&logoColor=white)
12
+ ![Nitro Modules](https://img.shields.io/badge/Nitro_Modules-4D6BFE)
13
+
14
+ </div>
15
+
16
+ Renders remote and bundled images through a Nitro view backed by SDWebImage on
17
+ iOS and Glide on Android. The native view owns loading and terminal presentation,
18
+ cache control, animated images, request cancellation and safe reuse of recycled
19
+ cells; the application owns sizing, source selection and business fallbacks. A
20
+ separate `OneKeyIcon` entry renders host-provided named SVG icons on native and
21
+ Web. The package has no Web renderer for `OneKeyImage` itself.
22
+
23
+ ## Features
24
+
25
+ - **Native image pipeline** — SDWebImage on iOS and Glide on Android with
26
+ `memory-disk`, `memory`, `disk` or `none` cache policies.
27
+ - **Native loading and fallback states** — static placeholders, opt-in skeleton
28
+ loading, and terminal error/fallback presentation drawn by the native view.
29
+ - **Explicit cache control** — `preload` and `clearMemory`/`clearDisk`/`clearAll`
30
+ resolve only after the requested native cache work completes.
31
+ - **Bounded TOS rendition** — `optimizeTos` may swap eligible OneKey asset URLs
32
+ for a rendition sized from `resizeWidth`/`resizeHeight` and `overscan`.
33
+ - **Recycled-cell safety** — `recyclingKey` and `reload()`/`cancel()` keep stale
34
+ work out of reused native views.
35
+ - **Named SVG icons** — a separate `OneKeyIcon` entry renders host-owned artwork
36
+ with no network request, on native and on Web.
37
+
38
+ ## Installation
39
+
40
+ ```sh
41
+ yarn add @onekeyfe/react-native-image \
42
+ @onekeyfe/react-native-skeleton \
43
+ react-native-nitro-modules@0.37.0
44
+ ```
45
+
46
+ Peer dependencies: `react`, `react-native`, `react-native-nitro-modules` 0.37.0
47
+ and `@onekeyfe/react-native-skeleton` (the native skeleton renderer). Install the
48
+ app's iOS pods and rebuild the native binary; a JavaScript-only install does not
49
+ register the views:
7
50
 
8
- The authoritative lifecycle, cache identity, cross-size memory-preview, safety,
9
- and platform contract is defined in [docs/SPEC.md](https://github.com/OneKeyHQ/app-modules/blob/main/native-views/react-native-image/docs/SPEC.md).
51
+ ```sh
52
+ cd ios && pod install
53
+ ```
54
+
55
+ Android links through autolinking; deployment floors are iOS 15.1 and Android
56
+ API 24. For a CocoaPods static-library integration, declare the SDWebImage coders
57
+ as modular headers in the application `Podfile`: SDWebImage `5.21.7`,
58
+ SDWebImageWebPCoder `0.14.6` and SDWebImageSVGCoder `1.7.0`.
59
+
60
+ ## Usage
10
61
 
11
62
  ```tsx
63
+ import {
64
+ OneKeyImage,
65
+ OneKeyImageLoadingStrategy,
66
+ OneKeyImageVariant,
67
+ } from '@onekeyfe/react-native-image';
68
+
12
69
  <OneKeyImage
13
- source={{ uri: 'https://example.com/avatar.png' }}
70
+ source={{ uri: avatarUrl }}
14
71
  variant={OneKeyImageVariant.AVATAR}
15
- style={{ width: 48, height: 48 }}
16
- />
72
+ loadingStrategy={OneKeyImageLoadingStrategy.SKELETON}
73
+ style={{ width: 48, height: 48, borderRadius: 24 }}
74
+ />;
17
75
  ```
18
76
 
19
- React placeholders and fallbacks are optional overlays. The default path draws
20
- all states in the native image view and never nests SkeletonView. The public
21
- state semantics match the native image libraries:
77
+ Give the view explicit dimensions: it does not derive its own size from the
78
+ image, and a reused list cell must receive a new `recyclingKey`.
22
79
 
23
- - `placeholder`: shown while a non-null source is loading.
24
- - `fallback`: shown when `source` is null, cannot be resolved, or fails to load.
80
+ ### Named icons
25
81
 
26
- `onError` is only emitted for an actual request failure; a null source displays
27
- the same fallback UI without emitting an error event.
82
+ `OneKeyIcon` lives in the separate `icon` entry and renders artwork the host
83
+ supplies at build time:
28
84
 
29
- The React event payloads follow the Expo Image envelope used by OneKey:
85
+ ```tsx
86
+ import { OneKeyIcon } from '@onekeyfe/react-native-image/icon';
30
87
 
31
- ```ts
32
- onLoad={({ source: { url, width, height }, cacheType }) => {}}
33
- onError={({ error }) => {}}
88
+ <OneKeyIcon name="StarOutline" color="#202020" style={{ width: 24, height: 24 }} />;
34
89
  ```
35
90
 
36
- `cacheType` is `OneKeyImageCacheType.NONE`, `.MEMORY`, or `.DISK`.
37
- `placeholder` remains visible through decode and is removed by `onDisplay`,
38
- when the decoded image has actually reached the screen. Overlay containers also
39
- clip their contents so image, placeholder, and fallback share the same rounded
40
- corners.
91
+ Names match `^[A-Z][A-Za-z0-9]*$`; the default size is 24 × 24 and the default
92
+ color is opaque black. `color` only resolves `currentColor` fills and strokes, it
93
+ is not a whole-image tint. The SDK ships no artwork: native builds provide the
94
+ icon bundle and Web builds must alias `#onekey-icon-assets` to the host's
95
+ generated icon table, otherwise named icons render blank.
41
96
 
42
- The default loading strategy is a lightweight static native placeholder. Native
43
- skeleton loading is opt-in and replaces the static loading appearance instead
44
- of appearing as a second stage:
97
+ ## API
45
98
 
46
- ```tsx
47
- <OneKeyImage
48
- source={{ uri }}
49
- loadingStrategy={OneKeyImageLoadingStrategy.SKELETON}
50
- fallback={<UnavailableImagePlaceholder />}
51
- />
52
- ```
99
+ ### `OneKeyImage`
53
100
 
54
- Passing a React `placeholder` disables the native loading strategy for that
55
- instance so only one loading surface is visible.
56
-
57
- Animated images intentionally default to `autoplay={false}` on Android to keep
58
- large lists conservative, and `autoplay={true}` on other native platforms. Pass
59
- `autoplay` explicitly whenever a screen needs the same behavior on both
60
- platforms.
61
-
62
- Animated-image canvas limits are intentionally platform-specific. Android caps
63
- the unavoidable decoded ARGB canvas at 4,194,304 pixels (16 MiB), while iOS
64
- allows metadata dimensions up to 16,000,000 pixels and separately caps its
65
- decoded animation frame buffer at 16 MiB. These limits reflect the native
66
- decoders' different allocation behavior.
67
-
68
- `recyclingKey` is available for recycled list cells. Changing it clears stale
69
- content before the next source is displayed.
70
-
71
- Cache clearing methods resolve only after their requested native cache work has
72
- completed, including `OneKeyImageCache.clearMemory()`.
73
-
74
- Pass the rendered logical dimensions and device pixel ratio when preloading so
75
- TOS URL selection and decode cache identity match the later render. `preload`
76
- resolves to `true` only when all requested sources complete successfully:
77
-
78
- ```ts
79
- const loaded = await OneKeyImageCache.preload([
80
- {
81
- uri,
82
- resizeWidth: 48,
83
- resizeHeight: 64,
84
- pixelRatio: 3,
85
- overscan: 1.1,
86
- },
87
- ]);
88
- ```
101
+ | Prop | Type | Default | Platforms | Description |
102
+ | --- | --- | --- | :-: | --- |
103
+ | `source` | URI source or numeric asset | — | iOS, Android | `null`, blank or unresolved input shows fallback without `onError`. |
104
+ | `variant`, `contentFit` | `generic` \| `token` \| `network` \| `avatar`; `cover` \| `contain` \| `fill` \| `center` | `generic`, `cover` | iOS, Android | Native placeholder/fallback presentation and display/decode sizing. |
105
+ | `cachePolicy`, `loadingStrategy` | `memory-disk` \| `memory` \| `disk` \| `none`; `static` \| `skeleton` \| `none` | `memory-disk`, `static` | iOS, Android | Cache policy (prop wins over source value) and native loading surface; a React `placeholder` disables the native surface. |
106
+ | `placeholder`, `fallback`, `placeholderColor` | `ReactNode`, color | — | iOS, Android | Overlay content clipped to the same rounded bounds (no pointer events) and theme color for native states. |
107
+ | `autoplay`, `recyclingKey`, `round`, `optimizeTos` | `boolean`, `string`, `boolean`, `boolean` | `false` Android / `true` iOS, —, `false`, `true` | iOS, Android | Animated images, request-generation identity, oval clip and bounded OneKey rendition URLs. |
108
+ | `resizeWidth`, `resizeHeight`, `overscan` | `number` | —, —, `1.1` | iOS, Android | Logical-size hints used by preload, TOS selection and memory probing. |
109
+ | `onLoadStart`, `onLoad`, `onLoadEnd`, `onDisplay`, `onError` | event callbacks | — | iOS, Android | `onLoad` receives `{ source: { url, width, height }, cacheType }`. |
110
+ | `hybridRef` | callback ref | — | iOS, Android | Exposes `reload()` and `cancel()`. |
89
111
 
90
- For a CocoaPods static-library integration, declare SDWebImage as a modular
91
- header in the application Podfile:
112
+ ### `OneKeyImageCache`
92
113
 
93
- ```ruby
94
- pod 'SDWebImage', '5.21.7', :modular_headers => true
95
- pod 'SDWebImageWebPCoder', '0.14.6', :modular_headers => true
96
- pod 'SDWebImageSVGCoder', '1.7.0', :modular_headers => true
97
- ```
114
+ | Method | Result | Platforms | Description |
115
+ | --- | --- | --- | :-: |
116
+ | `preload(sources)` | `Promise<boolean>` | iOS, Android | Resolves `true` only when every valid source succeeds. |
117
+ | `clearMemory()`, `clearDisk()`, `clearAll()` | `Promise<void>` | iOS, Android | Resolve after the requested native cache work, including cross-size hints. |
118
+
119
+ Enums exported by the package: `OneKeyImageVariant`, `OneKeyImageContentFit`,
120
+ `OneKeyImageCachePolicy`, `OneKeyImageLoadingStrategy` and
121
+ `OneKeyImageCacheType` (`none`, `memory`, `disk`).
122
+
123
+ ### `OneKeyIcon`
124
+
125
+ | Prop | Type | Platforms | Description |
126
+ | --- | --- | :-: | --- |
127
+ | `name`, `color`, `style` | `string`, `string`, view props | iOS, Android, Web | Required host icon name; native accepts `#hex`/`rgb()`/`rgba()`, Web follows CSS. Explicit dimensions beat the 24 × 24 default. |
128
+
129
+ The package also exports `createNamedIcon(document, name)` from
130
+ `@onekeyfe/react-native-image/icon/dom` for non-React Web surfaces.
131
+
132
+ ## Platform support
133
+
134
+ | Capability | iOS | Android | Web |
135
+ | --- | :-: | :-: | :-: |
136
+ | `OneKeyImage` rendering | ✅ | ✅ | — |
137
+ | Native loading, skeleton and fallback states | ✅ | ✅ | — |
138
+ | Cache preload and clearing | ✅ | ✅ | — |
139
+ | Animated images | ✅ | ✅ | — |
140
+ | `OneKeyIcon` named SVG | ✅ | ✅ | ✅ host-supplied assets |
141
+
142
+ ## Caveats
143
+
144
+ > [!IMPORTANT]
145
+ > `OneKeyImage` is a native view for iOS and Android only. The Web entry of this
146
+ > package provides `OneKeyIcon` and `createNamedIcon`; it never renders
147
+ > `OneKeyImage`.
148
+
149
+ > [!NOTE]
150
+ > Both platforms reject oversized or malformed input: 32 MiB encoded images,
151
+ > 8 MiB decoded data URIs, 16 MiB animated files, 1,000 frames and 60 seconds.
152
+
153
+ > [!WARNING]
154
+ > A reused native view must receive a new `recyclingKey` (or an explicit
155
+ > `reload()`/`cancel()`) when its logical content changes; otherwise stale work
156
+ > from the previous source owns the view.
157
+
158
+ ## References
98
159
 
99
- ## Named icon resource ownership
160
+ - [Package spec](docs/SPEC.md)
161
+ - [Example image page](../../example/react-native/pages/OneKeyImageTestPage.tsx)
162
+ - [npm package](https://www.npmjs.com/package/@onekeyfe/react-native-image)
163
+ - [Changelog](../../CHANGELOG.md)
100
164
 
101
- The host owns canonical SVG artwork and build output. Native builds supply a
102
- `OneKeyIcons.bundle` on iOS and `assets/icons` on Android, including the manifest.
103
- Web builds alias `#onekey-icon-assets` to a generated module exporting
104
- `iconResourceHref(name: string): string | undefined`; the default SDK provider
105
- is empty. `OneKeyIcon` props are unchanged. See [the resource contract](docs/SPEC.md#16-host-owned-icon-resources--implemented-sdk-fixture-runtime-verified).
165
+ ## License
106
166
 
107
- The SDK example carries 63 independent test samples. `icons:check` and
108
- `icons:test` are repository maintenance commands that require the example
109
- fixtures; npm consumers do not receive those samples or the complete catalog.
167
+ MIT. See [LICENSE](LICENSE).
@@ -85,4 +85,5 @@ dependencies {
85
85
  implementation project(":react-native-nitro-modules")
86
86
  implementation project(":onekeyfe_react-native-skeleton")
87
87
  testImplementation "junit:junit:4.13.2"
88
+ testImplementation "org.json:json:20231013"
88
89
  }
@@ -8,3 +8,12 @@
8
8
  *** rewind();
9
9
  }
10
10
  -dontwarn com.bumptech.glide.load.resource.bitmap.VideoDecoder
11
+
12
+ # @onekeyfe/react-native-native-overlay draws toast icons through this registry
13
+ # by reflection (Class.forName + method name and arity), so R8 must keep the
14
+ # class name, the singleton field and these members unrenamed in app builds.
15
+ -keep class com.margelo.nitro.onekeyimage.OneKeyNamedSVG {
16
+ public static final com.margelo.nitro.onekeyimage.OneKeyNamedSVG INSTANCE;
17
+ public final void request(java.lang.Object, android.content.res.AssetManager, java.lang.String, java.lang.String, int, int, float, kotlin.jvm.functions.Function1);
18
+ public final void cancel(java.lang.Object);
19
+ }
@@ -1 +1,12 @@
1
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <application>
3
+ <meta-data
4
+ android:name="com.margelo.nitro.onekeyimage.OneKeyImageGlideModule"
5
+ android:value="GlideModule" />
6
+ <provider
7
+ android:name="com.margelo.nitro.onekeyimage.OneKeyImageStartupProvider"
8
+ android:authorities="${applicationId}.onekeyimagestartup"
9
+ android:exported="false"
10
+ android:initOrder="100" />
11
+ </application>
12
+ </manifest>
@@ -63,7 +63,11 @@ class HybridOneKeyIcon(context: ThemedReactContext) : HybridOneKeyIconSpec(), Re
63
63
  if (displayedGeometry == geometry && ready != null && host.drawable != null) {
64
64
  if (ready.canTint(color)) { applyTint(ready, color); return }
65
65
  } else clearImage()
66
- OneKeyNamedSVG.cachedRender(name, color, host.width, host.height, scale)?.let { hit ->
66
+ val appContext = host.context.applicationContext ?: host.context
67
+ OneKeyNamedSVG.setCacheDirIfNeeded(appContext.cacheDir)
68
+ val hit = OneKeyNamedSVG.cachedRender(name, color, host.width, host.height, scale)
69
+ ?: OneKeyNamedSVG.diskRender(appContext.assets, name, color, host.width, host.height, scale)
70
+ if (hit != null) {
67
71
  displayed = hit; displayedGeometry = geometry
68
72
  applyTint(hit, color)
69
73
  host.setImageBitmap(hit.bitmap)
@@ -11,6 +11,7 @@ import android.graphics.Outline
11
11
  import android.graphics.Paint
12
12
  import android.graphics.Path
13
13
  import android.graphics.drawable.Animatable
14
+ import android.graphics.drawable.BitmapDrawable
14
15
  import android.graphics.drawable.Drawable
15
16
  import android.os.Build
16
17
  import android.os.Looper
@@ -572,7 +573,41 @@ class HybridOneKeyImage(private val context: ThemedReactContext) :
572
573
  addAll(OneKeyImageMemoryVariantRegistry.candidates(family, exactVariant))
573
574
  }.distinct()
574
575
 
576
+ val allowPrewarmedCache = OneKeyImageModel.headers(sourceHeadersJson).isEmpty()
575
577
  for (candidate in candidates) {
578
+ val prewarmedBitmap = if (allowPrewarmedCache) {
579
+ OneKeyImageStartupPrewarm.cachedBitmap(
580
+ requestUrl = candidate.requestUrl,
581
+ width = candidate.width,
582
+ height = candidate.height,
583
+ round = candidate.round,
584
+ headersJson = sourceHeadersJson,
585
+ )
586
+ } else {
587
+ null
588
+ }
589
+ if (prewarmedBitmap != null) {
590
+ clearMemoryPreviewTarget()
591
+ memoryPreviewTarget = null
592
+ memoryPreviewFamily = family
593
+ scalesCenterMemoryPreview = shouldScaleCenterMemoryPreview(
594
+ contentFit = contentFit ?: OneKeyImageContentFit.COVER,
595
+ candidate = candidate,
596
+ target = exactVariant,
597
+ )
598
+ applyContentFit()
599
+ displayState = DisplayState.IMAGE
600
+ requestActive = false
601
+ isPreservingDisplayedImage = false
602
+ hostView.skeletonRequested = false
603
+ hostView.drawStateSymbol = false
604
+ hostView.setBackgroundColor(Color.TRANSPARENT)
605
+ hostView.setImageDrawable(BitmapDrawable(hostView.resources, prewarmedBitmap))
606
+ applyAutoplay()
607
+ OneKeyImageMemoryVariantRegistry.record(family, candidate)
608
+ return true
609
+ }
610
+
576
611
  var synchronousResource: Drawable? = null
577
612
  val target = object : CustomTarget<Drawable>(candidate.width, candidate.height) {
578
613
  override fun onResourceReady(
@@ -631,12 +666,163 @@ class HybridOneKeyImage(private val context: ThemedReactContext) :
631
666
  return false
632
667
  }
633
668
 
669
+ private fun showDirectPrewarmedOrSyncImageIfAvailable(
670
+ rawUrl: String,
671
+ optimizedUrl: String,
672
+ decodeDimensions: OneKeyImageDecodeDimensions,
673
+ memoryFamily: OneKeyImageMemoryFamilyKey,
674
+ policy: OneKeyImageCachePolicy,
675
+ requestGeneration: Long,
676
+ ): Boolean {
677
+ if (
678
+ requestGeneration != generation ||
679
+ disposed ||
680
+ (policy != OneKeyImageCachePolicy.MEMORY && policy != OneKeyImageCachePolicy.MEMORY_DISK) ||
681
+ OneKeyImageModel.headers(sourceHeadersJson).isNotEmpty()
682
+ ) {
683
+ return false
684
+ }
685
+ val urls = if (optimizedUrl == rawUrl) listOf(optimizedUrl) else listOf(optimizedUrl, rawUrl)
686
+ val isRound = round == true
687
+ for (url in urls) {
688
+ val bitmap = OneKeyImageStartupPrewarm.cachedBitmap(
689
+ requestUrl = url,
690
+ width = decodeDimensions.width,
691
+ height = decodeDimensions.height,
692
+ round = isRound,
693
+ headersJson = sourceHeadersJson,
694
+ ) ?: continue
695
+ val hitVariant = OneKeyImageMemoryVariant(
696
+ requestUrl = url,
697
+ width = decodeDimensions.width,
698
+ height = decodeDimensions.height,
699
+ round = isRound,
700
+ )
701
+ clearMemoryPreviewTarget()
702
+ requestActive = false
703
+ displayState = DisplayState.IMAGE
704
+ isPreservingDisplayedImage = false
705
+ hostView.skeletonRequested = false
706
+ hostView.drawStateSymbol = false
707
+ hostView.setBackgroundColor(Color.TRANSPARENT)
708
+ resetImageTransition()
709
+ hostView.setImageDrawable(BitmapDrawable(hostView.resources, bitmap))
710
+ applyContentFit()
711
+ applyAutoplay()
712
+ OneKeyImageMemoryVariantRegistry.record(memoryFamily, hitVariant)
713
+ OneKeyImageStartupPrewarm.note(
714
+ cacheDir = context.applicationContext?.cacheDir ?: context.cacheDir,
715
+ requestUrl = url,
716
+ rawUrl = rawUrl,
717
+ headersJson = sourceHeadersJson,
718
+ cachePolicy = policy,
719
+ width = decodeDimensions.width,
720
+ height = decodeDimensions.height,
721
+ round = isRound,
722
+ )
723
+ val loadCallback = onLoad
724
+ val loadEndCallback = onLoadEnd
725
+ OneKeyTerminalEventPair.dispatch(
726
+ primary = loadCallback?.let { callback ->
727
+ {
728
+ callback(
729
+ bitmap.width.coerceAtLeast(0).toDouble(),
730
+ bitmap.height.coerceAtLeast(0).toDouble(),
731
+ OneKeyImageCacheType.MEMORY,
732
+ )
733
+ }
734
+ },
735
+ onLoadEnd = loadEndCallback,
736
+ )
737
+ if (requestGeneration == generation && !disposed) {
738
+ scheduleOnDisplay(requestGeneration)
739
+ }
740
+ return true
741
+ }
742
+ return false
743
+ }
744
+
745
+ private fun hasGlideExactMemoryCacheHit(
746
+ rawUrl: String,
747
+ optimizedUrl: String,
748
+ decodeDimensions: OneKeyImageDecodeDimensions,
749
+ policy: OneKeyImageCachePolicy,
750
+ requestGeneration: Long,
751
+ ): Boolean {
752
+ if (
753
+ Looper.myLooper() != Looper.getMainLooper() ||
754
+ disposed ||
755
+ requestGeneration != generation ||
756
+ (policy != OneKeyImageCachePolicy.MEMORY && policy != OneKeyImageCachePolicy.MEMORY_DISK)
757
+ ) {
758
+ return false
759
+ }
760
+ val urls = if (optimizedUrl == rawUrl) listOf(optimizedUrl) else listOf(optimizedUrl, rawUrl)
761
+ val isRound = round == true
762
+ for (url in urls) {
763
+ var hit = false
764
+ val probeTarget = object : CustomTarget<Drawable>(decodeDimensions.width, decodeDimensions.height) {
765
+ override fun onResourceReady(
766
+ resource: Drawable,
767
+ transition: Transition<in Drawable>?,
768
+ ) {
769
+ hit = true
770
+ }
771
+
772
+ override fun onLoadCleared(placeholder: Drawable?) = Unit
773
+ }
774
+ requestManager()
775
+ .asDrawable()
776
+ .load(OneKeyImageModel.build(url, sourceHeadersJson))
777
+ .apply(memoryProbeRequestOptions(requestOptions(policy, url, isRound)))
778
+ .override(decodeDimensions.width, decodeDimensions.height)
779
+ .into(probeTarget)
780
+ requestManager().clear(probeTarget)
781
+ if (hit) return true
782
+ }
783
+ return false
784
+ }
785
+
786
+ private fun promoteSmallCachedImageToMemory(
787
+ rawUrl: String,
788
+ optimizedUrl: String,
789
+ decodeDimensions: OneKeyImageDecodeDimensions,
790
+ policy: OneKeyImageCachePolicy,
791
+ ): Boolean {
792
+ if (policy != OneKeyImageCachePolicy.MEMORY_DISK) return false
793
+ if (OneKeyImageModel.headers(sourceHeadersJson).isNotEmpty()) return false
794
+ if (maxOf(decodeDimensions.width, decodeDimensions.height) > OneKeyMainThreadDecode.MAX_THUMBNAIL_PIXEL_SIZE) {
795
+ return false
796
+ }
797
+ val appCacheDir = context.applicationContext?.cacheDir ?: context.cacheDir
798
+ val urls = if (optimizedUrl == rawUrl) listOf(optimizedUrl) else listOf(optimizedUrl, rawUrl)
799
+ val isRound = round == true
800
+ val promoted = OneKeyMainThreadDecode.run {
801
+ for (url in urls) {
802
+ if (
803
+ OneKeyMainThreadDecode.promoteToMemory(
804
+ cacheDir = appCacheDir,
805
+ url = url,
806
+ rawUrl = rawUrl,
807
+ width = decodeDimensions.width,
808
+ height = decodeDimensions.height,
809
+ round = isRound,
810
+ )
811
+ ) {
812
+ return@run true
813
+ }
814
+ }
815
+ null
816
+ }
817
+ return promoted == true
818
+ }
819
+
634
820
  private fun startLoad(force: Boolean) {
635
821
  if (disposed) return
636
822
  if (hostView.width <= 0 || hostView.height <= 0) {
637
823
  cancelCurrent(invalidateGeneration = true, clearMemoryPreview = false)
638
824
  lastSignature = null
639
- if (memoryPreviewTarget == null || hostView.drawable == null) {
825
+ if (memoryPreviewFamily == null || hostView.drawable == null) {
640
826
  showLoading(requestIsActive = false)
641
827
  }
642
828
  return
@@ -692,15 +878,53 @@ class HybridOneKeyImage(private val context: ThemedReactContext) :
692
878
  } else rawUrl
693
879
  val decodeDimensions = OneKeyImageDecodeDimensions.forRender(hostView.width, hostView.height)
694
880
  val memoryFamily = OneKeyImageMemoryFamilyKey.from(rawUrl, sourceHeadersJson)
881
+ val effectivePolicy = cachePolicy ?: OneKeyImageCachePolicy.MEMORY_DISK
695
882
  val exactVariant = OneKeyImageMemoryVariant(
696
883
  requestUrl = optimizedUrl,
697
884
  width = decodeDimensions.width,
698
885
  height = decodeDimensions.height,
699
886
  round = round == true,
700
887
  )
888
+ if (
889
+ showDirectPrewarmedOrSyncImageIfAvailable(
890
+ rawUrl = rawUrl,
891
+ optimizedUrl = optimizedUrl,
892
+ decodeDimensions = decodeDimensions,
893
+ memoryFamily = memoryFamily,
894
+ policy = effectivePolicy,
895
+ requestGeneration = requestGeneration,
896
+ )
897
+ ) {
898
+ return
899
+ }
900
+ if (
901
+ !hasGlideExactMemoryCacheHit(
902
+ rawUrl = rawUrl,
903
+ optimizedUrl = optimizedUrl,
904
+ decodeDimensions = decodeDimensions,
905
+ policy = effectivePolicy,
906
+ requestGeneration = requestGeneration,
907
+ ) &&
908
+ promoteSmallCachedImageToMemory(
909
+ rawUrl = rawUrl,
910
+ optimizedUrl = optimizedUrl,
911
+ decodeDimensions = decodeDimensions,
912
+ policy = effectivePolicy,
913
+ ) &&
914
+ showDirectPrewarmedOrSyncImageIfAvailable(
915
+ rawUrl = rawUrl,
916
+ optimizedUrl = optimizedUrl,
917
+ decodeDimensions = decodeDimensions,
918
+ memoryFamily = memoryFamily,
919
+ policy = effectivePolicy,
920
+ requestGeneration = requestGeneration,
921
+ )
922
+ ) {
923
+ return
924
+ }
701
925
  if (
702
926
  shouldProbeMemoryPreview(
703
- hasTarget = memoryPreviewTarget != null,
927
+ hasTarget = memoryPreviewFamily != null,
704
928
  sameFamily = memoryPreviewFamily == memoryFamily,
705
929
  hasDrawable = hostView.drawable != null,
706
930
  )
@@ -709,7 +933,7 @@ class HybridOneKeyImage(private val context: ThemedReactContext) :
709
933
  family = memoryFamily,
710
934
  exactVariant = exactVariant,
711
935
  includeExact = false,
712
- policy = cachePolicy ?: OneKeyImageCachePolicy.MEMORY_DISK,
936
+ policy = effectivePolicy,
713
937
  requestGeneration = requestGeneration,
714
938
  )
715
939
  }
@@ -719,7 +943,7 @@ class HybridOneKeyImage(private val context: ThemedReactContext) :
719
943
  requestGeneration = requestGeneration,
720
944
  mayFallbackToRaw = optimizedUrl != rawUrl,
721
945
  headersJson = sourceHeadersJson,
722
- policy = cachePolicy ?: OneKeyImageCachePolicy.MEMORY_DISK,
946
+ policy = effectivePolicy,
723
947
  decodeDimensions = decodeDimensions,
724
948
  memoryFamily = memoryFamily,
725
949
  memoryVariant = exactVariant,
@@ -747,13 +971,13 @@ class HybridOneKeyImage(private val context: ThemedReactContext) :
747
971
  if (requestGeneration != generation || disposed) return
748
972
  showLoading(
749
973
  requestIsActive = true,
750
- preserveDisplayedImage = memoryPreviewTarget != null && hostView.drawable != null,
974
+ preserveDisplayedImage = memoryPreviewFamily != null && hostView.drawable != null,
751
975
  )
752
976
  }
753
977
 
754
978
  override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
755
979
  if (requestGeneration != generation || disposed) return
756
- val replacesMemoryPreview = memoryPreviewTarget != null && hostView.drawable != null
980
+ val replacesMemoryPreview = memoryPreviewFamily != null && hostView.drawable != null
757
981
  requestActive = false
758
982
  displayState = DisplayState.IMAGE
759
983
  hostView.skeletonRequested = false
@@ -767,6 +991,16 @@ class HybridOneKeyImage(private val context: ThemedReactContext) :
767
991
  policy == OneKeyImageCachePolicy.MEMORY_DISK)
768
992
  ) {
769
993
  OneKeyImageMemoryVariantRegistry.record(memoryFamily, memoryVariant)
994
+ OneKeyImageStartupPrewarm.note(
995
+ cacheDir = context.applicationContext?.cacheDir ?: context.cacheDir,
996
+ requestUrl = requestUrl,
997
+ rawUrl = rawUrl,
998
+ headersJson = headersJson,
999
+ cachePolicy = policy,
1000
+ width = decodeDimensions.width,
1001
+ height = decodeDimensions.height,
1002
+ round = memoryVariant.round,
1003
+ )
770
1004
  }
771
1005
  clearMemoryPreviewTarget()
772
1006
  applyLoadedImageTransition(
@@ -98,12 +98,14 @@ class HybridOneKeyImageCache : HybridOneKeyImageCacheSpec() {
98
98
  OneKeyMediaPreviewCache.get(context).clearMemory()
99
99
  Glide.get(context).clearMemory()
100
100
  OneKeyImageMemoryVariantRegistry.clear()
101
+ OneKeyImageStartupPrewarm.clearMemoryCache()
101
102
  }
102
103
  }
103
104
 
104
105
  override fun clearDisk(): Promise<Unit> = Promise.async {
105
106
  val context = NitroModules.applicationContext
106
107
  ?: throw IllegalStateException("React application context is unavailable")
108
+ OneKeyImageStartupPrewarm.clearDiskCache(context.cacheDir)
107
109
  kotlinx.coroutines.suspendCancellableCoroutine<Unit> { continuation ->
108
110
  android.os.Handler(android.os.Looper.getMainLooper()).post {
109
111
  OneKeyMediaPreviewCache.get(context).clearDisk { continuation.resumeWith(Result.success(Unit)) }
@@ -119,7 +121,9 @@ class HybridOneKeyImageCache : HybridOneKeyImageCacheSpec() {
119
121
  OneKeyMediaPreviewCache.get(context).clearMemory()
120
122
  Glide.get(context).clearMemory()
121
123
  OneKeyImageMemoryVariantRegistry.clear()
124
+ OneKeyImageStartupPrewarm.clearMemoryCache()
122
125
  }
126
+ OneKeyImageStartupPrewarm.clearDiskCache(context.cacheDir)
123
127
  kotlinx.coroutines.suspendCancellableCoroutine<Unit> { continuation ->
124
128
  android.os.Handler(android.os.Looper.getMainLooper()).post {
125
129
  OneKeyMediaPreviewCache.get(context).clearDisk { continuation.resumeWith(Result.success(Unit)) }
@@ -0,0 +1,17 @@
1
+ package com.margelo.nitro.onekeyimage
2
+
3
+ import android.content.Context
4
+ import com.bumptech.glide.Glide
5
+ import com.bumptech.glide.GlideBuilder
6
+ import com.bumptech.glide.Registry
7
+ import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
8
+ import com.bumptech.glide.module.GlideModule
9
+
10
+ @Suppress("DEPRECATION")
11
+ class OneKeyImageGlideModule : GlideModule {
12
+ override fun applyOptions(context: Context, builder: GlideBuilder) {
13
+ builder.setDiskCache(InternalCacheDiskCacheFactory(context, 320L * 1024 * 1024))
14
+ }
15
+
16
+ override fun registerComponents(context: Context, glide: Glide, registry: Registry) {}
17
+ }