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