@@ -5,51 +5,55 @@ export interface URISource {
55 uri : string
66}
77
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
2114}
2215
2316/**
2417 * @param source either a remote URL or a local file resource.
2518 * @returns original image dimensions (width, height and aspect ratio).
2619 */
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 } )
2922
3023 useEffect ( ( ) => {
3124 try {
3225 if ( typeof source === 'number' ) {
3326 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+
3739 Image . getSize (
3840 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 } ) ,
4147 )
42- } else {
43- throw new Error ( 'not implemented' )
48+
49+ return
4450 }
45- } catch ( e ) {
46- setState ( [ undefined , e ] )
51+
52+ throw new Error ( 'not implemented' )
53+ } catch ( error ) {
54+ setResult ( { error, loading : false } )
4755 }
4856 } , [ source ] )
4957
50- return {
51- dimensions,
52- error,
53- loading : ! dimensions && ! error ,
54- }
58+ return result
5559}
0 commit comments