fix: complete Avatar image composition and fallback migration

This commit is contained in:
maoyingjie
2026-10-27 18:05:26 +08:00
parent 6de246de49
commit fa8b22719e
16 changed files with 366 additions and 23 deletions
+226
View File
@@ -0,0 +1,226 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { flushPromises, mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import { Avatar, AvatarImage, AvatarFallback } from "../packages/vue/src";
import CustomImageDemo from "../apps/docs/demos/avatar-custom-image-component.vue";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
vi.unstubAllGlobals();
vi.useRealTimers();
});
function mockImages() {
const images: PreloadImage[] = [];
class PreloadImage extends EventTarget {
source = "";
get src() {
return this.source;
}
set src(value: string) {
this.source = value;
this.complete = false;
this.naturalWidth = 0;
}
complete = false;
naturalWidth = 0;
constructor() {
super();
images.push(this);
}
finish(type: "load" | "error") {
this.complete = true;
this.naturalWidth = type === "load" ? 40 : 0;
this.dispatchEvent(new Event(type));
}
}
vi.stubGlobal("Image", PreloadImage);
return images;
}
function renderAvatar(
imageProps: Record<string, unknown> = {},
fallbackProps = {},
) {
const w = mount(Avatar, {
slots: {
default: () => [
h(AvatarImage, imageProps),
h(AvatarFallback, fallbackProps, { default: () => "JD" }),
],
},
});
wrappers.push(w);
return w;
}
describe("Avatar public loading composition", () => {
it("renders the fixed-source custom image demo through asChild", async () => {
const images = mockImages();
const w = mount(CustomImageDemo, { attachTo: document.body });
wrappers.push(w);
await flushPromises();
expect(w.findAll("img")).toHaveLength(1);
const img = w.get("img");
expect(img.attributes("alt")).toBe("约翰·多伊");
expect(img.attributes("width")).toBe("40");
expect(img.classes()).toContain("hv-avatar__image");
images[0].finish("load");
await flushPromises();
expect(img.isVisible()).toBe(true);
expect(w.find("[data-slot=avatar-fallback]").exists()).toBe(false);
});
it("keeps native events and dynamic attrs on the custom image", async () => {
mockImages();
const load = vi.fn();
const error = vi.fn();
const title = ref("first");
const w = mount(
defineComponent({
setup: () => () =>
h(
Avatar,
{},
{
default: () =>
h(
AvatarImage,
{
src: "/a.png",
asChild: true,
title: title.value,
onLoad: load,
onError: error,
srcSet: "/a.png 1x, /b.png 2x",
sizes: "40px",
},
{
default: () =>
h("img", { alt: "custom", class: "child-image" }),
},
),
},
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
const img = w.get("img");
expect(img.attributes("srcset")).toContain("2x");
expect(img.attributes("sizes")).toBe("40px");
expect(img.classes()).toContain("child-image");
await img.trigger("load");
await img.trigger("error");
expect(load).toHaveBeenCalledTimes(1);
expect(error).toHaveBeenCalledTimes(1);
title.value = "second";
await nextTick();
expect(img.attributes("title")).toBe("second");
});
it("returns to fallback for a changed failed source and can recover", async () => {
const images = mockImages();
const src = ref("/first.png");
const w = mount(
defineComponent({
setup: () => () =>
h(
Avatar,
{},
{
default: () => [
h(AvatarImage, { src: src.value, alt: "profile" }),
h(AvatarFallback, {}, { default: () => "JD" }),
],
},
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
await flushPromises();
expect(w.get("[data-slot=avatar-fallback]").text()).toBe("JD");
images[0].finish("load");
await flushPromises();
expect(w.get("img").isVisible()).toBe(true);
expect(w.find("[data-slot=avatar-fallback]").exists()).toBe(false);
images[0].complete = false;
src.value = "/missing.png";
await flushPromises();
expect(w.get("img").isVisible()).toBe(false);
images[0].finish("error");
await flushPromises();
expect(w.get("[data-slot=avatar-fallback]").text()).toBe("JD");
images[0].complete = false;
src.value = "/recovered.png";
await flushPromises();
images[0].finish("load");
await flushPromises();
expect(w.get("img").attributes("src")).toBe("/recovered.png");
expect(w.get("img").isVisible()).toBe(true);
expect(w.find("[data-slot=avatar-fallback]").exists()).toBe(false);
});
it("shows fallback with an omitted src and zero delay", async () => {
mockImages();
vi.useFakeTimers();
const w = renderAvatar({}, { delayMs: 0 });
await vi.runAllTimersAsync();
await flushPromises();
expect(w.get("[data-slot=avatar-fallback]").text()).toBe("JD");
});
it("updates a pending delay to zero and supports root/fallback asChild", async () => {
vi.useFakeTimers();
const delay = ref(600);
const w = mount(
defineComponent({
setup: () => () =>
h(
Avatar,
{ asChild: true },
{
default: () =>
h("div", { "data-custom-root": "" }, [
h(
AvatarFallback,
{ asChild: true, delayMs: delay.value },
{
default: () =>
h("strong", { "aria-label": "initials" }, "JD"),
},
),
]),
},
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
expect(w.get("[data-slot=avatar]").element.tagName).toBe("DIV");
expect(w.find("strong").exists()).toBe(false);
delay.value = 0;
await nextTick();
expect(w.get("strong").text()).toBe("JD");
expect(w.get("strong").attributes("aria-label")).toBe("initials");
expect(w.get("strong").classes()).toContain("hv-avatar__fallback");
expect(vi.getTimerCount()).toBe(0);
});
it("honors positive delay and cancels the pending fallback on unmount", async () => {
mockImages();
vi.useFakeTimers();
const w = renderAvatar({ src: "/pending.png" }, { delayMs: 600 });
expect(w.find("[data-slot=avatar-fallback]").exists()).toBe(false);
await vi.advanceTimersByTimeAsync(599);
expect(w.find("[data-slot=avatar-fallback]").exists()).toBe(false);
await vi.advanceTimersByTimeAsync(1);
expect(w.get("[data-slot=avatar-fallback]").text()).toBe("JD");
const pending = renderAvatar({}, { delayMs: 1000 });
pending.unmount();
wrappers.splice(wrappers.indexOf(pending), 1);
expect(vi.getTimerCount()).toBe(0);
});
});
+47
View File
@@ -0,0 +1,47 @@
import { h } from "vue";
import {
Avatar,
AvatarRoot,
AvatarImage,
AvatarFallback,
avatarVariants,
type AvatarProps,
type AvatarRootProps,
type AvatarImageProps,
type AvatarFallbackProps,
} from "@heroui-vue/components";
const root: AvatarProps = {
size: "lg",
color: "accent",
variant: "soft",
as: "div",
asChild: true,
};
const image: AvatarImageProps = {
asChild: true,
srcSet: "/a.png 2x",
sizes: "40px",
loading: "lazy",
crossOrigin: "anonymous",
referrerPolicy: "no-referrer",
onLoad: (event: Event) => event.type,
onError: (event: Event) => event.type,
};
const fallback: AvatarFallbackProps = {
delayMs: 0,
color: "danger",
asChild: true,
};
const rootAlias: AvatarRootProps = root;
h(AvatarRoot, rootAlias);
h(AvatarImage, image);
h(AvatarFallback, fallback);
// @ts-expect-error baseline size only
const badRoot: AvatarProps = { size: "xl" };
// @ts-expect-error baseline color only
const badFallback: AvatarFallbackProps = { color: "blue" };
// @ts-expect-error native loading policy
const badImage: AvatarImageProps = { loading: "immediate" };
// @ts-expect-error native referrer policy
const badPolicy: AvatarImageProps = { referrerPolicy: "secret" };
void [Avatar, avatarVariants, badRoot, badFallback, badImage, badPolicy];
+17
View File
@@ -532,5 +532,22 @@
"background-color:var(--overlay)",
"data-exiting"
]
},
"avatar": {
"exports": [
"Avatar",
"AvatarRoot",
"AvatarImage",
"AvatarFallback",
"avatarVariants"
],
"css": [
".hv-avatar",
".hv-avatar__image",
".hv-avatar__fallback",
".hv-avatar--sm",
".hv-avatar--lg",
".hv-avatar--soft"
]
}
}