Skip to content

armgit / ente

Public Imported from GitHub
0

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

Restore Space avatar crop flow

Anand Baburajandeea379aeb84
diff --git a/web/apps/space/package.json b/web/apps/space/package.json
index 0f4db0f7d5..71181bdd46 100644
--- a/web/apps/space/package.json
+++ b/web/apps/space/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/space/src/pages/_app.tsx b/web/apps/space/src/pages/_app.tsx
index 6e9276f406..468d53ae2e 100644
--- a/web/apps/space/src/pages/_app.tsx
+++ b/web/apps/space/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 { SpaceAppStateProvider } from "state/SpaceAppStateProvider";
import "styles/globals.css";
diff --git a/web/apps/space/src/screens/SetupProfileScreen.tsx b/web/apps/space/src/screens/SetupProfileScreen.tsx
index 2d6d240178..722191f4bb 100644
--- a/web/apps/space/src/screens/SetupProfileScreen.tsx
+++ b/web/apps/space/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 {
- prepareSpaceAvatarImage,
+ prepareSpaceAvatarImageFromCrop,
+ spaceAvatarCropImageForFile,
spaceAvatarImageErrorMessage,
spaceAvatarImageInputAccept,
} from "utils/spacePostImage";
@@ -29,6 +31,11 @@ export interface SetupProfileInput extends SetupProfile {
avatarFile?: File | null;
}
+interface AvatarCropImage {
+ file: File;
+ url: string;
+}
+
interface SetupProfileScreenProps {
ctaLabel?: string;
errorMessage?: string;
@@ -48,6 +55,21 @@ interface TextInputProps {
value?: string;
}
+interface AvatarCropPageProps {
+ crop: Point;
+ errorMessage?: string;
+ imageURL: string;
+ isDoneDisabled?: boolean;
+ isSaving?: boolean;
+ onBack: () => 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 = () => (
<Box
component="svg"
@@ -239,6 +261,265 @@ const TextInput: React.FC<TextInputProps> = ({
</Box>
);
+const AvatarCropPageButton: 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: "0 0 auto",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ height: 44,
+ justifyContent: "center",
+ lineHeight: "20px",
+ minWidth: 0,
+ px: 2,
+ width: "100%",
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 3,
+ },
+ "&:hover":
+ !disabled && variant == "primary"
+ ? { bgcolor: "#07AE22" }
+ : undefined,
+ }}
+ >
+ {children}
+ </Box>
+);
+
+const AvatarCropPage: React.FC<AvatarCropPageProps> = ({
+ crop,
+ errorMessage,
+ imageURL,
+ isDoneDisabled = false,
+ isSaving = false,
+ onBack,
+ onChooseAnother,
+ onCropChange,
+ onCropComplete,
+ onDone,
+ onZoomChange,
+ zoom,
+}) => (
+ <Box
+ component="main"
+ sx={{
+ bgcolor: setupProfileBackground,
+ color: textBase,
+ display: "grid",
+ minHeight: "100svh",
+ overflow: "hidden",
+ placeItems: { xs: "stretch", sm: "start center" },
+ }}
+ >
+ <Box
+ sx={{
+ bgcolor: setupProfileBackground,
+ boxSizing: "border-box",
+ display: "flex",
+ flexDirection: "column",
+ minHeight: "100svh",
+ mx: "auto",
+ pb: "172px",
+ px: 3,
+ width: "100%",
+ "@media (min-width: 600px)": { maxWidth: 390 },
+ }}
+ >
+ <Box
+ component="header"
+ sx={{
+ display: "grid",
+ gridTemplateColumns: "42px 1fr 42px",
+ height: 42,
+ mt: "32px",
+ width: "100%",
+ }}
+ >
+ <Box
+ component="button"
+ type="button"
+ aria-label="Back"
+ disabled={isSaving}
+ onClick={onBack}
+ sx={{
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ color: textBase,
+ cursor: isSaving ? "default" : "pointer",
+ display: "flex",
+ height: 42,
+ justifyContent: "flex-start",
+ p: 0,
+ width: 42,
+ "&:focus-visible": {
+ borderRadius: "50%",
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ }}
+ >
+ <BackIcon />
+ </Box>
+ <Box
+ component="h1"
+ sx={{
+ alignSelf: "center",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 20,
+ fontWeight: 600,
+ justifySelf: "center",
+ lineHeight: "28px",
+ m: 0,
+ whiteSpace: "nowrap",
+ }}
+ >
+ Edit profile picture
+ </Box>
+ <Box />
+ </Box>
+
+ <Box
+ sx={{
+ bgcolor: "#111",
+ borderRadius: "8px",
+ height: "auto",
+ aspectRatio: "1 / 1",
+ mt: "32px",
+ 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: "28px", width: "100%" }}>
+ <Box
+ component="label"
+ htmlFor="space-avatar-zoom"
+ sx={{
+ border: 0,
+ clip: "rect(0 0 0 0)",
+ height: 1,
+ m: -1,
+ overflow: "hidden",
+ p: 0,
+ position: "absolute",
+ width: 1,
+ }}
+ >
+ Zoom
+ </Box>
+ <Box
+ component="input"
+ id="space-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>
+ {errorMessage && (
+ <Box
+ role="alert"
+ sx={{
+ color: warning,
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 500,
+ lineHeight: "18px",
+ mt: 2,
+ textAlign: "center",
+ }}
+ >
+ {errorMessage}
+ </Box>
+ )}
+
+ <Box
+ sx={{
+ bgcolor: setupProfileBackground,
+ bottom: 0,
+ boxSizing: "border-box",
+ display: "flex",
+ flexDirection: "column",
+ gap: "10px",
+ left: "50%",
+ maxWidth: 390,
+ p: 3,
+ position: "fixed",
+ transform: "translateX(-50%)",
+ width: "100%",
+ }}
+ >
+ <AvatarCropPageButton
+ disabled={isSaving}
+ variant="secondary"
+ onClick={onChooseAnother}
+ >
+ Choose another
+ </AvatarCropPageButton>
+ <AvatarCropPageButton
+ disabled={isSaving || isDoneDisabled}
+ variant="primary"
+ onClick={onDone}
+ >
+ {isSaving ? "Saving..." : "Done"}
+ </AvatarCropPageButton>
+ </Box>
+ </Box>
+ </Box>
+);
+
export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
ctaLabel = "Next",
errorMessage,
@@ -250,41 +531,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 prepareSpaceAvatarImage(file);
- if (avatarSelectionIDRef.current != selectionID) return;
+ const cropImage = await spaceAvatarCropImageForFile(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 space avatar", error);
setAvatarError(spaceAvatarImageErrorMessage(error));
+ } finally {
+ if (avatarSelectionIDRef.current == selectionID) {
+ setIsPreparingAvatar(false);
+ }
}
};
@@ -302,6 +625,31 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
void prepareSelectedAvatar(file, selectionID);
};
+ const applyAvatarCrop = async () => {
+ if (!avatarCropImage || !avatarCropPixels) return;
+
+ setIsApplyingAvatarCrop(true);
+ try {
+ const avatar = await prepareSpaceAvatarImageFromCrop(
+ avatarCropImage.file,
+ avatarCropImage.url,
+ avatarCropPixels,
+ );
+
+ 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 space avatar", error);
+ setAvatarError(spaceAvatarImageErrorMessage(error));
+ setIsApplyingAvatarCrop(false);
+ }
+ };
+
const handleUsernameChange = (value: string) => {
setUsername(value);
onUsernameChange?.(value);
@@ -323,6 +671,41 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
submitProfile();
};
+ const avatarFileInput = (
+ <Box
+ component="input"
+ ref={fileInputRef}
+ accept={spaceAvatarImageInputAccept}
+ onChange={handleAvatarChange}
+ type="file"
+ sx={{ display: "none" }}
+ />
+ );
+
+ if (avatarCropImage) {
+ return (
+ <>
+ {avatarFileInput}
+ <AvatarCropPage
+ crop={avatarCrop}
+ errorMessage={avatarError}
+ imageURL={avatarCropImage.url}
+ isDoneDisabled={!avatarCropPixels}
+ isSaving={isApplyingAvatarCrop}
+ onBack={clearAvatarCropImage}
+ onChooseAnother={() => fileInputRef.current?.click()}
+ onCropChange={setAvatarCrop}
+ onCropComplete={(_croppedArea, croppedAreaPixels) =>
+ setAvatarCropPixels(croppedAreaPixels)
+ }
+ onDone={() => void applyAvatarCrop()}
+ onZoomChange={setAvatarZoom}
+ zoom={avatarZoom}
+ />
+ </>
+ );
+ }
+
return (
<Box
component="main"
@@ -415,14 +798,7 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
width: "100%",
}}
>
- <Box
- component="input"
- ref={fileInputRef}
- accept={spaceAvatarImageInputAccept}
- onChange={handleAvatarChange}
- type="file"
- sx={{ display: "none" }}
- />
+ {avatarFileInput}
<Box sx={{ position: "relative" }}>
<Box
@@ -433,6 +809,7 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
? "Change profile picture"
: "Upload profile picture"
}
+ disabled={isPreparingAvatar}
onClick={() => fileInputRef.current?.click()}
sx={{
alignItems: "center",
@@ -441,7 +818,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 +834,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 ? (
<Box
component="img"
alt=""
@@ -475,17 +868,20 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({
<Box
component="button"
type="button"
- aria-label="Change profile picture"
+ aria-label="Edit profile picture"
+ disabled={isPreparingAvatar}
onClick={() => fileInputRef.current?.click()}
sx={{
alignItems: "center",
bgcolor: "white",
- border: "1px solid #E6E6E6",
+ border: 0,
borderRadius: "50%",
bottom: 6,
- boxShadow: "0 4px 10px rgba(0, 0, 0, 0.12)",
+ boxShadow: "0 1px 3px rgba(0, 0, 0, 0.08)",
color: textBase,
- cursor: "pointer",
+ cursor: isPreparingAvatar
+ ? "default"
+ : "pointer",
display: "flex",
height: 30,
justifyContent: "center",
diff --git a/web/apps/space/src/utils/spacePostImage.ts b/web/apps/space/src/utils/spacePostImage.ts
index 5beb02a422..e3fc4d668d 100644
--- a/web/apps/space/src/utils/spacePostImage.ts
+++ b/web/apps/space/src/utils/spacePostImage.ts
@@ -11,6 +11,17 @@ export interface PreparedSpaceImage {
export type PreparedSpaceAvatarImage = PreparedSpaceImage;
export type PreparedSpacePostImage = PreparedSpaceImage;
+export interface SpaceAvatarCropImage {
+ url: string;
+}
+
+export interface SpaceImageCropArea {
+ height: number;
+ width: number;
+ x: number;
+ y: number;
+}
+
export const spaceAvatarImageInputAccept =
"image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif";
export const spacePostImageInputAccept =
@@ -81,6 +92,47 @@ export const prepareSpaceAvatarImage = async (
};
};
+export const spaceAvatarCropImageForFile = async (
+ file: File,
+): Promise<SpaceAvatarCropImage> => {
+ const renderableBlob = await renderableBlobForSpaceImage(file);
+ const imageURL = URL.createObjectURL(renderableBlob);
+
+ try {
+ await loadImage(imageURL);
+ return { url: imageURL };
+ } catch (error) {
+ URL.revokeObjectURL(imageURL);
+ throw error;
+ }
+};
+
+export const prepareSpaceAvatarImageFromCrop = async (
+ file: File,
+ imageURL: string,
+ cropArea: SpaceImageCropArea,
+): Promise<PreparedSpaceAvatarImage> => {
+ const { blob, height, width } = await webPBlobFromImage(
+ imageURL,
+ (width, height) => avatarCanvasPlanForCrop(width, height, cropArea),
+ false,
+ );
+ assertSpaceImageSize(
+ blob,
+ maxSpaceAvatarImageBytes,
+ spaceAvatarImageMaxSizeMessage,
+ );
+
+ return {
+ file: new File([blob], webPFileName(file.name), {
+ lastModified: file.lastModified || Date.now(),
+ type: spacePostImageMimeType,
+ }),
+ height,
+ width,
+ };
+};
+
export const spacePostImageErrorMessage = (error: unknown) =>
error instanceof SpaceImageSizeError
? error.message
@@ -222,6 +274,39 @@ const avatarCanvasPlan = (width: number, height: number): CanvasPlan => {
};
};
+const avatarCanvasPlanForCrop = (
+ width: number,
+ height: number,
+ cropArea: SpaceImageCropArea,
+): 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 = spaceAvatarImageMaxEdge;
+
+ 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,
@@ -241,6 +326,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.lock
index efb9dc35f7..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"