Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Add photo cropping and rotation to Space posts

Anand Baburajanfd7badf4486d
diff --git a/web/apps/space/src/components/FeedPostButton.tsx b/web/apps/space/src/components/FeedPostButton.tsx
index 3874a61c5e..de6bd1bbe8 100644
--- a/web/apps/space/src/components/FeedPostButton.tsx
+++ b/web/apps/space/src/components/FeedPostButton.tsx
@@ -38,14 +38,13 @@ export const SpaceFeedPostButton: React.FC<SpaceFeedPostButtonProps> = ({
borderRadius: "50%",
bottom: "calc(env(safe-area-inset-bottom) + 20px)",
boxShadow: "0 10px 24px rgba(0, 0, 0, 0.22)",
- color: "#FFFFFF",
+ color: disabled ? "rgba(255, 255, 255, 0.72)" : "#FFFFFF",
cursor: disabled ? "default" : "pointer",
display: "flex",
fontSize: 0,
height: buttonSize,
justifyContent: "center",
lineHeight: 0,
- opacity: disabled ? 0.72 : 1,
p: 0,
position: "fixed",
right: "max(20px, calc((100vw - 390px) / 2 + 20px))",
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsx
index a7665f460d..d240080248 100644
--- a/web/apps/space/src/components/FileViewer.tsx
+++ b/web/apps/space/src/components/FileViewer.tsx
@@ -4,6 +4,7 @@ import {
Cancel01Icon,
Delete02Icon,
Edit01Icon,
+ Edit03Icon,
Loading03Icon,
MoreHorizontalIcon,
Tick02Icon,
@@ -137,6 +138,7 @@ interface SpaceFileViewerProps {
draftPostPreparationError?: string;
isDraftPostPreviewPending?: boolean;
onClose: () => void;
+ onEditDraftPhoto?: () => void;
onDeletePost?: () => Promise<void> | void;
onDraftPostExitAnimationStart?: () => void;
onDraftPostExitStart?: () => void;
@@ -334,6 +336,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
focusReplyOnOpen = false,
isDraftPostPreviewPending = false,
onClose,
+ onEditDraftPhoto,
onDeletePost,
onDraftPostExitAnimationStart,
onDraftPostExitStart,
@@ -1465,6 +1468,34 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
/>
</Box>
)}
+ {isDraftPost && onEditDraftPhoto && (
+ <Box
+ component="button"
+ type="button"
+ aria-label="Edit photo"
+ title="Edit photo"
+ disabled={
+ isDraftPostActionRunning ||
+ isDraftPostPreviewPending ||
+ Boolean(draftPostPreparationError)
+ }
+ onClick={onEditDraftPhoto}
+ sx={{
+ ...viewerHeaderButtonSx,
+ mr: postPhotoCount > 1 ? "8px" : 0,
+ "&:disabled": {
+ opacity: 0.3,
+ cursor: "default",
+ },
+ }}
+ >
+ <HugeiconsIcon
+ icon={Edit03Icon}
+ size={16}
+ strokeWidth={1.8}
+ />
+ </Box>
+ )}
{postPhotoCount > 1 && (
<Box
component="span"
diff --git a/web/apps/space/src/components/PostComposer.tsx b/web/apps/space/src/components/PostComposer.tsx
index cb460ee7c6..f0fcb09dfb 100644
--- a/web/apps/space/src/components/PostComposer.tsx
+++ b/web/apps/space/src/components/PostComposer.tsx
@@ -3,6 +3,10 @@ import {
SpaceViewerPostBackdrop,
type SpaceViewerPhoto,
} from "components/FileViewer";
+import {
+ SpacePostPhotoEditor,
+ type SpacePostPhotoEditResult,
+} from "components/PostPhotoEditor";
import { SpacePostPhotoInput } from "components/PostPhotoInput";
import { SpacePostPhotoStrip } from "components/PostPhotoStrip";
import log from "ente-base/log";
@@ -16,6 +20,7 @@ import {
spacePostImageErrorMessage,
spacePostPreviewImageForFile,
type SpaceDraftPostImage,
+ type SpacePostPhotoEdit,
} from "utils/post-image";
import { maxSpacePostPhotos, movePostPhoto } from "utils/post-photos";
import { useSpaceRouter } from "utils/route-transitions";
@@ -26,6 +31,8 @@ interface DraftPhoto {
id: number;
error?: string;
photo?: SpaceViewerPhoto;
+ originalPhoto?: SpaceViewerPhoto;
+ edit?: SpacePostPhotoEdit;
}
let nextDraftPhotoID = 0;
@@ -48,8 +55,9 @@ export const SpacePostComposer: React.FC<{
const [activeIndex, setActiveIndex] = React.useState(0);
const [isPublishing, setIsPublishing] = React.useState(false);
const [isExiting, setIsExiting] = React.useState(false);
+ const [isEditing, setIsEditing] = React.useState(false);
const inputRef = React.useRef<HTMLInputElement | null>(null);
- const previewURLsRef = React.useRef(new Map<number, string>());
+ const previewURLsRef = React.useRef(new Set<string>());
const publishedPreviewURLRef = React.useRef<string>(undefined);
const preparingRef = React.useRef(new Set<number>());
const draftsRef = React.useRef(drafts);
@@ -126,10 +134,12 @@ export const SpacePostComposer: React.FC<{
URL.revokeObjectURL(photo.imageUrl);
continue;
}
- previewURLsRef.current.set(draft.id, photo.imageUrl);
+ previewURLsRef.current.add(photo.imageUrl);
setDrafts((current) =>
current.map((item) =>
- item.id == draft.id ? { ...item, photo } : item,
+ item.id == draft.id
+ ? { ...item, photo, originalPhoto: photo }
+ : item,
),
);
} catch (error) {
@@ -165,9 +175,15 @@ export const SpacePostComposer: React.FC<{
}
const removed = drafts[activeIndex];
if (!removed) return;
- const url = previewURLsRef.current.get(removed.id);
- if (url) URL.revokeObjectURL(url);
- previewURLsRef.current.delete(removed.id);
+ for (const url of new Set([
+ removed.photo?.imageUrl,
+ removed.originalPhoto?.imageUrl,
+ ])) {
+ if (url) {
+ URL.revokeObjectURL(url);
+ previewURLsRef.current.delete(url);
+ }
+ }
setDrafts((current) =>
current.filter((draft) => draft.id != removed.id),
);
@@ -177,6 +193,29 @@ export const SpacePostComposer: React.FC<{
setDrafts((current) => movePostPhoto(current, from, to));
setActiveIndex(to);
};
+ const applyEdits = (results: SpacePostPhotoEditResult[], index: number) => {
+ const nextDrafts = drafts.map((draft) => {
+ const result = results.find((result) => result.id == draft.id);
+ if (!result) return draft;
+ if (draft.photo!.imageUrl != draft.originalPhoto!.imageUrl) {
+ URL.revokeObjectURL(draft.photo!.imageUrl);
+ previewURLsRef.current.delete(draft.photo!.imageUrl);
+ }
+ const photo = result.preview
+ ? {
+ ...draft.originalPhoto!,
+ imageUrl: result.preview.url,
+ width: result.preview.width,
+ height: result.preview.height,
+ }
+ : draft.originalPhoto!;
+ previewURLsRef.current.add(photo.imageUrl);
+ return { ...draft, edit: result.edit, photo };
+ });
+ setDrafts(nextDrafts);
+ setActiveIndex(index);
+ setIsEditing(false);
+ };
const photos = drafts.map((draft, index) => ({
...(draft.photo ?? placeholder),
postPhotoIndex: index,
@@ -215,6 +254,7 @@ export const SpacePostComposer: React.FC<{
draftPostPreparationError={preparationError}
isDraftPostPreviewPending={isPreparing || !drafts.length}
onClose={onClose}
+ onEditDraftPhoto={() => setIsEditing(true)}
onDraftPostExitStart={() => setIsPublishing(true)}
onDraftPostExitAnimationStart={() => setIsExiting(true)}
onDraftPostPublished={() => {
@@ -228,9 +268,12 @@ export const SpacePostComposer: React.FC<{
drafts[0]!.photo!.imageUrl;
return onPublish(
drafts.map((draft) => ({
+ cropArea: draft.edit?.cropArea,
file: draft.file,
height: draft.photo!.height,
previewUrl: draft.photo!.imageUrl,
+ rotationDegrees:
+ draft.edit?.rotationDegrees,
width: draft.photo!.width,
})),
caption,
@@ -243,6 +286,21 @@ export const SpacePostComposer: React.FC<{
onPhotoIndexChange={setActiveIndex}
postActionMode="draft-post"
/>
+ {isEditing && (
+ <SpacePostPhotoEditor
+ initialIndex={activeIndex}
+ onClose={() => setIsEditing(false)}
+ onDone={applyEdits}
+ photos={drafts.map((draft) => ({
+ id: draft.id,
+ imageURL: draft.originalPhoto!.imageUrl,
+ previewURL: draft.photo!.imageUrl,
+ width: draft.originalPhoto!.width!,
+ height: draft.originalPhoto!.height!,
+ edit: draft.edit,
+ }))}
+ />
+ )}
</>
);
};
diff --git a/web/apps/space/src/components/PostPhotoEditor.tsx b/web/apps/space/src/components/PostPhotoEditor.tsx
new file mode 100644
index 0000000000..dbdc94dda4
--- /dev/null
+++ b/web/apps/space/src/components/PostPhotoEditor.tsx
@@ -0,0 +1,421 @@
+import { Cancel01Icon, RotateTopRightIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Box, Dialog } from "@mui/material";
+import { SpacePostPhotoStrip } from "components/PostPhotoStrip";
+import { SpacePhotoCrop } from "components/photo-crop/PhotoCrop";
+import {
+ cropWithAspect,
+ fullImageCrop,
+ rotateImageCrop,
+ rotatedImageSize,
+} from "components/photo-crop/geometry";
+import log from "ente-base/log";
+import { useBrowserBackClose } from "hooks/use-browser-back-close";
+import React from "react";
+import {
+ spacePostPreviewImageFromEdit,
+ type SpacePostPhotoEdit,
+ type SpacePostPreviewImage,
+} from "utils/post-image";
+
+export interface SpaceEditablePostPhoto {
+ id: number;
+ imageURL: string;
+ previewURL: string;
+ width: number;
+ height: number;
+ edit?: SpacePostPhotoEdit;
+}
+
+export interface SpacePostPhotoEditResult {
+ id: number;
+ edit: SpacePostPhotoEdit;
+ preview?: SpacePostPreviewImage;
+}
+
+const originalEdit: SpacePostPhotoEdit = { rotationDegrees: 0 };
+const aspects = [
+ { label: "Free", value: undefined },
+ { label: "Square", value: 1 },
+ { label: "3:4", value: 3 / 4 },
+ { label: "16:9", value: 16 / 9 },
+];
+const buttonSx = {
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ borderRadius: "999px",
+ color: "inherit",
+ cursor: "pointer",
+ display: "inline-flex",
+ font: "inherit",
+ fontSize: 14,
+ fontWeight: 600,
+ gap: "8px",
+ justifyContent: "center",
+ minHeight: 44,
+ px: "12px",
+ "&:disabled": { opacity: 0.4, cursor: "default" },
+ "&:focus-visible": { outline: "2px solid #08C225", outlineOffset: 2 },
+};
+
+export const SpacePostPhotoEditor: React.FC<{
+ photos: SpaceEditablePostPhoto[];
+ initialIndex: number;
+ onClose: () => void;
+ onDone: (results: SpacePostPhotoEditResult[], activeIndex: number) => void;
+}> = ({ photos, initialIndex, onClose, onDone }) => {
+ const [activeIndex, setActiveIndex] = React.useState(initialIndex);
+ const [edits, setEdits] = React.useState(() =>
+ photos.map((photo) => photo.edit ?? originalEdit),
+ );
+ const [isSaving, setIsSaving] = React.useState(false);
+ const [error, setError] = React.useState<string>();
+ const mounted = React.useRef(false);
+ const photo = photos[activeIndex]!;
+ const edit = edits[activeIndex]!;
+ const size = rotatedImageSize(photo, edit.rotationDegrees);
+ const crop = edit.cropArea ?? fullImageCrop(size);
+ const isEdited = Boolean(
+ edit.cropArea || edit.rotationDegrees || edit.aspect,
+ );
+
+ React.useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+
+ useBrowserBackClose({
+ open: true,
+ onClose,
+ stateKey: "space-post-photo-editor",
+ });
+
+ const updateEdit = (next: SpacePostPhotoEdit) => {
+ setError(undefined);
+ setEdits((current) =>
+ current.map((item, index) => (index == activeIndex ? next : item)),
+ );
+ };
+ const save = async () => {
+ setIsSaving(true);
+ setError(undefined);
+ const results: SpacePostPhotoEditResult[] = [];
+ try {
+ for (const [index, photo] of photos.entries()) {
+ const edit = edits[index]!;
+ if (edit === (photo.edit ?? originalEdit)) continue;
+ const preview =
+ edit.cropArea || edit.rotationDegrees
+ ? await spacePostPreviewImageFromEdit(
+ photo.imageURL,
+ edit,
+ )
+ : undefined;
+ results.push({ id: photo.id, edit, preview });
+ if (!mounted.current) return;
+ }
+ onDone(results, activeIndex);
+ results.length = 0;
+ } catch (error) {
+ log.error("Failed to prepare edited post photos", error);
+ if (mounted.current)
+ setError("Couldn't apply your edits. Try again.");
+ } finally {
+ for (const result of results) {
+ if (result.preview) URL.revokeObjectURL(result.preview.url);
+ }
+ if (mounted.current) setIsSaving(false);
+ }
+ };
+
+ return (
+ <Dialog
+ open
+ fullScreen
+ onClose={onClose}
+ onKeyDown={(event) => event.stopPropagation()}
+ aria-labelledby="space-photo-editor-title"
+ slotProps={{
+ paper: {
+ sx: {
+ bgcolor: "#000000",
+ color: "#F2F2F2",
+ backgroundImage: "none",
+ height: "100dvh",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ },
+ },
+ }}
+ sx={{ zIndex: 1400 }}
+ >
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "grid",
+ gridTemplateColumns: "1fr auto 1fr",
+ px: "16px",
+ pt: "max(6px, env(safe-area-inset-top))",
+ pb: "6px",
+ flexShrink: 0,
+ }}
+ >
+ <Box
+ component="button"
+ type="button"
+ aria-label="Cancel photo edits"
+ onClick={onClose}
+ sx={{
+ ...buttonSx,
+ justifySelf: "start",
+ width: 44,
+ ml: "-8px",
+ p: 0,
+ }}
+ >
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ size={20}
+ strokeWidth={1.8}
+ />
+ </Box>
+ <Box
+ id="space-photo-editor-title"
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ gap: "8px",
+ fontSize: 14,
+ fontWeight: 600,
+ }}
+ >
+ Edit
+ {photos.length > 1 && (
+ <Box
+ component="span"
+ sx={{
+ color: "#A6A6A6",
+ fontSize: 12,
+ fontWeight: 500,
+ }}
+ >
+ {activeIndex + 1} / {photos.length}
+ </Box>
+ )}
+ </Box>
+ <Box
+ component="button"
+ type="button"
+ disabled={isSaving}
+ aria-busy={isSaving}
+ onClick={() => void save()}
+ sx={{
+ ...buttonSx,
+ justifySelf: "end",
+ borderRadius: "999px",
+ p: 0,
+ }}
+ >
+ <Box
+ component="span"
+ sx={{
+ alignItems: "center",
+ bgcolor: "#FFFFFF",
+ borderRadius: "999px",
+ color: "#171717",
+ display: "inline-flex",
+ height: 32,
+ px: "16px",
+ }}
+ >
+ {isSaving ? "Saving…" : "Done"}
+ </Box>
+ </Box>
+ </Box>
+ <Box
+ sx={{
+ display: "flex",
+ flex: 1,
+ minHeight: 0,
+ px: "24px",
+ py: "20px",
+ maxWidth: 1000,
+ width: "100%",
+ boxSizing: "border-box",
+ alignSelf: "center",
+ }}
+ >
+ <SpacePhotoCrop
+ key={photo.id}
+ imageURL={photo.imageURL}
+ imageSize={photo}
+ rotation={edit.rotationDegrees}
+ crop={crop}
+ aspect={edit.aspect}
+ disabled={isSaving}
+ onChange={(cropArea) => updateEdit({ ...edit, cropArea })}
+ />
+ </Box>
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: "12px",
+ px: "12px",
+ pb: "max(16px, env(safe-area-inset-bottom))",
+ flexShrink: 0,
+ }}
+ >
+ {error && (
+ <Box role="alert" sx={{ color: "#FF8A8A", fontSize: 13 }}>
+ {error}
+ </Box>
+ )}
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "grid",
+ gridTemplateColumns: "44px minmax(0, 1fr) 56px",
+ gap: "6px",
+ width: "100%",
+ maxWidth: 390,
+ }}
+ >
+ <Box
+ component="button"
+ type="button"
+ aria-label="Rotate photo 90 degrees clockwise"
+ title="Rotate 90°"
+ disabled={isSaving}
+ onClick={() => {
+ const rotationDegrees =
+ (edit.rotationDegrees + 90) % 360;
+ const rotatedCrop = rotateImageCrop(crop, size);
+ updateEdit({
+ ...edit,
+ rotationDegrees,
+ cropArea: edit.aspect
+ ? cropWithAspect(
+ rotatedCrop,
+ edit.aspect,
+ rotatedImageSize(
+ photo,
+ rotationDegrees,
+ ),
+ )
+ : edit.cropArea
+ ? rotatedCrop
+ : undefined,
+ });
+ }}
+ sx={{ ...buttonSx, bgcolor: "#1C1C1E", p: 0 }}
+ >
+ <HugeiconsIcon
+ icon={RotateTopRightIcon}
+ size={20}
+ strokeWidth={1.8}
+ />
+ </Box>
+ <Box
+ role="group"
+ aria-label="Crop aspect ratio"
+ sx={{
+ display: "flex",
+ bgcolor: "#1C1C1E",
+ borderRadius: "999px",
+ px: "4px",
+ }}
+ >
+ {aspects.map(({ label, value }) => (
+ <Box
+ key={label}
+ component="button"
+ type="button"
+ disabled={isSaving}
+ aria-pressed={edit.aspect == value}
+ onClick={() =>
+ updateEdit({
+ ...edit,
+ aspect: value,
+ cropArea: value
+ ? cropWithAspect(crop, value, size)
+ : edit.cropArea,
+ })
+ }
+ sx={{
+ ...buttonSx,
+ flex: "1 0 auto",
+ fontSize: 13,
+ p: 0,
+ color:
+ edit.aspect == value
+ ? "#FFFFFF"
+ : "#A6A6A6",
+ }}
+ >
+ <Box
+ component="span"
+ sx={{
+ alignItems: "center",
+ bgcolor:
+ edit.aspect == value
+ ? "#3A3A3C"
+ : "transparent",
+ borderRadius: "999px",
+ boxSizing: "border-box",
+ display: "flex",
+ height: 36,
+ justifyContent: "center",
+ width: "100%",
+ px: "10px",
+ "@media (max-width: 359px)": {
+ px: "6px",
+ },
+ }}
+ >
+ {label}
+ </Box>
+ </Box>
+ ))}
+ </Box>
+ <Box
+ component="button"
+ type="button"
+ title="Reset edits"
+ disabled={isSaving || !isEdited}
+ onClick={() => updateEdit(originalEdit)}
+ sx={{
+ ...buttonSx,
+ bgcolor: "#1C1C1E",
+ fontSize: 13,
+ p: 0,
+ "&:disabled": {
+ opacity: 1,
+ color: "#777777",
+ cursor: "default",
+ },
+ }}
+ >
+ Reset
+ </Box>
+ </Box>
+ {photos.length > 1 && (
+ <Box sx={{ width: "100%", maxWidth: 390 }}>
+ <SpacePostPhotoStrip
+ activeIndex={activeIndex}
+ disabled={isSaving}
+ onSelect={setActiveIndex}
+ photos={photos.map((photo) => ({
+ id: photo.id,
+ imageUrl: photo.previewURL,
+ }))}
+ />
+ </Box>
+ )}
+ </Box>
+ </Dialog>
+ );
+};
diff --git a/web/apps/space/src/components/PostPhotoStrip.tsx b/web/apps/space/src/components/PostPhotoStrip.tsx
index 68d3f1ae9c..cac50d8e1d 100644
--- a/web/apps/space/src/components/PostPhotoStrip.tsx
+++ b/web/apps/space/src/components/PostPhotoStrip.tsx
@@ -39,9 +39,9 @@ const iconButtonSx = {
export const SpacePostPhotoStrip: React.FC<{
activeIndex: number;
disabled: boolean;
- onAdd: () => void;
- onMove: (from: number, to: number) => void;
- onRemove: () => void;
+ onAdd?: () => void;
+ onMove?: (from: number, to: number) => void;
+ onRemove?: () => void;
onSelect: (index: number) => void;
photos: StripPhoto[];
}> = ({ activeIndex, disabled, onAdd, onMove, onRemove, onSelect, photos }) => {
@@ -53,6 +53,7 @@ export const SpacePostPhotoStrip: React.FC<{
const [announcement, setAnnouncement] = React.useState("");
const [hasPhotosOnRight, setHasPhotosOnRight] = React.useState(false);
const dragging = Boolean(drag);
+ const canMove = Boolean(onMove);
React.useEffect(() => {
const strip = stripRef.current;
@@ -80,7 +81,7 @@ export const SpacePostPhotoStrip: React.FC<{
React.useEffect(() => {
const strip = stripRef.current;
- if (!strip || disabled || photos.length < 2) return;
+ if (!strip || disabled || !canMove || photos.length < 2) return;
let gesture:
| {
pointerID: number;
@@ -185,7 +186,7 @@ export const SpacePostPhotoStrip: React.FC<{
completed.to = positionAt(event.clientX);
stop();
if (active && completed.from != completed.to) {
- callbacksRef.current.onMove(completed.from, completed.to);
+ callbacksRef.current.onMove?.(completed.from, completed.to);
setAnnouncement(
`Photo moved to position ${completed.to + 1} of ${photos.length}`,
);
@@ -215,7 +216,7 @@ export const SpacePostPhotoStrip: React.FC<{
window.removeEventListener("pointercancel", stop);
window.removeEventListener("keydown", cancelOnEscape, true);
};
- }, [disabled, photos.length]);
+ }, [canMove, disabled, photos.length]);
const shownPhotos = drag
? movePostPhoto(photos, drag.from, drag.to)
@@ -303,13 +304,18 @@ export const SpacePostPhotoStrip: React.FC<{
aria-pressed={
photo.id == photos[activeIndex]?.id
}
- aria-keyshortcuts="Alt+ArrowLeft Alt+ArrowRight"
+ aria-keyshortcuts={
+ onMove
+ ? "Alt+ArrowLeft Alt+ArrowRight"
+ : undefined
+ }
disabled={disabled}
onClick={() => onSelect(index)}
onKeyDown={(
event: React.KeyboardEvent,
) => {
if (
+ !onMove ||
!event.altKey ||
![
"ArrowLeft",
@@ -343,7 +349,9 @@ export const SpacePostPhotoStrip: React.FC<{
borderRadius: "9px",
cursor: disabled
? "default"
- : "grab",
+ : onMove
+ ? "grab"
+ : "pointer",
height: "100%",
width: "100%",
overflow: "hidden",
@@ -356,42 +364,45 @@ export const SpacePostPhotoStrip: React.FC<{
>
{preview(photo)}
</Box>
- {index == activeIndex && !dragging && (
- <Box
- component="button"
- type="button"
- aria-label="Remove photo"
- disabled={disabled}
- onClick={onRemove}
- sx={{
- ...iconButtonSx,
- position: "absolute",
- right: -10,
- top: -10,
- width: 32,
- height: 32,
- }}
- >
+ {onRemove &&
+ index == activeIndex &&
+ !dragging && (
<Box
- component="span"
+ component="button"
+ type="button"
+ aria-label="Remove photo"
+ disabled={disabled}
+ onClick={onRemove}
sx={{
- alignItems: "center",
- bgcolor: "#3A3A3A",
- border: "1px solid #000000",
- borderRadius: "50%",
- display: "flex",
- justifyContent: "center",
- width: 20,
- height: 20,
+ ...iconButtonSx,
+ position: "absolute",
+ right: -10,
+ top: -10,
+ width: 32,
+ height: 32,
}}
>
- <HugeiconsIcon
- icon={Cancel01Icon}
- size={12}
- />
+ <Box
+ component="span"
+ sx={{
+ alignItems: "center",
+ bgcolor: "#3A3A3A",
+ border: "1px solid #000000",
+ borderRadius: "50%",
+ display: "flex",
+ justifyContent:
+ "center",
+ width: 20,
+ height: 20,
+ }}
+ >
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ size={12}
+ />
+ </Box>
</Box>
- </Box>
- )}
+ )}
</Box>
</Box>
))}
@@ -412,7 +423,7 @@ export const SpacePostPhotoStrip: React.FC<{
/>
)}
</Box>
- {photos.length < maxSpacePostPhotos && (
+ {onAdd && photos.length < maxSpacePostPhotos && (
<Box
component="button"
type="button"
diff --git a/web/apps/space/src/components/photo-crop/PhotoCrop.tsx b/web/apps/space/src/components/photo-crop/PhotoCrop.tsx
new file mode 100644
index 0000000000..44d306c8f1
--- /dev/null
+++ b/web/apps/space/src/components/photo-crop/PhotoCrop.tsx
@@ -0,0 +1,318 @@
+import { Box } from "@mui/material";
+import React from "react";
+import type { SpaceImageCropArea } from "utils/post-image";
+import {
+ moveImageCrop,
+ resizeImageCrop,
+ rotatedImageSize,
+ type CropHandle,
+ type ImageSize,
+} from "./geometry";
+
+const handles: { handle: CropHandle; label: string; x: number; y: number }[] = [
+ { handle: "nw", label: "top left", x: 0, y: 0 },
+ { handle: "n", label: "top", x: 50, y: 0 },
+ { handle: "ne", label: "top right", x: 100, y: 0 },
+ { handle: "e", label: "right", x: 100, y: 50 },
+ { handle: "se", label: "bottom right", x: 100, y: 100 },
+ { handle: "s", label: "bottom", x: 50, y: 100 },
+ { handle: "sw", label: "bottom left", x: 0, y: 100 },
+ { handle: "w", label: "left", x: 0, y: 50 },
+];
+
+export const SpacePhotoCrop: React.FC<{
+ imageURL: string;
+ imageSize: ImageSize;
+ rotation: number;
+ crop: SpaceImageCropArea;
+ aspect?: number;
+ disabled: boolean;
+ onChange: (crop: SpaceImageCropArea) => void;
+}> = ({ imageURL, imageSize, rotation, crop, aspect, disabled, onChange }) => {
+ const containerRef = React.useRef<HTMLDivElement>(null);
+ const [available, setAvailable] = React.useState({ width: 0, height: 0 });
+ const gesture = React.useRef<{
+ pointerID: number;
+ x: number;
+ y: number;
+ crop: SpaceImageCropArea;
+ handle?: CropHandle;
+ }>(undefined);
+ const size = rotatedImageSize(imageSize, rotation);
+ const scale = Math.min(
+ available.width / size.width,
+ available.height / size.height,
+ );
+ const cropStyle = {
+ left: `${(crop.x / size.width) * 100}%`,
+ top: `${(crop.y / size.height) * 100}%`,
+ width: `${(crop.width / size.width) * 100}%`,
+ height: `${(crop.height / size.height) * 100}%`,
+ };
+
+ React.useEffect(() => {
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry)
+ setAvailable({
+ width: entry.contentRect.width,
+ height: entry.contentRect.height,
+ });
+ });
+ observer.observe(containerRef.current!);
+ return () => observer.disconnect();
+ }, []);
+
+ const change = (
+ start: SpaceImageCropArea,
+ dx: number,
+ dy: number,
+ handle?: CropHandle,
+ ) =>
+ onChange(
+ handle
+ ? resizeImageCrop(
+ start,
+ handle,
+ dx / scale,
+ dy / scale,
+ size,
+ 24 / scale,
+ aspect,
+ )
+ : moveImageCrop(start, dx / scale, dy / scale, size),
+ );
+
+ const start = (
+ event: React.PointerEvent<HTMLElement>,
+ handle?: CropHandle,
+ ) => {
+ if (disabled || !event.isPrimary || event.button != 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ event.currentTarget.focus({ preventScroll: true });
+ event.currentTarget.setPointerCapture(event.pointerId);
+ gesture.current = {
+ pointerID: event.pointerId,
+ x: event.clientX,
+ y: event.clientY,
+ crop,
+ handle,
+ };
+ };
+ const keyDown = (event: React.KeyboardEvent, handle?: CropHandle) => {
+ if (
+ disabled ||
+ !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(
+ event.key,
+ )
+ )
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ const step = event.shiftKey ? 10 : 1;
+ change(
+ crop,
+ event.key == "ArrowLeft"
+ ? -step
+ : event.key == "ArrowRight"
+ ? step
+ : 0,
+ event.key == "ArrowUp"
+ ? -step
+ : event.key == "ArrowDown"
+ ? step
+ : 0,
+ handle,
+ );
+ };
+
+ return (
+ <Box
+ ref={containerRef}
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ flex: 1,
+ justifyContent: "center",
+ minHeight: 0,
+ width: "100%",
+ }}
+ >
+ {scale > 0 && (
+ <Box
+ onPointerMove={(event) => {
+ const active = gesture.current;
+ if (active?.pointerID != event.pointerId) return;
+ change(
+ active.crop,
+ event.clientX - active.x,
+ event.clientY - active.y,
+ active.handle,
+ );
+ }}
+ onPointerUp={() => {
+ gesture.current = undefined;
+ }}
+ onPointerCancel={() => {
+ gesture.current = undefined;
+ }}
+ onLostPointerCapture={() => {
+ gesture.current = undefined;
+ }}
+ sx={{
+ width: size.width * scale,
+ height: size.height * scale,
+ position: "relative",
+ touchAction: "none",
+ userSelect: "none",
+ }}
+ >
+ <Box
+ sx={{
+ position: "absolute",
+ inset: 0,
+ overflow: "hidden",
+ }}
+ >
+ <Box
+ component="img"
+ src={imageURL}
+ alt="Photo to crop"
+ draggable={false}
+ sx={{
+ position: "absolute",
+ left: "50%",
+ top: "50%",
+ width: imageSize.width * scale,
+ height: imageSize.height * scale,
+ maxWidth: "none",
+ transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
+ pointerEvents: "none",
+ }}
+ />
+ <Box
+ style={cropStyle}
+ sx={{
+ position: "absolute",
+ boxShadow: "0 0 0 9999px rgba(0,0,0,0.6)",
+ pointerEvents: "none",
+ }}
+ />
+ </Box>
+ <Box
+ role="group"
+ aria-label="Crop selection"
+ aria-description="Use arrow keys to move the crop. Hold Shift for larger steps."
+ tabIndex={disabled ? -1 : 0}
+ onPointerDown={(event) => start(event)}
+ onKeyDown={(event) => keyDown(event)}
+ style={cropStyle}
+ sx={{
+ position: "absolute",
+ boxSizing: "border-box",
+ border: "1px solid white",
+ cursor: "move",
+ "&:focus-visible": {
+ outline: "2px solid #08C225",
+ outlineOffset: 2,
+ },
+ }}
+ >
+ {[1, 2].map((line) => (
+ <React.Fragment key={line}>
+ <Box
+ sx={{
+ position: "absolute",
+ left: `${(line * 100) / 3}%`,
+ top: 0,
+ bottom: 0,
+ borderLeft:
+ "1px solid rgba(255,255,255,0.35)",
+ pointerEvents: "none",
+ }}
+ />
+ <Box
+ sx={{
+ position: "absolute",
+ top: `${(line * 100) / 3}%`,
+ left: 0,
+ right: 0,
+ borderTop:
+ "1px solid rgba(255,255,255,0.35)",
+ pointerEvents: "none",
+ }}
+ />
+ </React.Fragment>
+ ))}
+ {handles
+ .filter(
+ ({ handle }) => !aspect || handle.length == 2,
+ )
+ .map(({ handle, label, x, y }) => (
+ <Box
+ key={handle}
+ component="button"
+ type="button"
+ disabled={disabled}
+ aria-label={`Resize crop ${label}`}
+ aria-description="Use arrow keys to resize the crop. Hold Shift for larger steps."
+ onPointerDown={(event) =>
+ start(event, handle)
+ }
+ onKeyDown={(event) =>
+ keyDown(event, handle)
+ }
+ sx={{
+ position: "absolute",
+ left: `${x}%`,
+ top: `${y}%`,
+ transform: "translate(-50%, -50%)",
+ width:
+ handle.length == 1 && y != 50
+ ? "calc(100% - 32px)"
+ : 32,
+ height:
+ handle.length == 1 && x != 50
+ ? "calc(100% - 32px)"
+ : 32,
+ minWidth: 16,
+ minHeight: 16,
+ bgcolor: "transparent",
+ border: 0,
+ p: 0,
+ cursor: `${handle}-resize`,
+ touchAction: "none",
+ "&:focus-visible": {
+ outline: "2px solid #08C225",
+ },
+ "&::after": {
+ content: '""',
+ position: "absolute",
+ left: "50%",
+ top: "50%",
+ transform: "translate(-50%, -50%)",
+ width:
+ handle.length == 2
+ ? 10
+ : y == 50
+ ? 3
+ : 16,
+ height:
+ handle.length == 2
+ ? 10
+ : x == 50
+ ? 3
+ : 16,
+ bgcolor: "white",
+ boxShadow:
+ "0 0 2px rgba(0,0,0,0.8)",
+ },
+ }}
+ />
+ ))}
+ </Box>
+ </Box>
+ )}
+ </Box>
+ );
+};
diff --git a/web/apps/space/src/components/photo-crop/geometry.ts b/web/apps/space/src/components/photo-crop/geometry.ts
new file mode 100644
index 0000000000..1889311b9e
--- /dev/null
+++ b/web/apps/space/src/components/photo-crop/geometry.ts
@@ -0,0 +1,108 @@
+import type { SpaceImageCropArea } from "utils/post-image";
+
+export type CropHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";
+export interface ImageSize {
+ width: number;
+ height: number;
+}
+
+const clamp = (value: number, min: number, max: number) =>
+ Math.min(Math.max(value, min), max);
+
+export const rotatedImageSize = (
+ size: ImageSize,
+ rotation: number,
+): ImageSize =>
+ rotation % 180 == 0 ? size : { width: size.height, height: size.width };
+
+export const fullImageCrop = (size: ImageSize): SpaceImageCropArea => ({
+ x: 0,
+ y: 0,
+ width: size.width,
+ height: size.height,
+});
+
+export const cropWithAspect = (
+ crop: SpaceImageCropArea,
+ aspect: number,
+ size: ImageSize,
+): SpaceImageCropArea => {
+ const width = Math.min(
+ Math.sqrt(crop.width * crop.height * aspect),
+ size.width,
+ size.height * aspect,
+ );
+ const height = width / aspect;
+ return {
+ x: clamp(crop.x + crop.width / 2 - width / 2, 0, size.width - width),
+ y: clamp(
+ crop.y + crop.height / 2 - height / 2,
+ 0,
+ size.height - height,
+ ),
+ width,
+ height,
+ };
+};
+
+export const rotateImageCrop = (
+ crop: SpaceImageCropArea,
+ size: ImageSize,
+): SpaceImageCropArea => ({
+ x: size.height - crop.y - crop.height,
+ y: crop.x,
+ width: crop.height,
+ height: crop.width,
+});
+
+export const moveImageCrop = (
+ crop: SpaceImageCropArea,
+ dx: number,
+ dy: number,
+ size: ImageSize,
+): SpaceImageCropArea => ({
+ ...crop,
+ x: clamp(crop.x + dx, 0, size.width - crop.width),
+ y: clamp(crop.y + dy, 0, size.height - crop.height),
+});
+
+export const resizeImageCrop = (
+ crop: SpaceImageCropArea,
+ handle: CropHandle,
+ dx: number,
+ dy: number,
+ size: ImageSize,
+ minSize: number,
+ aspect?: number,
+): SpaceImageCropArea => {
+ const west = handle.includes("w");
+ const north = handle.includes("n");
+ const horizontal = west || handle.includes("e");
+ const vertical = north || handle.includes("s");
+ const anchorX = west ? crop.x + crop.width : crop.x;
+ const anchorY = north ? crop.y + crop.height : crop.y;
+ const maxWidth = west ? anchorX : size.width - anchorX;
+ const maxHeight = north ? anchorY : size.height - anchorY;
+ let width = horizontal ? crop.width + (west ? -dx : dx) : crop.width;
+ let height = vertical ? crop.height + (north ? -dy : dy) : crop.height;
+ if (aspect) {
+ const proposedWidth =
+ Math.abs(dx) >= Math.abs(dy * aspect) ? width : height * aspect;
+ const max = Math.min(maxWidth, maxHeight * aspect);
+ width = clamp(
+ proposedWidth,
+ Math.min(minSize * Math.max(1, aspect), max),
+ max,
+ );
+ height = width / aspect;
+ } else {
+ width = clamp(width, Math.min(minSize, maxWidth), maxWidth);
+ height = clamp(height, Math.min(minSize, maxHeight), maxHeight);
+ }
+ return {
+ x: west ? anchorX - width : crop.x,
+ y: north ? anchorY - height : crop.y,
+ width,
+ height,
+ };
+};
diff --git a/web/apps/space/src/utils/post-image.ts b/web/apps/space/src/utils/post-image.ts
index 8d449f2ea2..a02528a127 100644
--- a/web/apps/space/src/utils/post-image.ts
+++ b/web/apps/space/src/utils/post-image.ts
@@ -32,6 +32,12 @@ export interface SpaceImageCropArea {
y: number;
}
+export interface SpacePostPhotoEdit {
+ cropArea?: SpaceImageCropArea;
+ rotationDegrees: number;
+ aspect?: number;
+}
+
export interface SpaceDraftPostImage {
cropArea?: SpaceImageCropArea;
file: File;
@@ -177,6 +183,18 @@ export const spacePostPreviewImageForFile = async (
}
};
+export const spacePostPreviewImageFromEdit = async (
+ imageURL: string,
+ edit: SpacePostPhotoEdit,
+): Promise<SpacePostPreviewImage> => {
+ const { blob, height, width } = await webPBlobFromEditedImage(
+ imageURL,
+ edit.cropArea,
+ edit.rotationDegrees,
+ );
+ return { url: URL.createObjectURL(blob), height, width };
+};
+
export const prepareSpaceAvatarImage = async (
file: File,
): Promise<PreparedSpaceAvatarImage> => {
diff --git a/web/apps/space/tests/photo-crop.test.ts b/web/apps/space/tests/photo-crop.test.ts
new file mode 100644
index 0000000000..9457c6005d
--- /dev/null
+++ b/web/apps/space/tests/photo-crop.test.ts
@@ -0,0 +1,114 @@
+import { expect, test } from "vitest";
+import {
+ cropWithAspect,
+ fullImageCrop,
+ moveImageCrop,
+ resizeImageCrop,
+ rotateImageCrop,
+ rotatedImageSize,
+ type CropHandle,
+} from "../src/components/photo-crop/geometry";
+
+const landscape = { width: 1200, height: 800 };
+const portrait = { width: 800, height: 1200 };
+
+test.each([1, 3 / 4, 16 / 9])(
+ "fits aspect %s to landscape and portrait photos",
+ (aspect) => {
+ for (const size of [landscape, portrait]) {
+ const crop = cropWithAspect(fullImageCrop(size), aspect, size);
+ expect(crop.width / crop.height).toBeCloseTo(aspect);
+ expect(crop.x).toBeCloseTo((size.width - crop.width) / 2);
+ expect(crop.y).toBeCloseTo((size.height - crop.height) / 2);
+ expect(crop.width <= size.width && crop.height <= size.height).toBe(
+ true,
+ );
+ expect(
+ Math.min(size.width - crop.width, size.height - crop.height),
+ ).toBeCloseTo(0);
+ }
+ },
+);
+
+test("moves the crop to image boundaries without changing its size", () => {
+ const crop = { x: 100, y: 200, width: 400, height: 300 };
+ expect(moveImageCrop(crop, -2000, 2000, landscape)).toEqual({
+ ...crop,
+ x: 0,
+ y: 500,
+ });
+ expect(moveImageCrop(crop, 2000, -2000, landscape)).toEqual({
+ ...crop,
+ x: 800,
+ y: 0,
+ });
+});
+
+test("resizes free edges without moving the opposite edge", () => {
+ const crop = { x: 100, y: 200, width: 400, height: 300 };
+ expect(resizeImageCrop(crop, "w", 80, 50, landscape, 24)).toEqual({
+ x: 180,
+ y: 200,
+ width: 320,
+ height: 300,
+ });
+ expect(resizeImageCrop(crop, "n", 80, 50, landscape, 24)).toEqual({
+ x: 100,
+ y: 250,
+ width: 400,
+ height: 250,
+ });
+});
+
+test.each([undefined, 1, 3 / 4, 16 / 9])(
+ "keeps aspect %s crops inside the photo at every drag boundary",
+ (aspect) => {
+ const handles: CropHandle[] = aspect
+ ? ["nw", "ne", "se", "sw"]
+ : ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
+ for (const size of [landscape, portrait, { width: 12, height: 8 }]) {
+ const crop = aspect
+ ? cropWithAspect(fullImageCrop(size), aspect, size)
+ : fullImageCrop(size);
+ for (const handle of handles) {
+ for (const dx of [-3000, -40, 0, 40, 3000]) {
+ for (const dy of [-3000, -40, 0, 40, 3000]) {
+ const next = resizeImageCrop(
+ crop,
+ handle,
+ dx,
+ dy,
+ size,
+ 24,
+ aspect,
+ );
+ expect(next.x).toBeGreaterThanOrEqual(-1e-10);
+ expect(next.y).toBeGreaterThanOrEqual(-1e-10);
+ expect(next.x + next.width).toBeLessThanOrEqual(
+ size.width + 1e-10,
+ );
+ expect(next.y + next.height).toBeLessThanOrEqual(
+ size.height + 1e-10,
+ );
+ expect(next.width).toBeGreaterThan(0);
+ expect(next.height).toBeGreaterThan(0);
+ if (aspect)
+ expect(next.width / next.height).toBeCloseTo(
+ aspect,
+ );
+ }
+ }
+ }
+ }
+ },
+);
+
+test("rotates the selected region clockwise and restores it after four turns", () => {
+ const original = { x: 100, y: 200, width: 400, height: 300 };
+ let crop = rotateImageCrop(original, landscape);
+ expect(crop).toEqual({ x: 300, y: 100, width: 300, height: 400 });
+ for (let rotation = 90; rotation < 360; rotation += 90) {
+ crop = rotateImageCrop(crop, rotatedImageSize(landscape, rotation));
+ }
+ expect(crop).toEqual(original);
+});