react-native-nitro-image-pipeline 1.2.0 → 1.2.1

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 (41) hide show
  1. package/README.md +72 -5
  2. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/HybridNitroImagePipeline.kt +17 -15
  3. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/transform/ResizeTransformation.kt +1 -2
  4. package/ios/HybridNitroImagePipeline.swift +54 -38
  5. package/ios/RoundedCornersProcessor.swift +1 -1
  6. package/lib/commonjs/NitroImagePipeline.js +9 -0
  7. package/lib/commonjs/NitroImagePipeline.js.map +1 -0
  8. package/lib/commonjs/PipelineImage.js +111 -0
  9. package/lib/commonjs/PipelineImage.js.map +1 -0
  10. package/lib/commonjs/index.js +40 -88
  11. package/lib/commonjs/index.js.map +1 -1
  12. package/lib/commonjs/resizeForStyle.js +68 -0
  13. package/lib/commonjs/resizeForStyle.js.map +1 -0
  14. package/lib/commonjs/useImage.js +95 -0
  15. package/lib/commonjs/useImage.js.map +1 -0
  16. package/lib/module/NitroImagePipeline.js +5 -0
  17. package/lib/module/NitroImagePipeline.js.map +1 -0
  18. package/lib/module/PipelineImage.js +107 -0
  19. package/lib/module/PipelineImage.js.map +1 -0
  20. package/lib/module/index.js +4 -86
  21. package/lib/module/index.js.map +1 -1
  22. package/lib/module/resizeForStyle.js +62 -0
  23. package/lib/module/resizeForStyle.js.map +1 -0
  24. package/lib/module/useImage.js +91 -0
  25. package/lib/module/useImage.js.map +1 -0
  26. package/lib/typescript/src/NitroImagePipeline.d.ts +3 -0
  27. package/lib/typescript/src/NitroImagePipeline.d.ts.map +1 -0
  28. package/lib/typescript/src/PipelineImage.d.ts +57 -0
  29. package/lib/typescript/src/PipelineImage.d.ts.map +1 -0
  30. package/lib/typescript/src/index.d.ts +5 -45
  31. package/lib/typescript/src/index.d.ts.map +1 -1
  32. package/lib/typescript/src/resizeForStyle.d.ts +30 -0
  33. package/lib/typescript/src/resizeForStyle.d.ts.map +1 -0
  34. package/lib/typescript/src/useImage.d.ts +53 -0
  35. package/lib/typescript/src/useImage.d.ts.map +1 -0
  36. package/package.json +1 -1
  37. package/src/NitroImagePipeline.ts +6 -0
  38. package/src/PipelineImage.tsx +156 -0
  39. package/src/index.ts +9 -139
  40. package/src/resizeForStyle.ts +96 -0
  41. package/src/useImage.ts +149 -0
@@ -0,0 +1,30 @@
1
+ import { type StyleProp, type ViewStyle } from 'react-native';
2
+ import type { CornerRadii, ResizeOptions } from './specs/nitro-image-toolkit.nitro';
3
+ /**
4
+ * Converts a layout size in points (dp) to the pipeline's `resize` option in
5
+ * whole bitmap pixels using `PixelRatio.getPixelSizeForLayoutSize`. Returns
6
+ * `undefined` unless both values are positive numbers.
7
+ */
8
+ export declare function resizeForLayout(width: unknown, height: unknown): ResizeOptions | undefined;
9
+ /**
10
+ * Derives the pipeline's `resize` option from a view style whose `width` and
11
+ * `height` are numeric points, so the bitmap matches the display size on
12
+ * every screen density:
13
+ * ```ts
14
+ * useImage({ url, resize: resizeForStyle(styles.image) });
15
+ * ```
16
+ * Arrays and registered styles are flattened. Returns `undefined` when either
17
+ * dimension is missing or not a number (`'50%'`, `'auto'`, flex-driven) —
18
+ * use `<PipelineImage>` for those, which measures the view instead.
19
+ */
20
+ export declare function resizeForStyle(style: StyleProp<ViewStyle>): ResizeOptions | undefined;
21
+ /**
22
+ * Derives a `cornerRadius` option from a view style's `borderRadius` /
23
+ * `borderTopLeftRadius` / `borderTopRightRadius` / `borderBottomLeftRadius` /
24
+ * `borderBottomRightRadius`, in points. Per-corner properties override
25
+ * `borderRadius` for that corner; a corner with neither set stays square.
26
+ * Non-numeric values (percentages, animated values) are ignored, like
27
+ * {@linkcode resizeForStyle}. Returns `undefined` when none are set.
28
+ */
29
+ export declare function cornerRadiusForStyle(style: StyleProp<ViewStyle>): number | CornerRadii | undefined;
30
+ //# sourceMappingURL=resizeForStyle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resizeForStyle.d.ts","sourceRoot":"","sources":["../../../src/resizeForStyle.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,SAAS,EAEd,KAAK,SAAS,EACf,MAAM,cAAc,CAAC;AAEtB,OAAO,KAAK,EACV,WAAW,EACX,aAAa,EACd,MAAM,mCAAmC,CAAC;AAE3C;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,OAAO,GACd,aAAa,GAAG,SAAS,CAS3B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,SAAS,CAAC,SAAS,CAAC,GAC1B,aAAa,GAAG,SAAS,CAG3B;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,SAAS,CAAC,SAAS,CAAC,GAC1B,MAAM,GAAG,WAAW,GAAG,SAAS,CAoClC"}
@@ -0,0 +1,53 @@
1
+ import type { Image } from 'react-native-nitro-image';
2
+ import type { CacheOption, CornerRadii, ResizeOptions } from './specs/nitro-image-toolkit.nitro';
3
+ type Result = {
4
+ image: undefined;
5
+ error: undefined;
6
+ } | {
7
+ image: Image;
8
+ error: undefined;
9
+ } | {
10
+ image: undefined;
11
+ error: Error;
12
+ };
13
+ /**
14
+ * A hook to asynchronously load an image from the
15
+ * given {@linkcode AsyncImageSource} into memory.
16
+ * @example
17
+ * ```ts
18
+ * const { image, error } = useImage({ filePath: '/tmp/image.jpg' })
19
+ * ```
20
+ */
21
+ export declare function useImage({ url, blur, cornerRadius, resize, cache, enabled, }: {
22
+ url: string;
23
+ /**
24
+ * Gaussian blur strength, as the standard deviation (sigma) of the blur in
25
+ * source-image pixels (of the resized bitmap when `resize` is set). Matches
26
+ * across iOS and Android; roughly half of React Native's `blurRadius`.
27
+ */
28
+ blur?: number;
29
+ /**
30
+ * Corner radius in pixels of the loaded bitmap. Pass a single number for
31
+ * uniform rounding, or per-corner radii (inline object literals are fine —
32
+ * the hook compares the radii by value, not identity). Pair with `resize`
33
+ * so the radii apply at the size you display instead of the source size.
34
+ */
35
+ cornerRadius?: number | CornerRadii;
36
+ /**
37
+ * Resize the bitmap to exactly this size in pixels (aspect-fill,
38
+ * center-crop) before blur/rounding. Typically your display size in points
39
+ * multiplied by `PixelRatio.get()`. Inline object literals are fine.
40
+ */
41
+ resize?: ResizeOptions;
42
+ cache?: CacheOption;
43
+ /**
44
+ * When `false`, no request is made and the result stays in the loading
45
+ * state (or keeps the current image if `url` is unchanged) until it becomes
46
+ * `true`. Use it to defer loading until inputs such as a layout size are
47
+ * known.
48
+ * @default true
49
+ */
50
+ enabled?: boolean;
51
+ }): Result;
52
+ export {};
53
+ //# sourceMappingURL=useImage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useImage.d.ts","sourceRoot":"","sources":["../../../src/useImage.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,0BAA0B,CAAC;AAGtD,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,aAAa,EACd,MAAM,mCAAmC,CAAC;AAE3C,KAAK,MAAM,GAEP;IACE,KAAK,EAAE,SAAS,CAAC;IACjB,KAAK,EAAE,SAAS,CAAC;CAClB,GAED;IACE,KAAK,EAAE,KAAK,CAAC;IACb,KAAK,EAAE,SAAS,CAAC;CAClB,GAED;IACE,KAAK,EAAE,SAAS,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC;CACd,CAAC;AAEN;;;;;;;GAOG;AACH,wBAAgB,QAAQ,CAAC,EACvB,GAAG,EACH,IAAQ,EACR,YAAgB,EAChB,MAAM,EACN,KAAK,EACL,OAAc,GACf,EAAE;IACD,GAAG,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,WAAW,CAAC;IACpC;;;;OAIG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,MAAM,CA4ET"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-image-pipeline",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "High-performance image loading, caching, and processing for React Native, built with Nitro Modules",
5
5
  "main": "./lib/commonjs/index.js",
6
6
  "module": "./lib/module/index.js",
@@ -0,0 +1,6 @@
1
+ import { NitroModules } from 'react-native-nitro-modules';
2
+
3
+ import type { NitroImagePipeline as NitroImagePipelineSpec } from './specs/nitro-image-toolkit.nitro';
4
+
5
+ export const NitroImagePipeline =
6
+ NitroModules.createHybridObject<NitroImagePipelineSpec>('NitroImagePipeline');
@@ -0,0 +1,156 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import {
3
+ type HostComponent,
4
+ type LayoutChangeEvent,
5
+ PixelRatio,
6
+ } from 'react-native';
7
+ import { type Image, NativeNitroImage } from 'react-native-nitro-image';
8
+
9
+ import {
10
+ cornerRadiusForStyle,
11
+ resizeForLayout,
12
+ resizeForStyle,
13
+ } from './resizeForStyle';
14
+ import type {
15
+ CacheOption,
16
+ CornerRadii,
17
+ ResizeOptions,
18
+ } from './specs/nitro-image-toolkit.nitro';
19
+ import { useImage } from './useImage';
20
+
21
+ type ReactProps<T> = T extends HostComponent<infer P> ? P : never;
22
+ type NativeImageProps = ReactProps<typeof NativeNitroImage>;
23
+
24
+ export interface PipelineImageProps extends Omit<NativeImageProps, 'image'> {
25
+ /** URL of the image to load through the pipeline. */
26
+ url: string;
27
+ /**
28
+ * Gaussian blur sigma in **points** (density-independent). Unlike
29
+ * `useImage`/`loadImage`, where it is bitmap pixels, the component
30
+ * multiplies it by `PixelRatio.get()` so the same value looks the same on
31
+ * every device.
32
+ * @default 0
33
+ */
34
+ blur?: number;
35
+ /**
36
+ * Corner radius in **points** — a single number or per-corner radii.
37
+ * Converted to bitmap pixels with `PixelRatio.get()` and baked into the
38
+ * bitmap at the display size.
39
+ *
40
+ * When omitted, it's derived from `style`'s `borderRadius` /
41
+ * `borderTopLeftRadius` / `borderTopRightRadius` / `borderBottomLeftRadius`
42
+ * / `borderBottomRightRadius` instead — set this prop to override that.
43
+ * @default undefined (derived from `style`, or square corners if unset there)
44
+ */
45
+ cornerRadius?: number | CornerRadii;
46
+ cache?: CacheOption;
47
+ /** Called with the processed `Image` each time a new variant resolves. */
48
+ onLoad?: (image: Image) => void;
49
+ /** Called when loading fails. */
50
+ onError?: (error: Error) => void;
51
+ }
52
+
53
+ function sameSize(a?: ResizeOptions, b?: ResizeOptions): boolean {
54
+ return a?.width === b?.width && a?.height === b?.height;
55
+ }
56
+
57
+ function scaleRadius(
58
+ cornerRadius: number | CornerRadii,
59
+ scale: number,
60
+ ): number | CornerRadii {
61
+ if (typeof cornerRadius === 'number') {
62
+ return cornerRadius * scale;
63
+ }
64
+ return {
65
+ topLeft: (cornerRadius.topLeft ?? 0) * scale,
66
+ topRight: (cornerRadius.topRight ?? 0) * scale,
67
+ bottomLeft: (cornerRadius.bottomLeft ?? 0) * scale,
68
+ bottomRight: (cornerRadius.bottomRight ?? 0) * scale,
69
+ };
70
+ }
71
+
72
+ /**
73
+ * A `NativeNitroImage` that loads `url` through the pipeline at exactly the
74
+ * size it is displayed: the bitmap is resized to the view's size in points ×
75
+ * `PixelRatio.get()`, so `blur` and `cornerRadius` (both in points here) apply
76
+ * 1:1 to what is on screen and large sources are never decoded at full size.
77
+ *
78
+ * A numeric `width`/`height` in `style` starts loading immediately; otherwise
79
+ * (`'50%'`, `flex`, `aspectRatio`, …) loading waits for the first `onLayout`.
80
+ * If the layout size later changes, a new variant is loaded and swapped in
81
+ * without flashing. Without an explicit `cornerRadius` prop, `style`'s
82
+ * `borderRadius`-family properties are baked into the bitmap instead — no
83
+ * separate view-layer rounding needed.
84
+ * @example
85
+ * ```tsx
86
+ * <PipelineImage
87
+ * url="https://example.com/photo.jpg"
88
+ * style={{ width: 300, height: 200 }}
89
+ * cornerRadius={24}
90
+ * />
91
+ * ```
92
+ */
93
+ export function PipelineImage({
94
+ url,
95
+ blur = 0,
96
+ cornerRadius,
97
+ cache,
98
+ onLoad,
99
+ onError,
100
+ style,
101
+ onLayout,
102
+ ...viewProps
103
+ }: PipelineImageProps) {
104
+ const scale = PixelRatio.get();
105
+ const styleSize = resizeForStyle(style);
106
+ const [layoutSize, setLayoutSize] = useState<ResizeOptions | undefined>(
107
+ undefined,
108
+ );
109
+ // A numeric style is what the caller declared, so it wins and starts the
110
+ // request a frame earlier; the measured layout is the fallback.
111
+ const resize = styleSize ?? layoutSize;
112
+ // Same precedence: an explicit prop wins over what style implies.
113
+ const effectiveCornerRadius =
114
+ cornerRadius ?? cornerRadiusForStyle(style) ?? 0;
115
+
116
+ const { image, error } = useImage({
117
+ url,
118
+ blur: blur * scale,
119
+ cornerRadius: scaleRadius(effectiveCornerRadius, scale),
120
+ cache,
121
+ resize,
122
+ enabled: resize !== undefined,
123
+ });
124
+
125
+ // Latest callbacks in refs so inline arrow props don't re-fire the effects.
126
+ const onLoadRef = useRef(onLoad);
127
+ const onErrorRef = useRef(onError);
128
+ useEffect(() => {
129
+ onLoadRef.current = onLoad;
130
+ onErrorRef.current = onError;
131
+ });
132
+ useEffect(() => {
133
+ if (image) onLoadRef.current?.(image);
134
+ }, [image]);
135
+ useEffect(() => {
136
+ if (error) onErrorRef.current?.(error);
137
+ }, [error]);
138
+
139
+ const handleLayout = (event: LayoutChangeEvent) => {
140
+ onLayout?.(event);
141
+ const { width, height } = event.nativeEvent.layout;
142
+ const next = resizeForLayout(width, height);
143
+ // Always record it (even when a numeric style is in charge) so a later
144
+ // switch to a non-numeric style has a size to fall back on.
145
+ setLayoutSize((prev) => (sameSize(prev, next) ? prev : next));
146
+ };
147
+
148
+ return (
149
+ <NativeNitroImage
150
+ {...viewProps}
151
+ style={style}
152
+ onLayout={handleLayout}
153
+ image={image}
154
+ />
155
+ );
156
+ }
package/src/index.ts CHANGED
@@ -1,144 +1,14 @@
1
- import { useEffect, useRef, useState } from 'react';
2
- import type { Image } from 'react-native-nitro-image';
3
- import { NitroModules } from 'react-native-nitro-modules';
4
-
5
- import type {
1
+ export { NitroImagePipeline } from './NitroImagePipeline';
2
+ export { PipelineImage, type PipelineImageProps } from './PipelineImage';
3
+ export {
4
+ cornerRadiusForStyle,
5
+ resizeForLayout,
6
+ resizeForStyle,
7
+ } from './resizeForStyle';
8
+ export type {
6
9
  CacheOption,
7
10
  CornerRadii,
8
- NitroImagePipeline as NitroImagePipelineSpec,
9
11
  Options,
10
12
  ResizeOptions,
11
13
  } from './specs/nitro-image-toolkit.nitro';
12
-
13
- export type { CacheOption, CornerRadii, Options, ResizeOptions };
14
-
15
- export const NitroImagePipeline =
16
- NitroModules.createHybridObject<NitroImagePipelineSpec>('NitroImagePipeline');
17
-
18
- type Result =
19
- // Loading State
20
- | {
21
- image: undefined;
22
- error: undefined;
23
- }
24
- // Loaded state
25
- | {
26
- image: Image;
27
- error: undefined;
28
- }
29
- // Error state
30
- | {
31
- image: undefined;
32
- error: Error;
33
- };
34
-
35
- /**
36
- * A hook to asynchronously load an image from the
37
- * given {@linkcode AsyncImageSource} into memory.
38
- * @example
39
- * ```ts
40
- * const { image, error } = useImage({ filePath: '/tmp/image.jpg' })
41
- * ```
42
- */
43
- export function useImage({
44
- url,
45
- blur = 0,
46
- cornerRadius = 0,
47
- resize,
48
- cache,
49
- }: {
50
- url: string;
51
- /**
52
- * Gaussian blur strength, as the standard deviation (sigma) of the blur in
53
- * source-image pixels (of the resized bitmap when `resize` is set). Matches
54
- * across iOS and Android; roughly half of React Native's `blurRadius`.
55
- */
56
- blur?: number;
57
- /**
58
- * Corner radius in pixels of the loaded bitmap. Pass a single number for
59
- * uniform rounding, or per-corner radii (inline object literals are fine —
60
- * the hook compares the radii by value, not identity). Pair with `resize`
61
- * so the radii apply at the size you display instead of the source size.
62
- */
63
- cornerRadius?: number | CornerRadii;
64
- /**
65
- * Resize the bitmap to exactly this size in pixels (aspect-fill,
66
- * center-crop) before blur/rounding. Typically your display size in points
67
- * multiplied by `PixelRatio.get()`. Inline object literals are fine.
68
- */
69
- resize?: ResizeOptions;
70
- cache?: CacheOption;
71
- }): Result {
72
- const [image, setImage] = useState<Result>({
73
- image: undefined,
74
- error: undefined,
75
- });
76
- const loadedUrlRef = useRef(url);
77
-
78
- // Split the option into primitives so an inline `{ topLeft: 24, ... }`
79
- // literal (new identity every render) doesn't re-trigger the effect.
80
- const isUniformRadius = typeof cornerRadius === 'number';
81
- const uniformRadius = isUniformRadius ? cornerRadius : 0;
82
- const {
83
- topLeft = 0,
84
- topRight = 0,
85
- bottomLeft = 0,
86
- bottomRight = 0,
87
- } = isUniformRadius ? {} : cornerRadius;
88
- const resizeWidth = resize?.width ?? 0;
89
- const resizeHeight = resize?.height ?? 0;
90
-
91
- useEffect(() => {
92
- let cancelled = false;
93
- // Only reset to the loading state when the URL changes; for same-URL
94
- // param tweaks (blur/cornerRadius/cache) keep showing the current image
95
- // until the new variant resolves, to avoid flashing empty.
96
- if (loadedUrlRef.current !== url) {
97
- loadedUrlRef.current = url;
98
- setImage({ image: undefined, error: undefined });
99
- }
100
-
101
- (async () => {
102
- try {
103
- const result = await NitroImagePipeline.loadImage(url, {
104
- blur,
105
- cornerRadius: isUniformRadius
106
- ? uniformRadius
107
- : { topLeft, topRight, bottomLeft, bottomRight },
108
- resize:
109
- resizeWidth > 0 && resizeHeight > 0
110
- ? { width: resizeWidth, height: resizeHeight }
111
- : undefined,
112
- cache,
113
- });
114
-
115
- if (!cancelled) {
116
- setImage({ image: result, error: undefined });
117
- }
118
- } catch (e) {
119
- const error = e instanceof Error ? e : new Error(`${e}`);
120
- if (!cancelled) {
121
- setImage({ image: undefined, error: error });
122
- }
123
- }
124
- })();
125
-
126
- return () => {
127
- cancelled = true;
128
- };
129
- }, [
130
- url,
131
- blur,
132
- isUniformRadius,
133
- uniformRadius,
134
- topLeft,
135
- topRight,
136
- bottomLeft,
137
- bottomRight,
138
- resizeWidth,
139
- resizeHeight,
140
- cache,
141
- ]);
142
-
143
- return image;
144
- }
14
+ export { useImage } from './useImage';
@@ -0,0 +1,96 @@
1
+ import {
2
+ PixelRatio,
3
+ type StyleProp,
4
+ StyleSheet,
5
+ type ViewStyle,
6
+ } from 'react-native';
7
+
8
+ import type {
9
+ CornerRadii,
10
+ ResizeOptions,
11
+ } from './specs/nitro-image-toolkit.nitro';
12
+
13
+ /**
14
+ * Converts a layout size in points (dp) to the pipeline's `resize` option in
15
+ * whole bitmap pixels using `PixelRatio.getPixelSizeForLayoutSize`. Returns
16
+ * `undefined` unless both values are positive numbers.
17
+ */
18
+ export function resizeForLayout(
19
+ width: unknown,
20
+ height: unknown,
21
+ ): ResizeOptions | undefined {
22
+ if (typeof width !== 'number' || typeof height !== 'number') {
23
+ return undefined;
24
+ }
25
+ const pixelWidth = PixelRatio.getPixelSizeForLayoutSize(width);
26
+ const pixelHeight = PixelRatio.getPixelSizeForLayoutSize(height);
27
+ return pixelWidth > 0 && pixelHeight > 0
28
+ ? { width: pixelWidth, height: pixelHeight }
29
+ : undefined;
30
+ }
31
+
32
+ /**
33
+ * Derives the pipeline's `resize` option from a view style whose `width` and
34
+ * `height` are numeric points, so the bitmap matches the display size on
35
+ * every screen density:
36
+ * ```ts
37
+ * useImage({ url, resize: resizeForStyle(styles.image) });
38
+ * ```
39
+ * Arrays and registered styles are flattened. Returns `undefined` when either
40
+ * dimension is missing or not a number (`'50%'`, `'auto'`, flex-driven) —
41
+ * use `<PipelineImage>` for those, which measures the view instead.
42
+ */
43
+ export function resizeForStyle(
44
+ style: StyleProp<ViewStyle>,
45
+ ): ResizeOptions | undefined {
46
+ const flat = StyleSheet.flatten(style);
47
+ return resizeForLayout(flat?.width, flat?.height);
48
+ }
49
+
50
+ /**
51
+ * Derives a `cornerRadius` option from a view style's `borderRadius` /
52
+ * `borderTopLeftRadius` / `borderTopRightRadius` / `borderBottomLeftRadius` /
53
+ * `borderBottomRightRadius`, in points. Per-corner properties override
54
+ * `borderRadius` for that corner; a corner with neither set stays square.
55
+ * Non-numeric values (percentages, animated values) are ignored, like
56
+ * {@linkcode resizeForStyle}. Returns `undefined` when none are set.
57
+ */
58
+ export function cornerRadiusForStyle(
59
+ style: StyleProp<ViewStyle>,
60
+ ): number | CornerRadii | undefined {
61
+ const flat = StyleSheet.flatten(style);
62
+ const base =
63
+ typeof flat?.borderRadius === 'number' ? flat.borderRadius : undefined;
64
+ const topLeft =
65
+ typeof flat?.borderTopLeftRadius === 'number'
66
+ ? flat.borderTopLeftRadius
67
+ : undefined;
68
+ const topRight =
69
+ typeof flat?.borderTopRightRadius === 'number'
70
+ ? flat.borderTopRightRadius
71
+ : undefined;
72
+ const bottomLeft =
73
+ typeof flat?.borderBottomLeftRadius === 'number'
74
+ ? flat.borderBottomLeftRadius
75
+ : undefined;
76
+ const bottomRight =
77
+ typeof flat?.borderBottomRightRadius === 'number'
78
+ ? flat.borderBottomRightRadius
79
+ : undefined;
80
+
81
+ if (
82
+ topLeft === undefined &&
83
+ topRight === undefined &&
84
+ bottomLeft === undefined &&
85
+ bottomRight === undefined
86
+ ) {
87
+ return base;
88
+ }
89
+
90
+ return {
91
+ topLeft: topLeft ?? base,
92
+ topRight: topRight ?? base,
93
+ bottomLeft: bottomLeft ?? base,
94
+ bottomRight: bottomRight ?? base,
95
+ };
96
+ }
@@ -0,0 +1,149 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import type { Image } from 'react-native-nitro-image';
3
+
4
+ import { NitroImagePipeline } from './NitroImagePipeline';
5
+ import type {
6
+ CacheOption,
7
+ CornerRadii,
8
+ ResizeOptions,
9
+ } from './specs/nitro-image-toolkit.nitro';
10
+
11
+ type Result =
12
+ // Loading State
13
+ | {
14
+ image: undefined;
15
+ error: undefined;
16
+ }
17
+ // Loaded state
18
+ | {
19
+ image: Image;
20
+ error: undefined;
21
+ }
22
+ // Error state
23
+ | {
24
+ image: undefined;
25
+ error: Error;
26
+ };
27
+
28
+ /**
29
+ * A hook to asynchronously load an image from the
30
+ * given {@linkcode AsyncImageSource} into memory.
31
+ * @example
32
+ * ```ts
33
+ * const { image, error } = useImage({ filePath: '/tmp/image.jpg' })
34
+ * ```
35
+ */
36
+ export function useImage({
37
+ url,
38
+ blur = 0,
39
+ cornerRadius = 0,
40
+ resize,
41
+ cache,
42
+ enabled = true,
43
+ }: {
44
+ url: string;
45
+ /**
46
+ * Gaussian blur strength, as the standard deviation (sigma) of the blur in
47
+ * source-image pixels (of the resized bitmap when `resize` is set). Matches
48
+ * across iOS and Android; roughly half of React Native's `blurRadius`.
49
+ */
50
+ blur?: number;
51
+ /**
52
+ * Corner radius in pixels of the loaded bitmap. Pass a single number for
53
+ * uniform rounding, or per-corner radii (inline object literals are fine —
54
+ * the hook compares the radii by value, not identity). Pair with `resize`
55
+ * so the radii apply at the size you display instead of the source size.
56
+ */
57
+ cornerRadius?: number | CornerRadii;
58
+ /**
59
+ * Resize the bitmap to exactly this size in pixels (aspect-fill,
60
+ * center-crop) before blur/rounding. Typically your display size in points
61
+ * multiplied by `PixelRatio.get()`. Inline object literals are fine.
62
+ */
63
+ resize?: ResizeOptions;
64
+ cache?: CacheOption;
65
+ /**
66
+ * When `false`, no request is made and the result stays in the loading
67
+ * state (or keeps the current image if `url` is unchanged) until it becomes
68
+ * `true`. Use it to defer loading until inputs such as a layout size are
69
+ * known.
70
+ * @default true
71
+ */
72
+ enabled?: boolean;
73
+ }): Result {
74
+ const [image, setImage] = useState<Result>({
75
+ image: undefined,
76
+ error: undefined,
77
+ });
78
+ const loadedUrlRef = useRef(url);
79
+
80
+ // Split the option into primitives so an inline `{ topLeft: 24, ... }`
81
+ // literal (new identity every render) doesn't re-trigger the effect.
82
+ const isUniformRadius = typeof cornerRadius === 'number';
83
+ const uniformRadius = isUniformRadius ? cornerRadius : 0;
84
+ const {
85
+ topLeft = 0,
86
+ topRight = 0,
87
+ bottomLeft = 0,
88
+ bottomRight = 0,
89
+ } = isUniformRadius ? {} : cornerRadius;
90
+ const resizeWidth = resize?.width ?? 0;
91
+ const resizeHeight = resize?.height ?? 0;
92
+
93
+ useEffect(() => {
94
+ let cancelled = false;
95
+ // Only reset to the loading state when the URL changes; for same-URL
96
+ // param tweaks (blur/cornerRadius/cache) keep showing the current image
97
+ // until the new variant resolves, to avoid flashing empty.
98
+ if (loadedUrlRef.current !== url) {
99
+ loadedUrlRef.current = url;
100
+ setImage({ image: undefined, error: undefined });
101
+ }
102
+
103
+ if (enabled) {
104
+ (async () => {
105
+ try {
106
+ const result = await NitroImagePipeline.loadImage(url, {
107
+ blur,
108
+ cornerRadius: isUniformRadius
109
+ ? uniformRadius
110
+ : { topLeft, topRight, bottomLeft, bottomRight },
111
+ resize:
112
+ resizeWidth > 0 && resizeHeight > 0
113
+ ? { width: resizeWidth, height: resizeHeight }
114
+ : undefined,
115
+ cache,
116
+ });
117
+
118
+ if (!cancelled) {
119
+ setImage({ image: result, error: undefined });
120
+ }
121
+ } catch (e) {
122
+ const error = e instanceof Error ? e : new Error(`${e}`);
123
+ if (!cancelled) {
124
+ setImage({ image: undefined, error: error });
125
+ }
126
+ }
127
+ })();
128
+ }
129
+
130
+ return () => {
131
+ cancelled = true;
132
+ };
133
+ }, [
134
+ url,
135
+ blur,
136
+ isUniformRadius,
137
+ uniformRadius,
138
+ topLeft,
139
+ topRight,
140
+ bottomLeft,
141
+ bottomRight,
142
+ resizeWidth,
143
+ resizeHeight,
144
+ cache,
145
+ enabled,
146
+ ]);
147
+
148
+ return image;
149
+ }