about summary refs log tree commit diff
path: root/src/state/models/cache/image-sizes.ts
blob: 2fd6e0013ba873de56944e020d03961c8f2762b7 (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
35
36
37
import {Image} from 'react-native'
import {Dim} from 'lib/media/manip'

export class ImageSizesCache {
  sizes: Map<string, Dim> = new Map()
  activeRequests: Map<string, Promise<Dim>> = new Map()

  constructor() {}

  get(uri: string): Dim | undefined {
    return this.sizes.get(uri)
  }

  async fetch(uri: string): Promise<Dim> {
    const dim = this.sizes.get(uri)
    if (dim) {
      return dim
    }
    const prom =
      this.activeRequests.get(uri) ||
      new Promise<Dim>(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})
          },
        )
      })
    this.activeRequests.set(uri, prom)
    const res = await prom
    this.activeRequests.delete(uri)
    this.sizes.set(uri, res)
    return res
  }
}