UNPKG

@applicaster/zapp-react-native-utils

Version:

Applicaster Zapp React Native utilities package

68 lines (58 loc) 2.02 kB
import axios from "axios"; import * as R from "ramda"; import { subscriber } from "../../functionUtils"; import { to64 } from "../../stringUtils"; const BASE_64_PREFIX = "data:image/png;base64,"; /** * Constructs an Image object * @param {string} imageUrl url of the image */ export function Image(imageUrl) { /* the inner image object is based on the subscriber object */ const image = subscriber({ url: imageUrl, ready: false }); /** * invokes the `ready` handler for the subscriber object * with the base64 image data from the request. This will set * the base64 data representation for the image, as well as * flag the image as ready to be used * @param {string} base64Img base64 representation of the image */ function invokeImageReadyHandler(base64Img) { image.base64 = base64Img; image.ready = true; image.invokeHandler("ready", image); } /** * invokes the `error` handler of the subscriber object */ function invokeErrorHandler(error) { image.invokeHandler("error", error); } /** * when the object is constructed, we get the image from the url * as an arrayBuffer representation. We then convert that to base64 * then invoke the `ready` handler on the subscription object */ axios .get(imageUrl, { responseType: "arraybuffer" }) .then(R.prop("data")) .then(to64) .then(invokeImageReadyHandler) .catch(invokeErrorHandler); /** * gets the base64 representation of the image data, ready to be used * in a `<img>` source tag. If the image is not ready, will return null */ image.get = function () { return image.ready ? `${BASE_64_PREFIX}${image.base64}` : null; }; /** * gets the base64 representation of the image data, wrapped in a `{ uri }` * object, ready to be used in the source prop of React Native `Image` component. * will return if the image is not ready */ image.getUri = function () { return image.ready ? { uri: image.get() } : null; }; return image; }