Skip to content

armgit / ente

Public Imported from GitHub
0

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

Optimize social image uploads

Anand Baburajan45022edb6f50
diff --git a/web/apps/social/next.config.js b/web/apps/social/next.config.js
index 736f640b5f..fc60f17a60 100644
--- a/web/apps/social/next.config.js
+++ b/web/apps/social/next.config.js
@@ -2,6 +2,9 @@ const baseConfig = require("ente-base/next.config.base.js");
module.exports = {
...baseConfig,
+ transpilePackages: Array.from(
+ new Set([...(baseConfig.transpilePackages || []), "ente-media"]),
+ ),
// Static deployments serve arbitrary profile links through index.html.
// In development, mirror that behavior with a fallback rewrite.
...(process.env.NODE_ENV === "development" && {
diff --git a/web/apps/social/package.json b/web/apps/social/package.json
index 66ac26e9c7..42b90e6499 100644
--- a/web/apps/social/package.json
+++ b/web/apps/social/package.json
@@ -7,6 +7,7 @@
"@hugeicons/react": "^1.1.4",
"ente-accounts-rs": "*",
"ente-base": "*",
+ "ente-media": "*",
"ente-wasm": "*",
"photoswipe": "^5.4.4"
},
diff --git a/web/apps/social/src/pages/app/index.tsx b/web/apps/social/src/pages/app/index.tsx
index 0460945e60..479c76f29f 100644
--- a/web/apps/social/src/pages/app/index.tsx
+++ b/web/apps/social/src/pages/app/index.tsx
@@ -18,18 +18,13 @@ import { firstNameFrom } from "utils/socialDisplay";
import { socialRoutes } from "utils/socialRoutes";
import { socialPostToViewerPhoto } from "utils/socialWallDisplay";
-const loadingHomeProfile = {
- avatarUrl: null,
- fullName: "",
- username: "",
-};
+const loadingHomeProfile = { avatarUrl: null, fullName: "", username: "" };
const Page: React.FC = () => {
const router = useRouter();
const { friends, profile, profileLoadStatus, setFriends } =
useSocialAppState();
- const [addedFriendToastName, setAddedFriendToastName] =
- useState<string>();
+ const [addedFriendToastName, setAddedFriendToastName] = useState<string>();
const [feedItems, setFeedItems] = useState<SocialWallPost[]>([]);
const [isFeedLoading, setIsFeedLoading] = useState(true);
const closeAddedFriendToast = React.useCallback(
@@ -102,12 +97,14 @@ const Page: React.FC = () => {
isFeedLoading={isFeedLoading}
profile={screenProfile}
onAddedFriendToastClose={closeAddedFriendToast}
- onCreatePost={async (file, caption) => {
+ onCreatePost={async (image, caption) => {
if (!profile?.wallId) throw new Error("Missing wall.");
const post = await createCurrentPhotoPost({
caption,
- file,
+ file: image.file,
+ height: image.height,
wallId: profile.wallId,
+ width: image.width,
});
if (!post) throw new Error("Couldn't create post.");
setFeedItems((currentItems) => [post, ...currentItems]);
diff --git a/web/apps/social/src/pages/app/profile.tsx b/web/apps/social/src/pages/app/profile.tsx
index 22fe1b4518..e19c79760e 100644
--- a/web/apps/social/src/pages/app/profile.tsx
+++ b/web/apps/social/src/pages/app/profile.tsx
@@ -26,7 +26,10 @@ const Page: React.FC = () => {
useSocialAppState();
const [posts, setPosts] = useState<SocialWallPost[]>([]);
const [isPostsLoading, setIsPostsLoading] = useState(true);
- const postGroups = useMemo(() => profilePostGroupsFromPosts(posts), [posts]);
+ const postGroups = useMemo(
+ () => profilePostGroupsFromPosts(posts),
+ [posts],
+ );
useEffect(() => {
if (profileLoadStatus == "ready" && !profile) {
@@ -79,12 +82,14 @@ const Page: React.FC = () => {
postGroups={postGroups}
profile={profile}
onBack={() => void router.push(socialRoutes.home)}
- onCreatePost={async (file, caption) => {
+ onCreatePost={async (image, caption) => {
if (!profile.wallId) throw new Error("Missing wall.");
const post = await createCurrentPhotoPost({
caption,
- file,
+ file: image.file,
+ height: image.height,
wallId: profile.wallId,
+ width: image.width,
});
if (!post) throw new Error("Couldn't create post.");
setPosts((currentPosts) => [post, ...currentPosts]);
diff --git a/web/apps/social/src/screens/HomeScreen.tsx b/web/apps/social/src/screens/HomeScreen.tsx
index f9ab2ebfb8..461b9f4ae2 100644
--- a/web/apps/social/src/screens/HomeScreen.tsx
+++ b/web/apps/social/src/screens/HomeScreen.tsx
@@ -20,15 +20,17 @@ import React, { useState } from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
import { ShareIcon } from "screens/ShareProfileLinkScreen";
import type { SocialWallPost } from "services/socialWall";
-import {
- createLocalPostPhoto,
- type LocalPostPhotoDimensions,
-} from "utils/localPostPhoto";
+import { createLocalPostPhoto } from "utils/localPostPhoto";
import {
firstNameFrom,
formatSocialDate,
initialsFor,
} from "utils/socialDisplay";
+import {
+ prepareSocialPostImage,
+ socialPostImageInputAccept,
+ type PreparedSocialPostImage,
+} from "utils/socialPostImage";
export const homeBackground = "#FFFFFF";
@@ -54,7 +56,10 @@ interface HomeScreenProps {
friendsCount: number;
isFeedLoading?: boolean;
onAddedFriendToastClose?: () => void;
- onCreatePost?: (file: File, caption: string) => Promise<SocialViewerPhoto>;
+ onCreatePost?: (
+ image: PreparedSocialPostImage,
+ caption: string,
+ ) => Promise<SocialViewerPhoto>;
onOpenFriend?: (friendID: string) => void;
onOpenNotifications?: () => void;
onOpenProfile?: () => void;
@@ -70,7 +75,7 @@ interface FeedPhotoDimensions {
}
interface SelectedHomeViewer {
- draftFile?: File;
+ draftImage?: PreparedSocialPostImage;
initialScreen: SocialViewerInitialScreen;
localObjectUrl?: string;
photo: SocialViewerPhoto;
@@ -563,19 +568,6 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
URL.revokeObjectURL(objectUrl);
localPostObjectUrlsRef.current.delete(objectUrl);
}, []);
- const applyLocalPostDimensions = React.useCallback(
- (objectUrl: string, dimensions: LocalPostPhotoDimensions) => {
- setSelectedViewer((currentViewer) =>
- currentViewer?.localObjectUrl == objectUrl
- ? {
- ...currentViewer,
- photo: { ...currentViewer.photo, ...dimensions },
- }
- : currentViewer,
- );
- },
- [],
- );
const openPostPhotoPicker = () => postInputRef.current?.click();
const openFeedPhoto = (
photo: SocialViewerPhoto,
@@ -609,22 +601,17 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
await navigator.clipboard.writeText(profileLink);
};
- const handlePostPhotoSelect: React.ChangeEventHandler<HTMLInputElement> = (
- event,
- ) => {
- const file = event.target.files?.[0];
- event.target.value = "";
- if (!file) return;
-
+ const prepareSelectedPostPhoto = async (file: File) => {
+ const image = await prepareSocialPostImage(file);
const localPost = createLocalPostPhoto({
avatarUrl: profile.avatarUrl,
- file,
+ dimensions: image,
+ file: image.file,
name: initialsSource || "You",
- onDimensionsLoaded: applyLocalPostDimensions,
});
localPostObjectUrlsRef.current.add(localPost.objectUrl);
setSelectedViewer({
- draftFile: file,
+ draftImage: image,
initialScreen: "photo",
localObjectUrl: localPost.objectUrl,
photo: localPost.photo,
@@ -632,6 +619,18 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
});
};
+ const handlePostPhotoSelect: React.ChangeEventHandler<HTMLInputElement> = (
+ event,
+ ) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (!file) return;
+
+ void prepareSelectedPostPhoto(file).catch((error: unknown) =>
+ console.error("Failed to prepare post photo", error),
+ );
+ };
+
React.useEffect(
() => () => {
localPostObjectUrlsRef.current.forEach((objectUrl) =>
@@ -682,7 +681,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
ref={postInputRef}
component="input"
type="file"
- accept="image/*"
+ accept={socialPostImageInputAccept}
onChange={handlePostPhotoSelect}
sx={{ display: "none" }}
/>
@@ -1009,12 +1008,12 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
}
onLoadPostLikers={onLoadPostLikers}
onPublishDraftPost={
- selectedViewer.draftFile && onCreatePost
+ selectedViewer.draftImage && onCreatePost
? async (caption) => {
const localObjectUrl =
selectedViewer.localObjectUrl;
const post = await onCreatePost(
- selectedViewer.draftFile!,
+ selectedViewer.draftImage!,
caption,
);
revokeLocalPostObjectUrl(localObjectUrl);
diff --git a/web/apps/social/src/screens/ProfileScreen.tsx b/web/apps/social/src/screens/ProfileScreen.tsx
index 8f2c9e3e95..0d6731868c 100644
--- a/web/apps/social/src/screens/ProfileScreen.tsx
+++ b/web/apps/social/src/screens/ProfileScreen.tsx
@@ -18,11 +18,13 @@ import { EnteLogo } from "ente-base/components/EnteLogo";
import React, { useState } from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
import { LinkIcon, ShareIcon } from "screens/ShareProfileLinkScreen";
-import {
- createLocalPostPhoto,
- type LocalPostPhotoDimensions,
-} from "utils/localPostPhoto";
+import { createLocalPostPhoto } from "utils/localPostPhoto";
import { firstNameFrom, initialsFor } from "utils/socialDisplay";
+import {
+ prepareSocialPostImage,
+ socialPostImageInputAccept,
+ type PreparedSocialPostImage,
+} from "utils/socialPostImage";
export const profileBackground = "#FFFFFF";
@@ -68,7 +70,7 @@ export interface ProfilePostGroup {
}
interface SelectedProfilePost {
- draftFile?: File;
+ draftImage?: PreparedSocialPostImage;
id: string;
localObjectUrl?: string;
photo: SocialViewerPhoto;
@@ -136,7 +138,10 @@ interface ProfileScreenProps {
isPostsLoading?: boolean;
onAddFriend?: () => void;
onBack?: () => void;
- onCreatePost?: (file: File, caption: string) => Promise<SocialViewerPhoto>;
+ onCreatePost?: (
+ image: PreparedSocialPostImage,
+ caption: string,
+ ) => Promise<SocialViewerPhoto>;
onDeletePost?: (postId: number) => Promise<void> | void;
onLoadPostLikers?: (postId: number) => Promise<SocialLiker[]>;
onOpenFriend?: (friendID: string) => void;
@@ -229,19 +234,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
URL.revokeObjectURL(objectUrl);
localPostObjectUrlsRef.current.delete(objectUrl);
}, []);
- const applyLocalPostDimensions = React.useCallback(
- (objectUrl: string, dimensions: LocalPostPhotoDimensions) => {
- setSelectedPost((currentPost) =>
- currentPost?.localObjectUrl == objectUrl
- ? {
- ...currentPost,
- photo: { ...currentPost.photo, ...dimensions },
- }
- : currentPost,
- );
- },
- [],
- );
const openPostPhotoPicker = () => postInputRef.current?.click();
const closeSelectedPost = () => {
const localObjectUrl = selectedPost?.localObjectUrl;
@@ -270,22 +262,17 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
});
};
- const handlePostPhotoSelect: React.ChangeEventHandler<HTMLInputElement> = (
- event,
- ) => {
- const file = event.target.files?.[0];
- event.target.value = "";
- if (!file) return;
-
+ const prepareSelectedPostPhoto = async (file: File) => {
+ const image = await prepareSocialPostImage(file);
const localPost = createLocalPostPhoto({
avatarUrl: profile.avatarUrl,
- file,
+ dimensions: image,
+ file: image.file,
name: displayName || "You",
- onDimensionsLoaded: applyLocalPostDimensions,
});
localPostObjectUrlsRef.current.add(localPost.objectUrl);
setSelectedPost({
- draftFile: file,
+ draftImage: image,
id: `local-${localPost.photo.timestampMs}`,
localObjectUrl: localPost.objectUrl,
photo: localPost.photo,
@@ -293,6 +280,18 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
});
};
+ const handlePostPhotoSelect: React.ChangeEventHandler<HTMLInputElement> = (
+ event,
+ ) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (!file) return;
+
+ void prepareSelectedPostPhoto(file).catch((error: unknown) =>
+ console.error("Failed to prepare post photo", error),
+ );
+ };
+
const copyProfileURL = async () => {
clearProfileLinkCopiedTimer();
if (!onShareProfileLink) {
@@ -379,7 +378,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
ref={postInputRef}
component="input"
type="file"
- accept="image/*"
+ accept={socialPostImageInputAccept}
onChange={handlePostPhotoSelect}
sx={{ display: "none" }}
/>
@@ -1028,8 +1027,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
likeCount:
item.likeCount,
name: displayName,
- postId:
- item.postId,
+ postId: item.postId,
timestampMs:
item.timestampMs,
viewerLiked:
@@ -1223,12 +1221,12 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
}
onOpenProfile={closeSelectedPost}
onPublishDraftPost={
- selectedPost.draftFile && onCreatePost
+ selectedPost.draftImage && onCreatePost
? async (caption) => {
const localObjectUrl =
selectedPost.localObjectUrl;
const post = await onCreatePost(
- selectedPost.draftFile!,
+ selectedPost.draftImage!,
caption,
);
revokeLocalPostObjectUrl(localObjectUrl);
diff --git a/web/apps/social/src/screens/SetupProfileScreen.tsx b/web/apps/social/src/screens/SetupProfileScreen.tsx
index 9ff9751571..becb73ab3f 100644
--- a/web/apps/social/src/screens/SetupProfileScreen.tsx
+++ b/web/apps/social/src/screens/SetupProfileScreen.tsx
@@ -1,5 +1,9 @@
import { Box } from "@mui/material";
import React, { useEffect, useRef, useState } from "react";
+import {
+ prepareSocialAvatarImage,
+ socialAvatarImageInputAccept,
+} from "utils/socialPostImage";
export const setupProfileBackground = "#FAFAFA";
@@ -250,6 +254,7 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
const [username, setUsername] = useState("");
const [fullName, setFullName] = useState("");
const avatarUrlRef = useRef<string | null>(null);
+ const avatarSelectionIDRef = useRef(0);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const canContinue =
@@ -265,30 +270,40 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
[],
);
+ const prepareSelectedAvatar = async (file: File, selectionID: number) => {
+ try {
+ const avatar = await prepareSocialAvatarImage(file);
+ if (avatarSelectionIDRef.current != selectionID) return;
+ if (avatar.file.size > maxAvatarBytes) {
+ setAvatarError("Choose an image under 19 MB.");
+ return;
+ }
+
+ if (avatarUrlRef.current) URL.revokeObjectURL(avatarUrlRef.current);
+ const nextUrl = URL.createObjectURL(avatar.file);
+ avatarUrlRef.current = nextUrl;
+ setAvatarError(undefined);
+ setAvatarFile(avatar.file);
+ setAvatarUrl(nextUrl);
+ } catch (error) {
+ if (avatarSelectionIDRef.current != selectionID) return;
+ console.error("Failed to prepare social avatar", error);
+ setAvatarError("Choose a JPEG, PNG, WebP, HEIC, or HEIF image.");
+ }
+ };
+
const handleAvatarChange: React.ChangeEventHandler<HTMLInputElement> = (
event,
) => {
const file = event.target.files?.[0];
+ event.target.value = "";
if (!file) return;
- if (!file.type.startsWith("image/")) {
- setAvatarError("Choose an image file.");
- event.target.value = "";
- return;
- }
- if (file.size > maxAvatarBytes) {
- setAvatarError("Choose an image under 19 MB.");
- event.target.value = "";
- return;
- }
-
- if (avatarUrlRef.current) URL.revokeObjectURL(avatarUrlRef.current);
- const nextUrl = URL.createObjectURL(file);
- avatarUrlRef.current = nextUrl;
+ const selectionID = avatarSelectionIDRef.current + 1;
+ avatarSelectionIDRef.current = selectionID;
setAvatarError(undefined);
- setAvatarFile(file);
- setAvatarUrl(nextUrl);
- event.target.value = "";
+
+ void prepareSelectedAvatar(file, selectionID);
};
const handleUsernameChange = (value: string) => {
@@ -407,7 +422,7 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
<Box
component="input"
ref={fileInputRef}
- accept="image/*"
+ accept={socialAvatarImageInputAccept}
onChange={handleAvatarChange}
type="file"
sx={{ display: "none" }}
diff --git a/web/apps/social/src/services/socialWall.ts b/web/apps/social/src/services/socialWall.ts
index bededc8565..bf37776e1e 100644
--- a/web/apps/social/src/services/socialWall.ts
+++ b/web/apps/social/src/services/socialWall.ts
@@ -414,21 +414,27 @@ export const loadCurrentWallPostsPage = async (
export const createCurrentPhotoPost = async ({
caption,
file,
+ height,
wallId,
+ width,
}: {
caption?: string;
file: File;
+ height?: number;
wallId: string;
+ width?: number;
}) => {
const ctx = await ensureCurrentWallContext();
try {
const bytes = new Uint8Array(await file.arrayBuffer());
+ const normalizedWidth = normalizedImageDimension(width);
+ const normalizedHeight = normalizedImageDimension(height);
const created = (await ctx.create_photo_post(
wallId,
bytes,
caption?.trim() || null,
- null,
- null,
+ normalizedWidth,
+ normalizedHeight,
file.type || null,
)) as WallPost;
return await postFromAccountPost(ctx, created);
@@ -437,6 +443,11 @@ export const createCurrentPhotoPost = async ({
}
};
+const normalizedImageDimension = (dimension: number | undefined) =>
+ typeof dimension == "number" && Number.isFinite(dimension) && dimension > 0
+ ? Math.round(dimension)
+ : null;
+
export const setCurrentPostLiked = async (postId: number, liked: boolean) => {
const ctx = await ensureCurrentWallContext();
try {
diff --git a/web/apps/social/src/utils/localPostPhoto.ts b/web/apps/social/src/utils/localPostPhoto.ts
index 9fb1e6725b..5e9a7f3a8d 100644
--- a/web/apps/social/src/utils/localPostPhoto.ts
+++ b/web/apps/social/src/utils/localPostPhoto.ts
@@ -12,6 +12,7 @@ export interface LocalPostPhoto {
interface CreateLocalPostPhotoAttributes {
avatarUrl?: string | null;
+ dimensions?: LocalPostPhotoDimensions;
file: File;
name: string;
onDimensionsLoaded?: (
@@ -22,6 +23,7 @@ interface CreateLocalPostPhotoAttributes {
export const createLocalPostPhoto = ({
avatarUrl,
+ dimensions,
file,
name,
onDimensionsLoaded,
@@ -30,11 +32,15 @@ export const createLocalPostPhoto = ({
const photo: SocialViewerPhoto = {
alt: `${name} post`,
avatarUrl,
+ height: dimensions?.height,
imageUrl: objectUrl,
name,
timestampMs: Date.now(),
+ width: dimensions?.width,
};
+ if (dimensions) return { objectUrl, photo };
+
const image = new Image();
image.onload = () => {
const { naturalHeight, naturalWidth } = image;
diff --git a/web/apps/social/src/utils/socialPostImage.ts b/web/apps/social/src/utils/socialPostImage.ts
new file mode 100644
index 0000000000..88463dfbb6
--- /dev/null
+++ b/web/apps/social/src/utils/socialPostImage.ts
@@ -0,0 +1,207 @@
+import { lowercaseExtension, nameAndExtension } from "ente-base/file-name";
+import { isHEICExtension } from "ente-media/formats";
+import { heicToJPEG } from "ente-media/heic-convert";
+
+export interface PreparedSocialImage {
+ file: File;
+ height: number;
+ width: number;
+}
+
+export type PreparedSocialAvatarImage = PreparedSocialImage;
+export type PreparedSocialPostImage = PreparedSocialImage;
+
+export const socialAvatarImageInputAccept =
+ "image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif";
+export const socialPostImageInputAccept =
+ "image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif";
+
+const socialAvatarImageMaxEdge = 512;
+const socialPostImageMaxLongEdge = 2560;
+const socialPostImageWebPQuality = 0.85;
+const socialPostImageMimeType = "image/webp";
+
+export const prepareSocialPostImage = async (
+ file: File,
+): Promise<PreparedSocialPostImage> => {
+ const renderableBlob = await renderableBlobForSocialImage(file);
+ const { blob, height, width } = await webPBlobFromImage(
+ renderableBlob,
+ postCanvasPlan,
+ );
+
+ return {
+ file: new File([blob], webPFileName(file.name), {
+ lastModified: file.lastModified || Date.now(),
+ type: socialPostImageMimeType,
+ }),
+ height,
+ width,
+ };
+};
+
+export const prepareSocialAvatarImage = async (
+ file: File,
+): Promise<PreparedSocialAvatarImage> => {
+ const renderableBlob = await renderableBlobForSocialImage(file);
+ const { blob, height, width } = await webPBlobFromImage(
+ renderableBlob,
+ avatarCanvasPlan,
+ );
+
+ return {
+ file: new File([blob], webPFileName(file.name), {
+ lastModified: file.lastModified || Date.now(),
+ type: socialPostImageMimeType,
+ }),
+ height,
+ width,
+ };
+};
+
+const renderableBlobForSocialImage = async (file: File): Promise<Blob> => {
+ const extension = lowercaseExtension(file.name);
+ const mediaType = file.type.toLowerCase();
+ const isHEIC =
+ (extension != undefined && isHEICExtension(extension)) ||
+ mediaType == "image/heic" ||
+ mediaType == "image/heif";
+
+ return isHEIC ? await heicToJPEG(file) : file;
+};
+
+interface CanvasPlan {
+ height: number;
+ sourceHeight: number;
+ sourceWidth: number;
+ sourceX: number;
+ sourceY: number;
+ width: number;
+}
+
+const webPBlobFromImage = async (
+ blob: Blob,
+ planForSource: (width: number, height: number) => CanvasPlan,
+): Promise<{ blob: Blob; height: number; width: number }> => {
+ const imageURL = URL.createObjectURL(blob);
+ try {
+ const image = await loadImage(imageURL);
+ const plan = planForSource(
+ image.naturalWidth || image.width,
+ image.naturalHeight || image.height,
+ );
+ if (plan.width <= 0 || plan.height <= 0) {
+ throw new Error("Invalid image dimensions");
+ }
+
+ const canvas = document.createElement("canvas");
+ canvas.width = plan.width;
+ canvas.height = plan.height;
+
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Could not create image canvas");
+
+ context.drawImage(
+ image,
+ plan.sourceX,
+ plan.sourceY,
+ plan.sourceWidth,
+ plan.sourceHeight,
+ 0,
+ 0,
+ plan.width,
+ plan.height,
+ );
+
+ return {
+ blob: await canvasToBlob(canvas, socialPostImageMimeType),
+ height: plan.height,
+ width: plan.width,
+ };
+ } finally {
+ URL.revokeObjectURL(imageURL);
+ }
+};
+
+const loadImage = async (imageURL: string) =>
+ await new Promise<HTMLImageElement>((resolve, reject) => {
+ const image = new Image();
+ image.decoding = "async";
+ image.onload = () => resolve(image);
+ image.onerror = () => reject(new Error("Could not decode image"));
+ image.src = imageURL;
+ });
+
+const postCanvasPlan = (width: number, height: number): CanvasPlan => {
+ const dimensions = scaledDimensions(
+ width,
+ height,
+ socialPostImageMaxLongEdge,
+ );
+ return {
+ ...dimensions,
+ sourceHeight: height,
+ sourceWidth: width,
+ sourceX: 0,
+ sourceY: 0,
+ };
+};
+
+const avatarCanvasPlan = (width: number, height: number): CanvasPlan => {
+ if (width <= 0 || height <= 0) {
+ return {
+ height: 0,
+ sourceHeight: 0,
+ sourceWidth: 0,
+ sourceX: 0,
+ sourceY: 0,
+ width: 0,
+ };
+ }
+
+ const sourceEdge = Math.min(width, height);
+ const outputEdge = Math.min(sourceEdge, socialAvatarImageMaxEdge);
+ return {
+ height: outputEdge,
+ sourceHeight: sourceEdge,
+ sourceWidth: sourceEdge,
+ sourceX: Math.floor((width - sourceEdge) / 2),
+ sourceY: Math.floor((height - sourceEdge) / 2),
+ width: outputEdge,
+ };
+};
+
+const scaledDimensions = (
+ width: number,
+ height: number,
+ maxLongEdge: number,
+): { height: number; width: number } => {
+ if (width <= 0 || height <= 0) return { height: 0, width: 0 };
+
+ const longEdge = Math.max(width, height);
+ if (longEdge <= maxLongEdge) {
+ return { height, width };
+ }
+
+ const scale = maxLongEdge / longEdge;
+ return {
+ height: Math.max(1, Math.round(height * scale)),
+ width: Math.max(1, Math.round(width * scale)),
+ };
+};
+
+const canvasToBlob = async (
+ canvas: HTMLCanvasElement,
+ mediaType: string,
+): Promise<Blob> => {
+ const blob = await new Promise<Blob | null>((resolve) =>
+ canvas.toBlob(resolve, mediaType, socialPostImageWebPQuality),
+ );
+ if (!blob) throw new Error("Could not encode image");
+ return blob;
+};
+
+const webPFileName = (fileName: string) => {
+ const [name] = nameAndExtension(fileName.trim());
+ return `${name || "post"}.webp`;
+};