π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add social onboarding avatar cropper
Anand Baburajane67aa011b202
diff --git a/web/apps/social/package.json b/web/apps/social/package.jsonindex 42b90e6499..f2468ca72b 100644--- a/web/apps/social/package.json+++ b/web/apps/social/package.json@@ -9,7 +9,8 @@"ente-base": "*","ente-media": "*","ente-wasm": "*",- "photoswipe": "^5.4.4"+ "photoswipe": "^5.4.4",+ "react-easy-crop": "^5.5.7"},"devDependencies": {"ente-build-config": "*"diff --git a/web/apps/social/src/pages/_app.tsx b/web/apps/social/src/pages/_app.tsxindex 8149bf8b58..639cc64ffa 100644--- a/web/apps/social/src/pages/_app.tsx+++ b/web/apps/social/src/pages/_app.tsx@@ -7,6 +7,7 @@ import { shareTheme } from "ente-base/components/utils/theme";import type { AppProps } from "next/app";import "photoswipe/dist/photoswipe.css";import React from "react";+import "react-easy-crop/react-easy-crop.css";import { SocialAppStateProvider } from "state/SocialAppStateProvider";import "styles/globals.css";diff --git a/web/apps/social/src/screens/SetupProfileScreen.tsx b/web/apps/social/src/screens/SetupProfileScreen.tsxindex becb73ab3f..9db7ddcbbc 100644--- a/web/apps/social/src/screens/SetupProfileScreen.tsx+++ b/web/apps/social/src/screens/SetupProfileScreen.tsx@@ -1,7 +1,9 @@import { Box } from "@mui/material";import React, { useEffect, useRef, useState } from "react";+import Cropper, { type Area, type Point } from "react-easy-crop";import {- prepareSocialAvatarImage,+ prepareSocialAvatarImageFromCrop,+ socialAvatarCropImageForFile,socialAvatarImageInputAccept,} from "utils/socialPostImage";@@ -13,7 +15,8 @@ const textLight = "#969696";const warning = "#F63A3A";const paleGreen = "#E7F6E9";const setupProfileFormID = "social-setup-profile-form";-const maxAvatarBytes = 19 * 1024 * 1024;+const maxAvatarBytes = 10 * 1024 * 1024;+const maxAvatarSizeMessage = "Choose an image under 10 MB.";export interface SetupProfile {avatarUrl: string | null;@@ -29,6 +32,11 @@ export interface SetupProfileInput extends SetupProfile {avatarFile?: File | null;}+interface AvatarCropImage {+ file: File;+ url: string;+}+interface SetupProfileScreenProps {ctaLabel?: string;errorMessage?: string;@@ -48,6 +56,20 @@ interface TextInputProps {value?: string;}+interface AvatarCropDialogProps {+ crop: Point;+ imageURL: string;+ isDoneDisabled?: boolean;+ isSaving?: boolean;+ onCancel: () => void;+ onChooseAnother: () => void;+ onCropChange: (crop: Point) => void;+ onCropComplete: (croppedArea: Area, croppedAreaPixels: Area) => void;+ onDone: () => void;+ onZoomChange: (zoom: number) => void;+ zoom: number;+}+const BackIcon: React.FC = () => (<Boxcomponent="svg"@@ -239,6 +261,203 @@ const TextInput: React.FC<TextInputProps> = ({</Box>);+const AvatarCropDialogButton: React.FC<{+ children: React.ReactNode;+ disabled?: boolean;+ onClick?: () => void;+ variant: "primary" | "secondary";+}> = ({ children, disabled = false, onClick, variant }) => (+ <Box+ className={variant == "primary" && !disabled ? "green-bg" : undefined}+ component="button"+ type="button"+ disabled={disabled}+ onClick={onClick}+ sx={{+ alignItems: "center",+ bgcolor:+ variant == "primary"+ ? disabled+ ? "#F5F5F5"+ : green+ : "transparent",+ border: variant == "primary" ? 0 : "1px solid #E6E6E6",+ borderRadius: "20px",+ color:+ variant == "primary"+ ? disabled+ ? textLight+ : "white"+ : textBase,+ cursor: disabled ? "default" : "pointer",+ display: "flex",+ flex: "1 1 0",+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ fontWeight: 500,+ height: 44,+ justifyContent: "center",+ lineHeight: "20px",+ minWidth: 0,+ px: 2,+ "&:focus-visible": {+ outline: `2px solid ${green}`,+ outlineOffset: 3,+ },+ "&:hover":+ !disabled && variant == "primary"+ ? { bgcolor: "#07AE22" }+ : undefined,+ }}+ >+ {children}+ </Box>+);++const AvatarCropDialog: React.FC<AvatarCropDialogProps> = ({+ crop,+ imageURL,+ isDoneDisabled = false,+ isSaving = false,+ onCancel,+ onChooseAnother,+ onCropChange,+ onCropComplete,+ onDone,+ onZoomChange,+ zoom,+}) => (+ <Box+ aria-labelledby="social-avatar-editor-title"+ aria-modal="true"+ role="dialog"+ sx={{+ alignItems: "center",+ bgcolor: "rgba(0, 0, 0, 0.42)",+ boxSizing: "border-box",+ display: "flex",+ inset: 0,+ justifyContent: "center",+ p: 3,+ position: "fixed",+ zIndex: 20,+ }}+ >+ <Box+ sx={{+ bgcolor: "white",+ borderRadius: "8px",+ boxShadow: "0 20px 60px rgba(0, 0, 0, 0.24)",+ boxSizing: "border-box",+ maxWidth: 342,+ p: 3,+ width: "100%",+ }}+ >+ <Box+ component="h2"+ id="social-avatar-editor-title"+ sx={{+ color: textBase,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 18,+ fontWeight: 600,+ lineHeight: "24px",+ m: 0,+ textAlign: "center",+ }}+ >+ Profile picture+ </Box>++ <Box+ sx={{+ bgcolor: "#111",+ borderRadius: "8px",+ height: 282,+ mt: 3,+ overflow: "hidden",+ position: "relative",+ width: "100%",+ }}+ >+ <Cropper+ aspect={1}+ crop={crop}+ cropShape="round"+ disableAutomaticStylesInjection+ image={imageURL}+ maxZoom={3}+ minZoom={1}+ objectFit="cover"+ onCropChange={onCropChange}+ onCropComplete={onCropComplete}+ onZoomChange={onZoomChange}+ showGrid={false}+ zoom={zoom}+ />+ </Box>++ <Box sx={{ mt: 3, width: "100%" }}>+ <Box+ component="label"+ htmlFor="social-avatar-zoom"+ sx={{+ color: textBase,+ display: "block",+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 13,+ fontWeight: 500,+ lineHeight: "18px",+ mb: "10px",+ }}+ >+ Zoom+ </Box>+ <Box+ component="input"+ id="social-avatar-zoom"+ type="range"+ min={1}+ max={3}+ step={0.01}+ value={zoom}+ onChange={(event) =>+ onZoomChange(Number(event.target.value))+ }+ sx={{ accentColor: green, display: "block", width: "100%" }}+ />+ </Box>++ <Box sx={{ display: "flex", gap: "10px", mt: 3, width: "100%" }}>+ <AvatarCropDialogButton+ disabled={isSaving}+ variant="secondary"+ onClick={onChooseAnother}+ >+ Choose another+ </AvatarCropDialogButton>+ <AvatarCropDialogButton+ disabled={isSaving}+ variant="secondary"+ onClick={onCancel}+ >+ Cancel+ </AvatarCropDialogButton>+ </Box>+ <Box sx={{ display: "flex", mt: "10px", width: "100%" }}>+ <AvatarCropDialogButton+ disabled={isSaving || isDoneDisabled}+ variant="primary"+ onClick={onDone}+ >+ {isSaving ? "Saving..." : "Done"}+ </AvatarCropDialogButton>+ </Box>+ </Box>+ </Box>+);+export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({ctaLabel = "Next",errorMessage,@@ -250,45 +469,83 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({}) => {const [avatarFile, setAvatarFile] = useState<File | null>(null);const [avatarUrl, setAvatarUrl] = useState<string | null>(null);+ const [avatarCropImage, setAvatarCropImage] =+ useState<AvatarCropImage | null>(null);+ const [avatarCrop, setAvatarCrop] = useState<Point>({ x: 0, y: 0 });+ const [avatarCropPixels, setAvatarCropPixels] = useState<Area | null>(null);const [avatarError, setAvatarError] = useState<string>();+ const [avatarZoom, setAvatarZoom] = useState(1);const [username, setUsername] = useState("");const [fullName, setFullName] = useState("");+ const [isApplyingAvatarCrop, setIsApplyingAvatarCrop] = useState(false);+ const [isPreparingAvatar, setIsPreparingAvatar] = useState(false);+ const avatarCropUrlRef = useRef<string | null>(null);const avatarUrlRef = useRef<string | null>(null);const avatarSelectionIDRef = useRef(0);const fileInputRef = useRef<HTMLInputElement | null>(null);const canContinue =!isSubmitting &&+ !avatarCropImage &&+ !isApplyingAvatarCrop &&+ !isPreparingAvatar &&usernameStatus != "unavailable" &&username.trim().length > 0 &&fullName.trim().length > 0;useEffect(() => () => {+ if (avatarCropUrlRef.current) {+ URL.revokeObjectURL(avatarCropUrlRef.current);+ }if (avatarUrlRef.current) URL.revokeObjectURL(avatarUrlRef.current);},[],);+ const clearAvatarCropImage = () => {+ avatarSelectionIDRef.current += 1;+ if (avatarCropUrlRef.current) {+ URL.revokeObjectURL(avatarCropUrlRef.current);+ avatarCropUrlRef.current = null;+ }+ setAvatarCropImage(null);+ setAvatarCrop({ x: 0, y: 0 });+ setAvatarCropPixels(null);+ setAvatarZoom(1);+ setIsApplyingAvatarCrop(false);+ setIsPreparingAvatar(false);+ };+const prepareSelectedAvatar = async (file: File, selectionID: number) => {+ setIsPreparingAvatar(true);+ if (avatarCropUrlRef.current) {+ URL.revokeObjectURL(avatarCropUrlRef.current);+ avatarCropUrlRef.current = null;+ }+ setAvatarCropImage(null);+ setAvatarCropPixels(null);try {- const avatar = await prepareSocialAvatarImage(file);- if (avatarSelectionIDRef.current != selectionID) return;- if (avatar.file.size > maxAvatarBytes) {- setAvatarError("Choose an image under 19 MB.");+ const cropImage = await socialAvatarCropImageForFile(file);+ if (avatarSelectionIDRef.current != selectionID) {+ URL.revokeObjectURL(cropImage.url);return;}- if (avatarUrlRef.current) URL.revokeObjectURL(avatarUrlRef.current);- const nextUrl = URL.createObjectURL(avatar.file);- avatarUrlRef.current = nextUrl;+ avatarCropUrlRef.current = cropImage.url;+ setAvatarCrop({ x: 0, y: 0 });+ setAvatarCropImage({ file, url: cropImage.url });+ setAvatarCropPixels(null);setAvatarError(undefined);- setAvatarFile(avatar.file);- setAvatarUrl(nextUrl);+ setAvatarZoom(1);} 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.");+ } finally {+ if (avatarSelectionIDRef.current == selectionID) {+ setIsPreparingAvatar(false);+ }}};@@ -306,6 +563,36 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({void prepareSelectedAvatar(file, selectionID);};+ const applyAvatarCrop = async () => {+ if (!avatarCropImage || !avatarCropPixels) return;++ setIsApplyingAvatarCrop(true);+ try {+ const avatar = await prepareSocialAvatarImageFromCrop(+ avatarCropImage.file,+ avatarCropImage.url,+ avatarCropPixels,+ );+ if (avatar.file.size > maxAvatarBytes) {+ setAvatarError(maxAvatarSizeMessage);+ setIsApplyingAvatarCrop(false);+ return;+ }++ if (avatarUrlRef.current) URL.revokeObjectURL(avatarUrlRef.current);+ const nextUrl = URL.createObjectURL(avatar.file);+ avatarUrlRef.current = nextUrl;+ setAvatarError(undefined);+ setAvatarFile(avatar.file);+ setAvatarUrl(nextUrl);+ clearAvatarCropImage();+ } catch (error) {+ console.error("Failed to crop social avatar", error);+ setAvatarError("Couldn't crop this image. Choose another one.");+ setIsApplyingAvatarCrop(false);+ }+ };+const handleUsernameChange = (value: string) => {setUsername(value);onUsernameChange?.(value);@@ -432,7 +719,12 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({<Boxcomponent="button"type="button"- aria-label="Upload profile picture"+ aria-label={+ avatarUrl+ ? "Change profile picture"+ : "Upload profile picture"+ }+ disabled={isPreparingAvatar}onClick={() => fileInputRef.current?.click()}sx={{alignItems: "center",@@ -441,7 +733,9 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({border: 0,borderRadius: "50%",color: green,- cursor: "pointer",+ cursor: isPreparingAvatar+ ? "default"+ : "pointer",display: "flex",height: 112,justifyContent: "center",@@ -455,7 +749,21 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({},}}>- {avatarUrl ? (+ {isPreparingAvatar ? (+ <Box+ component="span"+ sx={{+ color: green,+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 13,+ fontWeight: 600,+ lineHeight: "18px",+ }}+ >+ Preparing...+ </Box>+ ) : avatarUrl ? (<Boxcomponent="img"alt=""@@ -476,6 +784,7 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({component="button"type="button"aria-label="Edit profile picture"+ disabled={isPreparingAvatar}onClick={() => fileInputRef.current?.click()}sx={{alignItems: "center",@@ -485,7 +794,9 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({bottom: 6,boxShadow: "0 4px 10px rgba(0, 0, 0, 0.12)",color: textBase,- cursor: "pointer",+ cursor: isPreparingAvatar+ ? "default"+ : "pointer",display: "flex",height: 30,justifyContent: "center",@@ -547,6 +858,24 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({</Box></Box>+ {avatarCropImage && (+ <AvatarCropDialog+ crop={avatarCrop}+ imageURL={avatarCropImage.url}+ isDoneDisabled={!avatarCropPixels}+ isSaving={isApplyingAvatarCrop}+ onCancel={clearAvatarCropImage}+ onChooseAnother={() => fileInputRef.current?.click()}+ onCropChange={setAvatarCrop}+ onCropComplete={(_croppedArea, croppedAreaPixels) =>+ setAvatarCropPixels(croppedAreaPixels)+ }+ onDone={() => void applyAvatarCrop()}+ onZoomChange={setAvatarZoom}+ zoom={avatarZoom}+ />+ )}+<Boxsx={{bgcolor: setupProfileBackground,diff --git a/web/apps/social/src/utils/socialPostImage.ts b/web/apps/social/src/utils/socialPostImage.tsindex 88463dfbb6..0f5b670be5 100644--- a/web/apps/social/src/utils/socialPostImage.ts+++ b/web/apps/social/src/utils/socialPostImage.ts@@ -11,6 +11,17 @@ export interface PreparedSocialImage {export type PreparedSocialAvatarImage = PreparedSocialImage;export type PreparedSocialPostImage = PreparedSocialImage;+export interface SocialAvatarCropImage {+ url: string;+}++export interface SocialImageCropArea {+ height: number;+ width: number;+ x: number;+ y: number;+}+export const socialAvatarImageInputAccept ="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif";export const socialPostImageInputAccept =@@ -59,6 +70,42 @@ export const prepareSocialAvatarImage = async (};};+export const socialAvatarCropImageForFile = async (+ file: File,+): Promise<SocialAvatarCropImage> => {+ const renderableBlob = await renderableBlobForSocialImage(file);+ const imageURL = URL.createObjectURL(renderableBlob);++ try {+ await loadImage(imageURL);+ return { url: imageURL };+ } catch (error) {+ URL.revokeObjectURL(imageURL);+ throw error;+ }+};++export const prepareSocialAvatarImageFromCrop = async (+ file: File,+ imageURL: string,+ cropArea: SocialImageCropArea,+): Promise<PreparedSocialAvatarImage> => {+ const { blob, height, width } = await webPBlobFromImage(+ imageURL,+ (width, height) => avatarCanvasPlanForCrop(width, height, cropArea),+ false,+ );++ 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();@@ -80,10 +127,14 @@ interface CanvasPlan {}const webPBlobFromImage = async (- blob: Blob,+ imageSource: Blob | string,planForSource: (width: number, height: number) => CanvasPlan,+ revokeImageURL = true,): Promise<{ blob: Blob; height: number; width: number }> => {- const imageURL = URL.createObjectURL(blob);+ const imageURL =+ typeof imageSource == "string"+ ? imageSource+ : URL.createObjectURL(imageSource);try {const image = await loadImage(imageURL);const plan = planForSource(@@ -119,7 +170,7 @@ const webPBlobFromImage = async (width: plan.width,};} finally {- URL.revokeObjectURL(imageURL);+ if (revokeImageURL) URL.revokeObjectURL(imageURL);}};@@ -171,6 +222,39 @@ const avatarCanvasPlan = (width: number, height: number): CanvasPlan => {};};+const avatarCanvasPlanForCrop = (+ width: number,+ height: number,+ cropArea: SocialImageCropArea,+): CanvasPlan => {+ if (width <= 0 || height <= 0) {+ return {+ height: 0,+ sourceHeight: 0,+ sourceWidth: 0,+ sourceX: 0,+ sourceY: 0,+ width: 0,+ };+ }++ const sourceEdge = Math.min(+ Math.max(1, Math.min(cropArea.width, cropArea.height)),+ width,+ height,+ );+ const outputEdge = socialAvatarImageMaxEdge;++ return {+ height: outputEdge,+ sourceHeight: sourceEdge,+ sourceWidth: sourceEdge,+ sourceX: clampNumber(cropArea.x, 0, Math.max(0, width - sourceEdge)),+ sourceY: clampNumber(cropArea.y, 0, Math.max(0, height - sourceEdge)),+ width: outputEdge,+ };+};+const scaledDimensions = (width: number,height: number,@@ -190,6 +274,9 @@ const scaledDimensions = (};};+const clampNumber = (value: number, min: number, max: number) =>+ Math.min(Math.max(value, min), max);+const canvasToBlob = async (canvas: HTMLCanvasElement,mediaType: string,diff --git a/web/yarn.lock b/web/yarn.lockindex 22c04f6b86..49899d936b 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -4245,6 +4245,11 @@ node-releases@^2.0.19:resolved "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz"integrity sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==+normalize-wheel@^1.0.1:+ version "1.0.1"+ resolved "https://registry.yarnpkg.com/normalize-wheel/-/normalize-wheel-1.0.1.tgz#aec886affdb045070d856447df62ecf86146ec45"+ integrity sha512-1OnlAPZ3zgrk8B91HyRj+eVv+kS5u+Z0SCsak6Xil/kmgEia50ga7zfkumayonZrImffAxPU/5WcyGhzetHNPA==+object-assign@^4.1.1:version "4.1.1"resolved "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz"@@ -4571,6 +4576,14 @@ [email protected]:file-selector "^0.6.0"prop-types "^15.8.1"+react-easy-crop@^5.5.7:+ version "5.5.7"+ resolved "https://registry.yarnpkg.com/react-easy-crop/-/react-easy-crop-5.5.7.tgz#220518895ef1ed28bd889cbdfbd5baed0f0009bb"+ integrity sha512-kYo4NtMeXFQB7h1U+h5yhUkE46WQbQdq7if54uDlbMdZHdRgNehfvaFrXnFw5NR1PNoUOJIfTwLnWmEx/MaZnA==+ dependencies:+ normalize-wheel "^1.0.1"+ tslib "^2.0.1"+react-fast-compare@^2.0.1:version "2.0.4"resolved "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-2.0.4.tgz"@@ -5392,7 +5405,7 @@ ts-api-utils@^2.1.0:resolved "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz"integrity sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==-tslib@^2.0.0, tslib@^2.1.0, tslib@^2.4.0, tslib@^2.8.0:+tslib@^2.0.0, tslib@^2.0.1, tslib@^2.1.0, tslib@^2.4.0, tslib@^2.8.0:version "2.8.1"resolved "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz"integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==