1import { ImageSource } from '../Image.types';
2
3type ImageHashType = 'blurhash' | 'thumbhash';
4
5function hashToUri(type: ImageHashType, hash: string): string {
6  const encodedBlurhash = encodeURI(hash).replace(/#/g, '%23').replace(/\?/g, '%3F');
7  return `${type}:/${encodedBlurhash}`;
8}
9
10/**
11 * Converts a blurhash string (`blurhash:/<hash>/<width>/<height>` or <hash>/<width>/<height>) into an `ImageSource`.
12 *
13 * @return An ImageSource representing the provided blurhash.
14 * */
15export function resolveBlurhashString(str: string): ImageSource {
16  const [blurhash, width, height] = str.replace(/^blurhash:\//, '').split('/');
17  return {
18    uri: hashToUri('blurhash', blurhash),
19    width: parseInt(width, 10) || 16,
20    height: parseInt(height, 10) || 16,
21  };
22}
23
24/**
25 * Converts a thumbhash string (`thumbhash:/<hash>` or `<hash>`) into an `ImageSource`.
26 *
27 * @return An ImageSource representing the provided thumbhash.
28 * */
29export function resolveThumbhashString(str: string): ImageSource {
30  const thumbhash = str.replace(/^thumbhash:\//, '');
31  return {
32    uri: hashToUri('thumbhash', thumbhash),
33  };
34}
35