@@ -7,30 +7,51 @@ export interface URISource {
7
7
8
8
/**
9
9
* @param source either a remote URL or a local file resource.
10
- * @returns original image width and height.
10
+ * @returns original image dimensions ( width and height) .
11
11
*/
12
12
function useImageDimensions ( source : ImageRequireSource | URISource ) {
13
- const [ state , setState ] = useState < {
14
- width ?: number
15
- height ?: number
16
- loading ?: boolean
17
- error ?: any
18
- } > ( { } )
13
+ const localAsset = typeof source === 'number'
14
+ const [ dimensions , setDimensions ] = useState <
15
+ | {
16
+ width : number
17
+ height : number
18
+ }
19
+ | undefined
20
+ > ( localAsset ? Image . resolveAssetSource ( source ) : undefined )
21
+ const [ error , setError ] = useState < Error > ( )
19
22
useEffect ( ( ) => {
20
- if ( typeof source === 'object' && typeof source . uri === 'string' ) {
21
- setState ( { loading : true } )
23
+ if ( localAsset ) {
24
+ return
25
+ }
26
+ try {
22
27
Image . getSize (
23
- source . uri ,
24
- ( width , height ) => setState ( { width, height} ) ,
25
- error => setState ( { error} ) ,
28
+ ( source as URISource ) . uri ,
29
+ ( width , height ) => setDimensions ( { width, height} ) ,
30
+ e => {
31
+ throw e
32
+ } ,
26
33
)
27
- } else if ( typeof source === 'number' ) {
28
- setState ( Image . resolveAssetSource ( source ) )
29
- } else {
30
- setState ( { error : 'not implemented' } )
34
+ } catch ( e ) {
35
+ setError ( e )
31
36
}
32
- } , [ source ] )
33
- return state
37
+ } , [ source , localAsset ] )
38
+
39
+ return {
40
+ dimensions,
41
+ error,
42
+ /**
43
+ * width to height ratio
44
+ */
45
+ get aspectRatio ( ) {
46
+ return dimensions && dimensions . width / dimensions . height
47
+ } ,
48
+ /**
49
+ * loading indicator for remote image
50
+ */
51
+ get loading ( ) {
52
+ return ! dimensions && ! error
53
+ } ,
54
+ }
34
55
}
35
56
36
57
export default useImageDimensions
0 commit comments