react-native-fast-image
Version:
FastImage, performant React Native image component.
724 lines (723 loc) • 27 kB
JavaScript
"use client";
"use client";
import React, { Children, forwardRef, memo, useMemo } from "react";
import { Image, Platform, StyleSheet, TurboModuleRegistry, View, codegenNativeCommands, codegenNativeComponent, requireNativeComponent } from "react-native";
//#region src/constants.ts
const resizeMode = {
contain: "contain",
cover: "cover",
stretch: "stretch",
center: "center",
repeat: "repeat"
};
const priority = {
low: "low",
normal: "normal",
high: "high"
};
const cacheControl = {
immutable: "immutable",
web: "web",
cacheOnly: "cacheOnly"
};
//#endregion
//#region src/objectFit.ts
function fromStyleKeys(style, keys) {
const found = {};
collectFromStyle(style, found, new Set(keys));
return found;
}
function collectFromStyle(style, found, missing) {
if (Array.isArray(style)) {
for (let i = style.length - 1; i >= 0 && missing.size > 0; i--) collectFromStyle(style[i], found, missing);
return;
}
if (typeof style === "number") style = StyleSheet.flatten(style);
if (!style || typeof style !== "object") return;
for (const key of missing) if (key in style) {
found[key] = style[key];
missing.delete(key);
}
}
const FITS = {
fill: true,
contain: true,
cover: true,
none: true,
"scale-down": true
};
function resolveObjectFit(objectFit, values) {
const fit = objectFit != null ? objectFit : values.objectFit;
return fit && FITS[fit] === true ? fit : "cover";
}
const SIDE_KEYS = [
"width",
"height",
"aspectRatio",
"position",
"inset",
"insetInline",
"insetInlineStart",
"insetInlineEnd",
"insetBlock",
"insetBlockStart",
"insetBlockEnd",
"left",
"right",
"start",
"end",
"top",
"bottom"
];
function readStyle(style) {
return fromStyleKeys(style, STYLE_KEYS);
}
const STYLE_KEYS = [
"tintColor",
"objectFit",
...SIDE_KEYS
];
function openSides(values, leftOut = "closed") {
const { width, height } = values;
const setWidth = width != null && width !== "auto";
const setHeight = height != null && height !== "auto";
let openWidth = leftOut === "open" ? !setWidth : width === "auto";
let openHeight = leftOut === "open" ? !setHeight : height === "auto";
const aspectRatio = values.aspectRatio != null && values.aspectRatio !== "auto";
if (setWidth !== setHeight && aspectRatio) openWidth = openHeight = false;
if ((openWidth || openHeight) && values.position === "absolute") {
const set = (key) => values[key] != null;
const inset = set("inset");
openWidth && (openWidth = !inset && !set("insetInline") && !((set("left") || set("start") || set("insetInlineStart")) && (set("right") || set("end") || set("insetInlineEnd"))));
openHeight && (openHeight = !inset && !set("insetBlock") && !((set("top") || set("insetBlockStart")) && (set("bottom") || set("insetBlockEnd"))));
}
return {
width: openWidth,
height: openHeight,
aspectRatio
};
}
function ownSize(source) {
if (!source || typeof source !== "object" || Array.isArray(source)) return;
const { width, height } = source;
return typeof width === "number" && typeof height === "number" && width > 0 && height > 0 ? {
width,
height
} : void 0;
}
//#endregion
//#region src/warnings.ts
const warned = /* @__PURE__ */ new Set();
function warnOnce(key, message, level) {
if (!warned.has(key)) {
warned.add(key);
console[level](message);
}
}
function warnIfChildren(children) {
if (Children.toArray(children).length > 0) warnOnce("children", "react-native-fast-image: FastImage doesn't render children (since 10.0): use FastImageBackground for content over an image.", "error");
}
//#endregion
//#region src/headers.ts
function withStringHeaders(source) {
const headers = source === null || source === void 0 ? void 0 : source.headers;
if (headers == null) return source;
if (typeof headers !== "object" || Array.isArray(headers)) {
warn("headers", "`headers` isn't an object, so none are sent");
const { headers: _, ...rest } = source;
return rest;
}
const values = headers;
const names = Object.keys(values);
let sent;
let left;
for (let i = 0; i < names.length; i++) {
const value = values[names[i]];
if (typeof value === "string") {
if (sent) sent[names[i]] = value;
continue;
}
if (!sent) {
sent = {};
for (let j = 0; j < i; j++) sent[names[j]] = values[names[j]];
}
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") sent[names[i]] = String(value);
else if (value != null) {
var _left;
((_left = left) !== null && _left !== void 0 ? _left : left = []).push(`"${names[i]}"`);
}
}
if (left) warn("header-values", `the headers ${left.join(", ")} are objects or functions, so they aren't sent`);
return sent ? {
...source,
headers: sent
} : source;
}
function warn(key, message) {
if (typeof __DEV__ !== "undefined" && __DEV__) warnOnce(key, `react-native-fast-image: ${message}.`, "warn");
}
const ARIA_KEY_SET = /* @__PURE__ */ new Set([
"alt",
"aria-busy",
"aria-checked",
"aria-disabled",
"aria-expanded",
"aria-hidden",
"aria-label",
"aria-labelledby",
"aria-live",
"aria-selected",
"aria-valuemax",
"aria-valuemin",
"aria-valuenow",
"aria-valuetext",
"id",
"tabIndex"
]);
function resolveAriaProps(props) {
const ios = Platform.OS === "ios";
let hasAria = ios && props.focusable != null;
if (!hasAria) {
for (const key in props) if (ARIA_KEY_SET.has(key) && props[key] !== void 0) {
hasAria = true;
break;
}
}
if (!hasAria) return props;
const { alt, "aria-busy": ariaBusy, "aria-checked": ariaChecked, "aria-disabled": ariaDisabled, "aria-expanded": ariaExpanded, "aria-hidden": ariaHidden, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "aria-live": ariaLive, "aria-selected": ariaSelected, "aria-valuemax": ariaValueMax, "aria-valuemin": ariaValueMin, "aria-valuenow": ariaValueNow, "aria-valuetext": ariaValueText, id, tabIndex, ...rest } = props;
const native = rest;
const label = resolveLabel(ariaLabel, native.accessibilityLabel, alt);
if (label !== native.accessibilityLabel) native.accessibilityLabel = label;
if (ariaLabelledBy != null) native.accessibilityLabelledBy = typeof ariaLabelledBy === "string" ? ariaLabelledBy.split(/\s*,\s*/g) : ariaLabelledBy;
if (ariaLive !== void 0) native.accessibilityLiveRegion = ariaLive === "off" ? "none" : ariaLive;
if (ariaHidden !== void 0) {
native.accessibilityElementsHidden = ariaHidden;
if (ariaHidden === true) {
native.importantForAccessibility = "no-hide-descendants";
if (ios) native.accessible = false;
}
}
if (id !== void 0) native.nativeID = id;
if (tabIndex !== void 0) native.focusable = !tabIndex;
if (ios && native.focusable != null) native.isTVSelectable = native.focusable;
if (ios && isLabel(label) && (ariaLabel != null || label === alt) && native.accessible == null && !native.accessibilityElementsHidden) native.accessible = true;
if (ariaBusy != null || ariaChecked != null || ariaDisabled != null || ariaExpanded != null || ariaSelected != null) {
const state = props.accessibilityState;
native.accessibilityState = {
busy: ariaBusy !== null && ariaBusy !== void 0 ? ariaBusy : state === null || state === void 0 ? void 0 : state.busy,
checked: ariaChecked !== null && ariaChecked !== void 0 ? ariaChecked : state === null || state === void 0 ? void 0 : state.checked,
disabled: ariaDisabled !== null && ariaDisabled !== void 0 ? ariaDisabled : state === null || state === void 0 ? void 0 : state.disabled,
expanded: ariaExpanded !== null && ariaExpanded !== void 0 ? ariaExpanded : state === null || state === void 0 ? void 0 : state.expanded,
selected: ariaSelected !== null && ariaSelected !== void 0 ? ariaSelected : state === null || state === void 0 ? void 0 : state.selected
};
}
if (ariaValueMax != null || ariaValueMin != null || ariaValueNow != null || ariaValueText != null) {
const value = props.accessibilityValue;
native.accessibilityValue = {
max: ariaValueMax !== null && ariaValueMax !== void 0 ? ariaValueMax : value === null || value === void 0 ? void 0 : value.max,
min: ariaValueMin !== null && ariaValueMin !== void 0 ? ariaValueMin : value === null || value === void 0 ? void 0 : value.min,
now: ariaValueNow !== null && ariaValueNow !== void 0 ? ariaValueNow : value === null || value === void 0 ? void 0 : value.now,
text: ariaValueText !== null && ariaValueText !== void 0 ? ariaValueText : value === null || value === void 0 ? void 0 : value.text
};
}
return native;
}
function resolveLabel(ariaLabel, accessibilityLabel, alt) {
const label = ariaLabel !== void 0 ? ariaLabel : accessibilityLabel;
return label == null && accessibilityLabel == null && isLabel(alt) ? alt : label;
}
function isLabel(value) {
return typeof value === "string" && value.trim() !== "";
}
//#endregion
//#region src/backgroundProps.ts
const IMAGE_KEY_SET = /* @__PURE__ */ new Set([
...Object.keys({
source: true,
placeholder: true,
defaultSource: true,
objectFit: true,
objectPosition: true,
recyclingKey: true,
loop: true,
imageRendering: true,
loading: true,
sizes: true,
paused: true,
transition: true,
downsample: true,
dynamicRangeLimit: true,
blurRadius: true,
tintColor: true,
alt: true,
onLoadStart: true,
onProgress: true,
onLoad: true,
onError: true,
onLoadEnd: true
}),
"fallback",
"resizeMode"
]);
function splitBackgroundProps(props, imageProps) {
const image = {};
const container = {};
for (const key in props) {
const value = props[key];
if (IMAGE_KEY_SET.has(key)) image[key] = value;
else container[key] = value;
}
if (imageProps) for (const key in imageProps) {
const value = imageProps[key];
if (value !== void 0) image[key] = value;
}
return [image, container];
}
//#endregion
//#region src/objectPosition.ts
const START = {
fraction: 0,
offset: 0
};
const CENTER = {
fraction: .5,
offset: 0
};
const END = {
fraction: 1,
offset: 0
};
/** The default, `50% 50%`. */
const CENTERED = {
x: CENTER,
y: CENTER
};
const NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
function length(text) {
const lower = text.toLowerCase();
if (lower.endsWith("%")) {
const number = lower.slice(0, -1);
return NUMBER.test(number) ? {
fraction: Number(number) / 100,
offset: 0
} : null;
}
if (lower.endsWith("px")) {
const number = lower.slice(0, -2);
return NUMBER.test(number) ? {
fraction: 0,
offset: Number(number)
} : null;
}
return NUMBER.test(lower) && Number(lower) === 0 ? START : null;
}
function token(text) {
const lower = text.toLowerCase();
if (lower === "left" || lower === "right" || lower === "top" || lower === "bottom" || lower === "center") return { keyword: lower };
const axis = length(text);
return axis ? { length: axis } : null;
}
const X = {
left: START,
center: CENTER,
right: END
};
const Y = {
top: START,
center: CENTER,
bottom: END
};
const x = (t) => "length" in t ? t.length : X[t.keyword];
const y = (t) => "length" in t ? t.length : Y[t.keyword];
function fromEdge(edge, axis) {
return edge === "left" || edge === "top" ? axis : {
fraction: 1 - axis.fraction,
offset: -axis.offset || 0
};
}
function parse(text) {
const tokens = [];
for (const part of text.trim().split(/\s+/)) {
const t = token(part);
if (!t) return null;
tokens.push(t);
}
if (tokens.length === 1) {
const [a] = tokens;
if ("keyword" in a && (a.keyword === "top" || a.keyword === "bottom")) return {
x: CENTER,
y: Y[a.keyword]
};
return {
x: x(a),
y: CENTER
};
}
if (tokens.length === 2) {
const [a, b] = tokens;
const ax = x(a);
const by = y(b);
if (ax && by) return {
x: ax,
y: by
};
if ("keyword" in a && "keyword" in b) {
const bx = X[b.keyword];
const ay = Y[a.keyword];
if (bx && ay) return {
x: bx,
y: ay
};
}
return null;
}
if (tokens.length === 4) {
const [a, b, c, d] = tokens;
if (!("keyword" in a && "length" in b && "keyword" in c && "length" in d)) return null;
const horizontal = (k) => k === "left" || k === "right";
const vertical = (k) => k === "top" || k === "bottom";
if (horizontal(a.keyword) && vertical(c.keyword)) return {
x: fromEdge(a.keyword, b.length),
y: fromEdge(c.keyword, d.length)
};
if (vertical(a.keyword) && horizontal(c.keyword)) return {
x: fromEdge(c.keyword, d.length),
y: fromEdge(a.keyword, b.length)
};
}
return null;
}
const parsed = /* @__PURE__ */ new Map();
function objectLength(value) {
if (typeof value === "number") return Number.isFinite(value) ? {
fraction: 0,
offset: value
} : null;
return typeof value === "string" && value.endsWith("%") ? length(value) : null;
}
/**
* The position for objectPosition, or null if it isn't valid. A string is
* CSS's syntax; an object has one of `top` and `bottom` and one of `left`
* and `right`, each in points or a percentage, and a missing axis is
* centered. Unset is centered.
*/
function resolveObjectPosition(position) {
if (position == null) return CENTERED;
if (typeof position === "string") {
let result = parsed.get(position);
if (result === void 0) {
result = parse(position);
if (parsed.size < 100) parsed.set(position, result);
}
return result;
}
if (typeof position !== "object") return null;
const edges = position;
const axis = (start, end) => {
const hasStart = edges[start] != null;
const hasEnd = edges[end] != null;
if (hasStart && hasEnd) return null;
if (!hasStart && !hasEnd) return CENTER;
const edge = hasStart ? start : end;
const value = objectLength(edges[edge]);
return value && fromEdge(edge, value);
};
const resolvedX = axis("left", "right");
const resolvedY = axis("top", "bottom");
return resolvedX && resolvedY ? {
x: resolvedX,
y: resolvedY
} : null;
}
/**
* The position for objectPosition, or centered if it isn't valid (as CSS
* ignores it), with a warning in development.
*/
function objectPositionOrCentered(position) {
const resolved = resolveObjectPosition(position);
if (resolved) return resolved;
if (typeof __DEV__ !== "undefined" && __DEV__) {
const value = JSON.stringify(position);
warnOnce(`objectPosition ${value}`, `react-native-fast-image: objectPosition ${value} isn't a position, so the image is centered. Use CSS's syntax with px or % (e.g. 'right 10px bottom 20%'), or { top | bottom, left | right } in points or percentages.`, "warn");
}
return CENTERED;
}
//#endregion
//#region src/specs/FastImageViewNativeComponent.ts
const Commands = codegenNativeCommands({ supportedCommands: ["reload"] });
var FastImageViewNativeComponent_default = codegenNativeComponent("FastImageView", { interfaceOnly: true });
var FastImageAutoView_default = requireNativeComponent("FastImageAutoView");
//#endregion
//#region src/specs/NativeFastImageModule.ts
var NativeFastImageModule_default = TurboModuleRegistry.get("FastImageModule");
//#endregion
//#region src/placeholders.ts
const SCHEME = /^[a-z][a-z\d+.-]*:/i;
function isImageName(value) {
return !SCHEME.test(value) && !value.startsWith("/");
}
function placeholderSource(value) {
const uri = typeof value === "string" ? value : value && typeof value === "object" ? value.uri : void 0;
if (typeof uri !== "string" || !/^https?:/i.test(uri)) return void 0;
return typeof value === "string" ? { uri } : value;
}
function hasSourcePlaceholder(value) {
return !!value && typeof value === "object" && ("thumbhash" in value || "blurDataUri" in value);
}
function dataUri(value) {
if (typeof value !== "string" || value === "") return void 0;
if (/^data:/i.test(value)) return value;
if (typeof __DEV__ !== "undefined" && __DEV__) warnOnce("placeholder-url", `react-native-fast-image: \`blurDataUri\` takes a data uri (data:image/…): "${value.slice(0, 60)}" is ignored. For a placeholder loaded from a url, use \`placeholder\`.`, "warn");
}
//#endregion
//#region src/composeRefs.ts
function composeRefs(...refs) {
return (value) => {
const cleanups = refs.map((ref) => {
if (typeof ref === "function") {
const cleanup = ref(value);
return typeof cleanup === "function" ? cleanup : () => {
ref(null);
};
}
if (ref) {
ref.current = value;
return () => {
ref.current = null;
};
}
});
return () => cleanups.forEach((cleanup) => cleanup === null || cleanup === void 0 ? void 0 : cleanup());
};
}
//#endregion
//#region src/reactNativeCache.ts
function warnIfReload(source) {
if (typeof __DEV__ !== "undefined" && __DEV__ && (source === null || source === void 0 ? void 0 : source.cache) === "reload") warnOnce("cache-reload", "react-native-fast-image: `cache: 'reload'` loads the image as the default, `'immutable'`: it isn't loaded again each time. For an image that changes at the same url, use `cache: 'web'` (it follows the server's cache headers), or change its `cacheKey`.", "warn");
}
//#endregion
//#region src/index.tsx
const resolvePlaceholder = (placeholder) => {
if (typeof placeholder === "string") {
if (isImageName(placeholder)) return Platform.OS === "android" ? placeholder : { uri: placeholder };
const uri = dataUri(placeholder);
if (!uri) return null;
return Platform.OS === "android" ? uri : { uri };
}
if (!placeholder) return null;
const resolved = Image.resolveAssetSource(placeholder);
if (!resolved) return null;
return Platform.OS === "android" ? resolved.uri : resolved;
};
function loopCount(loop) {
if (loop === void 0) return -1;
if (loop === true) return 0;
if (loop === false) return 1;
return Number.isFinite(loop) ? Math.max(1, Math.floor(loop)) : 0;
}
function loadResult(event) {
var _event$width, _event$height, _event$error;
return event.ok ? {
ok: true,
width: (_event$width = event.width) !== null && _event$width !== void 0 ? _event$width : 0,
height: (_event$height = event.height) !== null && _event$height !== void 0 ? _event$height : 0
} : {
ok: false,
error: (_event$error = event.error) !== null && _event$error !== void 0 ? _event$error : "Failed to load the image"
};
}
function handledEvents({ onLoadStart, onProgress, onLoad, onError, onLoadEnd }) {
return (onLoadStart ? 1 : 0) | (onProgress ? 2 : 0) | (onLoad ? 4 : 0) | (onError ? 8 : 0) | (onLoadEnd ? 16 : 0);
}
function usualFadeMs() {
return Platform.OS === "ios" ? 250 : 300;
}
const NO_TRANSITION = {
transitionDuration: 0,
transitionBetweenImages: false,
transitionSkipOnCacheHit: "memory"
};
function resolveTransition(transition, base) {
if (transition == null) return base;
if (transition === false) return {
...base,
transitionDuration: 0
};
const usual = base.transitionDuration > 0 ? base.transitionDuration : usualFadeMs();
if (transition === true) return {
...base,
transitionDuration: usual
};
const { duration, betweenImages, skipOnCacheHit } = typeof transition === "number" ? { duration: transition } : transition;
const resolvedDuration = duration !== null && duration !== void 0 ? duration : usual;
return {
transitionDuration: typeof resolvedDuration === "number" && resolvedDuration > 0 ? resolvedDuration : 0,
transitionBetweenImages: betweenImages !== null && betweenImages !== void 0 ? betweenImages : base.transitionBetweenImages,
transitionSkipOnCacheHit: skipOnCacheHit !== null && skipOnCacheHit !== void 0 ? skipOnCacheHit : base.transitionSkipOnCacheHit
};
}
function builtInTransition() {
return resolveTransition(Platform.OS === "android", NO_TRANSITION);
}
let defaultTransition;
function FastImageBase({ source, placeholder, defaultSource, tintColor, onLoadStart, onProgress, onLoad, onError, onLoadEnd, style, children, objectFit, objectPosition, loop, transition, loading: _loading, sizes: _sizes, forwardedRef, ...viewProps }) {
var _props$recyclingKey, _defaultTransition;
const { fallback, resizeMode: _resizeMode, ...props } = viewProps;
if (__DEV__ && fallback !== void 0) warnOnce("fallback", "react-native-fast-image: `fallback` was removed in 10.0, and does nothing: images always load natively. Remove it, or use React Native's Image for those images.", "warn");
if (__DEV__) warnIfChildren(children);
const styleValues = readStyle(style);
const resolvedTintColor = tintColor != null ? tintColor : styleValues.tintColor;
const fit = resolveObjectFit(objectFit, styleValues);
const position = objectPositionOrCentered(objectPosition);
const resolvedSource = useMemo(() => {
if (__DEV__) for (const entry of [source].flat()) {
dataUri(entry === null || entry === void 0 ? void 0 : entry.blurDataUri);
warnIfReload(entry);
}
const single = Array.isArray(source) && source.length === 1 ? source[0] : source;
return Array.isArray(single) ? single.map((entry) => Image.resolveAssetSource(withStringHeaders(entry))) : Image.resolveAssetSource(withStringHeaders(single));
}, [source]);
const own = ownSize(resolvedSource);
const open = own ? {
width: false,
height: false
} : openSides(styleValues);
const NativeView = own || open.width || open.height ? FastImageAutoView_default : FastImageViewNativeComponent_default;
const resolvedPlaceholder = useMemo(() => {
var _withStringHeaders;
return hasSourcePlaceholder(placeholder) ? placeholder.thumbhash || dataUri(placeholder.blurDataUri) ? placeholder : resolvePlaceholder(defaultSource) : (_withStringHeaders = withStringHeaders(placeholderSource(placeholder))) !== null && _withStringHeaders !== void 0 ? _withStringHeaders : resolvePlaceholder(placeholder !== null && placeholder !== void 0 ? placeholder : defaultSource);
}, [placeholder, defaultSource]);
const ref = useMemo(() => composeRefs(addReload, forwardedRef), [forwardedRef]);
return /* @__PURE__ */ React.createElement(NativeView, {
...resolveAriaProps(props),
ref,
style: [styles.image, style],
recyclingKey: (_props$recyclingKey = props.recyclingKey) !== null && _props$recyclingKey !== void 0 ? _props$recyclingKey : void 0,
loopCount: loopCount(loop),
...resolveTransition(transition, (_defaultTransition = defaultTransition) !== null && _defaultTransition !== void 0 ? _defaultTransition : builtInTransition()),
source: resolvedSource,
placeholder: resolvedPlaceholder,
autoSize: (open.width ? 1 : 0) | (open.height ? 2 : 0) || void 0,
ownWidth: own === null || own === void 0 ? void 0 : own.width,
ownHeight: own === null || own === void 0 ? void 0 : own.height,
onFastImageLoadStart: onLoadStart,
onFastImageProgress: onProgress,
handledEvents: handledEvents({
onLoadStart,
onProgress,
onLoad,
onError,
onLoadEnd
}),
onFastImageLoad: onLoad,
onFastImageError: onError,
onFastImageLoadEnd: onLoadEnd && ((event) => onLoadEnd(loadResult(event.nativeEvent))),
tintColor: resolvedTintColor,
objectFit: fit,
objectPositionX: position.x.fraction,
objectPositionXOffset: position.x.offset,
objectPositionY: position.y.fraction,
objectPositionYOffset: position.y.offset
});
}
function addReload(view) {
if (view) view.reload = () => Commands.reload(view);
}
const FastImageMemo = memo(FastImageBase);
const FastImageComponent = forwardRef((props, ref) => /* @__PURE__ */ React.createElement(FastImageMemo, {
forwardedRef: ref,
...props
}));
FastImageComponent.displayName = "FastImage";
const noResult = {
ok: false,
error: "No result"
};
function nativeModule() {
if (!NativeFastImageModule_default) throw new Error("react-native-fast-image: the native module FastImageModule isn't in this app. Rebuild the app after installing the package (run pod install on iOS). It needs the New Architecture, and isn't in Expo Go: use a development build. In Jest, mock the function (e.g. jest.spyOn(FastImage, \"preload\")).");
return NativeFastImageModule_default;
}
const FastImage = FastImageComponent;
FastImage.cacheControl = cacheControl;
FastImage.priority = priority;
FastImage.resizeMode = resizeMode;
FastImage.setDefaults = ({ transition } = {}) => {
if (transition === null) defaultTransition = void 0;
else if (transition !== void 0) defaultTransition = resolveTransition(transition, builtInTransition());
};
const ONE_SOURCE = "Takes one source, not an array of sizes: pass the size to use";
const isSourceObject = (source) => typeof source === "object" && source !== null && !Array.isArray(source);
function nativeSource(source) {
return isSourceObject(source) ? withStringHeaders(source) : {};
}
FastImage.preload = (sources) => Promise.resolve(nativeModule().preload(sources.map(nativeSource))).then((results) => sources.map((source, i) => {
var _results$i;
if (Array.isArray(source)) return {
ok: false,
error: ONE_SOURCE,
uri: void 0
};
const uri = isSourceObject(source) ? source.uri : void 0;
const result = (_results$i = results === null || results === void 0 ? void 0 : results[i]) !== null && _results$i !== void 0 ? _results$i : noResult;
if (!result.ok) return {
...result,
uri
};
return typeof uri === "string" ? {
...result,
uri
} : {
ok: false,
error: "Invalid source: no uri",
uri
};
}));
FastImage.clearMemoryCache = () => nativeModule().clearMemoryCache();
FastImage.clearDiskCache = () => nativeModule().clearDiskCache();
FastImage.configureCache = (limits) => {
const set = {};
const reset = [];
for (const [name, value] of Object.entries(limits !== null && limits !== void 0 ? limits : {})) if (value === null) reset.push(name);
else if (typeof value === "number") set[name] = value;
return nativeModule().configureCache({
...set,
reset
});
};
FastImage.writeToCache = (source, file) => Array.isArray(source) ? Promise.resolve({
ok: false,
error: ONE_SOURCE
}) : Promise.resolve(nativeModule().writeToCache(nativeSource(source), file));
FastImage.getCachePath = (source) => Array.isArray(source) ? Promise.resolve({
ok: false,
error: ONE_SOURCE
}) : Promise.resolve(nativeModule().getCachePath(nativeSource(source)));
const styles = StyleSheet.create({ image: { overflow: "hidden" } });
/**
* An image with content on top of it, like React Native's `ImageBackground`: a
* view that the image fills, with the children on top (`FastImage` is a single
* native view, which doesn't take children). View props (accessibility,
* focus, testID, layout, touch) go to the view, FastImage's own to the image,
* and `imageProps` to the image over them; the ref is the view's.
*/
const FastImageBackground = forwardRef(({ style, imageStyle, imageRef, imageProps, children, ...props }, ref) => {
var _container$accessibil;
const [image, container] = splitBackgroundProps(props, imageProps);
if (container.tabIndex !== void 0) {
container.focusable = !container.tabIndex;
delete container.tabIndex;
}
return /* @__PURE__ */ React.createElement(View, {
...container,
accessibilityIgnoresInvertColors: (_container$accessibil = container.accessibilityIgnoresInvertColors) !== null && _container$accessibil !== void 0 ? _container$accessibil : true,
style,
ref
}, /* @__PURE__ */ React.createElement(FastImageComponent, {
...image,
style: [StyleSheet.absoluteFill, imageStyle],
ref: imageRef
}), children);
});
FastImageBackground.displayName = "FastImageBackground";
//#endregion
export { FastImageBackground, FastImage as default };