π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Refine Space invites and back navigation
Anand Baburajan06f4e29a9816
diff --git a/web/apps/space/src/components/AddFriendDialog.tsx b/web/apps/space/src/components/AddFriendDialog.tsxindex b9d04df47a..ac4f877e5c 100644--- a/web/apps/space/src/components/AddFriendDialog.tsx+++ b/web/apps/space/src/components/AddFriendDialog.tsx@@ -321,7 +321,7 @@ export const SpaceAddFriendDialog: React.FC<SpaceAddFriendDialogProps> = ({) : isSent ? (<SpaceActionFeedbackIcon phase="done" />) : (- "Send request"+ "Send friend request")}</Box>{profileLink && (diff --git a/web/apps/space/src/components/AuthenticatedFriendProfile.tsx b/web/apps/space/src/components/AuthenticatedFriendProfile.tsxindex f01ddc0f6d..34c74bad43 100644--- a/web/apps/space/src/components/AuthenticatedFriendProfile.tsx+++ b/web/apps/space/src/components/AuthenticatedFriendProfile.tsx@@ -23,7 +23,7 @@ import { useSpaceAppState } from "state/app-state";import { spaceAppBackgroundColor } from "styles/colors";import { profilePostItemsFromPosts } from "utils/post-display";import { spaceDefaultCoverImagePath } from "utils/post-image";-import { hasPreviousSpaceRoute, useSpaceRouter } from "utils/route-transitions";+import { useSpaceRouter } from "utils/route-transitions";import { spaceRoutes } from "utils/routes";interface AuthenticatedFriendProfileProps {@@ -124,11 +124,7 @@ export const AuthenticatedFriendProfile: React.FC<}, [friendSpaceId, profile?.spaceId]);const goBack = () => {- if (hasPreviousSpaceRoute()) {- router.back();- } else {- void router.push(spaceRoutes.home);- }+ void router.back(spaceRoutes.home);};const unfriend = React.useCallback(async () => {diff --git a/web/apps/space/src/components/MessagesPage.tsx b/web/apps/space/src/components/MessagesPage.tsxindex 1a5cc48b0c..515c126c79 100644--- a/web/apps/space/src/components/MessagesPage.tsx+++ b/web/apps/space/src/components/MessagesPage.tsx@@ -350,7 +350,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({);const closeConversation = React.useCallback(() => {- if (selectedSpaceId) void router.push(spaceRoutes.messages);+ if (selectedSpaceId) void router.back(spaceRoutes.messages);}, [router, selectedSpaceId]);const appendMessageIfThreadIsCurrent = React.useCallback(@@ -602,6 +602,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({isThreadReadOnly={isThreadReadOnly}isThreadRecipientLoading={isThreadRecipientLoading}messages={messages}+ onBack={() => void router.back(spaceRoutes.home)}onCloseThread={closeConversation}onOpenSelectedFriendProfile={(friend) => {const username = friend.username || friend.spaceSlug;diff --git a/web/apps/space/src/components/ProfileImagePages.tsx b/web/apps/space/src/components/ProfileImagePages.tsxindex 6c4027544d..24dc03509a 100644--- a/web/apps/space/src/components/ProfileImagePages.tsx+++ b/web/apps/space/src/components/ProfileImagePages.tsx@@ -106,7 +106,7 @@ export const SpaceProfileImageViewerPage: React.FC<{{ cause: error },);}- void router.push(backRoute).catch((error: unknown) => {+ void router.backTo(backRoute).catch((error: unknown) => {log.error("Failed to return to Space profile", error);});};@@ -126,7 +126,7 @@ export const SpaceProfileImageViewerPage: React.FC<{<ProfileImageViewerScreenprofile={profile}variant={variant}- onBack={() => void router.push(backRoute)}+ onBack={() => void router.back(backRoute)}onRemoveImage={(variant == "cover"@@ -208,7 +208,7 @@ export const SpaceProfileImageEditPage: React.FC<{: { ...profile, avatarFile: file },);setProfile(savedProfile);- await router.push(savedRoute);+ await router.backTo(savedRoute);clearPendingFile();} catch (error) {log.error(@@ -221,9 +221,9 @@ export const SpaceProfileImageEditPage: React.FC<{}};- const handleBack = () => {+ const handleBack = async () => {+ await router.back(profileImageRoute);clearPendingFile();- void router.push(profileImageRoute);};return (diff --git a/web/apps/space/src/components/RouteFallback.tsx b/web/apps/space/src/components/RouteFallback.tsxindex 75fc1679ad..8baf87b9d3 100644--- a/web/apps/space/src/components/RouteFallback.tsx+++ b/web/apps/space/src/components/RouteFallback.tsx@@ -74,7 +74,17 @@ export const SpaceRouteFallback: React.FC<SpaceRouteFallbackProps> = ({</Box></Box>) : (- <SpaceLoadingSpinner />+ <Box+ sx={{+ display: "grid",+ inset: 0,+ placeItems: "center",+ pointerEvents: "none",+ position: "fixed",+ }}+ >+ <SpaceLoadingSpinner />+ </Box>)}</Box></>diff --git a/web/apps/space/src/pages/add-profile-photo.tsx b/web/apps/space/src/pages/add-profile-photo.tsxindex 453a2610ac..caa75df1fc 100644--- a/web/apps/space/src/pages/add-profile-photo.tsx+++ b/web/apps/space/src/pages/add-profile-photo.tsx@@ -62,7 +62,7 @@ const Page: React.FC = () => {errorMessage={setupError}isSubmitting={isSubmitting}onBack={() =>- void router.push(+ void router.back(spaceRoutes.createProfile(createProfileSource),)}diff --git a/web/apps/space/src/pages/app/friends/index.tsx b/web/apps/space/src/pages/app/friends/index.tsxindex 10b61a87f7..f9df09d8a6 100644--- a/web/apps/space/src/pages/app/friends/index.tsx+++ b/web/apps/space/src/pages/app/friends/index.tsx@@ -90,6 +90,7 @@ const Page: React.FC = () => {friendRequests={friendRequests}friends={friends}isLoading={isFriendsLoading}+ onBack={() => void router.back(spaceRoutes.home)}onLoadFriendAvatar={loadCurrentFriendAvatarURL}onAddFriend={async (username) => {const actorSpaceId = profile.spaceId;diff --git a/web/apps/space/src/pages/app/notifications.tsx b/web/apps/space/src/pages/app/notifications.tsxindex 715d9de6b7..7495c3bea6 100644--- a/web/apps/space/src/pages/app/notifications.tsx+++ b/web/apps/space/src/pages/app/notifications.tsx@@ -1039,8 +1039,8 @@ const Page: React.FC = () => {<Boxcomponent="button"type="button"- aria-label="Back to home"- onClick={() => void router.push(spaceRoutes.home)}+ aria-label="Back"+ onClick={() => void router.back(spaceRoutes.home)}sx={{display: "flex",alignItems: "center",diff --git a/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx b/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsxindex c5db3d7874..ecc3cfb87e 100644--- a/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx+++ b/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx@@ -13,7 +13,7 @@ import {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 { useSpaceRouter } from "utils/route-transitions";import { postPhotoIdFromObjectKey, spaceRoutes } from "utils/routes";const postBackground = "#000000";@@ -141,11 +141,7 @@ const Page: React.FC = () => {}, [post?.spaceId, post?.username, profile?.spaceId, router, spaceId]);const closePost = React.useCallback(() => {- if (hasPreviousSpaceRoute()) {- router.back();- return;- }- void router.replace(spaceRoutes.home);+ void router.back(spaceRoutes.home);}, [router]);if (diff --git a/web/apps/space/src/pages/app/profile.tsx b/web/apps/space/src/pages/app/profile.tsxindex 8c64eb00c7..2aee41e0f4 100644--- a/web/apps/space/src/pages/app/profile.tsx+++ b/web/apps/space/src/pages/app/profile.tsx@@ -127,7 +127,7 @@ const Page: React.FC = () => {postItems={postItems}profile={profile}showPostLoadingIndicator={showInitialPostLoadingIndicator}- onBack={() => void router.push(spaceRoutes.home)}+ onBack={() => void router.back(spaceRoutes.home)}onPostPhotoSelect={setPendingPostPhotoFiles}onDeletePost={async (postId) => {const spaceId = profile.spaceId;diff --git a/web/apps/space/src/pages/app/settings.tsx b/web/apps/space/src/pages/app/settings.tsxindex d7bb2c981b..b9a89367dc 100644--- a/web/apps/space/src/pages/app/settings.tsx+++ b/web/apps/space/src/pages/app/settings.tsx@@ -32,7 +32,7 @@ const Page: React.FC = () => {<><SpacePageMeta themeColor={spaceAppBackgroundColor} /><SettingsScreen- onBack={() => void router.push(spaceRoutes.home)}+ onBack={() => void router.back(spaceRoutes.home)}onChangeCoverImage={() =>void router.push(spaceRoutes.profileCoverFrom("settings"))}diff --git a/web/apps/space/src/pages/app/settings/profile/name.tsx b/web/apps/space/src/pages/app/settings/profile/name.tsxindex dffe6a0ff5..2f745e46c6 100644--- a/web/apps/space/src/pages/app/settings/profile/name.tsx+++ b/web/apps/space/src/pages/app/settings/profile/name.tsx@@ -38,14 +38,14 @@ const Page: React.FC = () => {errorMessage={errorMessage}initialName={profile.fullName}isSaving={isSaving}- onBack={() => void router.push(spaceRoutes.settings)}+ onBack={() => void router.back(spaceRoutes.settings)}onSave={(fullName) => {setErrorMessage(undefined);setIsSaving(true);void saveSpaceProfile({ ...profile, fullName }).then((savedProfile) => {setProfile(savedProfile);- void router.push(spaceRoutes.settings);+ void router.backTo(spaceRoutes.settings);}).catch((error: unknown) => {log.error("Space name update failed", error);diff --git a/web/apps/space/src/pages/create-profile.tsx b/web/apps/space/src/pages/create-profile.tsxindex e147288fe7..2552dd4b07 100644--- a/web/apps/space/src/pages/create-profile.tsx+++ b/web/apps/space/src/pages/create-profile.tsx@@ -108,7 +108,7 @@ const Page: React.FC = () => {<SetupProfileScreeninitialProfile={pendingCreateProfile}onBack={() =>- void router.push(+ void router.back(backSource == "login"? spaceRoutes.login: spaceRoutes.verify,diff --git a/web/apps/space/src/pages/index.tsx b/web/apps/space/src/pages/index.tsxindex 0c5153c692..26275b2940 100644--- a/web/apps/space/src/pages/index.tsx+++ b/web/apps/space/src/pages/index.tsx@@ -8,6 +8,7 @@ import { SpacePublicProfileNotificationControl } from "components/PublicProfileNimport { SpaceRouteFallback } from "components/RouteFallback";import log from "ente-base/log";import React, { useEffect, useMemo, useState } from "react";+import { FriendRequestScreen } from "screens/FriendRequestScreen";import { OnboardingScreen, onboardingGreen } from "screens/OnboardingScreen";import { ProfileScreen } from "screens/ProfileScreen";import {@@ -26,6 +27,7 @@ import {type SpaceInviteRoute,} from "services/invite";import {+ clearSpaceFriendsCache,loadCurrentSpaceRelationship,loadPublicSpaceIdentity,openPublicSpaceLink,@@ -602,8 +604,11 @@ export const Page: React.FC<PageProps> = ({ invitePreview }) => {<><SpacePageMetathemeColor={- publicLink ? spaceAppBackgroundColor : "#FFFFFF"+ publicLink || profile+ ? spaceAppBackgroundColor+ : "#FFFFFF"}+ title={profile && !publicLink ? "Add friend" : undefined}preview="invite"/>{publicLink ? (@@ -620,7 +625,13 @@ export const Page: React.FC<PageProps> = ({ invitePreview }) => {onAddFriendForPostAction={(intent) =>void addFriend(intent)}- onBack={() => window.location.assign("/")}+ onBack={() =>+ void router.back(+ profile+ ? spaceRoutes.home+ : spaceRoutes.onboarding,+ )+ }onCreateSpace={createSpace}onLoadPostImage={publicLink.loadPostImage}postItems={publicPostItems}@@ -637,6 +648,25 @@ export const Page: React.FC<PageProps> = ({ invitePreview }) => {/>{!profile && <SpaceMobileBestToast />}</>+ ) : profile ? (+ <FriendRequestScreen+ key={publicIdentity.spaceId}+ username={publicIdentity.username}+ onBack={() => void router.back(spaceRoutes.friends)}+ onAddFriend={async () => {+ const status = await requestFriendByUsername({+ spaceUsername: publicIdentity.username,+ });+ clearPendingSpaceInvite();+ clearPendingSpaceInviteFriend();+ clearPendingSpaceInviteIntent();+ if (status == "friend") {+ clearSpaceFriendsCache();+ setAuthenticatedProfileRoute("friend");+ }+ return status;+ }}+ />) : (<PublicFriendRequestScreenidentity={publicIdentity}diff --git a/web/apps/space/src/pages/login.tsx b/web/apps/space/src/pages/login.tsxindex 7459c1d83e..7c29693d00 100644--- a/web/apps/space/src/pages/login.tsx+++ b/web/apps/space/src/pages/login.tsx@@ -63,7 +63,7 @@ const Page: React.FC = () => {<LoginScreenerrorMessage={loginError}isSubmitting={isSubmitting}- onBack={() => void router.push(spaceRoutes.onboarding)}+ onBack={() => void router.back(spaceRoutes.onboarding)}onContinue={async (credentials) => {setIsSubmitting(true);setLoginError(undefined);diff --git a/web/apps/space/src/pages/passkeys/verify.tsx b/web/apps/space/src/pages/passkeys/verify.tsxindex 964ddac0da..8e34c05610 100644--- a/web/apps/space/src/pages/passkeys/verify.tsx+++ b/web/apps/space/src/pages/passkeys/verify.tsx@@ -119,7 +119,7 @@ const Page: React.FC = () => {<PasskeyVerificationScreencanUseTwoFactor={verification.hasTwoFactorFallback}errorMessage={errorMessage}- onBack={() => void router.push(spaceRoutes.login)}+ onBack={() => void router.back(spaceRoutes.login)}onCheckStatus={() => void checkStatus()}onTryAgain={tryAgain}onUseTwoFactor={useTwoFactor}diff --git a/web/apps/space/src/pages/signup.tsx b/web/apps/space/src/pages/signup.tsxindex df4885fe6b..8ac41988c0 100644--- a/web/apps/space/src/pages/signup.tsx+++ b/web/apps/space/src/pages/signup.tsx@@ -36,7 +36,7 @@ const Page: React.FC = () => {<CreateAccountScreenerrorMessage={signupError}isSubmitting={isSubmitting}- onBack={() => void router.push(spaceRoutes.onboarding)}+ onBack={() => void router.back(spaceRoutes.onboarding)}onCreateAccount={(input) => void createAccount(input)}/></>diff --git a/web/apps/space/src/pages/two-factor/verify.tsx b/web/apps/space/src/pages/two-factor/verify.tsxindex d3227dab43..b1d1084c5a 100644--- a/web/apps/space/src/pages/two-factor/verify.tsx+++ b/web/apps/space/src/pages/two-factor/verify.tsx@@ -78,7 +78,7 @@ const Page: React.FC = () => {codeResetKey={codeResetKey}errorMessage={errorMessage}isSubmitting={isSubmitting}- onBack={() => void router.push(spaceRoutes.login)}+ onBack={() => void router.back(spaceRoutes.login)}onVerify={(code) => void verifySecondFactor(code)}/></>diff --git a/web/apps/space/src/pages/verify.tsx b/web/apps/space/src/pages/verify.tsxindex 8bef10b35b..ccd57289c4 100644--- a/web/apps/space/src/pages/verify.tsx+++ b/web/apps/space/src/pages/verify.tsx@@ -221,14 +221,14 @@ const Page: React.FC = () => {isResending={isResending}isSubmitting={isSubmitting}onBack={() =>- void router.push(+ void router.back(isLoginVerification? spaceRoutes.login: spaceRoutes.signup,)}onChangeEmail={() =>- void router.push(+ void router.back(isLoginVerification? spaceRoutes.login: spaceRoutes.signup,diff --git a/web/apps/space/src/screens/EditProfilePhotoScreen.tsx b/web/apps/space/src/screens/EditProfilePhotoScreen.tsxindex 2f6608a3b3..bc061bf91e 100644--- a/web/apps/space/src/screens/EditProfilePhotoScreen.tsx+++ b/web/apps/space/src/screens/EditProfilePhotoScreen.tsx@@ -82,7 +82,7 @@ const EditProfilePhotoShell: React.FC<<Boxcomponent="button"type="button"- aria-label="Back to profile"+ aria-label="Back"onClick={onBack}sx={{alignItems: "center",diff --git a/web/apps/space/src/screens/FriendRequestScreen.tsx b/web/apps/space/src/screens/FriendRequestScreen.tsxnew file mode 100644index 0000000000..f6562fa206--- /dev/null+++ b/web/apps/space/src/screens/FriendRequestScreen.tsx@@ -0,0 +1,178 @@+import { ArrowLeft02Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { Box } from "@mui/material";+import log from "ente-base/log";+import React from "react";+import { spaceEmptyStateButtonSx } from "styles/buttons";+import {+ spaceAppBackgroundColor,+ spaceControlBackground,+ spaceText,+ spaceTextMuted,+} from "styles/colors";++interface FriendRequestScreenProps {+ username: string;+ onBack: () => void;+ onAddFriend: () => Promise<"friend" | "requested">;+}++export const FriendRequestScreen: React.FC<FriendRequestScreenProps> = ({+ username,+ onBack,+ onAddFriend,+}) => {+ const [phase, setPhase] = React.useState<"sending" | "sent">();+ const [failed, setFailed] = React.useState(false);++ const addFriend = async () => {+ setPhase("sending");+ setFailed(false);+ try {+ if ((await onAddFriend()) == "requested") setPhase("sent");+ } catch (error) {+ log.error("Failed to send friend request", error);+ setFailed(true);+ setPhase(undefined);+ }+ };++ return (+ <Box+ sx={{+ bgcolor: spaceAppBackgroundColor,+ color: spaceText,+ minHeight: "var(--space-page-height, 100svh)",+ pt: "env(safe-area-inset-top)",+ }}+ >+ <Box+ sx={{+ display: "flex",+ flexDirection: "column",+ minHeight:+ "calc(var(--space-page-height, 100svh) - env(safe-area-inset-top))",+ mx: "auto",+ width: "100%",+ "@media (min-width: 600px)": { maxWidth: 390 },+ }}+ >+ <Box+ component="header"+ sx={{+ alignItems: "center",+ display: "grid",+ flexShrink: 0,+ gridTemplateColumns: "44px 1fr 44px",+ height: 56,+ px: 2,+ }}+ >+ <Box+ component="button"+ type="button"+ aria-label="Back"+ onClick={onBack}+ sx={{+ alignItems: "center",+ bgcolor: "transparent",+ border: 0,+ borderRadius: "50%",+ color: spaceText,+ cursor: "pointer",+ display: "flex",+ height: 44,+ justifyContent: "flex-start",+ ml: "-2px",+ p: 0,+ width: 44,+ "&:focus-visible": { outline: "2px solid #08C225" },+ }}+ >+ <HugeiconsIcon+ icon={ArrowLeft02Icon}+ size={24}+ strokeWidth={1.8}+ />+ </Box>+ <Box+ component="h1"+ sx={{+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 18,+ fontWeight: 700,+ justifySelf: "center",+ lineHeight: "24px",+ m: 0,+ }}+ >+ Add friend+ </Box>+ </Box>+ <Box+ component="main"+ sx={{+ alignItems: "center",+ display: "flex",+ flex: 1,+ flexDirection: "column",+ justifyContent: "center",+ px: 3,+ py: 4,+ textAlign: "center",+ }}+ >+ <Box+ component="h2"+ sx={{+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 24,+ fontWeight: 700,+ lineHeight: "32px",+ m: 0,+ maxWidth: "100%",+ overflowWrap: "anywhere",+ }}+ >+ @{username}+ </Box>+ <Box aria-live="polite" sx={{ mt: "24px" }}>+ <Box+ component="button"+ type="button"+ disabled={Boolean(phase)}+ aria-busy={phase == "sending"}+ onClick={() => void addFriend()}+ sx={{+ ...spaceEmptyStateButtonSx,+ minWidth: 144,+ ...(phase == "sent" && {+ bgcolor: spaceControlBackground,+ color: spaceTextMuted,+ "&:disabled": { opacity: 1 },+ }),+ }}+ >+ {phase == "sent"+ ? "Request sent"+ : "Send friend request"}+ </Box>+ </Box>+ {failed && (+ <Box+ role="alert"+ sx={{+ color: spaceTextMuted,+ fontSize: 14,+ lineHeight: "20px",+ mt: "16px",+ }}+ >+ Couldn't send your request. Try again.+ </Box>+ )}+ </Box>+ </Box>+ </Box>+ );+};diff --git a/web/apps/space/src/screens/FriendsScreen.tsx b/web/apps/space/src/screens/FriendsScreen.tsxindex 08970ecc8f..b366a12cbc 100644--- a/web/apps/space/src/screens/FriendsScreen.tsx+++ b/web/apps/space/src/screens/FriendsScreen.tsx@@ -1,4 +1,5 @@import {+ ArrowLeft02Icon,BubbleChatIcon,Cancel01Icon,HandPointingRightIcon,@@ -56,6 +57,7 @@ interface FriendsScreenProps {friendRequests: SpaceFriendRequest[];friends: FriendProfile[];isLoading: boolean;+ onBack: () => void;onAcceptFriendRequest: (requestID: number) => Promise<void>;onDeleteFriendRequest: (requestID: number) => Promise<void>;onLoadFriendAvatar?: (friend: FriendProfile) => Promise<string | null>;@@ -711,6 +713,7 @@ export const FriendsScreen: React.FC<FriendsScreenProps> = ({isLoading,onAcceptFriendRequest,onAddFriend,+ onBack,onDeleteFriendRequest,onLoadFriendAvatar,onMessage,@@ -862,7 +865,36 @@ export const FriendsScreen: React.FC<FriendsScreenProps> = ({width: "100%",}}>- <Box aria-hidden />+ <Box+ component="button"+ type="button"+ aria-label="Back"+ onClick={onBack}+ sx={{+ alignItems: "center",+ bgcolor: "transparent",+ border: 0,+ color: textBase,+ cursor: "pointer",+ display: "flex",+ height: spaceTouchTargetSize,+ justifyContent: "flex-start",+ ml: "-2px",+ p: 0,+ width: spaceTouchTargetSize,+ "&:focus-visible": {+ borderRadius: "50%",+ outline: `2px solid ${green}`,+ outlineOffset: 2,+ },+ }}+ >+ <HugeiconsIcon+ icon={ArrowLeft02Icon}+ size={24}+ strokeWidth={1.8}+ />+ </Box><Boxcomponent="h1"sx={{diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsxindex 1524c44d13..acc9be20c7 100644--- a/web/apps/space/src/screens/MessagesScreen.tsx+++ b/web/apps/space/src/screens/MessagesScreen.tsx@@ -107,6 +107,7 @@ interface MessagesScreenProps {isThreadReadOnly?: boolean;isThreadRecipientLoading?: boolean;messages: SpaceMessage[];+ onBack: () => void;onCloseThread: () => void;onDeleteMessage: (messageId: string) => Promise<void>;onOpenSelectedFriendProfile: (@@ -130,7 +131,6 @@ interface MessagesScreenProps {profileLink?: string;profile: SetupProfile;selectedFriend?: SpaceMessageConversation["friend"];- threadBackLabel?: string;}interface MessageContextMenuState {@@ -1547,6 +1547,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({isThreadReadOnly = false,isThreadRecipientLoading = false,messages,+ onBack,onCloseThread,onDeleteMessage,onOpenSelectedFriendProfile,@@ -1559,7 +1560,6 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({profile,profileLink,selectedFriend,- threadBackLabel = "Back to messages",}) => {const [messageText, setMessageText] = React.useState("");const [messageContextMenu, setMessageContextMenu] =@@ -2129,20 +2129,16 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({}}><Box- component={isThreadOpen ? "button" : "span"}- type={isThreadOpen ? "button" : undefined}- aria-hidden={!isThreadOpen || undefined}- aria-label={- isThreadOpen ? threadBackLabel : undefined- }- onClick={isThreadOpen ? onCloseThread : undefined}+ component="button"+ type="button"+ aria-label="Back"+ onClick={isThreadOpen ? onCloseThread : onBack}sx={{alignItems: "center",bgcolor: "transparent",border: 0,color: conversationPrimaryText,- cursor: isThreadOpen ? "pointer" : undefined,- visibility: isThreadOpen ? "visible" : "hidden",+ cursor: "pointer",display: "flex",height: spaceTouchTargetSize,justifyContent: "flex-start",diff --git a/web/apps/space/src/screens/ProfileImageViewerScreen.tsx b/web/apps/space/src/screens/ProfileImageViewerScreen.tsxindex a944ff0caa..87ec797281 100644--- a/web/apps/space/src/screens/ProfileImageViewerScreen.tsx+++ b/web/apps/space/src/screens/ProfileImageViewerScreen.tsx@@ -251,7 +251,7 @@ export const ProfileImageViewerScreen: React.FC<<Boxcomponent="button"type="button"- aria-label="Back to profile"+ aria-label="Back"onClick={onBack}sx={{alignItems: "center",diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsxindex d6479c32d9..e247626ad3 100644--- a/web/apps/space/src/screens/ProfileScreen.tsx+++ b/web/apps/space/src/screens/ProfileScreen.tsx@@ -676,22 +676,16 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({) : (<><Box- component={isFriendProfile ? "button" : "span"}- type={isFriendProfile ? "button" : undefined}- aria-hidden={!isFriendProfile || undefined}- aria-label={- isFriendProfile ? "Back to friends" : undefined- }- onClick={isFriendProfile ? onBack : undefined}+ component="button"+ type="button"+ aria-label="Back"+ onClick={onBack}sx={{alignItems: "center",bgcolor: "transparent",border: 0,color: "inherit",- cursor: isFriendProfile ? "pointer" : undefined,- visibility: isFriendProfile- ? "visible"- : "hidden",+ cursor: "pointer",display: "flex",height: spaceTouchTargetSize,justifyContent: "flex-start",diff --git a/web/apps/space/src/screens/SettingsScreen.tsx b/web/apps/space/src/screens/SettingsScreen.tsxindex 3c15826d23..c250a8f146 100644--- a/web/apps/space/src/screens/SettingsScreen.tsx+++ b/web/apps/space/src/screens/SettingsScreen.tsx@@ -448,7 +448,7 @@ export const SettingsScreen: React.FC<SettingsScreenProps> = ({<Boxcomponent="button"type="button"- aria-label="Back to home"+ aria-label="Back"onClick={onBack}sx={{alignItems: "center",@@ -691,7 +691,7 @@ export const ChangeNameSettingsScreen: React.FC<<Boxcomponent="button"type="button"- aria-label="Back to profile settings"+ aria-label="Back"onClick={onBack}sx={{alignItems: "center",diff --git a/web/apps/space/src/utils/route-transitions.tsx b/web/apps/space/src/utils/route-transitions.tsxindex e514d4209f..cee7bad0d6 100644--- a/web/apps/space/src/utils/route-transitions.tsx+++ b/web/apps/space/src/utils/route-transitions.tsx@@ -1,113 +1,102 @@import log from "ente-base/log";import { useRouter, type NextRouter } from "next/router";import React from "react";+import { spaceBackFallback } from "utils/routes";-type SpaceRouteMotionDirection = "forward" | "back";type SpaceRouteURL = Parameters<NextRouter["push"]>[0];type SpaceRouteAs = Parameters<NextRouter["push"]>[1];type SpaceRouteOptions = Parameters<NextRouter["push"]>[2];+type SpaceRouter = Omit<NextRouter, "back"> & {+ back: (fallback?: string) => Promise<boolean>;+ backTo: (path: string) => Promise<boolean>;+};let routeMotionSequence = 0;-let routeStack: string[] = [];--const routePath = (route: SpaceRouteURL | SpaceRouteAs): string => {- if (!route) return "";-- if (typeof route == "string") {- const [routeWithoutHash = ""] = route.split("#", 1);- const [routeWithoutQuery = ""] = routeWithoutHash.split("?", 1);- const path = route.startsWith("http")- ? new URL(route).pathname- : routeWithoutQuery;- return path.length > 1 ? path.replace(/\/+$/, "") : path || "/";+let routeHistory: { key: string; as: string }[] = [];+let routeHistoryIndex = -1;+const routeHistoryStorageKey = "space-route-history";++const saveRouteHistory = () => {+ try {+ sessionStorage.setItem(+ routeHistoryStorageKey,+ JSON.stringify({ entries: routeHistory, index: routeHistoryIndex }),+ );+ } catch (error) {+ log.warn("Failed to save Space navigation history", error);}-- const pathname = route.pathname;- if (!pathname || typeof pathname != "string") return "";- return pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;};-const parentRoutePaths = (path: string) => {- if (/^\/app\/messages\/[^/]+$/.test(path)) return ["/app/messages"];- if (/^\/app\/posts\/[^/]+\/[^/]+$/.test(path)) {- return ["/app"];+const recordRoute = (action: "push" | "replace" | "pop") => {+ const { key, as } = window.history.state as { key: string; as: string };+ const index = routeHistory.findIndex((entry) => entry.key == key);+ if (index >= 0) {+ routeHistoryIndex = index;+ routeHistory[index] = { key, as };+ } else if (action == "push") {+ routeHistory = routeHistory.slice(0, routeHistoryIndex + 1);+ routeHistory.push({ key, as });+ routeHistoryIndex = routeHistory.length - 1;+ } else if (action == "replace" && routeHistoryIndex >= 0) {+ routeHistory[routeHistoryIndex] = { key, as };+ } else {+ routeHistory = [{ key, as }];+ routeHistoryIndex = 0;}-- return (- {- "/app/friends": ["/app/profile"],- "/app/messages": ["/app"],- "/app/notifications": ["/app"],- "/app/profile": ["/app"],- "/app/profile/cover": ["/app/profile"],- "/app/profile/cover-edit": ["/app/profile/cover"],- "/app/profile/photo": ["/app/profile"],- "/app/profile/photo-edit": ["/app/profile/photo"],- "/app/settings": ["/app"],- "/app/settings/profile/name": ["/app/settings"],- "/login": ["/"],- "/passkeys/finish": ["/passkeys/verify"],- "/passkeys/verify": ["/login", "/verify"],- "/create-profile": ["/login", "/verify"],- "/add-profile-photo": ["/create-profile"],- "/signup": ["/"],- "/two-factor/verify": ["/login", "/verify"],- "/verify": ["/login", "/signup"],- } satisfies Record<string, string[]>- )[path];-};--const previousStackRoute = () =>- routeStack.length > 1 ? routeStack[routeStack.length - 2] : undefined;--export const hasPreviousSpaceRoute = () => Boolean(previousStackRoute());--const ensureRouteStack = (currentPath: string) => {- if (routeStack.length == 0 && currentPath) routeStack = [currentPath];+ saveRouteHistory();};-const routeMotionDirection = (- currentPath: string,- targetPath: string,-): SpaceRouteMotionDirection => {- ensureRouteStack(currentPath);-- if (previousStackRoute() == targetPath) return "back";- if (parentRoutePaths(currentPath)?.includes(targetPath)) return "back";- return "forward";-};--const recordRoutePush = (- currentPath: string,- targetPath: string,- direction: SpaceRouteMotionDirection,-) => {- ensureRouteStack(currentPath);-- if (direction == "back") {- const targetIndex = routeStack.lastIndexOf(targetPath);- routeStack =- targetIndex >= 0- ? routeStack.slice(0, targetIndex + 1)- : [targetPath];- return;+const initializeRouteHistory = (router: NextRouter) => {+ if (routeHistoryIndex >= 0) return;+ const state = window.history.state as {+ key: string;+ url: string;+ as: string;+ options: object;+ __N: boolean;+ };+ const navigation = performance.getEntriesByType("navigation")[0] as+ | PerformanceNavigationTiming+ | undefined;+ if (navigation?.type == "reload") {+ try {+ const saved = JSON.parse(+ sessionStorage.getItem(routeHistoryStorageKey) ?? "null",+ ) as { entries: typeof routeHistory; index: number } | null;+ if (saved?.entries[saved.index]?.as == router.asPath) {+ routeHistory = saved.entries;+ routeHistoryIndex = saved.index;+ routeHistory[routeHistoryIndex] = {+ key: state.key,+ as: state.as,+ };+ saveRouteHistory();+ return;+ }+ } catch (error) {+ log.warn("Failed to restore Space navigation history", error);+ }}- if (routeStack[routeStack.length - 1] != currentPath) {- routeStack.push(currentPath);- }- if (routeStack[routeStack.length - 1] != targetPath) {- routeStack.push(targetPath);+ const parents: string[] = [];+ let parent = spaceBackFallback(router.asPath, router.pathname);+ while (parent) {+ parents.unshift(parent);+ parent = spaceBackFallback(parent);}-};--const recordRouteReplace = (targetPath: string) => {- if (!targetPath) return;- if (routeStack.length == 0) {- routeStack = [targetPath];- return;+ for (const [index, as] of parents.entries()) {+ const key = crypto.randomUUID();+ window.history[index == 0 ? "replaceState" : "pushState"](+ { ...state, key, url: as, as, options: {} },+ "",+ as,+ );+ routeHistory.push({ key, as });}- routeStack[routeStack.length - 1] = targetPath;+ if (parents.length > 0) window.history.pushState(state, "", state.as);+ routeHistory.push({ key: state.key, as: state.as });+ routeHistoryIndex = routeHistory.length - 1;+ saveRouteHistory();};const prefersReducedMotion = () =>@@ -155,17 +144,11 @@ const pushSpaceRoute = async (as?: SpaceRouteAs,options?: SpaceRouteOptions,) => {- const currentPath = routePath(router.asPath);- const targetPath = routePath(as ?? url);- if (!targetPath || targetPath == currentPath) {- return await router.push(url, as, options);- }-- const direction = routeMotionDirection(currentPath, targetPath);+ initializeRouteHistory(router);const didNavigate = await startSpaceRouteTransition(() =>router.push(url, as, options),);- if (didNavigate) recordRoutePush(currentPath, targetPath, direction);+ if (didNavigate) recordRoute("push");return didNavigate;};@@ -175,50 +158,43 @@ const replaceSpaceRoute = async (as?: SpaceRouteAs,options?: SpaceRouteOptions,) => {+ initializeRouteHistory(router);const didNavigate = await router.replace(url, as, options);- if (didNavigate) recordRouteReplace(routePath(as ?? url));+ if (didNavigate) recordRoute("replace");return didNavigate;};-const backSpaceRoute = (router: NextRouter) => {- const currentPath = routePath(router.asPath);- const targetPath = previousStackRoute();-- void startSpaceRouteTransition(() => {- const routeChangePromise = new Promise<boolean>((resolve, reject) => {- const cleanup = () => {- router.events.off("routeChangeComplete", handleComplete);- router.events.off("routeChangeError", handleError);- };- const handleComplete = () => {- cleanup();- resolve(true);- };- const handleError = (error: unknown) => {- cleanup();- reject(- error instanceof Error- ? error- : new Error("Space route change failed"),- );- };-- router.events.on("routeChangeComplete", handleComplete);- router.events.on("routeChangeError", handleError);- });+const backSpaceRoute = (+ router: NextRouter,+ fallback: string,+ index = routeHistoryIndex - 1,+) => {+ if (index < 0) return replaceSpaceRoute(router, fallback);+ return new Promise<boolean>((resolve, reject) => {+ const cleanup = () => {+ router.events.off("routeChangeComplete", handleComplete);+ router.events.off("routeChangeError", handleError);+ };+ const handleComplete = () => {+ cleanup();+ resolve(true);+ };+ const handleError = (error: unknown) => {+ cleanup();+ reject(+ error instanceof Error+ ? error+ : new Error("Space route change failed"),+ );+ };- router.back();- return routeChangePromise;- })- .then((didNavigate) => {- if (didNavigate && targetPath) {- recordRoutePush(currentPath, targetPath, "back");- }- })- .catch((error: unknown) => log.error("Failed to navigate back", error));+ router.events.on("routeChangeComplete", handleComplete);+ router.events.on("routeChangeError", handleError);+ window.history.go(index - routeHistoryIndex);+ });};-export const useSpaceRouter = (): NextRouter => {+export const useSpaceRouter = (): SpaceRouter => {const router = useRouter();return React.useMemo(@@ -240,7 +216,18 @@ export const useSpaceRouter = (): NextRouter => {) => replaceSpaceRoute(target, url, as, options);}if (property == "back") {- return () => backSpaceRoute(target);+ return (fallback = "/app") =>+ backSpaceRoute(target, fallback);+ }+ if (property == "backTo") {+ return (path: string) =>+ backSpaceRoute(+ target,+ path,+ routeHistory+ .slice(0, routeHistoryIndex)+ .findLastIndex((entry) => entry.as == path),+ );}const value = target[property as keyof NextRouter];@@ -248,7 +235,7 @@ export const useSpaceRouter = (): NextRouter => {? value.bind(target): value;},- }),+ }) as SpaceRouter,[router],);};@@ -261,22 +248,22 @@ export const useSpaceRouteTransitionPopState = () => {React.useEffect(() => {const scrollRestoration = window.history.scrollRestoration;window.history.scrollRestoration = "manual";- recordRouteReplace(routePath(router.asPath));+ initializeRouteHistory(router);router.beforePopState((state) => {- if (state.as == asPathRef.current) return false;-- const currentPath = routePath(asPathRef.current);- const targetPath = routePath(state.as);-- if (!targetPath || targetPath == currentPath) return true;+ if (+ state.as == asPathRef.current &&+ (window.history.state as { key: string }).key ==+ routeHistory[routeHistoryIndex]?.key+ )+ return false;void startSpaceRouteTransition(() =>router.replace(state.url, state.as, state.options),).then((didNavigate) => {if (didNavigate) {- recordRoutePush(currentPath, targetPath, "back");+ recordRoute("pop");}}).catch((error: unknown) =>diff --git a/web/apps/space/src/utils/routes.ts b/web/apps/space/src/utils/routes.tsindex 9f78406d15..930902b35a 100644--- a/web/apps/space/src/utils/routes.ts+++ b/web/apps/space/src/utils/routes.ts@@ -52,6 +52,37 @@ export const spaceRoutes = {verifyLogin: "/verify?flow=login",} as const;+export const spaceBackFallback = (asPath: string, page = asPath) => {+ const [path = "/", search = ""] = asPath.split("?", 2);+ if (page == spaceRoutes.friendPage) return spaceRoutes.home;+ if (path.startsWith("/app/messages/")) return spaceRoutes.messages;+ if (path.startsWith("/app/posts/")) return spaceRoutes.home;++ const source = profileImageFlowSourceFromQuery(+ new URLSearchParams(search).get("from") ?? undefined,+ );+ if (path == spaceRoutes.profilePhoto || path == spaceRoutes.profileCover)+ return source == "settings"+ ? spaceRoutes.settings+ : spaceRoutes.profile;+ if (path == spaceRoutes.editProfilePhoto)+ return spaceRoutes.profilePhotoFrom(source);+ if (path == spaceRoutes.editProfileCover)+ return spaceRoutes.profileCoverFrom(source);++ return (+ {+ [spaceRoutes.friends]: spaceRoutes.home,+ [spaceRoutes.messages]: spaceRoutes.home,+ [spaceRoutes.notifications]: spaceRoutes.home,+ [spaceRoutes.profile]: spaceRoutes.home,+ [spaceRoutes.settings]: spaceRoutes.home,+ [spaceRoutes.settingsProfileName]: spaceRoutes.settings,+ "/app/post": spaceRoutes.home,+ } as Record<string, string | undefined>+ )[path];+};+export const verifyFlowFromQuery = (value: string | string[] | undefined,): VerifyFlow => (valueFromQuery(value) == "login" ? "login" : "signup");diff --git a/web/apps/space/tests/route-transitions.test.tsx b/web/apps/space/tests/route-transitions.test.tsxnew file mode 100644index 0000000000..f91728b2c7--- /dev/null+++ b/web/apps/space/tests/route-transitions.test.tsx@@ -0,0 +1,215 @@+import type { NextRouter } from "next/router";+import type { EffectCallback } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ router: undefined as unknown as NextRouter,+ effects: [] as EffectCallback[],+}));++vi.mock("next/router", () => ({ useRouter: () => mocks.router }));+vi.mock("ente-base/log", () => ({+ default: { error: vi.fn(), warn: vi.fn() },+}));+vi.mock("react", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react")>();+ return {+ ...actual,+ default: {+ ...actual,+ useEffect: (effect: EffectCallback) => {+ mocks.effects.push(effect);+ },+ },+ };+});++beforeEach(() => {+ vi.resetModules();+ mocks.effects = [];+});++afterEach(() => vi.unstubAllGlobals());++const setup = async (initialPath: string) => {+ const { useSpaceRouter, useSpaceRouteTransitionPopState } =+ await import("../src/utils/route-transitions");+ interface Entry {+ key: string;+ url: string;+ as: string;+ options: object;+ }+ let entries: Entry[] = [+ { key: "0", url: initialPath, as: initialPath, options: {} },+ ];+ let position = 0;+ let nextKey = 0;+ let popState: (state: Entry) => boolean = () => true;+ const events = new Map<string, Set<(...args: unknown[]) => void>>();+ const emit = (name: string, ...args: unknown[]) =>+ events.get(name)?.forEach((handler) => handler(...args));+ let router: ReturnType<typeof useSpaceRouter>;+ const Harness = () => {+ router = useSpaceRouter();+ useSpaceRouteTransitionPopState();+ return null;+ };+ const render = () => {+ renderToStaticMarkup(<Harness />);+ mocks.effects.splice(0).forEach((effect) => effect());+ };+ const navigate = (url: string, as = url, replace = false) => {+ const entry = {+ key: replace ? entries[position]!.key : String(++nextKey),+ url,+ as,+ options: {},+ };+ if (replace) entries[position] = entry;+ else {+ entries = entries.slice(0, position + 1);+ entries.push(entry);+ position++;+ }+ mocks.router.asPath = as;+ render();+ emit("routeChangeComplete", as);+ return Promise.resolve(true);+ };+ const go = vi.fn((delta: number) => {+ position += delta;+ popState(entries[position]!);+ });+ vi.stubGlobal("window", {+ history: {+ get state() {+ return entries[position];+ },+ go,+ replaceState: (state: Entry) => {+ entries[position] = state;+ },+ pushState: (state: Entry) => {+ entries = entries.slice(0, position + 1);+ entries.push(state);+ position++;+ },+ scrollRestoration: "auto",+ },+ });+ mocks.router = {+ asPath: initialPath,+ pathname: initialPath.split("?")[0],+ push: vi.fn((url: string, as?: string) => navigate(url, as)),+ replace: vi.fn((url: string, as?: string) => navigate(url, as, true)),+ beforePopState: (callback: typeof popState) => {+ popState = callback;+ },+ events: {+ on: (name: string, handler: (...args: unknown[]) => void) => {+ if (!events.has(name)) events.set(name, new Set());+ events.get(name)!.add(handler);+ },+ off: (name: string, handler: (...args: unknown[]) => void) =>+ events.get(name)?.delete(handler),+ },+ } as unknown as NextRouter;+ render();+ return {+ get router() {+ return router;+ },+ get path() {+ return entries[position]!.as;+ },+ get length() {+ return entries.length;+ },+ go,+ };+};++describe("Space back navigation", () => {+ it.each(["/app/friends", "/app/messages", "/anand"])(+ "returns from a DM to its origin %s",+ async (origin) => {+ const app = await setup(origin);+ await app.router.push("/app/messages/anand");+ await app.router.back("/app/messages");+ expect(app.path).toBe(origin);+ },+ );++ it("retraces a notification, friend profile, and DM without losing history", async () => {+ const app = await setup("/app/notifications");+ await app.router.push("/profile-link", "/anand");+ await app.router.push("/app/messages/anand");+ await app.router.back("/app/messages");+ expect(app.path).toBe("/anand");+ await app.router.back("/app");+ expect(app.path).toBe("/app/notifications");+ });++ it("keeps repeated tab visits in their actual browser order", async () => {+ const app = await setup("/app");+ await app.router.push("/app/friends");+ await app.router.push("/app");+ await app.router.push("/app/profile");+ await app.router.back("/app");+ await app.router.back("/app");+ expect(app.path).toBe("/app/friends");+ });++ it("keeps query parameters when returning from profile editing", async () => {+ const app = await setup("/app/settings");+ await app.router.push("/app/profile/photo?from=settings");+ await app.router.push("/app/profile/photo-edit?from=settings");+ await app.router.back("/app/profile/photo");+ expect(app.path).toBe("/app/profile/photo?from=settings");+ await app.router.back("/app/profile");+ expect(app.path).toBe("/app/settings");+ });++ it("returns past a completed edit flow without adding a settings visit", async () => {+ const app = await setup("/app");+ await app.router.push("/app/settings");+ await app.router.push("/app/profile/photo?from=settings");+ await app.router.push("/app/profile/photo-edit?from=settings");+ await app.router.backTo("/app/settings");+ expect(app.go).toHaveBeenLastCalledWith(-2);+ expect(app.path).toBe("/app/settings");+ await app.router.back("/app");+ expect(app.path).toBe("/app");+ });++ it("uses replace for a direct link fallback, avoiding a back loop", async () => {+ const app = await setup("/login");+ await app.router.back("/app/messages");+ expect(app.path).toBe("/app/messages");+ expect(app.go).not.toHaveBeenCalled();+ expect(app.length).toBe(1);+ await app.router.back("/app");+ expect(app.path).toBe("/app");+ expect(app.length).toBe(1);+ });++ it("gives browser Back a parent chain on a freshly opened DM link", async () => {+ const app = await setup("/app/messages/anand");+ app.go(-1);+ await vi.waitFor(() => expect(app.path).toBe("/app/messages"));+ await app.router.back("/app");+ expect(app.path).toBe("/app");+ });++ it("follows browser Back and Forward before navigating back again", async () => {+ const app = await setup("/app/friends");+ await app.router.push("/app/messages/anand");+ await app.router.back("/app/messages");+ app.go(1);+ await vi.waitFor(() => expect(app.path).toBe("/app/messages/anand"));+ await app.router.back("/app/messages");+ expect(app.path).toBe("/app/friends");+ });+});