Skip to content

Commit f609fce

Browse files
cynfrianpub19x6jnl6rhepymwyl2xlltz3ce7rfg2ktllle3g2vu59n3s490k8s9n40l3loganj
authored
Keep avatar preview visible during upload (#2237)
Signed-off-by: npub19x6jnl6rhepymwyl2xlltz3ce7rfg2ktllle3g2vu59n3s490k8s9n40l3 <29b529ff43be424db89f51bff58a38cf86942acbffff98a14ce50b38c2a57d8f@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub19x6jnl6rhepymwyl2xlltz3ce7rfg2ktllle3g2vu59n3s490k8s9n40l3 <29b529ff43be424db89f51bff58a38cf86942acbffff98a14ce50b38c2a57d8f@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Logan Johnson <[email protected]>
1 parent fd55ab6 commit f609fce

8 files changed

Lines changed: 563 additions & 41 deletions

File tree

‎desktop/src/features/onboarding/ui/CommunityOnboardingFlow.tsx‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
takePendingWelcomeChannelForDirectEntry,
1414
WELCOME_SURFACE_READY_EVENT,
1515
} from "@/features/onboarding/welcome";
16+
import { useAvatarPresentation } from "@/features/profile/avatarPresentationStore";
1617
import { profileQueryKey } from "@/features/profile/hooks";
1718
import { ProfileAvatar } from "@/features/profile/ui/ProfileAvatar";
1819
import {
@@ -80,7 +81,9 @@ function AvatarCircle({
8081
triggerRef?: React.Ref<HTMLButtonElement>;
8182
}) {
8283
const emojiAvatar = parseEmojiAvatarDataUrl(avatarUrl);
83-
const hasAvatar = avatarUrl.trim().length > 0;
84+
const presentation = useAvatarPresentation(avatarUrl);
85+
const hasAvatar =
86+
avatarUrl.trim().length > 0 && presentation?.state !== "failed";
8487

8588
return (
8689
<button
@@ -103,9 +106,13 @@ function AvatarCircle({
103106
avatarUrl={avatarUrl}
104107
className="h-36 w-36 rounded-full text-4xl"
105108
label={previewName}
109+
testId="community-avatar-circle"
106110
/>
107111
) : (
108-
<span className="flex h-36 w-36 items-center justify-center rounded-full bg-white/30 text-[var(--buzz-onboarding-backup-ink)] transition-colors group-hover:bg-white/40">
112+
<span
113+
className="flex h-36 w-36 items-center justify-center rounded-full bg-white/30 text-[var(--buzz-onboarding-backup-ink)] transition-colors group-hover:bg-white/40"
114+
data-testid="community-avatar-empty"
115+
>
109116
<Plus className="h-7 w-7" aria-hidden="true" />
110117
</span>
111118
)}
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
import * as React from "react";
2+
import { toast } from "sonner";
3+
4+
import { rewriteRelayUrl } from "@/shared/lib/mediaUrl";
5+
6+
export type AvatarPresentationState = "failed" | "pending" | "ready";
7+
8+
export type AvatarPresentation = {
9+
displayUrl: string;
10+
state: AvatarPresentationState;
11+
};
12+
13+
type AvatarPresentationEntry = {
14+
generation: number;
15+
localPreviewUrl: string | null;
16+
remoteUrl: string;
17+
snapshot: AvatarPresentation;
18+
};
19+
20+
const PROBE_DELAYS_MS = [0, 750, 1_500, 3_000] as const;
21+
const PROBE_TIMEOUT_MS = 3_000;
22+
const READY_PRESENTATION_TTL_MS = 30_000;
23+
const presentations = new Map<string, AvatarPresentationEntry>();
24+
const listeners = new Set<() => void>();
25+
let nextGeneration = 1;
26+
27+
function emitChange(): void {
28+
for (const listener of listeners) listener();
29+
}
30+
31+
function toastId(remoteUrl: string): string {
32+
return `avatar-presentation:${remoteUrl}`;
33+
}
34+
35+
function releaseLocalPreview(entry: AvatarPresentationEntry): void {
36+
if (!entry.localPreviewUrl) return;
37+
URL.revokeObjectURL(entry.localPreviewUrl);
38+
entry.localPreviewUrl = null;
39+
}
40+
41+
function isCurrent(entry: AvatarPresentationEntry): boolean {
42+
return presentations.get(entry.remoteUrl)?.generation === entry.generation;
43+
}
44+
45+
function wait(delayMs: number): Promise<void> {
46+
return new Promise((resolve) => window.setTimeout(resolve, delayMs));
47+
}
48+
49+
function buildProbeUrl(remoteUrl: string, attempt: number): string {
50+
try {
51+
const url = new URL(remoteUrl);
52+
url.searchParams.set(
53+
"buzz_avatar_probe",
54+
`${Date.now()}-${attempt.toString()}`,
55+
);
56+
return url.toString();
57+
} catch {
58+
return remoteUrl;
59+
}
60+
}
61+
62+
function probeImage(
63+
remoteUrl: string,
64+
attempt: number,
65+
): Promise<string | null> {
66+
return new Promise((resolve) => {
67+
const image = new Image();
68+
let settled = false;
69+
const verifiedUrl = buildProbeUrl(remoteUrl, attempt);
70+
const finish = (result: string | null) => {
71+
if (settled) return;
72+
settled = true;
73+
window.clearTimeout(timeoutId);
74+
image.onload = null;
75+
image.onerror = null;
76+
resolve(result);
77+
};
78+
const timeoutId = window.setTimeout(() => finish(null), PROBE_TIMEOUT_MS);
79+
80+
image.onload = () => finish(verifiedUrl);
81+
image.onerror = () => finish(null);
82+
image.referrerPolicy = "no-referrer";
83+
image.src = rewriteRelayUrl(verifiedUrl);
84+
});
85+
}
86+
87+
async function verifyPresentation(
88+
entry: AvatarPresentationEntry,
89+
): Promise<void> {
90+
for (const [attempt, delayMs] of PROBE_DELAYS_MS.entries()) {
91+
await wait(delayMs);
92+
if (!isCurrent(entry) || entry.snapshot.state !== "pending") return;
93+
94+
const verifiedUrl = await probeImage(entry.remoteUrl, attempt);
95+
if (!isCurrent(entry) || entry.snapshot.state !== "pending") return;
96+
if (!verifiedUrl) continue;
97+
98+
releaseLocalPreview(entry);
99+
entry.snapshot = { displayUrl: verifiedUrl, state: "ready" };
100+
toast.dismiss(toastId(entry.remoteUrl));
101+
emitChange();
102+
window.setTimeout(() => {
103+
if (!isCurrent(entry) || entry.snapshot.state !== "ready") return;
104+
presentations.delete(entry.remoteUrl);
105+
emitChange();
106+
}, READY_PRESENTATION_TTL_MS);
107+
return;
108+
}
109+
110+
if (!isCurrent(entry) || entry.snapshot.state !== "pending") return;
111+
entry.snapshot = {
112+
displayUrl: entry.remoteUrl,
113+
state: "failed",
114+
};
115+
emitChange();
116+
toast.error("Avatar couldn’t finish uploading", {
117+
action: {
118+
label: "Retry",
119+
onClick: () => retryAvatarPresentation(entry.remoteUrl),
120+
},
121+
description: "Your default avatar is showing instead.",
122+
id: toastId(entry.remoteUrl),
123+
});
124+
}
125+
126+
export function beginAvatarPresentation(remoteUrl: string, image: Blob): void {
127+
const existing = presentations.get(remoteUrl);
128+
if (existing) releaseLocalPreview(existing);
129+
130+
const localPreviewUrl = URL.createObjectURL(image);
131+
const entry: AvatarPresentationEntry = {
132+
generation: nextGeneration++,
133+
localPreviewUrl,
134+
remoteUrl,
135+
snapshot: { displayUrl: localPreviewUrl, state: "pending" },
136+
};
137+
presentations.set(remoteUrl, entry);
138+
emitChange();
139+
void verifyPresentation(entry);
140+
}
141+
142+
export function retryAvatarPresentation(remoteUrl: string): void {
143+
const entry = presentations.get(remoteUrl);
144+
if (entry?.snapshot.state !== "failed") return;
145+
entry.generation = nextGeneration++;
146+
entry.snapshot = {
147+
displayUrl: entry.localPreviewUrl ?? entry.remoteUrl,
148+
state: "pending",
149+
};
150+
emitChange();
151+
void verifyPresentation(entry);
152+
}
153+
154+
export function getAvatarPresentation(
155+
remoteUrl: string | null,
156+
): AvatarPresentation | null {
157+
if (!remoteUrl) return null;
158+
return presentations.get(remoteUrl)?.snapshot ?? null;
159+
}
160+
161+
export function subscribeAvatarPresentations(listener: () => void): () => void {
162+
listeners.add(listener);
163+
return () => listeners.delete(listener);
164+
}
165+
166+
export function useAvatarPresentation(
167+
remoteUrl: string | null,
168+
): AvatarPresentation | null {
169+
return React.useSyncExternalStore(
170+
subscribeAvatarPresentations,
171+
() => getAvatarPresentation(remoteUrl),
172+
() => null,
173+
);
174+
}

‎desktop/src/features/profile/ui/ProfileAvatar.tsx‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import * as React from "react";
22
import { UserRound } from "lucide-react";
33

4+
import { useAvatarPresentation } from "@/features/profile/avatarPresentationStore";
45
import { parseAnimatedAvatarUrl } from "@/shared/lib/animatedAvatar";
56
import { cn } from "@/shared/lib/cn";
67
import { getInitials } from "@/shared/lib/initials";
78
import { rewriteRelayUrl } from "@/shared/lib/mediaUrl";
89
import { Avatar, AvatarFallback, AvatarImage } from "@/shared/ui/avatar";
10+
import { Spinner } from "@/shared/ui/spinner";
911

1012
type ProfileAvatarProps = {
1113
avatarUrl: string | null;
@@ -29,16 +31,18 @@ export function ProfileAvatar({
2931
testId,
3032
}: ProfileAvatarProps) {
3133
const initials = getInitials(label);
34+
const presentation = useAvatarPresentation(avatarUrl);
35+
const presentedAvatarUrl = presentation?.displayUrl ?? avatarUrl;
3236

3337
// Animated avatars show their static poster frame until hovered, then play
3438
// the animation.
35-
const animated = parseAnimatedAvatarUrl(avatarUrl);
39+
const animated = parseAnimatedAvatarUrl(presentedAvatarUrl);
3640
const [isHovered, setIsHovered] = React.useState(false);
3741
const baseUrl = animated
3842
? isHovered
3943
? animated.animationUrl
4044
: animated.posterUrl
41-
: avatarUrl;
45+
: presentedAvatarUrl;
4246

4347
// Compute the live (proxied) source. Failures are tracked per resolved URL so
4448
// the poster and hover animation can recover independently.
@@ -69,7 +73,11 @@ export function ProfileAvatar({
6973
{src !== undefined ? (
7074
<AvatarImage
7175
alt={`${label} avatar`}
72-
className={cn("object-cover", imageClassName)}
76+
className={cn(
77+
"object-cover",
78+
presentation?.state === "pending" && "brightness-75",
79+
imageClassName,
80+
)}
7381
data-testid={testId ? `${testId}-image` : undefined}
7482
onLoadingStatusChange={(status) => {
7583
if (status === "error") setFailedSrc(liveSrc);
@@ -97,6 +105,18 @@ export function ProfileAvatar({
97105
)}
98106
</AvatarFallback>
99107
) : null}
108+
{presentation?.state === "pending" ? (
109+
<span
110+
aria-label="Avatar upload pending"
111+
className="pointer-events-none absolute inset-0 flex items-center justify-center text-white drop-shadow-sm"
112+
data-testid={testId ? `${testId}-upload-pending` : undefined}
113+
role="status"
114+
>
115+
<span className="flex size-7 items-center justify-center rounded-full bg-black/35">
116+
<Spinner aria-hidden="true" className="border-2" size={16} />
117+
</span>
118+
</span>
119+
) : null}
100120
</Avatar>
101121
);
102122
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import * as React from "react";
2+
3+
import { beginAvatarPresentation } from "@/features/profile/avatarPresentationStore";
4+
5+
export const DONE_BUTTON_CONTENT_TRANSITION = {
6+
duration: 0.14,
7+
ease: [0.23, 1, 0.32, 1],
8+
} as const;
9+
10+
export const DONE_BUTTON_SHELL_TRANSITION = {
11+
duration: 0.18,
12+
ease: [0.23, 1, 0.32, 1],
13+
} as const;
14+
15+
export function waitForPendingButtonPaint() {
16+
return new Promise<void>((resolve) => {
17+
if (
18+
typeof window === "undefined" ||
19+
typeof window.requestAnimationFrame !== "function"
20+
) {
21+
setTimeout(resolve, 0);
22+
return;
23+
}
24+
25+
window.requestAnimationFrame(() => {
26+
window.requestAnimationFrame(() => setTimeout(resolve, 0));
27+
});
28+
});
29+
}
30+
31+
export function useUploadPreviewLifecycle({
32+
clearFallback,
33+
onSuccess,
34+
showFallback,
35+
}: {
36+
clearFallback: () => void;
37+
onSuccess: (uploadedUrl: string) => void;
38+
showFallback: (file: File) => void;
39+
}) {
40+
const pendingFileRef = React.useRef<File | null>(null);
41+
42+
return {
43+
onUploadSettled: () => {
44+
pendingFileRef.current = null;
45+
clearFallback();
46+
},
47+
onUploadStart: (file: File) => {
48+
pendingFileRef.current = file;
49+
showFallback(file);
50+
},
51+
onUploadSuccess: (uploadedUrl: string) => {
52+
const pendingFile = pendingFileRef.current;
53+
if (pendingFile) beginAvatarPresentation(uploadedUrl, pendingFile);
54+
onSuccess(uploadedUrl);
55+
},
56+
};
57+
}
58+
59+
export function useLocalAvatarPreview() {
60+
const [previewUrl, setPreviewUrl] = React.useState<string | null>(null);
61+
const previewUrlRef = React.useRef<string | null>(null);
62+
63+
const clearPreview = React.useCallback(() => {
64+
if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current);
65+
previewUrlRef.current = null;
66+
setPreviewUrl(null);
67+
}, []);
68+
69+
const showFilePreview = React.useCallback((file: File) => {
70+
if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current);
71+
const nextUrl = URL.createObjectURL(file);
72+
previewUrlRef.current = nextUrl;
73+
setPreviewUrl(nextUrl);
74+
}, []);
75+
76+
React.useEffect(() => clearPreview, [clearPreview]);
77+
78+
return { clearPreview, previewUrl, showFilePreview };
79+
}

0 commit comments

Comments
 (0)