react-native-fast-image
Version:
FastImage, performant React Native image component.
831 lines (830 loc) • 30.2 kB
JavaScript
"use client";
"use client";
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
let react = require("react");
react = __toESM(react);
let react_native = require("react-native");
let react_native_web_dist_modules_AssetRegistry = require("react-native-web/dist/modules/AssetRegistry");
//#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 = react_native.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
};
}
const NO_PADDING = {
padding: 0,
paddingHorizontal: 0,
paddingVertical: 0,
paddingTop: 0,
paddingBottom: 0,
paddingLeft: 0,
paddingRight: 0,
paddingStart: 0,
paddingEnd: 0,
paddingBlock: 0,
paddingBlockStart: 0,
paddingBlockEnd: 0,
paddingInline: 0,
paddingInlineStart: 0,
paddingInlineEnd: 0
};
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 (react.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/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;
}
const round = (n) => Math.round(n * 1e6) / 1e6;
/**
* 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;
}
/** The position as CSS (for the web version's object-position). */
function cssPosition({ x, y }) {
const axis = ({ fraction, offset }) => {
const percent = round(fraction * 100);
const px = round(offset);
if (px === 0) return `${percent}%`;
if (percent === 0) return `${px}px`;
return `calc(${percent}% ${px < 0 ? "-" : "+"} ${Math.abs(px)}px)`;
};
return `${axis(x)} ${axis(y)}`;
}
//#endregion
//#region src/placeholders.ts
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");
}
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/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/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/index.web.tsx
const notSupported = {
ok: false,
error: "Not supported on the web"
};
const useClientLayoutEffect = globalThis.document === void 0 ? react.useEffect : react.useLayoutEffect;
function FastImageBase({ source, placeholder, defaultSource, tintColor, blurRadius, onLoadStart, onLoad, onError, onLoadEnd, style, children, objectFit, objectPosition, loading, sizes, dynamicRangeLimit, forwardedRef, onLayout, pointerEvents, recyclingKey: _recyclingKey, loop: _loop, imageRendering: _imageRendering, paused: _paused, transition: _transition, downsample: _downsample, onProgress: _onProgress, ...props }) {
var _resolveUri, _placeholderSource;
if (typeof __DEV__ !== "undefined" && __DEV__) warnIfChildren(children);
const { accessibilityLabel, "aria-label": ariaLabel, alt, resizeMode: _resizeMode, ...viewProps } = props;
const picked = resolveLabel(ariaLabel, accessibilityLabel, alt);
const label = isLabel(picked) ? picked : void 0;
const several = Array.isArray(source) && source.length > 1 ? source : void 0;
const sized = several ? sizedSources(several) : void 0;
const src = sized ? sized.src : resolveUri(source);
const srcSet = sized === null || sized === void 0 ? void 0 : sized.srcSet;
const key = srcSet !== null && srcSet !== void 0 ? srcSet : src;
const [reloads, setReloads] = (0, react.useState)(0);
const ref = (0, react.useMemo)(() => composeRefs((view) => {
if (view) view.reload = () => setReloads((count) => count + 1);
}, forwardedRef), [forwardedRef]);
const priority = sourcePriority(source);
const preview = hasSourcePlaceholder(placeholder) ? placeholder : void 0;
const blurUri = (_resolveUri = resolveUri(dataUri(shared(source, "blurDataUri", preview)))) !== null && _resolveUri !== void 0 ? _resolveUri : thumbhashUri(shared(source, "thumbhash", preview));
const urlPlaceholder = (_placeholderSource = placeholderSource(placeholder)) === null || _placeholderSource === void 0 ? void 0 : _placeholderSource.uri;
const placeholderKey = `${urlPlaceholder} ${reloads}`;
const [failedPlaceholder, setFailedPlaceholder] = (0, react.useState)();
const defaultUri = blurUri !== null && blurUri !== void 0 ? blurUri : resolveUri(preview ? defaultSource : urlPlaceholder ? void 0 : placeholder !== null && placeholder !== void 0 ? placeholder : defaultSource);
const [result, setResult] = (0, react.useState)();
const [imageSize, setImageSize] = (0, react.useState)();
if (!src && imageSize) setImageSize(void 0);
const single = several ? void 0 : [source].flat()[0];
const own = ownSize(typeof single === "number" ? (0, react_native_web_dist_modules_AssetRegistry.getAssetByID)(single) : single);
const shownSize = own !== null && own !== void 0 ? own : imageSize;
const styleValues = readStyle(style);
const open = openSides(styleValues, own ? "open" : "closed");
const sizeStyle = shownSize && shownSize.width > 0 && shownSize.height > 0 && (open.width || open.height) ? { aspectRatio: shownSize.width / shownSize.height } : void 0;
const bothOpen = open.width && open.height || (open.width || open.height) && open.aspectRatio;
const spacer = sizeStyle && bothOpen ? /* @__PURE__ */ react.default.createElement(react_native.View, {
style: {
width: shownSize.width,
maxWidth: "100%"
},
pointerEvents: "none"
}) : null;
const ok = result && result.key === key ? result.ok : void 0;
const svgId = (0, react.useId)().replace(/[^\w-]/g, "");
const tintId = `fast-image-tint-${svgId}`;
const blurId = `fast-image-blur-${svgId}`;
const fit = resolveObjectFit(objectFit, styleValues);
const position = cssPosition(objectPositionOrCentered(objectPosition));
const filter = [blurRadius ? `blur(${blurRadius}px)` : "", tintColor ? `url(#${tintId})` : ""].filter(Boolean).join(" ") || void 0;
const showDefault = ok !== true;
useClientLayoutEffect(() => {
if (key) onLoadStart === null || onLoadStart === void 0 || onLoadStart();
}, [key, reloads]);
return /* @__PURE__ */ react.default.createElement(react_native.View, {
...viewProps,
"aria-label": label,
style: sizeStyle ? [
styles.container,
spacer && styles.fits,
style,
NO_PADDING,
!open.aspectRatio && sizeStyle
] : [
styles.container,
style,
NO_PADDING
],
onLayout,
pointerEvents,
ref
}, spacer, defaultUri && showDefault ? /* @__PURE__ */ react.default.createElement(Picture, {
key: `default ${defaultUri}`,
src: defaultUri,
loading,
priority,
dynamicRangeLimit,
fit: blurUri && (fit === "scale-down" || fit === "none") ? "contain" : fit,
position,
filter: blurUri ? [`url(#${blurId})`, tintColor ? `url(#${tintId})` : ""].filter(Boolean).join(" ") : filter,
alt: key ? "" : label !== null && label !== void 0 ? label : ""
}) : null, urlPlaceholder && showDefault ? /* @__PURE__ */ react.default.createElement(Picture, {
key: `placeholder ${placeholderKey}`,
src: urlPlaceholder,
loading,
priority: "high",
dynamicRangeLimit,
fit: fit === "scale-down" || fit === "none" ? "contain" : fit,
position,
filter: tintColor ? `url(#${tintId})` : void 0,
hidden: failedPlaceholder === placeholderKey,
onError: () => setFailedPlaceholder(placeholderKey),
alt: ""
}) : null, key && src ? /* @__PURE__ */ react.default.createElement(Picture, {
key: `${several ? "sizes" : key} ${reloads}`,
src,
srcSet,
sizes,
loading,
priority,
dynamicRangeLimit,
fit,
position,
filter,
hidden: ok === false,
alt: label !== null && label !== void 0 ? label : "",
onLoad: (image) => {
const { width, height } = loadedSize(image, sized);
const scale = loadedScale(image, source, sized);
setResult({
key,
ok: true
});
setImageSize((previous) => (previous === null || previous === void 0 ? void 0 : previous.width) === width / scale && previous.height === height / scale ? previous : {
width: width / scale,
height: height / scale
});
onLoad === null || onLoad === void 0 || onLoad({ nativeEvent: {
width,
height
} });
onLoadEnd === null || onLoadEnd === void 0 || onLoadEnd({
ok: true,
width,
height
});
},
onError: (uri) => {
const error = `Failed to load resource ${uri}`;
setResult({
key,
ok: false
});
setImageSize(void 0);
onError === null || onError === void 0 || onError({ nativeEvent: { error } });
onLoadEnd === null || onLoadEnd === void 0 || onLoadEnd({
ok: false,
error
});
}
}) : null, tintColor ? /* @__PURE__ */ react.default.createElement(TintFilter, {
id: tintId,
color: tintColor
}) : null, blurUri && showDefault ? /* @__PURE__ */ react.default.createElement(PreviewBlur, { id: blurId }) : null);
}
function thumbhashUri(hash) {
if (!hash) return void 0;
const decode = globalThis[Symbol.for("react-native-fast-image/thumbhash")];
if (decode) return decode(hash);
if (typeof __DEV__ !== "undefined" && __DEV__) warnOnce("thumbhash-web", "react-native-fast-image: on the web, a `thumbhash` shows only with `import 'react-native-fast-image/thumbhash'` (it decodes them). Or make it a `blurDataUri` before it reaches the browser (e.g. on your server) with that module's thumbHashToBlurDataUri, which needs no JavaScript in the browser.", "warn");
}
function sourcePriority(source) {
const values = (Array.isArray(source) ? source : [source]).map((entry) => entry && typeof entry === "object" ? entry.priority : void 0);
return [
"high",
"normal",
"low"
].find((priority) => values.includes(priority));
}
function shared(source, key, preview) {
const values = (Array.isArray(source) ? source : [source]).map((entry) => {
var _ref;
const own = entry && typeof entry === "object" ? entry : void 0;
return (_ref = (own === null || own === void 0 ? void 0 : own.thumbhash) || dataUri(own === null || own === void 0 ? void 0 : own.blurDataUri) ? own : preview) === null || _ref === void 0 ? void 0 : _ref[key];
});
return values.every((value) => value && value === values[0]) ? values[0] : void 0;
}
function resolveUri(source) {
let uri;
if (typeof source === "number") {
const asset = (0, react_native_web_dist_modules_AssetRegistry.getAssetByID)(source);
if (!asset) return void 0;
const scale = assetScale(asset);
const suffix = scale !== 1 ? `@${scale}x` : "";
uri = `${asset.httpServerLocation}/${asset.name}${suffix}.${asset.type}`;
} else if (typeof source === "string") uri = source;
else if (Array.isArray(source)) return resolveUri(source[0]);
else if (source && typeof source.uri === "string") uri = source.uri;
const svg = uri === null || uri === void 0 ? void 0 : uri.match(/^(data:image\/svg\+xml;utf8,)(.*)/);
return svg ? svg[1] + encodeURIComponent(svg[2]) : uri || void 0;
}
function assetScale(asset) {
var _asset$scales$;
return asset.scales.reduce((best, scale) => Math.abs(scale - react_native.PixelRatio.get()) < Math.abs(best - react_native.PixelRatio.get()) ? scale : best, (_asset$scales$ = asset.scales[0]) !== null && _asset$scales$ !== void 0 ? _asset$scales$ : 1);
}
function sizedSource(source) {
if (typeof source !== "number") return source;
const asset = (0, react_native_web_dist_modules_AssetRegistry.getAssetByID)(source);
return asset ? {
uri: resolveUri(source),
width: asset.width,
height: asset.height,
scale: assetScale(asset)
} : void 0;
}
function sizedSources(entries) {
var _largest$uri, _sources$find;
const sources = entries.map(sizedSource);
const widths = sources.filter((source) => !!(source === null || source === void 0 ? void 0 : source.uri) && !!source.width).map((source) => {
var _source$width, _source$scale, _source$height, _source$scale2, _source$scale3;
return {
uri: source.uri,
width: Math.round(((_source$width = source.width) !== null && _source$width !== void 0 ? _source$width : 0) * ((_source$scale = source.scale) !== null && _source$scale !== void 0 ? _source$scale : 1)),
height: Math.round(((_source$height = source.height) !== null && _source$height !== void 0 ? _source$height : 0) * ((_source$scale2 = source.scale) !== null && _source$scale2 !== void 0 ? _source$scale2 : 1)),
scale: (_source$scale3 = source.scale) !== null && _source$scale3 !== void 0 ? _source$scale3 : 1
};
});
const largest = widths.reduce((best, source) => !best || source.width > best.width ? source : best, void 0);
return {
src: (_largest$uri = largest === null || largest === void 0 ? void 0 : largest.uri) !== null && _largest$uri !== void 0 ? _largest$uri : (_sources$find = sources.find((source) => source === null || source === void 0 ? void 0 : source.uri)) === null || _sources$find === void 0 ? void 0 : _sources$find.uri,
srcSet: widths.length > 0 ? widths.map((source) => `${source.uri} ${source.width}w`).join(", ") : void 0,
widths
};
}
function loadedSize(image, sized) {
const picked = pickedSource(image, sized);
if (!picked) return {
width: image.naturalWidth,
height: image.naturalHeight
};
return {
width: picked.width,
height: image.naturalWidth > 0 ? Math.round(image.naturalHeight * picked.width / image.naturalWidth) : picked.height
};
}
function pickedSource(image, sized) {
return (sized === null || sized === void 0 ? void 0 : sized.srcSet) ? sized.widths.find((source) => new URL(source.uri, image.currentSrc).href === image.currentSrc) : void 0;
}
function loadedScale(image, source, sized) {
var _pickedSource$scale, _pickedSource;
if (sized) return (_pickedSource$scale = (_pickedSource = pickedSource(image, sized)) === null || _pickedSource === void 0 ? void 0 : _pickedSource.scale) !== null && _pickedSource$scale !== void 0 ? _pickedSource$scale : 1;
const single = Array.isArray(source) ? source[0] : source;
if (typeof single === "number") {
const asset = (0, react_native_web_dist_modules_AssetRegistry.getAssetByID)(single);
return asset ? assetScale(asset) : 1;
}
return 1;
}
const fill = {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%"
};
function Picture({ src, srcSet, sizes, loading, priority, dynamicRangeLimit, fit, position, filter, hidden, alt, onLoad, onError }) {
const image = (0, react.useRef)(null);
const mounted = (0, react.useRef)(true);
const handled = (0, react.useRef)(void 0);
const loaded = (target) => {
var _handled$current, _target$decode;
const file = target.currentSrc || src;
const sources = srcSet !== null && srcSet !== void 0 ? srcSet : src;
if (!mounted.current || ((_handled$current = handled.current) === null || _handled$current === void 0 ? void 0 : _handled$current.sources) === sources && handled.current.file === file) return;
handled.current = {
sources,
file
};
const done = () => {
if (mounted.current) onLoad === null || onLoad === void 0 || onLoad(target);
};
Promise.resolve((_target$decode = target.decode) === null || _target$decode === void 0 ? void 0 : _target$decode.call(target)).then(done, done);
};
(0, react.useEffect)(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
useClientLayoutEffect(() => {
var _target$decode2;
const target = image.current;
if (!(target === null || target === void 0 ? void 0 : target.complete)) return;
if (target.naturalWidth > 0) return loaded(target);
Promise.resolve((_target$decode2 = target.decode) === null || _target$decode2 === void 0 ? void 0 : _target$decode2.call(target)).then(() => loaded(target), () => {
if (mounted.current) onError === null || onError === void 0 || onError(target.currentSrc || src);
});
}, []);
return /* @__PURE__ */ react.default.createElement("img", {
ref: image,
src,
srcSet,
sizes: srcSet ? sizes !== null && sizes !== void 0 ? sizes : "auto, 100vw" : void 0,
loading: loading === "eager" ? void 0 : "lazy",
fetchPriority: priority === "high" || priority === "low" ? priority : void 0,
alt,
draggable: false,
style: {
...fill,
objectFit: fit,
objectPosition: position,
filter,
opacity: hidden ? 0 : void 0,
dynamicRangeLimit
},
onLoad: (event) => loaded(event.currentTarget),
onError: (event) => {
const target = event.currentTarget;
if (mounted.current) onError === null || onError === void 0 || onError((target === null || target === void 0 ? void 0 : target.currentSrc) || src);
}
});
}
function TintFilter({ id, color }) {
return /* @__PURE__ */ react.default.createElement("svg", { style: tintStyle }, /* @__PURE__ */ react.default.createElement("defs", null, /* @__PURE__ */ react.default.createElement("filter", { id }, /* @__PURE__ */ react.default.createElement("feFlood", {
floodColor: String(color),
key: String(color)
}), /* @__PURE__ */ react.default.createElement("feComposite", {
in2: "SourceAlpha",
operator: "in"
}))));
}
function PreviewBlur({ id }) {
return /* @__PURE__ */ react.default.createElement("svg", { style: tintStyle }, /* @__PURE__ */ react.default.createElement("defs", null, /* @__PURE__ */ react.default.createElement("filter", {
id,
x: "0",
y: "0",
width: "1",
height: "1",
primitiveUnits: "objectBoundingBox",
colorInterpolationFilters: "sRGB"
}, /* @__PURE__ */ react.default.createElement("feGaussianBlur", { stdDeviation: "0.06" }), /* @__PURE__ */ react.default.createElement("feComponentTransfer", null, /* @__PURE__ */ react.default.createElement("feFuncA", {
type: "table",
tableValues: "0 1 1 1 1"
})))));
}
const tintStyle = {
position: "absolute",
width: 0,
height: 0,
visibility: "hidden"
};
const FastImageMemo = (0, react.memo)(FastImageBase);
const FastImageComponent = (0, react.forwardRef)((props, ref) => /* @__PURE__ */ react.default.createElement(FastImageMemo, {
forwardedRef: ref,
...props
}));
FastImageComponent.displayName = "FastImage";
function getSize(uri) {
return new Promise((resolve) => {
react_native.Image.getSize(uri, (width, height) => resolve({
width,
height
}), () => resolve({
width: 0,
height: 0
}));
});
}
const FastImage = FastImageComponent;
FastImage.cacheControl = cacheControl;
FastImage.priority = priority;
FastImage.resizeMode = resizeMode;
FastImage.preload = (sources) => Promise.all(sources.map((source) => {
const uri = source ? source.uri : void 0;
if (typeof uri !== "string" || !uri) return Promise.resolve({
ok: false,
error: "Invalid source: no uri",
uri
});
return react_native.Image.prefetch(uri).then(() => getSize(uri).then((size) => ({
ok: true,
uri,
...size
})), () => ({
ok: false,
error: "Failed to load the image",
uri
}));
}));
FastImage.clearMemoryCache = () => Promise.resolve(notSupported);
FastImage.clearDiskCache = () => Promise.resolve(notSupported);
FastImage.configureCache = () => Promise.resolve({});
FastImage.setDefaults = () => {};
FastImage.writeToCache = () => Promise.resolve(notSupported);
FastImage.getCachePath = () => Promise.resolve(notSupported);
const styles = react_native.StyleSheet.create({
container: { overflow: "hidden" },
fits: { maxWidth: "100%" }
});
const FastImageBackground = (0, react.forwardRef)(({ style, imageStyle, imageRef, imageProps, children, ...props }, ref) => {
const [image, container] = splitBackgroundProps(props, imageProps);
return /* @__PURE__ */ react.default.createElement(react_native.View, {
...container,
style,
ref
}, /* @__PURE__ */ react.default.createElement(FastImageComponent, {
...image,
style: [react_native.StyleSheet.absoluteFill, imageStyle],
ref: imageRef
}), children);
});
FastImageBackground.displayName = "FastImageBackground";
//#endregion
exports.FastImageBackground = FastImageBackground;
exports.default = FastImage;