Skip to content

Commit 8479063

Browse files
authored
refactor(ui): unify user avatar rendering (#114496)
1 parent da9ed01 commit 8479063

8 files changed

Lines changed: 450 additions & 173 deletions
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
/* @vitest-environment jsdom */
2+
3+
import { html, render } from "lit";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { resolveAvatarInitials, setAvatarGatewayOrigin } from "../lib/identity-avatar.ts";
6+
import {
7+
identityAvatarClass,
8+
renderIdentityAvatarImage,
9+
resolveIdentityAvatarView,
10+
type IdentityAvatarView,
11+
} from "./identity-avatar-view.ts";
12+
13+
function renderAvatar(view: IdentityAvatarView, container: HTMLElement): void {
14+
render(
15+
html`<span class=${identityAvatarClass("test-avatar", view)}>
16+
${renderIdentityAvatarImage({
17+
view,
18+
fallbackSelector: ".test-avatar",
19+
className: "test-avatar__image",
20+
alt: "Ada Lovelace",
21+
ariaHidden: true,
22+
})}
23+
</span>`,
24+
container,
25+
);
26+
}
27+
28+
afterEach(() => {
29+
document.body.replaceChildren();
30+
setAvatarGatewayOrigin(null);
31+
vi.restoreAllMocks();
32+
});
33+
34+
describe("shared identity avatar view", () => {
35+
it("derives fallback initials and colors from the canonical user identity", () => {
36+
const identity = {
37+
id: "profile-riley",
38+
name: "Riley",
39+
username: "[email protected]",
40+
};
41+
42+
const view = resolveIdentityAvatarView(identity);
43+
44+
expect(view.fallback).toEqual(resolveAvatarInitials(identity));
45+
expect(view.fallback.initials).toBe("R");
46+
expect(view.imageUrl).toBeNull();
47+
expect(view.pending).toBe(false);
48+
});
49+
50+
it("keeps hostile avatar origins out of the shared authenticated renderer", () => {
51+
setAvatarGatewayOrigin("https://gateway.example.test", "Bearer avatar-token");
52+
const fetchAvatar = vi.spyOn(globalThis, "fetch");
53+
54+
const view = resolveIdentityAvatarView({
55+
id: "profile-mallory",
56+
name: "Mallory",
57+
profileAvatarUrl: "https://evil.example/api/users/profile-mallory/avatar",
58+
});
59+
60+
expect(view.fallback.initials).toBe("M");
61+
expect(view.imageUrl).toBeNull();
62+
expect(view.pending).toBe(false);
63+
expect(fetchAvatar).not.toHaveBeenCalled();
64+
});
65+
66+
it("shares authenticated loading and reconciles image fallback events", async () => {
67+
setAvatarGatewayOrigin("https://gateway.example.test", "Bearer avatar-token");
68+
const fetchAvatar = vi.spyOn(globalThis, "fetch").mockResolvedValue(
69+
new Response(new Uint8Array([1, 2, 3]), {
70+
headers: { "content-type": "image/png" },
71+
}),
72+
);
73+
vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:shared-identity-avatar");
74+
75+
const view = resolveIdentityAvatarView({
76+
id: "profile-ada",
77+
name: "Ada Lovelace",
78+
profileAvatarUrl: "/api/users/profile-ada/avatar?v=7",
79+
});
80+
const container = document.createElement("div");
81+
document.body.append(container);
82+
renderAvatar(view, container);
83+
84+
const wrapper = container.querySelector<HTMLElement>(".test-avatar");
85+
expect(view.pending).toBe(true);
86+
expect(wrapper?.classList.contains("is-fallback")).toBe(true);
87+
88+
const image = await vi.waitFor(() => {
89+
const element = container.querySelector<HTMLImageElement>(".test-avatar__image");
90+
expect(element?.getAttribute("src")).toBe("blob:shared-identity-avatar");
91+
return element!;
92+
});
93+
expect(image.getAttribute("alt")).toBe("Ada Lovelace");
94+
expect(image.getAttribute("aria-hidden")).toBe("true");
95+
expect(image.getAttribute("referrerpolicy")).toBe("no-referrer");
96+
expect(fetchAvatar).toHaveBeenCalledOnce();
97+
expect(fetchAvatar).toHaveBeenCalledWith(
98+
"https://gateway.example.test/api/users/profile-ada/avatar?v=7",
99+
expect.objectContaining({ headers: { Authorization: "Bearer avatar-token" } }),
100+
);
101+
102+
image.dispatchEvent(new Event("load"));
103+
expect(wrapper?.classList.contains("is-fallback")).toBe(false);
104+
105+
image.dispatchEvent(new Event("error"));
106+
expect(wrapper?.classList.contains("is-fallback")).toBe(true);
107+
108+
image.dispatchEvent(new Event("load"));
109+
expect(wrapper?.classList.contains("is-fallback")).toBe(false);
110+
});
111+
112+
it("retains its existing image while a newer avatar revision loads", async () => {
113+
setAvatarGatewayOrigin("https://gateway.example.test", "Bearer avatar-token");
114+
vi.spyOn(globalThis, "fetch").mockImplementation(
115+
async () =>
116+
new Response(new Uint8Array([1, 2, 3]), {
117+
headers: { "content-type": "image/png" },
118+
}),
119+
);
120+
vi.spyOn(URL, "createObjectURL")
121+
.mockReturnValueOnce("blob:identity-avatar-v1")
122+
.mockReturnValueOnce("blob:identity-avatar-v2");
123+
124+
const identity = { id: "profile-ada", name: "Ada Lovelace" };
125+
const container = document.createElement("div");
126+
document.body.append(container);
127+
renderAvatar(
128+
resolveIdentityAvatarView({
129+
...identity,
130+
profileAvatarUrl: "/api/users/profile-ada/avatar?v=1",
131+
}),
132+
container,
133+
);
134+
135+
const firstImage = await vi.waitFor(() => {
136+
const image = container.querySelector<HTMLImageElement>(".test-avatar__image");
137+
expect(image?.getAttribute("src")).toBe("blob:identity-avatar-v1");
138+
return image!;
139+
});
140+
firstImage.dispatchEvent(new Event("load"));
141+
142+
renderAvatar(
143+
resolveIdentityAvatarView({
144+
...identity,
145+
profileAvatarUrl: "/api/users/profile-ada/avatar?v=2",
146+
}),
147+
container,
148+
);
149+
expect(container.querySelector(".test-avatar")?.classList.contains("is-fallback")).toBe(true);
150+
151+
const secondImage = await vi.waitFor(() => {
152+
const image = container.querySelector<HTMLImageElement>(".test-avatar__image");
153+
expect(image?.getAttribute("src")).toBe("blob:identity-avatar-v2");
154+
return image!;
155+
});
156+
expect(secondImage).toBe(firstImage);
157+
158+
secondImage.dispatchEvent(new Event("load"));
159+
expect(container.querySelector(".test-avatar")?.classList.contains("is-fallback")).toBe(false);
160+
});
161+
});
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { html, nothing } from "lit";
2+
import { live } from "lit/directives/live.js";
3+
import { until } from "lit/directives/until.js";
4+
import {
5+
resolveAvatar,
6+
resolveAvatarImageUrl,
7+
resolveAvatarInitials,
8+
settleAvatarImageUrl,
9+
type IdentityAvatarInput,
10+
type ResolvedIdentityAvatar,
11+
} from "../lib/identity-avatar.ts";
12+
13+
type IdentityAvatarFallback = Extract<ResolvedIdentityAvatar, { kind: "initials" }>;
14+
15+
export type IdentityAvatarView = {
16+
fallback: IdentityAvatarFallback;
17+
imageUrl: string | Promise<string | null> | null;
18+
pending: boolean;
19+
};
20+
21+
/** Resolve one user identity consistently across the roster, profile, and chat. */
22+
export function resolveIdentityAvatarView(identity: IdentityAvatarInput): IdentityAvatarView {
23+
const avatar = resolveAvatar(identity);
24+
const fallback = avatar.kind === "initials" ? avatar : resolveAvatarInitials(identity);
25+
const imageUrl = avatar.kind === "profile" ? resolveAvatarImageUrl(avatar.url) : null;
26+
return {
27+
fallback,
28+
imageUrl,
29+
pending: imageUrl !== null && typeof imageUrl !== "string",
30+
};
31+
}
32+
33+
/** Reconcile image-event fallback mutations without replacing an existing image. */
34+
export function identityAvatarClass(className: string, view: IdentityAvatarView) {
35+
return live(`${className}${view.pending ? " is-fallback" : ""}`);
36+
}
37+
38+
function settleIdentityAvatarImage(event: Event, fallbackSelector: string, failed: boolean): void {
39+
const image = event.currentTarget;
40+
if (!(image instanceof HTMLImageElement)) {
41+
return;
42+
}
43+
// All user-avatar surfaces share blob settlement and fallback transitions;
44+
// revoking a pending image or retaining a previous error breaks reused DOM.
45+
settleAvatarImageUrl(image.getAttribute("src"));
46+
image.closest<HTMLElement>(fallbackSelector)?.classList.toggle("is-fallback", failed);
47+
}
48+
49+
/** Render the shared authenticated user image with its canonical event lifecycle. */
50+
export function renderIdentityAvatarImage({
51+
view,
52+
fallbackSelector,
53+
className,
54+
alt = "",
55+
ariaHidden = false,
56+
}: {
57+
view: IdentityAvatarView;
58+
fallbackSelector: string;
59+
className?: string;
60+
alt?: string;
61+
ariaHidden?: boolean;
62+
}) {
63+
if (!view.imageUrl) {
64+
return nothing;
65+
}
66+
return html`<img
67+
class=${className ?? nothing}
68+
src=${typeof view.imageUrl === "string"
69+
? view.imageUrl
70+
: until(
71+
view.imageUrl.then((url) => url ?? nothing),
72+
nothing,
73+
)}
74+
alt=${alt}
75+
aria-hidden=${ariaHidden ? "true" : nothing}
76+
referrerpolicy="no-referrer"
77+
@error=${(event: Event) => settleIdentityAvatarImage(event, fallbackSelector, true)}
78+
@load=${(event: Event) => settleIdentityAvatarImage(event, fallbackSelector, false)}
79+
/>`;
80+
}

‎ui/src/components/viewer-facepile.test.ts‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
/* @vitest-environment jsdom */
22

3+
import { render } from "lit";
34
import { afterEach, expect, it, vi } from "vitest";
45
import type { ControlUiBuildInfo } from "../build-info.ts";
5-
import { setAvatarGatewayOrigin } from "../lib/identity-avatar.ts";
6+
import { resolveAvatarInitials, setAvatarGatewayOrigin } from "../lib/identity-avatar.ts";
7+
import { renderChatAuthorAvatar } from "../pages/chat/components/chat-author-avatar.ts";
68
import {
79
hasMultiplePresenceIdentities,
810
hasSessionPresenceViewers,
@@ -20,6 +22,41 @@ afterEach(() => {
2022
vi.restoreAllMocks();
2123
});
2224

25+
it("uses the same user initials and identity hue in the roster and attributed chat", async () => {
26+
const user: PresenceViewer = {
27+
id: "profile-riley",
28+
name: "Riley",
29+
30+
watchedSessions: [],
31+
};
32+
const viewerAvatar = document.createElement("openclaw-viewer-avatar") as ViewerAvatarElement;
33+
viewerAvatar.user = user;
34+
document.body.append(viewerAvatar);
35+
36+
const chat = document.createElement("div");
37+
document.body.append(chat);
38+
render(renderChatAuthorAvatar({ id: user.id, name: user.name, username: user.email }), chat);
39+
40+
const expected = resolveAvatarInitials({
41+
id: user.id,
42+
name: user.name,
43+
username: user.email,
44+
});
45+
await vi.waitFor(async () => {
46+
await viewerAvatar.updateComplete;
47+
const rosterInitials = viewerAvatar.querySelector(".viewer-avatar > span");
48+
const chatInitials = chat.querySelector(".chat-author-avatar__initials");
49+
expect(rosterInitials?.textContent?.trim()).toBe(expected.initials);
50+
expect(chatInitials?.textContent?.trim()).toBe(expected.initials);
51+
expect(rosterInitials?.getAttribute("style")).toContain(
52+
`hsl(${expected.colorSeed % 360} 48% 42%)`,
53+
);
54+
expect(chatInitials?.getAttribute("style")).toContain(
55+
`--chat-author-avatar-hue: ${expected.colorSeed % 360}`,
56+
);
57+
});
58+
});
59+
2360
it("uses the shared resolver and rejects cross-origin presence avatar metadata", async () => {
2461
const avatar = document.createElement("openclaw-viewer-avatar") as ViewerAvatarElement;
2562
avatar.user = {
@@ -33,7 +70,7 @@ it("uses the shared resolver and rejects cross-origin presence avatar metadata",
3370
await vi.waitFor(async () => {
3471
await avatar.updateComplete;
3572
expect(avatar.querySelector("img")).toBeNull();
36-
expect(avatar.textContent?.trim()).toBe("MA");
73+
expect(avatar.textContent?.trim()).toBe("M");
3774
});
3875
});
3976

0 commit comments

Comments
 (0)