π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Refine Space posting feedback, previews, and home tiles
Anand Baburajan44f15eece250
diff --git a/web/apps/space/src/components/AddFriendTile.tsx b/web/apps/space/src/components/AddFriendTile.tsxindex 3e817ae014..186c7813cd 100644--- a/web/apps/space/src/components/AddFriendTile.tsx+++ b/web/apps/space/src/components/AddFriendTile.tsx@@ -1,9 +1,9 @@import { UserAdd02Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { Box } from "@mui/material";-import { SpaceShareIcon } from "components/ShareInviteButton";+import { SpaceShareInviteButton } from "components/ShareInviteButton";+import log from "ente-base/log";import React from "react";-import { spaceEmptyStateButtonSx } from "styles/buttons";import {spaceSurface,spaceSurfaceHover,@@ -19,131 +19,142 @@ import type {interface SpaceAddFriendTileProps {onClick: () => void;placement: HomeTilePlacement;+ profileLink?: string;variant: AddFriendTileVariant;}export const SpaceAddFriendTile: React.FC<SpaceAddFriendTileProps> = ({onClick,placement,+ profileLink,variant,-}) => (- <Box- component="li"- sx={{- ...spaceTileCornerStyles(- Math.min(- spacePostTileRadius,- Math.min(placement.width, placement.height) * 0.2,+}) => {+ const [isSharing, setIsSharing] = React.useState(false);++ return (+ <Box+ component="li"+ sx={{+ ...spaceTileCornerStyles(+ Math.min(+ spacePostTileRadius,+ Math.min(placement.width, placement.height) * 0.2,+ ),),- ),- height: placement.height,- left: placement.x,- listStyle: "none",- position: "absolute",- top: placement.y,- width: placement.width,- }}- >- {variant == "empty" ? (- <Box- sx={{- alignItems: "center",- bgcolor: spaceSurface,- borderRadius: "inherit",- boxSizing: "border-box",- color: spaceText,- display: "flex",- flexDirection: "column",- height: "100%",- justifyContent: "center",- px: "24px",- py: "32px",- textAlign: "center",- }}- >- <HugeiconsIcon- icon={UserAdd02Icon}- size={32}- strokeWidth={1.7}- color={spaceTextMuted}- style={{ flexShrink: 0, marginBottom: 16 }}- />- <Box- component="h2"- sx={{- fontFamily: '"Nunito", sans-serif',- fontSize: 22,- fontWeight: 800,- lineHeight: "28px",- m: 0,- mb: "8px",- textWrap: "balance",- }}- >- Invite your close friends and family- </Box>+ height: placement.height,+ left: placement.x,+ listStyle: "none",+ position: "absolute",+ top: placement.y,+ width: placement.width,+ }}+ >+ {variant == "empty" ? (<Box- component="p"sx={{- color: spaceTextMuted,- fontFamily: '"Inter Variable", Inter, sans-serif',- fontSize: 13,- lineHeight: "20px",- m: 0,- maxWidth: 240,+ alignItems: "center",+ bgcolor: spaceSurface,+ borderRadius: "inherit",+ boxSizing: "border-box",+ color: spaceText,+ display: "flex",+ flexDirection: "column",+ height: "100%",+ justifyContent: "center",+ px: "24px",+ py: "32px",+ textAlign: "center",}}>- Each person gets a little spot of their own in your Space.+ <HugeiconsIcon+ icon={UserAdd02Icon}+ size={32}+ strokeWidth={1.7}+ color={spaceTextMuted}+ style={{ flexShrink: 0, marginBottom: 16 }}+ />+ <Box+ component="h2"+ sx={{+ fontFamily: '"Nunito", sans-serif',+ fontSize: 22,+ fontWeight: 800,+ lineHeight: "28px",+ m: 0,+ mb: "8px",+ textWrap: "balance",+ }}+ >+ Invite your close friends and family+ </Box>+ <Box+ component="p"+ sx={{+ color: spaceTextMuted,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 13,+ lineHeight: "20px",+ m: 0,+ maxWidth: 240,+ }}+ >+ Each person gets a little spot of their own in your+ Space.+ </Box>+ <Box sx={{ mt: "24px" }}>+ <SpaceShareInviteButton+ profileLink={profileLink}+ sharing={isSharing}+ onSharingChange={setIsSharing}+ onShareError={(error) =>+ log.error(+ "Failed to share Space invite link",+ error,+ )+ }+ />+ </Box></Box>+ ) : (<Box- className="green-bg"component="button"type="button"+ aria-label="Add friend"onClick={onClick}- sx={{ ...spaceEmptyStateButtonSx, mt: "24px" }}+ sx={{+ alignItems: "center",+ appearance: "none",+ bgcolor: spaceSurface,+ border: 0,+ borderRadius: "inherit",+ color: "#65656D",+ cursor: "pointer",+ display: "flex",+ height: "100%",+ justifyContent: "center",+ p: "var(--space-tile-padding)",+ width: "100%",+ transition:+ "background-color 160ms ease, box-shadow 160ms ease",+ "&:hover": {+ bgcolor: spaceSurfaceHover,+ boxShadow:+ "inset 0 0 0 1px rgba(255, 255, 255, 0.08)",+ },+ "&:active": { bgcolor: spaceSurface },+ "&:focus-visible": {+ outline: "2px solid #08C225",+ outlineOffset: -4,+ },+ }}>- <SpaceShareIcon />- Share invite link+ <HugeiconsIcon+ icon={UserAdd02Icon}+ size={28}+ strokeWidth={1.7}+ /></Box>- </Box>- ) : (- <Box- component="button"- type="button"- aria-label="Add friend"- onClick={onClick}- sx={{- alignItems: "center",- appearance: "none",- bgcolor: spaceSurface,- border: 0,- borderRadius: "inherit",- color: "#65656D",- cursor: "pointer",- display: "flex",- height: "100%",- justifyContent: "center",- p: "var(--space-tile-padding)",- width: "100%",- transition:- "background-color 160ms ease, box-shadow 160ms ease",- "&:hover": {- bgcolor: spaceSurfaceHover,- boxShadow: "inset 0 0 0 1px rgba(255, 255, 255, 0.08)",- },- "&:active": { bgcolor: spaceSurface },- "&:focus-visible": {- outline: "2px solid #08C225",- outlineOffset: -4,- },- }}- >- <HugeiconsIcon- icon={UserAdd02Icon}- size={28}- strokeWidth={1.7}- />- </Box>- )}- </Box>-);+ )}+ </Box>+ );+};diff --git a/web/apps/space/src/components/FriendQuickActionsDialog.tsx b/web/apps/space/src/components/FriendQuickActionsDialog.tsxindex d3583ba992..5315299552 100644--- a/web/apps/space/src/components/FriendQuickActionsDialog.tsx+++ b/web/apps/space/src/components/FriendQuickActionsDialog.tsx@@ -122,8 +122,7 @@ export const FriendQuickActionsDialog: React.FC<ref: paperRef,sx: {bgcolor: spaceSurface,- boxShadow:- "0 0 0 1px rgba(255, 255, 255, 0.08), 0 24px 64px rgba(0, 0, 0, 0.48)",+ boxShadow: "0 24px 64px rgba(0, 0, 0, 0.48)",borderRadius: `${dialogRadius}px`,boxSizing: "border-box",display: "flex",@@ -264,9 +263,7 @@ export const FriendQuickActionsDialog: React.FC<sx={{alignItems: "center",appearance: "none",- bgcolor: action.active- ? "#24412E"- : spaceDialogBackground,+ bgcolor: spaceDialogBackground,border: 0,borderRadius: `${innerRadius}px`,color: action.active@@ -278,14 +275,15 @@ export const FriendQuickActionsDialog: React.FC<height: actionHeight,minWidth: 0,p: "0 8px",- transition:- "background-color 120ms ease, color 120ms ease",- "&:hover:not(:disabled)": {- bgcolor: spaceSurfaceHover,- },- "&:active:not(:disabled)": {- bgcolor: spaceAppBackgroundColor,- },+ ...(action.label != "Poke" && {+ transition: "background-color 120ms ease",+ "&:hover:not(:disabled)": {+ bgcolor: spaceSurfaceHover,+ },+ "&:active:not(:disabled)": {+ bgcolor: spaceAppBackgroundColor,+ },+ }),"&:focus-visible": {outline: `2px solid ${spaceText}`,outlineOffset: 2,diff --git a/web/apps/space/src/components/MessagesPage.tsx b/web/apps/space/src/components/MessagesPage.tsxindex cfe50a13c0..246a20ae31 100644--- a/web/apps/space/src/components/MessagesPage.tsx+++ b/web/apps/space/src/components/MessagesPage.tsx@@ -120,7 +120,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({}) => {const router = useSpaceRouter();const {- postPublishPhase,+ postPublication,profile,profileLoadError,profileLoadStatus,@@ -525,8 +525,8 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({}, [profile?.spaceId, refreshConversations]);React.useEffect(() => {- if (postPublishPhase == "posted") void refreshConversations();- }, [postPublishPhase, refreshConversations]);+ if (postPublication?.phase == "posted") void refreshConversations();+ }, [postPublication?.phase, refreshConversations]);React.useEffect(() => {const previousSelectedSpaceId = previousSelectedSpaceIdRef.current;diff --git a/web/apps/space/src/components/OwnPostTile.tsx b/web/apps/space/src/components/OwnPostTile.tsxindex dd9aa5536e..11ef2ff5c6 100644--- a/web/apps/space/src/components/OwnPostTile.tsx+++ b/web/apps/space/src/components/OwnPostTile.tsx@@ -1,12 +1,12 @@import { Add01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { Box, Skeleton } from "@mui/material";+import { Box, Fade, Skeleton } from "@mui/material";import { SpaceAvatarImage } from "components/AvatarImage";import log from "ente-base/log";import React from "react";import type { SetupProfile } from "screens/SetupProfileScreen";import type { SpacePost, SpacePostAssetURLLoader } from "services/space";-import { useSpaceAppState } from "state/app-state";+import { useSpaceAppState, type SpacePostPublishPhase } from "state/app-state";import { spaceSurface, spaceTextMuted } from "styles/colors";import {spacePostTileRadius,@@ -14,13 +14,90 @@ import {spaceTileCornerStyles,} from "styles/tiles";import { spaceDefaultCoverImagePath } from "utils/post-image";+import { thumbHashDataURLFromBase64 } from "utils/thumbhash";const green = "#08C225";-const actionSize = 44;+const actionSize = 56;++const PostStatus: React.FC<{+ phase: SpacePostPublishPhase;+ expiresAtMs?: number;+}> = ({ phase, expiresAtMs }) => {+ const [dotCount, setDotCount] = React.useState(1);+ const [isVisible, setIsVisible] = React.useState(+ () => !expiresAtMs || expiresAtMs > Date.now(),+ );++ React.useEffect(() => {+ setIsVisible(!expiresAtMs || expiresAtMs > Date.now());+ if (!expiresAtMs) return;++ const timeoutID = window.setTimeout(+ () => setIsVisible(false),+ Math.max(0, expiresAtMs - Date.now()),+ );+ return () => window.clearTimeout(timeoutID);+ }, [expiresAtMs]);++ React.useEffect(() => {+ if (phase != "posting") return;++ setDotCount(1);+ const intervalID = window.setInterval(() => {+ setDotCount((count) => (count % 3) + 1);+ }, 500);+ return () => window.clearInterval(intervalID);+ }, [phase]);++ const label =+ phase == "posting"+ ? "Posting"+ : phase == "posted"+ ? "Posted"+ : "Failed";++ return (+ <Fade in={isVisible} appear={false} timeout={200} unmountOnExit>+ <Box+ role="status"+ aria-label={label}+ sx={{+ bgcolor:+ phase == "posted"+ ? green+ : phase == "failed"+ ? "#F63A3A"+ : "rgba(0, 0, 0, 0.64)",+ borderRadius: "999px",+ color: "#FFFFFF",+ display: "inline-flex",+ fontSize: 12,+ fontWeight: 500,+ left: "var(--space-tile-padding)",+ lineHeight: "16px",+ pointerEvents: "none",+ position: "absolute",+ px: "10px",+ py: "4px",+ top: "var(--space-tile-padding)",+ whiteSpace: "nowrap",+ }}+ >+ {label}+ {phase == "posting" && (+ <Box component="span" aria-hidden sx={{ width: 12 }}>+ {".".repeat(dotCount)}+ </Box>+ )}+ </Box>+ </Fade>+ );+};interface SpaceOwnPostTileProps {profile: SetupProfile | null;post?: SpacePost;+ avatarSize?: number;isLoading?: boolean;isUnavailable?: boolean;isNewPostDisabled?: boolean;@@ -33,6 +110,7 @@ interface SpaceOwnPostTileProps {export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({profile,post,+ avatarSize = 36,isLoading = false,isUnavailable = false,isNewPostDisabled = false,@@ -41,7 +119,11 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({onOpenProfile,onNewPost,}) => {- const { cachedProfileAvatarUrl } = useSpaceAppState();+ const { cachedProfileAvatarUrl, postPublication } = useSpaceAppState();+ const tileRef = React.useRef<HTMLElement>(null);+ const publishPhase =+ postPublication?.post == post ? postPublication?.phase : undefined;+ const hasPublication = Boolean(publishPhase);const avatarUrl = profile ? profile.avatarUrl : cachedProfileAvatarUrl;const isAvatarLoading =!avatarUrl && (!profile || Boolean(profile.avatarObjectID));@@ -52,13 +134,28 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({}>();const postImage = loadedImage?.post == post ? loadedImage : undefined;const imageUrl = post?.imageUrl ?? postImage?.url;+ const thumbHashDataURL = React.useMemo(+ () => thumbHashDataURLFromBase64(post?.thumbHash),+ [post?.thumbHash],+ );const unavailable =isUnavailable || post?.isUnavailable || postImage?.failed;+ const canOpenPost = Boolean(+ imageUrl &&+ !unavailable &&+ onOpenPost &&+ (!publishPhase || publishPhase == "posted"),+ );const loading =isLoading || Boolean(post?.imageAsset && !imageUrl && !unavailable);const isEmpty = !post && !loading && !unavailable;const coverUrl = isEmpty ? spaceDefaultCoverImagePath : imageUrl;+ React.useEffect(() => {+ if (hasPublication)+ tileRef.current?.scrollIntoView({ block: "nearest" });+ }, [hasPublication]);+React.useEffect(() => {if (!post?.imageAsset || post.imageUrl || !onLoadPostImage) return;@@ -78,12 +175,13 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({return (<Box+ ref={tileRef}component="section"aria-label="Your latest post"sx={{...spaceTileCornerStyles(spacePostTileRadius),aspectRatio: "1.7",- bgcolor: spaceSurface,+ bgcolor: unavailable ? spaceSurface : "transparent",flexShrink: 0,fontFamily: '"Inter Variable", Inter, sans-serif',overflow: "hidden",@@ -99,7 +197,7 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({component="button"type="button"aria-label="Open your posts"- disabled={!imageUrl || unavailable || !onOpenPost}+ disabled={!canOpenPost}onClick={() => imageUrl && onOpenPost?.(imageUrl)}sx={{appearance: "none",@@ -107,7 +205,7 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({border: 0,borderRadius: "inherit",color: spaceTextMuted,- cursor: imageUrl && onOpenPost ? "pointer" : "default",+ cursor: canOpenPost ? "pointer" : "default",font: "inherit",inset: 0,p: 0,@@ -115,27 +213,49 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({width: "100%",}}>- {coverUrl && !unavailable ? (- <Box- component="img"- alt={isEmpty ? "" : post?.caption || "Your latest post"}- src={coverUrl}- onError={() =>- post && setLoadedImage({ post, failed: true })- }- sx={{- display: "block",- height: "100%",- objectFit: "cover",- width: "100%",- }}- />- ) : loading ? (- <Skeleton- variant="rectangular"- sx={{ height: "100%", transform: "none" }}- />- ) : (+ {(coverUrl || thumbHashDataURL) && !unavailable ? (+ <>+ {thumbHashDataURL && (+ <Box+ component="img"+ alt=""+ aria-hidden+ src={thumbHashDataURL}+ sx={{+ filter: "blur(14px)",+ height: "100%",+ inset: 0,+ objectFit: "cover",+ position: "absolute",+ transform: "scale(1.08)",+ width: "100%",+ }}+ />+ )}+ {coverUrl && (+ <Box+ component="img"+ alt={+ isEmpty+ ? ""+ : post?.caption || "Your latest post"+ }+ src={coverUrl}+ onError={() =>+ post &&+ setLoadedImage({ post, failed: true })+ }+ sx={{+ display: "block",+ height: "100%",+ objectFit: "cover",+ position: "relative",+ width: "100%",+ }}+ />+ )}+ </>+ ) : !loading ? (<Boxsx={{fontSize: 15,@@ -145,7 +265,7 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({>Couldn't load your latest post</Box>- )}+ ) : null}{isEmpty && (<Boxsx={{@@ -174,7 +294,7 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({py: "3px",}}>- Your posts will show up here+ Your latest posts will show up here</Box><Boxcomponent="span"@@ -197,10 +317,6 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({</Box><Boxsx={{- background:- coverUrl && !unavailable- ? "linear-gradient(transparent, rgba(0, 0, 0, 0.72))"- : undefined,bottom: 0,height: "50%",left: 0,@@ -220,16 +336,16 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({bgcolor: "transparent",border: 0,borderRadius: "50%",- bottom: spaceTileCircleInset(actionSize),+ bottom: spaceTileCircleInset(avatarSize),cursor: onOpenProfile ? "pointer" : "default",display: "flex",- height: actionSize,+ height: avatarSize,justifyContent: "center",- left: spaceTileCircleInset(actionSize),+ left: spaceTileCircleInset(avatarSize),p: 0,pointerEvents: "auto",position: "absolute",- width: actionSize,+ width: avatarSize,}}><Box@@ -240,9 +356,9 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({borderRadius: "50%",boxSizing: "border-box",flexShrink: 0,- height: actionSize,+ height: avatarSize,overflow: "hidden",- width: actionSize,+ width: avatarSize,}}>{isAvatarLoading ? (@@ -288,9 +404,15 @@ export const SpaceOwnPostTile: React.FC<SpaceOwnPostTileProps> = ({"&:focus-visible": { outlineColor: "#FFFFFF" },}}>- <HugeiconsIcon icon={Add01Icon} size={24} strokeWidth={2} />+ <HugeiconsIcon icon={Add01Icon} size={28} strokeWidth={2} /></Box></Box>+ {publishPhase && (+ <PostStatus+ phase={publishPhase}+ expiresAtMs={postPublication?.statusExpiresAtMs}+ />+ )}</Box>);};diff --git a/web/apps/space/src/components/PostComposer.tsx b/web/apps/space/src/components/PostComposer.tsxindex 52b1852294..12b055284d 100644--- a/web/apps/space/src/components/PostComposer.tsx+++ b/web/apps/space/src/components/PostComposer.tsx@@ -16,6 +16,8 @@ import {spacePostPreviewImageForFile,type SpaceDraftPostImage,} from "utils/post-image";+import { useSpaceRouter } from "utils/route-transitions";+import { spaceRoutes } from "utils/routes";interface PendingPostDraft {error?: string;@@ -39,6 +41,8 @@ const SpacePostComposer: React.FC<SpacePostComposerProps> = ({onPublish,profile,}) => {+ const router = useSpaceRouter();+ const publishedPreviewURLRef = React.useRef<string>(undefined);const displayName =profile.fullName.trim() || profile.username.trim() || "You";const [draft, setDraft] = React.useState<PendingPostDraft>(() => ({@@ -112,7 +116,9 @@ const SpacePostComposer: React.FC<SpacePostComposerProps> = ({return () => {cancelled = true;- if (previewURL) URL.revokeObjectURL(previewURL);+ if (previewURL && previewURL != publishedPreviewURLRef.current) {+ URL.revokeObjectURL(previewURL);+ }};}, [displayName, file, profile.avatarUrl]);@@ -128,22 +134,28 @@ const SpacePostComposer: React.FC<SpacePostComposerProps> = ({}onDraftPostExitStart={() => setIsDraftPostExiting(true)}onDraftPostPublished={() => {- void clearBrowserBackState("back");+ void clearBrowserBackState("back").then(() =>+ router.push(spaceRoutes.home),+ );}}onPublishDraftPost={draft.isPreviewPending || draft.error? undefined- : (caption, edit) =>- onPublish(+ : (caption, edit) => {+ publishedPreviewURLRef.current =+ draft.photo.imageUrl;+ return onPublish({cropArea: edit.cropArea,file,height: edit.height,+ previewUrl: draft.photo.imageUrl,rotationDegrees: edit.rotationDegrees,width: edit.width,},caption,- ).then(() => undefined)+ ).then(() => undefined);+ }}photo={draft.photo}postActionMode="draft-post"diff --git a/web/apps/space/src/components/PostToast.tsx b/web/apps/space/src/components/PostToast.tsxdeleted file mode 100644index b44eb23840..0000000000--- a/web/apps/space/src/components/PostToast.tsx+++ /dev/null@@ -1,48 +0,0 @@-import { AlertCircleIcon } from "@hugeicons/core-free-icons";-import { HugeiconsIcon } from "@hugeicons/react";-import { SpaceActionFeedbackIcon } from "components/ActionFeedback";-import {- SpaceActionToast,- spaceToastAutoDismissDurationMs,-} from "components/ActionToast";-import React from "react";-import { useSpaceAppState } from "state/app-state";--const dangerColor = "#F63A3A";--export const SpacePostToast: React.FC = () => {- const { dismissPostPublishToast, postPublishPhase } = useSpaceAppState();-- if (!postPublishPhase) return null;-- const isPosting = postPublishPhase == "posting";- const isFailed = postPublishPhase == "failed";- return (- <SpaceActionToast- animateEntrance={isPosting}- autoDismissAfterMs={- isPosting ? undefined : spaceToastAutoDismissDurationMs- }- closeLabel="Dismiss post status"- icon={- isFailed ? (- <HugeiconsIcon- color={dangerColor}- icon={AlertCircleIcon}- size={20}- strokeWidth={1.8}- />- ) : (- <SpaceActionFeedbackIcon- phase={isPosting ? "busy" : "done"}- size={20}- />- )- }- message={isPosting ? "Posting..." : isFailed ? "Failed" : "Posted"}- onClose={dismissPostPublishToast}- showCloseButton={false}- zIndex={1400}- />- );-};diff --git a/web/apps/space/src/components/PostUnreadBadge.tsx b/web/apps/space/src/components/PostUnreadBadge.tsxindex 3cbe863b2e..9ec41984ba 100644--- a/web/apps/space/src/components/PostUnreadBadge.tsx+++ b/web/apps/space/src/components/PostUnreadBadge.tsx@@ -55,7 +55,7 @@ export const SpacePostBadge: React.FC<SpacePostBadgeProps> = ({maxWidth: `calc(100% - 2 * (${inset}))`,}),...(variant == "unread" && {- boxShadow: "0 1px 3px rgba(0, 0, 0, 0.15)",+ border: "1px solid #FFFFFF",fontSize: 12,px: "6px",}),diff --git a/web/apps/space/src/hooks/use-own-latest-post.ts b/web/apps/space/src/hooks/use-own-latest-post.tsindex 571db0e3f1..dc04505368 100644--- a/web/apps/space/src/hooks/use-own-latest-post.ts+++ b/web/apps/space/src/hooks/use-own-latest-post.ts@@ -1,5 +1,6 @@import log from "ente-base/log";import { useCallback, useEffect, useState } from "react";+import { loadCachedOwnLatestPost } from "services/post-cache";import {deleteCurrentPost,loadCurrentSpaceProfilePostsPage,@@ -8,9 +9,8 @@ import {} from "services/space";import { useSpaceAppState } from "state/app-state";-export const useOwnLatestPost = () => {- const { profile, profileLoadStatus } = useSpaceAppState();- const spaceId = profile?.spaceId;+export const useOwnLatestPost = (spaceId: string | undefined) => {+ const { postPublication, setPostPublication } = useSpaceAppState();const [ownLatestPost, setOwnLatestPost] = useState<SpacePost>();const [ownPostsVersion, setOwnPostsVersion] = useState(0);const [isOwnLatestPostLoading, setIsOwnLatestPostLoading] = useState(true);@@ -18,21 +18,30 @@ export const useOwnLatestPost = () => {useState(false);useEffect(() => {- if (profileLoadStatus != "ready") return;-setOwnLatestPost(undefined);- setIsOwnLatestPostLoading(Boolean(spaceId));+ setIsOwnLatestPostLoading(true);setIsOwnLatestPostUnavailable(false);if (!spaceId) return;let cancelled = false;- void loadCurrentSpaceProfilePostsPage(spaceId, spaceId)+ let cachedPost: SpacePost | undefined;+ void loadCachedOwnLatestPost(spaceId)+ .then((post) => {+ if (cancelled) return;+ cachedPost = post;+ if (post) {+ setOwnLatestPost(post);+ setIsOwnLatestPostLoading(false);+ }+ return loadCurrentSpaceProfilePostsPage(spaceId, spaceId);+ }).then((page) => {- if (!cancelled) setOwnLatestPost(page.items[0]);+ if (!cancelled && page) setOwnLatestPost(page.items[0]);}).catch((error: unknown) => {log.error("Failed to load own latest Space post", error);- if (!cancelled) setIsOwnLatestPostUnavailable(true);+ if (!cancelled && !cachedPost)+ setIsOwnLatestPostUnavailable(true);}).finally(() => {if (!cancelled) setIsOwnLatestPostLoading(false);@@ -40,26 +49,26 @@ export const useOwnLatestPost = () => {return () => {cancelled = true;};- }, [spaceId, profileLoadStatus, ownPostsVersion]);-- const setCreatedPost = useCallback((post: SpacePost) => {- setOwnLatestPost(post);- setIsOwnLatestPostLoading(false);- setIsOwnLatestPostUnavailable(false);- }, []);+ }, [spaceId, ownPostsVersion]);const deleteOwnPost = useCallback(async (postId: number) => {if (!spaceId) throw new Error("Missing space.");await deleteCurrentPost(spaceId, postId);- if (ownLatestPost?.postId == postId) {+ if (+ ownLatestPost?.postId == postId ||+ postPublication?.post.postId == postId+ ) {+ setPostPublication((current) =>+ current?.post.postId == postId ? null : current,+ );setOwnLatestPost(undefined);setIsOwnLatestPostLoading(true);setOwnPostsVersion((version) => version + 1);}},- [spaceId, ownLatestPost?.postId],+ [spaceId, ownLatestPost?.postId, postPublication, setPostPublication],);const updateOwnPostCaption = useCallback(@@ -67,20 +76,31 @@ export const useOwnLatestPost = () => {if (!spaceId) throw new Error("Missing space.");await updateCurrentPostCaption(spaceId, postId, caption);+ setPostPublication((current) =>+ current?.post.postId == postId+ ? {+ ...current,+ post: {+ ...current.post,+ caption: caption.trim() || undefined,+ },+ }+ : current,+ );setOwnLatestPost((post) =>post?.postId == postId? { ...post, caption: caption.trim() || undefined }: post,);},- [spaceId],+ [spaceId, setPostPublication],);return {- ownLatestPost,- isOwnLatestPostLoading,- isOwnLatestPostUnavailable,- setCreatedPost,+ ownLatestPost: postPublication?.post ?? ownLatestPost,+ isOwnLatestPostLoading: !postPublication && isOwnLatestPostLoading,+ isOwnLatestPostUnavailable:+ !postPublication && isOwnLatestPostUnavailable,deleteOwnPost,updateOwnPostCaption,};diff --git a/web/apps/space/src/pages/_app.tsx b/web/apps/space/src/pages/_app.tsxindex 2a23395de1..da1bb5ecbe 100644--- a/web/apps/space/src/pages/_app.tsx+++ b/web/apps/space/src/pages/_app.tsx@@ -3,7 +3,6 @@ import "@fontsource/nunito/800.css";import { CssBaseline } from "@mui/material";import { createTheme, ThemeProvider } from "@mui/material/styles";import { SpacePostComposerHost } from "components/PostComposer";-import { SpacePostToast } from "components/PostToast";import { SpaceRouteTransitionBoundary } from "components/RouteTransitionBoundary";import { SpaceShareLinkDialogHost } from "components/ShareLinkDialog";import "configure-zod";@@ -156,7 +155,6 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {<SpaceAppStateProvider><Component {...pageProps} /><SpacePostComposerHost />- <SpacePostToast /><SpaceShareLinkDialogHost /></SpaceAppStateProvider></SpaceRouteTransitionBoundary>diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsxindex 2851fac6d9..c0bf355a14 100644--- a/web/apps/space/src/pages/app/index.tsx+++ b/web/apps/space/src/pages/app/index.tsx@@ -58,14 +58,14 @@ const Page: React.FC = () => {[],);const [latestPosts, setLatestPosts] = useState<SpacePost[]>([]);+ const [spaceId, setSpaceId] = useState<string>();const {ownLatestPost,isOwnLatestPostLoading,isOwnLatestPostUnavailable,- setCreatedPost,deleteOwnPost,updateOwnPostCaption,- } = useOwnLatestPost();+ } = useOwnLatestPost(spaceId);const [unreadPosts, setUnreadPosts] = useState<SpacePost[]>([]);const [hasUnreadMessages, setHasUnreadMessages] = useState<boolean>();const [isLatestPostsLoading, setIsLatestPostsLoading] = useState(true);@@ -77,7 +77,6 @@ const Page: React.FC = () => {const [showFriendRequestCanceledToast, setShowFriendRequestCanceledToast] =useState(false);const [showFriendLimitToast, setShowFriendLimitToast] = useState(false);- const [spaceId, setSpaceId] = useState<string>();const closeFriendRequestSentToast = React.useCallback(() => setFriendRequestSentToastName(undefined),[],@@ -343,8 +342,7 @@ const Page: React.FC = () => {onCreatePost={profile? async (image, caption) => {- const post = await publishPost(image, caption);- setCreatedPost(post);+ await publishPost(image, caption);}: undefined}diff --git a/web/apps/space/src/pages/app/profile.tsx b/web/apps/space/src/pages/app/profile.tsxindex 7e5b18abb6..e51d3dbd8c 100644--- a/web/apps/space/src/pages/app/profile.tsx+++ b/web/apps/space/src/pages/app/profile.tsx@@ -23,8 +23,13 @@ const initialPostLoadingIndicatorDelayMs = 350;const Page: React.FC = () => {const router = useSpaceRouter();- const { profile, profileLoadError, profileLoadStatus, publishPost } =- useSpaceAppState();+ const {+ profile,+ profileLoadError,+ profileLoadStatus,+ publishPost,+ setPostPublication,+ } = useSpaceAppState();const [friendsCount, setFriendsCount] = useState(0);const [posts, setPosts] = useState<SpaceProfilePost[]>([]);const [isPostsLoading, setIsPostsLoading] = useState(true);@@ -120,19 +125,17 @@ const Page: React.FC = () => {profile={profile}showPostLoadingIndicator={showInitialPostLoadingIndicator}onBack={() => void router.push(spaceRoutes.home)}+ onPostSubmitted={() => void router.push(spaceRoutes.home)}onCreatePost={async (image, caption) => {- const post = await publishPost(image, caption);- setPosts((currentPosts) => [- post,- ...currentPosts.filter(- (currentPost) => currentPost.postId != post.postId,- ),- ]);+ await publishPost(image, caption);}}onDeletePost={async (postId) => {const spaceId = profile.spaceId;if (!spaceId) throw new Error("Missing space.");await deleteCurrentPost(spaceId, postId);+ setPostPublication((current) =>+ current?.post.postId == postId ? null : current,+ );setPosts((currentPosts) =>currentPosts.filter((post) => post.postId != postId),);@@ -143,6 +146,17 @@ const Page: React.FC = () => {await updateCurrentPostCaption(spaceId, postId, caption);const normalizedCaption = caption.trim() || undefined;+ setPostPublication((current) =>+ current?.post.postId == postId+ ? {+ ...current,+ post: {+ ...current.post,+ caption: normalizedCaption,+ },+ }+ : current,+ );setPosts((currentPosts) =>currentPosts.map((post) =>post.postId == postIddiff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsxindex 4dea99fbb7..cc9b226108 100644--- a/web/apps/space/src/screens/HomeScreen.tsx+++ b/web/apps/space/src/screens/HomeScreen.tsx@@ -1,6 +1,6 @@import { Cancel01Icon, UserAdd02Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { Box, Skeleton } from "@mui/material";+import { Box } from "@mui/material";import { SpaceActionFeedbackIcon } from "components/ActionFeedback";import {SpaceActionToast,@@ -46,6 +46,7 @@ import {} from "styles/colors";import {spacePostTileRadius,+ spaceTileAvatarSize,spaceTileCircleInset,spaceTileCornerStyles,spaceTileInnerRadius,@@ -348,7 +349,7 @@ export const FriendPostTile: React.FC<FriendPostTileProps> = ({Boolean(post && !postUnavailable && !isPhotoReady);const tileSize = Math.min(placement.width, placement.height);const tileRadius = Math.min(spacePostTileRadius, tileSize * 0.2);- const avatarSize = Math.min(36, tileSize * 0.22);+ const avatarSize = spaceTileAvatarSize(placement);const requestActionSize = showFriendRequestDetails? Math.min(44, Math.max(40, tileSize * 0.13)): Math.min(40, Math.max(26, tileSize * 0.14));@@ -502,7 +503,10 @@ export const FriendPostTile: React.FC<FriendPostTileProps> = ({sx={{alignItems: "center",appearance: "none",- bgcolor: mediaPlaceholderColor,+ bgcolor:+ !isLoading && (!post || postUnavailable)+ ? mediaPlaceholderColor+ : "transparent",border: 0,borderRadius: "inherit",color: textBase,@@ -518,29 +522,8 @@ export const FriendPostTile: React.FC<FriendPostTileProps> = ({zIndex: 1,}}>- {isLoading ? (- <Skeleton- variant="rectangular"- sx={{- bgcolor: mediaPlaceholderColor,- height: "100%",- transform: "none",- width: "100%",- }}- />- ) : post && !postUnavailable ? (+ {post && !postUnavailable && (<>- {!thumbHashDataURL && !isPhotoReady && (- <Skeleton- variant="rectangular"- sx={{- bgcolor: mediaPlaceholderColor,- height: "100%",- transform: "none",- width: "100%",- }}- />- )}{thumbHashDataURL && (<Boxcomponent="img"@@ -583,15 +566,6 @@ export const FriendPostTile: React.FC<FriendPostTileProps> = ({/>)}</>- ) : (- <Box- aria-hidden- sx={{- bgcolor: mediaPlaceholderColor,- height: "100%",- width: "100%",- }}- />)}{!isLoading &&!post &&@@ -1144,6 +1118,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({postTileCanvasSize.width,postTileCanvasSize.height,);+ const firstFriendTile = postLayout?.friends[0];const isInstallPromptEnabled =showInstallPrompt && !friendRequestSentToastName && !selectedViewer;const isHomeItemsLoading = isFriendsLoading || isFriendRequestsLoading;@@ -1156,11 +1131,6 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({);localPostObjectUrlsRef.current.clear();}, []);- const releaseLocalPostObjectUrl = React.useCallback((objectUrl: string) => {- localPostObjectUrlsRef.current.delete(objectUrl);- URL.revokeObjectURL(objectUrl);- }, []);-const openPostPhotoPicker = () => {if (isPostPhotoButtonDisabled) return;@@ -1767,6 +1737,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({{postLayout.addFriend && (<SpaceAddFriendTileplacement={postLayout.addFriend}+ profileLink={profileLink}variant={postLayout.addFriendVariant}@@ -1785,6 +1756,11 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({<SpaceOwnPostTileprofile={profile}post={ownLatestPost}+ avatarSize={+ firstFriendTile+ ? spaceTileAvatarSize(firstFriendTile)+ : undefined+ }isLoading={isOwnLatestPostLoading}isUnavailable={isOwnLatestPostUnavailable}isNewPostDisabled={isPostPhotoButtonDisabled}@@ -1910,15 +1886,17 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({cropArea: edit.cropArea,file: selectedViewer.draftFile!,height: edit.height,+ previewUrl,rotationDegrees:edit.rotationDegrees,width: edit.width,},caption,);- return publishPromise.finally(() =>- releaseLocalPostObjectUrl(previewUrl),+ localPostObjectUrlsRef.current.delete(+ previewUrl,);+ return publishPromise;}: undefined}diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsxindex e4718480e4..6afe0ce075 100644--- a/web/apps/space/src/screens/ProfileScreen.tsx+++ b/web/apps/space/src/screens/ProfileScreen.tsx@@ -529,6 +529,7 @@ interface ProfileScreenProps {isStatsLoading?: boolean;showPostLoadingIndicator?: boolean;onBack?: () => void;+ onPostSubmitted?: () => void;onAddFriend?: () => void;onAddFriendForPostAction?: (intent: SpaceInviteIntent) => void;onCreateSpace?: () => void;@@ -568,6 +569,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({isPostsLoading = false,isStatsLoading = false,onBack,+ onPostSubmitted,onAddFriend,onAddFriendForPostAction,onCreateSpace,@@ -732,10 +734,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({);localPostObjectUrlsRef.current.clear();}, []);- const releaseLocalPostObjectUrl = React.useCallback((objectUrl: string) => {- localPostObjectUrlsRef.current.delete(objectUrl);- URL.revokeObjectURL(objectUrl);- }, []);const openPostPhotoPicker = () => {if (isPostPhotoOpening) return;@@ -748,13 +746,14 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({setSelectedPost(null);revokeLocalPostObjectUrls();};- useBrowserBackClose({- open: Boolean(selectedPost),- onClose: () => {- if (!isDraftPostExiting) closeSelectedPost();- },- stateKey: "space-profile-viewer",- });+ const { clearBrowserBackState: clearSelectedPostHistory } =+ useBrowserBackClose({+ open: Boolean(selectedPost),+ onClose: () => {+ if (!isDraftPostExiting) closeSelectedPost();+ },+ stateKey: "space-profile-viewer",+ });const rememberLoadedPhotoDimensions = (itemID: string,image: HTMLImageElement,@@ -2013,6 +2012,11 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({setIsDraftPostExitAnimating(true);}}onDraftPostExitStart={() => setIsDraftPostExiting(true)}+ onDraftPostPublished={() => {+ void clearSelectedPostHistory("back").then(() =>+ onPostSubmitted?.(),+ );+ }}onDeletePost={isOwnerProfile ? deleteSelectedPost : undefined}@@ -2037,9 +2041,10 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({},caption,);- return publishPromise.finally(() =>- releaseLocalPostObjectUrl(previewUrl),+ localPostObjectUrlsRef.current.delete(+ previewUrl,);+ return publishPromise;}: undefined}diff --git a/web/apps/space/src/services/home-posts.ts b/web/apps/space/src/services/home-posts.tsindex 6d36a9d964..592c0c107b 100644--- a/web/apps/space/src/services/home-posts.ts+++ b/web/apps/space/src/services/home-posts.ts@@ -3,40 +3,12 @@ import { savedPartialLocalUser } from "ente-accounts/services/accounts-db";import { getKV, removeKV, setKV } from "ente-base/kv";import log from "ente-base/log";import { apiOrigin } from "ente-base/origins";+import { CachedSpacePost } from "services/post-cache";import { loadCurrentHomePostsPage, type SpacePost } from "services/space";import { z } from "zod";const homePostsVersion = 1;-const CachedSpacePostAsset = z.object({- encryptedPostKey: z.string(),- keyVersion: z.number(),- mediaType: z.string().optional(),- objectKey: z.string(),- postId: z.number(),- spaceId: z.string(),-});--const CachedSpacePost = z.object({- avatarKeyVersion: z.number().optional(),- avatarObjectID: z.string().optional(),- avatarSize: z.number().optional(),- avatarUpdatedAt: z.string().optional(),- caption: z.string().optional(),- friendID: z.string(),- height: z.number().optional(),- imageAsset: CachedSpacePostAsset.optional(),- isUnavailable: z.boolean().optional(),- name: z.string(),- postId: z.number(),- spaceId: z.string(),- thumbHash: z.string().optional(),- timestampMs: z.number(),- username: z.string().optional(),- viewerLiked: z.boolean(),- width: z.number().optional(),-});-const PostMarker = z.object({postId: z.number().int().positive(),timestampMs: z.number().nonnegative(),diff --git a/web/apps/space/src/services/post-cache.ts b/web/apps/space/src/services/post-cache.tsnew file mode 100644index 0000000000..f20b9f64a8--- /dev/null+++ b/web/apps/space/src/services/post-cache.ts@@ -0,0 +1,87 @@+import { savedPartialLocalUser } from "ente-accounts/services/accounts-db";+import { getKV, removeKV, setKV } from "ente-base/kv";+import log from "ente-base/log";+import { apiOrigin } from "ente-base/origins";+import type { SpacePost } from "services/space";+import { z } from "zod";++const CachedSpacePostAsset = z.object({+ encryptedPostKey: z.string(),+ keyVersion: z.number(),+ mediaType: z.string().optional(),+ objectKey: z.string(),+ postId: z.number(),+ spaceId: z.string(),+});++export const CachedSpacePost = z.object({+ avatarKeyVersion: z.number().optional(),+ avatarObjectID: z.string().optional(),+ avatarSize: z.number().optional(),+ avatarUpdatedAt: z.string().optional(),+ caption: z.string().optional(),+ friendID: z.string(),+ height: z.number().optional(),+ imageAsset: CachedSpacePostAsset.optional(),+ isUnavailable: z.boolean().optional(),+ name: z.string(),+ postId: z.number(),+ spaceId: z.string(),+ thumbHash: z.string().optional(),+ timestampMs: z.number(),+ username: z.string().optional(),+ viewerLiked: z.boolean(),+ width: z.number().optional(),+});++const ownLatestPostKey = async (spaceId: string) => {+ const userID = savedPartialLocalUser()?.id;+ if (!userID) return undefined;+ return [+ "space-own-latest-post",+ "v1",+ await apiOrigin(),+ userID,+ spaceId,+ ].join(":");+};++export const loadCachedOwnLatestPost = async (spaceId: string) => {+ try {+ const key = await ownLatestPostKey(spaceId);+ if (!key) return undefined;+ const parsed = CachedSpacePost.safeParse(await getKV(key));+ return parsed.success ? parsed.data : undefined;+ } catch (error) {+ log.warn("Failed to read own latest Space post cache", error);+ return undefined;+ }+};++export const cacheOwnLatestPost = async (+ spaceId: string,+ post: SpacePost | undefined,+) => {+ try {+ const key = await ownLatestPostKey(spaceId);+ if (!key) return;+ if (post) await setKV(key, CachedSpacePost.parse(post));+ else await removeKV(key);+ } catch (error) {+ log.warn("Failed to persist own latest Space post cache", error);+ }+};++export const patchCachedOwnLatestPost = async (+ spaceId: string,+ postId: number,+ patch: Partial<SpacePost> | undefined,+) => {+ const post = await loadCachedOwnLatestPost(spaceId);+ if (post?.postId == postId) {+ await cacheOwnLatestPost(+ spaceId,+ patch ? { ...post, ...patch } : undefined,+ );+ }+};diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.tsindex c0590111d6..2d4f051c27 100644--- a/web/apps/space/src/services/space.ts+++ b/web/apps/space/src/services/space.ts@@ -18,6 +18,10 @@ import {spacePostMediaCacheKey,spaceProfileMediaCacheKey,} from "services/media-cache";+import {+ cacheOwnLatestPost,+ patchCachedOwnLatestPost,+} from "services/post-cache";import {ensureCurrentSpaceContext,loadExistingSpaceProfile,@@ -1219,7 +1223,7 @@ export const loadCurrentSpaceProfilePostsPage = async (): Promise<SpaceProfilePostPage> => {const ctx = await ensureCurrentSpaceContext();try {- return profilePostPageFromPage(+ const page = profilePostPageFromPage((await ctx.listPosts(spaceId,viewerSpaceId ?? null,@@ -1227,6 +1231,10 @@ export const loadCurrentSpaceProfilePostsPage = async (60,)) as SpacePostPageResponse,);+ if (!cursor && spaceId == viewerSpaceId) {+ await cacheOwnLatestPost(spaceId, page.items[0]);+ }+ return page;} finally {releaseCurrentSpaceContext(ctx);}@@ -1361,7 +1369,9 @@ export const createCurrentPhotoPost = async ({)) as SpacePostResponse;const object = firstObject(created);if (object) await cacheAccountPostAssetURL(created, object, file);- return await postFromAccountPost(ctx, created, true, spaceId);+ const post = await postFromAccountPost(ctx, created, true, spaceId);+ await cacheOwnLatestPost(spaceId, post);+ return post;} finally {releaseCurrentSpaceContext(ctx);}@@ -1711,6 +1721,7 @@ export const deleteCurrentPost = async (spaceId: string, postId: number) => {const ctx = await ensureCurrentSpaceContext();try {await ctx.deletePost(spaceId, BigInt(postId));+ await patchCachedOwnLatestPost(spaceId, postId, undefined);} finally {releaseCurrentSpaceContext(ctx);}@@ -1728,6 +1739,9 @@ export const updateCurrentPostCaption = async (BigInt(postId),caption.trim() || null,);+ await patchCachedOwnLatestPost(spaceId, postId, {+ caption: caption.trim() || undefined,+ });} finally {releaseCurrentSpaceContext(ctx);}diff --git a/web/apps/space/src/state/AppStateProvider.tsx b/web/apps/space/src/state/AppStateProvider.tsxindex e469de52a3..822627ef5f 100644--- a/web/apps/space/src/state/AppStateProvider.tsx+++ b/web/apps/space/src/state/AppStateProvider.tsx@@ -30,12 +30,14 @@ import {type RefreshSpaceProfileOptions,type SpaceAppState,SpaceAppStateContext,- type SpacePostPublishPhase,+ type SpacePostPublication,type SpaceProfileLoadStatus,initialFriends,} from "state/app-state";import { prepareSpacePostImageFromEdit } from "utils/post-image";+const postStatusDurationMs = 2000;+export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({children,}) => {@@ -62,8 +64,8 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({const [profileLoadError, setProfileLoadError] = useState<string>();const [profileLoadStatus, setProfileLoadStatus] =useState<SpaceProfileLoadStatus>("loading");- const [postPublishPhase, setPostPublishPhase] =- useState<SpacePostPublishPhase | null>(null);+ const [postPublication, setPostPublication] =+ useState<SpacePostPublication | null>(null);const [signupEmail, setSignupEmail] = useState("");const avatarURLRef = useRef<string | null>(null);const coverURLRef = useRef<string | null>(null);@@ -71,27 +73,61 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({const profileLoadGenerationRef = useRef(0);const postPublishGenerationRef = useRef(0);- const dismissPostPublishToast = useCallback(() => {- postPublishGenerationRef.current += 1;- setPostPublishPhase(null);- }, []);+ const postPreviewUrl = postPublication?.previewUrl;+ useEffect(+ () => () => {+ if (postPreviewUrl) URL.revokeObjectURL(postPreviewUrl);+ },+ [postPreviewUrl],+ );const publishPost = useCallback(async (image: Parameters<SpaceAppState["publishPost"]>[0],caption: string,) => {- const spaceId = profileRef.current?.spaceId;+ const profile = profileRef.current;+ const spaceId = profile?.spaceId;if (!spaceId) throw new Error("Missing space.");const generation = ++postPublishGenerationRef.current;- setPostPublishPhase("posting");+ let publication: SpacePostPublication = {+ phase: "posting",+ previewUrl: image.previewUrl,+ post: {+ caption: caption.trim() || undefined,+ friendID: spaceId,+ height: image.height,+ imageUrl: image.previewUrl,+ name: profile.fullName,+ postId: 0,+ spaceId,+ timestampMs: Date.now(),+ viewerLiked: false,+ width: image.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);+ }const post = await createCurrentPhotoPost({caption,file: preparedImage.file,@@ -101,12 +137,21 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({width: preparedImage.width,});if (postPublishGenerationRef.current == generation) {- setPostPublishPhase("posted");+ setPostPublication({+ ...publication,+ phase: "posted",+ post,+ statusExpiresAtMs: Date.now() + postStatusDurationMs,+ });}return post;} catch (error) {if (postPublishGenerationRef.current == generation) {- setPostPublishPhase("failed");+ setPostPublication({+ ...publication,+ phase: "failed",+ statusExpiresAtMs: Date.now() + postStatusDurationMs,+ });}throw error;}@@ -278,7 +323,8 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({applyProfile(null);setProfileLoadError(undefined);setProfileLoadStatus("ready");- dismissPostPublishToast();+ postPublishGenerationRef.current += 1;+ setPostPublication(null);setPendingLoginCredentials(null);setPendingPasskeyVerification(null);setPendingPostPhotoFile(null);@@ -287,7 +333,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({setPendingCreateProfile(null);setOnboardingEntrySource("direct");setFriends(initialFriends());- }, [applyProfile, dismissPostPublishToast]);+ }, [applyProfile]);useEffect(() => {void refreshProfile();@@ -305,13 +351,13 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({pendingProfileAvatarFile,pendingProfileCoverFile,pendingCreateProfile,- postPublishPhase,+ postPublication,profile,profileLoadError,profileLoadStatus,refreshProfile,resetAfterLogout,- dismissPostPublishToast,+ setPostPublication,publishPost,setFriends,setIsLiveSignupVerification,@@ -337,13 +383,12 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({pendingProfileAvatarFile,pendingProfileCoverFile,pendingCreateProfile,- postPublishPhase,+ postPublication,profile,profileLoadError,profileLoadStatus,refreshProfile,resetAfterLogout,- dismissPostPublishToast,publishPost,signupEmail,applyProfile,diff --git a/web/apps/space/src/state/app-state.tsx b/web/apps/space/src/state/app-state.tsxindex fb436e552c..f01b80bfc9 100644--- a/web/apps/space/src/state/app-state.tsx+++ b/web/apps/space/src/state/app-state.tsx@@ -13,6 +13,12 @@ import type { CreateProfileSource } from "utils/routes";export type OnboardingEntrySource = "direct" | "add-friend-link";export type SpaceProfileLoadStatus = "error" | "loading" | "ready";export type SpacePostPublishPhase = "failed" | "posted" | "posting";+export interface SpacePostPublication {+ phase: SpacePostPublishPhase;+ post: SpacePost;+ previewUrl: string;+ statusExpiresAtMs?: number;+}export type PendingCreateProfile = SetupProfileDetails & {source: CreateProfileSource;};@@ -35,9 +41,11 @@ export interface SpaceAppState {profile: SetupProfile | null;profileLoadError?: string;profileLoadStatus: SpaceProfileLoadStatus;- postPublishPhase: SpacePostPublishPhase | null;+ postPublication: SpacePostPublication | null;signupEmail: string;- dismissPostPublishToast: () => void;+ setPostPublication: React.Dispatch<+ React.SetStateAction<SpacePostPublication | null>+ >;publishPost: (image: SpaceDraftPostImage,caption: string,diff --git a/web/apps/space/src/styles/tiles.ts b/web/apps/space/src/styles/tiles.tsindex dd080e7a11..e9bcca13d8 100644--- a/web/apps/space/src/styles/tiles.ts+++ b/web/apps/space/src/styles/tiles.ts@@ -1,5 +1,8 @@export const spacePostTileRadius = 28;+export const spaceTileAvatarSize = (tile: { width: number; height: number }) =>+ Math.min(36, Math.min(tile.width, tile.height) * 0.22);+export const spaceTileCornerStyles = (radius: number) => ({"--space-tile-radius": `${radius}px`,"--space-tile-padding": `${radius / 2}px`,diff --git a/web/apps/space/src/utils/post-image.ts b/web/apps/space/src/utils/post-image.tsindex dc151f1f2a..e4c9834882 100644--- a/web/apps/space/src/utils/post-image.ts+++ b/web/apps/space/src/utils/post-image.ts@@ -37,7 +37,7 @@ export interface SpaceDraftPostImage {cropArea?: SpaceImageCropArea;file: File;height?: number;- previewUrl?: string;+ previewUrl: string;rotationDegrees?: number;width?: number;}diff --git a/web/apps/space/tests/post-cache.test.ts b/web/apps/space/tests/post-cache.test.tsnew file mode 100644index 0000000000..18eaecf3c4--- /dev/null+++ b/web/apps/space/tests/post-cache.test.ts@@ -0,0 +1,103 @@+import { savedPartialLocalUser } from "ente-accounts/services/accounts-db";+import { getKV, removeKV, setKV } from "ente-base/kv";+import { apiOrigin } from "ente-base/origins";+import { beforeEach, expect, test, vi } from "vitest";+import {+ cacheOwnLatestPost,+ loadCachedOwnLatestPost,+ patchCachedOwnLatestPost,+} from "../src/services/post-cache";+import type { SpacePost } from "../src/services/space";++vi.mock("ente-accounts/services/accounts-db", () => ({+ savedPartialLocalUser: vi.fn(),+}));+vi.mock("ente-base/kv", () => ({+ getKV: vi.fn(),+ setKV: vi.fn(),+ removeKV: vi.fn(),+}));+vi.mock("ente-base/log", () => ({ default: { warn: vi.fn() } }));+vi.mock("ente-base/origins", () => ({ apiOrigin: vi.fn() }));++const storage = new Map<string, unknown>();+const post: SpacePost = {+ avatarUrl: "blob:avatar",+ caption: "A photo",+ friendID: "self",+ imageAsset: {+ encryptedPostKey: "encrypted-key",+ keyVersion: 1,+ objectKey: "photo",+ postId: 1,+ spaceId: "self",+ },+ imageUrl: "blob:photo",+ name: "Me",+ postId: 1,+ spaceId: "self",+ thumbHash: "3OcRJYB4d3h/iIeHeEh3eIhw+j3A",+ timestampMs: 1,+ viewerLiked: false,+};++beforeEach(() => {+ vi.resetAllMocks();+ storage.clear();+ vi.mocked(savedPartialLocalUser).mockReturnValue({ id: 1 });+ vi.mocked(apiOrigin).mockResolvedValue("https://api.example.com");+ vi.mocked(getKV).mockImplementation((key) =>+ Promise.resolve(storage.get(key)),+ );+ vi.mocked(setKV).mockImplementation((key, value) => {+ storage.set(key, structuredClone(value));+ return Promise.resolve();+ });+ vi.mocked(removeKV).mockImplementation((key) => {+ storage.delete(key);+ return Promise.resolve();+ });+});++test("restores the hash and image asset without expired blob URLs", async () => {+ await cacheOwnLatestPost("self", post);+ const restored = await loadCachedOwnLatestPost("self");+ expect(restored?.thumbHash).toBe(post.thumbHash);+ expect(restored?.imageAsset).toEqual(post.imageAsset);+ expect(restored).not.toHaveProperty("imageUrl");+ expect(restored).not.toHaveProperty("avatarUrl");+});++test("keeps previews separate across spaces, accounts, and servers", async () => {+ await cacheOwnLatestPost("self", post);+ expect(await loadCachedOwnLatestPost("another-space")).toBeUndefined();+ vi.mocked(savedPartialLocalUser).mockReturnValue({ id: 2 });+ expect(await loadCachedOwnLatestPost("self")).toBeUndefined();+ vi.mocked(savedPartialLocalUser).mockReturnValue({ id: 1 });+ vi.mocked(apiOrigin).mockResolvedValue("https://other.example.com");+ expect(await loadCachedOwnLatestPost("self")).toBeUndefined();+});++test("updates captions and removes deleted posts without clearing newer posts", async () => {+ await cacheOwnLatestPost("self", post);+ await patchCachedOwnLatestPost("self", 1, { caption: "Edited" });+ expect((await loadCachedOwnLatestPost("self"))?.caption).toBe("Edited");+ await cacheOwnLatestPost("self", { ...post, postId: 2 });+ await patchCachedOwnLatestPost("self", 1, undefined);+ expect((await loadCachedOwnLatestPost("self"))?.postId).toBe(2);+ await patchCachedOwnLatestPost("self", 2, undefined);+ expect(await loadCachedOwnLatestPost("self")).toBeUndefined();+});++test("clears the preview when the refreshed profile has no posts", async () => {+ await cacheOwnLatestPost("self", post);+ await cacheOwnLatestPost("self", undefined);+ expect(await loadCachedOwnLatestPost("self")).toBeUndefined();+});++test("a cache failure does not fail the post operation", async () => {+ vi.mocked(setKV).mockRejectedValue(new Error("Storage unavailable"));+ await expect(cacheOwnLatestPost("self", post)).resolves.toBeUndefined();+ vi.mocked(getKV).mockRejectedValue(new Error("Storage unavailable"));+ await expect(loadCachedOwnLatestPost("self")).resolves.toBeUndefined();+});