refactor: Simplify LazyImage component by removing unnecessary state and optimizing IntersectionObserver usage; enhance test setup with improved window.location mock
This commit is contained in:
@@ -23,7 +23,6 @@ export function LazyImage({
|
|||||||
...props
|
...props
|
||||||
}: LazyImageProps) {
|
}: LazyImageProps) {
|
||||||
const [isLoaded, setIsLoaded] = useState(false)
|
const [isLoaded, setIsLoaded] = useState(false)
|
||||||
const [isInView, setIsInView] = useState(priority)
|
|
||||||
const [error, setError] = useState(false)
|
const [error, setError] = useState(false)
|
||||||
const imgRef = useRef<HTMLImageElement>(null)
|
const imgRef = useRef<HTMLImageElement>(null)
|
||||||
const [imageSrc, setImageSrc] = useState(priority ? src : placeholder)
|
const [imageSrc, setImageSrc] = useState(priority ? src : placeholder)
|
||||||
@@ -35,14 +34,12 @@ export function LazyImage({
|
|||||||
const observer = new IntersectionObserver(
|
const observer = new IntersectionObserver(
|
||||||
([entry]) => {
|
([entry]) => {
|
||||||
if (entry.isIntersecting) {
|
if (entry.isIntersecting) {
|
||||||
setIsInView(true)
|
|
||||||
setImageSrc(src)
|
setImageSrc(src)
|
||||||
observer.disconnect()
|
observer.disconnect()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{ rootMargin: '50px' }
|
{ rootMargin: '50px' }
|
||||||
)
|
)
|
||||||
|
|
||||||
const currentImg = imgRef.current
|
const currentImg = imgRef.current
|
||||||
if (currentImg) {
|
if (currentImg) {
|
||||||
observer.observe(currentImg)
|
observer.observe(currentImg)
|
||||||
|
|||||||
@@ -58,10 +58,21 @@ Object.defineProperty(window, 'localStorage', {
|
|||||||
|
|
||||||
// Mock window.location
|
// Mock window.location
|
||||||
delete (window as any).location
|
delete (window as any).location
|
||||||
window.location = {
|
|
||||||
...window.location,
|
Object.defineProperty(window, 'location', {
|
||||||
hash: '#/',
|
writable: true,
|
||||||
pathname: '/',
|
value: {
|
||||||
search: '',
|
...window.location,
|
||||||
href: 'http://localhost:3000/',
|
hash: '#/',
|
||||||
}
|
pathname: '/',
|
||||||
|
get search() {
|
||||||
|
return '';
|
||||||
|
},
|
||||||
|
get href() {
|
||||||
|
return 'http://localhost:3000/';
|
||||||
|
},
|
||||||
|
assign: vi.fn(),
|
||||||
|
replace: vi.fn(),
|
||||||
|
reload: vi.fn(),
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user