about summary refs log tree commit diff
path: root/src/lib/media/image-sizes.ts
blob: 4ea95ea2377b81e95dc5a8173751982fdcdef1c6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import {Image} from 'react-native'
import type {Dimensions} from 'lib/media/types'

const sizes: Map<string, Dimensions> = new Map()
const activeRequests: Map<string, Promise<Dimensions>> = new Map()

export function get(uri: string): Dimensions | undefined {
  return sizes.get(uri)
}

export async function fetch(uri: string): Promise<Dimensions> {
  const Dimensions = sizes.get(uri)
  if (Dimensions) {
    return Dimensions
  }

  const prom =
    activeRequests.get(uri) ||
    new Promise<Dimensions>(resolve => {
      Image.getSize(
        uri,
        (width: number, height: number) => resolve({width, height}),
        (err: any) => {
          console.error('Failed to fetch image dimensions for', uri, err)
          resolve({width: 0, height: 0})
        },
      )
    })
  activeRequests.set(uri, prom)
  const res = await prom
  activeRequests.delete(uri)
  sizes.set(uri, res)
  return res
}