Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): unify remote image loading and ready state (#921)

Gener1105369aa8db
diff --git a/src/web/src/components/avatar/profile-avatar.test.ts b/src/web/src/components/avatar/profile-avatar.test.ts
index 2989ed875..6dd8e0c06 100644
--- a/src/web/src/components/avatar/profile-avatar.test.ts
+++ b/src/web/src/components/avatar/profile-avatar.test.ts
@@ -32,7 +32,8 @@ describe("ProfileAvatar", () => {
expect(html).toContain('data-slot="avatar-image" data-avatar-photo-state="pending"')
expect(html).toContain('src="https://cdn.example.com/ada.png" alt="Ada"')
expect(html).toContain("opacity-0")
- expect(html).toContain("transition-opacity duration-150 ease-out motion-reduce:transition-none")
+ expect(html).not.toContain("transition-opacity")
+ expect(html).toContain("transition-none")
expect(html).toContain("width:40px;height:40px")
expect(html).toContain("ring-2")
})
diff --git a/src/web/src/components/community/messages/image-lightbox.dom.test.ts b/src/web/src/components/community/messages/image-lightbox.dom.test.ts
index 0e1ab9842..7ed5db6a0 100644
--- a/src/web/src/components/community/messages/image-lightbox.dom.test.ts
+++ b/src/web/src/components/community/messages/image-lightbox.dom.test.ts
@@ -73,9 +73,67 @@ describe("ImageLightbox", () => {
afterEach(() => {
vi.useRealTimers()
+ vi.restoreAllMocks()
vi.unstubAllGlobals()
})
+ it("shows a complete cached original immediately without decode or a scheduled reveal", () => {
+ const descriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "decode")
+ const decode = vi.fn(() => new Promise<void>(() => {}))
+ Object.defineProperty(HTMLImageElement.prototype, "decode", { configurable: true, value: decode })
+ vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(true)
+ vi.spyOn(HTMLImageElement.prototype, "naturalWidth", "get").mockReturnValue(1000)
+ vi.spyOn(HTMLImageElement.prototype, "naturalHeight", "get").mockReturnValue(500)
+ const schedule = vi.fn()
+ vi.stubGlobal("requestAnimationFrame", schedule)
+ try {
+ for (let mount = 0; mount < 2; mount++) {
+ const { renderer } = renderLightbox({ originalUrl: "/cached-original", thumbnailUrl: "/cached-thumbnail", name: "cached" })
+ expect(image(renderer, tid.imageLightboxOriginal)).toHaveClass("opacity-100", "pointer-events-auto")
+ expect(image(renderer, tid.imageLightboxOriginal)).not.toHaveClass("transition-opacity")
+ expect(image(renderer, tid.imageLightboxThumbnail)).toHaveClass("opacity-0")
+ expect(renderer.queryByTestId(tid.imageLightboxLoading)).not.toBeInTheDocument()
+ expect(renderer.getByTestId(tid.imageLightbox).style.aspectRatio).toBe("1000 / 500")
+ expect(renderer.getByRole("button", { name: "Zoom in" })).toBeEnabled()
+ renderer.unmount()
+ }
+ expect(decode).not.toHaveBeenCalled()
+ expect(schedule).not.toHaveBeenCalled()
+ } finally {
+ if (descriptor) Object.defineProperty(HTMLImageElement.prototype, "decode", descriptor)
+ else delete (HTMLImageElement.prototype as Partial<HTMLImageElement>).decode
+ }
+ })
+
+ it("recreates a failed original on online after its old node is removed and fences the old decode", async () => {
+ let finish!: () => void
+ const oldDecode = new Promise<void>((resolve) => { finish = resolve })
+ const { renderer } = renderLightbox({ originalUrl: "/original?v=3&size=640", thumbnailUrl: "/thumbnail", name: "photo" })
+ await loadThumbnail(renderer, 640, 480)
+ const thumbnail = image(renderer, tid.imageLightboxThumbnail)
+ const old = image(renderer, tid.imageLightboxOriginal)
+ prepareImage(old, 640, 480, () => oldDecode)
+ fireEvent.load(old)
+ fireEvent.error(old)
+ expect(old.isConnected).toBe(false)
+ expect(renderer.queryByTestId(tid.imageLightboxOriginal)).not.toBeInTheDocument()
+ fireEvent(window, new Event("online"))
+ const retried = image(renderer, tid.imageLightboxOriginal)
+ expect(retried).not.toBe(old)
+ expect(retried).toHaveAttribute("src", "/original?v=3&size=640")
+ expect(image(renderer, tid.imageLightboxThumbnail)).toBe(thumbnail)
+ expect(thumbnail).toHaveClass("opacity-100")
+ await act(async () => { finish(); await oldDecode })
+ expect(retried).toHaveAttribute("data-remote-image-state", "pending")
+ fireEvent.error(old)
+ expect(retried).toHaveAttribute("data-remote-image-state", "pending")
+ await loadImage(retried, 640, 480, () => Promise.resolve())
+ expect(retried).toHaveClass("opacity-100")
+ expect(renderer.queryByTestId(tid.imageLightboxError)).not.toBeInTheDocument()
+ fireEvent(window, new Event("online"))
+ expect(image(renderer, tid.imageLightboxOriginal)).toBe(retried)
+ })
+
it("reserves the known frame and reveals the original only after decode", async () => {
let resolveDecode!: () => void
const decodePromise = new Promise<void>((resolve) => { resolveDecode = resolve })
@@ -284,12 +342,9 @@ describe("ImageLightbox", () => {
expect(image(renderer, tid.imageLightboxOriginal)).toHaveClass("opacity-100")
})
- it("shows a cold pending frame, then paints the thumbnail before an already-decoded original", async () => {
- let runAnimationFrame: FrameRequestCallback | undefined
- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
- runAnimationFrame = callback
- return 1
- })
+ it("keeps a cold thumbnail until the original is decoded without an additional reveal frame", async () => {
+ const schedule = vi.fn()
+ vi.stubGlobal("requestAnimationFrame", schedule)
vi.stubGlobal("cancelAnimationFrame", vi.fn())
try {
@@ -305,17 +360,14 @@ describe("ImageLightbox", () => {
expect(frame().parentElement).not.toHaveClass("invisible")
expect(renderer.getByTestId(tid.imageLightboxLoading)).toBeInTheDocument()
- await loadImage(original, 1200, 630, () => Promise.resolve())
- expect(image(renderer, tid.imageLightboxOriginal)).toHaveClass("opacity-0")
-
await loadThumbnail(renderer, 512, 269)
expect(frame().parentElement).not.toHaveClass("invisible")
expect(image(renderer, tid.imageLightboxThumbnail)).toHaveClass("opacity-100")
expect(image(renderer, tid.imageLightboxOriginal)).toHaveClass("opacity-0")
- expect(runAnimationFrame).toBeTypeOf("function")
-
- act(() => runAnimationFrame!(0))
+ await loadImage(original, 1200, 630, () => Promise.resolve())
expect(image(renderer, tid.imageLightboxOriginal)).toHaveClass("opacity-100")
+ expect(image(renderer, tid.imageLightboxThumbnail)).toHaveClass("opacity-0")
+ expect(schedule).not.toHaveBeenCalled()
} finally {
vi.unstubAllGlobals()
}
diff --git a/src/web/src/components/community/messages/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsx
index 84b8f430b..81fd2d4a6 100644
--- a/src/web/src/components/community/messages/image-lightbox.tsx
+++ b/src/web/src/components/community/messages/image-lightbox.tsx
@@ -2,7 +2,7 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useMemo } from "react"
+import { useLayoutEffect, useMemo } from "react"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { MinusIcon, PlusIcon, RotateCcwIcon, XIcon } from "lucide-react"
@@ -22,7 +22,6 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>
[image.height, image.width],
)
const [dimensions, setDimensions] = useAtom(useCreateAtom<ImageDimensions | undefined>(knownDimensions))
- const [revealedAttempt, setRevealedAttempt] = useAtom(useCreateAtom<number | null>(null))
const [
thumbnailStatus,
thumbnailAttempt,
@@ -30,7 +29,7 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>
thumbnailRef,
onThumbnailLoad,
onThumbnailError,
- ] = useRemoteImageAttempt()
+ ] = useRemoteImageAttempt({ source: image.thumbnailUrl })
const [
originalStatus,
originalAttempt,
@@ -39,29 +38,19 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>
onOriginalLoad,
onOriginalError,
retryOriginal,
- ] = useRemoteImageAttempt()
+ ] = useRemoteImageAttempt({ source: image.originalUrl })
const frameStyle = previewFrameStyle(dimensions)
const thumbnailReady = !!image.thumbnailUrl && thumbnailStatus === "ready"
- const originalReady = originalStatus === "ready" && revealedAttempt === originalAttempt
+ const originalReady = originalStatus === "ready"
const { frameRef, view, reset, zoomIn, zoomOut, handlers } = useImageLightboxZoom(originalReady)
const imageTransform = { transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }
- useEffect(() => {
+ useLayoutEffect(() => {
if (originalStatus !== "ready" || !originalImage) return
- const requestKey = originalAttempt
const naturalDimensions = validImageDimensions(originalImage.naturalWidth, originalImage.naturalHeight)
- const reveal = () => {
- setDimensions(knownDimensions ?? naturalDimensions)
- setRevealedAttempt(requestKey)
- }
- if (typeof requestAnimationFrame !== "function") {
- reveal()
- return
- }
- const frameId = requestAnimationFrame(reveal)
- return () => cancelAnimationFrame(frameId)
- }, [knownDimensions, originalAttempt, originalImage, originalStatus, setDimensions, setRevealedAttempt])
+ setDimensions(knownDimensions ?? naturalDimensions)
+ }, [knownDimensions, originalImage, originalStatus, setDimensions])
return (
<div className="relative w-fit">
@@ -90,7 +79,7 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>
style={imageTransform}
onLoad={onThumbnailLoad}
onError={onThumbnailError}
- className={`absolute inset-0 size-full rounded-lg object-contain transition-opacity duration-150 ease-out motion-reduce:transition-none ${thumbnailReady && !originalReady ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"}`}
+ className={`absolute inset-0 size-full rounded-lg object-contain ${thumbnailReady && !originalReady ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"}`}
/>
)}
{!thumbnailReady && !originalReady && originalStatus === "pending" && (
@@ -115,7 +104,7 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>
style={imageTransform}
onLoad={onOriginalLoad}
onError={onOriginalError}
- className={`absolute inset-0 size-full rounded-lg object-contain transition-opacity duration-150 ease-out motion-reduce:transition-none ${originalReady ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"}`}
+ className={`absolute inset-0 size-full rounded-lg object-contain ${originalReady ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"}`}
/>
)}
</div>
diff --git a/src/web/src/components/community/messages/message.render.dom.test.ts b/src/web/src/components/community/messages/message.render.dom.test.ts
index ebd90842b..c73f78117 100644
--- a/src/web/src/components/community/messages/message.render.dom.test.ts
+++ b/src/web/src/components/community/messages/message.render.dom.test.ts
@@ -1702,6 +1702,52 @@ describe("Message desktop text selection", () => {
})
describe("Message image attachment layout", () => {
+ it.each([
+ { name: "attachment", fields: { attachments: [{ kind: "image" as const, name: "same.png", url: "/same.png" }] } },
+ { name: "embed", fields: { embeds: [{ image: { url: "/same.png", width: 320, height: 200 } }] } },
+ { name: "Markdown", fields: { content: "![Image](/same.png)" } },
+ ])("retains a same-message $name image but retires readiness and late decode for a different message", async ({ fields }) => {
+ const onOpenThread = vi.fn()
+ const tree = (id: string, suffix = "") => makeTree({
+ m: baseMsg({ ...fields, id, reactions: suffix ? [{ emoji: "🔥", count: 1, me: false, userIds: [] }] : [] }),
+ onOpenThread,
+ })
+ const renderer = render(tree("one"))
+ const current = () => renderer.root.element.querySelector<HTMLImageElement>('[data-remote-image-kind="content"]')!
+ const prepare = (image: HTMLImageElement, decode = () => Promise.resolve()) => Object.defineProperties(image, {
+ decode: { configurable: true, value: decode },
+ naturalWidth: { configurable: true, value: 320 },
+ naturalHeight: { configurable: true, value: 200 },
+ })
+ const first = current()
+ prepare(first)
+ fireEvent.load(first)
+ await act(async () => { await Promise.resolve() })
+ expect(first).toHaveAttribute("data-remote-image-state", "ready")
+ renderer.rerender(tree("one", " update"))
+ expect(current()).toBe(first)
+ expect(first).toHaveClass("opacity-100")
+
+ renderer.rerender(tree("two"))
+ const second = current()
+ expect(second).not.toBe(first)
+ expect(first.isConnected).toBe(false)
+ let finish!: () => void
+ const obsolete = new Promise<void>((resolve) => { finish = resolve })
+ prepare(second, () => obsolete)
+ fireEvent.load(second)
+ renderer.rerender(tree("three"))
+ const third = current()
+ expect(third).not.toBe(second)
+ await act(async () => { finish(); await obsolete })
+ expect(third).toHaveAttribute("data-remote-image-state", "pending")
+ expect(third).toHaveClass("opacity-0")
+ prepare(third)
+ fireEvent.load(third)
+ await act(async () => { await Promise.resolve() })
+ expect(third).toHaveAttribute("data-remote-image-state", "ready")
+ })
+
it("keeps a known portrait image intrinsic and constrains it by message width + max height", () => {
let renderer: DomRenderer
act(() => {
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index eac4a5c34..75adbcbdd 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -694,6 +694,7 @@ function MessageImpl({
) : (
visibleContent && (
<MessageBody
+ key={m.id}
text={visibleContent}
onOpenProfile={onOpenProfile}
perspective={
@@ -712,7 +713,7 @@ function MessageImpl({
const frameStyle = attachmentImageFrameStyle(a.width, a.height)
return (
<RemoteContentImage
- key={i}
+ key={`${m.id}:${i}`}
data-testid={tid.messageImage(m.id, i)}
src={a.thumbnailUrl ?? a.url}
alt={a.name}
@@ -743,7 +744,7 @@ function MessageImpl({
<div className="flex flex-col gap-2">
{m.embeds.map((embed, ei) => (
<article
- key={ei}
+ key={`${m.id}:${ei}`}
className="flex max-w-108 items-start gap-2 overflow-hidden rounded-lg border border-border bg-card p-2"
>
{embed.color && (
diff --git a/src/web/src/components/community/messages/thread-opener.dom.test.ts b/src/web/src/components/community/messages/thread-opener.dom.test.ts
index f09a635aa..8a43307da 100644
--- a/src/web/src/components/community/messages/thread-opener.dom.test.ts
+++ b/src/web/src/components/community/messages/thread-opener.dom.test.ts
@@ -30,6 +30,44 @@ describe("ThreadOpener image attachment layout", () => {
vi.unstubAllGlobals()
})
+ it.each(["attachment", "Markdown"])("retires a previous opener's $name attempt even when its source is reused", async (kind) => {
+ const select = (id: string) => useMessageMock.mockReturnValue({
+ isLoading: false,
+ isError: false,
+ message: {
+ id, type: "chat", authorId: "user_1", authorName: "Alice", createdAt: "2026-08-08T00:00:00.000Z",
+ content: kind === "Markdown" ? "![Image](/same.png)" : "Image",
+ attachments: kind === "attachment" ? [{ kind: "image", name: "same.png", url: "/same.png" }] : undefined,
+ },
+ })
+ const tree = (id: string) => React.createElement(ThreadOpener, {
+ parentMessageId: id, parentChannelId: "parent_1", serverId: "server_1", viewerUserId: "viewer_1",
+ })
+ select("one")
+ const renderer = render(tree("one"))
+ const current = () => renderer.container.querySelector<HTMLImageElement>('[data-remote-image-kind="content"]')!
+ const first = current()
+ let finish!: () => void
+ const obsolete = new Promise<void>((resolve) => { finish = resolve })
+ Object.defineProperties(first, {
+ decode: { configurable: true, value: () => obsolete },
+ naturalWidth: { configurable: true, value: 320 },
+ naturalHeight: { configurable: true, value: 200 },
+ })
+ fireEvent.load(first)
+ renderer.rerender(tree("one"))
+ expect(current()).toBe(first)
+ select("two")
+ renderer.rerender(tree("two"))
+ const next = current()
+ expect(next).not.toBe(first)
+ expect(first.isConnected).toBe(false)
+ await act(async () => { finish(); await obsolete })
+ expect(next).toHaveAttribute("src", "/same.png")
+ expect(next).toHaveAttribute("data-remote-image-state", "pending")
+ expect(next).toHaveClass("opacity-0")
+ })
+
it("renders projected reply content in the opener", () => {
useMessageMock.mockReturnValue({
isLoading: false,
diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsx
index 9db45d3f5..2f3ee56aa 100644
--- a/src/web/src/components/community/messages/thread-opener.tsx
+++ b/src/web/src/components/community/messages/thread-opener.tsx
@@ -153,6 +153,7 @@ export function ThreadOpener({
{visibleContent && (
<MessageBody
+ key={msg.id}
text={visibleContent}
onOpenProfile={onOpenProfile}
perspective={msg.authorId === viewerUserId ? "sender" : "recipient"}
@@ -166,7 +167,7 @@ export function ThreadOpener({
const frameStyle = attachmentImageFrameStyle(a.width, a.height)
return (
<RemoteContentImage
- key={i}
+ key={`${msg.id}:${i}`}
data-testid={tid.threadOpenerImage(i)}
src={a.thumbnailUrl ?? a.url}
alt={a.name}
diff --git a/src/web/src/components/remote-image/remote-image-attempt.ts b/src/web/src/components/remote-image/remote-image-attempt.ts
index c720f7274..82e0a4f77 100644
--- a/src/web/src/components/remote-image/remote-image-attempt.ts
+++ b/src/web/src/components/remote-image/remote-image-attempt.ts
@@ -2,6 +2,8 @@
import {
useCallback,
+ useEffect,
+ useEffectEvent,
useLayoutEffect,
useRef,
type RefCallback,
@@ -24,14 +26,14 @@ type AttemptAction =
| { type: "retry" }
| { type: "source"; source?: string }
-function reduceAttempt(state: AttemptState, action: AttemptAction, identity: boolean): AttemptState {
+function reduceAttempt(state: AttemptState, action: AttemptAction, retainImage: boolean): AttemptState {
if (action.type === "source" && action.source === state.source) return state
if (action.type === "retry" || action.type === "source") {
return {
attempt: state.attempt + 1,
status: "pending",
source: action.type === "source" ? action.source : state.source,
- image: identity ? state.image : undefined,
+ image: retainImage ? state.image : undefined,
}
}
if (state.attempt !== action.attempt || state.source !== action.source || state.status !== "pending") return state
@@ -40,27 +42,28 @@ function reduceAttempt(state: AttemptState, action: AttemptAction, identity: boo
: { attempt: state.attempt, source: state.source, status: "error" }
}
-export function useRemoteImageAttempt({ source, cachedReady = false }: { source?: string; cachedReady?: boolean } = {}) {
- const identity = source !== undefined
+export function useRemoteImageAttempt({ source, retainImage = false }: { source?: string; retainImage?: boolean }) {
const store = useCreateStore({ attempt: 0, status: "pending", source, active: true, generation: 0 } as AttemptState & { active: boolean; generation: number })
const node = useRef<HTMLImageElement | null>(null)
const state = useSelector(store, (value) => value)
const dispatch = useCallback((action: AttemptAction, generation = store.get().generation) => store.setState((current) => {
if (!current.active || current.generation !== generation) return current
- const next = reduceAttempt(current, action, identity)
+ const next = reduceAttempt(current, action, retainImage)
return next === current ? current : { ...next, active: current.active, generation: current.generation }
- }), [identity, store])
+ }), [retainImage, store])
useLayoutEffect(() => {
store.setState((current) => ({ ...current, active: true }))
return () => store.setState((current) => ({ ...current, active: false, generation: current.generation + 1 }))
}, [store])
useLayoutEffect(() => { dispatch({ type: "source", source }) }, [dispatch, source])
- const matchesSource = useCallback((image: HTMLImageElement) => source === undefined || (
- image.getAttribute("src") === source
+ const matchesSource = useCallback((image: HTMLImageElement) => source !== undefined && (
+ image === node.current
+ && image.getAttribute("src") === source
&& (!image.currentSrc || image.currentSrc === image.src)
), [source])
const decode = useCallback(async (image: HTMLImageElement, attempt: number) => {
- if (!matchesSource(image) || store.get().source !== source) return
+ const current = store.get()
+ if (!matchesSource(image) || current.source !== source || current.attempt !== attempt || current.status !== "pending" || !current.active) return
const generation = store.get().generation
try {
await image.decode?.()
@@ -84,9 +87,8 @@ export function useRemoteImageAttempt({ source, cachedReady = false }: { source?
dispatch({ type: "error", attempt: state.attempt, source })
return
}
- if (cachedReady) dispatch({ type: "ready", attempt: state.attempt, image, source })
- else void decode(image, state.attempt)
- }, [cachedReady, decode, dispatch, matchesSource, source, state.attempt, store])
+ dispatch({ type: "ready", attempt: state.attempt, image, source })
+ }, [dispatch, matchesSource, source, state.attempt, store])
const onLoad = useCallback((event: SyntheticEvent<HTMLImageElement>) => {
void decode(event.currentTarget, state.attempt)
@@ -97,10 +99,22 @@ export function useRemoteImageAttempt({ source, cachedReady = false }: { source?
}, [dispatch, matchesSource, source, state.attempt])
const retry = useCallback(() => {
+ const current = store.get()
+ if (source === undefined || current.source !== source || !current.active) return
dispatch({ type: "retry" })
const image = node.current
if (source !== undefined && image?.getAttribute("src") === source) image.src = source
- }, [dispatch, source])
+ }, [dispatch, source, store])
+
+ const retryAfterReconnect = useEffectEvent(() => {
+ if (store.get().status !== "ready") retry()
+ })
+ useEffect(() => {
+ if (source === undefined) return
+ const onOnline = () => retryAfterReconnect()
+ window.addEventListener("online", onOnline)
+ return () => window.removeEventListener("online", onOnline)
+ }, [source])
return [
state.source === source ? state.status : "pending",
diff --git a/src/web/src/components/remote-image/remote-image.dom.test.ts b/src/web/src/components/remote-image/remote-image.dom.test.ts
index e24b50ca7..e6096c364 100644
--- a/src/web/src/components/remote-image/remote-image.dom.test.ts
+++ b/src/web/src/components/remote-image/remote-image.dom.test.ts
@@ -1,6 +1,7 @@
import React from "react"
import { afterEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent, render, screen } from "@/test/react-dom-harness"
+import { renderCommunity } from "@/test/community-owner-harness"
import { RemoteContentImage, RemoteIdentityImage } from "./remote-image"
import { RemoteMarkdownImage } from "./remote-markdown-image"
import { ShareImagePreparationContext } from "./share-image-context"
@@ -66,25 +67,29 @@ describe("remote image state adapters", () => {
}
})
- it("keeps content and Markdown cached pixels behind their original decode", async () => {
+ it.each([false, true])("shows content and Markdown cached pixels synchronously (StrictMode: %s)", (strict) => {
const descriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "decode")
- let finish!: () => void
- const pending = new Promise<void>((resolve) => { finish = resolve })
- Object.defineProperty(HTMLImageElement.prototype, "decode", { configurable: true, value: () => pending })
+ const decode = vi.fn(() => new Promise<void>(() => {}))
+ Object.defineProperty(HTMLImageElement.prototype, "decode", { configurable: true, value: decode })
vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(true)
vi.spyOn(HTMLImageElement.prototype, "naturalWidth", "get").mockReturnValue(40)
vi.spyOn(HTMLImageElement.prototype, "naturalHeight", "get").mockReturnValue(40)
const owner = createApplicationOwner("cached-content-viewer")
try {
- const rendered = render(React.createElement(ApplicationOwnerProvider, { owner },
+ const tree = React.createElement(ApplicationOwnerProvider, { owner },
React.createElement(RemoteContentImage, { src: "/cached-content.png", alt: "Content" }),
React.createElement(RemoteMarkdownImage, { src: "/cached-markdown.png", alt: "Markdown" }),
- ))
- const images = [...rendered.container.querySelectorAll("img")]
- expect(images.every((image) => image.dataset.remoteImageState === "pending")).toBe(true)
- await act(async () => { finish(); await pending })
- expect(images.every((image) => image.dataset.remoteImageState === "ready")).toBe(true)
- rendered.unmount()
+ )
+ for (let mount = 0; mount < 2; mount++) {
+ const rendered = render(strict ? React.createElement(React.StrictMode, null, tree) : tree)
+ const images = [...rendered.container.querySelectorAll("img")]
+ expect(images.every((image) => image.dataset.remoteImageState === "ready")).toBe(true)
+ expect(images.every((image) => image.classList.contains("opacity-100"))).toBe(true)
+ expect(images.every((image) => !image.classList.contains("transition-opacity"))).toBe(true)
+ expect(rendered.container.querySelector("[data-remote-image-placeholder]")).toBeNull()
+ rendered.unmount()
+ }
+ expect(decode).not.toHaveBeenCalled()
} finally {
owner.queryClient.clear()
if (descriptor) Object.defineProperty(HTMLImageElement.prototype, "decode", descriptor)
@@ -92,6 +97,73 @@ describe("remote image state adapters", () => {
}
})
+ it.each([
+ { name: "content", element: (src: string, alt: string) => React.createElement(RemoteContentImage, { src, alt }) },
+ { name: "Markdown", element: (src: string, alt: string) => React.createElement(RemoteMarkdownImage, { src, alt }) },
+ ])("keeps the same ready $name node on a same-source update and recovers the exact URL on online", async ({ element }) => {
+ const source = "/same.png?v=2&size=40"
+ const rendered = renderCommunity(element(source, "Before"))
+ const original = contentImage(rendered.container)
+ await makeReady(original)
+ rendered.rerender(element(source, "After"))
+ expect(contentImage(rendered.container)).toBe(original)
+ fireEvent(window, new Event("online"))
+ expect(contentImage(rendered.container)).toBe(original)
+ expect(original).toHaveAttribute("data-remote-image-state", "ready")
+
+ rendered.rerender(element("/failed.png?v=3&size=40", "Failed"))
+ const failed = contentImage(rendered.container)
+ fireEvent.error(failed)
+ fireEvent(window, new Event("online"))
+ const retried = contentImage(rendered.container)
+ expect(retried).not.toBe(failed)
+ expect(retried).toHaveAttribute("src", "/failed.png?v=3&size=40")
+ expect(retried).toHaveAttribute("data-remote-image-state", "pending")
+ await makeReady(retried)
+ expect(retried).toHaveAttribute("data-remote-image-state", "ready")
+ })
+
+ it.each([
+ { name: "identity", element: () => identityElement("/share.png") },
+ { name: "content", element: () => React.createElement(RemoteContentImage, { src: "/share.png", alt: "Content" }) },
+ { name: "Markdown", element: () => React.createElement(RemoteMarkdownImage, { src: "/share.png", alt: "Markdown" }) },
+ ])("retires $name readiness and keeps its URL inert throughout share preparation and online", async ({ element }) => {
+ const tree = (preparing: boolean) => React.createElement(ShareImagePreparationContext, { value: preparing }, element())
+ const rendered = renderCommunity(tree(false))
+ const live = rendered.container.querySelector<HTMLImageElement>("img")!
+ await makeReady(live)
+ rendered.rerender(tree(true))
+ const inert = rendered.container.querySelector<HTMLImageElement>("img")!
+ expect(inert).not.toBe(live)
+ expect(live.isConnected).toBe(false)
+ expect(inert).not.toHaveAttribute("src")
+ expect(inert).toHaveAttribute("data-share-image-src", "/share.png")
+ fireEvent(window, new Event("online"))
+ fireEvent.load(inert)
+ expect(rendered.container.querySelector("img")).toBe(inert)
+ expect(inert).not.toHaveAttribute("src")
+ expect(inert).toHaveAttribute("data-remote-image-state", "pending")
+ rendered.rerender(tree(false))
+ const resumed = rendered.container.querySelector<HTMLImageElement>("img")!
+ expect(resumed).not.toBe(inert)
+ expect(resumed).toHaveAttribute("src", "/share.png")
+ expect(resumed).toHaveAttribute("data-remote-image-state", "pending")
+ })
+
+ it.each([
+ { complete: true, width: 0, height: 0, currentSrc: "", status: "error" },
+ { complete: false, width: 40, height: 40, currentSrc: "", status: "pending" },
+ { complete: true, width: 40, height: 40, currentSrc: "https://wrong.example/old.png", status: "pending" },
+ ])("checks complete, current source and natural pixels before cached readiness: %j", ({ complete, width, height, currentSrc, status }) => {
+ vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(complete)
+ vi.spyOn(HTMLImageElement.prototype, "naturalWidth", "get").mockReturnValue(width)
+ vi.spyOn(HTMLImageElement.prototype, "naturalHeight", "get").mockReturnValue(height)
+ vi.spyOn(HTMLImageElement.prototype, "currentSrc", "get").mockReturnValue(currentSrc)
+ const rendered = render(React.createElement(RemoteContentImage, { src: "/current.png", alt: "Current" }))
+ expect(contentImage(rendered.container)).toHaveAttribute("data-remote-image-state", status)
+ expect(contentImage(rendered.container)).toHaveClass("opacity-0")
+ })
+
it("keeps the same ready identity node when only its props update", async () => {
const rendered = render(identityElement("/peer?v=1"))
const original = sourceImage(rendered.container, "/peer?v=1")
diff --git a/src/web/src/components/remote-image/remote-image.tsx b/src/web/src/components/remote-image/remote-image.tsx
index 9f1a08400..9177f6c2c 100644
--- a/src/web/src/components/remote-image/remote-image.tsx
+++ b/src/web/src/components/remote-image/remote-image.tsx
@@ -34,17 +34,9 @@ function IdentityImageAttempt({
"data-testid": testId,
}: IdentityImageProps) {
const sourceProps = useShareImageSource(src)
- const [status, , usableImage, imageRef, onLoad, onError, retry] = useRemoteImageAttempt({ source: src, cachedReady: true })
+ const [status, , usableImage, imageRef, onLoad, onError] = useRemoteImageAttempt({ source: sourceProps.src, retainImage: true })
const visible = Boolean(usableImage)
const placeholderStatus = visible ? "ready" : status
- const retryAfterReconnect = useEffectEvent(() => {
- if (status !== "ready") retry()
- })
- useEffect(() => {
- const onOnline = () => retryAfterReconnect()
- window.addEventListener("online", onOnline)
- return () => window.removeEventListener("online", onOnline)
- }, [])
const legacyStatus = status === "error" ? "failed" : status
return (
@@ -71,11 +63,10 @@ function IdentityImageAttempt({
{...sourceProps}
alt={alt}
className={cn(
- "absolute inset-0 size-full object-cover transition-opacity duration-150 ease-out motion-reduce:transition-none",
+ "absolute inset-0 size-full object-cover transition-none",
visible ? "opacity-100" : "opacity-0",
className,
)}
- style={{ transitionProperty: "none" }}
onLoad={onLoad}
onError={onError}
/>
@@ -127,7 +118,7 @@ function ContentImageAttempt({
...imageProps
}: ContentImageProps) {
const sourceProps = useShareImageSource(src)
- const [status, attempt, readyImage, imageRef, onLoad, onError, retry] = useRemoteImageAttempt()
+ const [status, attempt, readyImage, imageRef, onLoad, onError, retry] = useRemoteImageAttempt({ source: sourceProps.src })
const notifyReady = useEffectEvent((image: HTMLImageElement) => onReady?.(image))
useEffect(() => onStateChange?.(status), [onStateChange, status])
@@ -160,7 +151,7 @@ function ContentImageAttempt({
alt={alt}
loading={loading}
className={cn(
- "absolute inset-0 size-full transition-opacity duration-150 ease-out motion-reduce:transition-none",
+ "absolute inset-0 size-full",
status === "ready" ? "opacity-100" : "opacity-0",
imageClassName,
)}
@@ -208,5 +199,6 @@ function ContentImageAttempt({
}
export function RemoteContentImage(props: ContentImageProps) {
- return <ContentImageAttempt key={props.src} {...props} />
+ const sourceProps = useShareImageSource(props.src)
+ return <ContentImageAttempt key={JSON.stringify([props.src, "src" in sourceProps])} {...props} />
}
diff --git a/src/web/src/components/remote-image/remote-markdown-image.tsx b/src/web/src/components/remote-image/remote-markdown-image.tsx
index db3846f7c..2ee86f577 100644
--- a/src/web/src/components/remote-image/remote-markdown-image.tsx
+++ b/src/web/src/components/remote-image/remote-markdown-image.tsx
@@ -30,7 +30,7 @@ function MarkdownImageAttempt({
}: MarkdownImageProps) {
const sourceProps = useShareImageSource(src ?? "")
void node
- const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt()
+ const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt({ source: sourceProps.src })
const imageWidth = dimension(width)
const imageHeight = dimension(height)
const aspectRatio = imageWidth && imageHeight ? `${imageWidth}/${imageHeight}` : "4/3"
@@ -67,7 +67,7 @@ function MarkdownImageAttempt({
height={imageHeight}
loading="lazy"
className={cn(
- "absolute inset-0 size-full rounded-lg object-contain transition-opacity duration-150 ease-out motion-reduce:transition-none",
+ "absolute inset-0 size-full rounded-lg object-contain",
status === "ready" ? "opacity-100" : "opacity-0",
className,
)}
@@ -108,5 +108,6 @@ function MarkdownImageAttempt({
}
export function RemoteMarkdownImage(props: MarkdownImageProps) {
- return props.src ? <MarkdownImageAttempt key={props.src} {...props} /> : null
+ const sourceProps = useShareImageSource(props.src ?? "")
+ return props.src ? <MarkdownImageAttempt key={JSON.stringify([props.src, "src" in sourceProps])} {...props} /> : null
}