Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add multi-photo publishing and viewing in Space

Anand Baburajan2448711e658d
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rs
index 1fafd8c98d..92c531c10b 100644
--- a/rust/bindings/wasm/space/src/space.rs
+++ b/rust/bindings/wasm/space/src/space.rs
@@ -146,6 +146,14 @@ pub struct PostPhotoAssetOptions {
thumb_hash: Option<String>,
}
+#[derive(Deserialize, Tsify)]
+pub struct PostPhotoInput {
+ #[serde(with = "swb::preserve")]
+ #[tsify(type = "Uint8Array")]
+ bytes: js_sys::Uint8Array,
+ options: PostPhotoAssetOptions,
+}
+
#[derive(Serialize, Tsify)]
#[serde(rename_all = "camelCase")]
pub struct CreatedSpace {
@@ -1227,31 +1235,43 @@ impl SpaceAccountCtxHandle {
pub async fn create_photo_post(
&self,
space_id: String,
- photo_bytes: Vec<u8>,
+ photos: Vec<<PostPhotoInput as Tsify>::JsType>,
caption: Option<String>,
- photo_options: <PostPhotoAssetOptions as Tsify>::JsType,
) -> Result<<PostResponse as Tsify>::JsType, Error> {
- let photo_options = PostPhotoAssetOptions::from_js(photo_options)?;
+ if photos.is_empty() || photos.len() > 10 {
+ return Err(
+ ente_space::Error::InvalidInput("Choose between 1 and 10 photos".into()).into(),
+ );
+ }
+ let photos = photos
+ .into_iter()
+ .map(PostPhotoInput::from_js)
+ .collect::<Result<Vec<_>, _>>()?;
let post_key = self.inner.generate_post_key();
- let object = self
- .inner
- .upload_post_photo_asset(
- &space_id,
- &post_key,
- &photo_bytes,
- ente_space::PostPhotoAssetOptions {
- width: photo_options.width,
- height: photo_options.height,
- media_type: photo_options.media_type,
- thumb_hash: photo_options.thumb_hash,
- },
- )
- .await?;
+ let mut objects = Vec::with_capacity(photos.len());
+ for (position, photo) in photos.into_iter().enumerate() {
+ let mut object = self
+ .inner
+ .upload_post_photo_asset(
+ &space_id,
+ &post_key,
+ &photo.bytes.to_vec(),
+ ente_space::PostPhotoAssetOptions {
+ width: photo.options.width,
+ height: photo.options.height,
+ media_type: photo.options.media_type,
+ thumb_hash: photo.options.thumb_hash,
+ },
+ )
+ .await?;
+ object.position = Some(position as i32);
+ objects.push(object);
+ }
let (post_id, _) = self
.inner
.create_post(
&space_id,
- &[object],
+ &objects,
caption.as_ref().map(String::as_bytes),
Some(&post_key),
)
diff --git a/web/apps/space/public/images/meta-invite.png b/web/apps/space/public/images/meta-invite.png
deleted file mode 100644
index 281e1b2cfe..0000000000
Binary files a/web/apps/space/public/images/meta-invite.png and /dev/null differ
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsx
index 7b2147d59c..172056fd8f 100644
--- a/web/apps/space/src/components/FileViewer.tsx
+++ b/web/apps/space/src/components/FileViewer.tsx
@@ -1,4 +1,6 @@
import {
+ ArrowLeft02Icon,
+ ArrowRight02Icon,
Cancel01Icon,
Delete02Icon,
Edit01Icon,
@@ -22,11 +24,11 @@ import log from "ente-base/log";
import type PhotoSwipe from "photoswipe";
import React from "react";
import type { SpaceInviteIntent } from "services/invite";
+import type { SpacePostAsset, SpacePostAssetURLLoader } from "services/space";
import { spaceDialogBackground, spaceTextMuted } from "styles/colors";
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom, formatSpaceDate } from "utils/display";
import { clampSpaceMessageText } from "utils/message-limits";
-import type { SpaceImageCropArea } from "utils/post-image";
const green = "#08C225";
const textBase = "#F4F4F4";
@@ -40,7 +42,6 @@ const dangerColor = "#F63A3A";
const viewerHeaderHeight = 56;
const viewerBottomPadding = 88;
const viewerDesktopMinWidth = 600;
-const draftViewerBottomPadding = 88;
const captionInputMinHeight = 40;
const replyInputMinHeight = 48;
const replyInputPadding = 14;
@@ -49,8 +50,6 @@ const viewerActionDoneDurationMs = 1000;
const captionInputMaxHeight = 112;
const defaultPhotoWidth = 900;
const defaultPhotoHeight = 680;
-const viewerSwipeMinDeltaPx = 72;
-const viewerSwipeAxisRatio = 1.5;
const viewerHeaderAvatarSize = 28;
const draftPostExitDurationMs = 320;
const keyboardInsetThresholdPx = 80;
@@ -90,25 +89,8 @@ const postButtonSpin = keyframes`
}
`;
-const photoPreviewSkeletonShimmer = keyframes`
- from {
- background-position: 100% 0;
- }
-
- to {
- background-position: -100% 0;
- }
-`;
-
export type SpaceViewerPostActionMode = "draft-post" | "hidden" | "like-only";
-export interface SpaceViewerDraftPostEdit {
- cropArea?: SpaceImageCropArea;
- height?: number;
- rotationDegrees: number;
- width?: number;
-}
-
interface SpaceViewerPostActionConfig {
showLikeButton: boolean;
}
@@ -129,6 +111,9 @@ export interface SpaceViewerPhoto {
friendID?: string;
height?: number;
imageUrl: string;
+ imageAsset?: SpacePostAsset;
+ postPhotoIndex?: number;
+ postPhotoCount?: number;
name: string;
postId?: number;
spaceId?: string;
@@ -146,8 +131,10 @@ interface SpaceViewerDeleteSnapshot {
type DraftPostExitPhase = "idle" | "waiting-for-keyboard" | "animating";
interface SpaceFileViewerProps {
+ closeOnSwipePastEnd?: boolean;
+ draftPhotoControls?: React.ReactNode;
+ onLoadPhoto?: SpacePostAssetURLLoader;
draftPostPreparationError?: string;
- isDraftPostPreparing?: boolean;
isDraftPostPreviewPending?: boolean;
onClose: () => void;
onDeletePost?: () => Promise<void> | void;
@@ -156,10 +143,7 @@ interface SpaceFileViewerProps {
onDraftPostPublished?: () => void;
onAddFriendForPostAction?: (intent: SpaceInviteIntent) => void;
onOpenProfile?: () => void;
- onPublishDraftPost?: (
- caption: string,
- edit: SpaceViewerDraftPostEdit,
- ) => Promise<void>;
+ onPublishDraftPost?: (caption: string) => Promise<void>;
onReplyToPost?: (
spaceId: string,
postId: number,
@@ -167,51 +151,32 @@ interface SpaceFileViewerProps {
) => Promise<void>;
onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
onUpdatePostCaption?: (postId: number, caption: string) => Promise<void>;
- onSwipeLeft?: () => void;
- onSwipeRight?: () => void;
onPhotoIndexChange?: (index: number) => void;
photo: SpaceViewerPhoto;
photoIndex?: number;
photos?: SpaceViewerPhoto[];
focusReplyOnOpen?: boolean;
postActionMode?: SpaceViewerPostActionMode;
- showSequenceProgress?: boolean;
-}
-
-interface ViewerSwipeGesture {
- lastX: number;
- lastY: number;
- pointerId?: number;
- startX: number;
- startY: number;
}
-const viewerSwipePointFromEvent = (event: Event) => {
- if (event.type.startsWith("mouse")) return undefined;
- if (
- "pointerType" in event &&
- (event as PointerEvent).pointerType == "mouse"
- ) {
- return undefined;
- }
+const viewerTouchPoint = (event: Event) => {
if ("changedTouches" in event) {
const touch = (event as TouchEvent).changedTouches[0];
- if (!touch) return undefined;
- return { x: touch.pageX, y: touch.pageY };
+ return touch ? { x: touch.pageX, y: touch.pageY } : undefined;
}
- if ("pageX" in event && "pageY" in event) {
- return {
- pointerId:
- "pointerId" in event
- ? (event as PointerEvent).pointerId
- : undefined,
- x: (event as MouseEvent).pageX,
- y: (event as MouseEvent).pageY,
- };
+ if (
+ "pointerType" in event &&
+ (event as PointerEvent).pointerType != "mouse"
+ ) {
+ const pointer = event as PointerEvent;
+ return { x: pointer.pageX, y: pointer.pageY };
}
return undefined;
};
+const viewerPhotoContentKey = (photo: SpaceViewerPhoto) =>
+ `${photo.imageUrl}:${photo.width ?? ""}:${photo.height ?? ""}:${photo.postPhotoCount ?? ""}`;
+
const viewerSwipeStartsOnInteractiveTarget = (target: EventTarget | null) =>
target instanceof Element &&
Boolean(
@@ -309,9 +274,11 @@ const SpaceViewerCaption: React.FC<{ caption: string }> = ({ caption }) => {
};
export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
+ closeOnSwipePastEnd = false,
+ draftPhotoControls,
+ onLoadPhoto,
draftPostPreparationError,
focusReplyOnOpen = false,
- isDraftPostPreparing = false,
isDraftPostPreviewPending = false,
onClose,
onDeletePost,
@@ -324,15 +291,25 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
onReplyToPost,
onSetPostLiked,
onUpdatePostCaption,
- onSwipeLeft,
- onSwipeRight,
onPhotoIndexChange,
photo,
- photoIndex = 0,
+ photoIndex,
photos,
postActionMode = "like-only",
- showSequenceProgress = false,
}) => {
+ const [localPhotoIndex, setLocalPhotoIndex] = React.useState(0);
+ const [loadedPhotoURLs, setLoadedPhotoURLs] = React.useState<
+ Record<string, string>
+ >({});
+ const [photoLoadErrors, setPhotoLoadErrors] = React.useState<
+ Record<string, true>
+ >({});
+ const photoLoadsRef = React.useRef(new Set<string>());
+ const photoKey = (item: SpaceViewerPhoto) =>
+ item.imageAsset
+ ? `${item.imageAsset.spaceId}:${item.imageAsset.objectKey}`
+ : item.imageUrl;
+ const hasDraftPhotoControls = Boolean(draftPhotoControls);
const activePostActionMode = postActionMode;
const isDraftPost = activePostActionMode == "draft-post";
const { showLikeButton: showPhotoLikeButton } =
@@ -345,22 +322,32 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
null,
);
const isDeleteViewerLocked = Boolean(deleteActionPhase) || isDeleteExit;
- const incomingViewerPhotos = photos && photos.length > 0 ? photos : [photo];
+ const incomingViewerPhotos = (
+ photos && photos.length > 0 ? photos : [photo]
+ ).map((item) => ({
+ ...item,
+ imageUrl: loadedPhotoURLs[photoKey(item)] || item.imageUrl || "",
+ }));
const viewerPhotos = isDeleteViewerLocked
? (deleteSnapshotRef.current?.photos ?? incomingViewerPhotos)
: incomingViewerPhotos;
const activePhotoIndex = Math.min(
Math.max(
isDeleteViewerLocked
- ? (deleteSnapshotRef.current?.photoIndex ?? photoIndex)
- : photoIndex,
+ ? (deleteSnapshotRef.current?.photoIndex ??
+ photoIndex ??
+ localPhotoIndex)
+ : (photoIndex ?? localPhotoIndex),
0,
),
viewerPhotos.length - 1,
);
const activePhoto = viewerPhotos[activePhotoIndex] ?? photo;
- const shouldShowSequenceProgress =
- showSequenceProgress && !isDraftPost && viewerPhotos.length > 1;
+ const postPhotoCount = activePhoto.postPhotoCount ?? 1;
+ const postPhotoIndex = activePhoto.postPhotoIndex ?? 0;
+ const activePhotoKey = photoKey(activePhoto);
+ const activePostKey = `${activePhoto.spaceId ?? ""}:${activePhoto.postId ?? ""}`;
+ const hasPhotoLoadError = Boolean(photoLoadErrors[activePhotoKey]);
const canUpdatePostCaption =
!isDraftPost &&
Boolean(activePhoto.postId) &&
@@ -372,16 +359,17 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
const initialPhotoIndexRef = React.useRef(activePhotoIndex);
const fallbackPhotoRef = React.useRef(activePhoto);
const pswpRef = React.useRef<PhotoSwipe | undefined>(undefined);
+ const closeOnSwipePastEndRef = React.useRef(closeOnSwipePastEnd);
+ closeOnSwipePastEndRef.current = closeOnSwipePastEnd;
viewerPhotosRef.current = viewerPhotos;
onCloseRef.current = onClose;
onPhotoIndexChangeRef.current = onPhotoIndexChange;
fallbackPhotoRef.current = activePhoto;
const viewerPhotosContentKey = viewerPhotos
- .map(
- (item) =>
- `${item.imageUrl}:${item.width ?? ""}:${item.height ?? ""}`,
- )
+ .map(viewerPhotoContentKey)
.join("|");
+ const viewerPhotoKeys = viewerPhotos.map(photoKey).join("|");
+ const displayedContentKeysRef = React.useRef<string[]>([]);
const [isPhotoLiked, setIsPhotoLiked] = React.useState(
activePhoto.viewerLiked ?? false,
);
@@ -398,6 +386,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
const isCaptionEditingRef = React.useRef(isCaptionEditing);
isCaptionEditingRef.current = isCaptionEditing;
const [replyText, setReplyText] = React.useState("");
+ const replyDraftsRef = React.useRef(new Map<string, string>());
const [isReplyFocused, setIsReplyFocused] =
React.useState(focusReplyOnOpen);
const [replyActionPhase, setReplyActionPhase] =
@@ -416,10 +405,6 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
typeof window != "undefined" &&
window.innerWidth >= viewerDesktopMinWidth,
);
- const [queuedDraftPost, setQueuedDraftPost] = React.useState<{
- caption: string;
- edit: SpaceViewerDraftPostEdit;
- }>();
const displayName = firstNameFrom(activePhoto.name);
const dateLabel = formatSpaceDate(activePhoto.timestampMs);
const displayCaption = isDraftPost ? "" : caption.trim();
@@ -447,15 +432,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
!onUpdatePostCaption;
const isDraftPostActionRunning = draftPostActionPhase != null;
const hasDraftPostPreparationError = Boolean(draftPostPreparationError);
- const canQueueDraftPostPublish =
- isDraftPostPreparing &&
- !isDraftPostPreviewPending &&
- !hasDraftPostPreparationError;
const isDraftPostPublishDisabled =
isDraftPostActionRunning ||
isDraftPostPreviewPending ||
hasDraftPostPreparationError ||
- (!onPublishDraftPost && !canQueueDraftPostPublish);
+ !onPublishDraftPost;
const isReplyActionRunning = replyActionPhase != null;
const canAddFriendForPostAction = Boolean(
!isDraftPost && onAddFriendForPostAction,
@@ -468,14 +449,10 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
const isReplyMode =
canReplyToPost &&
(isReplyFocused || replyText.trim().length > 0 || isReplyActionRunning);
- const usePhotoSwipeViewer = !isDraftPost || isDesktopViewer;
const canSendReply =
canReplyToPost &&
!isReplyActionRunning &&
(canAddFriendForPostAction || replyText.trim().length > 0);
- const swipeGestureRef = React.useRef<ViewerSwipeGesture | null>(null);
- const swipeActionsRef = React.useRef({ onSwipeLeft, onSwipeRight });
- swipeActionsRef.current = { onSwipeLeft, onSwipeRight };
const isSwipeBlockedRef = React.useRef(false);
isSwipeBlockedRef.current =
isActionsOpen ||
@@ -484,9 +461,10 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
isDeleteExit ||
isDraftPostExit ||
isCaptionEditing ||
- isReplyMode ||
- isDraftPost ||
- isDraftPostPreviewPending;
+ isReplyActionRunning ||
+ isDraftPostActionRunning;
+ const isDismissBlockedRef = React.useRef(false);
+ isDismissBlockedRef.current = isSwipeBlockedRef.current || isReplyMode;
const viewerViewportSize = React.useCallback(() => {
const currentSize = currentViewerViewportSize(viewerRootRef.current);
const stableSize = stableViewportSizeRef.current;
@@ -552,7 +530,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
}, [caption]);
const closeViewer = () => {
- if (isDraftPostExit) return;
+ if (isDraftPostExit || isDraftPostActionRunning) return;
if (isCaptionEditing && !isCaptionUpdateActionRunning) {
cancelCaptionEdit();
return;
@@ -616,14 +594,6 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
})();
};
- const draftPostEdit = React.useCallback((): SpaceViewerDraftPostEdit => {
- return {
- height: activePhoto.height,
- rotationDegrees: 0,
- width: activePhoto.width,
- };
- }, [activePhoto.height, activePhoto.width]);
-
const dismissCaptionKeyboard = React.useCallback(
(onDismissed: () => void) => {
const input = captionInputRef.current;
@@ -681,29 +651,24 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
React.useEffect(() => () => cancelKeyboardDismissWaitRef.current?.(), []);
const publishDraftPostWithCaption = React.useCallback(
- (captionToPublish: string, editToPublish: SpaceViewerDraftPostEdit) => {
+ (captionToPublish: string) => {
if (!onPublishDraftPost || isDeleteExit || isDraftPostExit) return;
-
setDraftPostActionPhase("busy");
- let publishPromise: Promise<void>;
+ let publication: Promise<void>;
try {
- publishPromise = Promise.resolve(
- onPublishDraftPost(captionToPublish, editToPublish),
- );
+ publication = onPublishDraftPost(captionToPublish);
} catch (error) {
log.error("Failed to publish space post", error);
setDraftPostActionPhase(null);
return;
}
-
- setQueuedDraftPost(undefined);
setDraftPostExitPhase("waiting-for-keyboard");
onDraftPostExitStart?.();
dismissCaptionKeyboard(() => {
setDraftPostExitPhase("animating");
onDraftPostExitAnimationStart?.();
});
- void publishPromise.catch((error: unknown) => {
+ void publication.catch((error: unknown) => {
log.error("Failed to publish space post", error);
});
},
@@ -728,16 +693,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
)
return;
- const edit = draftPostEdit();
- if (!onPublishDraftPost) {
- if (!canQueueDraftPostPublish) return;
-
- setQueuedDraftPost({ caption, edit });
- setDraftPostActionPhase("busy");
- return;
- }
-
- publishDraftPostWithCaption(caption, edit);
+ publishDraftPostWithCaption(caption);
};
const sendReply = () => {
@@ -764,6 +720,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
activePhoto.postId!,
text,
);
+ replyDraftsRef.current.delete(activePostKey);
setReplyText("");
setReplyActionPhase("done");
} catch (error) {
@@ -835,21 +792,6 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
return () => window.clearTimeout(timeoutID);
}, [deleteActionPhase]);
- React.useEffect(() => {
- if (draftPostPreparationError && queuedDraftPost != undefined) {
- setQueuedDraftPost(undefined);
- setDraftPostActionPhase(null);
- }
- }, [draftPostPreparationError, queuedDraftPost]);
-
- React.useEffect(() => {
- if (queuedDraftPost == undefined || !onPublishDraftPost) return;
-
- const draftPost = queuedDraftPost;
- setQueuedDraftPost(undefined);
- publishDraftPostWithCaption(draftPost.caption, draftPost.edit);
- }, [onPublishDraftPost, publishDraftPostWithCaption, queuedDraftPost]);
-
React.useEffect(() => {
if (captionUpdateActionPhase != "done") return;
@@ -873,30 +815,24 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
}, [replyActionPhase]);
React.useEffect(() => {
- if (isCaptionEditingRef.current) return;
+ if (isDraftPost || isCaptionEditingRef.current) return;
setCaption(activePhoto.caption ?? "");
setCaptionEditValue(activePhoto.caption ?? "");
- }, [activePhoto.caption]);
+ }, [activePhoto.caption, activePhoto.postId, isDraftPost]);
React.useEffect(() => {
setIsPhotoLiked(activePhoto.viewerLiked ?? false);
- }, [activePhoto.imageUrl, activePhoto.postId, activePhoto.viewerLiked]);
+ }, [activePhoto.postId, activePhoto.viewerLiked]);
React.useEffect(() => {
setCaptionUpdateActionPhase(null);
setHasCaptionUpdateError(false);
setIsCaptionEditing(false);
- setReplyText("");
+ setReplyText(replyDraftsRef.current.get(activePostKey) ?? "");
setIsReplyFocused(focusReplyOnOpen && canReplyToPost);
setReplyActionPhase(null);
- }, [
- activePhoto.imageUrl,
- activePhoto.postId,
- activePhoto.timestampMs,
- canReplyToPost,
- focusReplyOnOpen,
- ]);
+ }, [activePostKey, canReplyToPost, focusReplyOnOpen]);
React.useEffect(() => {
setPhotoLikePopID(0);
@@ -912,21 +848,63 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
return () => window.clearTimeout(timeoutID);
}, [photoLikePopID]);
+ React.useEffect(() => {
+ if (!onLoadPhoto) return;
+ const requested = viewerPhotosRef.current.slice(
+ Math.max(0, activePhotoIndex - 1),
+ activePhotoIndex + 2,
+ );
+ for (const item of requested) {
+ const key = photoKey(item);
+ if (
+ !item.imageAsset ||
+ photoLoadErrors[key] ||
+ photoLoadsRef.current.has(key)
+ )
+ continue;
+ photoLoadsRef.current.add(key);
+ void onLoadPhoto(item.imageAsset)
+ .then((url) => {
+ setLoadedPhotoURLs((current) =>
+ current[key] == url
+ ? current
+ : { ...current, [key]: url },
+ );
+ })
+ .catch((error: unknown) => {
+ log.warn("Failed to load post photo", error);
+ setPhotoLoadErrors((current) => ({
+ ...current,
+ [key]: true,
+ }));
+ })
+ .finally(() => {
+ photoLoadsRef.current.delete(key);
+ });
+ }
+ }, [activePhotoIndex, onLoadPhoto, viewerPhotoKeys, photoLoadErrors]);
+
React.useEffect(() => {
const pswp = pswpRef.current;
if (!pswp) return;
pswp.options.allowPanToNext = viewerPhotosRef.current.length > 1;
- const refreshIndex = (index: number) => {
- if (index >= 0 && index < viewerPhotosRef.current.length) {
+ const contentKeys = viewerPhotosRef.current.map(viewerPhotoContentKey);
+ const previousKeys = displayedContentKeysRef.current;
+ displayedContentKeysRef.current = contentKeys;
+ contentKeys.forEach((key, index) => {
+ if (key != previousKeys[index]) {
pswp.refreshSlideContent(index);
}
- };
- refreshIndex(pswp.currIndex - 1);
- refreshIndex(pswp.currIndex);
- refreshIndex(pswp.currIndex + 1);
+ });
}, [viewerPhotosContentKey]);
+ React.useEffect(() => {
+ const pswp = pswpRef.current;
+ if (pswp && pswp.currIndex != activePhotoIndex)
+ pswp.goTo(activePhotoIndex);
+ }, [activePhotoIndex]);
+
const handleDeleteSheetExited = () => {
if (!isDeleteExit) return;
@@ -1009,11 +987,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
React.useEffect(() => {
const root = viewerRootRef.current;
if (!root) return;
- if (!usePhotoSwipeViewer || isDraftPostPreviewPending) return;
let disposed = false;
let closedByReact = false;
let pswp: PhotoSwipe | undefined;
+ let edgeSwipeStart: { x: number; y: number } | undefined;
void import("photoswipe").then(({ default: PhotoSwipeClass }) => {
if (disposed || !viewerRootRef.current) return;
@@ -1021,7 +999,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
pswp = new PhotoSwipeClass({
allowPanToNext: viewerPhotosRef.current.length > 1,
appendToEl: viewerRootRef.current,
- arrowKeys: false,
+ arrowKeys: true,
arrowNext: false,
arrowPrev: false,
bgClickAction: false,
@@ -1039,10 +1017,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
loop: false,
mainClass: "pswp-space-viewer",
paddingFn: () => ({
- bottom:
- window.innerWidth >= viewerDesktopMinWidth
- ? 0
- : viewerBottomPadding,
+ bottom: hasDraftPhotoControls
+ ? 176
+ : window.innerWidth >= viewerDesktopMinWidth
+ ? 0
+ : viewerBottomPadding,
left: 0,
right: 0,
top:
@@ -1060,10 +1039,17 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
zoom: false,
});
pswpRef.current = pswp;
+ displayedContentKeysRef.current = viewerPhotosRef.current.map(
+ viewerPhotoContentKey,
+ );
pswp.addFilter("numItems", () => viewerPhotosRef.current.length);
pswp.addFilter("itemData", (_, index) => {
const item =
viewerPhotosRef.current[index] ?? fallbackPhotoRef.current;
+ if (!item.imageUrl)
+ return {
+ html: `<div class="space-photo-placeholder" role="status">${item.postPhotoCount == 0 ? "Add photos to your post" : "Loading photo…"}</div>`,
+ };
return {
alt: item.alt ?? `${item.name} post`,
height: item.height ?? defaultPhotoHeight,
@@ -1075,7 +1061,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
if (!closedByReact) onCloseRef.current();
});
pswp.on("verticalDrag", (event) => {
- if (isSwipeBlockedRef.current) event.preventDefault();
+ if (isDismissBlockedRef.current) event.preventDefault();
});
pswp.on("zoomPanUpdate", () => {
root.style.setProperty(
@@ -1086,85 +1072,54 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
pswp.on("change", () => {
const nextIndex = pswp?.currIndex;
if (nextIndex != undefined) {
+ setLocalPhotoIndex(nextIndex);
onPhotoIndexChangeRef.current?.(nextIndex);
}
});
pswp.on("keydown", (event) => {
- if (event.originalEvent.target instanceof HTMLTextAreaElement) {
+ if (
+ isSwipeBlockedRef.current ||
+ event.originalEvent.target instanceof HTMLTextAreaElement
+ ) {
event.preventDefault();
}
});
- pswp.on("pointerDown", ({ originalEvent }) => {
- if (isSwipeBlockedRef.current) return;
- if (
- !swipeActionsRef.current.onSwipeLeft &&
- !swipeActionsRef.current.onSwipeRight
- ) {
+ pswp.on("pointerDown", (event) => {
+ if (isSwipeBlockedRef.current) {
+ event.preventDefault();
return;
}
- if (viewerSwipeStartsOnInteractiveTarget(originalEvent.target))
+ if (edgeSwipeStart) {
+ edgeSwipeStart = undefined;
return;
-
- const point = viewerSwipePointFromEvent(originalEvent);
- if (!point) return;
-
- swipeGestureRef.current = {
- lastX: point.x,
- lastY: point.y,
- pointerId: point.pointerId,
- startX: point.x,
- startY: point.y,
- };
- });
- pswp.on("pointerMove", ({ originalEvent }) => {
- const gesture = swipeGestureRef.current;
- if (!gesture) return;
-
- const point = viewerSwipePointFromEvent(originalEvent);
- if (!point) return;
+ }
if (
- gesture.pointerId != undefined &&
- point.pointerId != undefined &&
- gesture.pointerId != point.pointerId
- ) {
+ !closeOnSwipePastEndRef.current ||
+ isDismissBlockedRef.current ||
+ pswp!.currIndex != viewerPhotosRef.current.length - 1 ||
+ pswp!.currSlide?.isPannable()
+ )
return;
- }
-
- gesture.lastX = point.x;
- gesture.lastY = point.y;
+ edgeSwipeStart = viewerTouchPoint(event.originalEvent);
});
pswp.on("pointerUp", ({ originalEvent }) => {
- const gesture = swipeGestureRef.current;
- swipeGestureRef.current = null;
- if (!gesture || isSwipeBlockedRef.current) return;
-
- const point = viewerSwipePointFromEvent(originalEvent);
- if (
- point &&
- (gesture.pointerId == undefined ||
- point.pointerId == undefined ||
- gesture.pointerId == point.pointerId)
- ) {
- gesture.lastX = point.x;
- gesture.lastY = point.y;
- }
-
- const deltaX = gesture.lastX - gesture.startX;
- const deltaY = gesture.lastY - gesture.startY;
- if (Math.abs(deltaX) < viewerSwipeMinDeltaPx) return;
+ const start = edgeSwipeStart;
+ edgeSwipeStart = undefined;
if (
- Math.abs(deltaX) <
- Math.abs(deltaY) * viewerSwipeAxisRatio
- ) {
+ !start ||
+ originalEvent.type.endsWith("cancel") ||
+ isDismissBlockedRef.current ||
+ pswp!.gestures.isMultitouch ||
+ pswp!.currSlide?.isPannable()
+ )
return;
+ const end = viewerTouchPoint(originalEvent);
+ if (!end) return;
+ const dx = end.x - start.x;
+ const dy = end.y - start.y;
+ if (dx < -72 && Math.abs(dx) > Math.abs(dy) * 1.5) {
+ onCloseRef.current();
}
- if (deltaX < 0 && pswp?.currSlide?.isPannable()) return;
-
- const swipeAction =
- deltaX < 0
- ? swipeActionsRef.current.onSwipeLeft
- : swipeActionsRef.current.onSwipeRight;
- swipeAction?.();
});
pswp.init();
});
@@ -1172,12 +1127,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
return () => {
disposed = true;
closedByReact = true;
- swipeGestureRef.current = null;
pswpRef.current = undefined;
pswp?.destroy();
root.style.removeProperty("--space-viewer-bg-opacity");
};
- }, [isDraftPostPreviewPending, usePhotoSwipeViewer, viewerViewportSize]);
+ }, [hasDraftPhotoControls, viewerViewportSize]);
React.useEffect(() => {
if (typeof document == "undefined") return;
@@ -1191,7 +1145,12 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
React.useEffect(() => {
const closeOnEscape = (event: KeyboardEvent) => {
- if (addFriendSheetOpen || deleteSheetOpen || isDraftPostExit)
+ if (
+ addFriendSheetOpen ||
+ deleteSheetOpen ||
+ isDraftPostExit ||
+ isDraftPostActionRunning
+ )
return;
if (event.key != "Escape") return;
@@ -1206,6 +1165,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
return () => window.removeEventListener("keydown", closeOnEscape);
}, [
cancelCaptionEdit,
+ isDraftPostActionRunning,
addFriendSheetOpen,
deleteSheetOpen,
isDraftPostExit,
@@ -1247,6 +1207,14 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
transition: `opacity ${draftPostExitDurationMs}ms cubic-bezier(0.22, 1, 0.36, 1)`,
width: "100%",
zIndex: 1300,
+ "& .space-photo-placeholder": {
+ alignItems: "center",
+ color: "#A6A6A6",
+ display: "flex",
+ height: "100%",
+ justifyContent: "center",
+ fontSize: 14,
+ },
"& [data-space-viewer-chrome='true'], & [data-space-viewer-bottom='true']":
{ opacity: "var(--space-viewer-bg-opacity, 1)" },
"@media (prefers-reduced-motion: reduce)": {
@@ -1404,33 +1372,6 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
justifySelf: "flex-end",
}}
>
- {shouldShowSequenceProgress && (
- <Box
- component="span"
- aria-label={`Post ${activePhotoIndex + 1} of ${viewerPhotos.length}`}
- sx={{
- alignItems: "center",
- bgcolor: "#F63A3A",
- borderRadius: "999px",
- boxSizing: "border-box",
- color: "#FFFFFF",
- display: "inline-flex",
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 12,
- fontVariantNumeric: "tabular-nums",
- fontWeight: 700,
- height: 24,
- justifyContent: "center",
- lineHeight: "16px",
- minWidth: 48,
- px: "10px",
- whiteSpace: "nowrap",
- }}
- >
- {activePhotoIndex + 1} / {viewerPhotos.length}
- </Box>
- )}
{canManagePost && !isCaptionEditing && (
<Box
component="button"
@@ -1471,6 +1412,34 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
/>
</Box>
)}
+ {postPhotoCount > 1 && (
+ <Box
+ component="span"
+ aria-live="polite"
+ aria-label={`Photo ${postPhotoIndex + 1} of ${postPhotoCount}`}
+ sx={{
+ alignItems: "center",
+ bgcolor: "#FFFFFF",
+ borderRadius: "999px",
+ boxSizing: "border-box",
+ color: "#000000",
+ display: "inline-flex",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 12,
+ fontVariantNumeric: "tabular-nums",
+ fontWeight: 700,
+ height: 24,
+ justifyContent: "center",
+ lineHeight: "16px",
+ minWidth: 48,
+ px: "10px",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {postPhotoIndex + 1} / {postPhotoCount}
+ </Box>
+ )}
<Box
component="button"
type="button"
@@ -1484,7 +1453,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
>
<HugeiconsIcon
icon={Cancel01Icon}
- size={18}
+ size={20}
strokeWidth={1.8}
/>
</Box>
@@ -1623,50 +1592,83 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
width: "100%",
}}
/>
- {isDraftPost && (!isDesktopViewer || isDraftPostPreviewPending) && (
+ {isDesktopViewer && viewerPhotos.length > 1 && (
+ <>
+ {[-1, 1].map((direction) => (
+ <Box
+ key={direction}
+ component="button"
+ type="button"
+ aria-label={
+ direction < 0 ? "Previous photo" : "Next photo"
+ }
+ disabled={
+ isSwipeBlockedRef.current ||
+ (direction < 0
+ ? activePhotoIndex == 0
+ : activePhotoIndex ==
+ viewerPhotos.length - 1)
+ }
+ onClick={() =>
+ pswpRef.current?.goTo(
+ activePhotoIndex + direction,
+ )
+ }
+ sx={{
+ ...viewerHeaderButtonSx,
+ bgcolor: "rgba(0,0,0,0.5)",
+ left: direction < 0 ? 16 : "auto",
+ right: direction > 0 ? 16 : "auto",
+ position: "absolute",
+ top: "45%",
+ zIndex: 2,
+ "&:disabled": { opacity: 0.25 },
+ }}
+ >
+ <HugeiconsIcon
+ icon={
+ direction < 0
+ ? ArrowLeft02Icon
+ : ArrowRight02Icon
+ }
+ size={24}
+ />
+ </Box>
+ ))}
+ </>
+ )}
+ {hasPhotoLoadError && (
<Box
sx={{
- bottom: { xs: draftViewerBottomPadding, sm: 0 },
- boxSizing: "border-box",
- display: "grid",
- left: 0,
- overflow: "hidden",
- placeItems: "center",
- position: "fixed",
- right: 0,
- top: { xs: viewerHeaderHeight, sm: 0 },
- zIndex: 0,
+ alignSelf: "center",
+ position: "absolute",
+ top: "45%",
+ zIndex: 2,
}}
>
- {isDraftPostPreviewPending ? (
- <Box
- role="status"
- aria-label="Preparing photo preview"
- sx={{
- animation: `${photoPreviewSkeletonShimmer} 1.4s ease-in-out infinite`,
- aspectRatio: "3 / 4",
- bgcolor: "#171717",
- backgroundImage:
- "linear-gradient(90deg, #171717 0%, #242424 42%, #2D2D2D 50%, #242424 58%, #171717 100%)",
- backgroundSize: "200% 100%",
- boxShadow: "0 16px 42px rgba(0, 0, 0, 0.34)",
- overflow: "hidden",
- width: "100vw",
- }}
- />
- ) : (
- <Box
- component="img"
- alt={activePhoto.alt ?? `${activePhoto.name} post`}
- src={activePhoto.imageUrl}
- sx={{
- display: "block",
- maxHeight: "100%",
- maxWidth: "100vw",
- objectFit: "contain",
- }}
- />
- )}
+ <Box
+ component="button"
+ type="button"
+ onClick={() =>
+ setPhotoLoadErrors((current) => {
+ return Object.fromEntries(
+ Object.entries(current).filter(
+ ([key]) => key != activePhotoKey,
+ ),
+ );
+ })
+ }
+ sx={{
+ bgcolor: "#333333",
+ border: 0,
+ borderRadius: "24px",
+ color: textBase,
+ cursor: "pointer",
+ p: 2,
+ }}
+ >
+ Couldn&apos;t load photo. Retry
+ </Box>
</Box>
)}
<Box
@@ -1708,7 +1710,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
boxSizing: "border-box",
display: "flex",
flexDirection: "column",
- gap: "8px",
+ gap: "4px",
left: { xs: "16px", sm: "auto" },
maxWidth: { sm: 390 },
position: "fixed",
@@ -1717,6 +1719,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
zIndex: 2,
}}
>
+ {draftPhotoControls}
{draftPostPreparationError && (
<Box
role="alert"
@@ -1789,11 +1792,9 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
component="button"
type="button"
aria-label={
- draftPostActionPhase == "busy"
- ? "Posting"
- : draftPostPreparationError
- ? "Photo could not be prepared"
- : "Post photo"
+ draftPostPreparationError
+ ? "Photo could not be prepared"
+ : "Post photos"
}
disabled={isDraftPostPublishDisabled}
onClick={publishDraftPost}
@@ -1833,7 +1834,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
},
}}
>
- {draftPostPreparationError ? "Error" : "Post"}
+ Post
</Box>
</Box>
</Box>
@@ -2085,6 +2086,10 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
);
event.currentTarget.value = nextText;
setReplyText(nextText);
+ replyDraftsRef.current.set(
+ activePostKey,
+ nextText,
+ );
},
onFocus: () => setIsReplyFocused(true),
onKeyDown: handleReplyKeyDown,
diff --git a/web/apps/space/src/components/HomeHeader.tsx b/web/apps/space/src/components/HomeHeader.tsx
index e21cd9784b..8a7ef6232f 100644
--- a/web/apps/space/src/components/HomeHeader.tsx
+++ b/web/apps/space/src/components/HomeHeader.tsx
@@ -66,7 +66,7 @@ export const SpaceHomeHeader: React.FC<SpaceHomeHeaderProps> = ({
zIndex: 4,
"&::after": {
bgcolor: headerBackground,
- borderRadius: "22px",
+ borderRadius: "16px",
content: '""',
height: spaceHomeHeaderBarHeight,
left: "16px",
diff --git a/web/apps/space/src/components/MessagesPage.tsx b/web/apps/space/src/components/MessagesPage.tsx
index ba391d2bec..82efb26d9b 100644
--- a/web/apps/space/src/components/MessagesPage.tsx
+++ b/web/apps/space/src/components/MessagesPage.tsx
@@ -121,7 +121,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
profileLoadError,
profileLoadStatus,
setFriends,
- setPendingPostPhotoFile,
+ setPendingPostPhotoFiles,
} = useSpaceAppState();
const [conversations, setConversations] = React.useState<
SpaceMessageConversation[]
@@ -697,7 +697,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
}
onOpenThread={openConversation}
onPostPhotoSelect={(file) => {
- setPendingPostPhotoFile(file);
+ setPendingPostPhotoFiles(file);
}}
onLoadActivityPost={(post) =>
loadCurrentMessageActivityPostPreview(post, actorSpaceId)
diff --git a/web/apps/space/src/components/PageMeta.tsx b/web/apps/space/src/components/PageMeta.tsx
index c9d3f99290..409a30b23d 100644
--- a/web/apps/space/src/components/PageMeta.tsx
+++ b/web/apps/space/src/components/PageMeta.tsx
@@ -10,7 +10,7 @@ const spaceInvitePreviewDescription =
"See the everyday photos I share on Ente Space.";
const previewImages = {
home: "https://ente.space/images/meta.png",
- invite: "https://ente.space/images/meta-invite.png",
+ invite: "https://ente.space/images/meta.png",
} as const;
interface SpacePageMetaProps {
diff --git a/web/apps/space/src/components/PostComposer.tsx b/web/apps/space/src/components/PostComposer.tsx
index bdbbb2e0c8..cb460ee7c6 100644
--- a/web/apps/space/src/components/PostComposer.tsx
+++ b/web/apps/space/src/components/PostComposer.tsx
@@ -3,11 +3,12 @@ import {
SpaceViewerPostBackdrop,
type SpaceViewerPhoto,
} from "components/FileViewer";
+import { SpacePostPhotoInput } from "components/PostPhotoInput";
+import { SpacePostPhotoStrip } from "components/PostPhotoStrip";
import log from "ente-base/log";
import { useBrowserBackClose } from "hooks/use-browser-back-close";
import React from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
-import type { SpacePost } from "services/space";
import { useSpaceAppState } from "state/app-state";
import { createLoadedLocalPostPhoto } from "utils/local-post-photo";
import {
@@ -16,152 +17,230 @@ import {
spacePostPreviewImageForFile,
type SpaceDraftPostImage,
} from "utils/post-image";
+import { maxSpacePostPhotos, movePostPhoto } from "utils/post-photos";
import { useSpaceRouter } from "utils/route-transitions";
import { spaceRoutes } from "utils/routes";
-interface PendingPostDraft {
+interface DraftPhoto {
+ file: File;
+ id: number;
error?: string;
- isPreviewPending: boolean;
- photo: SpaceViewerPhoto;
+ photo?: SpaceViewerPhoto;
}
-interface SpacePostComposerProps {
- file: File;
+let nextDraftPhotoID = 0;
+const draftPhotos = (files: File[]): DraftPhoto[] =>
+ files.map((file) => ({ file, id: nextDraftPhotoID++ }));
+
+export const SpacePostComposer: React.FC<{
+ files: File[];
onClose: () => void;
onPublish: (
- image: SpaceDraftPostImage,
+ images: SpaceDraftPostImage[],
caption: string,
- ) => Promise<SpacePost>;
+ ) => Promise<void>;
+ onPublished?: () => void;
profile: SetupProfile;
-}
-
-const SpacePostComposer: React.FC<SpacePostComposerProps> = ({
- file,
- onClose,
- onPublish,
- profile,
-}) => {
- const router = useSpaceRouter();
- const publishedPreviewURLRef = React.useRef<string>(undefined);
+}> = ({ files, onClose, onPublish, onPublished, profile }) => {
const displayName =
profile.fullName.trim() || profile.username.trim() || "You";
- const [draft, setDraft] = React.useState<PendingPostDraft>(() => ({
- isPreviewPending: true,
- photo: {
- alt: `${displayName} post`,
+ const [drafts, setDrafts] = React.useState(() => draftPhotos(files));
+ const [activeIndex, setActiveIndex] = React.useState(0);
+ const [isPublishing, setIsPublishing] = React.useState(false);
+ const [isExiting, setIsExiting] = React.useState(false);
+ const inputRef = React.useRef<HTMLInputElement | null>(null);
+ const previewURLsRef = React.useRef(new Map<number, string>());
+ const publishedPreviewURLRef = React.useRef<string>(undefined);
+ const preparingRef = React.useRef(new Set<number>());
+ const draftsRef = React.useRef(drafts);
+ draftsRef.current = drafts;
+ const mountedRef = React.useRef(false);
+ const placeholder = React.useMemo<SpaceViewerPhoto>(
+ () => ({
avatarUrl: profile.avatarUrl,
imageUrl: "",
+ postPhotoCount: 0,
name: displayName,
timestampMs: Date.now(),
- },
- }));
- const [isDraftPostExitAnimating, setIsDraftPostExitAnimating] =
- React.useState(false);
- const [isDraftPostExiting, setIsDraftPostExiting] = React.useState(false);
+ }),
+ [displayName, profile.avatarUrl],
+ );
const { clearBrowserBackState } = useBrowserBackClose({
open: true,
onClose: () => {
- if (!isDraftPostExiting) onClose();
+ if (!isPublishing) onClose();
},
stateKey: "space-post-composer",
});
React.useEffect(() => {
- let cancelled = false;
- let previewURL: string | undefined;
-
- const preparePreview = async () => {
- if (canPreviewSpaceImageFile(file)) {
- return await createLoadedLocalPostPhoto({
- avatarUrl: profile.avatarUrl,
- file,
- name: displayName,
- });
- }
-
- const preview = await spacePostPreviewImageForFile(file);
- return {
- objectUrl: preview.url,
- photo: {
- alt: `${displayName} post`,
- avatarUrl: profile.avatarUrl,
- height: preview.height,
- imageUrl: preview.url,
- name: displayName,
- timestampMs: Date.now(),
- width: preview.width,
- },
- };
+ mountedRef.current = true;
+ const urls = previewURLsRef.current;
+ return () => {
+ mountedRef.current = false;
+ urls.forEach((url) => {
+ if (url != publishedPreviewURLRef.current)
+ URL.revokeObjectURL(url);
+ });
+ urls.clear();
};
+ }, []);
- void preparePreview()
- .then((preview) => {
- previewURL = preview.objectUrl;
- if (cancelled) {
- URL.revokeObjectURL(preview.objectUrl);
- return;
+ React.useEffect(() => {
+ const isActiveDraft = (id: number) =>
+ mountedRef.current &&
+ draftsRef.current.some((item) => item.id == id);
+ const pending = drafts.filter(
+ (draft) =>
+ !draft.photo &&
+ !draft.error &&
+ !preparingRef.current.has(draft.id),
+ );
+ pending.forEach((draft) => preparingRef.current.add(draft.id));
+ void (async () => {
+ for (const draft of pending) {
+ if (!isActiveDraft(draft.id)) continue;
+ try {
+ let photo: SpaceViewerPhoto;
+ if (canPreviewSpaceImageFile(draft.file)) {
+ photo = (
+ await createLoadedLocalPostPhoto({
+ avatarUrl: profile.avatarUrl,
+ file: draft.file,
+ name: displayName,
+ })
+ ).photo;
+ } else {
+ const preview = await spacePostPreviewImageForFile(
+ draft.file,
+ );
+ photo = {
+ ...placeholder,
+ imageUrl: preview.url,
+ height: preview.height,
+ width: preview.width,
+ };
+ }
+ if (!isActiveDraft(draft.id)) {
+ URL.revokeObjectURL(photo.imageUrl);
+ continue;
+ }
+ previewURLsRef.current.set(draft.id, photo.imageUrl);
+ setDrafts((current) =>
+ current.map((item) =>
+ item.id == draft.id ? { ...item, photo } : item,
+ ),
+ );
+ } catch (error) {
+ log.error("Failed to prepare post preview", error);
+ if (isActiveDraft(draft.id))
+ setDrafts((current) =>
+ current.map((item) =>
+ item.id == draft.id
+ ? {
+ ...item,
+ error: spacePostImageErrorMessage(
+ error,
+ ),
+ }
+ : item,
+ ),
+ );
+ } finally {
+ preparingRef.current.delete(draft.id);
}
- setDraft({ isPreviewPending: false, photo: preview.photo });
- })
- .catch((error: unknown) => {
- log.error("Failed to prepare post preview", error);
- if (cancelled) return;
- setDraft((current) => ({
- ...current,
- error: spacePostImageErrorMessage(error),
- isPreviewPending: false,
- }));
- });
-
- return () => {
- cancelled = true;
- if (previewURL && previewURL != publishedPreviewURLRef.current) {
- URL.revokeObjectURL(previewURL);
}
- };
- }, [displayName, file, profile.avatarUrl]);
+ })();
+ }, [displayName, drafts, placeholder, profile.avatarUrl]);
+
+ const addPhotos = (files: File[]) => {
+ setActiveIndex(drafts.length);
+ setDrafts((current) => [...current, ...draftPhotos(files)]);
+ };
+ const removePhoto = () => {
+ if (drafts.length == 1) {
+ onClose();
+ return;
+ }
+ const removed = drafts[activeIndex];
+ if (!removed) return;
+ const url = previewURLsRef.current.get(removed.id);
+ if (url) URL.revokeObjectURL(url);
+ previewURLsRef.current.delete(removed.id);
+ setDrafts((current) =>
+ current.filter((draft) => draft.id != removed.id),
+ );
+ setActiveIndex(Math.max(0, Math.min(activeIndex, drafts.length - 2)));
+ };
+ const movePhoto = (from: number, to: number) => {
+ setDrafts((current) => movePostPhoto(current, from, to));
+ setActiveIndex(to);
+ };
+ const photos = drafts.map((draft, index) => ({
+ ...(draft.photo ?? placeholder),
+ postPhotoIndex: index,
+ postPhotoCount: drafts.length,
+ }));
+ const isPreparing = drafts.some((draft) => !draft.photo && !draft.error);
+ const preparationError = drafts.find((draft) => draft.error)?.error;
+ const controls =
+ files.length > 1 ? (
+ <>
+ <SpacePostPhotoInput
+ inputRef={inputRef}
+ onSelect={addPhotos}
+ remaining={maxSpacePostPhotos - drafts.length}
+ />
+ <SpacePostPhotoStrip
+ activeIndex={activeIndex}
+ disabled={isPublishing}
+ onAdd={() => inputRef.current?.click()}
+ onMove={movePhoto}
+ onRemove={removePhoto}
+ onSelect={setActiveIndex}
+ photos={drafts.map((draft) => ({
+ id: draft.id,
+ imageUrl: draft.photo?.imageUrl,
+ }))}
+ />
+ </>
+ ) : undefined;
return (
<>
- <SpaceViewerPostBackdrop exiting={isDraftPostExitAnimating} />
+ <SpaceViewerPostBackdrop exiting={isExiting} />
<SpaceFileViewer
- draftPostPreparationError={draft.error}
- isDraftPostPreviewPending={draft.isPreviewPending}
+ draftPhotoControls={controls}
+ draftPostPreparationError={preparationError}
+ isDraftPostPreviewPending={isPreparing || !drafts.length}
onClose={onClose}
- onDraftPostExitAnimationStart={() =>
- setIsDraftPostExitAnimating(true)
- }
- onDraftPostExitStart={() => setIsDraftPostExiting(true)}
+ onDraftPostExitStart={() => setIsPublishing(true)}
+ onDraftPostExitAnimationStart={() => setIsExiting(true)}
onDraftPostPublished={() => {
- void clearBrowserBackState("back").then(() => {
- if (router.pathname != spaceRoutes.home) {
- void router.push(spaceRoutes.home);
- } else {
- window.scrollTo({ top: 0, behavior: "smooth" });
- }
- });
+ void clearBrowserBackState("back").then(onPublished);
}}
onPublishDraftPost={
- draft.isPreviewPending || draft.error
+ preparationError || isPreparing || !drafts.length
? undefined
- : (caption, edit) => {
+ : (caption) => {
publishedPreviewURLRef.current =
- draft.photo.imageUrl;
+ drafts[0]!.photo!.imageUrl;
return onPublish(
- {
- cropArea: edit.cropArea,
- file,
- height: edit.height,
- previewUrl: draft.photo.imageUrl,
- rotationDegrees: edit.rotationDegrees,
- width: edit.width,
- },
+ drafts.map((draft) => ({
+ file: draft.file,
+ height: draft.photo!.height,
+ previewUrl: draft.photo!.imageUrl,
+ width: draft.photo!.width,
+ })),
caption,
- ).then(() => undefined);
+ );
}
}
- photo={draft.photo}
+ photo={photos[0] ?? placeholder}
+ photos={photos.length ? photos : [placeholder]}
+ photoIndex={activeIndex}
+ onPhotoIndexChange={setActiveIndex}
postActionMode="draft-post"
/>
</>
@@ -170,19 +249,25 @@ const SpacePostComposer: React.FC<SpacePostComposerProps> = ({
export const SpacePostComposerHost: React.FC = () => {
const {
- pendingPostPhotoFile,
+ pendingPostPhotoFiles,
profile,
publishPost,
- setPendingPostPhotoFile,
+ setPendingPostPhotoFiles,
} = useSpaceAppState();
-
- if (!pendingPostPhotoFile || !profile) return null;
-
+ const router = useSpaceRouter();
+ if (!pendingPostPhotoFiles || !profile) return null;
return (
<SpacePostComposer
- file={pendingPostPhotoFile}
- onClose={() => setPendingPostPhotoFile(null)}
- onPublish={publishPost}
+ files={pendingPostPhotoFiles}
+ onClose={() => setPendingPostPhotoFiles(null)}
+ onPublish={async (images, caption) => {
+ await publishPost(images, caption);
+ }}
+ onPublished={() => {
+ if (router.pathname != spaceRoutes.home)
+ void router.push(spaceRoutes.home);
+ else window.scrollTo({ top: 0, behavior: "smooth" });
+ }}
profile={profile}
/>
);
diff --git a/web/apps/space/src/components/PostPhotoInput.tsx b/web/apps/space/src/components/PostPhotoInput.tsx
new file mode 100644
index 0000000000..f36bb5c4a7
--- /dev/null
+++ b/web/apps/space/src/components/PostPhotoInput.tsx
@@ -0,0 +1,69 @@
+import { Alert02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ SpaceActionToast,
+ spaceToastAutoDismissDurationMs,
+} from "components/ActionToast";
+import React from "react";
+import { spacePostImageInputAccept } from "utils/post-image";
+import { maxSpacePostPhotos } from "utils/post-photos";
+
+export const SpacePostPhotoInput: React.FC<{
+ inputRef: React.Ref<HTMLInputElement>;
+ onSelect: (files: File[]) => void;
+ remaining?: number;
+}> = ({ inputRef, onSelect, remaining = maxSpacePostPhotos }) => {
+ const [error, setError] = React.useState<string>();
+ return (
+ <>
+ <input
+ ref={inputRef}
+ type="file"
+ accept={spacePostImageInputAccept}
+ multiple
+ style={{ display: "none" }}
+ onChange={(event) => {
+ const files = Array.from(event.target.files ?? []);
+ event.target.value = "";
+ if (!files.length) return;
+ if (files.length > remaining) {
+ setError(
+ remaining == maxSpacePostPhotos
+ ? "Only 10 photos per post."
+ : `You can only add ${remaining} more ${remaining == 1 ? "photo" : "photos"}.`,
+ );
+ return;
+ }
+ setError(undefined);
+ onSelect(files);
+ }}
+ />
+ {error && (
+ <SpaceActionToast
+ autoDismissAfterMs={spaceToastAutoDismissDurationMs}
+ closeLabel="Dismiss photo limit message"
+ icon={
+ <HugeiconsIcon
+ icon={Alert02Icon}
+ size={20}
+ color="#FFB020"
+ />
+ }
+ message={
+ <span
+ style={{
+ display: "block",
+ padding: "8px 0",
+ whiteSpace: "normal",
+ }}
+ >
+ {error}
+ </span>
+ }
+ onClose={() => setError(undefined)}
+ zIndex={1600}
+ />
+ )}
+ </>
+ );
+};
diff --git a/web/apps/space/src/components/PostPhotoStrip.tsx b/web/apps/space/src/components/PostPhotoStrip.tsx
new file mode 100644
index 0000000000..68d3f1ae9c
--- /dev/null
+++ b/web/apps/space/src/components/PostPhotoStrip.tsx
@@ -0,0 +1,488 @@
+import { Add01Icon, Cancel01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Box } from "@mui/material";
+import { keyframes } from "@mui/material/styles";
+import React from "react";
+import { maxSpacePostPhotos, movePostPhoto } from "utils/post-photos";
+
+interface StripPhoto {
+ id: number;
+ imageUrl?: string;
+}
+
+interface PhotoDrag {
+ from: number;
+ to: number;
+ x: number;
+ top: number;
+}
+
+const photoSize = 48;
+const photoGap = 8;
+const liftPhoto = keyframes`
+ from { transform: translateY(4px) scale(1); }
+ to { transform: translateY(0) scale(1.04); }
+`;
+const iconButtonSx = {
+ alignItems: "center",
+ background: "none",
+ border: 0,
+ color: "#D8D8D8",
+ cursor: "pointer",
+ display: "flex",
+ justifyContent: "center",
+ p: 0,
+ "&:disabled": { opacity: 0.3, cursor: "default" },
+ "&:focus-visible": { outline: "2px solid #FFFFFF", outlineOffset: 2 },
+};
+
+export const SpacePostPhotoStrip: React.FC<{
+ activeIndex: number;
+ disabled: boolean;
+ onAdd: () => void;
+ onMove: (from: number, to: number) => void;
+ onRemove: () => void;
+ onSelect: (index: number) => void;
+ photos: StripPhoto[];
+}> = ({ activeIndex, disabled, onAdd, onMove, onRemove, onSelect, photos }) => {
+ const stripRef = React.useRef<HTMLDivElement | null>(null);
+ const suppressClickRef = React.useRef(false);
+ const callbacksRef = React.useRef({ onMove, onSelect });
+ callbacksRef.current = { onMove, onSelect };
+ const [drag, setDrag] = React.useState<PhotoDrag>();
+ const [announcement, setAnnouncement] = React.useState("");
+ const [hasPhotosOnRight, setHasPhotosOnRight] = React.useState(false);
+ const dragging = Boolean(drag);
+
+ React.useEffect(() => {
+ const strip = stripRef.current;
+ if (!strip) return;
+ const updateOverflow = () =>
+ setHasPhotosOnRight(
+ strip.scrollWidth - strip.clientWidth - strip.scrollLeft > 1,
+ );
+ const observer = new ResizeObserver(updateOverflow);
+ observer.observe(strip);
+ strip.addEventListener("scroll", updateOverflow, { passive: true });
+ updateOverflow();
+ return () => {
+ observer.disconnect();
+ strip.removeEventListener("scroll", updateOverflow);
+ };
+ }, [photos.length]);
+
+ React.useEffect(() => {
+ if (dragging) return;
+ stripRef.current
+ ?.querySelector('[aria-pressed="true"]')
+ ?.scrollIntoView({ block: "nearest", inline: "nearest" });
+ }, [activeIndex, dragging, photos.length]);
+
+ React.useEffect(() => {
+ const strip = stripRef.current;
+ if (!strip || disabled || photos.length < 2) return;
+ let gesture:
+ | {
+ pointerID: number;
+ startX: number;
+ startY: number;
+ touch: boolean;
+ active: boolean;
+ drag: PhotoDrag;
+ }
+ | undefined;
+ let holdTimer: number | undefined;
+ let frame: number | undefined;
+
+ const stop = () => {
+ window.clearTimeout(holdTimer);
+ if (frame != undefined) cancelAnimationFrame(frame);
+ gesture = undefined;
+ setDrag(undefined);
+ };
+ const positionAt = (x: number) => {
+ let distance = Infinity;
+ let position = 0;
+ strip
+ .querySelectorAll<HTMLElement>("[data-photo-slot]")
+ .forEach((slot, index) => {
+ const rect = slot.getBoundingClientRect();
+ const nextDistance = Math.abs(
+ x - rect.left - rect.width / 2,
+ );
+ if (nextDistance < distance) {
+ distance = nextDistance;
+ position = index;
+ }
+ });
+ return position;
+ };
+ const update = () => {
+ if (!gesture?.active) return;
+ const { x } = gesture.drag;
+ const bounds = strip.getBoundingClientRect();
+ const edge = 32;
+ const scroll =
+ x < bounds.left + edge
+ ? -Math.min(8, (bounds.left + edge - x) / 4)
+ : x > bounds.right - edge
+ ? Math.min(8, (x - bounds.right + edge) / 4)
+ : 0;
+ strip.scrollLeft += scroll;
+ gesture.drag.to = positionAt(x);
+ setDrag({ ...gesture.drag });
+ frame = requestAnimationFrame(update);
+ };
+ const activate = () => {
+ if (!gesture) return;
+ gesture.active = true;
+ suppressClickRef.current = true;
+ callbacksRef.current.onSelect(gesture.drag.from);
+ strip.setPointerCapture(gesture.pointerID);
+ update();
+ };
+ const start = (event: PointerEvent) => {
+ suppressClickRef.current = false;
+ if (gesture || !event.isPrimary) {
+ stop();
+ return;
+ }
+ if (event.button != 0 || !(event.target instanceof Element)) return;
+ const photo =
+ event.target.closest<HTMLElement>("[data-photo-index]");
+ if (!photo) return;
+ const from = Number(photo.dataset.photoIndex);
+ gesture = {
+ pointerID: event.pointerId,
+ startX: event.clientX,
+ startY: event.clientY,
+ touch: event.pointerType == "touch",
+ active: false,
+ drag: {
+ from,
+ to: from,
+ x: event.clientX,
+ top: photo.getBoundingClientRect().top - 4,
+ },
+ };
+ if (gesture.touch) holdTimer = window.setTimeout(activate, 180);
+ };
+ const move = (event: PointerEvent) => {
+ if (event.pointerId != gesture?.pointerID) return;
+ gesture.drag.x = event.clientX;
+ if (gesture.active) return;
+ const distance = Math.hypot(
+ event.clientX - gesture.startX,
+ event.clientY - gesture.startY,
+ );
+ if (distance < 8) return;
+ if (gesture.touch) stop();
+ else activate();
+ };
+ const finish = (event: PointerEvent) => {
+ if (event.pointerId != gesture?.pointerID) return;
+ const { active, drag: completed } = gesture;
+ completed.to = positionAt(event.clientX);
+ stop();
+ if (active && completed.from != completed.to) {
+ callbacksRef.current.onMove(completed.from, completed.to);
+ setAnnouncement(
+ `Photo moved to position ${completed.to + 1} of ${photos.length}`,
+ );
+ }
+ };
+ const preventScroll = (event: TouchEvent) => {
+ if (gesture?.active) event.preventDefault();
+ };
+ const cancelOnEscape = (event: KeyboardEvent) => {
+ if (event.key != "Escape" || !gesture) return;
+ event.preventDefault();
+ event.stopPropagation();
+ stop();
+ };
+ strip.addEventListener("pointerdown", start);
+ strip.addEventListener("touchmove", preventScroll, { passive: false });
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", finish);
+ window.addEventListener("pointercancel", stop);
+ window.addEventListener("keydown", cancelOnEscape, true);
+ return () => {
+ stop();
+ strip.removeEventListener("pointerdown", start);
+ strip.removeEventListener("touchmove", preventScroll);
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", finish);
+ window.removeEventListener("pointercancel", stop);
+ window.removeEventListener("keydown", cancelOnEscape, true);
+ };
+ }, [disabled, photos.length]);
+
+ const shownPhotos = drag
+ ? movePostPhoto(photos, drag.from, drag.to)
+ : photos;
+ const draggedPhoto = drag ? photos[drag.from] : undefined;
+ const preview = (photo: StripPhoto) =>
+ photo.imageUrl ? (
+ <Box
+ component="img"
+ src={photo.imageUrl}
+ alt=""
+ draggable={false}
+ sx={{
+ height: "100%",
+ width: "100%",
+ objectFit: "cover",
+ pointerEvents: "none",
+ }}
+ />
+ ) : (
+ photos.indexOf(photo) + 1
+ );
+
+ return (
+ <Box sx={{ mb: "8px" }}>
+ <Box
+ sx={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ minWidth: 0,
+ }}
+ >
+ <Box sx={{ flex: 1, minWidth: 0, position: "relative" }}>
+ <Box
+ ref={stripRef}
+ onClickCapture={(event) => {
+ if (!suppressClickRef.current || event.detail == 0)
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ onContextMenu={(event) => event.preventDefault()}
+ sx={{
+ display: "flex",
+ gap: `${photoGap}px`,
+ overflowX: "auto",
+ px: "6px",
+ py: "10px",
+ scrollbarWidth: "none",
+ userSelect: "none",
+ WebkitTouchCallout: "none",
+ "&::-webkit-scrollbar": { display: "none" },
+ }}
+ >
+ {photos.map((photo, index) => (
+ <Box
+ key={photo.id}
+ data-photo-slot
+ sx={{
+ flexShrink: 0,
+ height: photoSize,
+ width: photoSize,
+ position: "relative",
+ }}
+ >
+ <Box
+ sx={{
+ height: "100%",
+ width: "100%",
+ position: "relative",
+ transform: `translateX(${(shownPhotos.indexOf(photo) - index) * (photoSize + photoGap)}px)`,
+ transition: dragging
+ ? "transform 180ms cubic-bezier(0.2, 0.8, 0.2, 1)"
+ : undefined,
+ "@media (prefers-reduced-motion: reduce)":
+ { transition: "none" },
+ }}
+ >
+ <Box
+ component="button"
+ type="button"
+ data-photo-index={index}
+ aria-label={`Photo ${index + 1}`}
+ aria-pressed={
+ photo.id == photos[activeIndex]?.id
+ }
+ aria-keyshortcuts="Alt+ArrowLeft Alt+ArrowRight"
+ disabled={disabled}
+ onClick={() => onSelect(index)}
+ onKeyDown={(
+ event: React.KeyboardEvent,
+ ) => {
+ if (
+ !event.altKey ||
+ ![
+ "ArrowLeft",
+ "ArrowRight",
+ ].includes(event.key)
+ )
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ const to =
+ index +
+ (event.key == "ArrowLeft"
+ ? -1
+ : 1);
+ if (to < 0 || to >= photos.length)
+ return;
+ onMove(index, to);
+ setAnnouncement(
+ `Photo moved to position ${to + 1} of ${photos.length}`,
+ );
+ }}
+ sx={{
+ ...iconButtonSx,
+ bgcolor: "#242424",
+ outline:
+ photo.id ==
+ photos[activeIndex]?.id
+ ? "1.5px solid #FFFFFF"
+ : "none",
+ outlineOffset: "-1.5px",
+ borderRadius: "9px",
+ cursor: disabled
+ ? "default"
+ : "grab",
+ height: "100%",
+ width: "100%",
+ overflow: "hidden",
+ scrollMarginInlineEnd: "36px",
+ opacity:
+ photo.id == draggedPhoto?.id
+ ? 0.3
+ : 1,
+ }}
+ >
+ {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,
+ }}
+ >
+ <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>
+ {hasPhotosOnRight && (
+ <Box
+ aria-hidden
+ sx={{
+ background:
+ "linear-gradient(to right, transparent, #000000)",
+ bottom: 0,
+ pointerEvents: "none",
+ position: "absolute",
+ right: 0,
+ top: 0,
+ width: 36,
+ }}
+ />
+ )}
+ </Box>
+ {photos.length < maxSpacePostPhotos && (
+ <Box
+ component="button"
+ type="button"
+ aria-label="Add photos"
+ disabled={disabled}
+ onClick={onAdd}
+ sx={{
+ ...iconButtonSx,
+ flexShrink: 0,
+ width: 44,
+ height: 44,
+ }}
+ >
+ <Box
+ component="span"
+ sx={{
+ alignItems: "center",
+ bgcolor: "#242424",
+ borderRadius: "50%",
+ display: "flex",
+ justifyContent: "center",
+ width: 32,
+ height: 32,
+ }}
+ >
+ <HugeiconsIcon icon={Add01Icon} size={20} />
+ </Box>
+ </Box>
+ )}
+ </Box>
+ <Box
+ role="status"
+ sx={{
+ position: "absolute",
+ width: 1,
+ height: 1,
+ overflow: "hidden",
+ clipPath: "inset(50%)",
+ }}
+ >
+ {announcement}
+ </Box>
+ {drag && draggedPhoto && (
+ <Box
+ aria-hidden
+ sx={{
+ position: "fixed",
+ left: drag.x - photoSize / 2,
+ top: drag.top,
+ width: photoSize,
+ height: photoSize,
+ borderRadius: "9px",
+ outline: "1.5px solid #FFFFFF",
+ outlineOffset: "-1.5px",
+ bgcolor: "#242424",
+ overflow: "hidden",
+ boxShadow: "0 4px 12px #00000088",
+ transform: "scale(1.04)",
+ animation: `${liftPhoto} 100ms ease-out`,
+ "@media (prefers-reduced-motion: reduce)": {
+ animation: "none",
+ },
+ pointerEvents: "none",
+ zIndex: 5,
+ boxSizing: "border-box",
+ }}
+ >
+ {preview(draggedPhoto)}
+ </Box>
+ )}
+ </Box>
+ );
+};
diff --git a/web/apps/space/src/components/PostPhotosBadge.tsx b/web/apps/space/src/components/PostPhotosBadge.tsx
new file mode 100644
index 0000000000..1ddcdf969c
--- /dev/null
+++ b/web/apps/space/src/components/PostPhotosBadge.tsx
@@ -0,0 +1,28 @@
+import { Album02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Box } from "@mui/material";
+
+export const SpacePostPhotosBadge = ({ count }: { count: number }) =>
+ count > 1 ? (
+ <Box
+ component="span"
+ aria-label={`${count} photos`}
+ sx={{
+ alignItems: "center",
+ color: "#FFFFFF",
+ display: "flex",
+ filter: "drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5))",
+ height: 30,
+ justifyContent: "center",
+ opacity: 0.8,
+ pointerEvents: "none",
+ position: "absolute",
+ right: 10,
+ top: 10,
+ width: 30,
+ zIndex: 2,
+ }}
+ >
+ <HugeiconsIcon icon={Album02Icon} size={18} strokeWidth={1.6} />
+ </Box>
+ ) : null;
diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsx
index ddae664b2f..bbda5dcf02 100644
--- a/web/apps/space/src/pages/app/index.tsx
+++ b/web/apps/space/src/pages/app/index.tsx
@@ -45,7 +45,7 @@ const Page: React.FC = () => {
profileLoadStatus,
setFriends,
setLocalFeedPosts,
- setPendingPostPhotoFile,
+ setPendingPostPhotoFiles,
} = useSpaceAppState();
const [friendRequestSentToastName, setFriendRequestSentToastName] =
useState<string>();
@@ -332,7 +332,7 @@ const Page: React.FC = () => {
onFriendRequestSentToastClose={closeFriendRequestSentToast}
onInviteFriendsToastClose={closeInviteFriendsToast}
onAddFriend={() => setIsAddFriendOpen(true)}
- onPostPhotoSelect={setPendingPostPhotoFile}
+ onPostPhotoSelect={setPendingPostPhotoFiles}
onDeletePost={async (postId) => {
const spaceId = profile?.spaceId;
if (!spaceId) throw new Error("Missing space.");
diff --git a/web/apps/space/src/pages/app/post.tsx b/web/apps/space/src/pages/app/post.tsx
index 25b75913ef..e317878126 100644
--- a/web/apps/space/src/pages/app/post.tsx
+++ b/web/apps/space/src/pages/app/post.tsx
@@ -3,6 +3,7 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Box } from "@mui/material";
import { SpaceBackIcon } from "components/BackIcon";
import { SpacePageMeta } from "components/PageMeta";
+import { SpacePostPhotoInput } from "components/PostPhotoInput";
import { SpaceRouteFallback } from "components/RouteFallback";
import React from "react";
import { useSpaceAppState } from "state/app-state";
@@ -14,7 +15,6 @@ import {
spaceTextMuted,
} from "styles/colors";
import { spaceTouchTargetSize } from "styles/touch-targets";
-import { spacePostImageInputAccept } from "utils/post-image";
import { useSpaceRouter } from "utils/route-transitions";
import { spaceRoutes } from "utils/routes";
@@ -29,11 +29,11 @@ const Page: React.FC = () => {
profile,
profileLoadError,
profileLoadStatus,
- pendingPostPhotoFile,
- setPendingPostPhotoFile,
+ pendingPostPhotoFiles,
+ setPendingPostPhotoFiles,
} = useSpaceAppState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
- const isOpeningPost = Boolean(pendingPostPhotoFile);
+ const isOpeningPost = Boolean(pendingPostPhotoFiles);
React.useEffect(() => {
if (profileLoadStatus == "ready" && !profile) {
@@ -50,16 +50,6 @@ const Page: React.FC = () => {
);
}
- const handlePhotoSelect: React.ChangeEventHandler<HTMLInputElement> = (
- event,
- ) => {
- const file = event.target.files?.[0];
- event.target.value = "";
- if (!file) return;
-
- setPendingPostPhotoFile(file);
- };
-
return (
<>
<SpacePageMeta themeColor={background} />
@@ -160,13 +150,9 @@ const Page: React.FC = () => {
>
Post a photo from your day.
</Box>
- <Box
- ref={inputRef}
- component="input"
- type="file"
- accept={spacePostImageInputAccept}
- onChange={handlePhotoSelect}
- sx={{ display: "none" }}
+ <SpacePostPhotoInput
+ inputRef={inputRef}
+ onSelect={setPendingPostPhotoFiles}
/>
<Box
className="green-bg"
diff --git a/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx b/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx
index ee9e3cca33..0699860b17 100644
--- a/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx
+++ b/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx
@@ -5,12 +5,14 @@ import log from "ente-base/log";
import React from "react";
import {
loadCurrentSpacePost,
+ loadCurrentSpacePostAssetURL,
replyToCurrentPost,
setCurrentPostLiked,
type SpacePost,
} from "services/space";
import { useSpaceAppState } from "state/app-state";
import { spaceAppBackgroundColor } from "styles/colors";
+import { viewerPhotosFromPost } from "utils/post-photos";
import { hasPreviousSpaceRoute, useSpaceRouter } from "utils/route-transitions";
import { spaceRoutes } from "utils/routes";
@@ -51,6 +53,7 @@ const viewerPhotoFromPost = (post: SpacePost) => ({
caption: post.caption,
friendID: post.friendID,
height: post.height,
+ photos: post.photos,
imageUrl: post.imageUrl ?? "",
name: post.name,
postId: post.postId,
@@ -169,7 +172,10 @@ const Page: React.FC = () => {
<>
<SpacePageMeta themeColor={postBackground} />
<SpaceFileViewer
+ key={post.postId}
photo={viewerPhotoFromPost(post)}
+ photos={viewerPhotosFromPost(viewerPhotoFromPost(post))}
+ onLoadPhoto={loadCurrentSpacePostAssetURL}
postActionMode={isOwnPost ? "hidden" : "like-only"}
onClose={closePost}
onOpenProfile={openOwnerProfile}
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index 3ca6052ae9..cebca70e23 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -21,6 +21,8 @@ import {
spacePostLikePopDurationMs,
spacePostLikePopTiming,
} from "components/post-like-animation";
+import { SpacePostPhotoInput } from "components/PostPhotoInput";
+import { SpacePostPhotosBadge } from "components/PostPhotosBadge";
import { SpacePWAInstallPrompt } from "components/PWAInstallPrompt";
import { SpaceLoadingSpinner } from "components/RouteFallback";
import { SpaceShareInviteButton } from "components/ShareInviteButton";
@@ -47,7 +49,7 @@ import {
} from "styles/colors";
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom, formatSpaceDate } from "utils/display";
-import { spacePostImageInputAccept } from "utils/post-image";
+import { viewerPhotosFromPost } from "utils/post-photos";
import { thumbHashDataURLFromBase64 } from "utils/thumbhash";
const homeBackground = spaceAppBackgroundColor;
@@ -99,7 +101,7 @@ interface HomeScreenProps {
showInstallPrompt?: boolean;
showInviteFriendsToast?: boolean;
onAddFriend: () => void;
- onPostPhotoSelect: (file: File) => void;
+ onPostPhotoSelect: (files: File[]) => void;
onDeletePost?: (postId: number) => Promise<void> | void;
onLoadMoreFeedItems?: () => Promise<void> | void;
onLoadPostAvatar?: SpacePostAvatarURLLoader;
@@ -139,6 +141,7 @@ interface DecodedImageState {
}
interface SelectedHomeViewer {
+ photos: SpaceViewerPhoto[];
focusReplyOnOpen?: boolean;
photo: SpaceViewerPhoto;
postActionMode?: SpaceViewerPostActionMode;
@@ -356,6 +359,7 @@ class FeedMotionList extends React.Component<FeedMotionListProps> {
type FeedTimestampStatus = "failed" | "post-limit" | "posted" | "posting";
interface FeedItemProps {
+ photoCount?: number;
aspectRatio: number;
avatarUrl: string | null;
caption?: string;
@@ -633,6 +637,7 @@ const FeedPhotoCaption: React.FC<{ caption: string }> = ({ caption }) => {
};
const FeedItem: React.FC<FeedItemProps> = ({
+ photoCount = 1,
aspectRatio,
avatarUrl,
caption,
@@ -900,6 +905,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
width: "100%",
}}
>
+ <SpacePostPhotosBadge count={photoCount} />
<Box
component="button"
type="button"
@@ -1526,12 +1532,14 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
postInputRef.current?.click();
};
const openFeedPhoto = (
+ post: SpacePost,
photo: SpaceViewerPhoto,
focusReplyOnOpen = false,
) => {
const isOwnPost =
Boolean(viewerSpaceId) && photo.friendID == viewerSpaceId;
setSelectedViewer({
+ photos: viewerPhotosFromPost({ ...photo, photos: post.photos }),
focusReplyOnOpen: isOwnPost ? false : focusReplyOnOpen,
photo,
postActionMode: isOwnPost ? "hidden" : "like-only",
@@ -1688,9 +1696,12 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
: () => loadFeedPostImage(item)
}
onOpenFriend={onOpenFriend}
- onOpenPhoto={openFeedPhoto}
+ onOpenPhoto={(photo, focusReply) =>
+ openFeedPhoto(item, photo, focusReply)
+ }
onOpenProfile={onOpenProfile}
onSetPostLiked={onSetPostLiked}
+ photoCount={item.photos?.length ?? 1}
postId={item.postId}
spaceId={item.spaceId}
thumbHash={item.thumbHash}
@@ -1724,6 +1735,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
isOwnPost
name={item.name}
onOpenProfile={onOpenProfile}
+ photoCount={item.photoCount}
postId={0}
timestampStatus={
item.status == "failed"
@@ -1792,14 +1804,6 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
onLoadMoreFeedItems,
]);
- const handlePostPhotoSelect: React.ChangeEventHandler<HTMLInputElement> = (
- event,
- ) => {
- const file = event.target.files?.[0];
- event.target.value = "";
- if (file) onPostPhotoSelect(file);
- };
-
return (
<Box
component="main"
@@ -1832,13 +1836,9 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
onOpenMessages={onOpenMessages}
onOpenProfile={onOpenProfile}
>
- <Box
- ref={postInputRef}
- component="input"
- type="file"
- accept={spacePostImageInputAccept}
- onChange={handlePostPhotoSelect}
- sx={{ display: "none" }}
+ <SpacePostPhotoInput
+ inputRef={postInputRef}
+ onSelect={onPostPhotoSelect}
/>
</SpaceHomeHeader>
<Box
@@ -2052,8 +2052,11 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
/>
{selectedViewer && (
<SpaceFileViewer
+ closeOnSwipePastEnd
focusReplyOnOpen={selectedViewer.focusReplyOnOpen}
photo={selectedViewer.photo}
+ photos={selectedViewer.photos}
+ onLoadPhoto={onLoadPostImage}
postActionMode={selectedViewer.postActionMode}
onClose={closeSelectedPhoto}
onOpenProfile={
@@ -2080,7 +2083,6 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
}
: undefined
}
- onSwipeLeft={closeSelectedPhoto}
onReplyToPost={
!selectedPhotoIsOwn &&
selectedViewer.photo.friendID != viewerSpaceId
diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsx
index 06cdc212f7..a501421dc2 100644
--- a/web/apps/space/src/screens/MessagesScreen.tsx
+++ b/web/apps/space/src/screens/MessagesScreen.tsx
@@ -16,6 +16,8 @@ import {
Popper,
} from "@mui/material";
import { SpaceAvatarImage } from "components/AvatarImage";
+import { SpacePostPhotoInput } from "components/PostPhotoInput";
+import { SpacePostPhotosBadge } from "components/PostPhotosBadge";
import { SpaceLoadingSpinner } from "components/RouteFallback";
import { SpaceShareInviteButton } from "components/ShareInviteButton";
import { formatTimeAgo } from "ente-base/date";
@@ -42,7 +44,6 @@ import {
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom } from "utils/display";
import { clampSpaceMessageText } from "utils/message-limits";
-import { spacePostImageInputAccept } from "utils/post-image";
const green = "#08C225";
const textBase = spaceText;
@@ -112,7 +113,7 @@ interface MessagesScreenProps {
) => void;
onOpenQuotePost: (quote: SpaceMessageQuote) => void;
onOpenThread: (conversation: SpaceMessageConversation) => void;
- onPostPhotoSelect: (file: File) => void;
+ onPostPhotoSelect: (files: File[]) => void;
onLoadActivityPost?: (
post: SpaceMessageActivityPost,
) => Promise<SpaceMessageActivityPost | undefined>;
@@ -1268,6 +1269,7 @@ const PostQuotePreview: React.FC<{
}) => {
const quote = message.quote;
const imageUrl = quote?.imageUrl ?? activityPost?.imageUrl;
+ const photoCount = quote?.photoCount ?? activityPost?.photoCount ?? 1;
const isUnavailable =
!quote ||
quote.isUnavailable == true ||
@@ -1275,7 +1277,7 @@ const PostQuotePreview: React.FC<{
(activityPost != undefined || onLoadActivityPost == undefined));
const loadedQuote =
quote && imageUrl && !isUnavailable
- ? { ...quote, imageUrl }
+ ? { ...quote, imageUrl, photoCount }
: undefined;
const isLoading = quote != undefined && !imageUrl && !isUnavailable;
const canOpen = Boolean(loadedQuote);
@@ -1307,6 +1309,7 @@ const PostQuotePreview: React.FC<{
font: "inherit",
overflow: "hidden",
p: 0,
+ position: "relative",
"&:focus-visible": {
outline: `2px solid ${green}`,
outlineOffset: 2,
@@ -1359,6 +1362,7 @@ const PostQuotePreview: React.FC<{
)}
</Box>
)}
+ {canOpen && <SpacePostPhotosBadge count={photoCount} />}
</Box>
</QuoteFrame>
);
@@ -1809,13 +1813,6 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
);
const isContextMessagePoke = messageContextMenu?.message.kind == "poke";
- const handlePostPhotoSelect: React.ChangeEventHandler<HTMLInputElement> = (
- event,
- ) => {
- const file = event.target.files?.[0];
- event.target.value = "";
- if (file) onPostPhotoSelect(file);
- };
const openPostPhotoPicker = () => postPhotoInputRef.current?.click();
const sendMessage = () => {
@@ -2131,13 +2128,9 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
return (
<>
- <Box
- ref={postPhotoInputRef}
- component="input"
- type="file"
- accept={spacePostImageInputAccept}
- onChange={handlePostPhotoSelect}
- sx={{ display: "none" }}
+ <SpacePostPhotoInput
+ inputRef={postPhotoInputRef}
+ onSelect={onPostPhotoSelect}
/>
<Box
component="main"
diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsx
index 1d73db2ee1..7d5e6a3da2 100644
--- a/web/apps/space/src/screens/ProfileScreen.tsx
+++ b/web/apps/space/src/screens/ProfileScreen.tsx
@@ -26,6 +26,9 @@ import {
type SpaceViewerPhoto,
type SpaceViewerPostActionMode,
} from "components/FileViewer";
+import { SpacePostComposer } from "components/PostComposer";
+import { SpacePostPhotoInput } from "components/PostPhotoInput";
+import { SpacePostPhotosBadge } from "components/PostPhotosBadge";
import { SpaceLoadingSpinner } from "components/RouteFallback";
import { SpaceShareIcon } from "components/ShareInviteButton";
import log from "ente-base/log";
@@ -33,7 +36,11 @@ import { useBrowserBackClose } from "hooks/use-browser-back-close";
import React, { useState } from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
import type { SpaceInviteIntent } from "services/invite";
-import { isSpaceContentError, type SpacePostAsset } from "services/space";
+import {
+ isSpaceContentError,
+ type SpacePostAsset,
+ type SpacePostPhoto,
+} from "services/space";
import { spaceEmptyStateButtonSx } from "styles/buttons";
import {
spaceAppBackground,
@@ -47,15 +54,11 @@ import {
import { spaceProfilePostRadius } from "styles/tiles";
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom } from "utils/display";
-import { createLoadedLocalPostPhoto } from "utils/local-post-photo";
import {
- canPreviewSpaceImageFile,
spaceDefaultCoverImagePath,
- spacePostImageErrorMessage,
- spacePostImageInputAccept,
- spacePostPreviewImageForFile,
type SpaceDraftPostImage,
} from "utils/post-image";
+import { viewerPhotosFromPost } from "utils/post-photos";
import { profilePhotoGap, profilePhotoRows } from "utils/profile-photo-layout";
import { thumbHashDataURLFromBase64 } from "utils/thumbhash";
@@ -98,6 +101,7 @@ export interface ProfilePostItem {
id: string;
imageAsset?: SpacePostAsset;
imageUrl?: string;
+ photos?: SpacePostPhoto[];
isUnavailable?: boolean;
name?: string;
postId?: number;
@@ -109,14 +113,9 @@ export interface ProfilePostItem {
}
interface SelectedProfilePost {
- draftFile?: File;
- draftImageError?: string;
id: string;
- isDraftImagePreviewPending?: boolean;
- localObjectUrl?: string;
photo: SpaceViewerPhoto;
- postIndex?: number;
- postActionMode?: SpaceViewerPostActionMode;
+ photoIndex: number;
}
interface PostMasonryTile {
@@ -456,6 +455,9 @@ const ProfilePostTile: React.FC<ProfilePostTileProps> = ({
}}
/>
) : null}
+ {!isUnavailable && (
+ <SpacePostPhotosBadge count={item.photos?.length ?? 1} />
+ )}
{isUnavailable && (
<Box
sx={{
@@ -493,7 +495,7 @@ interface ProfileScreenProps {
onAddFriendForPostAction?: (intent: SpaceInviteIntent) => void;
onCreateSpace?: () => void;
onCreatePost?: (
- image: SpaceDraftPostImage,
+ images: SpaceDraftPostImage[],
caption: string,
) => Promise<void>;
onDeletePost?: (postId: number) => Promise<void> | void;
@@ -556,8 +558,8 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
}) => {
const [selectedPost, setSelectedPost] =
useState<SelectedProfilePost | null>(null);
- const [isDraftPostExiting, setIsDraftPostExiting] = useState(false);
- const [isPostPhotoOpening, setIsPostPhotoOpening] = useState(false);
+ const [draftFiles, setDraftFiles] = useState<File[] | null>(null);
+ const isPostPhotoOpening = Boolean(draftFiles);
const [isInviteLinkCopied, setIsInviteLinkCopied] = useState(false);
const [deletedPostIDs, setDeletedPostIDs] = useState<Set<string>>(
() => new Set(),
@@ -587,8 +589,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
const postImageLoadsInFlightRef = React.useRef<
Map<string, Promise<string | undefined>>
>(new Map());
- const localPostObjectUrlsRef = React.useRef<Set<string>>(new Set());
- const activeLocalPostObjectUrlRef = React.useRef<string | null>(null);
const isOwnerProfile = headerVariant == "owner";
const isFriendProfile = headerVariant == "friend";
const isAnonymousPublicProfile = headerVariant == "public-anonymous";
@@ -718,31 +718,15 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
setUnfriendErrorMessage(null);
};
- const revokeLocalPostObjectUrls = React.useCallback(() => {
- localPostObjectUrlsRef.current.forEach((objectUrl) =>
- URL.revokeObjectURL(objectUrl),
- );
- localPostObjectUrlsRef.current.clear();
- }, []);
const openPostPhotoPicker = () => {
- if (isPostPhotoOpening) return;
-
- postInputRef.current?.click();
- };
- const closeSelectedPost = () => {
- activeLocalPostObjectUrlRef.current = null;
- setIsDraftPostExiting(false);
- setSelectedPost(null);
- revokeLocalPostObjectUrls();
+ if (!isPostPhotoOpening) postInputRef.current?.click();
};
- const { clearBrowserBackState: clearSelectedPostHistory } =
- useBrowserBackClose({
- open: Boolean(selectedPost),
- onClose: () => {
- if (!isDraftPostExiting) closeSelectedPost();
- },
- stateKey: "space-profile-viewer",
- });
+ const closeSelectedPost = () => setSelectedPost(null);
+ useBrowserBackClose({
+ open: Boolean(selectedPost),
+ onClose: closeSelectedPost,
+ stateKey: "space-profile-viewer",
+ });
const rememberLoadedPhotoDimensions = (
itemID: string,
image: HTMLImageElement,
@@ -824,221 +808,22 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
[loadedPhotoDimensionsByID],
);
- const selectedPostForItem = React.useCallback(
- (
- item: ProfilePostItem,
- postIndex: number,
- imageUrl: string,
- ): SelectedProfilePost => {
- const dimensions = dimensionsForPost(item);
- return {
- id: item.id,
- photo: {
- alt: `${displayName} post ${postIndex + 1}`,
- avatarUrl: profile.avatarUrl,
- caption: item.caption,
- height: dimensions.height,
- imageUrl,
- name: displayName,
- postId: item.postId,
- spaceId: item.spaceId,
- timestampMs: item.timestampMs,
- viewerLiked: item.viewerLiked,
- width: dimensions.width,
- },
- postIndex,
- };
- },
- [dimensionsForPost, displayName, profile.avatarUrl],
- );
-
- const profileViewerPhotos = React.useMemo(
- () =>
- viewerPostItems.map((item, index) => {
- const dimensions = dimensionsForPost(item);
- return {
- alt: `${displayName} post ${index + 1}`,
- avatarUrl: profile.avatarUrl,
- caption: item.caption,
- height: dimensions.height,
- imageUrl:
- loadedPostImageURLFor(item) ??
- (selectedPost?.id == item.id
- ? selectedPost.photo.imageUrl
- : ""),
- name: displayName,
- postId: item.postId,
- spaceId: item.spaceId,
- timestampMs: item.timestampMs,
- viewerLiked: item.viewerLiked,
- width: dimensions.width,
- };
- }),
- [
- dimensionsForPost,
- displayName,
- loadedPostImageURLFor,
- profile.avatarUrl,
- selectedPost?.id,
- selectedPost?.photo.imageUrl,
- viewerPostItems,
- ],
- );
-
- const handleSelectedPostIndexChange = React.useCallback(
- (postIndex: number) => {
- const item = viewerPostItems[postIndex];
- if (!item) return;
-
- const updateSelectedPost = (imageUrl: string) => {
- setSelectedPost((currentPost) => {
- if (currentPost?.postIndex == undefined) {
- return currentPost;
- }
- if (
- currentPost.id == item.id &&
- currentPost.photo.imageUrl == imageUrl
- ) {
- return currentPost;
- }
- return selectedPostForItem(item, postIndex, imageUrl);
- });
- };
-
- const imageUrl = loadedPostImageURLFor(item);
- if (imageUrl) {
- updateSelectedPost(imageUrl);
- return;
- }
-
- void loadPostImage(item).then((loadedImageUrl) => {
- if (loadedImageUrl) updateSelectedPost(loadedImageUrl);
- });
- },
- [
- loadPostImage,
- loadedPostImageURLFor,
- selectedPostForItem,
- viewerPostItems,
- ],
- );
-
- const selectedViewerPostIndex = selectedPost
- ? viewerPostIndexByID.get(selectedPost.id)
- : undefined;
-
- React.useEffect(() => {
- const currentPostIndex = selectedViewerPostIndex;
- if (currentPostIndex == undefined) return;
-
- for (const offset of [-1, 1]) {
- const adjacentPost = viewerPostItems[currentPostIndex + offset];
- if (!adjacentPost || loadedPostImageURLFor(adjacentPost)) continue;
-
- void loadPostImage(adjacentPost);
- }
- }, [
- loadPostImage,
- loadedPostImageURLFor,
- selectedViewerPostIndex,
- viewerPostItems,
- ]);
-
- const prepareSelectedPostPhoto = async (file: File) => {
- const canShowLocalPreview = canPreviewSpaceImageFile(file);
- if (!canShowLocalPreview) {
- const timestampMs = Date.now();
- const draftKey = `pending-preview-${timestampMs}`;
- activeLocalPostObjectUrlRef.current = draftKey;
- setSelectedPost({
- draftFile: file,
- id: `local-${timestampMs}`,
- isDraftImagePreviewPending: true,
- localObjectUrl: draftKey,
- photo: {
- alt: `${displayName || "You"} post`,
- avatarUrl: profile.avatarUrl,
- imageUrl: "",
- name: displayName || "You",
- timestampMs,
- },
- postActionMode: "draft-post",
- });
-
- window.setTimeout(() => {
- if (activeLocalPostObjectUrlRef.current != draftKey) return;
-
- void spacePostPreviewImageForFile(file)
- .then((preview) => {
- if (activeLocalPostObjectUrlRef.current != draftKey) {
- URL.revokeObjectURL(preview.url);
- return;
- }
-
- localPostObjectUrlsRef.current.add(preview.url);
- activeLocalPostObjectUrlRef.current = preview.url;
- setSelectedPost((currentPost) => {
- if (currentPost?.localObjectUrl != draftKey)
- return currentPost;
-
- return {
- ...currentPost,
- isDraftImagePreviewPending: false,
- localObjectUrl: preview.url,
- photo: {
- ...currentPost.photo,
- height: preview.height,
- imageUrl: preview.url,
- width: preview.width,
- },
- };
- });
- })
- .catch((error: unknown) => {
- log.error("Failed to prepare post preview", error);
- const message = spacePostImageErrorMessage(error);
- setSelectedPost((currentPost) => {
- if (currentPost?.localObjectUrl != draftKey)
- return currentPost;
-
- return { ...currentPost, draftImageError: message };
- });
- });
- }, 0);
- return;
- }
-
- const localPost = await createLoadedLocalPostPhoto({
+ const profileViewerPhotos = viewerPostItems.flatMap((item) =>
+ viewerPhotosFromPost({
+ ...item,
+ ...dimensionsForPost(item),
avatarUrl: profile.avatarUrl,
- file,
- name: displayName || "You",
- });
- localPostObjectUrlsRef.current.add(localPost.objectUrl);
- activeLocalPostObjectUrlRef.current = localPost.objectUrl;
- setSelectedPost({
- draftFile: file,
- id: `local-${localPost.photo.timestampMs}`,
- localObjectUrl: localPost.objectUrl,
- photo: localPost.photo,
- postActionMode: "draft-post",
- });
- };
-
- const handlePostPhotoSelect: React.ChangeEventHandler<HTMLInputElement> = (
- event,
- ) => {
- const file = event.target.files?.[0];
- event.target.value = "";
- if (!file) return;
-
- setIsPostPhotoOpening(true);
- void prepareSelectedPostPhoto(file)
- .catch((error: unknown) => {
- log.error("Failed to open post photo draft", error);
- })
- .finally(() => {
- setIsPostPhotoOpening(false);
- });
+ imageUrl: loadedPostImageURLFor(item),
+ name: displayName,
+ }),
+ );
+ const handleSelectedPostIndexChange = (photoIndex: number) => {
+ const photo = profileViewerPhotos[photoIndex];
+ if (!photo) return;
+ const item = viewerPostItems.find(
+ (item) => item.postId == photo.postId,
+ );
+ if (item) setSelectedPost({ id: item.id, photo, photoIndex });
};
const shareInvite = async () => {
@@ -1073,14 +858,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
});
};
- React.useEffect(
- () => () => {
- activeLocalPostObjectUrlRef.current = null;
- revokeLocalPostObjectUrls();
- },
- [revokeLocalPostObjectUrls],
- );
-
const renderPostTile = (
{ aspectRatio, index, item }: PostMasonryTile,
rowAspectRatio: number,
@@ -1107,9 +884,17 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
onOpen={(openedImageUrl) => {
const postIndex = viewerPostIndexByID.get(item.id);
if (postIndex == undefined) return;
- setSelectedPost(
- selectedPostForItem(item, postIndex, openedImageUrl),
+ const photoIndex = profileViewerPhotos.findIndex(
+ (photo) => photo.postId == item.postId,
);
+ setSelectedPost({
+ id: item.id,
+ photoIndex,
+ photo: {
+ ...profileViewerPhotos[photoIndex]!,
+ imageUrl: openedImageUrl,
+ },
+ });
}}
onRememberDimensions={rememberLoadedPhotoDimensions}
/>
@@ -1340,13 +1125,9 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
}}
>
{isOwnerProfile && (
- <Box
- ref={postInputRef}
- component="input"
- type="file"
- accept={spacePostImageInputAccept}
- onChange={handlePostPhotoSelect}
- sx={{ display: "none" }}
+ <SpacePostPhotoInput
+ inputRef={postInputRef}
+ onSelect={setDraftFiles}
/>
)}
<Box
@@ -2002,40 +1783,29 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
onClick={openPostPhotoPicker}
/>
)}
+ {draftFiles && onCreatePost && (
+ <SpacePostComposer
+ files={draftFiles}
+ onClose={() => setDraftFiles(null)}
+ onPublish={onCreatePost}
+ onPublished={onPostSubmitted}
+ profile={profile}
+ />
+ )}
{selectedPost && (
<SpaceFileViewer
photo={selectedPost.photo}
- draftPostPreparationError={selectedPost.draftImageError}
- isDraftPostPreviewPending={
- selectedPost.isDraftImagePreviewPending
- }
- postActionMode={
- selectedPost.postActionMode ??
- selectedPostActionMode
- }
- photos={
- selectedViewerPostIndex == undefined
- ? undefined
- : profileViewerPhotos
- }
- photoIndex={selectedViewerPostIndex}
- onPhotoIndexChange={
- selectedViewerPostIndex == undefined
- ? undefined
- : handleSelectedPostIndexChange
- }
+ photos={profileViewerPhotos}
+ photoIndex={selectedPost.photoIndex}
+ onPhotoIndexChange={handleSelectedPostIndexChange}
+ onLoadPhoto={onLoadPostImage}
+ postActionMode={selectedPostActionMode}
onClose={closeSelectedPost}
onAddFriendForPostAction={
isPublicProfile
? onAddFriendForPostAction
: undefined
}
- onDraftPostExitStart={() => setIsDraftPostExiting(true)}
- onDraftPostPublished={() => {
- void clearSelectedPostHistory("back").then(() =>
- onPostSubmitted?.(),
- );
- }}
onDeletePost={
isOwnerProfile ? deleteSelectedPost : undefined
}
@@ -2043,30 +1813,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
onReplyToPost={
isFriendProfile ? onReplyToPost : undefined
}
- onPublishDraftPost={
- selectedPost.draftFile && onCreatePost
- ? (caption, edit) => {
- const previewUrl =
- selectedPost.photo.imageUrl;
- const publishPromise = onCreatePost(
- {
- cropArea: edit.cropArea,
- file: selectedPost.draftFile!,
- height: edit.height,
- previewUrl,
- rotationDegrees:
- edit.rotationDegrees,
- width: edit.width,
- },
- caption,
- );
- localPostObjectUrlsRef.current.delete(
- previewUrl,
- );
- return publishPromise;
- }
- : undefined
- }
onSetPostLiked={onSetPostLiked}
onUpdatePostCaption={
isOwnerProfile ? onUpdatePostCaption : undefined
diff --git a/web/apps/space/src/services/feed-cache.ts b/web/apps/space/src/services/feed-cache.ts
index 7a99ee5858..17421c641d 100644
--- a/web/apps/space/src/services/feed-cache.ts
+++ b/web/apps/space/src/services/feed-cache.ts
@@ -6,7 +6,7 @@ import { CachedSpacePost } from "services/post-cache";
import type { SpacePost, SpacePostPage } from "services/space";
import { z } from "zod";
-const spaceFeedCacheVersion = 1;
+const spaceFeedCacheVersion = 2;
const spaceFeedCacheSize = 10;
const SpaceFeedCacheSnapshotSchema = z.object({
@@ -51,6 +51,10 @@ const cacheKey = async (spaceId: string) => {
const clonePost = (post: SpacePost): SpacePost => ({
...post,
imageAsset: post.imageAsset ? { ...post.imageAsset } : undefined,
+ photos: post.photos?.map((photo) => ({
+ ...photo,
+ imageAsset: photo.imageAsset ? { ...photo.imageAsset } : undefined,
+ })),
});
const cloneSnapshot = (
@@ -64,6 +68,9 @@ const cacheablePost = (post: SpacePost): SpacePost => {
const cached = clonePost(post);
delete cached.avatarUrl;
delete cached.imageUrl;
+ cached.photos?.forEach((photo) => {
+ delete photo.imageUrl;
+ });
return cached;
};
diff --git a/web/apps/space/src/services/post-cache.ts b/web/apps/space/src/services/post-cache.ts
index 423f0187df..15016e71c2 100644
--- a/web/apps/space/src/services/post-cache.ts
+++ b/web/apps/space/src/services/post-cache.ts
@@ -18,6 +18,16 @@ export const CachedSpacePost = z.object({
friendID: z.string(),
height: z.number().optional(),
imageAsset: CachedSpacePostAsset.optional(),
+ photos: z
+ .array(
+ z.object({
+ height: z.number().optional(),
+ imageAsset: CachedSpacePostAsset.optional(),
+ thumbHash: z.string().optional(),
+ width: z.number().optional(),
+ }),
+ )
+ .optional(),
isUnavailable: z.boolean().optional(),
name: z.string(),
postId: z.number(),
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 321479310f..ea97e51e58 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -79,9 +79,16 @@ export interface SpacePostAsset {
spaceId: string;
}
-export interface SpacePost extends SpacePostBase {
+export interface SpacePostPhoto {
+ height?: number;
imageAsset?: SpacePostAsset;
imageUrl?: string;
+ thumbHash?: string;
+ width?: number;
+}
+
+export interface SpacePost extends SpacePostBase, SpacePostPhoto {
+ photos?: SpacePostPhoto[];
}
export interface SpacePostPage {
@@ -89,10 +96,7 @@ export interface SpacePostPage {
nextCursor?: string;
}
-export interface SpaceProfilePost extends SpacePostBase {
- imageAsset?: SpacePostAsset;
- imageUrl?: string;
-}
+export type SpaceProfilePost = SpacePost;
export interface SpaceProfilePostPage {
items: SpaceProfilePost[];
@@ -140,6 +144,7 @@ export type SpaceMessageKind = MessageResponse["kind"];
export interface SpaceMessageQuote {
imageUrl?: string;
isUnavailable?: boolean;
+ photoCount?: number;
postId: number;
spaceId: string;
}
@@ -166,6 +171,7 @@ export type SpaceMessageActivityType = MessageConversationActivity["type"];
export interface SpaceMessageActivityPost {
imageUrl?: string;
isDeleted?: boolean;
+ photoCount?: number;
postId: number;
spaceId: string;
}
@@ -439,6 +445,14 @@ const cacheAccountPostAssetURL = async (
const firstObject = (post: PostResponse) =>
post.objects.find((object) => object.objectKey.trim()) ?? null;
+const postPhotosFromResponse = (post: PostResponse): SpacePostPhoto[] =>
+ post.objects.map((object) => ({
+ height: object.height,
+ imageAsset: postAssetFrom(post, object),
+ thumbHash: object.thumbHash,
+ width: object.width,
+ }));
+
const postBaseFromResponse = (
post: PostResponse,
author: FriendProfile,
@@ -489,6 +503,7 @@ const postFromAccountPost = async (
height: object.height,
imageAsset: postAssetFrom(post, object),
imageUrl,
+ photos: postPhotosFromResponse(post),
thumbHash: object.thumbHash,
width: object.width,
};
@@ -506,6 +521,7 @@ const profilePostFromPost = (post: PostResponse): SpaceProfilePost => {
avatarUrl: null,
height: object.height,
imageAsset: postAssetFrom(post, object),
+ photos: postPhotosFromResponse(post),
thumbHash: object.thumbHash,
width: object.width,
};
@@ -621,6 +637,7 @@ const messageQuoteFromPostResponse = async (
): Promise<SpaceMessageQuote> => {
const object = firstObject(post);
const quote: SpaceMessageQuote = {
+ photoCount: post.objects.length,
postId: post.postId,
spaceId: post.spaceId,
};
@@ -757,6 +774,7 @@ export const loadCurrentMessageActivityPostPreview = async (
...post,
imageUrl: quote.imageUrl,
isDeleted: quote.isUnavailable,
+ photoCount: quote.photoCount,
};
} finally {
releaseCurrentSpaceContext(ctx);
@@ -1132,37 +1150,36 @@ export const loadCurrentFriendAvatarURL = async (
export const createCurrentPhotoPost = async ({
caption,
- file,
- height,
+ images,
spaceId,
- thumbHash,
- width,
}: {
caption?: string;
- file: File;
- height?: number;
+ images: { file: File; height: number; width: number; thumbHash: string }[];
spaceId: string;
- thumbHash: string;
- width?: number;
}) => {
const ctx = await ensureCurrentSpaceContext();
try {
- const bytes = new Uint8Array(await file.arrayBuffer());
- const normalizedWidth = normalizedImageDimension(width);
- const normalizedHeight = normalizedImageDimension(height);
+ const photos = await Promise.all(
+ images.map(async (image) => ({
+ bytes: new Uint8Array(await image.file.arrayBuffer()),
+ options: {
+ width: normalizedImageDimension(image.width),
+ height: normalizedImageDimension(image.height),
+ mediaType: image.file.type || undefined,
+ thumbHash: image.thumbHash || undefined,
+ },
+ })),
+ );
const created = await ctx.createPhotoPost(
spaceId,
- bytes,
+ photos,
caption?.trim() || null,
- {
- width: normalizedWidth,
- height: normalizedHeight,
- mediaType: file.type || undefined,
- thumbHash: thumbHash || undefined,
- },
);
- const object = firstObject(created);
- if (object) await cacheAccountPostAssetURL(created, object, file);
+ await Promise.all(
+ created.objects.map((object, index) =>
+ cacheAccountPostAssetURL(created, object, images[index]!.file),
+ ),
+ );
const post = await postFromAccountPost(ctx, created, true, spaceId);
await prependCachedSpaceFeedPost(spaceId, post);
return post;
diff --git a/web/apps/space/src/state/AppStateProvider.tsx b/web/apps/space/src/state/AppStateProvider.tsx
index 864b3df7bd..ec86a0425c 100644
--- a/web/apps/space/src/state/AppStateProvider.tsx
+++ b/web/apps/space/src/state/AppStateProvider.tsx
@@ -62,8 +62,9 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
useState<SpaceLoginCredentials | null>(null);
const [pendingPasskeyVerification, setPendingPasskeyVerification] =
useState<PendingSpacePasskeyVerification | null>(null);
- const [pendingPostPhotoFile, setPendingPostPhotoFile] =
- useState<File | null>(null);
+ const [pendingPostPhotoFiles, setPendingPostPhotoFiles] = useState<
+ File[] | null
+ >(null);
const [pendingProfileAvatarFile, setPendingProfileAvatarFile] =
useState<File | null>(null);
const [pendingProfileCoverFile, setPendingProfileCoverFile] =
@@ -118,87 +119,67 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
const publishPost = useCallback(
async (
- image: Parameters<SpaceAppState["publishPost"]>[0],
+ images: Parameters<SpaceAppState["publishPost"]>[0],
caption: string,
) => {
const profile = profileRef.current;
const spaceId = profile?.spaceId;
if (!spaceId) throw new Error("Missing space.");
+ const cover = images[0]!;
+ const previewUrl = cover.previewUrl;
const generation = ++postPublishGenerationRef.current;
const localPostId = createLocalFeedPostID();
+ const timestampMs = Date.now();
setLocalFeedPosts((current) => [
{
avatarUrl: profile.avatarUrl,
caption: caption.trim() || undefined,
friendID: spaceId,
- height: image.height,
+ height: cover.height,
id: localPostId,
- imageUrl: image.previewUrl,
+ imageUrl: previewUrl,
name: profile.fullName.trim() || profile.username.trim(),
+ photoCount: images.length,
spaceId,
status: "pending",
- timestampMs: Date.now(),
- width: image.width,
+ timestampMs,
+ width: cover.width,
},
...current,
]);
- let publication: SpacePostPublication = {
+ const publication: SpacePostPublication = {
phase: "posting",
- previewUrl: image.previewUrl,
+ previewUrl,
post: {
caption: caption.trim() || undefined,
friendID: spaceId,
- height: image.height,
- imageUrl: image.previewUrl,
+ height: cover.height,
+ imageUrl: previewUrl,
name: profile.fullName,
postId: 0,
spaceId,
- timestampMs: Date.now(),
+ timestampMs,
viewerLiked: false,
- width: image.width,
+ width: cover.width,
},
};
setPostPublication(publication);
try {
- const preparedImage = await prepareSpacePostImageFromEdit(
- image.file,
- image.cropArea,
- image.rotationDegrees,
- );
- if (postPublishGenerationRef.current == generation) {
- const previewUrl = URL.createObjectURL(preparedImage.file);
- publication = {
- ...publication,
- previewUrl,
- post: {
- ...publication.post,
- height: preparedImage.height,
- imageUrl: previewUrl,
- width: preparedImage.width,
- },
- };
- setPostPublication(publication);
- setLocalFeedPosts((current) =>
- current.map((item) =>
- item.id == localPostId && item.status == "pending"
- ? {
- ...item,
- imageUrl: previewUrl,
- height: preparedImage.height,
- width: preparedImage.width,
- }
- : item,
+ const preparedImages = [];
+ for (const image of images) {
+ preparedImages.push(
+ await prepareSpacePostImageFromEdit(
+ image.file,
+ image.cropArea,
+ image.rotationDegrees,
),
);
}
const post = await createCurrentPhotoPost({
caption,
- file: preparedImage.file,
- height: preparedImage.height,
+ images: preparedImages,
spaceId,
- thumbHash: preparedImage.thumbHash,
- width: preparedImage.width,
});
confirmLocalFeedPost(setLocalFeedPosts, localPostId, post);
if (postPublishGenerationRef.current == generation) {
@@ -396,7 +377,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
setPostPublication(null);
setPendingLoginCredentials(null);
setPendingPasskeyVerification(null);
- setPendingPostPhotoFile(null);
+ setPendingPostPhotoFiles(null);
setPendingProfileAvatarFile(null);
setPendingProfileCoverFile(null);
setPendingCreateProfile(null);
@@ -417,7 +398,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
onboardingEntrySource,
pendingLoginCredentials,
pendingPasskeyVerification,
- pendingPostPhotoFile,
+ pendingPostPhotoFiles,
pendingProfileAvatarFile,
pendingProfileCoverFile,
pendingCreateProfile,
@@ -435,7 +416,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
setOnboardingEntrySource,
setPendingLoginCredentials,
setPendingPasskeyVerification,
- setPendingPostPhotoFile,
+ setPendingPostPhotoFiles,
setPendingProfileAvatarFile,
setPendingProfileCoverFile,
setPendingCreateProfile,
@@ -451,7 +432,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
onboardingEntrySource,
pendingLoginCredentials,
pendingPasskeyVerification,
- pendingPostPhotoFile,
+ pendingPostPhotoFiles,
pendingProfileAvatarFile,
pendingProfileCoverFile,
pendingCreateProfile,
diff --git a/web/apps/space/src/state/app-state.tsx b/web/apps/space/src/state/app-state.tsx
index 249b1ce2d8..a419147de3 100644
--- a/web/apps/space/src/state/app-state.tsx
+++ b/web/apps/space/src/state/app-state.tsx
@@ -36,6 +36,7 @@ export interface PendingSpaceFeedPost {
imageUrl: string;
name: string;
spaceId: string;
+ photoCount: number;
status: "pending";
timestampMs: number;
width?: number;
@@ -75,7 +76,7 @@ export interface SpaceAppState {
onboardingEntrySource: OnboardingEntrySource;
pendingLoginCredentials: SpaceLoginCredentials | null;
pendingPasskeyVerification: PendingSpacePasskeyVerification | null;
- pendingPostPhotoFile: File | null;
+ pendingPostPhotoFiles: File[] | null;
pendingProfileAvatarFile: File | null;
pendingProfileCoverFile: File | null;
pendingCreateProfile: PendingCreateProfile | null;
@@ -88,7 +89,7 @@ export interface SpaceAppState {
React.SetStateAction<SpacePostPublication | null>
>;
publishPost: (
- image: SpaceDraftPostImage,
+ images: SpaceDraftPostImage[],
caption: string,
) => Promise<SpacePost>;
refreshProfile: (
@@ -106,7 +107,9 @@ export interface SpaceAppState {
setPendingPasskeyVerification: React.Dispatch<
React.SetStateAction<PendingSpacePasskeyVerification | null>
>;
- setPendingPostPhotoFile: React.Dispatch<React.SetStateAction<File | null>>;
+ setPendingPostPhotoFiles: React.Dispatch<
+ React.SetStateAction<File[] | null>
+ >;
setPendingProfileAvatarFile: React.Dispatch<
React.SetStateAction<File | null>
>;
diff --git a/web/apps/space/src/utils/post-display.ts b/web/apps/space/src/utils/post-display.ts
index a565b92478..99b03021dc 100644
--- a/web/apps/space/src/utils/post-display.ts
+++ b/web/apps/space/src/utils/post-display.ts
@@ -12,6 +12,7 @@ export const profilePostItemsFromPosts = (
id: String(post.postId),
imageAsset: post.imageAsset,
imageUrl: post.imageUrl,
+ photos: post.photos,
isUnavailable: post.isUnavailable,
name: post.name,
postId: post.postId,
diff --git a/web/apps/space/src/utils/post-photos.ts b/web/apps/space/src/utils/post-photos.ts
new file mode 100644
index 0000000000..27b8aeb2f7
--- /dev/null
+++ b/web/apps/space/src/utils/post-photos.ts
@@ -0,0 +1,37 @@
+import type { SpaceViewerPhoto } from "components/FileViewer";
+import type { SpacePostPhoto } from "services/space";
+
+export const maxSpacePostPhotos = 10;
+
+export const spacePostPhotos = (
+ post: SpacePostPhoto & { photos?: SpacePostPhoto[] },
+): SpacePostPhoto[] => (post.photos?.length ? post.photos : [post]);
+
+export const viewerPhotosFromPost = (
+ post: Omit<SpaceViewerPhoto, "imageUrl"> & {
+ imageUrl?: string;
+ photos?: SpacePostPhoto[];
+ },
+): SpaceViewerPhoto[] => {
+ const photos = spacePostPhotos(post);
+ return photos.map((photo, index) => ({
+ ...post,
+ ...photo,
+ height: photo.height ?? (index == 0 ? post.height : undefined),
+ imageUrl: photo.imageUrl || (index == 0 ? post.imageUrl : "") || "",
+ postPhotoIndex: index,
+ postPhotoCount: photos.length,
+ width: photo.width ?? (index == 0 ? post.width : undefined),
+ }));
+};
+
+export const movePostPhoto = <T>(
+ photos: T[],
+ from: number,
+ to: number,
+): T[] => {
+ const reordered = [...photos];
+ const [photo] = reordered.splice(from, 1);
+ reordered.splice(to, 0, photo!);
+ return reordered;
+};
diff --git a/web/apps/space/tests/feed-cache.test.ts b/web/apps/space/tests/feed-cache.test.ts
index f133c03676..0737ece239 100644
--- a/web/apps/space/tests/feed-cache.test.ts
+++ b/web/apps/space/tests/feed-cache.test.ts
@@ -87,6 +87,41 @@ test("persists the first publication before a feed has been cached", async () =>
expect(cached?.dirty).toBe(true);
});
+test("restores every photo in order and preserves shared post edits", async () => {
+ const original = post(3);
+ original.photos = ["cover", "second", "third"].map((objectKey, index) => ({
+ imageAsset: { ...original.imageAsset!, objectKey },
+ imageUrl: `blob:${objectKey}`,
+ height: 800 + index,
+ width: 1200,
+ thumbHash: `hash-${index}`,
+ }));
+ await cacheCurrentSpaceFeedPage("self", { items: [original] });
+ await patchCachedSpaceFeedPost("self", 3, {
+ caption: "Edited caption",
+ viewerLiked: true,
+ });
+ const firstRead = await loadCachedSpaceFeed("self");
+ firstRead!.items[0]!.photos![1]!.imageAsset!.objectKey =
+ "changed by caller";
+ clearSpaceFeedMemoryCache();
+ const restored = (await loadCachedSpaceFeed("self"))!.items[0]!;
+ expect(restored).toMatchObject({
+ caption: "Edited caption",
+ viewerLiked: true,
+ });
+ expect(
+ restored.photos?.map((photo) => photo.imageAsset?.objectKey),
+ ).toEqual(["cover", "second", "third"]);
+ expect(restored.photos?.map((photo) => photo.height)).toEqual([
+ 800, 801, 802,
+ ]);
+ expect(restored.photos?.every((photo) => !("imageUrl" in photo))).toBe(
+ true,
+ );
+ expect(original.photos[1]?.imageUrl).toBe("blob:second");
+});
+
test("serializes new posts, likes, edits and deletions without losing changes", async () => {
await cacheCurrentSpaceFeedPage("self", {
items: [post(2), post(1)],
diff --git a/web/apps/space/tests/post-photos.test.ts b/web/apps/space/tests/post-photos.test.ts
new file mode 100644
index 0000000000..241220dbca
--- /dev/null
+++ b/web/apps/space/tests/post-photos.test.ts
@@ -0,0 +1,82 @@
+import { expect, test } from "vitest";
+import { viewerPhotosFromPost } from "../src/utils/post-photos";
+
+test("profile navigation groups photos under their post and resets each counter", () => {
+ const posts = [
+ {
+ postId: 1,
+ name: "Maya",
+ timestampMs: 1,
+ caption: "A day out",
+ viewerLiked: true,
+ imageUrl: "blob:cover",
+ photos: [
+ { width: 1200, height: 800 },
+ { imageUrl: "blob:portrait", width: 800, height: 1200 },
+ ],
+ },
+ { postId: 2, name: "Maya", timestampMs: 2, imageUrl: "blob:single" },
+ ];
+ const slides = posts.flatMap(viewerPhotosFromPost);
+ expect(
+ slides.map((photo) => [
+ photo.postId,
+ photo.postPhotoIndex,
+ photo.postPhotoCount,
+ ]),
+ ).toEqual([
+ [1, 0, 2],
+ [1, 1, 2],
+ [2, 0, 1],
+ ]);
+ expect(slides.map((photo) => photo.imageUrl)).toEqual([
+ "blob:cover",
+ "blob:portrait",
+ "blob:single",
+ ]);
+ expect(
+ slides.slice(0, 2).map((photo) => [photo.caption, photo.viewerLiked]),
+ ).toEqual([
+ ["A day out", true],
+ ["A day out", true],
+ ]);
+ expect(slides[1]).toMatchObject({ width: 800, height: 1200 });
+});
+
+test.each([
+ { width: 800, height: 1200 },
+ { width: 800, height: 800 },
+])("preserves measured cover dimensions $width Γ— $height", (dimensions) => {
+ const slides = viewerPhotosFromPost({
+ name: "Maya",
+ timestampMs: 1,
+ imageUrl: "blob:cover",
+ ...dimensions,
+ photos: [
+ { width: undefined, height: undefined },
+ { imageUrl: "blob:other" },
+ ],
+ });
+
+ expect(slides[0]).toMatchObject(dimensions);
+ expect(slides[1]?.width).toBeUndefined();
+ expect(slides[1]?.height).toBeUndefined();
+});
+
+test.each([
+ { width: 600, height: 900 },
+ { width: 600, height: undefined },
+ { width: undefined, height: 900 },
+])("uses available cover metadata dimensions %o", (metadata) => {
+ const [slide] = viewerPhotosFromPost({
+ name: "Maya",
+ timestampMs: 1,
+ imageUrl: "blob:cover",
+ width: 800,
+ height: 1200,
+ photos: [metadata],
+ });
+
+ expect(slide?.width).toBe(metadata.width ?? 800);
+ expect(slide?.height).toBe(metadata.height ?? 1200);
+});
diff --git a/web/apps/space/tests/post-upload.test.ts b/web/apps/space/tests/post-upload.test.ts
new file mode 100644
index 0000000000..6bdff67aeb
--- /dev/null
+++ b/web/apps/space/tests/post-upload.test.ts
@@ -0,0 +1,216 @@
+import {
+ encryptSpaceRootEntityKey,
+ openSpaceAccountContext,
+} from "ente-space-wasm";
+import { afterEach, expect, test, vi } from "vitest";
+
+afterEach(() => vi.unstubAllGlobals());
+
+const photo = (index: number) => ({
+ bytes: new TextEncoder().encode("RIFF\x04\x00\x00\x00WEBP"),
+ options: {
+ width: 1200 + index,
+ height: 800,
+ mediaType: "image/webp",
+ thumbHash: `hash-${index}`,
+ },
+});
+
+interface UploadedPost {
+ encryptedPostKey: string;
+ captionCipher: string;
+ keyVersion: number;
+ objects: { objectKey: string; position: number; metadataCipher: string }[];
+}
+
+const uploadFixture = async (failSecondUpload = false) => {
+ const rootKey = btoa("r".repeat(32));
+ const spaceKey = btoa("s".repeat(32));
+ const ctx = await openSpaceAccountContext({
+ baseUrl: "http://localhost",
+ spaceSessionToken: "test-session",
+ spaceRootKeyB64: rootKey,
+ clientPackage: "space-test",
+ ownedSpaces: [
+ {
+ spaceId: "test-space",
+ spaceSlug: "test",
+ rootWrappedSpaceKey: await encryptSpaceRootEntityKey(
+ spaceKey,
+ rootKey,
+ ),
+ publicKey: "",
+ encryptedSecretKey: "",
+ encryptedProfile: "",
+ keyVersion: 1,
+ },
+ ],
+ });
+ const calls: string[] = [];
+ const uploadedAssets = new Map<string, ArrayBuffer>();
+ let presigned = 0;
+ let created: UploadedPost | undefined;
+ const respond = async (request: Request) => {
+ const path = new URL(request.url).pathname;
+ calls.push(`${request.method} ${path}`);
+ if (path.endsWith("/uploads/presign")) {
+ const index = presigned++;
+ return Response.json({
+ url: `http://localhost/upload/${index}`,
+ method: "PUT",
+ headers: {},
+ objectKey: `photo-${index}`,
+ expiresIn: 300,
+ });
+ }
+ if (request.method == "PUT") {
+ uploadedAssets.set(
+ `photo-${path.split("/").at(-1)}`,
+ await request.arrayBuffer(),
+ );
+ return new Response("", {
+ status: failSecondUpload && path == "/upload/1" ? 500 : 200,
+ });
+ }
+ if (path.endsWith("/assets/redirect")) {
+ const objectKey = new URL(request.url).searchParams.get(
+ "objectKey",
+ );
+ return Response.json({
+ url: `http://localhost/assets/${objectKey}`,
+ expiresIn: 300,
+ });
+ }
+ if (path.startsWith("/assets/")) {
+ return new Response(
+ uploadedAssets.get(path.slice("/assets/".length)),
+ );
+ }
+ if (request.method == "POST" && path.endsWith("/posts")) {
+ created = (await request.json()) as UploadedPost;
+ return Response.json({ postId: 501 });
+ }
+ if (request.method == "GET" && path.endsWith("/posts/501")) {
+ return Response.json({
+ ...created,
+ postId: 501,
+ spaceId: "test-space",
+ spaceSlug: "test",
+ author: { spaceId: "test-space", spaceSlug: "test" },
+ createdAt: "2026-09-17T00:00:00Z",
+ viewerLiked: false,
+ });
+ }
+ throw new Error(`Unexpected request: ${request.method} ${path}`);
+ };
+ vi.stubGlobal("fetch", async (request: Request) => {
+ const response = await respond(request);
+ Object.defineProperty(response, "url", { value: request.url });
+ return response;
+ });
+ return { ctx, calls, created: () => created };
+};
+
+test.each([1, 3, 10])(
+ "publishes %i encrypted photos in order with one caption",
+ async (count) => {
+ const { ctx, calls, created } = await uploadFixture();
+ try {
+ const result = await ctx.createPhotoPost(
+ "test-space",
+ Array.from({ length: count }, (_, index) => photo(index)),
+ "One shared caption",
+ );
+ expect(result.caption).toBe("One shared caption");
+ expect(result.objects.map((object) => object.objectKey)).toEqual(
+ Array.from({ length: count }, (_, i) => `photo-${i}`),
+ );
+ expect(result.objects.map((object) => object.width)).toEqual(
+ Array.from({ length: count }, (_, i) => 1200 + i),
+ );
+ expect(result.objects.map((object) => object.thumbHash)).toEqual(
+ Array.from({ length: count }, (_, i) => `hash-${i}`),
+ );
+ expect(created()?.objects.map((object) => object.position)).toEqual(
+ Array.from({ length: count }, (_, i) => i),
+ );
+ expect(created()?.captionCipher).not.toContain(
+ "One shared caption",
+ );
+ expect(
+ created()?.objects.every((object) => object.metadataCipher),
+ ).toBe(true);
+ expect(
+ calls.filter((call) => call == "POST /spaces/test-space/posts"),
+ ).toHaveLength(1);
+ expect(
+ calls.indexOf("POST /spaces/test-space/posts"),
+ ).toBeGreaterThan(calls.indexOf(`PUT /upload/${count - 1}`));
+ } finally {
+ ctx.free();
+ }
+ },
+);
+
+test("copies typed-array photo bytes without JavaScript iteration", async () => {
+ const { ctx, created } = await uploadFixture();
+ const input = photo(0);
+ const buffer = new Uint8Array(input.bytes.length + 16);
+ buffer.set(input.bytes, 8);
+ input.bytes = buffer.subarray(8, 8 + input.bytes.length);
+ Object.defineProperty(input.bytes, Symbol.iterator, {
+ value: () => {
+ throw new Error("Photo bytes must be copied in bulk");
+ },
+ });
+ try {
+ const post = await ctx.createPhotoPost(
+ "test-space",
+ [input],
+ "Caption",
+ );
+ expect(created()?.objects).toHaveLength(1);
+ const downloaded = await ctx.downloadPostAssetWithKey(
+ post.spaceId,
+ post.encryptedPostKey,
+ post.keyVersion,
+ post.spaceId,
+ post.objects[0]!.objectKey,
+ );
+ expect(downloaded).toEqual(photo(0).bytes);
+ } finally {
+ ctx.free();
+ }
+});
+
+test("a failed photo upload does not publish a partial post", async () => {
+ const { ctx, calls } = await uploadFixture(true);
+ try {
+ await expect(
+ ctx.createPhotoPost(
+ "test-space",
+ [photo(0), photo(1), photo(2)],
+ "Caption",
+ ),
+ ).rejects.toThrow();
+ expect(calls).not.toContain("POST /spaces/test-space/posts");
+ } finally {
+ ctx.free();
+ }
+});
+
+test.each([0, 11])("rejects %i photos before uploading", async (count) => {
+ const { ctx, calls } = await uploadFixture();
+ try {
+ await expect(
+ ctx.createPhotoPost(
+ "test-space",
+ Array.from({ length: count }, (_, i) => photo(i)),
+ "Caption",
+ ),
+ ).rejects.toThrow("Choose between 1 and 10 photos");
+ expect(calls).toHaveLength(0);
+ } finally {
+ ctx.free();
+ }
+});