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