Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add ThumbHash placeholders for Space posts

Anand Baburajanc2dcd7ac0d3c
diff --git a/rust/bindings/wasm/ente-wasm/src/space.rs b/rust/bindings/wasm/ente-wasm/src/space.rs
index 8ccd60e123..65b4aee426 100644
--- a/rust/bindings/wasm/ente-wasm/src/space.rs
+++ b/rust/bindings/wasm/ente-wasm/src/space.rs
@@ -268,6 +268,8 @@ struct PostObjectJs {
#[serde(skip_serializing_if = "Option::is_none")]
blur_hash: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
+ thumb_hash: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
width: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
height: Option<i32>,
@@ -400,6 +402,7 @@ fn post_object_to_js(
position: object.position,
variant: metadata.as_ref().and_then(|value| value.variant.clone()),
blur_hash: metadata.as_ref().and_then(|value| value.blur_hash.clone()),
+ thumb_hash: metadata.as_ref().and_then(|value| value.thumb_hash.clone()),
width: metadata.as_ref().and_then(|value| value.width),
height: metadata.as_ref().and_then(|value| value.height),
media_type: metadata.and_then(|value| value.media_type),
@@ -962,6 +965,7 @@ impl SpaceAccountCtxHandle {
width: Option<i32>,
height: Option<i32>,
media_type: Option<String>,
+ thumb_hash: Option<String>,
) -> Result<JsValue, WasmSpaceError> {
let post_key = self.inner.generate_post_key();
let object = self
@@ -973,6 +977,7 @@ impl SpaceAccountCtxHandle {
width,
height,
media_type,
+ thumb_hash,
)
.await?;
let (post_id, _) = self
diff --git a/rust/e2e/tests/space_e2e.rs b/rust/e2e/tests/space_e2e.rs
index c8c4b465ce..d037e385f8 100644
--- a/rust/e2e/tests/space_e2e.rs
+++ b/rust/e2e/tests/space_e2e.rs
@@ -108,6 +108,7 @@ async fn space_bootstrap_posts_friend_share_and_link_suite() {
Some(320),
Some(240),
Some("image/webp".to_owned()),
+ None,
)
.await
.expect("post asset upload should succeed");
@@ -337,6 +338,7 @@ async fn space_unfriend_revokes_reciprocal_account_access_suite() {
Some(320),
Some(240),
Some("image/webp".to_owned()),
+ None,
)
.await
.expect("post asset upload should succeed");
@@ -576,6 +578,7 @@ async fn space_rotation_history_refresh_and_link_suite() {
Some(320),
Some(240),
Some("image/webp".to_owned()),
+ None,
)
.await
.expect("v1 post asset upload should succeed");
@@ -642,6 +645,7 @@ async fn space_rotation_history_refresh_and_link_suite() {
Some(320),
Some(240),
Some("image/webp".to_owned()),
+ None,
)
.await
.expect("v2 post asset upload should succeed");
diff --git a/rust/space/src/client/assets.rs b/rust/space/src/client/assets.rs
index c408d7129b..24bd0cac10 100644
--- a/rust/space/src/client/assets.rs
+++ b/rust/space/src/client/assets.rs
@@ -122,6 +122,7 @@ impl AccountSpaceCtx {
width: Option<i32>,
height: Option<i32>,
media_type: Option<String>,
+ thumb_hash: Option<String>,
) -> Result<PostObjectPayload> {
let inferred_media_type = ensure_supported_photo_bytes(plaintext)?;
let media_type = ensure_supported_photo_media_type(media_type.as_deref())?
@@ -135,6 +136,7 @@ impl AccountSpaceCtx {
width: width.filter(|value| *value > 0),
height: height.filter(|value| *value > 0),
media_type: Some(media_type),
+ thumb_hash,
..Default::default()
},
)?);
diff --git a/rust/space/src/client/tests.rs b/rust/space/src/client/tests.rs
index 6dea6256dc..af7060a304 100644
--- a/rust/space/src/client/tests.rs
+++ b/rust/space/src/client/tests.rs
@@ -497,6 +497,7 @@ async fn upload_post_photo_asset_attaches_photo_metadata() {
Some(4032),
Some(3024),
Some("image/webp".to_owned()),
+ Some("thumbhash-test".to_owned()),
)
.await
.expect("photo upload should succeed");
@@ -510,6 +511,7 @@ async fn upload_post_photo_asset_attaches_photo_metadata() {
assert_eq!(metadata.width, Some(4032));
assert_eq!(metadata.height, Some(3024));
assert_eq!(metadata.media_type.as_deref(), Some("image/webp"));
+ assert_eq!(metadata.thumb_hash.as_deref(), Some("thumbhash-test"));
presign.assert_async().await;
upload.assert_async().await;
}
@@ -527,6 +529,7 @@ async fn upload_post_photo_asset_rejects_video_media_type() {
Some(4032),
Some(3024),
Some("video/mp4".to_owned()),
+ None,
)
.await
.expect_err("video media type should fail before upload");
@@ -547,6 +550,7 @@ async fn upload_post_photo_asset_rejects_video_bytes() {
Some(1920),
Some(1080),
Some("image/webp".to_owned()),
+ None,
)
.await
.expect_err("video bytes should fail before upload");
diff --git a/rust/space/src/models.rs b/rust/space/src/models.rs
index 648ea1660d..7676f1b893 100644
--- a/rust/space/src/models.rs
+++ b/rust/space/src/models.rs
@@ -70,6 +70,8 @@ pub struct PostObjectMetadata {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blur_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
+ pub thumb_hash: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub width: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub height: Option<i32>,
diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsx
index 73bc1dc444..8ff5ed17e7 100644
--- a/web/apps/space/src/pages/app/index.tsx
+++ b/web/apps/space/src/pages/app/index.tsx
@@ -259,6 +259,7 @@ const Page: React.FC = () => {
file: preparedImage.file,
height: preparedImage.height,
spaceId,
+ thumbHash: preparedImage.thumbHash,
width: preparedImage.width,
});
if (!post)
diff --git a/web/apps/space/src/pages/app/profile.tsx b/web/apps/space/src/pages/app/profile.tsx
index 5c3ed6f5c1..9472783c34 100644
--- a/web/apps/space/src/pages/app/profile.tsx
+++ b/web/apps/space/src/pages/app/profile.tsx
@@ -155,6 +155,7 @@ const Page: React.FC = () => {
file: preparedImage.file,
height: preparedImage.height,
spaceId,
+ thumbHash: preparedImage.thumbHash,
width: preparedImage.width,
});
if (!post) throw new Error("Couldn't create post.");
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index c98a62cc92..f34753140a 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -42,6 +42,7 @@ import {
spacePostImageInputAccept,
spacePostPreviewImageForFile,
} from "utils/spacePostImage";
+import { thumbHashDataURLFromBase64 } from "utils/thumbhash";
export const homeBackground = "#F5F5F7";
@@ -184,6 +185,7 @@ interface FeedItemProps {
onOpenProfile?: () => void;
onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
postId: number;
+ thumbHash?: string;
timestampStatus?: FeedTimestampStatus;
timestampMs: number;
viewerLiked: boolean;
@@ -195,6 +197,7 @@ interface FeedSkeletonItemProps {
pb?: string;
rootRef?: React.Ref<HTMLElement>;
showFooter?: boolean;
+ thumbHashDataURL?: string;
}
interface AddedFriendToastProps {
@@ -363,6 +366,7 @@ const FeedSkeletonItem: React.FC<FeedSkeletonItemProps> = ({
pb = "8px",
rootRef,
showFooter = true,
+ thumbHashDataURL,
}) => (
<Box
ref={rootRef}
@@ -395,17 +399,35 @@ const FeedSkeletonItem: React.FC<FeedSkeletonItemProps> = ({
width: "100%",
}}
>
- <Skeleton
- variant="rectangular"
- sx={{
- aspectRatio,
- bgcolor: feedSkeletonElementBackground,
- display: "block",
- height: "100%",
- transform: "none",
- width: "100%",
- }}
- />
+ {thumbHashDataURL ? (
+ <Box
+ component="img"
+ alt=""
+ aria-hidden
+ src={thumbHashDataURL}
+ sx={{
+ display: "block",
+ filter: "blur(14px)",
+ height: "100%",
+ objectFit: "cover",
+ objectPosition: "center",
+ transform: "scale(1.08)",
+ width: "100%",
+ }}
+ />
+ ) : (
+ <Skeleton
+ variant="rectangular"
+ sx={{
+ aspectRatio,
+ bgcolor: feedSkeletonElementBackground,
+ display: "block",
+ height: "100%",
+ transform: "none",
+ width: "100%",
+ }}
+ />
+ )}
<Box
sx={{
alignItems: "center",
@@ -633,6 +655,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
onOpenProfile,
onSetPostLiked,
postId,
+ thumbHash,
timestampStatus,
timestampMs,
viewerLiked,
@@ -647,6 +670,10 @@ const FeedItem: React.FC<FeedItemProps> = ({
const dateLabel = formatSpaceDate(timestampMs);
const postingDotCount = usePostingDotCount(timestampStatus == "posting");
const displayCaption = caption?.trim();
+ const thumbHashDataURL = React.useMemo(
+ () => thumbHashDataURLFromBase64(thumbHash),
+ [thumbHash],
+ );
const showFooter = !isOwnPost || Boolean(displayCaption);
const canOpenAuthor = isOwnPost
? Boolean(onOpenProfile)
@@ -678,6 +705,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
feedPhotoFrameDimensionsFor(photoDimensions);
const isFeedItemReady =
Boolean(displayImageUrl) && decodedPhoto.ready && isAvatarReady;
+ const [showResolvedPhoto, setShowResolvedPhoto] = useState(false);
const decodedPhotoHeight = decodedPhoto.height;
const decodedPhotoSrc = decodedPhoto.src;
const decodedPhotoWidth = decodedPhoto.width;
@@ -807,6 +835,20 @@ const FeedItem: React.FC<FeedItemProps> = ({
return () => window.clearTimeout(timeoutID);
}, [likePopID]);
+ React.useEffect(() => {
+ setShowResolvedPhoto(false);
+ if (!isFeedItemReady) return;
+ if (!thumbHashDataURL) {
+ setShowResolvedPhoto(true);
+ return;
+ }
+
+ const frameID = window.requestAnimationFrame(() =>
+ setShowResolvedPhoto(true),
+ );
+ return () => window.cancelAnimationFrame(frameID);
+ }, [displayImageUrl, isFeedItemReady, thumbHashDataURL]);
+
if (!isFeedItemReady) {
return (
<FeedSkeletonItem
@@ -815,6 +857,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
pb={isOwnPost ? "5px" : "8px"}
rootRef={rootRef}
showFooter={showFooter}
+ thumbHashDataURL={thumbHashDataURL}
/>
);
}
@@ -865,7 +908,9 @@ const FeedItem: React.FC<FeedItemProps> = ({
height: "100%",
maxWidth: "100%",
minWidth: 0,
+ overflow: "hidden",
p: 0,
+ position: "relative",
width: "100%",
"&:focus-visible": {
outline: `2px solid ${green}`,
@@ -873,6 +918,25 @@ const FeedItem: React.FC<FeedItemProps> = ({
},
}}
>
+ {thumbHashDataURL ? (
+ <Box
+ component="img"
+ alt=""
+ aria-hidden
+ src={thumbHashDataURL}
+ sx={{
+ display: "block",
+ filter: "blur(14px)",
+ height: "100%",
+ inset: 0,
+ objectFit: "cover",
+ objectPosition: "center",
+ position: "absolute",
+ transform: "scale(1.08)",
+ width: "100%",
+ }}
+ />
+ ) : null}
<Box
component="img"
alt={`${name} post`}
@@ -885,7 +949,17 @@ const FeedItem: React.FC<FeedItemProps> = ({
minWidth: 0,
objectFit: "cover",
objectPosition: "center",
+ opacity: showResolvedPhoto ? 1 : 0,
+ position: "relative",
+ transition: thumbHashDataURL
+ ? "opacity 220ms ease"
+ : "none",
width: "100%",
+ zIndex: 1,
+ "@media (prefers-reduced-motion: reduce)": {
+ opacity: 1,
+ transition: "none",
+ },
}}
/>
</Box>
@@ -1503,6 +1577,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
onOpenProfile={onOpenProfile}
onSetPostLiked={onSetPostLiked}
postId={item.postId}
+ thumbHash={item.thumbHash}
timestampStatus={timestampStatus}
timestampMs={item.timestampMs}
viewerLiked={item.viewerLiked}
diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsx
index 35a7febb76..e88ec04ba7 100644
--- a/web/apps/space/src/screens/ProfileScreen.tsx
+++ b/web/apps/space/src/screens/ProfileScreen.tsx
@@ -31,6 +31,7 @@ import {
spacePostImageInputAccept,
spacePostPreviewImageForFile,
} from "utils/spacePostImage";
+import { thumbHashDataURLFromBase64 } from "utils/thumbhash";
export const profileBackground = "#FFFFFF";
@@ -73,6 +74,7 @@ export interface ProfilePostItem {
name?: string;
postId?: number;
timestampMs: number;
+ thumbHash?: string;
viewerLiked?: boolean;
width?: number;
}
@@ -265,7 +267,13 @@ const ProfilePostTile: React.FC<ProfilePostTileProps> = ({
onRememberDimensions,
}) => {
const [shouldLoad, setShouldLoad] = React.useState(Boolean(imageUrl));
+ const [readyImageUrl, setReadyImageUrl] = React.useState<string>();
const tileRef = React.useRef<HTMLButtonElement | null>(null);
+ const thumbHashDataURL = React.useMemo(
+ () => thumbHashDataURLFromBase64(item.thumbHash),
+ [item.thumbHash],
+ );
+ const isCurrentImageReady = Boolean(imageUrl && readyImageUrl == imageUrl);
React.useEffect(() => {
if (imageUrl) setShouldLoad(true);
@@ -328,40 +336,61 @@ const ProfilePostTile: React.FC<ProfilePostTileProps> = ({
opacity: 1,
overflow: "hidden",
p: 0,
+ position: "relative",
"&:focus-visible": {
outline: `2px solid ${green}`,
outlineOffset: -2,
},
}}
>
- {imageUrl ? (
+ {thumbHashDataURL ? (
<Box
component="img"
- alt={`${groupLabel} post ${index + 1}`}
- onLoad={(event) =>
- onRememberDimensions(item.id, event.currentTarget)
- }
- src={imageUrl}
+ alt=""
+ aria-hidden
+ src={thumbHashDataURL}
sx={{
display: "block",
+ filter: "blur(14px)",
height: "100%",
+ inset: 0,
objectFit: "cover",
objectPosition: "center",
+ position: "absolute",
+ transform: "scale(1.08)",
width: "100%",
}}
/>
- ) : (
- <Skeleton
- variant="rectangular"
+ ) : null}
+ {imageUrl ? (
+ <Box
+ component="img"
+ alt={`${groupLabel} post ${index + 1}`}
+ onLoad={(event) => {
+ setReadyImageUrl(imageUrl);
+ onRememberDimensions(item.id, event.currentTarget);
+ }}
+ src={imageUrl}
sx={{
- bgcolor: photoMasonryPlaceholderBackground,
display: "block",
height: "100%",
- transform: "none",
+ inset: 0,
+ objectFit: "cover",
+ objectPosition: "center",
+ opacity:
+ isCurrentImageReady || !thumbHashDataURL ? 1 : 0,
+ position: "absolute",
+ transition: thumbHashDataURL
+ ? "opacity 220ms ease"
+ : "none",
width: "100%",
+ "@media (prefers-reduced-motion: reduce)": {
+ opacity: 1,
+ transition: "none",
+ },
}}
/>
- )}
+ ) : null}
</Box>
);
};
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 7d59c8e11c..e50e119271 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -56,6 +56,7 @@ interface SpacePostObject {
mediaType?: string;
objectKey: string;
size?: number;
+ thumbHash?: string;
width?: number;
}
@@ -174,6 +175,7 @@ interface SpacePostBase {
name: string;
postId: number;
timestampMs: number;
+ thumbHash?: string;
viewerLiked: boolean;
spaceId: string;
width?: number;
@@ -533,6 +535,7 @@ const postFromAccountPost = async (
name: author.fullName || author.username,
postId: post.postId,
timestampMs: timestampMsFromSpaceDate(post.createdAt),
+ thumbHash: object.thumbHash,
viewerLiked: post.viewerLiked,
spaceId: post.spaceId,
width: object.width,
@@ -558,6 +561,7 @@ const profilePostFromPost = (
name: author.fullName || author.username,
postId: post.postId,
timestampMs: timestampMsFromSpaceDate(post.createdAt),
+ thumbHash: object.thumbHash,
viewerLiked: post.viewerLiked,
spaceId: post.spaceId,
width: object.width,
@@ -917,12 +921,14 @@ export const createCurrentPhotoPost = async ({
file,
height,
spaceId,
+ thumbHash,
width,
}: {
caption?: string;
file: File;
height?: number;
spaceId: string;
+ thumbHash: string;
width?: number;
}) => {
const ctx = await ensureCurrentSpaceContext();
@@ -937,6 +943,7 @@ export const createCurrentPhotoPost = async ({
normalizedWidth,
normalizedHeight,
file.type || null,
+ thumbHash || null,
)) as SpacePostResponse;
const object = firstObject(created);
if (object) await cacheAccountPostAssetURL(created, object, file);
@@ -1070,10 +1077,10 @@ export const loadCurrentFriendRequestConversations =
async (): Promise<SpaceMessageConversation[]> => {
const ctx = await ensureCurrentSpaceContext();
try {
- const requests: SpaceFriendRequestResponse[] = await (
+ const requests = (await (
ctx as SpaceFriendRequestContext
- ).list_friend_requests();
- return (requests ?? []).map((request) => ({
+ ).list_friend_requests()) as SpaceFriendRequestResponse[];
+ return requests.map((request) => ({
friend: actorProfile(request.requester),
latestActivity: {
createdAtMs: timestampMsFromSpaceDate(request.createdAt),
diff --git a/web/apps/space/src/utils/spacePostDisplay.ts b/web/apps/space/src/utils/spacePostDisplay.ts
index 0fdcd035e6..c8304a7f88 100644
--- a/web/apps/space/src/utils/spacePostDisplay.ts
+++ b/web/apps/space/src/utils/spacePostDisplay.ts
@@ -32,6 +32,7 @@ export const profilePostGroupsFromPosts = (
name: post.name,
postId: post.postId,
timestampMs: post.timestampMs,
+ thumbHash: post.thumbHash,
viewerLiked: post.viewerLiked,
width: post.width,
});
diff --git a/web/apps/space/src/utils/spacePostImage.ts b/web/apps/space/src/utils/spacePostImage.ts
index 135ed6fecb..e4a04157e9 100644
--- a/web/apps/space/src/utils/spacePostImage.ts
+++ b/web/apps/space/src/utils/spacePostImage.ts
@@ -1,6 +1,7 @@
import { lowercaseExtension, nameAndExtension } from "ente-base/file-name";
import { isHEICExtension } from "ente-media/formats";
import { heicToJPEG } from "ente-media/heic-convert";
+import { thumbHashBase64FromCanvas } from "utils/thumbhash";
export interface PreparedSpaceImage {
file: File;
@@ -10,7 +11,9 @@ export interface PreparedSpaceImage {
export type PreparedSpaceAvatarImage = PreparedSpaceImage;
export type PreparedSpaceCoverImage = PreparedSpaceImage;
-export type PreparedSpacePostImage = PreparedSpaceImage;
+export interface PreparedSpacePostImage extends PreparedSpaceImage {
+ thumbHash: string;
+}
export interface SpaceAvatarCropImage {
url: string;
@@ -80,9 +83,10 @@ export const prepareSpacePostImage = async (
file: File,
): Promise<PreparedSpacePostImage> => {
const renderableBlob = await renderableBlobForSpaceImage(file);
- const { blob, height, width } = await webPBlobFromImage(
+ const { blob, height, thumbHash, width } = await webPBlobFromImage(
renderableBlob,
postCanvasPlan,
+ true,
);
assertSpaceImageSize(
blob,
@@ -96,6 +100,7 @@ export const prepareSpacePostImage = async (
type: spacePostImageMimeType,
}),
height,
+ thumbHash,
width,
};
};
@@ -112,7 +117,7 @@ export const prepareSpacePostImageFromEdit = async (
}
const renderableBlob = await renderableBlobForSpaceImage(file);
- const { blob, height, width } = await webPBlobFromEditedImage(
+ const { blob, height, thumbHash, width } = await webPBlobFromEditedImage(
renderableBlob,
cropArea,
normalizedRotationDegrees,
@@ -129,6 +134,7 @@ export const prepareSpacePostImageFromEdit = async (
type: spacePostImageMimeType,
}),
height,
+ thumbHash,
width,
};
};
@@ -212,6 +218,7 @@ export const prepareSpaceAvatarImageFromCrop = async (
imageURL,
(width, height) => avatarCanvasPlanForCrop(width, height, cropArea),
false,
+ false,
);
assertSpaceImageSize(
blob,
@@ -238,6 +245,7 @@ export const prepareSpaceCoverImageFromCrop = async (
imageURL,
(width, height) => coverCanvasPlanForCrop(width, height, cropArea),
false,
+ false,
);
assertSpaceImageSize(
blob,
@@ -332,8 +340,14 @@ interface CanvasPlan {
const webPBlobFromImage = async (
imageSource: Blob | string,
planForSource: (width: number, height: number) => CanvasPlan,
+ includeThumbHash = false,
revokeImageURL = true,
-): Promise<{ blob: Blob; height: number; width: number }> => {
+): Promise<{
+ blob: Blob;
+ height: number;
+ thumbHash: string;
+ width: number;
+}> => {
const imageURL =
typeof imageSource == "string"
? imageSource
@@ -367,11 +381,16 @@ const webPBlobFromImage = async (
plan.height,
);
- return {
+ const result = {
blob: await canvasToBlob(canvas, spacePostImageMimeType),
height: plan.height,
+ thumbHash: "",
width: plan.width,
};
+ if (includeThumbHash) {
+ result.thumbHash = thumbHashBase64FromCanvas(canvas);
+ }
+ return result;
} finally {
if (revokeImageURL) URL.revokeObjectURL(imageURL);
}
@@ -381,7 +400,12 @@ const webPBlobFromEditedImage = async (
imageSource: Blob | string,
cropArea: SpaceImageCropArea | undefined,
rotationDegrees: number,
-): Promise<{ blob: Blob; height: number; width: number }> => {
+): Promise<{
+ blob: Blob;
+ height: number;
+ thumbHash: string;
+ width: number;
+}> => {
const imageURL =
typeof imageSource == "string"
? imageSource
@@ -434,6 +458,7 @@ const webPBlobFromEditedImage = async (
return {
blob: await canvasToBlob(canvas, spacePostImageMimeType),
height: dimensions.height,
+ thumbHash: thumbHashBase64FromCanvas(canvas),
width: dimensions.width,
};
} finally {
diff --git a/web/apps/space/src/utils/thumbhash.ts b/web/apps/space/src/utils/thumbhash.ts
new file mode 100644
index 0000000000..94a987787d
--- /dev/null
+++ b/web/apps/space/src/utils/thumbhash.ts
@@ -0,0 +1,470 @@
+/*
+ * ThumbHash
+ *
+ * Copyright (c) 2023 Evan Wallace
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ * Source: https://github.com/evanw/thumbhash/blob/main/js/thumbhash.js
+ */
+
+type RGBABytes = Uint8Array | Uint8ClampedArray;
+
+type ByteSequence = Uint8Array | readonly number[];
+
+const byteStringFromBytes = (bytes: ByteSequence) => {
+ let value = "";
+ for (const byte of bytes) {
+ value += String.fromCharCode(byte);
+ }
+ return value;
+};
+
+const bytesFromByteString = (value: string) => {
+ const bytes = new Uint8Array(value.length);
+ for (let i = 0; i < value.length; i++) {
+ bytes[i] = value.charCodeAt(i);
+ }
+ return bytes;
+};
+
+const bytesToBase64 = (bytes: ByteSequence) => btoa(byteStringFromBytes(bytes));
+
+const base64ToBytes = (value: string) => bytesFromByteString(atob(value));
+
+/**
+ * Encodes an RGBA image to a ThumbHash. RGB should not be premultiplied by A.
+ *
+ * @param w The width of the input image. Must be <=100px.
+ * @param h The height of the input image. Must be <=100px.
+ * @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
+ * @returns The ThumbHash as a Uint8Array.
+ */
+export function rgbaToThumbHash(w: number, h: number, rgba: RGBABytes) {
+ if (w > 100 || h > 100) throw new Error(`${w}x${h} doesn't fit in 100x100`);
+ const { PI, abs, cos, max, round } = Math;
+
+ let avgR = 0;
+ let avgG = 0;
+ let avgB = 0;
+ let avgA = 0;
+ for (let i = 0, j = 0; i < w * h; i++, j += 4) {
+ const alpha = rgba[j + 3]! / 255;
+ avgR += (alpha / 255) * rgba[j]!;
+ avgG += (alpha / 255) * rgba[j + 1]!;
+ avgB += (alpha / 255) * rgba[j + 2]!;
+ avgA += alpha;
+ }
+ if (avgA) {
+ avgR /= avgA;
+ avgG /= avgA;
+ avgB /= avgA;
+ }
+
+ const hasAlpha = avgA < w * h;
+ const lLimit = hasAlpha ? 5 : 7;
+ const lx = max(1, round((lLimit * w) / max(w, h)));
+ const ly = max(1, round((lLimit * h) / max(w, h)));
+ const l: number[] = [];
+ const p: number[] = [];
+ const q: number[] = [];
+ const a: number[] = [];
+
+ for (let i = 0, j = 0; i < w * h; i++, j += 4) {
+ const alpha = rgba[j + 3]! / 255;
+ const r = avgR * (1 - alpha) + (alpha / 255) * rgba[j]!;
+ const g = avgG * (1 - alpha) + (alpha / 255) * rgba[j + 1]!;
+ const b = avgB * (1 - alpha) + (alpha / 255) * rgba[j + 2]!;
+ l[i] = (r + g + b) / 3;
+ p[i] = (r + g) / 2 - b;
+ q[i] = r - g;
+ a[i] = alpha;
+ }
+
+ const encodeChannel = (
+ channel: number[],
+ nx: number,
+ ny: number,
+ ): [number, number[], number] => {
+ let dc = 0;
+ const ac: number[] = [];
+ let scale = 0;
+ const fx: number[] = [];
+ for (let cy = 0; cy < ny; cy++) {
+ for (let cx = 0; cx * ny < nx * (ny - cy); cx++) {
+ let f = 0;
+ for (let x = 0; x < w; x++) {
+ fx[x] = cos((PI / w) * cx * (x + 0.5));
+ }
+ for (let y = 0; y < h; y++) {
+ const fy = cos((PI / h) * cy * (y + 0.5));
+ for (let x = 0; x < w; x++) {
+ f += channel[x + y * w]! * fx[x]! * fy;
+ }
+ }
+ f /= w * h;
+ if (cx || cy) {
+ ac.push(f);
+ scale = max(scale, abs(f));
+ } else {
+ dc = f;
+ }
+ }
+ }
+ if (scale) {
+ for (let i = 0; i < ac.length; i++) {
+ ac[i] = 0.5 + (0.5 / scale) * ac[i]!;
+ }
+ }
+ return [dc, ac, scale];
+ };
+
+ const [lDC, lAC, lScale] = encodeChannel(l, max(3, lx), max(3, ly));
+ const [pDC, pAC, pScale] = encodeChannel(p, 3, 3);
+ const [qDC, qAC, qScale] = encodeChannel(q, 3, 3);
+ const [aDC, aAC, aScale] = hasAlpha ? encodeChannel(a, 5, 5) : [0, [], 0];
+
+ const isLandscape = w > h;
+ const header24 =
+ round(63 * lDC) |
+ (round(31.5 + 31.5 * pDC) << 6) |
+ (round(31.5 + 31.5 * qDC) << 12) |
+ (round(31 * lScale) << 18) |
+ (Number(hasAlpha) << 23);
+ const header16 =
+ (isLandscape ? ly : lx) |
+ (round(63 * pScale) << 3) |
+ (round(63 * qScale) << 9) |
+ (Number(isLandscape) << 15);
+ const hash = [
+ header24 & 255,
+ (header24 >> 8) & 255,
+ header24 >> 16,
+ header16 & 255,
+ header16 >> 8,
+ ];
+ const acStart = hasAlpha ? 6 : 5;
+ let acIndex = 0;
+ if (hasAlpha) hash.push(round(15 * aDC) | (round(15 * aScale) << 4));
+
+ for (const ac of hasAlpha ? [lAC, pAC, qAC, aAC] : [lAC, pAC, qAC]) {
+ for (const f of ac) {
+ hash[acStart + (acIndex >> 1)]! |=
+ round(15 * f) << ((acIndex++ & 1) << 2);
+ }
+ }
+ return new Uint8Array(hash);
+}
+
+/**
+ * Decodes a ThumbHash to an RGBA image. RGB is not premultiplied by A.
+ *
+ * @param hash The bytes of the ThumbHash.
+ * @returns The width, height, and pixels of the rendered placeholder image.
+ */
+export function thumbHashToRGBA(hash: Uint8Array) {
+ const { PI, cos, max, min, round } = Math;
+
+ const header24 = hash[0]! | (hash[1]! << 8) | (hash[2]! << 16);
+ const header16 = hash[3]! | (hash[4]! << 8);
+ const lDC = (header24 & 63) / 63;
+ const pDC = ((header24 >> 6) & 63) / 31.5 - 1;
+ const qDC = ((header24 >> 12) & 63) / 31.5 - 1;
+ const lScale = ((header24 >> 18) & 31) / 31;
+ const hasAlpha = header24 >> 23;
+ const pScale = ((header16 >> 3) & 63) / 63;
+ const qScale = ((header16 >> 9) & 63) / 63;
+ const isLandscape = header16 >> 15;
+ const lx = max(3, isLandscape ? (hasAlpha ? 5 : 7) : header16 & 7);
+ const ly = max(3, isLandscape ? header16 & 7 : hasAlpha ? 5 : 7);
+ const aDC = hasAlpha ? (hash[5]! & 15) / 15 : 1;
+ const aScale = (hash[5]! >> 4) / 15;
+
+ let acIndex = 0;
+ const acStart = hasAlpha ? 6 : 5;
+ const decodeChannel = (nx: number, ny: number, scale: number) => {
+ const ac: number[] = [];
+ for (let cy = 0; cy < ny; cy++) {
+ for (let cx = cy ? 0 : 1; cx * ny < nx * (ny - cy); cx++) {
+ ac.push(
+ (((hash[acStart + (acIndex >> 1)]! >>
+ ((acIndex++ & 1) << 2)) &
+ 15) /
+ 7.5 -
+ 1) *
+ scale,
+ );
+ }
+ }
+ return ac;
+ };
+ const lAC = decodeChannel(lx, ly, lScale);
+ const pAC = decodeChannel(3, 3, pScale * 1.25);
+ const qAC = decodeChannel(3, 3, qScale * 1.25);
+ const aAC = hasAlpha ? decodeChannel(5, 5, aScale) : [];
+
+ const ratio = thumbHashToApproximateAspectRatio(hash);
+ const w = round(ratio > 1 ? 32 : 32 * ratio);
+ const h = round(ratio > 1 ? 32 / ratio : 32);
+ const rgba = new Uint8Array(w * h * 4);
+ const fx: number[] = [];
+ const fy: number[] = [];
+ for (let y = 0, i = 0; y < h; y++) {
+ for (let x = 0; x < w; x++, i += 4) {
+ let l = lDC;
+ let p = pDC;
+ let q = qDC;
+ let a = aDC;
+
+ for (let cx = 0, n = max(lx, hasAlpha ? 5 : 3); cx < n; cx++) {
+ fx[cx] = cos((PI / w) * (x + 0.5) * cx);
+ }
+ for (let cy = 0, n = max(ly, hasAlpha ? 5 : 3); cy < n; cy++) {
+ fy[cy] = cos((PI / h) * (y + 0.5) * cy);
+ }
+
+ for (let cy = 0, j = 0; cy < ly; cy++) {
+ const fy2 = fy[cy]! * 2;
+ for (let cx = cy ? 0 : 1; cx * ly < lx * (ly - cy); cx++, j++) {
+ l += lAC[j]! * fx[cx]! * fy2;
+ }
+ }
+
+ for (let cy = 0, j = 0; cy < 3; cy++) {
+ const fy2 = fy[cy]! * 2;
+ for (let cx = cy ? 0 : 1; cx < 3 - cy; cx++, j++) {
+ const f = fx[cx]! * fy2;
+ p += pAC[j]! * f;
+ q += qAC[j]! * f;
+ }
+ }
+
+ if (hasAlpha) {
+ for (let cy = 0, j = 0; cy < 5; cy++) {
+ const fy2 = fy[cy]! * 2;
+ for (let cx = cy ? 0 : 1; cx < 5 - cy; cx++, j++) {
+ a += aAC[j]! * fx[cx]! * fy2;
+ }
+ }
+ }
+
+ const b = l - (2 / 3) * p;
+ const r = (3 * l - b + q) / 2;
+ const g = r - q;
+ rgba[i] = max(0, 255 * min(1, r));
+ rgba[i + 1] = max(0, 255 * min(1, g));
+ rgba[i + 2] = max(0, 255 * min(1, b));
+ rgba[i + 3] = max(0, 255 * min(1, a));
+ }
+ }
+ return { w, h, rgba };
+}
+
+/**
+ * Extracts the approximate aspect ratio of the original image.
+ *
+ * @param hash The bytes of the ThumbHash.
+ * @returns The approximate aspect ratio, width / height.
+ */
+export function thumbHashToApproximateAspectRatio(hash: Uint8Array) {
+ const header = hash[3]!;
+ const hasAlpha = hash[2]! & 0x80;
+ const isLandscape = hash[4]! & 0x80;
+ const lx = isLandscape ? (hasAlpha ? 5 : 7) : header & 7;
+ const ly = isLandscape ? header & 7 : hasAlpha ? 5 : 7;
+ return lx / ly;
+}
+
+/**
+ * Encodes an RGBA image to a PNG data URL. RGB should not be premultiplied by A.
+ *
+ * @param w The width of the input image. Must be <=100px.
+ * @param h The height of the input image. Must be <=100px.
+ * @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
+ * @returns A data URL containing a PNG for the input image.
+ */
+export function rgbaToDataURL(w: number, h: number, rgba: RGBABytes) {
+ const row = w * 4 + 1;
+ const idat = 6 + h * (5 + row);
+ const bytes = [
+ 137,
+ 80,
+ 78,
+ 71,
+ 13,
+ 10,
+ 26,
+ 10,
+ 0,
+ 0,
+ 0,
+ 13,
+ 73,
+ 72,
+ 68,
+ 82,
+ 0,
+ 0,
+ w >> 8,
+ w & 255,
+ 0,
+ 0,
+ h >> 8,
+ h & 255,
+ 8,
+ 6,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ idat >>> 24,
+ (idat >> 16) & 255,
+ (idat >> 8) & 255,
+ idat & 255,
+ 73,
+ 68,
+ 65,
+ 84,
+ 120,
+ 1,
+ ];
+ const table = [
+ 0, 498536548, 997073096, 651767980, 1994146192, 1802195444, 1303535960,
+ 1342533948, -306674912, -267414716, -690576408, -882789492, -1687895376,
+ -2032938284, -1609899400, -1111625188,
+ ];
+ let a = 1;
+ let b = 0;
+ for (let y = 0, i = 0, end = row - 1; y < h; y++, end += row - 1) {
+ bytes.push(
+ y + 1 < h ? 0 : 1,
+ row & 255,
+ row >> 8,
+ ~row & 255,
+ (row >> 8) ^ 255,
+ 0,
+ );
+ for (b = (b + a) % 65521; i < end; i++) {
+ const u = rgba[i]! & 255;
+ bytes.push(u);
+ a = (a + u) % 65521;
+ b = (b + a) % 65521;
+ }
+ }
+ bytes.push(
+ b >> 8,
+ b & 255,
+ a >> 8,
+ a & 255,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 73,
+ 69,
+ 78,
+ 68,
+ 174,
+ 66,
+ 96,
+ 130,
+ );
+ const chunks: [number, number][] = [
+ [12, 29],
+ [37, 41 + idat],
+ ];
+ for (const [start, initialEnd] of chunks) {
+ const end = initialEnd;
+ let c = ~0;
+ for (let i = start; i < end; i++) {
+ c ^= bytes[i]!;
+ c = (c >>> 4) ^ table[c & 15]!;
+ c = (c >>> 4) ^ table[c & 15]!;
+ }
+ c = ~c;
+ bytes[end] = c >>> 24;
+ bytes[end + 1] = (c >> 16) & 255;
+ bytes[end + 2] = (c >> 8) & 255;
+ bytes[end + 3] = c & 255;
+ }
+ return `data:image/png;base64,${bytesToBase64(bytes)}`;
+}
+
+/**
+ * Decodes a ThumbHash to a PNG data URL.
+ *
+ * @param hash The bytes of the ThumbHash.
+ * @returns A data URL containing a PNG for the rendered ThumbHash.
+ */
+export function thumbHashToDataURL(hash: Uint8Array) {
+ const image = thumbHashToRGBA(hash);
+ return rgbaToDataURL(image.w, image.h, image.rgba);
+}
+
+export const thumbHashToBase64 = (hash: Uint8Array) => bytesToBase64(hash);
+
+const minThumbHashBytes = 5;
+const maxThumbHashBytes = 25;
+const maxThumbHashBase64Length = 36;
+
+export const thumbHashDataURLFromBase64 = (hash: string | undefined) => {
+ if (
+ !hash ||
+ hash.length > maxThumbHashBase64Length ||
+ typeof atob != "function" ||
+ typeof btoa != "function"
+ ) {
+ return undefined;
+ }
+ try {
+ const bytes = base64ToBytes(hash);
+ if (
+ bytes.length < minThumbHashBytes ||
+ bytes.length > maxThumbHashBytes
+ ) {
+ return undefined;
+ }
+ return thumbHashToDataURL(bytes);
+ } catch {
+ return undefined;
+ }
+};
+
+export const thumbHashBase64FromCanvas = (canvas: HTMLCanvasElement) => {
+ const scale = Math.min(100 / canvas.width, 100 / canvas.height, 1);
+ const width = Math.max(1, Math.round(canvas.width * scale));
+ const height = Math.max(1, Math.round(canvas.height * scale));
+ const thumbCanvas = document.createElement("canvas");
+ thumbCanvas.width = width;
+ thumbCanvas.height = height;
+
+ const context = thumbCanvas.getContext("2d");
+ if (!context) throw new Error("Could not create ThumbHash canvas");
+
+ context.drawImage(canvas, 0, 0, width, height);
+ const rgba = context.getImageData(0, 0, width, height).data;
+ return thumbHashToBase64(rgbaToThumbHash(width, height, rgba));
+};