π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Improve space mobile viewer navigation
Anand Baburajana52356988a11
diff --git a/web/apps/space/src/components/SpaceFileViewer.tsx b/web/apps/space/src/components/SpaceFileViewer.tsxindex f9d970b81a..cc5ee7e0c6 100644--- a/web/apps/space/src/components/SpaceFileViewer.tsx+++ b/web/apps/space/src/components/SpaceFileViewer.tsx@@ -43,6 +43,8 @@ const replyInputPaddingLeft = 18;const captionInputMaxHeight = 112;const defaultPhotoWidth = 900;const defaultPhotoHeight = 680;+const viewerSwipeMinDeltaPx = 72;+const viewerSwipeAxisRatio = 1.5;const postButtonSpin = keyframes`from {@@ -114,11 +116,58 @@ interface SpaceFileViewerProps {) => Promise<void>;onReplyToPost?: (postId: number, text: string) => Promise<void>;onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;+ onSwipeLeft?: () => void;+ onSwipeRight?: () => void;+ onPhotoIndexChange?: (index: number) => void;photo: SpaceViewerPhoto;+ photoIndex?: number;+ photos?: SpaceViewerPhoto[];focusReplyOnOpen?: boolean;postActionMode?: SpaceViewerPostActionMode;}+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;+ }+ if ("changedTouches" in event) {+ const touch = (event as TouchEvent).changedTouches[0];+ if (!touch) return undefined;+ return { x: touch.pageX, y: touch.pageY };+ }+ 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,+ };+ }+ return undefined;+};++const viewerSwipeStartsOnInteractiveTarget = (target: EventTarget | null) =>+ target instanceof Element &&+ Boolean(+ target.closest(+ "input, textarea, select, button, [data-space-viewer-chrome='true'], [data-space-viewer-bottom='true']",+ ),+ );+const viewerActionButtonSx = {alignItems: "center",bgcolor: controlBackground,@@ -178,17 +227,44 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({onPublishDraftPost,onReplyToPost,onSetPostLiked,+ onSwipeLeft,+ onSwipeRight,+ onPhotoIndexChange,photo,+ photoIndex = 0,+ photos,postActionMode = "like-only",}) => {const activePostActionMode = postActionMode;const isDraftPost = activePostActionMode == "draft-post";const { showLikeButton: showPhotoLikeButton } =spaceViewerPostActionConfigs[activePostActionMode];+ const viewerPhotos = photos && photos.length > 0 ? photos : [photo];+ const activePhotoIndex = Math.min(+ Math.max(photoIndex, 0),+ viewerPhotos.length - 1,+ );+ const activePhoto = viewerPhotos[activePhotoIndex] ?? photo;+ const viewerPhotosRef = React.useRef(viewerPhotos);+ const onCloseRef = React.useRef(onClose);+ const onPhotoIndexChangeRef = React.useRef(onPhotoIndexChange);+ const initialPhotoIndexRef = React.useRef(activePhotoIndex);+ const fallbackPhotoRef = React.useRef(activePhoto);+ const pswpRef = React.useRef<PhotoSwipe | undefined>(undefined);+ viewerPhotosRef.current = viewerPhotos;+ onCloseRef.current = onClose;+ onPhotoIndexChangeRef.current = onPhotoIndexChange;+ fallbackPhotoRef.current = activePhoto;+ const viewerPhotosContentKey = viewerPhotos+ .map(+ (item) =>+ `${item.imageUrl}:${item.width ?? ""}:${item.height ?? ""}`,+ )+ .join("|");const [isPhotoLiked, setIsPhotoLiked] = React.useState(- photo.viewerLiked ?? false,+ activePhoto.viewerLiked ?? false,);- const [caption, setCaption] = React.useState(photo.caption ?? "");+ const [caption, setCaption] = React.useState(activePhoto.caption ?? "");const [replyText, setReplyText] = React.useState("");const [isReplyFocused, setIsReplyFocused] =React.useState(focusReplyOnOpen);@@ -200,8 +276,8 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({caption: string;edit: SpaceViewerDraftPostEdit;}>();- const displayName = firstNameFrom(photo.name);- const dateLabel = formatSpaceDate(photo.timestampMs);+ const displayName = firstNameFrom(activePhoto.name);+ const dateLabel = formatSpaceDate(activePhoto.timestampMs);const displayCaption = isDraftPost ? "" : caption.trim();const hasDisplayCaption = displayCaption.length > 0;const viewerRootRef = React.useRef<HTMLDivElement | null>(null);@@ -230,29 +306,41 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({(!onPublishDraftPost && !canQueueDraftPostPublish);const isReplyActionRunning = replyActionPhase != null;const canReplyToPost = Boolean(- !isDraftPost && photo.postId && onReplyToPost,+ !isDraftPost && activePhoto.postId && onReplyToPost,);const isReplyMode =canReplyToPost &&(isReplyFocused || replyText.trim().length > 0 || isReplyActionRunning);const canSendReply =canReplyToPost &&- Boolean(photo.postId) &&+ Boolean(activePhoto.postId) &&replyText.trim().length > 0 &&!isReplyActionRunning;+ 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 ||+ deleteSheetOpen ||+ isDeleteExit ||+ isDraftPost ||+ isDraftPostPreviewPending;const handlePhotoLikeClick = () => {- if (!photo.postId || !onSetPostLiked) {+ if (!activePhoto.postId || !onSetPostLiked) {setIsPhotoLiked((isLiked) => !isLiked);return;}const nextLiked = !isPhotoLiked;setIsPhotoLiked(nextLiked);- void onSetPostLiked(photo.postId, nextLiked).catch((error: unknown) => {- console.error("Failed to update post like", error);- setIsPhotoLiked(!nextLiked);- });+ void onSetPostLiked(activePhoto.postId, nextLiked).catch(+ (error: unknown) => {+ console.error("Failed to update post like", error);+ setIsPhotoLiked(!nextLiked);+ },+ );};const closeActions = () => setActionsAnchor(null);@@ -283,8 +371,12 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({};const draftPostEdit = React.useCallback((): SpaceViewerDraftPostEdit => {- return { height: photo.height, rotationDegrees: 0, width: photo.width };- }, [photo.height, photo.width]);+ return {+ height: activePhoto.height,+ rotationDegrees: 0,+ width: activePhoto.width,+ };+ }, [activePhoto.height, activePhoto.width]);const publishDraftPostWithCaption = React.useCallback((captionToPublish: string, editToPublish: SpaceViewerDraftPostEdit) => {@@ -336,12 +428,12 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({const sendReply = () => {const text = replyText.trim();- if (!canSendReply || !photo.postId || !onReplyToPost) return;+ if (!canSendReply || !activePhoto.postId || !onReplyToPost) return;setReplyActionPhase("busy");void (async () => {try {- await onReplyToPost(photo.postId!, text);+ await onReplyToPost(activePhoto.postId!, text);setReplyText("");setReplyActionPhase("done");} catch (error) {@@ -375,7 +467,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({setIsReplyFocused(true);replyInputRef.current?.focus();- }, [canReplyToPost, focusReplyOnOpen, photo.postId]);+ }, [canReplyToPost, focusReplyOnOpen, activePhoto.postId]);React.useEffect(() => {if (deleteActionPhase != "done") return;@@ -415,21 +507,35 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({}, [replyActionPhase]);React.useEffect(() => {- setIsPhotoLiked(photo.viewerLiked ?? false);- setCaption(photo.caption ?? "");+ setIsPhotoLiked(activePhoto.viewerLiked ?? false);+ setCaption(activePhoto.caption ?? "");setReplyText("");setIsReplyFocused(focusReplyOnOpen && canReplyToPost);setReplyActionPhase(null);}, [- photo.caption,- photo.imageUrl,- photo.postId,- photo.timestampMs,- photo.viewerLiked,+ activePhoto.caption,+ activePhoto.imageUrl,+ activePhoto.postId,+ activePhoto.timestampMs,+ activePhoto.viewerLiked,canReplyToPost,focusReplyOnOpen,]);+ React.useEffect(() => {+ const pswp = pswpRef.current;+ if (!pswp) return;++ const refreshIndex = (index: number) => {+ if (index >= 0 && index < viewerPhotosRef.current.length) {+ pswp.refreshSlideContent(index);+ }+ };+ refreshIndex(pswp.currIndex - 1);+ refreshIndex(pswp.currIndex);+ refreshIndex(pswp.currIndex + 1);+ }, [viewerPhotosContentKey]);+const handleDeleteSheetExited = () => {if (!isDeleteExit) return;@@ -455,7 +561,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({if (disposed || !viewerRootRef.current) return;pswp = new PhotoSwipeClass({- allowPanToNext: false,+ allowPanToNext: viewerPhotosRef.current.length > 1,appendToEl: viewerRootRef.current,arrowKeys: false,arrowNext: false,@@ -466,19 +572,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({close: false,closeOnVerticalDrag: false,counter: false,- dataSource: [- {- alt: photo.alt ?? `${photo.name} post`,- height: photo.height ?? defaultPhotoHeight,- src: photo.imageUrl,- width: photo.width ?? defaultPhotoWidth,- },- ],doubleTapAction: "zoom",errorMsg: "Unable to preview this photo",escKey: false,imageClickAction: "zoom",- index: 0,+ index: initialPhotoIndexRef.current,loop: false,mainClass: "pswp-space-viewer",paddingFn: () => ({@@ -496,8 +594,97 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({wheelToZoom: true,zoom: false,});+ pswpRef.current = pswp;+ pswp.addFilter("numItems", () => viewerPhotosRef.current.length);+ pswp.addFilter("itemData", (_, index) => {+ const item =+ viewerPhotosRef.current[index] ?? fallbackPhotoRef.current;+ return {+ alt: item.alt ?? `${item.name} post`,+ height: item.height ?? defaultPhotoHeight,+ src: item.imageUrl,+ width: item.width ?? defaultPhotoWidth,+ };+ });pswp.on("close", () => {- if (!closedByReact) onClose();+ if (!closedByReact) onCloseRef.current();+ });+ pswp.on("change", () => {+ const nextIndex = pswp?.currIndex;+ if (nextIndex != undefined) {+ onPhotoIndexChangeRef.current?.(nextIndex);+ }+ });+ pswp.on("pointerDown", ({ originalEvent }) => {+ if (isSwipeBlockedRef.current) return;+ if (+ !swipeActionsRef.current.onSwipeLeft &&+ !swipeActionsRef.current.onSwipeRight+ ) {+ return;+ }+ if (viewerSwipeStartsOnInteractiveTarget(originalEvent.target))+ 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+ ) {+ return;+ }++ gesture.lastX = point.x;+ gesture.lastY = point.y;+ });+ 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;+ if (+ Math.abs(deltaX) <+ Math.abs(deltaY) * viewerSwipeAxisRatio+ ) {+ return;+ }++ const swipeAction =+ deltaX < 0+ ? swipeActionsRef.current.onSwipeLeft+ : swipeActionsRef.current.onSwipeRight;+ swipeAction?.();});pswp.init();});@@ -505,18 +692,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({return () => {disposed = true;closedByReact = true;+ swipeGestureRef.current = null;+ pswpRef.current = undefined;pswp?.destroy();};- }, [- onClose,- photo.alt,- photo.height,- photo.imageUrl,- photo.name,- photo.width,- isDraftPost,- isDraftPostPreviewPending,- ]);+ }, [isDraftPost, isDraftPostPreviewPending]);React.useEffect(() => {if (typeof document == "undefined") return;@@ -533,12 +713,12 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({if (deleteSheetOpen) return;if (event.key != "Escape") return;- onClose();+ onCloseRef.current();};window.addEventListener("keydown", closeOnEscape);return () => window.removeEventListener("keydown", closeOnEscape);- }, [deleteSheetOpen, onClose]);+ }, [deleteSheetOpen]);return (<Box@@ -616,11 +796,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({},}}>- {photo.avatarUrl ? (+ {activePhoto.avatarUrl ? (<Boxcomponent="img"alt=""- src={photo.avatarUrl}+ src={activePhoto.avatarUrl}sx={{display: "block",height: "100%",@@ -704,7 +884,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({<Boxcomponent="time"dateTime={new Date(- photo.timestampMs,+ activePhoto.timestampMs,).toISOString()}sx={{color: textTertiary,@@ -901,8 +1081,8 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({) : (<Boxcomponent="img"- alt={photo.alt ?? `${photo.name} post`}- src={photo.imageUrl}+ alt={activePhoto.alt ?? `${activePhoto.name} post`}+ src={activePhoto.imageUrl}sx={{display: "block",maxHeight: "100%",diff --git a/web/apps/space/src/hooks/useBrowserBackClose.ts b/web/apps/space/src/hooks/useBrowserBackClose.tsnew file mode 100644index 0000000000..d60d78520c--- /dev/null+++ b/web/apps/space/src/hooks/useBrowserBackClose.ts@@ -0,0 +1,130 @@+import { useCallback, useEffect, useRef } from "react";++type BrowserBackCleanupAction = "back" | "replace";++const waitForNextPopState = () =>+ new Promise<void>((resolve) => {+ const timeoutIDRef = { current: 0 };+ const finish = () => {+ window.removeEventListener("popstate", handlePopState);+ window.clearTimeout(timeoutIDRef.current);+ resolve();+ };+ const handlePopState = () => finish();++ window.addEventListener("popstate", handlePopState, { once: true });+ timeoutIDRef.current = window.setTimeout(finish, 1000);+ });++const browserBackStateWithMarker = (+ state: unknown,+ stateKey: string,+ marker: string,+) =>+ state && typeof state == "object"+ ? { ...(state as Record<string, unknown>), [stateKey]: marker }+ : { [stateKey]: marker };++const browserBackStateHasMarker = (+ state: unknown,+ stateKey: string,+ marker: string,+) =>+ !!state &&+ typeof state == "object" &&+ (state as Record<string, unknown>)[stateKey] == marker;++const browserBackStateWithoutMarker = (state: unknown, stateKey: string) => {+ if (!state || typeof state != "object") return state;++ const next: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(+ state as Record<string, unknown>,+ )) {+ if (key != stateKey) next[key] = value;+ }+ return next;+};++interface UseBrowserBackCloseOptions {+ open: boolean;+ onClose: () => void;+ stateKey: string;+ enabled?: boolean;+}++export const useBrowserBackClose = ({+ open,+ onClose,+ stateKey,+ enabled = true,+}: UseBrowserBackCloseOptions) => {+ const markerRef = useRef<string | undefined>(undefined);+ const onCloseRef = useRef(onClose);+ onCloseRef.current = onClose;++ const clearBrowserBackState = useCallback(+ (action: BrowserBackCleanupAction = "replace") => {+ if (typeof window == "undefined") return Promise.resolve();++ const marker = markerRef.current;+ if (!marker) return Promise.resolve();++ markerRef.current = undefined;++ const latestHistoryState: unknown = window.history.state;+ if (+ !browserBackStateHasMarker(latestHistoryState, stateKey, marker)+ ) {+ return Promise.resolve();+ }++ if (action == "back") {+ const popStatePromise = waitForNextPopState();+ window.history.back();+ return popStatePromise;+ }++ window.history.replaceState(+ browserBackStateWithoutMarker(latestHistoryState, stateKey),+ "",+ window.location.href,+ );+ return Promise.resolve();+ },+ [stateKey],+ );++ useEffect(() => {+ if (!open || !enabled || typeof window == "undefined") return;++ const marker = `${Date.now()}-${Math.random().toString(36).slice(2)}`;+ markerRef.current = marker;++ window.history.pushState(+ browserBackStateWithMarker(window.history.state, stateKey, marker),+ "",+ window.location.href,+ );++ const handlePopState = (event: PopStateEvent) => {+ if (markerRef.current != marker) return;+ if (browserBackStateHasMarker(event.state, stateKey, marker)) {+ return;+ }++ markerRef.current = undefined;+ onCloseRef.current();+ };++ window.addEventListener("popstate", handlePopState);++ return () => {+ window.removeEventListener("popstate", handlePopState);+ if (markerRef.current != marker) return;+ void clearBrowserBackState("back");+ };+ }, [clearBrowserBackState, enabled, open, stateKey]);++ return { clearBrowserBackState };+};diff --git a/web/apps/space/src/pages/app/messages.tsx b/web/apps/space/src/pages/app/messages.tsxindex a195f50c03..d93edff56b 100644--- a/web/apps/space/src/pages/app/messages.tsx+++ b/web/apps/space/src/pages/app/messages.tsx@@ -1,5 +1,6 @@import { SpacePageMeta } from "components/SpacePageMeta";import { SpaceRouteFallback } from "components/SpaceRouteFallback";+import { useBrowserBackClose } from "hooks/useBrowserBackClose";import { useRouter } from "next/router";import React from "react";import { MessagesScreen, messagesBackground } from "screens/MessagesScreen";@@ -139,6 +140,11 @@ const Page: React.FC = () => {setIsThreadLoading(false);setMessages([]);}, []);+ const { clearBrowserBackState: clearThreadHistory } = useBrowserBackClose({+ open: Boolean(selectedFriend),+ onClose: closeConversation,+ stateKey: "space-message-thread",+ });const appendMessageIfThreadIsCurrent = React.useCallback((spaceId: string, message: SpaceMessage) => {@@ -225,9 +231,12 @@ const Page: React.FC = () => {onBack={() => void router.push(spaceRoutes.home)}onCloseThread={closeConversation}onOpenSelectedFriendProfile={(friend) =>- void router.push(- spaceRoutes.friend(friend.spaceId ?? friend.id),- )+ void clearThreadHistory("back").finally(() => {+ closeConversation();+ void router.push(+ spaceRoutes.friend(friend.spaceId ?? friend.id),+ );+ })}onOpenThread={openConversation}onSendMessage={async (spaceId, text) => {diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsxindex a7a3459e90..90e7802a6f 100644--- a/web/apps/space/src/screens/HomeScreen.tsx+++ b/web/apps/space/src/screens/HomeScreen.tsx@@ -15,6 +15,7 @@ import {type SpaceViewerPostActionMode,} from "components/SpaceFileViewer";import { EnteLogo } from "ente-base/components/EnteLogo";+import { useBrowserBackClose } from "hooks/useBrowserBackClose";import React, { useState } from "react";import type { SetupProfile } from "screens/SetupProfileScreen";import { ShareIcon } from "screens/ShareProfileLinkScreen";@@ -992,6 +993,12 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({setSelectedViewer(null);revokeLocalPostObjectUrls();};+ const { clearBrowserBackState: clearSelectedPhotoHistory } =+ useBrowserBackClose({+ open: Boolean(selectedViewer),+ onClose: closeSelectedPhoto,+ stateKey: "space-feed-viewer",+ });const deleteSelectedPost = async () => {const postId = selectedViewer?.photo.postId;if (!postId || !onDeletePost) return;@@ -1630,16 +1637,25 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({onOpenProfile={selectedPhotoIsOwn && onOpenProfile? () => {- closeSelectedPhoto();- onOpenProfile();+ void clearSelectedPhotoHistory(+ "back",+ ).finally(() => {+ closeSelectedPhoto();+ onOpenProfile();+ });}: selectedPhotoFriendID && onOpenFriend? () => {- closeSelectedPhoto();- onOpenFriend(selectedPhotoFriendID);+ void clearSelectedPhotoHistory(+ "back",+ ).finally(() => {+ closeSelectedPhoto();+ onOpenFriend(selectedPhotoFriendID);+ });}: undefined}+ onSwipeLeft={closeSelectedPhoto}onReplyToPost={!selectedPhotoIsOwn &&selectedViewer.photo.friendID != profile.spaceIddiff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsxindex d6301d2056..c198ed97b1 100644--- a/web/apps/space/src/screens/ProfileScreen.tsx+++ b/web/apps/space/src/screens/ProfileScreen.tsx@@ -13,6 +13,7 @@ import {} from "components/SpaceFileViewer";import { SpaceLoadingSpinner } from "components/SpaceRouteFallback";import { EnteLogo } from "ente-base/components/EnteLogo";+import { useBrowserBackClose } from "hooks/useBrowserBackClose";import React, { useState } from "react";import type { SetupProfile } from "screens/SetupProfileScreen";import { ShareIcon } from "screens/ShareProfileLinkScreen";@@ -82,6 +83,7 @@ interface SelectedProfilePost {isDraftImagePreviewPending?: boolean;localObjectUrl?: string;photo: SpaceViewerPhoto;+ postIndex?: number;postActionMode?: SpaceViewerPostActionMode;}@@ -356,6 +358,10 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({items: group.items.filter((item) => !deletedPostIDs.has(item.id)),})).filter((group) => group.items.length > 0);+ const visiblePostItems = visiblePostGroups.flatMap((group) => group.items);+ const visiblePostIndexByID = new Map(+ visiblePostItems.map((item, index) => [item.id, index]),+ );const postsSharedCount = visiblePostGroups.reduce((count, group) => count + group.items.length,0,@@ -393,6 +399,12 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({setSelectedPost(null);revokeLocalPostObjectUrls();};+ const { clearBrowserBackState: clearSelectedPostHistory } =+ useBrowserBackClose({+ open: Boolean(selectedPost),+ onClose: closeSelectedPost,+ stateKey: "space-profile-viewer",+ });const rememberLoadedPhotoDimensions = (itemID: string,image: HTMLImageElement,@@ -456,6 +468,129 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({[loadedPostImageURLFor, onLoadPostImage],);+ const dimensionsForPost = React.useCallback(+ (item: ProfilePostItem): ProfilePhotoDimensions =>+ loadedPhotoDimensionsByID[item.id] ?? {+ height: item.height ?? 1,+ width: item.width ?? 1,+ },+ [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,+ timestampMs: item.timestampMs,+ viewerLiked: item.viewerLiked,+ width: dimensions.width,+ },+ postIndex,+ };+ },+ [dimensionsForPost, displayName, profile.avatarUrl],+ );++ const profileViewerPhotos = React.useMemo(+ () =>+ visiblePostItems.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,+ timestampMs: item.timestampMs,+ viewerLiked: item.viewerLiked,+ width: dimensions.width,+ };+ }),+ [+ dimensionsForPost,+ displayName,+ loadedPostImageURLFor,+ profile.avatarUrl,+ selectedPost?.id,+ selectedPost?.photo.imageUrl,+ visiblePostItems,+ ],+ );++ const handleSelectedPostIndexChange = React.useCallback(+ (postIndex: number) => {+ const item = visiblePostItems[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,+ visiblePostItems,+ ],+ );++ React.useEffect(() => {+ const currentPostIndex = selectedPost?.postIndex;+ if (currentPostIndex == undefined) return;++ for (const offset of [-1, 1]) {+ const adjacentPost = visiblePostItems[currentPostIndex + offset];+ if (!adjacentPost || loadedPostImageURLFor(adjacentPost)) continue;++ void loadPostImage(adjacentPost);+ }+ }, [+ loadPostImage,+ loadedPostImageURLFor,+ selectedPost?.postIndex,+ visiblePostItems,+ ]);+const prepareSelectedPostPhoto = async (file: File) => {const canShowLocalPreview = canPreviewSpaceImageFile(file);if (!canShowLocalPreview) {@@ -1223,29 +1358,14 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({openedImageUrl,) =>setSelectedPost(- {- id: item.id,- photo: {- alt: `${displayName} post ${- index +- 1- }`,- avatarUrl:- profile.avatarUrl,- caption:- item.caption,- height: dimensions.height,- imageUrl:- openedImageUrl,- name: displayName,- postId: item.postId,- timestampMs:- item.timestampMs,- viewerLiked:- item.viewerLiked,- width: dimensions.width,- },- },+ selectedPostForItem(+ item,+ visiblePostIndexByID.get(+ item.id,+ ) ??+ index,+ openedImageUrl,+ ),)}onRememberDimensions={@@ -1376,6 +1496,17 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({selectedPost.postActionMode ??selectedPostActionMode}+ photos={+ selectedPost.postIndex == undefined+ ? undefined+ : profileViewerPhotos+ }+ photoIndex={selectedPost.postIndex}+ onPhotoIndexChange={+ selectedPost.postIndex == undefined+ ? undefined+ : handleSelectedPostIndexChange+ }onClose={closeSelectedPost}onDeletePost={isOwnerProfile ? deleteSelectedPost : undefined@@ -1403,7 +1534,15 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({}: undefined}- onDraftPostPublished={onDraftPostPublished}+ onDraftPostPublished={+ onDraftPostPublished+ ? () => {+ void clearSelectedPostHistory(+ "back",+ ).finally(onDraftPostPublished);+ }+ : undefined+ }onSetPostLiked={onSetPostLiked}/>)}