Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: improve message image sizing, thumbnails and preview zoom (#901)

Gustavo Ye04d011b15c35
diff --git a/src/daemon/scripts/thumbnail-pack-smoke.mjs b/src/daemon/scripts/thumbnail-pack-smoke.mjs
index 0a16eaa44..8aecaa3fa 100644
--- a/src/daemon/scripts/thumbnail-pack-smoke.mjs
+++ b/src/daemon/scripts/thumbnail-pack-smoke.mjs
@@ -72,11 +72,11 @@ try {
const payloadStart = binary.indexOf("\r\n\r\n", thumbnailStart) + 4
const payloadEnd = binary.indexOf(`\r\n--${boundary}`, payloadStart)
const thumbnail = body.subarray(payloadStart, payloadEnd)
- assert(thumbnail.length <= 512 * 1024)
+ assert(thumbnail.length <= 256 * 1024)
assert.deepEqual([...thumbnail.subarray(0, 2)], [0xff, 0xd8])
assert.deepEqual([...thumbnail.subarray(-2)], [0xff, 0xd9])
const thumbnailMetadata = await sharp(thumbnail).metadata()
- assert(Math.max(thumbnailMetadata.width ?? 0, thumbnailMetadata.height ?? 0) <= 1024)
+ assert(Math.max(thumbnailMetadata.width ?? 0, thumbnailMetadata.height ?? 0) <= 720)
process.stdout.write("daemon thumbnail pack smoke passed\n")
} finally {
fs.rmSync(temp, { recursive: true, force: true })
diff --git a/src/daemon/src/cli/imageThumbnail.test.ts b/src/daemon/src/cli/imageThumbnail.test.ts
index 9cbcb2c2c..aafda6947 100644
--- a/src/daemon/src/cli/imageThumbnail.test.ts
+++ b/src/daemon/src/cli/imageThumbnail.test.ts
@@ -17,16 +17,16 @@ describe("prepareCommunityImageUpload", () => {
prepareCommunityImageUpload(new Uint8Array(1), "image/png"),
).resolves.toEqual({});
await expect(
- prepareCommunityImageUpload(new Uint8Array(512 * 1024 + 1), "image/png"),
+ prepareCommunityImageUpload(new Uint8Array(256 * 1024 + 1), "image/png"),
).rejects.toThrow("required image preview");
});
it("rejects when every bounded JPEG candidate remains over the byte cap", async () => {
const pipeline = {
- metadata: vi.fn().mockResolvedValue({ width: 1025, height: 512 }),
+ metadata: vi.fn().mockResolvedValue({ width: 721, height: 512 }),
resize: vi.fn(),
jpeg: vi.fn(),
- toBuffer: vi.fn().mockResolvedValue(new Uint8Array(512 * 1024 + 1)),
+ toBuffer: vi.fn().mockResolvedValue(new Uint8Array(256 * 1024 + 1)),
};
pipeline.resize.mockReturnValue(pipeline);
pipeline.jpeg.mockReturnValue(pipeline);
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 2789f5624..732c0221d 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -1496,7 +1496,7 @@ describe("message attachment upload", () => {
const { default: sharp } = await import("sharp")
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-raster-matrix-"))
const file = path.join(dir, `source.${extension}`)
- let pipeline = sharp({ create: { width: 1025, height: 24, channels: 3, background: "#123456" } })
+ let pipeline = sharp({ create: { width: 721, height: 24, channels: 3, background: "#123456" } })
pipeline = extension === "jpg" ? pipeline.jpeg() : extension === "webp" ? pipeline.webp() : pipeline.gif()
fs.writeFileSync(file, await pipeline.toBuffer())
const uploadSpy = vi.fn(async () => ({
@@ -1509,9 +1509,9 @@ describe("message attachment upload", () => {
fs.rmSync(dir, { recursive: true, force: true })
}
const request = uploadSpy.mock.calls[0]![0]
- expect(request).toMatchObject({ width: 1025, height: 24 })
+ expect(request).toMatchObject({ width: 721, height: 24 })
expect(request.thumbnail?.contentType).toBe("image/jpeg")
- expect((request.thumbnail?.data as Uint8Array).byteLength).toBeLessThanOrEqual(512 * 1024)
+ expect((request.thumbnail?.data as Uint8Array).byteLength).toBeLessThanOrEqual(256 * 1024)
})
it("generates a bounded JPEG when only the original byte limit is exceeded", async () => {
@@ -1525,7 +1525,7 @@ describe("message attachment upload", () => {
const source = await sharp(randomBytes(640 * 480 * 3), {
raw: { width: 640, height: 480, channels: 3 },
}).png({ compressionLevel: 0 }).toBuffer()
- expect(source.byteLength).toBeGreaterThan(512 * 1024)
+ expect(source.byteLength).toBeGreaterThan(256 * 1024)
fs.writeFileSync(file, source)
const uploadSpy = vi.fn(async (req: Parameters<ServerApi["attachmentUpload"]>[0]) => ({
id: "att", filename: "source.png", contentType: "image/png", size: source.byteLength,
@@ -1539,7 +1539,7 @@ describe("message attachment upload", () => {
}
const request = uploadSpy.mock.calls[0]![0]
expect(request).toMatchObject({ width: 640, height: 480 })
- expect((request.thumbnail?.data as Uint8Array).byteLength).toBeLessThanOrEqual(512 * 1024)
+ expect((request.thumbnail?.data as Uint8Array).byteLength).toBeLessThanOrEqual(256 * 1024)
})
it("uploads corrupt declared raster input without thumbnail or dimensions", async () => {
@@ -1571,7 +1571,7 @@ describe("message attachment upload", () => {
const path = await import("node:path")
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-corrupt-large-image-"))
const file = path.join(dir, "corrupt.png")
- fs.writeFileSync(file, new Uint8Array(512 * 1024 + 1))
+ fs.writeFileSync(file, new Uint8Array(256 * 1024 + 1))
const uploadSpy = vi.fn()
setApiForTesting(stubApi({ attachmentUpload: uploadSpy }))
try {
diff --git a/src/shared/src/constants/community.test.ts b/src/shared/src/constants/community.test.ts
index 469ac4dc5..e74abed0c 100644
--- a/src/shared/src/constants/community.test.ts
+++ b/src/shared/src/constants/community.test.ts
@@ -13,9 +13,9 @@ import {
} from "./community"
describe("Community attachment thumbnail constants", () => {
- it("locks the 1024px and 512 KiB policy through both export surfaces", () => {
- expect(MAX_ATTACHMENT_THUMBNAIL_EDGE_PX).toBe(1024)
- expect(MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES).toBe(512 * 1024)
+ it("locks the 720px and 256 KiB policy through both export surfaces", () => {
+ expect(MAX_ATTACHMENT_THUMBNAIL_EDGE_PX).toBe(720)
+ expect(MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES).toBe(256 * 1024)
expect(alook.MAX_ATTACHMENT_THUMBNAIL_EDGE_PX).toBe(MAX_ATTACHMENT_THUMBNAIL_EDGE_PX)
expect(alook.MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES).toBe(MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES)
})
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index 4f6b2658d..fefabd31e 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -27,8 +27,8 @@ export const MAX_EMOJI_BYTES = 32
// Attachments / uploads
export const MAX_ATTACHMENTS_PER_MESSAGE = 10
export const MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024 // 25 MB
-export const MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 1024
-export const MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 512 * 1024 // 512 KiB
+export const MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 720
+export const MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 256 * 1024 // 256 KiB
export const MAX_SERVER_ICON_SIZE_BYTES = 5 * 1024 * 1024 // 5 MB
export const ALLOWED_ICON_MIME_TYPES = [
"image/png",
diff --git a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
index 6bf9c81ba..de2ed7941 100644
--- a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
@@ -66,7 +66,6 @@ vi.mock("@/components/community/messages/message-context-sheet", () => ({
}))
vi.mock("@alook/shared", async (importOriginal) => ({ ...await importOriginal<typeof import("@alook/shared")>(),
deriveThreadName: () => "thread",
- MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES: 512 * 1024,
}))
vi.mock("@/stores/community", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/stores/community")>();
diff --git a/src/web/src/components/community/messages/attachment-layout.ts b/src/web/src/components/community/messages/attachment-layout.ts
index c0ab3da1a..d349ead8b 100644
--- a/src/web/src/components/community/messages/attachment-layout.ts
+++ b/src/web/src/components/community/messages/attachment-layout.ts
@@ -10,12 +10,13 @@ export function attachmentImageFrameStyle(
height: number | undefined,
): { width: string; aspectRatio: string } {
if (!width || !height || width <= 0 || height <= 0) {
- return { width: "min(100%, 300px)", aspectRatio: "4/3" }
+ return {
+ width: "min(100%, calc(var(--attachment-image-max-height, 200px) * 4 / 3))",
+ aspectRatio: "4/3",
+ }
}
- const constrainedWidth = Math.min(width, 300 * width / height)
- const roundedWidth = Math.round(constrainedWidth * 1000) / 1000
return {
- width: `min(100%, ${roundedWidth}px)`,
+ width: `min(100%, ${width}px, calc(var(--attachment-image-max-height, 200px) * ${width} / ${height}))`,
aspectRatio: `${width}/${height}`,
}
}
diff --git a/src/web/src/components/community/messages/image-lightbox-layout.test.ts b/src/web/src/components/community/messages/image-lightbox-layout.test.ts
index 61c4970ba..e4567f45e 100644
--- a/src/web/src/components/community/messages/image-lightbox-layout.test.ts
+++ b/src/web/src/components/community/messages/image-lightbox-layout.test.ts
@@ -12,31 +12,35 @@ describe("image lightbox layout", () => {
{ name: "portrait within bounds", image: { width: 396, height: 702 }, expected: { width: 396, height: 702 } },
{ name: "small image is not enlarged", image: { width: 80, height: 40 }, expected: { width: 80, height: 40 } },
{ name: "width cap", image: { width: 2000, height: 1000 }, expected: { width: 900, height: 450 } },
- { name: "height cap", image: { width: 1000, height: 2000 }, expected: { width: 382.5, height: 765 } },
+ { name: "height cap", image: { width: 1000, height: 2000 }, expected: { width: 378, height: 756 } },
])("fits $name", ({ image, expected }) => {
expect(fitImageToViewport(image, { width: 1000, height: 900 })).toEqual(expected)
})
it("uses a capped square fallback while legacy dimensions are unknown", () => {
expect(fallbackPreviewSize({ width: 390, height: 844 })).toEqual({ width: 200, height: 200 })
- expect(fallbackPreviewSize({ width: 120, height: 100 })).toEqual({ width: 85, height: 85 })
+ expect(fallbackPreviewSize({ width: 120, height: 100 })).toEqual({ width: 1, height: 1 })
})
it("uses live viewport CSS without upscaling or a JavaScript viewport snapshot", () => {
expect(previewFrameStyle({ width: 1200, height: 630 })).toEqual({
- width: "min(1200px, 90vw, 161.904762vh)",
+ width: "min(1200px, 90vw, 161.904762vh, calc(max(1px, calc(100vh - 144px)) * 1.904762))",
aspectRatio: "1200 / 630",
})
expect(previewFrameStyle({ width: 80, height: 40 })).toEqual({
- width: "min(80px, 90vw, 170vh)",
+ width: "min(80px, 90vw, 170vh, calc(max(1px, calc(100vh - 144px)) * 2))",
aspectRatio: "80 / 40",
})
expect(previewFrameStyle()).toEqual({
- width: "min(200px, 90vw, 85vh)",
+ width: "min(200px, 90vw, 85vh, max(1px, calc(100vh - 144px)))",
aspectRatio: "1 / 1",
})
})
+ it("reserves space for the controls above a tall image in landscape orientation", () => {
+ expect(fitImageToViewport({ width: 450, height: 800 }, { width: 844, height: 390 })).toEqual({ width: 138.375, height: 246 })
+ })
+
it("rejects incomplete or invalid dimensions", () => {
expect(validImageDimensions(640, 480)).toEqual({ width: 640, height: 480 })
expect(validImageDimensions(undefined, 480)).toBeUndefined()
diff --git a/src/web/src/components/community/messages/image-lightbox-layout.ts b/src/web/src/components/community/messages/image-lightbox-layout.ts
index 8904f7b88..5f38d3e4f 100644
--- a/src/web/src/components/community/messages/image-lightbox-layout.ts
+++ b/src/web/src/components/community/messages/image-lightbox-layout.ts
@@ -10,6 +10,7 @@ export type PreviewFrameStyle = {
const DEFAULT_PREVIEW_EDGE = 200
const PREVIEW_MAX_WIDTH_RATIO = 0.9
const PREVIEW_MAX_HEIGHT_RATIO = 0.85
+const PREVIEW_VERTICAL_MARGIN_PX = 144
function formatCssNumber(value: number): string {
return Number(value.toFixed(6)).toString()
@@ -33,7 +34,7 @@ export function fitImageToViewport(
viewport: ViewportDimensions,
): ImageDimensions {
const maxWidth = Math.max(1, viewport.width * PREVIEW_MAX_WIDTH_RATIO)
- const maxHeight = Math.max(1, viewport.height * PREVIEW_MAX_HEIGHT_RATIO)
+ const maxHeight = Math.max(1, Math.min(viewport.height * PREVIEW_MAX_HEIGHT_RATIO, viewport.height - PREVIEW_VERTICAL_MARGIN_PX))
const scale = Math.min(1, maxWidth / image.width, maxHeight / image.height)
return {
@@ -46,7 +47,7 @@ export function fallbackPreviewSize(viewport: ViewportDimensions): ImageDimensio
const edge = Math.min(
DEFAULT_PREVIEW_EDGE,
Math.max(1, viewport.width * PREVIEW_MAX_WIDTH_RATIO),
- Math.max(1, viewport.height * PREVIEW_MAX_HEIGHT_RATIO),
+ Math.max(1, Math.min(viewport.height * PREVIEW_MAX_HEIGHT_RATIO, viewport.height - PREVIEW_VERTICAL_MARGIN_PX)),
)
return { width: edge, height: edge }
}
@@ -59,14 +60,14 @@ export function fallbackPreviewSize(viewport: ViewportDimensions): ImageDimensio
export function previewFrameStyle(dimensions?: ImageDimensions): PreviewFrameStyle {
if (!dimensions) {
return {
- width: `min(${DEFAULT_PREVIEW_EDGE}px, ${PREVIEW_MAX_WIDTH_RATIO * 100}vw, ${PREVIEW_MAX_HEIGHT_RATIO * 100}vh)`,
+ width: `min(${DEFAULT_PREVIEW_EDGE}px, ${PREVIEW_MAX_WIDTH_RATIO * 100}vw, ${PREVIEW_MAX_HEIGHT_RATIO * 100}vh, max(1px, calc(100vh - ${PREVIEW_VERTICAL_MARGIN_PX}px)))`,
aspectRatio: "1 / 1",
}
}
const heightLimitedWidth = PREVIEW_MAX_HEIGHT_RATIO * 100 * (dimensions.width / dimensions.height)
return {
- width: `min(${formatCssNumber(dimensions.width)}px, ${PREVIEW_MAX_WIDTH_RATIO * 100}vw, ${formatCssNumber(heightLimitedWidth)}vh)`,
+ width: `min(${formatCssNumber(dimensions.width)}px, ${PREVIEW_MAX_WIDTH_RATIO * 100}vw, ${formatCssNumber(heightLimitedWidth)}vh, calc(max(1px, calc(100vh - ${PREVIEW_VERTICAL_MARGIN_PX}px)) * ${formatCssNumber(dimensions.width / dimensions.height)}))`,
aspectRatio: `${formatCssNumber(dimensions.width)} / ${formatCssNumber(dimensions.height)}`,
}
}
diff --git a/src/web/src/components/community/messages/image-lightbox-zoom.ts b/src/web/src/components/community/messages/image-lightbox-zoom.ts
new file mode 100644
index 000000000..bb459a7be
--- /dev/null
+++ b/src/web/src/components/community/messages/image-lightbox-zoom.ts
@@ -0,0 +1,165 @@
+"use client"
+
+import { useAtom, useCreateAtom } from "@tanstack/react-store"
+import { useCallback, useEffect, useRef, type KeyboardEvent, type MouseEvent, type PointerEvent } from "react"
+
+export type ImageView = { scale: number; x: number; y: number }
+type Point = { x: number; y: number }
+type Bounds = { width: number; height: number }
+const FIT_VIEW: ImageView = { scale: 1, x: 0, y: 0 }
+const MAX_ZOOM = 8
+
+function constrain(view: ImageView, bounds: Bounds): ImageView {
+ const scale = Math.max(1, Math.min(MAX_ZOOM, view.scale))
+ const maxX = bounds.width * (scale - 1) / 2
+ const maxY = bounds.height * (scale - 1) / 2
+ return {
+ scale,
+ x: Math.max(-maxX, Math.min(maxX, view.x)),
+ y: Math.max(-maxY, Math.min(maxY, view.y)),
+ }
+}
+
+function zoomAt(view: ImageView, scale: number, point: Point, bounds: Bounds): ImageView {
+ const nextScale = Math.max(1, Math.min(MAX_ZOOM, scale))
+ const ratio = nextScale / view.scale
+ return constrain({
+ scale: nextScale,
+ x: point.x - (point.x - view.x) * ratio,
+ y: point.y - (point.y - view.y) * ratio,
+ }, bounds)
+}
+
+function midpoint(points: Point[]): Point {
+ return points.length === 1 ? points[0] : {
+ x: (points[0].x + points[1].x) / 2,
+ y: (points[0].y + points[1].y) / 2,
+ }
+}
+
+function distance(points: Point[]): number {
+ return Math.hypot(points[1].x - points[0].x, points[1].y - points[0].y)
+}
+
+export function useImageLightboxZoom(enabled: boolean) {
+ const frameRef = useRef<HTMLDivElement>(null)
+ const pointers = useRef(new Map<number, Point>())
+ const [view, setView] = useAtom(useCreateAtom<ImageView>(FIT_VIEW))
+ const currentView = useRef(FIT_VIEW)
+
+ const apply = useCallback((next: ImageView) => {
+ const bounds = frameRef.current?.getBoundingClientRect()
+ const constrained = bounds ? constrain(next, bounds) : FIT_VIEW
+ currentView.current = constrained
+ setView(constrained)
+ }, [setView])
+
+ const reset = useCallback(() => {
+ pointers.current.clear()
+ apply(FIT_VIEW)
+ }, [apply])
+
+ const zoomTo = useCallback((scale: number, point?: Point) => {
+ const bounds = frameRef.current?.getBoundingClientRect()
+ if (!bounds) return
+ const anchor = point ? {
+ x: point.x - bounds.left - bounds.width / 2,
+ y: point.y - bounds.top - bounds.height / 2,
+ } : { x: 0, y: 0 }
+ apply(zoomAt(currentView.current, scale, anchor, bounds))
+ }, [apply])
+
+ useEffect(() => {
+ if (!enabled) {
+ reset()
+ return
+ }
+ const frame = frameRef.current
+ if (!frame) return
+ const wheel = (event: WheelEvent) => {
+ event.preventDefault()
+ const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? frame.clientHeight : 1
+ const factor = event.ctrlKey ? 0.005 : 0.002
+ zoomTo(currentView.current.scale * Math.exp(-event.deltaY * unit * factor), {
+ x: event.clientX, y: event.clientY,
+ })
+ }
+ const activePointers = pointers.current
+ frame.addEventListener("wheel", wheel, { passive: false })
+ const observer = typeof ResizeObserver === "function" ? new ResizeObserver(() => {
+ pointers.current.clear()
+ apply(currentView.current)
+ }) : undefined
+ observer?.observe(frame)
+ return () => {
+ frame.removeEventListener("wheel", wheel)
+ observer?.disconnect()
+ activePointers.clear()
+ }
+ }, [apply, enabled, reset, zoomTo])
+
+ const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
+ if (!enabled || event.button !== 0 || pointers.current.size >= 2) return
+ pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY })
+ event.currentTarget.setPointerCapture?.(event.pointerId)
+ }
+
+ const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
+ if (!pointers.current.has(event.pointerId)) return
+ const before = [...pointers.current.values()]
+ pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY })
+ const after = [...pointers.current.values()]
+ const oldMidpoint = midpoint(before)
+ const newMidpoint = midpoint(after)
+ const bounds = event.currentTarget.getBoundingClientRect()
+ const anchor = {
+ x: oldMidpoint.x - bounds.left - bounds.width / 2,
+ y: oldMidpoint.y - bounds.top - bounds.height / 2,
+ }
+ const ratio = before.length === 2 ? distance(after) / Math.max(1, distance(before)) : 1
+ const next = zoomAt(currentView.current, currentView.current.scale * ratio, anchor, bounds)
+ apply({ ...next, x: next.x + newMidpoint.x - oldMidpoint.x, y: next.y + newMidpoint.y - oldMidpoint.y })
+ }
+
+ const onPointerEnd = (event: PointerEvent<HTMLDivElement>) => {
+ pointers.current.delete(event.pointerId)
+ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId)
+ }
+ }
+
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (!enabled || event.ctrlKey || event.metaKey || event.altKey) return
+ if (event.key === "+" || event.key === "=") zoomTo(currentView.current.scale * 1.5)
+ else if (event.key === "-") zoomTo(currentView.current.scale / 1.5)
+ else if (event.key === "0") reset()
+ else if (event.key.startsWith("Arrow")) {
+ const next = currentView.current
+ apply({
+ ...next,
+ x: next.x + (event.key === "ArrowLeft" ? 40 : event.key === "ArrowRight" ? -40 : 0),
+ y: next.y + (event.key === "ArrowUp" ? 40 : event.key === "ArrowDown" ? -40 : 0),
+ })
+ } else return
+ event.preventDefault()
+ }
+
+ return {
+ frameRef,
+ view,
+ reset,
+ zoomIn: () => zoomTo(currentView.current.scale * 1.5),
+ zoomOut: () => zoomTo(currentView.current.scale / 1.5),
+ handlers: {
+ onPointerDown,
+ onPointerMove,
+ onPointerUp: onPointerEnd,
+ onPointerCancel: onPointerEnd,
+ onLostPointerCapture: onPointerEnd,
+ onKeyDown,
+ onDoubleClick: (event: MouseEvent<HTMLDivElement>) => {
+ if (enabled) zoomTo(currentView.current.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })
+ },
+ },
+ }
+}
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 9d49282b7..0e1ab9842 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
@@ -1,7 +1,7 @@
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { tid } from "@/lib/community/testids"
-import { act, fireEvent, render, type RenderResult } from "@/test/react-dom-harness"
+import { act, fireEvent, render, mockElementGeometry, type RenderResult } from "@/test/react-dom-harness"
vi.mock("@/components/ui/dialog", () => ({
Dialog: ({ children, onOpenChange }: {
@@ -91,7 +91,7 @@ describe("ImageLightbox", () => {
const original = image(renderer, tid.imageLightboxOriginal)
expect(previewFrameStyle({ width: 800, height: 450 })).toEqual({
- width: "min(800px, 90vw, 151.111111vh)",
+ width: "min(800px, 90vw, 151.111111vh, calc(max(1px, calc(100vh - 144px)) * 1.777778))",
aspectRatio: "800 / 450",
})
expect(frame.style.aspectRatio).toBe("800 / 450")
@@ -130,7 +130,7 @@ describe("ImageLightbox", () => {
"opacity-0",
)
expect(previewFrameStyle({ width: 800, height: 450 })).toEqual({
- width: "min(800px, 90vw, 151.111111vh)",
+ width: "min(800px, 90vw, 151.111111vh, calc(max(1px, calc(100vh - 144px)) * 1.777778))",
aspectRatio: "800 / 450",
})
})
@@ -172,7 +172,7 @@ describe("ImageLightbox", () => {
})
const frame = () => renderer.getByTestId(tid.imageLightbox)
- expect(previewFrameStyle(undefined)).toEqual({ width: "min(200px, 90vw, 85vh)", aspectRatio: "1 / 1" })
+ expect(previewFrameStyle(undefined)).toEqual({ width: "min(200px, 90vw, 85vh, max(1px, calc(100vh - 144px)))", aspectRatio: "1 / 1" })
expect(frame().style.aspectRatio).toBe("1 / 1")
await loadThumbnail(renderer, 200, 100)
expect(frame().style.aspectRatio).toBe("1 / 1")
@@ -188,7 +188,7 @@ describe("ImageLightbox", () => {
await decodePromise
})
expect(previewFrameStyle({ width: 1000, height: 500 })).toEqual({
- width: "min(1000px, 90vw, 170vh)",
+ width: "min(1000px, 90vw, 170vh, calc(max(1px, calc(100vh - 144px)) * 2))",
aspectRatio: "1000 / 500",
})
expect(frame().style.aspectRatio).toBe("1000 / 500")
@@ -250,7 +250,7 @@ describe("ImageLightbox", () => {
expect(renderer.getByTestId(tid.imageLightboxLoading))
.toHaveTextContent("Loading original image")
expect(previewFrameStyle(undefined)).toEqual({
- width: "min(200px, 90vw, 85vh)",
+ width: "min(200px, 90vw, 85vh, max(1px, calc(100vh - 144px)))",
aspectRatio: "1 / 1",
})
expect(renderer.getByTestId(tid.imageLightbox).style.aspectRatio).toBe("1 / 1")
@@ -344,4 +344,147 @@ describe("ImageLightbox", () => {
fireEvent.click(renderer.container.querySelector('[data-dialog-open-change="false"]')!)
expect(onClose).toHaveBeenCalledOnce()
})
+
+ async function readyPreview() {
+ const result = renderLightbox({ originalUrl: "/zoom-original", thumbnailUrl: "/zoom-thumbnail", name: "detail", width: 800, height: 600 })
+ const frame = result.renderer.getByTestId(tid.imageLightbox)
+ mockElementGeometry(frame, { left: 100, top: 100, width: 400, height: 300, clientWidth: 400, clientHeight: 300 })
+ await loadImage(image(result.renderer, tid.imageLightboxOriginal), 800, 600, () => Promise.resolve())
+ return { ...result, frame, original: image(result.renderer, tid.imageLightboxOriginal) }
+ }
+
+ function pointer(frame: HTMLElement, type: string, id: number, x: number, y: number, button = 0) {
+ const event = new MouseEvent(type, { bubbles: true, clientX: x, clientY: y, button })
+ Object.defineProperties(event, { pointerId: { value: id }, pointerType: { value: "touch" } })
+ fireEvent(frame, event)
+ }
+
+ it("zooms around the wheel pointer without moving the frame or zooming the page", async () => {
+ const { frame, original, renderer } = await readyPreview()
+ const frameStyle = frame.getAttribute("style")
+ const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, clientX: 400, clientY: 250, deltaY: -Math.log(2) / 0.002 })
+ fireEvent(frame, wheel)
+ expect(wheel.defaultPrevented).toBe(true)
+ expect(Number(frame.dataset.zoomScale)).toBeCloseTo(2)
+ expect(original.style.transform).toBe("translate(-100px, 0px) scale(2)")
+ expect(image(renderer, tid.imageLightboxThumbnail).style.transform).toBe(original.style.transform)
+ expect(frame.getAttribute("style")).toBe(frameStyle)
+ expect(original).toHaveAttribute("draggable", "false")
+ expect(frame.style.touchAction).toBe("none")
+ })
+
+ it("clamps mouse dragging to the enlarged image and ignores a right-button drag", async () => {
+ const { frame, original, renderer } = await readyPreview()
+ const captures = new Set<number>()
+ const release = vi.fn((id: number) => captures.delete(id))
+ Object.assign(frame, {
+ setPointerCapture: (id: number) => captures.add(id),
+ hasPointerCapture: (id: number) => captures.has(id),
+ releasePointerCapture: release,
+ })
+ fireEvent.doubleClick(frame, { clientX: 300, clientY: 250 })
+ pointer(frame, "pointerdown", 1, 300, 250)
+ pointer(frame, "pointermove", 1, 2000, 1800)
+ expect(original.style.transform).toBe("translate(200px, 150px) scale(2)")
+ pointer(frame, "pointerup", 1, 2000, 1800)
+ expect(release).toHaveBeenCalledWith(1)
+ expect(captures.size).toBe(0)
+ pointer(frame, "pointermove", 1, 100, 100)
+ expect(original.style.transform).toBe("translate(200px, 150px) scale(2)")
+ fireEvent.click(renderer.getByRole("button", { name: "Fit image" }))
+ pointer(frame, "pointerdown", 2, 300, 250, 2)
+ pointer(frame, "pointermove", 2, 500, 400, 2)
+ expect(original.style.transform).toBe("translate(0px, 0px) scale(1)")
+ })
+
+ it("pinches with two pointers, continues panning with one, and stops on cancellation", async () => {
+ const { frame, original } = await readyPreview()
+ pointer(frame, "pointerdown", 1, 250, 250)
+ pointer(frame, "pointerdown", 2, 350, 250)
+ pointer(frame, "pointermove", 1, 200, 250)
+ pointer(frame, "pointermove", 2, 400, 250)
+ expect(Number(frame.dataset.zoomScale)).toBeCloseTo(2)
+ expect(original.style.transform).toBe("translate(0px, 0px) scale(2)")
+ pointer(frame, "pointerup", 1, 200, 250)
+ pointer(frame, "pointermove", 2, 450, 280)
+ expect(original.style.transform).toBe("translate(50px, 30px) scale(2)")
+ pointer(frame, "pointercancel", 2, 450, 280)
+ pointer(frame, "pointermove", 2, 2000, 2000)
+ expect(original.style.transform).toBe("translate(50px, 30px) scale(2)")
+ })
+
+ it("bounds wheel and trackpad zoom and keeps fit and close accessible", async () => {
+ const { frame, renderer, onClose } = await readyPreview()
+ fireEvent.wheel(frame, { cancelable: true, deltaY: -100000, ctrlKey: true })
+ expect(frame.dataset.zoomScale).toBe("8")
+ expect(renderer.getByRole("button", { name: "Zoom in" })).toBeDisabled()
+ expect(renderer.getByRole("button", { name: "Zoom out" })).toBeEnabled()
+ fireEvent.click(renderer.getByRole("button", { name: "Fit image" }))
+ expect(frame.dataset.zoomScale).toBe("1")
+ expect(renderer.getByRole("button", { name: "Zoom out" })).toBeDisabled()
+ fireEvent.click(renderer.getByRole("button", { name: "Zoom in" }))
+ expect(frame.dataset.zoomScale).toBe("1.5")
+ fireEvent.click(renderer.getByRole("button", { name: "Zoom out" }))
+ expect(frame.dataset.zoomScale).toBe("1")
+ fireEvent.click(renderer.getByRole("button", { name: "Close image preview" }))
+ expect(onClose).toHaveBeenCalledOnce()
+ })
+
+ it("supports keyboard zoom and pan, double-click reset, and a fresh view for a new image", async () => {
+ const { frame, original, renderer } = await readyPreview()
+ fireEvent.keyDown(frame, { key: "+" })
+ fireEvent.keyDown(frame, { key: "ArrowRight" })
+ expect(original.style.transform).toBe("translate(-40px, 0px) scale(1.5)")
+ const tab = new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true })
+ fireEvent(frame, tab)
+ expect(tab.defaultPrevented).toBe(false)
+ expect(original.style.transform).toBe("translate(-40px, 0px) scale(1.5)")
+ fireEvent.doubleClick(frame)
+ expect(frame.dataset.zoomScale).toBe("1")
+ fireEvent.keyDown(frame, { key: "+" })
+ fireEvent.keyDown(frame, { key: "0" })
+ expect(frame.dataset.zoomScale).toBe("1")
+ fireEvent.keyDown(frame, { key: "+" })
+ renderer.rerender(React.createElement(ImageLightbox, { image: { originalUrl: "/next-original", name: "next", width: 800, height: 600 }, onClose: vi.fn() }))
+ expect(renderer.getByTestId(tid.imageLightbox).dataset.zoomScale).toBe("1")
+ })
+
+ it("does not intercept wheel or enable zoom until the original is decoded", async () => {
+ const { renderer } = renderLightbox({ originalUrl: "/pending-original", name: "pending" })
+ const frame = renderer.getByTestId(tid.imageLightbox)
+ const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -100 })
+ fireEvent(frame, wheel)
+ expect(wheel.defaultPrevented).toBe(false)
+ expect(renderer.getByRole("button", { name: "Zoom in" })).toBeDisabled()
+ expect(renderer.getByRole("button", { name: "Close image preview" })).toBeEnabled()
+ fireEvent.error(image(renderer, tid.imageLightboxOriginal))
+ expect(renderer.getByRole("button", { name: "Zoom in" })).toBeDisabled()
+ expect(renderer.getByTestId(tid.imageLightboxRetry)).toBeVisible()
+ })
+
+
+ it("reclamps a panned image on resize, cancels its drag, and disconnects on close", async () => {
+ let resize!: ResizeObserverCallback
+ const disconnect = vi.fn()
+ vi.stubGlobal("ResizeObserver", class {
+ constructor(callback: ResizeObserverCallback) { resize = callback }
+ observe = vi.fn()
+ disconnect = disconnect
+ })
+ const { frame, original, renderer } = await readyPreview()
+ fireEvent.doubleClick(frame, { clientX: 300, clientY: 250 })
+ pointer(frame, "pointerdown", 1, 300, 250)
+ pointer(frame, "pointermove", 1, 1000, 1000)
+ mockElementGeometry(frame, { left: 100, top: 100, width: 200, height: 150 })
+ act(() => resize([], {} as ResizeObserver))
+ expect(original.style.transform).toBe("translate(100px, 75px) scale(2)")
+ pointer(frame, "pointermove", 1, 1200, 1200)
+ expect(original.style.transform).toBe("translate(100px, 75px) scale(2)")
+ renderer.unmount()
+ expect(disconnect).toHaveBeenCalledOnce()
+ const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -100 })
+ fireEvent(frame, wheel)
+ expect(wheel.defaultPrevented).toBe(false)
+ })
+
})
diff --git a/src/web/src/components/community/messages/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsx
index 7b455acdb..84b8f430b 100644
--- a/src/web/src/components/community/messages/image-lightbox.tsx
+++ b/src/web/src/components/community/messages/image-lightbox.tsx
@@ -4,6 +4,8 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useEffect, useMemo } from "react"
import { Dialog, DialogContent } from "@/components/ui/dialog"
+import { Button } from "@/components/ui/button"
+import { MinusIcon, PlusIcon, RotateCcwIcon, XIcon } from "lucide-react"
import type { ImagePreview } from "@/lib/community/models/message"
import { tid } from "@/lib/community/testids"
import {
@@ -12,8 +14,9 @@ import {
validImageDimensions,
} from "./image-lightbox-layout"
import { useRemoteImageAttempt } from "@/components/remote-image/remote-image-attempt"
+import { useImageLightboxZoom } from "./image-lightbox-zoom"
-function PreviewFrame({ image }: { image: ImagePreview }) {
+function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () => void }) {
const knownDimensions = useMemo(
() => validImageDimensions(image.width, image.height),
[image.height, image.width],
@@ -41,6 +44,8 @@ function PreviewFrame({ image }: { image: ImagePreview }) {
const frameStyle = previewFrameStyle(dimensions)
const thumbnailReady = !!image.thumbnailUrl && thumbnailStatus === "ready"
const originalReady = originalStatus === "ready" && revealedAttempt === originalAttempt
+ const { frameRef, view, reset, zoomIn, zoomOut, handlers } = useImageLightboxZoom(originalReady)
+ const imageTransform = { transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }
useEffect(() => {
if (originalStatus !== "ready" || !originalImage) return
@@ -61,10 +66,16 @@ function PreviewFrame({ image }: { image: ImagePreview }) {
return (
<div className="relative w-fit">
<div
+ ref={frameRef}
data-testid={tid.imageLightbox}
+ data-zoom-scale={view.scale}
data-native-context-menu="true"
- className="relative overflow-hidden rounded-lg bg-background"
- style={frameStyle}
+ role="region"
+ aria-label="Image preview. Use plus and minus to zoom, arrow keys to pan, and zero to fit."
+ tabIndex={originalReady ? 0 : -1}
+ className={`relative select-none overflow-hidden rounded-lg bg-background ${view.scale > 1 ? "cursor-grab active:cursor-grabbing" : "cursor-default"}`}
+ style={{ ...frameStyle, touchAction: originalReady ? "none" : undefined }}
+ {...handlers}
>
{image.thumbnailUrl && (
<img
@@ -75,6 +86,8 @@ function PreviewFrame({ image }: { image: ImagePreview }) {
data-remote-image-state={thumbnailStatus}
src={image.thumbnailUrl}
alt={image.name}
+ draggable={false}
+ 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"}`}
@@ -98,12 +111,25 @@ function PreviewFrame({ image }: { image: ImagePreview }) {
data-remote-image-state={originalStatus}
src={image.originalUrl}
alt={image.name}
+ draggable={false}
+ 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"}`}
/>
)}
</div>
+ <div
+ role="toolbar"
+ aria-label="Image controls"
+ className="absolute left-1/2 z-20 flex -translate-x-1/2 items-center gap-1 rounded-lg border border-border bg-background p-1"
+ style={{ top: "calc(50% - 50vh + 12px)" }}
+ >
+ <Button variant="ghost" size="icon" className="size-11 sm:size-9" aria-label="Zoom out" title="Zoom out" disabled={!originalReady || view.scale <= 1} onClick={zoomOut}><MinusIcon /></Button>
+ <Button variant="ghost" size="icon" className="size-11 sm:size-9" aria-label="Fit image" title="Fit image" disabled={!originalReady || view.scale === 1} onClick={reset}><RotateCcwIcon /></Button>
+ <Button variant="ghost" size="icon" className="size-11 sm:size-9" aria-label="Zoom in" title="Zoom in" disabled={!originalReady || view.scale >= 8} onClick={zoomIn}><PlusIcon /></Button>
+ <Button variant="ghost" size="icon" className="size-11 sm:size-9" aria-label="Close image preview" title="Close" onClick={onClose}><XIcon /></Button>
+ </div>
{originalStatus === "error" && (
<div
data-testid={tid.imageLightboxError}
@@ -129,12 +155,14 @@ export function ImageLightbox({ image, onClose }: { image: ImagePreview; onClose
return (
<Dialog open onOpenChange={(open) => { if (!open) onClose() }}>
<DialogContent
+ aria-label={image.name}
className="flex max-h-[90vh] w-auto items-center justify-center border-none bg-transparent p-0 shadow-none sm:max-w-none"
showCloseButton={false}
>
<PreviewFrame
key={`${image.originalUrl}\u0000${image.thumbnailUrl ?? ""}\u0000${image.width ?? ""}\u0000${image.height ?? ""}`}
image={image}
+ onClose={onClose}
/>
</DialogContent>
</Dialog>
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 b0f3d8bf7..8a07f19f5 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
@@ -1668,8 +1668,9 @@ describe("Message image attachment layout", () => {
const frame = renderer!.root.findByProps({ "data-remote-image-frame": true })
expect(frame.props.className).toContain("relative")
expect(frame.props.className).toContain("max-w-full")
+ expect(frame.props.className).toContain("sm:[--attachment-image-max-height:240px]")
expect(frame.props.style).toEqual({
- width: "min(100%, 169.231px)",
+ width: "min(100%, 396px, calc(var(--attachment-image-max-height, 200px) * 396 / 702))",
aspectRatio: "396/702",
})
})
diff --git a/src/web/src/components/community/messages/message.test.ts b/src/web/src/components/community/messages/message.test.ts
index 3f1c7ccc2..e2fb45e4d 100644
--- a/src/web/src/components/community/messages/message.test.ts
+++ b/src/web/src/components/community/messages/message.test.ts
@@ -24,34 +24,34 @@ describe("attachmentAspectRatio", () => {
})
describe("attachmentImageFrameStyle", () => {
- it("reserves a 300px square for a larger square image", () => {
+ it("reserves a responsive height-limited square for a larger square image", () => {
expect(attachmentImageFrameStyle(512, 512)).toEqual({
- width: "min(100%, 300px)",
+ width: "min(100%, 512px, calc(var(--attachment-image-max-height, 200px) * 512 / 512))",
aspectRatio: "512/512",
})
})
it("caps a portrait by height and preserves its ratio", () => {
expect(attachmentImageFrameStyle(396, 702)).toEqual({
- width: "min(100%, 169.231px)",
+ width: "min(100%, 396px, calc(var(--attachment-image-max-height, 200px) * 396 / 702))",
aspectRatio: "396/702",
})
})
it("keeps a small known-size image at intrinsic width", () => {
expect(attachmentImageFrameStyle(120, 80)).toEqual({
- width: "min(100%, 120px)",
+ width: "min(100%, 120px, calc(var(--attachment-image-max-height, 200px) * 120 / 80))",
aspectRatio: "120/80",
})
})
it("reserves a safe fixed frame for legacy incomplete dimensions", () => {
expect(attachmentImageFrameStyle(undefined, 80)).toEqual({
- width: "min(100%, 300px)",
+ width: "min(100%, calc(var(--attachment-image-max-height, 200px) * 4 / 3))",
aspectRatio: "4/3",
})
expect(attachmentImageFrameStyle(120, undefined)).toEqual({
- width: "min(100%, 300px)",
+ width: "min(100%, calc(var(--attachment-image-max-height, 200px) * 4 / 3))",
aspectRatio: "4/3",
})
})
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index 5be80b4c5..da19ef4ba 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -724,7 +724,7 @@ function MessageImpl({
width: a.width,
height: a.height,
})}
- frameClassName="block max-w-full rounded-lg border border-border transition-colors hover:border-primary/40"
+ frameClassName="block max-w-full rounded-lg border border-border [--attachment-image-max-height:200px] transition-colors hover:border-primary/40 sm:[--attachment-image-max-height:240px]"
frameStyle={frameStyle}
imageClassName="block rounded-lg object-contain"
errorLabel="Attachment failed to load"
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 2b169ddae..f09a635aa 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
@@ -135,8 +135,9 @@ describe("ThreadOpener image attachment layout", () => {
const frame = renderer!.container.querySelector<HTMLElement>('[data-remote-image-frame="true"]')!
expect(frame.className).toContain("relative")
expect(frame.className).toContain("max-w-full")
+ expect(frame.className).toContain("sm:[--attachment-image-max-height:240px]")
expect(attachmentImageFrameStyle(396, 702)).toEqual({
- width: "min(100%, 169.231px)",
+ width: "min(100%, 396px, calc(var(--attachment-image-max-height, 200px) * 396 / 702))",
aspectRatio: "396/702",
})
expect(frame.style.aspectRatio).toBe("396/702")
diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsx
index 6cc3ee029..2e3a1d78b 100644
--- a/src/web/src/components/community/messages/thread-opener.tsx
+++ b/src/web/src/components/community/messages/thread-opener.tsx
@@ -183,7 +183,7 @@ export function ThreadOpener({
width: a.width,
height: a.height,
})}
- frameClassName="block max-w-full rounded-lg border border-border transition-colors hover:border-primary/40"
+ frameClassName="block max-w-full rounded-lg border border-border [--attachment-image-max-height:200px] transition-colors hover:border-primary/40 sm:[--attachment-image-max-height:240px]"
frameStyle={frameStyle}
imageClassName="block rounded-lg object-contain"
errorLabel="Attachment failed to load"
diff --git a/src/web/src/hooks/community/mutations/uploads.test.ts b/src/web/src/hooks/community/mutations/uploads.test.ts
index 14e806bed..91ad95aab 100644
--- a/src/web/src/hooks/community/mutations/uploads.test.ts
+++ b/src/web/src/hooks/community/mutations/uploads.test.ts
@@ -68,10 +68,10 @@ describe("appendGeneratedThumbnail", () => {
expect((form.get("thumbnail") as File).type).toBe("image/jpeg")
})
- it("rejects a generated thumbnail over 512 KiB instead of silently dropping it", () => {
+ it("rejects a generated thumbnail over 256 KiB instead of silently dropping it", () => {
const form = new FormData()
- const blob = new Blob([new Uint8Array(512 * 1024 + 1)], { type: "image/jpeg" })
- expect(() => appendGeneratedThumbnail(form, "image/png", blob)).toThrow("512 KiB")
+ const blob = new Blob([new Uint8Array(256 * 1024 + 1)], { type: "image/jpeg" })
+ expect(() => appendGeneratedThumbnail(form, "image/png", blob)).toThrow("256 KiB")
expect(form.has("thumbnail")).toBe(false)
})
diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.ts
index e0b415191..dde1f57b1 100644
--- a/src/web/src/lib/community/upload.test.ts
+++ b/src/web/src/lib/community/upload.test.ts
@@ -183,7 +183,7 @@ describe("handleAttachmentUpload", () => {
it("accepts an original-only image at the exact policy boundaries", async () => {
const put = vi.fn().mockResolvedValue(undefined)
const res = await handleAttachmentUpload(
- reqWithUpload(fakeFile("edge.png", "image/png", 512 * 1024), null, "1024", "768"),
+ reqWithUpload(fakeFile("edge.png", "image/png", 256 * 1024), null, "720", "540"),
envWithR2(put), "channel", "c1", USER_TAG,
)
@@ -194,9 +194,9 @@ describe("handleAttachmentUpload", () => {
})
it.each([
- ["byte size", fakeFile("large.png", "image/png", 512 * 1024 + 1), "640", "480"],
- ["width", fakeFile("wide.png", "image/png", 10), "1025", "480"],
- ["height", fakeFile("tall.png", "image/png", 10), "480", "1025"],
+ ["byte size", fakeFile("large.png", "image/png", 256 * 1024 + 1), "640", "480"],
+ ["width", fakeFile("wide.png", "image/png", 10), "721", "480"],
+ ["height", fakeFile("tall.png", "image/png", 10), "480", "721"],
])("rejects a missing required thumbnail proved by %s before either R2 put", async (_label, file, width, height) => {
const put = vi.fn()
const res = await handleAttachmentUpload(
@@ -306,10 +306,10 @@ describe("handleAttachmentUpload", () => {
expect(put).toHaveBeenCalledTimes(2)
})
- it("rejects a JPEG thumbnail over 1024px before either R2 put", async () => {
+ it("rejects a JPEG thumbnail over 720px before either R2 put", async () => {
const put = vi.fn()
const res = await handleAttachmentUpload(
- reqWithUpload(fakeFile("hi.png", "image/png", 10), fakeJpegFile(1025, 512)),
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), fakeJpegFile(721, 512)),
envWithR2(put), "channel", "c1", USER_TAG,
)
@@ -333,7 +333,7 @@ describe("handleAttachmentUpload", () => {
{
label: "oversized thumbnail",
file: fakeFile("photo.png", "image/png", 10),
- thumbnail: { ...fakeFile("thumbnail.jpg", "image/jpeg", 512 * 1024 + 1), arrayBuffer: async () => new ArrayBuffer(0) },
+ thumbnail: { ...fakeFile("thumbnail.jpg", "image/jpeg", 256 * 1024 + 1), arrayBuffer: async () => new ArrayBuffer(0) },
},
])("rejects $label before either R2 put", async ({ file, thumbnail }) => {
const put = vi.fn()
diff --git a/src/web/src/lib/image-thumbnail.test.ts b/src/web/src/lib/image-thumbnail.test.ts
index b06af56d5..fd9b5b245 100644
--- a/src/web/src/lib/image-thumbnail.test.ts
+++ b/src/web/src/lib/image-thumbnail.test.ts
@@ -119,36 +119,36 @@ describe("generateThumbnail", () => {
expect(result).toBeNull()
})
- it("uses the original at the exact 1024px and 512 KiB boundaries", async () => {
+ it("uses the original at the exact 720px and 256 KiB boundaries", async () => {
const canvases = stubBrowserImageApis()
- FakeImage.nextWidth = 1024
- FakeImage.nextHeight = 768
- const file = new File([new Uint8Array(512 * 1024)], "photo.png", { type: "image/png" })
+ FakeImage.nextWidth = 720
+ FakeImage.nextHeight = 540
+ const file = new File([new Uint8Array(256 * 1024)], "photo.png", { type: "image/png" })
const result = await prepareCommunityImage(file)
- expect(result).toEqual({ blob: null, width: 1024, height: 768 })
+ expect(result).toEqual({ blob: null, width: 720, height: 540 })
expect(canvases).toHaveLength(0)
})
- it("generates a 1024px preview when dimensions exceed the edge limit", async () => {
+ it("generates a 720px preview when dimensions exceed the edge limit", async () => {
const canvases = stubBrowserImageApis([100])
- FakeImage.nextWidth = 1025
+ FakeImage.nextWidth = 721
FakeImage.nextHeight = 512
const file = new File([new Uint8Array(100)], "photo.png", { type: "image/png" })
const result = await prepareCommunityImage(file)
expect(result?.blob?.size).toBe(100)
- expect(result).toMatchObject({ width: 1025, height: 512 })
- expect(canvases[0]).toMatchObject({ width: 1024, height: 512 })
+ expect(result).toMatchObject({ width: 721, height: 512 })
+ expect(canvases[0]).toMatchObject({ width: 720, height: 511 })
})
it("generates at original dimensions when only the byte limit is exceeded", async () => {
const canvases = stubBrowserImageApis([100])
FakeImage.nextWidth = 640
FakeImage.nextHeight = 480
- const file = new File([new Uint8Array(512 * 1024 + 1)], "photo.png", { type: "image/png" })
+ const file = new File([new Uint8Array(256 * 1024 + 1)], "photo.png", { type: "image/png" })
const result = await prepareCommunityImage(file)
@@ -157,7 +157,7 @@ describe("generateThumbnail", () => {
})
it("reduces dimensions after exhausting bounded quality attempts", async () => {
- const oversized = new Array(7).fill(512 * 1024 + 1)
+ const oversized = new Array(7).fill(256 * 1024 + 1)
const canvases = stubBrowserImageApis([...oversized, 256 * 1024])
FakeImage.nextWidth = 2048
FakeImage.nextHeight = 1024
@@ -167,13 +167,13 @@ describe("generateThumbnail", () => {
expect(result?.blob?.size).toBe(256 * 1024)
expect(canvases).toHaveLength(2)
- expect(canvases[0]).toMatchObject({ width: 1024, height: 512 })
- expect(canvases[1]).toMatchObject({ width: 870, height: 435 })
+ expect(canvases[0]).toMatchObject({ width: 720, height: 360 })
+ expect(canvases[1]).toMatchObject({ width: 612, height: 306 })
})
it("throws when a thumbnail is required but encoding cannot satisfy the cap", async () => {
- stubBrowserImageApis([512 * 1024 + 1])
- FakeImage.nextWidth = 1025
+ stubBrowserImageApis([256 * 1024 + 1])
+ FakeImage.nextWidth = 721
FakeImage.nextHeight = 512
const file = new File([new Uint8Array(100)], "photo.png", { type: "image/png" })
@@ -184,7 +184,7 @@ describe("generateThumbnail", () => {
stubBrowserImageApis()
FakeImage.nextShouldError = true
const file = new File(
- [new Uint8Array(512 * 1024 + 1)],
+ [new Uint8Array(256 * 1024 + 1)],
"corrupt.png",
{ type: "image/png" },
)
diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
index cb69e4083..337482016 100644
--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
@@ -242,6 +242,8 @@ test("image previews keep one frame through loading, decode, failure, retry, and
const landscapeListFrame = landscapeListImage.locator("xpath=ancestor::*[@data-remote-image-frame]")
await expect(landscapeListFrame).toHaveAttribute("data-remote-image-state", "pending")
const pendingListRect = await boundingRect(landscapeListFrame)
+ expect(pendingListRect.height).toBeCloseTo(240, 0)
+ expect(pendingListRect.width / pendingListRect.height).toBeCloseTo(800 / 450, 2)
await page.emulateMedia({ reducedMotion: "reduce" })
expect(await landscapeListFrame.locator("[data-remote-image-placeholder]").evaluate((element) => (
getComputedStyle(element).animationName
@@ -310,6 +312,35 @@ test("image previews keep one frame through loading, decode, failure, retry, and
const desktopLandscapeLoaded = await previewRects(page)
expectSameRect(desktopLandscapeLoaded.container, desktopLandscapeRestored.container)
await attachScreenshot(testInfo, "desktop-landscape-loaded", page)
+ const desktopZoomFrame = page.getByTestId(tid.imageLightbox)
+ await desktopZoomFrame.hover()
+ await page.mouse.wheel(0, -350)
+ await expect.poll(async () => Number(await desktopZoomFrame.getAttribute("data-zoom-scale"))).toBeGreaterThan(1)
+ expectSameRect(await boundingRect(desktopZoomFrame), desktopLandscapeLoaded.container)
+ const desktopZoomRect = await boundingRect(landscapeOriginal)
+ expect(desktopZoomRect.width).toBeGreaterThan(desktopLandscapeLoaded.original.width)
+ const beforeDrag = await landscapeOriginal.evaluate((element) => element.style.transform)
+ const desktopCenter = {
+ x: desktopLandscapeLoaded.container.x + desktopLandscapeLoaded.container.width / 2,
+ y: desktopLandscapeLoaded.container.y + desktopLandscapeLoaded.container.height / 2,
+ }
+ await page.mouse.move(desktopCenter.x, desktopCenter.y)
+ await page.mouse.down()
+ await page.mouse.move(desktopCenter.x + 70, desktopCenter.y + 40, { steps: 5 })
+ await page.mouse.up()
+ await expect.poll(() => landscapeOriginal.evaluate((element) => element.style.transform)).not.toBe(beforeDrag)
+ await attachScreenshot(testInfo, "desktop-original-zoomed", page)
+ await page.getByRole("button", { name: "Fit image", exact: true }).click()
+ await expect(desktopZoomFrame).toHaveAttribute("data-zoom-scale", "1")
+ await desktopZoomFrame.dblclick()
+ await expect(desktopZoomFrame).toHaveAttribute("data-zoom-scale", "2")
+ await desktopZoomFrame.dblclick()
+ await expect(desktopZoomFrame).toHaveAttribute("data-zoom-scale", "1")
+ await page.getByRole("button", { name: "Close image preview", exact: true }).click()
+ await expect(desktopZoomFrame).toHaveCount(0)
+ await landscapeButton.click()
+ await expect(desktopZoomFrame).toHaveAttribute("data-zoom-scale", "1")
+ await expect(landscapeOriginal).toHaveClass(/opacity-100/)
await page.keyboard.press("Escape")
await expect(page.getByTestId(tid.imageLightbox)).toHaveCount(0)
await page.unroute(`**${landscape.originalPath}`)
@@ -398,12 +429,17 @@ test("image previews keep one frame through loading, decode, failure, retry, and
})
expect(messagePostCount).toBe(4)
- const { page: mobilePage } = await asUser("alice")
+ const { page: mobilePage } = await asUser("alice", { hasTouch: true })
await mobilePage.setViewportSize({ width: 390, height: 844 })
await mobilePage.goto(channelUrl)
await mobilePage.waitForURL(new RegExp(`/c/channels/[^/]+/${channelId}$`), { waitUntil: "commit" })
await expect(mobilePage.getByTestId(tid.messageImage(landscape.messageId, 0)))
.toBeVisible({ timeout: 30_000 })
+ const mobilePortraitListFrame = mobilePage.getByTestId(tid.messageImage(portrait.messageId, 0))
+ .locator("xpath=ancestor::*[@data-remote-image-frame]")
+ const mobilePortraitListRect = await boundingRect(mobilePortraitListFrame)
+ expect(mobilePortraitListRect.height).toBeCloseTo(200, 0)
+ expect(mobilePortraitListRect.width / mobilePortraitListRect.height).toBeCloseTo(450 / 800, 2)
let releaseMobileLandscape!: () => void
const mobileLandscapeGate = new Promise<void>((resolve) => { releaseMobileLandscape = resolve })
@@ -452,6 +488,8 @@ test("image previews keep one frame through loading, decode, failure, retry, and
const mobilePortraitLandscapeOrientation = await previewRects(mobilePage)
expectWithinPreviewViewport(mobilePortraitLandscapeOrientation.container, { width: 844, height: 390 })
expect(mobilePortraitLandscapeOrientation.container.height).toBeLessThan(mobilePortraitLoading.container.height)
+ const rotatedControls = await boundingRect(mobilePage.getByRole("toolbar", { name: "Image controls" }))
+ expect(rotatedControls.y + rotatedControls.height).toBeLessThan(mobilePortraitLandscapeOrientation.container.y)
await attachScreenshot(testInfo, "mobile-portrait-landscape-orientation-loading", mobilePage)
await mobilePage.setViewportSize({ width: 390, height: 844 })
const mobilePortraitRestored = await previewRects(mobilePage)
@@ -462,7 +500,43 @@ test("image previews keep one frame through loading, decode, failure, retry, and
const mobilePortraitLoaded = await previewRects(mobilePage)
expectSameRect(mobilePortraitLoaded.container, mobilePortraitRestored.container)
await attachScreenshot(testInfo, "mobile-portrait-loaded", mobilePage)
- await mobilePage.keyboard.press("Escape")
+ const mobileZoomFrame = mobilePage.getByTestId(tid.imageLightbox)
+ const mobileOriginal = mobilePage.getByTestId(tid.imageLightboxOriginal)
+ const centerX = mobilePortraitLoaded.container.x + mobilePortraitLoaded.container.width / 2
+ const centerY = mobilePortraitLoaded.container.y + mobilePortraitLoaded.container.height / 2
+ const touchSession = await mobilePage.context().newCDPSession(mobilePage)
+ try {
+ const points = (gap: number) => [
+ { id: 1, x: centerX - gap, y: centerY, radiusX: 1, radiusY: 1, force: 1 },
+ { id: 2, x: centerX + gap, y: centerY, radiusX: 1, radiusY: 1, force: 1 },
+ ]
+ await touchSession.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: points(40) })
+ await touchSession.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: points(80) })
+ await touchSession.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] })
+ await expect.poll(async () => Number(await mobileZoomFrame.getAttribute("data-zoom-scale"))).toBeCloseTo(2, 1)
+ expect(await mobilePage.evaluate(() => window.visualViewport?.scale)).toBe(1)
+ const beforePan = await mobileOriginal.evaluate((element) => element.style.transform)
+ await touchSession.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ id: 1, x: centerX, y: centerY, radiusX: 1, radiusY: 1, force: 1 }] })
+ await touchSession.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ id: 1, x: centerX + 40, y: centerY + 30, radiusX: 1, radiusY: 1, force: 1 }] })
+ await touchSession.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] })
+ await expect.poll(() => mobileOriginal.evaluate((element) => element.style.transform)).not.toBe(beforePan)
+ } finally {
+ await touchSession.detach()
+ }
+ expectSameRect(await boundingRect(mobileZoomFrame), mobilePortraitLoaded.container)
+ await attachScreenshot(testInfo, "mobile-original-pinched", mobilePage)
+ for (const name of ["Zoom out", "Fit image", "Zoom in", "Close image preview"]) {
+ const control = await boundingRect(mobilePage.getByRole("button", { name, exact: true }))
+ expect(control.width).toBeGreaterThanOrEqual(44)
+ expect(control.height).toBeGreaterThanOrEqual(44)
+ expect(control.y).toBeGreaterThanOrEqual(0)
+ expect(control.x).toBeGreaterThanOrEqual(0)
+ expect(control.x + control.width).toBeLessThanOrEqual(390)
+ }
+ await mobilePage.getByRole("button", { name: "Fit image", exact: true }).click()
+ await expect(mobileZoomFrame).toHaveAttribute("data-zoom-scale", "1")
+ expectSameRect(await boundingRect(mobileOriginal), mobilePortraitLoaded.original)
+ await mobilePage.getByRole("button", { name: "Close image preview", exact: true }).click()
await expect(mobilePage.getByTestId(tid.imageLightbox)).toHaveCount(0)
async function assertExtremeFailure(args: {
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index aba77703e..279317394 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -1,4 +1,4 @@
-import type { Locator, Page, Request } from "@playwright/test"
+import type { Locator, Page, Request, Route } from "@playwright/test"
import { test, expect, userId } from "./_fixtures/community-fixture"
import {
composerEditable,
@@ -744,18 +744,28 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
const directProfileCard = alice.page.getByTestId(tid.profileCard)
await expect(directProfileCard).toBeVisible()
await directProfileCard.getByPlaceholder(`Message @${bobInfo.name}`).fill(directDmBody)
- const directResponsePromise = alice.page.waitForResponse((response) => (
- response.request().method() === "POST"
- && new URL(response.url()).pathname === `/api/community/channels/${dmId}/messages`
- ))
+ const directPostPath = `/api/community/channels/${dmId}/messages`
+ let directStatus: number | undefined
+ let directPayload: { message: { id: string } } | undefined
+ const captureDirectResponse = async (route: Route) => {
+ if (route.request().method() !== "POST") {
+ await route.continue()
+ return
+ }
+ const response = await route.fetch()
+ directPayload = await response.json() as { message: { id: string } }
+ directStatus = response.status()
+ await route.fulfill({ response })
+ }
+ await alice.page.route(`**${directPostPath}`, captureDirectResponse)
await directProfileCard.getByRole("button", { name: "Send message" }).click()
- const directResponse = await directResponsePromise
- expect(directResponse.status()).toBe(201)
- const directPayload = await directResponse.json() as { message: { id: string } }
+ await expect.poll(() => directStatus).toBe(201)
+ await alice.page.unroute(`**${directPostPath}`, captureDirectResponse)
+ expect(directPayload).toMatchObject({ message: { id: expect.any(String) } })
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)
expect(await latestSeq(alice.page, dmId)).toBe(dmSeqBeforeDirect + 1)
await expect.poll(() => bobProxy.frames.filter((frame) => (
- frameHasMessage(frame, dmId, directPayload.message.id)
+ frameHasMessage(frame, dmId, directPayload!.message.id)
)).length).toBe(1)
await bob.page.goto(`/c/me/${dmId}`, { waitUntil: "commit" })
await ignoreNextDevToolsPointerCapture(alice.page)
diff --git a/src/web/src/test/fixtures/media.ts b/src/web/src/test/fixtures/media.ts
index 9d9b457e4..2d41ae8b4 100644
--- a/src/web/src/test/fixtures/media.ts
+++ b/src/web/src/test/fixtures/media.ts
@@ -44,7 +44,7 @@ export function solidPngFixture(
return Buffer.concat([
Buffer.from("89504e470d0a1a0a", "hex"),
pngChunk("IHDR", header),
- // Keep browser-E2E fixtures above the 512 KiB preview threshold. A highly
+ // Keep browser-E2E fixtures above the 256 KiB preview threshold. A highly
// compressed solid image skips the required-thumbnail path entirely.
pngChunk("IDAT", deflateSync(pixels, { level: 0 })),
pngChunk("IEND", Buffer.alloc(0)),