Open History to see the last commit
1import { expect, it, vi } from "vite-plus/test";
2
3import { render } from "../../../test/render";
4import "~/index.css";
5import PreviewImageContent from "./PreviewImageContent";
6
7function png(width: number, height: number) {
8 const canvas = document.createElement("canvas");
9 canvas.width = width;
10 canvas.height = height;
11 return canvas.toDataURL("image/png");
12}
13
14it("fits the image inside a pane with a fractional width", async () => {
15 const host = document.createElement("div");
16 host.style.cssText = "display:flex;flex-direction:column;width:500.5px;height:600px";
17 await using _screen = await render(
18 <PreviewImageContent src={png(1600, 900)} name="wide.png" mimeType="image/png" />,
19 { container: host },
20 );
21 const image = host.querySelector("img")!;
22 const padding = 32;
23
24 await vi.waitFor(() => {
25 const width = image.getBoundingClientRect().width + padding;
26 expect(width).toBeGreaterThan(499.5);
27 expect(width).toBeLessThanOrEqual(500.5);
28 });
29});
30
31it("keeps a cached image out of view until it is fitted", async () => {
32 const src = png(1600, 900);
33 const host = document.createElement("div");
34 host.style.cssText = "display:flex;flex-direction:column;width:500px;height:600px";
35 const image = () => host.querySelector("img");
36 await using screen = await render(
37 <PreviewImageContent key="first" src={src} name="wide.png" mimeType="image/png" />,
38 { container: host },
39 );
40 await vi.waitFor(() => expect(image()?.getBoundingClientRect().width).toBeGreaterThan(400));
41
42 // A new key remounts the preview, as a new file revision does. The cached image has its natural
43 // size on insertion, and the observer measures it before the load event can fit it.
44 let insertedWidth: number | undefined;
45 const mounts = new MutationObserver(() => {
46 insertedWidth ??= image()?.getBoundingClientRect().width;
47 });
48 mounts.observe(host, { childList: true, subtree: true });
49 await screen.rerender(
50 <PreviewImageContent key="second" src={src} name="wide.png" mimeType="image/png" />,
51 );
52 mounts.disconnect();
53
54 expect(insertedWidth).toBeLessThanOrEqual(500);
55 await vi.waitFor(() => expect(image()?.getBoundingClientRect().width).toBeGreaterThan(400));
56});