-
Notifications
You must be signed in to change notification settings - Fork 5
feat(messages): show message-carried blurhash before decoded originals #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| import { useEffect, useRef, useState } from "react"; | ||
| import type { Attachment } from "../relay/contracts"; | ||
| import { validatedBlurhash } from "../relay/blurhash"; | ||
| import { BLURHASH_SIZE, paintBlurhash } from "./blurhash"; | ||
| import styles from "./Messages.module.css"; | ||
|
|
||
| export function AttachmentImage({ | ||
| attachment, | ||
| url, | ||
| source, | ||
| onOpenLink, | ||
| }: { | ||
| attachment: Attachment; | ||
| url: string; | ||
| source: string; | ||
| onOpenLink(url: string): boolean; | ||
| }) { | ||
| return ( | ||
| <a | ||
| className={styles.attachmentImage} | ||
| style={ | ||
| attachment.dimensions | ||
| ? { | ||
| width: Math.min( | ||
| 360, | ||
| attachment.dimensions.width, | ||
| (320 * attachment.dimensions.width) / | ||
| attachment.dimensions.height, | ||
| ), | ||
| aspectRatio: `${attachment.dimensions.width} / ${attachment.dimensions.height}`, | ||
| } | ||
| : undefined | ||
| } | ||
| href={url} | ||
| target="_blank" | ||
| rel="noreferrer" | ||
| aria-label="Open image attachment" | ||
| onClick={(event) => { | ||
| if ( | ||
| !event.metaKey && | ||
| !event.ctrlKey && | ||
| !event.shiftKey && | ||
| onOpenLink(url) | ||
| ) | ||
| event.preventDefault(); | ||
| }} | ||
| > | ||
| {/* Retargeting retires both the DOM pixels and all pending callbacks before | ||
| the new source can paint. Session switches also remount the workspace. */} | ||
| <ImagePixels | ||
| key={JSON.stringify([source, attachment.blurhash])} | ||
| source={source} | ||
| blurhash={attachment.blurhash} | ||
| /> | ||
| </a> | ||
| ); | ||
| } | ||
|
|
||
| function ImagePixels({ | ||
| source, | ||
| blurhash, | ||
| }: { | ||
| source: string; | ||
| blurhash: string | undefined; | ||
| }) { | ||
| const image = useRef<HTMLImageElement>(null); | ||
| const canvas = useRef<HTMLCanvasElement>(null); | ||
| const [ready, setReady] = useState(false); | ||
| const hash = validatedBlurhash(blurhash); | ||
| useEffect(() => { | ||
| const original = image.current; | ||
| if (!original) return; | ||
| let active = true; | ||
| let decoded = false; | ||
| let painted = false; | ||
| let decoding = false; | ||
| let observer: IntersectionObserver | undefined; | ||
| const loaded = async () => { | ||
| if (!active || decoding || decoded || !original.naturalWidth) return; | ||
| decoding = true; | ||
| try { | ||
| await original.decode(); | ||
| if (!active) return; | ||
| decoded = true; | ||
| observer?.disconnect(); | ||
| setReady(true); | ||
| } catch { | ||
| // Keep the blur preview on original failure, including decode rejection. | ||
| } finally { | ||
| decoding = false; | ||
| } | ||
| }; | ||
| original.addEventListener("load", loaded); | ||
| if (original.complete) void loaded(); | ||
| const preview = canvas.current; | ||
| if (hash && preview && typeof IntersectionObserver !== "undefined") { | ||
| // Original requests keep native loading="lazy". Only preview CPU work is | ||
| // visibility-gated, including nonvirtualized thread rows. No new scheduler. | ||
| observer = new IntersectionObserver((entries) => { | ||
| if ( | ||
| !active || | ||
| decoded || | ||
| painted || | ||
| !entries.some((entry) => entry.isIntersecting) | ||
| ) | ||
| return; | ||
| observer?.disconnect(); | ||
| painted = true; | ||
| paintBlurhash(preview, hash); | ||
| }); | ||
| observer.observe(preview); | ||
| } | ||
| // Without IntersectionObserver, retain the old placeholder rather than | ||
| // eagerly decode every mounted thread attachment. | ||
| return () => { | ||
| active = false; | ||
| original.removeEventListener("load", loaded); | ||
| observer?.disconnect(); | ||
| }; | ||
| }, [hash]); | ||
| return ( | ||
| <> | ||
| {hash && !ready && ( | ||
| <canvas | ||
| ref={canvas} | ||
| width={BLURHASH_SIZE} | ||
| height={BLURHASH_SIZE} | ||
| tabIndex={-1} | ||
| aria-hidden="true" | ||
| /> | ||
| )} | ||
| <img | ||
| ref={image} | ||
| src={source} | ||
| alt="" | ||
| loading="lazy" | ||
| style={{ visibility: ready ? "visible" : "hidden" }} | ||
| /> | ||
| </> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import { afterEach, expect, it, vi } from "vitest"; | ||
| import { decode } from "blurhash"; | ||
| import { BLURHASH_SIZE, paintBlurhash } from "./blurhash"; | ||
| vi.mock("blurhash", async (original) => ({ | ||
| ...(await original<typeof import("blurhash")>()), | ||
| decode: vi.fn((await original<typeof import("blurhash")>()).decode), | ||
| })); | ||
| afterEach(() => vi.mocked(decode).mockClear()); | ||
| const hash = "LEHV6nWB2yk8pyo0adR*.7kCMdnj"; | ||
| function canvas() { | ||
| const data = new Uint8ClampedArray(BLURHASH_SIZE ** 2 * 4); | ||
| const context = { | ||
| createImageData: vi.fn(() => ({ data })), | ||
| putImageData: vi.fn(), | ||
| }; | ||
| const element = { getContext: vi.fn(() => context) }; | ||
| return { element: element as unknown as HTMLCanvasElement, context, data }; | ||
| } | ||
| it("uses the canonical decoder with a fixed tiny raster, with no source dimensions", () => { | ||
| const { element, context, data } = canvas(); | ||
| paintBlurhash(element, hash); | ||
| expect(decode).toHaveBeenCalledExactlyOnceWith(hash, 32, 32); | ||
| expect(context.putImageData).toHaveBeenCalledOnce(); | ||
| expect(data.some((value) => value > 0)).toBe(true); | ||
| }); | ||
| it("rejects invalid/oversized input before any canvas or decoder work", () => { | ||
| const { element } = canvas(); | ||
| for (const value of [ | ||
| "invalid", | ||
| "0".repeat(10000), | ||
| "~000000000000000000000000000000000000000", | ||
| ]) | ||
| paintBlurhash(element, value); | ||
| expect(element.getContext).not.toHaveBeenCalled(); | ||
| expect(decode).not.toHaveBeenCalled(); | ||
| }); | ||
| it("contains decoder, unavailable canvas and raster write failures", () => { | ||
| const { element, context } = canvas(); | ||
| vi.mocked(decode).mockImplementationOnce(() => { | ||
| throw new Error("decode"); | ||
| }); | ||
| expect(() => paintBlurhash(element, hash)).not.toThrow(); | ||
| expect(context.putImageData).not.toHaveBeenCalled(); | ||
| context.putImageData.mockImplementationOnce(() => { | ||
| throw new Error("canvas"); | ||
| }); | ||
| expect(() => paintBlurhash(element, hash)).not.toThrow(); | ||
| expect(() => | ||
| paintBlurhash( | ||
| { getContext: () => null } as unknown as HTMLCanvasElement, | ||
| hash, | ||
| ), | ||
| ).not.toThrow(); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import { decode } from "blurhash"; | ||
| import { validatedBlurhash } from "../relay/blurhash"; | ||
|
|
||
| export const BLURHASH_SIZE = 32; | ||
|
|
||
| /** Local, bounded raster only; no URL, source-sized canvas or retained cache. */ | ||
| export function paintBlurhash(canvas: HTMLCanvasElement, hash: string): void { | ||
| if (!validatedBlurhash(hash)) return; | ||
| try { | ||
| const context = canvas.getContext("2d"); | ||
| if (!context) return; | ||
| const image = context.createImageData(BLURHASH_SIZE, BLURHASH_SIZE); | ||
| image.data.set(decode(hash, BLURHASH_SIZE, BLURHASH_SIZE)); | ||
| context.putImageData(image, 0, 0); | ||
| } catch { | ||
| // Bad metadata, unavailable canvas or decoder failure keeps the frame's | ||
| // existing background. Original loading must never depend on the preview. | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| // Signed imeta is still untrusted. Validate syntax without doing pixel work in | ||
| // message folding: at most 9x9 components (166 base83 characters). | ||
| const BASE83 = | ||
| "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"; | ||
| export function validatedBlurhash(value: unknown): string | undefined { | ||
| if (typeof value !== "string" || value.length < 6 || value.length > 166) | ||
| return undefined; | ||
| for (const character of value) { | ||
| if (!BASE83.includes(character)) return undefined; | ||
| } | ||
| const size = BASE83.indexOf(value.charAt(0)); | ||
| if (size > 80) return undefined; | ||
| const components = ((size % 9) + 1) * (Math.floor(size / 9) + 1); | ||
| return value.length === 4 + 2 * components ? value : undefined; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The reviewed commit has no
Signed-off-by:trailer, so it violates the repository's per-commit DCO requirement and cannot pass the documented DCO merge gate. Recreate the commit with a sign-off matching its verified effective author identity.AGENTS.md reference: AGENTS.md:L49-L54
Useful? React with 👍 / 👎.