Fix/avatar flashing (#3987)

* fix(use-image): cached image flashing

* chore: merged with canary

---------

Co-authored-by: Rakha Kanz Kautsar <rkkautsar@gmail.com>
This commit is contained in:
Junior Garcia 2024-11-04 17:57:28 -03:00 committed by GitHub
parent ad7e2615d3
commit 90cb5b14ab
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 5610 additions and 5703 deletions

View File

@ -0,0 +1,6 @@
---
"@nextui-org/use-image": patch
"@nextui-org/test-utils": patch
---
fix cached image flashing due to use-image always returning pending initially. The fix was to check if the image is loaded instantly through HTMLImageElement.complete attribute and use that to initialize the state.

View File

@ -0,0 +1,44 @@
import {renderHook} from "@testing-library/react-hooks";
import {mocks} from "@nextui-org/test-utils";
import {useImage} from "../src";
describe("use-image hook", () => {
let mockImage: {restore: any; simulate: (value: "loaded" | "error") => void};
beforeEach(() => {
mockImage = mocks.image();
});
afterEach(() => {
mockImage.restore();
});
it("can handle missing src", () => {
const rendered = renderHook(() => useImage({}));
expect(rendered.result.current).toEqual("pending");
});
it("can handle loading image", async () => {
const rendered = renderHook(() => useImage({src: "/test.png"}));
expect(rendered.result.current).toEqual("loading");
mockImage.simulate("loaded");
await rendered.waitForValueToChange(() => rendered.result.current === "loaded");
});
it("can handle error image", async () => {
mockImage.simulate("error");
const rendered = renderHook(() => useImage({src: "/test.png"}));
expect(rendered.result.current).toEqual("loading");
await rendered.waitForValueToChange(() => rendered.result.current === "failed");
});
it("can handle cached image", async () => {
mockImage.simulate("loaded");
const rendered = renderHook(() => useImage({src: "/test.png"}));
expect(rendered.result.current).toEqual("loaded");
});
});

View File

@ -41,7 +41,8 @@
},
"devDependencies": {
"clean-package": "2.2.0",
"react": "^18.0.0"
"react": "^18.0.0",
"@nextui-org/test-utils": "workspace:*"
},
"clean-package": "../../../clean-package.config.json",
"tsup": {
@ -52,4 +53,4 @@
"esm"
]
}
}
}

View File

@ -1,9 +1,9 @@
/**
* Part of this code is taken from @chakra-ui/react package
*/
import type {ImgHTMLAttributes, SyntheticEvent} from "react";
import type {ImgHTMLAttributes, MutableRefObject, SyntheticEvent} from "react";
import {useCallback, useEffect, useRef, useState} from "react";
import {useEffect, useRef, useState} from "react";
import {useSafeLayoutEffect} from "@nextui-org/use-safe-layout-effect";
type NativeImageProps = ImgHTMLAttributes<HTMLImageElement>;
@ -66,40 +66,37 @@ type ImageEvent = SyntheticEvent<HTMLImageElement, Event>;
export function useImage(props: UseImageProps = {}) {
const {loading, src, srcSet, onLoad, onError, crossOrigin, sizes, ignoreFallback} = props;
const [status, setStatus] = useState<Status>("pending");
const imageRef = useRef<HTMLImageElement | null>();
const firstMount = useRef<boolean>(true);
const [status, setStatus] = useState<Status>(() => setImageAndGetInitialStatus(props, imageRef));
useSafeLayoutEffect(() => {
if (firstMount.current) {
firstMount.current = false;
return;
}
setStatus(setImageAndGetInitialStatus(props, imageRef));
return () => {
flush();
};
}, [src, crossOrigin, srcSet, sizes, loading]);
useEffect(() => {
setStatus(src ? "loading" : "pending");
}, [src]);
const imageRef = useRef<HTMLImageElement | null>();
const load = useCallback(() => {
if (!src) return;
flush();
const img = new Image();
img.src = src;
if (crossOrigin) img.crossOrigin = crossOrigin;
if (srcSet) img.srcset = srcSet;
if (sizes) img.sizes = sizes;
if (loading) img.loading = loading;
img.onload = (event) => {
if (!imageRef.current) return;
imageRef.current.onload = (event) => {
flush();
setStatus("loaded");
onLoad?.(event as unknown as ImageEvent);
};
img.onerror = (error) => {
imageRef.current.onerror = (error) => {
flush();
setStatus("failed");
onError?.(error as any);
};
imageRef.current = img;
}, [src, crossOrigin, srcSet, sizes, onLoad, onError, loading]);
}, [imageRef.current]);
const flush = () => {
if (imageRef.current) {
@ -109,22 +106,6 @@ export function useImage(props: UseImageProps = {}) {
}
};
useSafeLayoutEffect(() => {
/**
* If user opts out of the fallback/placeholder
* logic, let's bail out.
*/
if (ignoreFallback) return undefined;
if (status === "loading") {
load();
}
return () => {
flush();
};
}, [status, load, ignoreFallback]);
/**
* If user opts out of the fallback/placeholder
* logic, let's just return 'loaded'
@ -132,6 +113,31 @@ export function useImage(props: UseImageProps = {}) {
return ignoreFallback ? "loaded" : status;
}
function setImageAndGetInitialStatus(
props: UseImageProps,
imageRef: MutableRefObject<HTMLImageElement | null | undefined>,
): Status {
const {loading, src, srcSet, crossOrigin, sizes, ignoreFallback} = props;
if (!src) return "pending";
if (ignoreFallback) return "loaded";
const img = new Image();
img.src = src;
if (crossOrigin) img.crossOrigin = crossOrigin;
if (srcSet) img.srcset = srcSet;
if (sizes) img.sizes = sizes;
if (loading) img.loading = loading;
imageRef.current = img;
if (img.complete && img.naturalWidth) {
return "loaded";
}
return "loading";
}
export const shouldShowFallbackImage = (status: Status, fallbackStrategy: FallbackStrategy) =>
(status !== "loaded" && fallbackStrategy === "beforeLoadOrError") ||
(status === "failed" && fallbackStrategy === "onError");

View File

@ -14,6 +14,10 @@ export function mockImage() {
onerror: VoidFunction = () => {};
src = "";
alt = "";
naturalWidth = 100;
get complete() {
return status === "loaded";
}
hasAttribute(name: string) {
return name in this;
}

11164
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff