Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions src/components/commons/LazyLoadImage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import {
describe,
it,
vi,
expect,
afterAll,
} from "vitest";
import { render, fireEvent } from "@solidjs/testing-library";
import { LazyLoadImage } from "./LazyLoadImage";

const getSkeleton = (container: HTMLElement) =>
container.querySelector(".animate-pulse");

const mockImageState = (isComplete: boolean, isNaturalWidth: number) => {
vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(
isComplete
);
vi.spyOn(HTMLImageElement.prototype, "naturalWidth", "get").mockReturnValue(
isNaturalWidth
);
};

afterAll(() => {
vi.restoreAllMocks();
});

describe("LazyLoadImage", () => {
it("when loading image show skeleton", async () => {
mockImageState(false, 0);

const { container } = render(() => (
<LazyLoadImage src="potato.png" imageClasses="h-48" />
));
const image = container.querySelector("img")!;

expect(getSkeleton(container)).toBeTruthy();
expect(image?.className).toContain("opacity-0");
});

it("when loaded image hide skeleton and show image", async () => {
mockImageState(false, 0);
const { container } = render(() => (
<LazyLoadImage src="potato.png" imageClasses="h-48" />
));
const image = container.querySelector("img")!;
expect(getSkeleton(container)).toBeTruthy();
expect(image?.className).toContain("opacity-0");

fireEvent.load(image);

expect(getSkeleton(container)).toBeNull();
expect(image?.className).toContain("opacity-100");
});

it("when image cached before dehydration show image", async () => {
mockImageState(true, 300);

const { container } = render(() => (
<LazyLoadImage src="potato.png" />
));
const image = container.querySelector("img")!;

expect(getSkeleton(container)).toBeNull();
expect(image?.className).toContain("opacity-100");
});

it("when image failed to load show error text", async () => {
mockImageState(false, 0);
const { container, getByTestId } = render(() => (
<LazyLoadImage src="potato.png" />
));
const image = container.querySelector("img")!;

fireEvent.error(image);

expect(getSkeleton(container)).toBeNull();
const imageFailure = getByTestId("image-failure");
expect(imageFailure.innerText).toBe("Failed To Load Image");
expect(image?.className).toContain("opacity-0");
});

it("when provided image classes should apply them", () => {
mockImageState(false, 0);
let imageRef: HTMLImageElement | undefined;
const onLoad = vi.fn();

const { container } = render(() => (
<LazyLoadImage
src="potato.png"
containerClasses="h-42"
imageClasses="object-cover"
ref={(element) => (imageRef = element)}
onLoad={onLoad}
/>
));

expect(container.firstElementChild?.className).toContain("h-42");
const image = container.querySelector("img")!;
expect(imageRef).toBe(image);
expect(image.className).toContain("object-cover");
});
});
102 changes: 102 additions & 0 deletions src/components/commons/LazyLoadImage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import clsx from "clsx";
import {
Component,
createSignal,
onCleanup,
onMount,
Show,
splitProps,
} from "solid-js";
import type { JSX } from "solid-js";

export interface LazyLoadImageProps extends JSX.ImgHTMLAttributes<HTMLImageElement> {
containerClasses?: string;
imageClasses?: string;
skeletonClasses?: string;
}

export const LazyLoadImage: Component<LazyLoadImageProps> = (
props
) => {
const [local, others] = splitProps(props, [
"containerClasses",
"imageClasses",
"skeletonClasses",
"ref",
]);

const [isLoaded, setIsLoaded] = createSignal(false);
const [isFailed, setIsFailed] = createSignal(false);

let imageRef: HTMLImageElement | undefined;

onMount(() => {
const image = imageRef;
if (!image) return;

const markLoaded = () => {
setIsLoaded(true);
setIsFailed(false);
};

const markLoadingError = () => {
setIsLoaded(false);
setIsFailed(true);
};

image.addEventListener("load", markLoaded);
image.addEventListener("error", markLoadingError);

onCleanup(() => {
image.removeEventListener("load", markLoaded);
image.removeEventListener("error", markLoadingError);
});

if (image.complete) {
if (image.naturalWidth > 0) markLoaded();
else markLoadingError();
}
});

const isShowSkeleton = () => !isLoaded() && !isFailed();
const isHideImage = () => isShowSkeleton() || isFailed();

return (
<div class={clsx("grid overflow-hidden", local.containerClasses)}>
<Show when={isShowSkeleton()}>
<div
aria-hidden="true"
class={clsx(
local.skeletonClasses,
"col-start-1 row-start-1 animate-pulse bg-background-50"
)}
/>
</Show>

<Show when={isFailed()}>
<div
data-testid="image-failure"
class={clsx(
"col-start-1 row-start-1 flex items-center justify-center"
)}
>
Failed To Load Image
</div>
</Show>
<img
{...others}
ref={(elementRef) => {
imageRef = elementRef;
const forwardedRef = local.ref;
if (typeof forwardedRef === "function") forwardedRef(imageRef);
}}
class={clsx(
local.imageClasses,
"col-start-1 row-start-1",
isHideImage() ? "opacity-0" : "opacity-100"
)}
loading="lazy"
/>
</div>
);
};
3 changes: 2 additions & 1 deletion src/components/commons/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ export { Drawer } from "./Drawer";
export { FAQSection } from "./FAQSection";
export { MarkdownLink } from "./Markdown";
export { Typography } from "./Typography";
export { Button } from "./Button/Button";
export { Button } from "./Button/Button";
export { LazyLoadImage } from "./LazyLoadImage";
26 changes: 6 additions & 20 deletions src/features/blog/components/BlogPostList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { BlogPostMetadata, BlogYearGroup } from "../blog.types";
import { A } from "@solidjs/router";
import clsx from "clsx";
import { FormattedDate } from "./FormattedDate";
import { Typography } from "~/components/commons";
import { LazyLoadImage, Typography } from "~/components/commons";
import { BlogPostThumbnail } from "./BlogPostThumbnail";
import { getBlogPostThumbnailPlaceholderAttributes } from "../utils/blog.thumbnail.helper";

Expand Down Expand Up @@ -80,25 +80,11 @@ const BlogPostCard: Component<{ post: BlogPostMetadata }> = (props) => {
/>
}
>
<div class="relative w-full h-48 overflow-hidden rounded-2xl bg-background-60">
<div
data-testid="image-skeleton"
class="absolute inset-0 animate-pulse bg-background-60/50"
/>

<img
src={props.post.thumbnailUrl}
alt={props.post.title}
class={clsx(
"relative",
"z-10",
"w-full h-48",
"rounded-2xl",
"bg-background-60",
"object-cover"
)}
/>
</div>
<LazyLoadImage
src={props.post.thumbnailUrl}
containerClasses="h-48 rounded-2xl"
class="w-full h-full object-cover"
/>
</Show>

<div class="px-6 py-3">
Expand Down
32 changes: 16 additions & 16 deletions src/features/blog/components/BlogPostRender.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { Meta, Title } from "@solidjs/meta";
import { Component, createMemo, Show } from "solid-js";
import { Container, Typography } from "~/components/commons";
import {
Container,
LazyLoadImage,
Typography,
} from "~/components/commons";
import { FormattedDate, MarkdownContentRender } from "~/features/blog";
import { BlogPost } from "~/features/blog/blog.types";
import { extractBlogHeadings } from "../utils/blog-table-of-contents.helper";
Expand Down Expand Up @@ -77,7 +81,13 @@ const BlogPostHeader: Component<BlogPostRenderProps> = (props) => {
when={props.post.metadata.thumbnailUrl}
fallback={<BlogPostThumbnailPlaceholder post={props.post} />}
>
<BlogPostThumbnailImage post={props.post} />
<LazyLoadImage
src={props.post.metadata.thumbnailUrl}
alt={props.post.metadata.title}
containerClasses="h-80 rounded-2xl"
imageClasses="h-full object-cover"
class="w-full"
/>
</Show>
</div>
</Container>
Expand All @@ -94,23 +104,13 @@ const BlogPostThumbnailPlaceholder: Component<BlogPostRenderProps> = (
return (
<div class="relative h-62 from-transparent to-background-80 bg-linear-to-b lg:bg-linear-to-r">
<div class="absolute inset-x-0 top-[15%] flex justify-end pr-4">
<img
<LazyLoadImage
src={thumbnailSettings().thumbnailPictureUrl}
class="h-50 w-auto"
imageClasses="object-cover"
containerClasses="h-50 w-auto"
skeletonClasses="rounded-xl"
/>
</div>
</div>
);
};

const BlogPostThumbnailImage: Component<BlogPostRenderProps> = (props) => {
return (
<div class="relative h-80 w-full">
<img
src={props.post.metadata.thumbnailUrl}
alt={props.post.metadata.title}
class="h-full w-full object-cover bg-background-80 rounded-2xl"
/>
</div>
);
};
8 changes: 5 additions & 3 deletions src/features/blog/components/BlogPostThumbnail.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Component } from "solid-js";
import { BlogPostThumbnailPlaceholder } from "../utils/blog.thumbnail.helper";
import clsx from "clsx";
import { LazyLoadImage } from "~/components/commons";

interface BlogPostThumbnailProps {
title: string;
Expand Down Expand Up @@ -45,11 +46,12 @@ export const BlogPostThumbnail: Component<BlogPostThumbnailProps> = (props) => {
</div>
</div>

<img
<LazyLoadImage
src={props.placeholder.thumbnailPictureUrl}
alt={props.title}
class="absolute right-1 mt-3 max-h-50 md:w-3/6 object-contain mx-auto"
loading="lazy"
containerClasses="absolute right-1 mt-3 max-h-50 md:w-3/6 mx-auto"
imageClasses="object-cover"
skeletonClasses="rounded-xl mr-3"
/>
</div>
);
Expand Down
8 changes: 5 additions & 3 deletions src/features/blog/components/markdown/MarkdownImgOverride.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { SolidMarkdownComponents } from "solid-markdown";
import { resolveAssetPath } from "../../utils/blog.helper";
import { LazyLoadImage } from "~/components/commons";

export function markdownImgOverride(
postId: string
Expand Down Expand Up @@ -29,11 +30,12 @@ export function markdownImgOverride(
}

return (
<img
<LazyLoadImage
{...props}
src={resolvedSrc}
class="max-h-96 object-contain mx-auto"
loading="lazy"
containerClasses="grid-cols-1 justify-items center"
skeletonClasses="h-96 my-2 mx-auto w-full rounded-xl"
imageClasses="max-h-96 object-contain mx-auto"
/>
);
};
Expand Down
Loading