Skip to content

armgit / ente

Public Imported from GitHub
0

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

Refresh Space feed layout and black theme

Anand Baburajane4767022c99c
diff --git a/web/apps/space/public/manifest-public.webmanifest b/web/apps/space/public/manifest-public.webmanifest
index 18ec79a62d..15ecf8277c 100644
--- a/web/apps/space/public/manifest-public.webmanifest
+++ b/web/apps/space/public/manifest-public.webmanifest
@@ -5,8 +5,8 @@
"id": "/app",
"scope": "/",
"display": "standalone",
- "background_color": "#08C225",
- "theme_color": "#1C1C1E",
+ "background_color": "#000000",
+ "theme_color": "#000000",
"icons": [
{
"src": "/images/pwa-icon-192.png",
diff --git a/web/apps/space/public/manifest.webmanifest b/web/apps/space/public/manifest.webmanifest
index 76317704b7..888024ffdd 100644
--- a/web/apps/space/public/manifest.webmanifest
+++ b/web/apps/space/public/manifest.webmanifest
@@ -6,8 +6,8 @@
"start_url": "/app",
"scope": "/",
"display": "standalone",
- "background_color": "#08C225",
- "theme_color": "#1C1C1E",
+ "background_color": "#000000",
+ "theme_color": "#000000",
"icons": [
{
"src": "/images/pwa-icon-192.png",
diff --git a/web/apps/space/src/components/CaptionText.tsx b/web/apps/space/src/components/CaptionText.tsx
index 9be5d01306..c460b9b382 100644
--- a/web/apps/space/src/components/CaptionText.tsx
+++ b/web/apps/space/src/components/CaptionText.tsx
@@ -1,6 +1,7 @@
import { Box } from "@mui/material";
import { visuallyHidden } from "@mui/utils";
import React from "react";
+import { spaceSurface } from "styles/colors";
const captionBubbleSx = {
borderRadius: "5px",
@@ -104,7 +105,7 @@ export const SpaceCaptionText: React.FC<{
>
<Box
component="span"
- sx={{ ...captionBubbleSx, bgcolor: "#202020" }}
+ sx={{ ...captionBubbleSx, bgcolor: spaceSurface }}
>
<Box component="span" sx={{ opacity: 0 }}>
{displayCaption}
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsx
index ffc70e212a..a3377f8304 100644
--- a/web/apps/space/src/components/FileViewer.tsx
+++ b/web/apps/space/src/components/FileViewer.tsx
@@ -36,19 +36,26 @@ import type {
SpacePostAssetURLLoader,
SpacePostVideo,
} from "services/space";
-import { spaceDialogBackground, spaceTextMuted } from "styles/colors";
+import {
+ spaceControlBackground,
+ spaceControlBackgroundHover,
+ spaceDialogBackground,
+ spaceMenuBackground,
+ spaceText,
+ spaceTextMuted,
+} from "styles/colors";
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom, formatSpaceDate } from "utils/display";
import { clampSpaceMessageText } from "utils/message-limits";
const green = "#08C225";
-const textBase = "#F4F4F4";
-const textSecondary = "#A6A6A6";
+const textBase = spaceText;
+const textSecondary = spaceTextMuted;
const textTertiary = "rgba(244, 244, 244, 0.52)";
const viewerBackground = "#000000";
-const inputBackground = "rgba(58, 58, 58, 0.86)";
-const inputBackgroundActive = "rgba(72, 72, 72, 0.9)";
-const controlIcon = "#D8D8D8";
+const inputBackground = spaceControlBackground;
+const inputBackgroundActive = spaceControlBackgroundHover;
+const controlIcon = spaceText;
const dangerColor = "#F63A3A";
const viewerHeaderHeight = 56;
const viewerBottomPadding = 88;
@@ -256,7 +263,7 @@ const draftHeaderButtonSx = {
const draftHeaderButtonContentSx = {
alignItems: "center",
- bgcolor: "#242424",
+ bgcolor: spaceControlBackground,
borderRadius: "999px",
display: "flex",
gap: "6px",
@@ -1428,7 +1435,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
zIndex: 1300,
"& .space-photo-placeholder": {
alignItems: "center",
- color: "#A6A6A6",
+ color: spaceTextMuted,
display: "flex",
height: "100%",
width: isDraftPost ? "100vw" : "100%",
@@ -1753,7 +1760,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
slotProps={{
paper: {
sx: {
- bgcolor: "#1E1E1E",
+ bgcolor: spaceMenuBackground,
borderRadius: "14px",
boxShadow:
"0 14px 40px rgba(0, 0, 0, 0.16)",
diff --git a/web/apps/space/src/components/HomeHeader.tsx b/web/apps/space/src/components/HomeHeader.tsx
index d264d022a0..a1e70d3509 100644
--- a/web/apps/space/src/components/HomeHeader.tsx
+++ b/web/apps/space/src/components/HomeHeader.tsx
@@ -14,7 +14,6 @@ import { spaceTouchTargetSize } from "styles/touch-targets";
const green = "#08C225";
const dangerColor = "#F63A3A";
-const headerBackground = "#2C2C2E";
const headerActionSize = spaceTouchTargetSize;
const headerAvatarImageSize = 28;
const headerChatCircleSize = 36;
@@ -65,7 +64,7 @@ export const SpaceHomeHeader: React.FC<SpaceHomeHeaderProps> = ({
width: "100%",
zIndex: 4,
"&::after": {
- bgcolor: headerBackground,
+ bgcolor: spaceSurface,
borderRadius: "16px",
content: '""',
height: spaceHomeHeaderBarHeight,
@@ -233,7 +232,7 @@ export const SpaceHomeHeader: React.FC<SpaceHomeHeaderProps> = ({
"&::after": { display: "none" },
},
bgcolor: dangerColor,
- border: `2px solid ${headerBackground}`,
+ border: `2px solid ${spaceSurface}`,
borderRadius: "50%",
boxSizing: "border-box",
height: 12.5,
diff --git a/web/apps/space/src/components/PostAvatar.tsx b/web/apps/space/src/components/PostAvatar.tsx
new file mode 100644
index 0000000000..981068d32f
--- /dev/null
+++ b/web/apps/space/src/components/PostAvatar.tsx
@@ -0,0 +1,60 @@
+import { Box } from "@mui/material";
+import { SpaceAvatarImage } from "components/AvatarImage";
+import React from "react";
+
+interface SpacePostAvatarProps {
+ ready: boolean;
+ size: number;
+ src?: string | null;
+}
+
+export const SpacePostAvatar: React.FC<SpacePostAvatarProps> = ({
+ ready,
+ size,
+ src,
+}) => (
+ <Box
+ sx={{
+ bgcolor: "rgba(255, 255, 255, 0.2)",
+ borderRadius: "50%",
+ flexShrink: 0,
+ height: size,
+ position: "relative",
+ width: size,
+ }}
+ >
+ {ready && (
+ <Box
+ key={src ?? "default-avatar"}
+ sx={{
+ "@keyframes spaceAvatarFade": {
+ from: { opacity: 0 },
+ to: { opacity: 1 },
+ },
+ animation:
+ "spaceAvatarFade 320ms cubic-bezier(0.22, 1, 0.36, 1) both",
+ borderRadius: "50%",
+ height: "100%",
+ overflow: "hidden",
+ width: "100%",
+ "@media (prefers-reduced-motion: reduce)": {
+ animation: "none",
+ },
+ }}
+ >
+ <SpaceAvatarImage src={src} borderRadius="50%" />
+ </Box>
+ )}
+ <Box
+ aria-hidden
+ sx={{
+ border: "1px solid rgba(255, 255, 255, 0.16)",
+ borderRadius: "50%",
+ boxShadow: "0 1px 4px rgba(0, 0, 0, 0.24)",
+ inset: 0,
+ pointerEvents: "none",
+ position: "absolute",
+ }}
+ />
+ </Box>
+);
diff --git a/web/apps/space/src/components/PostGrid.tsx b/web/apps/space/src/components/PostGrid.tsx
new file mode 100644
index 0000000000..2a73965cad
--- /dev/null
+++ b/web/apps/space/src/components/PostGrid.tsx
@@ -0,0 +1,102 @@
+import { Box } from "@mui/material";
+import React from "react";
+import { postPhotoLayout, profilePhotoGap } from "utils/profile-photo-layout";
+
+interface PostGridItem {
+ id: string;
+ width?: number;
+ height?: number;
+ frameAspectRatio?: number;
+}
+
+export const SpacePostGrid = <Item extends PostGridItem>({
+ items,
+ postCount,
+ renderTile,
+}: {
+ items: Item[];
+ postCount?: number;
+ renderTile: (
+ item: Item,
+ index: number,
+ flexGrow: number,
+ ) => React.ReactNode;
+}) => {
+ const [width, setWidth] = React.useState(0);
+ const [previousLayout, setLayout] = React.useState(() => ({
+ ...postPhotoLayout([], 0),
+ items,
+ postCount,
+ }));
+ const gridRef = React.useRef<HTMLDivElement | null>(null);
+ React.useLayoutEffect(() => {
+ const grid = gridRef.current!;
+ const observer = new ResizeObserver(([entry]) =>
+ setWidth(entry!.contentRect.width),
+ );
+ setWidth(grid.getBoundingClientRect().width);
+ observer.observe(grid);
+ return () => observer.disconnect();
+ }, []);
+
+ const layout =
+ previousLayout.items == items &&
+ previousLayout.width == width &&
+ previousLayout.postCount == postCount
+ ? previousLayout
+ : {
+ ...postPhotoLayout(
+ items.map((item) => ({
+ id: item.id,
+ aspectRatio:
+ item.frameAspectRatio ??
+ (item.width && item.height
+ ? item.width / item.height
+ : 1),
+ })),
+ width,
+ previousLayout,
+ postCount,
+ ),
+ items,
+ postCount,
+ };
+ if (layout != previousLayout) setLayout(layout);
+
+ const itemsByID = new Map(
+ items.map((item, index) => [item.id, { item, index }]),
+ );
+
+ return (
+ <Box
+ ref={gridRef}
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ gap: `${profilePhotoGap}px`,
+ }}
+ >
+ {layout.rows.map((row) => (
+ <Box
+ key={row.tiles[0]!.id}
+ sx={{
+ display: "flex",
+ flexShrink: 0,
+ gap: `${profilePhotoGap}px`,
+ height: row.height,
+ width: row.width,
+ }}
+ >
+ {row.tiles.map(({ id, aspectRatio }) => {
+ const { item, index } = itemsByID.get(id)!;
+ return renderTile(
+ item,
+ index,
+ aspectRatio / row.aspectRatio,
+ );
+ })}
+ </Box>
+ ))}
+ </Box>
+ );
+};
diff --git a/web/apps/space/src/components/PostPhotoEditor.tsx b/web/apps/space/src/components/PostPhotoEditor.tsx
index 3df7625fe0..4cd4a0122f 100644
--- a/web/apps/space/src/components/PostPhotoEditor.tsx
+++ b/web/apps/space/src/components/PostPhotoEditor.tsx
@@ -15,6 +15,13 @@ import {
import log from "ente-base/log";
import { useBrowserBackClose } from "hooks/use-browser-back-close";
import React from "react";
+import {
+ spaceControlBackground,
+ spaceControlBackgroundHover,
+ spaceSurface,
+ spaceText,
+ spaceTextMuted,
+} from "styles/colors";
import {
spacePostPreviewImageFromEdit,
type SpacePostPhotoEdit,
@@ -219,7 +226,7 @@ export const SpacePostPhotoEditor: React.FC<{
paper: {
sx: {
bgcolor: "#000000",
- color: "#F2F2F2",
+ color: spaceText,
backgroundImage: "none",
height: "100dvh",
fontFamily: '"Inter Variable", Inter, sans-serif',
@@ -261,7 +268,7 @@ export const SpacePostPhotoEditor: React.FC<{
component="span"
sx={{
alignItems: "center",
- bgcolor: "#242424",
+ bgcolor: spaceControlBackground,
borderRadius: "50%",
color: "#E4E4E4",
display: "flex",
@@ -442,7 +449,7 @@ export const SpacePostPhotoEditor: React.FC<{
: undefined,
});
}}
- sx={{ ...buttonSx, bgcolor: "#1C1C1E", p: 0 }}
+ sx={{ ...buttonSx, bgcolor: spaceSurface, p: 0 }}
>
<HugeiconsIcon
icon={RotateTopRightIcon}
@@ -456,7 +463,7 @@ export const SpacePostPhotoEditor: React.FC<{
sx={{
position: "relative",
display: "flex",
- bgcolor: "#1C1C1E",
+ bgcolor: spaceSurface,
borderRadius: "999px",
px: "4px",
}}
@@ -470,7 +477,7 @@ export const SpacePostPhotoEditor: React.FC<{
bottom: 4,
left: 4,
width: `calc((100% - 8px) / ${aspects.length})`,
- bgcolor: "#3A3A3C",
+ bgcolor: spaceControlBackgroundHover,
borderRadius: "999px",
pointerEvents: "none",
transform: `translateX(${aspectIndex * 100}%)`,
@@ -510,7 +517,7 @@ export const SpacePostPhotoEditor: React.FC<{
color:
edit.aspect == value
? "#FFFFFF"
- : "#A6A6A6",
+ : spaceTextMuted,
}}
>
{label}
@@ -525,7 +532,7 @@ export const SpacePostPhotoEditor: React.FC<{
onClick={() => updateEdit(originalEdit)}
sx={{
...buttonSx,
- bgcolor: "#1C1C1E",
+ bgcolor: spaceSurface,
fontSize: 13,
px: "16px",
py: 0,
diff --git a/web/apps/space/src/components/PostPhotoStrip.tsx b/web/apps/space/src/components/PostPhotoStrip.tsx
index a41db279a5..eacb142a14 100644
--- a/web/apps/space/src/components/PostPhotoStrip.tsx
+++ b/web/apps/space/src/components/PostPhotoStrip.tsx
@@ -4,6 +4,11 @@ import { Box, Skeleton } from "@mui/material";
import { keyframes } from "@mui/material/styles";
import { SpacePostVideoBadge } from "components/PostPhotosBadge";
import React from "react";
+import {
+ spaceControlBackground,
+ spaceControlBackgroundHover,
+ spaceText,
+} from "styles/colors";
import { maxSpacePostPhotos, movePostPhoto } from "utils/post-photos";
interface StripPhoto {
@@ -32,7 +37,7 @@ const iconButtonSx = {
alignItems: "center",
background: "none",
border: 0,
- color: "#D8D8D8",
+ color: spaceText,
cursor: "pointer",
display: "flex",
justifyContent: "center",
@@ -253,7 +258,11 @@ export const SpacePostPhotoStrip: React.FC<{
<Skeleton
animation="wave"
variant="rectangular"
- sx={{ width: "100%", height: "100%", bgcolor: "#242424" }}
+ sx={{
+ width: "100%",
+ height: "100%",
+ bgcolor: spaceControlBackground,
+ }}
/>
)}
<SpacePostVideoBadge durationMs={photo.durationMs} size={12} />
@@ -359,7 +368,7 @@ export const SpacePostPhotoStrip: React.FC<{
}}
sx={{
...iconButtonSx,
- bgcolor: "#242424",
+ bgcolor: spaceControlBackground,
outline:
photo.id ==
photos[activeIndex]?.id
@@ -407,7 +416,8 @@ export const SpacePostPhotoStrip: React.FC<{
component="span"
sx={{
alignItems: "center",
- bgcolor: "#3A3A3A",
+ bgcolor:
+ spaceControlBackgroundHover,
border: "1px solid #000000",
borderRadius: "50%",
display: "flex",
@@ -436,7 +446,7 @@ export const SpacePostPhotoStrip: React.FC<{
onClick={onAdd}
sx={{
...iconButtonSx,
- bgcolor: "#242424",
+ bgcolor: spaceControlBackground,
borderRadius: "9px",
flexShrink: 0,
width: photoSize,
@@ -490,7 +500,7 @@ export const SpacePostPhotoStrip: React.FC<{
borderRadius: "9px",
outline: "1.5px solid #FFFFFF",
outlineOffset: "-1.5px",
- bgcolor: "#242424",
+ bgcolor: spaceControlBackground,
overflow: "hidden",
boxShadow: "0 4px 12px #00000088",
transform: "scale(1.04)",
diff --git a/web/apps/space/src/components/PostReplyControls.tsx b/web/apps/space/src/components/PostReplyControls.tsx
index d9e2021f58..286f7b2303 100644
--- a/web/apps/space/src/components/PostReplyControls.tsx
+++ b/web/apps/space/src/components/PostReplyControls.tsx
@@ -15,14 +15,21 @@ import {
spacePostLikePopTiming,
} from "components/post-like-animation";
import React from "react";
+import {
+ spaceControlBackground,
+ spaceControlBackgroundHover,
+ spaceMenuHover,
+ spaceText,
+ spaceTextMuted,
+} from "styles/colors";
const green = "#08C225";
-const textBase = "#F4F4F4";
-const textSecondary = "#A6A6A6";
-const controlBackground = "#242424";
-const controlBackgroundHover = "#2E2E2E";
-const controlBackgroundActive = "#383838";
-const controlIcon = "#D8D8D8";
+const textBase = spaceText;
+const textSecondary = spaceTextMuted;
+const controlBackground = spaceControlBackground;
+const controlBackgroundHover = spaceControlBackgroundHover;
+const controlBackgroundActive = spaceMenuHover;
+const controlIcon = spaceText;
const spacePostReplyInputMinHeight = 48;
const replyInputPadding = 14;
const replyInputPaddingLeft = 18;
diff --git a/web/apps/space/src/components/PostTile.tsx b/web/apps/space/src/components/PostTile.tsx
new file mode 100644
index 0000000000..060acc1843
--- /dev/null
+++ b/web/apps/space/src/components/PostTile.tsx
@@ -0,0 +1,301 @@
+import { Box } from "@mui/material";
+import { SpacePostAvatar } from "components/PostAvatar";
+import {
+ SpacePostPhotosBadge,
+ SpacePostVideoBadge,
+} from "components/PostPhotosBadge";
+import log from "ente-base/log";
+import { useDecodedImage } from "hooks/use-decoded-image";
+import React from "react";
+import type { SpacePostAsset, SpacePostPhoto } from "services/space";
+import { spaceSurface, spaceTextMuted } from "styles/colors";
+import { spaceProfilePostRadius } from "styles/tiles";
+import { spaceTouchTargetSize } from "styles/touch-targets";
+import { thumbHashDataURLFromBase64 } from "utils/thumbhash";
+
+const green = "#08C225";
+
+export interface SpacePostTileItem {
+ avatarUrl?: string | null;
+ caption?: string;
+ friendID?: string;
+ height?: number;
+ id: string;
+ imageAsset?: SpacePostAsset;
+ imageUrl?: string;
+ photos?: SpacePostPhoto[];
+ isUnavailable?: boolean;
+ name?: string;
+ postId?: number;
+ spaceId?: string;
+ timestampMs: number;
+ thumbHash?: string;
+ viewerLiked?: boolean;
+ width?: number;
+}
+
+interface SpacePostTileProps {
+ displayName: string;
+ showAvatar?: boolean;
+ onLoadAvatar?: () => Promise<string | null>;
+ flexGrow: number;
+ imageUrl?: string;
+ index: number;
+ isAvatarPending?: boolean;
+ isUnavailable: boolean;
+ item: SpacePostTileItem;
+ loadRootMargin: string;
+ onImageDecodeError: () => void;
+ onLoadImage: () => Promise<string | undefined>;
+ onOpen: (imageUrl: string) => void;
+ onOpenProfile?: () => void;
+ onRememberDimensions?: (itemID: string, image: HTMLImageElement) => void;
+}
+
+export const SpacePostTile: React.FC<SpacePostTileProps> = ({
+ displayName,
+ showAvatar = false,
+ onLoadAvatar,
+ flexGrow,
+ imageUrl,
+ index,
+ isAvatarPending = false,
+ isUnavailable: isPostUnavailable,
+ item,
+ loadRootMargin,
+ onImageDecodeError,
+ onLoadImage,
+ onOpen,
+ onOpenProfile,
+ onRememberDimensions,
+}) => {
+ const [shouldLoad, setShouldLoad] = React.useState(Boolean(imageUrl));
+ const [readyImageUrl, setReadyImageUrl] = React.useState<string>();
+ const [imageDecodeFailed, setImageDecodeFailed] = React.useState(false);
+ const decodedAvatar = useDecodedImage(
+ showAvatar ? item.avatarUrl : undefined,
+ true,
+ );
+ const tileRef = React.useRef<HTMLButtonElement | null>(null);
+ const thumbHashDataURL = React.useMemo(
+ () => thumbHashDataURLFromBase64(item.thumbHash),
+ [item.thumbHash],
+ );
+ const isCurrentImageReady = Boolean(imageUrl && readyImageUrl == imageUrl);
+ const isUnavailable = isPostUnavailable || imageDecodeFailed;
+ const photoCount = item.photos?.length ?? 1;
+
+ React.useEffect(() => {
+ if (imageUrl) setShouldLoad(true);
+ }, [imageUrl]);
+
+ React.useEffect(() => {
+ if (isUnavailable) return;
+ if (shouldLoad || imageUrl) return;
+ const element = tileRef.current;
+ if (!element) return;
+ if (
+ typeof window == "undefined" ||
+ !("IntersectionObserver" in window)
+ ) {
+ setShouldLoad(true);
+ return;
+ }
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ setShouldLoad(true);
+ observer.disconnect();
+ }
+ },
+ { rootMargin: loadRootMargin },
+ );
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [imageUrl, isUnavailable, loadRootMargin, shouldLoad]);
+
+ React.useEffect(() => {
+ if (isUnavailable) return;
+ if (!shouldLoad || imageUrl) return;
+ void onLoadImage().catch((error: unknown) => {
+ log.warn("Failed to load profile post image", error);
+ });
+ }, [imageUrl, isUnavailable, onLoadImage, shouldLoad]);
+
+ React.useEffect(() => {
+ if (shouldLoad && !isUnavailable) void onLoadAvatar?.();
+ }, [isUnavailable, onLoadAvatar, shouldLoad]);
+
+ return (
+ <Box
+ sx={{
+ bgcolor: spaceSurface,
+ borderRadius: `${spaceProfilePostRadius}px`,
+ flex: `${flexGrow} 1 0px`,
+ height: "100%",
+ minWidth: 0,
+ overflow: "hidden",
+ position: "relative",
+ }}
+ >
+ <Box
+ ref={tileRef}
+ component="button"
+ type="button"
+ aria-label={
+ isUnavailable
+ ? "Post unavailable"
+ : `Open ${displayName} post ${index + 1}${
+ photoCount > 1 ? `, ${photoCount} photos` : ""
+ }`
+ }
+ disabled={!imageUrl || isUnavailable}
+ onClick={() => {
+ if (imageUrl && !isUnavailable) onOpen(imageUrl);
+ }}
+ sx={{
+ appearance: "none",
+ bgcolor: spaceSurface,
+ border: 0,
+ borderRadius: `${spaceProfilePostRadius}px`,
+ cursor: imageUrl && !isUnavailable ? "pointer" : "default",
+ display: "block",
+ height: "100%",
+ minWidth: 0,
+ opacity: 1,
+ overflow: "hidden",
+ p: 0,
+ position: "relative",
+ width: "100%",
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: -2,
+ },
+ }}
+ >
+ {!isUnavailable && thumbHashDataURL ? (
+ <Box
+ component="img"
+ alt=""
+ aria-hidden
+ src={thumbHashDataURL}
+ sx={{
+ display: "block",
+ filter: "blur(14px)",
+ height: "100%",
+ inset: 0,
+ objectFit: "cover",
+ objectPosition: "center",
+ position: "absolute",
+ transform: "scale(1.08)",
+ width: "100%",
+ }}
+ />
+ ) : null}
+ {!isUnavailable && imageUrl ? (
+ <Box
+ component="img"
+ alt={`${displayName} post ${index + 1}`}
+ onLoad={(event) => {
+ setReadyImageUrl(imageUrl);
+ onRememberDimensions?.(
+ item.id,
+ event.currentTarget,
+ );
+ }}
+ onError={() => {
+ log.warn(
+ `Post ${item.postId} is unavailable because the browser could not decode its image`,
+ );
+ setImageDecodeFailed(true);
+ onImageDecodeError();
+ }}
+ src={imageUrl}
+ sx={{
+ display: "block",
+ height: "100%",
+ inset: 0,
+ objectFit: "cover",
+ objectPosition: "center",
+ opacity:
+ isCurrentImageReady || !thumbHashDataURL
+ ? 1
+ : 0,
+ position: "absolute",
+ transition: thumbHashDataURL
+ ? "opacity 220ms ease"
+ : "none",
+ width: "100%",
+ "@media (prefers-reduced-motion: reduce)": {
+ opacity: 1,
+ transition: "none",
+ },
+ }}
+ />
+ ) : null}
+ {!isUnavailable && (
+ <>
+ <SpacePostPhotosBadge count={photoCount} inset={8} />
+ <SpacePostVideoBadge
+ durationMs={item.photos?.[0]?.video?.durationMs}
+ size={18}
+ />
+ </>
+ )}
+ {isUnavailable && (
+ <Box
+ sx={{
+ alignItems: "center",
+ color: spaceTextMuted,
+ display: "flex",
+ fontSize: 12,
+ fontWeight: 600,
+ height: "100%",
+ justifyContent: "center",
+ width: "100%",
+ }}
+ >
+ Post unavailable
+ </Box>
+ )}
+ </Box>
+ {showAvatar && (
+ <Box
+ component="button"
+ type="button"
+ aria-label={`Open ${displayName}'s profile`}
+ disabled={!onOpenProfile}
+ onClick={onOpenProfile}
+ sx={{
+ alignItems: "flex-end",
+ appearance: "none",
+ bgcolor: "transparent",
+ border: 0,
+ borderRadius: "50%",
+ bottom: 0,
+ cursor: onOpenProfile ? "pointer" : "default",
+ display: "flex",
+ height: spaceTouchTargetSize,
+ left: 0,
+ p: "0 0 8px 8px",
+ position: "absolute",
+ width: spaceTouchTargetSize,
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: -2,
+ },
+ }}
+ >
+ <SpacePostAvatar
+ ready={!isAvatarPending && decodedAvatar.ready}
+ size={22}
+ src={
+ decodedAvatar.failed ? undefined : decodedAvatar.src
+ }
+ />
+ </Box>
+ )}
+ </Box>
+ );
+};
diff --git a/web/apps/space/src/components/PostVideoEditor.tsx b/web/apps/space/src/components/PostVideoEditor.tsx
index 2eed1c0842..0f1b431bb4 100644
--- a/web/apps/space/src/components/PostVideoEditor.tsx
+++ b/web/apps/space/src/components/PostVideoEditor.tsx
@@ -7,6 +7,12 @@ import {
} from "components/video-trim/geometry";
import { createVideoTrimPlayback } from "components/video-trim/playback";
import React from "react";
+import {
+ spaceControlBackgroundHover,
+ spaceSurface,
+ spaceText,
+ spaceTextMuted,
+} from "styles/colors";
import {
clampVideoCover,
initialSpaceVideoEdit,
@@ -17,10 +23,10 @@ import {
const control = {
alignItems: "center",
- bgcolor: "#1C1C1E",
+ bgcolor: spaceSurface,
border: 0,
borderRadius: "999px",
- color: "#F2F2F2",
+ color: spaceText,
cursor: "pointer",
display: "inline-flex",
font: "inherit",
@@ -393,7 +399,7 @@ export const SpacePostVideoEditor: React.FC<{
sx={{
height: 64,
position: "relative",
- bgcolor: "#1C1C1E",
+ bgcolor: spaceSurface,
borderRadius: "8px",
touchAction: "none",
userSelect: "none",
@@ -572,7 +578,7 @@ export const SpacePostVideoEditor: React.FC<{
sx={{
position: "relative",
display: "flex",
- bgcolor: "#1C1C1E",
+ bgcolor: spaceSurface,
borderRadius: "999px",
px: "4px",
}}
@@ -585,7 +591,7 @@ export const SpacePostVideoEditor: React.FC<{
bottom: 4,
left: 4,
width: "calc((100% - 8px) / 2)",
- bgcolor: "#3A3A3C",
+ bgcolor: spaceControlBackgroundHover,
borderRadius: "999px",
pointerEvents: "none",
transform: `translateX(${mode == "trim" ? 0 : 100}%)`,
@@ -610,7 +616,9 @@ export const SpacePostVideoEditor: React.FC<{
p: 0,
bgcolor: "transparent",
color:
- mode == value ? "#FFFFFF" : "#A6A6A6",
+ mode == value
+ ? "#FFFFFF"
+ : spaceTextMuted,
}}
>
{value == "trim" ? "Trim" : "Cover"}
diff --git a/web/apps/space/src/hooks/use-decoded-image.ts b/web/apps/space/src/hooks/use-decoded-image.ts
new file mode 100644
index 0000000000..e9b802dc03
--- /dev/null
+++ b/web/apps/space/src/hooks/use-decoded-image.ts
@@ -0,0 +1,72 @@
+import { useEffect, useState } from "react";
+
+interface DecodedImageState {
+ failed?: boolean;
+ height?: number;
+ ready: boolean;
+ src?: string | null;
+ width?: number;
+}
+
+export const useDecodedImage = (
+ src?: string | null,
+ keepPreviousUntilReady = false,
+): DecodedImageState => {
+ const [state, setState] = useState<DecodedImageState>({ ready: !src, src });
+
+ useEffect(() => {
+ if (!src) {
+ setState({ ready: true, src });
+ return;
+ }
+
+ let cancelled = false;
+ const image = new Image();
+
+ const finish = () => {
+ if (cancelled) return;
+
+ setState({
+ height: image.naturalHeight || undefined,
+ ready: true,
+ src,
+ width: image.naturalWidth || undefined,
+ });
+ };
+ const fail = () => {
+ if (cancelled) return;
+ setState({ failed: true, ready: true, src });
+ };
+ const decodeLoadedImage = () => {
+ if (typeof image.decode != "function") {
+ finish();
+ return;
+ }
+
+ void image.decode().then(finish, fail);
+ };
+
+ setState((currentState) =>
+ keepPreviousUntilReady && currentState.ready && currentState.src
+ ? currentState
+ : { ready: false, src },
+ );
+ image.addEventListener("load", decodeLoadedImage, { once: true });
+ image.addEventListener("error", fail, { once: true });
+ image.src = src;
+ if (image.complete) {
+ if (image.naturalWidth) decodeLoadedImage();
+ else fail();
+ }
+
+ return () => {
+ cancelled = true;
+ image.removeEventListener("load", decodeLoadedImage);
+ image.removeEventListener("error", fail);
+ };
+ }, [keepPreviousUntilReady, src]);
+
+ if (state.src == src) return state;
+ if (keepPreviousUntilReady && src && state.ready && state.src) return state;
+ return { ready: !src, src };
+};
diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsx
index 2ed948a4cb..50b8f2f59f 100644
--- a/web/apps/space/src/pages/app/index.tsx
+++ b/web/apps/space/src/pages/app/index.tsx
@@ -7,6 +7,10 @@ import { HomeScreen } from "screens/HomeScreen";
import {
cacheCurrentSpaceFeedPage,
loadCachedSpaceFeed,
+ loadSpaceFeedSession,
+ rememberSpaceFeedSessionPosts,
+ spaceFeedSessionItems,
+ type SpaceFeedSession,
} from "services/feed-cache";
import { consumeSentSpaceInviteFriend, spaceInviteURL } from "services/invite";
import { savedSpaceOwnedSpaces } from "services/persistent-session";
@@ -53,11 +57,13 @@ const Page: React.FC = () => {
[],
);
const [feedItems, setFeedItems] = useState<SpacePost[]>([]);
+ const [feedSession, setFeedSession] = useState<SpaceFeedSession>();
const [hasFeedLoadMoreError, setHasFeedLoadMoreError] = useState(false);
const [feedNextCursor, setFeedNextCursor] = useState<string>();
const [hasUnreadMessages, setHasUnreadMessages] = useState<boolean>();
const [hasOwnPosts, setHasOwnPosts] = useState<boolean>();
const [isFeedLoading, setIsFeedLoading] = useState(true);
+ const [isFeedComplete, setIsFeedComplete] = useState(false);
const [isFeedLoadingMore, setIsFeedLoadingMore] = useState(false);
const [isFriendsLoading, setIsFriendsLoading] = useState(true);
const [spaceId, setSpaceId] = useState<string>();
@@ -134,24 +140,39 @@ const Page: React.FC = () => {
const isCancelled = () => request.cancelled;
let loadedSpaceId: string | undefined;
let cachedFeedSyncedAtMs: number | undefined;
+ let loadedFeedSession: SpaceFeedSession | undefined;
setSpaceId(undefined);
setFeedItems([]);
+ setFeedSession(undefined);
setHasFeedLoadMoreError(false);
setFeedNextCursor(undefined);
setHasUnreadMessages(undefined);
setIsFeedLoading(true);
+ setIsFeedComplete(false);
setIsFeedLoadingMore(false);
setIsFriendsLoading(true);
void (async () => {
const savedSpaceId = savedSpaceOwnedSpaces()?.[0]?.spaceId;
const loadCache = async (spaceId: string) => {
+ const session = await loadSpaceFeedSession(spaceId);
const cachedFeed = await loadCachedSpaceFeed(spaceId);
if (isCancelled()) return;
+ loadedFeedSession = session;
+ setFeedSession(session);
cachedFeedSyncedAtMs = cachedFeed?.syncedAtMs;
- setFeedItems(cachedFeed?.items ?? []);
+ setFeedItems(
+ spaceFeedSessionItems(session, cachedFeed?.items ?? []),
+ );
setFeedNextCursor(
cachedFeed?.dirty ? undefined : cachedFeed?.nextCursor,
);
+ setIsFeedComplete(
+ Boolean(
+ cachedFeed &&
+ !cachedFeed.dirty &&
+ !cachedFeed.nextCursor,
+ ),
+ );
};
if (savedSpaceId) {
loadedSpaceId = savedSpaceId;
@@ -174,6 +195,7 @@ const Page: React.FC = () => {
nextSpaceId,
feed,
{ syncedAtMs: cachedFeedSyncedAtMs },
+ Date.now(),
);
if (applied) return feed;
cachedFeedSyncedAtMs = (await loadCachedSpaceFeed(nextSpaceId))
@@ -184,8 +206,11 @@ const Page: React.FC = () => {
.then((feed) => {
if (isCancelled() || !loadedSpaceId || !feed) return;
- setFeedItems(feed.items);
+ setFeedItems(
+ spaceFeedSessionItems(loadedFeedSession, feed.items),
+ );
setFeedNextCursor(feed.nextCursor);
+ setIsFeedComplete(!feed.nextCursor);
const refreshedPostIDs = new Set(
feed.items.map((item) => item.postId),
);
@@ -244,6 +269,7 @@ const Page: React.FC = () => {
setIsFeedLoadingMore(true);
try {
const feed = await loadCurrentFeedPage(spaceId, feedNextCursor);
+ await rememberSpaceFeedSessionPosts(spaceId, feed.items);
setFeedItems((currentItems) => {
const existingPostIds = new Set(
currentItems.map((item) => item.postId),
@@ -256,6 +282,7 @@ const Page: React.FC = () => {
];
});
setFeedNextCursor(feed.nextCursor);
+ setIsFeedComplete(!feed.nextCursor);
} catch (error) {
setHasFeedLoadMoreError(true);
log.error("Failed to load more space feed", error);
@@ -304,8 +331,10 @@ const Page: React.FC = () => {
hasUnreadMessages={hasUnreadMessages}
hasMoreFeedItems={!isFeedLoading && Boolean(feedNextCursor)}
isFeedLoading={isFeedLoading}
+ isFeedComplete={isFeedComplete}
isFeedLoadingMore={isFeedLoadingMore}
localFeedPosts={localFeedPosts}
+ feedSession={feedSession}
showFirstPostPrompt={
hasOwnPosts === false &&
localFeedPosts.length == 0 &&
@@ -450,12 +479,20 @@ const Page: React.FC = () => {
]);
setFriendRequests(requests);
setFriends(friends);
- setFeedItems(feed.items);
- setFeedNextCursor(feed.nextCursor);
await cacheCurrentSpaceFeedPage(
actorSpaceId,
feed,
+ undefined,
+ Date.now(),
+ );
+ setFeedItems(
+ spaceFeedSessionItems(
+ feedSession,
+ feed.items,
+ ),
);
+ setFeedNextCursor(feed.nextCursor);
+ setIsFeedComplete(!feed.nextCursor);
} else {
setFriendRequests(
await loadCurrentFriendRequests(
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index 27324196c1..fd620654b8 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -9,7 +9,6 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Box, Skeleton } from "@mui/material";
import { visuallyHidden } from "@mui/utils";
import { SpaceActionToast } from "components/ActionToast";
-import { SpaceAvatarImage } from "components/AvatarImage";
import { SpaceCaptionText } from "components/CaptionText";
import {
focusFeedPost,
@@ -29,17 +28,22 @@ import {
spacePostLikePopDurationMs,
spacePostLikePopTiming,
} from "components/post-like-animation";
+import { SpacePostAvatar } from "components/PostAvatar";
+import { SpacePostGrid } from "components/PostGrid";
import { SpacePostPhotoInput } from "components/PostPhotoInput";
import { SpacePostPhotosCounter } from "components/PostPhotosCounter";
import { SpacePostPhotosDots } from "components/PostPhotosDots";
+import { SpacePostTile } from "components/PostTile";
import { SpacePWAInstallPrompt } from "components/PWAInstallPrompt";
import { SpaceLoadingSpinner } from "components/RouteFallback";
import { SpaceShareInviteButton } from "components/ShareInviteButton";
import { SpaceSkipLink } from "components/SkipLink";
import log from "ente-base/log";
import { useBrowserBackClose } from "hooks/use-browser-back-close";
+import { useDecodedImage } from "hooks/use-decoded-image";
import React, { useState } from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
+import type { SpaceFeedSession } from "services/feed-cache";
import {
isSpaceContentError,
type SpacePost,
@@ -61,6 +65,7 @@ import {
} from "styles/colors";
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom, formatSpaceDate } from "utils/display";
+import { homeFeedEntries, type HomeFeedEntry } from "utils/home-feed";
import {
spacePostFrameAspectRatio,
spacePostPhotos,
@@ -73,9 +78,9 @@ const homeBackground = spaceAppBackgroundColor;
const green = "#08C225";
const feedAccentBackground = "#263D2C";
const feedAccentBackgroundHover = "#2C4B32";
-const feedActionBackground = "#363639";
-const feedActionForeground = "#DEDEDE";
-const feedTimestampForeground = "#C8C8C8";
+const feedActionBackground = spaceControlBackground;
+const feedActionForeground = spaceText;
+const feedTimestampForeground = "#D9D9D9";
const feedSkeletonElementBackground = spaceSurfaceHover;
const textBase = spaceText;
const textSecondary = spaceTextMuted;
@@ -85,15 +90,10 @@ const feedLikeActionSize = spaceTouchTargetSize;
const feedActionIconSize = 20;
const feedHorizontalPadding = "16px";
const feedMediaLoadRootMargin = "640px 0px";
-const feedLoadMoreRootMargin = "0px 0px 160px 0px";
+const feedLoadMoreRootMargin = "0px 0px 800px 0px";
const feedRowEnterDurationMs = 460;
const feedRowEnterStaggerMs = 35;
const feedRowEnterTiming = "cubic-bezier(0.2, 0.8, 0.2, 1)";
-const avatarFadeSx = {
- "@keyframes spaceAvatarFade": { from: { opacity: 0 }, to: { opacity: 1 } },
- animation: "spaceAvatarFade 320ms cubic-bezier(0.22, 1, 0.36, 1) both",
- "@media (prefers-reduced-motion: reduce)": { animation: "none" },
-} as const;
const feedPhotoCaptionTextSx = {
color: "#E6E6E6",
fontFamily: '"Inter Variable", Inter, sans-serif',
@@ -110,8 +110,10 @@ interface HomeScreenProps {
hasMoreFeedItems?: boolean;
hasUnreadMessages?: boolean;
isFeedLoading?: boolean;
+ isFeedComplete?: boolean;
isFeedLoadingMore?: boolean;
localFeedPosts?: LocalSpaceFeedPost[];
+ feedSession?: SpaceFeedSession;
showFirstPostPrompt?: boolean;
showInstallPrompt?: boolean;
showInviteFriendsToast?: boolean;
@@ -145,14 +147,6 @@ interface FeedPhotoDimensions {
width: number;
}
-interface DecodedImageState {
- failed?: boolean;
- height?: number;
- ready: boolean;
- src?: string | null;
- width?: number;
-}
-
interface SelectedHomeViewer {
photoIndex: number;
photos: SpaceViewerPhoto[];
@@ -161,15 +155,6 @@ interface SelectedHomeViewer {
postActionMode?: SpaceViewerPostActionMode;
}
-type HomeFeedEntry =
- | {
- identity: string;
- item: LocalSpaceFeedPost;
- kind: "local";
- renderKey: string;
- }
- | { identity: string; item: SpacePost; kind: "remote"; renderKey: string };
-
interface FeedLayoutSnapshot {
enteringKeys: Set<string>;
previousTops: Map<string, number>;
@@ -177,10 +162,18 @@ interface FeedLayoutSnapshot {
interface FeedMotionListProps {
entries: HomeFeedEntry[];
+ presentedPostIdentities?: Set<string>;
renderEntry: (entry: HomeFeedEntry) => React.ReactNode;
}
class FeedMotionList extends React.Component<FeedMotionListProps> {
+ private localPresentedPostIdentities = new Set<string>();
+ private get presentedPostIdentities() {
+ return (
+ this.props.presentedPostIdentities ??
+ this.localPresentedPostIdentities
+ );
+ }
private animations = new Map<string, Animation>();
private identityKeys = new Map<string, string>();
private rowElements = new Map<string, HTMLDivElement>();
@@ -240,20 +233,24 @@ class FeedMotionList extends React.Component<FeedMotionListProps> {
const addedEntries = this.props.entries.filter(
(entry) => !previousIdentities.has(entry.identity),
);
- if (
- previousProps.entries.length == 0 ||
- addedEntries.some((entry) => entry.kind == "local")
- )
- return null;
+ if (addedEntries.some((entry) => entry.kind == "local")) return null;
const firstRetainedIndex = this.props.entries.findIndex((entry) =>
previousIdentities.has(entry.identity),
);
+ const enteringCount =
+ previousProps.entries.length == 0
+ ? this.props.entries.length
+ : firstRetainedIndex;
const enteringKeys = new Set(
- firstRetainedIndex > 0
+ enteringCount > 0
? this.props.entries
- .slice(0, firstRetainedIndex)
+ .slice(0, enteringCount)
.filter((entry) => entry.kind == "remote")
+ .filter(
+ (entry) =>
+ !this.presentedPostIdentities.has(entry.identity),
+ )
.map(this.stableKeyFor)
: [],
);
@@ -264,11 +261,38 @@ class FeedMotionList extends React.Component<FeedMotionListProps> {
return { enteringKeys, previousTops };
}
+ componentDidMount() {
+ this.animateFrom({
+ enteringKeys: new Set(
+ this.props.entries
+ .filter((entry) => entry.kind == "remote")
+ .filter(
+ (entry) =>
+ !this.presentedPostIdentities.has(entry.identity),
+ )
+ .map(this.stableKeyFor),
+ ),
+ previousTops: new Map(),
+ });
+ this.rememberPresentedPosts();
+ }
+
componentDidUpdate(
_previousProps: FeedMotionListProps,
_previousState: unknown,
snapshot: FeedLayoutSnapshot | null,
) {
+ this.animateFrom(snapshot);
+ this.rememberPresentedPosts();
+ }
+
+ private rememberPresentedPosts() {
+ this.props.entries.forEach((entry) =>
+ this.presentedPostIdentities.add(entry.identity),
+ );
+ }
+
+ private animateFrom(snapshot: FeedLayoutSnapshot | null) {
if (
!snapshot ||
window.matchMedia("(prefers-reduced-motion: reduce)").matches
@@ -450,69 +474,6 @@ const feedPostAvatarCacheKey = (item: SpacePost) =>
item.avatarSize ?? "",
].join(":");
-const useDecodedImage = (
- src?: string | null,
- keepPreviousUntilReady = false,
-): DecodedImageState => {
- const [state, setState] = useState<DecodedImageState>({ ready: !src, src });
-
- React.useEffect(() => {
- if (!src) {
- setState({ ready: true, src });
- return;
- }
-
- let cancelled = false;
- const image = new Image();
-
- const finish = () => {
- if (cancelled) return;
-
- setState({
- height: image.naturalHeight || undefined,
- ready: true,
- src,
- width: image.naturalWidth || undefined,
- });
- };
- const fail = () => {
- if (cancelled) return;
- setState({ failed: true, ready: true, src });
- };
- const decodeLoadedImage = () => {
- if (typeof image.decode != "function") {
- finish();
- return;
- }
-
- void image.decode().then(finish, fail);
- };
-
- setState((currentState) =>
- keepPreviousUntilReady && currentState.ready && currentState.src
- ? currentState
- : { ready: false, src },
- );
- image.addEventListener("load", decodeLoadedImage, { once: true });
- image.addEventListener("error", fail, { once: true });
- image.src = src;
- if (image.complete) {
- if (image.naturalWidth) decodeLoadedImage();
- else fail();
- }
-
- return () => {
- cancelled = true;
- image.removeEventListener("load", decodeLoadedImage);
- image.removeEventListener("error", fail);
- };
- }, [keepPreviousUntilReady, src]);
-
- if (state.src == src) return state;
- if (keepPreviousUntilReady && src && state.ready && state.src) return state;
- return { ready: !src, src };
-};
-
const scrollPageToTop = () => {
const behavior = window.matchMedia("(prefers-reduced-motion: reduce)")
.matches
@@ -1519,48 +1480,10 @@ const FeedItem: React.FC<FeedItemProps> = ({
},
}}
>
- <Box
- aria-hidden
- sx={{
- bgcolor: "rgba(255, 255, 255, 0.2)",
- borderRadius: "50%",
- height: feedAvatarSize,
- width: feedAvatarSize,
- position: "absolute",
- zIndex: 0,
- }}
- />
- {isAvatarReady ? (
- <Box
- key={displayAvatarUrl ?? "default-avatar"}
- sx={{
- ...avatarFadeSx,
- borderRadius: "50%",
- height: feedAvatarSize,
- overflow: "hidden",
- position: "relative",
- width: feedAvatarSize,
- zIndex: 1,
- }}
- >
- <SpaceAvatarImage
- src={displayAvatarUrl}
- borderRadius="50%"
- />
- </Box>
- ) : null}
- <Box
- aria-hidden
- sx={{
- border: "1px solid rgba(255, 255, 255, 0.16)",
- borderRadius: "50%",
- boxShadow: "0 1px 4px rgba(0, 0, 0, 0.24)",
- height: feedAvatarSize,
- width: feedAvatarSize,
- pointerEvents: "none",
- position: "absolute",
- zIndex: 2,
- }}
+ <SpacePostAvatar
+ ready={isAvatarReady}
+ size={feedAvatarSize}
+ src={displayAvatarUrl}
/>
</Box>
<Box sx={{ minWidth: 0 }}>
@@ -1923,8 +1846,10 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
hasMoreFeedItems = false,
hasUnreadMessages,
isFeedLoading = false,
+ isFeedComplete = false,
isFeedLoadingMore = false,
localFeedPosts = [],
+ feedSession,
showFirstPostPrompt = false,
showInstallPrompt = false,
showInviteFriendsToast = false,
@@ -1974,41 +1899,15 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
const selectedPhotoFriendID = selectedViewer?.photo.friendID;
const selectedPhotoIsOwn =
Boolean(viewerSpaceId) && selectedPhotoFriendID == viewerSpaceId;
- const desiredFeedEntries = React.useMemo<HomeFeedEntry[]>(() => {
- const localResolvedPostIds = new Set(
- localFeedPosts.map((item) =>
- item.status == "posted" || item.status == "ready"
- ? item.post.postId
- : item.postId,
- ),
+ const { latest: latestFeedEntries, history: gridFeedItems } =
+ homeFeedEntries(
+ feedItems,
+ localFeedPosts,
+ feedSession?.newPostsSinceMs,
+ new Set(feedSession?.latestPosts.map((post) => post.postId)),
);
- return [
- ...localFeedPosts.map(
- (item): HomeFeedEntry => ({
- identity:
- item.status == "posted" || item.status == "ready"
- ? `post:${item.post.postId}`
- : item.postId
- ? `post:${item.postId}`
- : `local:${item.id}`,
- item,
- kind: "local",
- renderKey: `local:${item.id}`,
- }),
- ),
- ...feedItems
- .filter((item) => !localResolvedPostIds.has(item.postId))
- .map(
- (item): HomeFeedEntry => ({
- identity: `post:${item.postId}`,
- item,
- kind: "remote",
- renderKey: `post:${item.postId}`,
- }),
- ),
- ];
- }, [feedItems, localFeedPosts]);
- const hasFeedItems = desiredFeedEntries.length > 0;
+ const hasFeedItems =
+ latestFeedEntries.length > 0 || gridFeedItems.length > 0;
const isEmptyFeedLoading = !hasFeedItems && isFeedLoading;
const showFeedCards = hasFeedItems;
const isInstallPromptEnabled =
@@ -2391,18 +2290,126 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
width: "100%",
}}
>
+ <Box
+ component="section"
+ aria-label="Latest"
+ hidden={latestFeedEntries.length == 0}
+ >
+ <FeedMotionList
+ entries={latestFeedEntries}
+ presentedPostIdentities={
+ feedSession?.presentedPostIdentities
+ }
+ renderEntry={(entry) =>
+ entry.kind == "local"
+ ? localFeedItemFor(entry.item)
+ : feedItemFor(entry.item, entry.item.postId)
+ }
+ />
+ </Box>
{hasFeedItems ? (
<>
- <FeedMotionList
- entries={desiredFeedEntries}
- renderEntry={(entry) =>
- entry.kind == "local"
- ? localFeedItemFor(entry.item)
- : feedItemFor(
- entry.item,
- entry.item.postId,
- )
+ <SpacePostGrid
+ postCount={
+ isFeedComplete
+ ? latestFeedEntries.length +
+ gridFeedItems.length
+ : undefined
}
+ items={gridFeedItems.map((item) => {
+ const photo = spacePostPhotos(item)[0]!;
+ return {
+ ...item,
+ id: String(item.postId),
+ frameAspectRatio: photo.video
+ ? spacePostFrameAspectRatio([photo])
+ : undefined,
+ };
+ })}
+ renderTile={(item, index, flexGrow) => {
+ const photo = {
+ ...spacePostPhotos(item)[0]!,
+ postId: item.postId,
+ spaceId: item.spaceId,
+ };
+ const imageUrl =
+ loadedFeedImageURLFor(photo);
+ const avatarUrl =
+ loadedFeedAvatarURLFor(item);
+ const isUnavailable = Boolean(
+ item.isUnavailable ||
+ unavailableFeedPostsByKey[
+ feedPostImageCacheKey(photo)
+ ],
+ );
+ const isOwnPost =
+ Boolean(viewerSpaceId) &&
+ item.spaceId == viewerSpaceId;
+ return (
+ <SpacePostTile
+ key={item.id}
+ item={{ ...item, avatarUrl }}
+ displayName={item.name}
+ showAvatar
+ flexGrow={flexGrow}
+ index={index}
+ imageUrl={imageUrl}
+ isAvatarPending={
+ !item.isUnavailable &&
+ avatarUrl === undefined
+ }
+ isUnavailable={isUnavailable}
+ loadRootMargin={
+ feedMediaLoadRootMargin
+ }
+ onOpenProfile={
+ isOwnPost
+ ? onOpenProfile
+ : onOpenFriend
+ ? () =>
+ onOpenFriend(
+ item.friendID,
+ item.username,
+ )
+ : undefined
+ }
+ onLoadAvatar={
+ avatarUrl === undefined
+ ? () =>
+ loadFeedPostAvatar(
+ item,
+ )
+ : undefined
+ }
+ onLoadImage={() =>
+ loadFeedPostImage(photo)
+ }
+ onImageDecodeError={() =>
+ setUnavailableFeedPostsByKey(
+ (current) => ({
+ ...current,
+ [feedPostImageCacheKey(
+ photo,
+ )]: true,
+ }),
+ )
+ }
+ onOpen={(imageUrl) => {
+ const post = {
+ ...item,
+ avatarUrl,
+ imageUrl,
+ };
+ openFeedPhoto(
+ post,
+ viewerPhotosFromPost(
+ post,
+ )[0]!,
+ );
+ }}
+ />
+ );
+ }}
/>
{hasMoreFeedItems && onLoadMoreFeedItems && (
<Box
diff --git a/web/apps/space/src/screens/ProfileImageViewerScreen.tsx b/web/apps/space/src/screens/ProfileImageViewerScreen.tsx
index f322b71d54..561f200ddb 100644
--- a/web/apps/space/src/screens/ProfileImageViewerScreen.tsx
+++ b/web/apps/space/src/screens/ProfileImageViewerScreen.tsx
@@ -24,7 +24,7 @@ import {
const green = "#08C225";
const textBase = spaceText;
-const profileCoverBackground = "#1F1F1F";
+const profileCoverBackground = spaceSurface;
const profileAvatarSkeletonBackground = spaceSurface;
export const friendProfileImageViewerBackground = "#000000";
diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsx
index 48a9bcdad6..5b683842d1 100644
--- a/web/apps/space/src/screens/ProfileScreen.tsx
+++ b/web/apps/space/src/screens/ProfileScreen.tsx
@@ -27,11 +27,9 @@ import {
type SpaceViewerPostActionMode,
} from "components/FileViewer";
import { SpacePostComposer } from "components/PostComposer";
+import { SpacePostGrid } from "components/PostGrid";
import { SpacePostPhotoInput } from "components/PostPhotoInput";
-import {
- SpacePostPhotosBadge,
- SpacePostVideoBadge,
-} from "components/PostPhotosBadge";
+import { SpacePostTile, type SpacePostTileItem } from "components/PostTile";
import { SpaceLoadingSpinner } from "components/RouteFallback";
import { SpaceShareIcon } from "components/ShareInviteButton";
import { SpaceSkipLink } from "components/SkipLink";
@@ -40,11 +38,7 @@ import { useBrowserBackClose } from "hooks/use-browser-back-close";
import React, { useState } from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
import type { SpaceInviteIntent } from "services/invite";
-import {
- isSpaceContentError,
- type SpacePostAsset,
- type SpacePostPhoto,
-} from "services/space";
+import { isSpaceContentError, type SpacePostAsset } from "services/space";
import { spaceEmptyStateButtonSx } from "styles/buttons";
import {
spaceAppBackground,
@@ -55,7 +49,6 @@ import {
spaceText,
spaceTextMuted,
} from "styles/colors";
-import { spaceProfilePostRadius } from "styles/tiles";
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom } from "utils/display";
import {
@@ -63,9 +56,6 @@ import {
type SpaceDraftPostImage,
} from "utils/post-image";
import { viewerPhotosFromPost } from "utils/post-photos";
-import { profilePhotoGap, profilePhotoRows } from "utils/profile-photo-layout";
-import { profilePostSections } from "utils/profile-post-sections";
-import { thumbHashDataURLFromBase64 } from "utils/thumbhash";
const green = "#08C225";
const dangerColor = "#F63A3A";
@@ -75,7 +65,7 @@ const coverForeground = "#FFFFFF";
const profileIdentityColor = spaceText;
const profileStatsColor = spaceTextMuted;
const profileStatsValueColor = spaceText;
-const profileCoverBackground = "#1F1F1F";
+const profileCoverBackground = spaceSurface;
const profileCoverTopShadow =
"linear-gradient(180deg, rgba(0, 0, 0, 0.26) 0%, rgba(0, 0, 0, 0.18) 36%, rgba(0, 0, 0, 0.08) 72%, rgba(0, 0, 0, 0) 100%)";
const profileCoverSkeletonBackground = spaceSurface;
@@ -93,24 +83,7 @@ interface ProfilePhotoDimensions {
width: number;
}
-export interface ProfilePostItem {
- avatarUrl?: string | null;
- caption?: string;
- friendID?: string;
- height?: number;
- id: string;
- imageAsset?: SpacePostAsset;
- imageUrl?: string;
- photos?: SpacePostPhoto[];
- isUnavailable?: boolean;
- name?: string;
- postId?: number;
- spaceId?: string;
- timestampMs: number;
- thumbHash?: string;
- viewerLiked?: boolean;
- width?: number;
-}
+export type ProfilePostItem = SpacePostTileItem;
interface SelectedProfilePost {
id: string;
@@ -118,12 +91,6 @@ interface SelectedProfilePost {
photoIndex: number;
}
-interface ProfilePhotoTile {
- aspectRatio: number;
- index: number;
- item: ProfilePostItem;
-}
-
const profilePostImageCacheKey = (item: ProfilePostItem) =>
[item.id, item.imageAsset?.objectKey ?? item.imageUrl ?? ""].join(":");
@@ -239,203 +206,6 @@ const ProfilePostLoadingIndicator: React.FC = () => (
</Box>
);
-interface ProfilePostTileProps {
- displayName: string;
- flexGrow: number;
- imageUrl?: string;
- index: number;
- isUnavailable: boolean;
- item: ProfilePostItem;
- loadRootMargin: string;
- onImageDecodeError: () => void;
- onLoadImage: () => Promise<string | undefined>;
- onOpen: (imageUrl: string) => void;
- onRememberDimensions: (itemID: string, image: HTMLImageElement) => void;
-}
-
-const ProfilePostTile: React.FC<ProfilePostTileProps> = ({
- displayName,
- flexGrow,
- imageUrl,
- index,
- isUnavailable: isPostUnavailable,
- item,
- loadRootMargin,
- onImageDecodeError,
- onLoadImage,
- onOpen,
- onRememberDimensions,
-}) => {
- const [shouldLoad, setShouldLoad] = React.useState(Boolean(imageUrl));
- const [readyImageUrl, setReadyImageUrl] = React.useState<string>();
- const [imageDecodeFailed, setImageDecodeFailed] = React.useState(false);
- const tileRef = React.useRef<HTMLButtonElement | null>(null);
- const thumbHashDataURL = React.useMemo(
- () => thumbHashDataURLFromBase64(item.thumbHash),
- [item.thumbHash],
- );
- const isCurrentImageReady = Boolean(imageUrl && readyImageUrl == imageUrl);
- const isUnavailable = isPostUnavailable || imageDecodeFailed;
- const photoCount = item.photos?.length ?? 1;
-
- React.useEffect(() => {
- if (imageUrl) setShouldLoad(true);
- }, [imageUrl]);
-
- React.useEffect(() => {
- if (isUnavailable) return;
- if (shouldLoad || imageUrl) return;
- const element = tileRef.current;
- if (!element) return;
- if (
- typeof window == "undefined" ||
- !("IntersectionObserver" in window)
- ) {
- setShouldLoad(true);
- return;
- }
-
- const observer = new IntersectionObserver(
- (entries) => {
- if (entries.some((entry) => entry.isIntersecting)) {
- setShouldLoad(true);
- observer.disconnect();
- }
- },
- { rootMargin: loadRootMargin },
- );
- observer.observe(element);
- return () => observer.disconnect();
- }, [imageUrl, isUnavailable, loadRootMargin, shouldLoad]);
-
- React.useEffect(() => {
- if (isUnavailable) return;
- if (!shouldLoad || imageUrl) return;
- void onLoadImage().catch((error: unknown) => {
- log.warn("Failed to load profile post image", error);
- });
- }, [imageUrl, isUnavailable, onLoadImage, shouldLoad]);
-
- return (
- <Box
- ref={tileRef}
- component="button"
- type="button"
- aria-label={
- isUnavailable
- ? "Post unavailable"
- : `Open ${displayName} post ${index + 1}${
- photoCount > 1 ? `, ${photoCount} photos` : ""
- }`
- }
- disabled={!imageUrl || isUnavailable}
- onClick={() => {
- if (imageUrl && !isUnavailable) onOpen(imageUrl);
- }}
- sx={{
- appearance: "none",
- bgcolor: photoPlaceholderBackground,
- border: 0,
- borderRadius: `${spaceProfilePostRadius}px`,
- cursor: imageUrl && !isUnavailable ? "pointer" : "default",
- display: "block",
- flex: `${flexGrow} 1 0px`,
- height: "100%",
- minWidth: 0,
- opacity: 1,
- overflow: "hidden",
- p: 0,
- position: "relative",
- "&:focus-visible": {
- outline: `2px solid ${green}`,
- outlineOffset: -2,
- },
- }}
- >
- {!isUnavailable && thumbHashDataURL ? (
- <Box
- component="img"
- alt=""
- aria-hidden
- src={thumbHashDataURL}
- sx={{
- display: "block",
- filter: "blur(14px)",
- height: "100%",
- inset: 0,
- objectFit: "cover",
- objectPosition: "center",
- position: "absolute",
- transform: "scale(1.08)",
- width: "100%",
- }}
- />
- ) : null}
- {!isUnavailable && imageUrl ? (
- <Box
- component="img"
- alt={`${displayName} post ${index + 1}`}
- onLoad={(event) => {
- setReadyImageUrl(imageUrl);
- onRememberDimensions(item.id, event.currentTarget);
- }}
- onError={() => {
- log.warn(
- `Post ${item.postId} is unavailable because the browser could not decode its image`,
- );
- setImageDecodeFailed(true);
- onImageDecodeError();
- }}
- src={imageUrl}
- sx={{
- display: "block",
- height: "100%",
- inset: 0,
- objectFit: "cover",
- objectPosition: "center",
- opacity:
- isCurrentImageReady || !thumbHashDataURL ? 1 : 0,
- position: "absolute",
- transition: thumbHashDataURL
- ? "opacity 220ms ease"
- : "none",
- width: "100%",
- "@media (prefers-reduced-motion: reduce)": {
- opacity: 1,
- transition: "none",
- },
- }}
- />
- ) : null}
- {!isUnavailable && (
- <>
- <SpacePostPhotosBadge count={photoCount} inset={8} />
- <SpacePostVideoBadge
- durationMs={item.photos?.[0]?.video?.durationMs}
- size={18}
- />
- </>
- )}
- {isUnavailable && (
- <Box
- sx={{
- alignItems: "center",
- color: textSoft,
- display: "flex",
- fontSize: 12,
- fontWeight: 600,
- height: "100%",
- justifyContent: "center",
- width: "100%",
- }}
- >
- Post unavailable
- </Box>
- )}
- </Box>
- );
-};
-
interface ProfileScreenProps {
friendsCount?: number;
headerVariant?: "friend" | "owner" | "public" | "public-anonymous";
@@ -539,8 +309,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
Record<string, true>
>({});
const [loadedCoverUrl, setLoadedCoverUrl] = useState<string | null>(null);
- const [postGridWidth, setPostGridWidth] = useState(0);
- const postGridRef = React.useRef<HTMLDivElement | null>(null);
const postInputRef = React.useRef<HTMLInputElement | null>(null);
const postImageLoadsInFlightRef = React.useRef<
Map<string, Promise<string | undefined>>
@@ -581,17 +349,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
const canOpenProfileCover = Boolean(onOpenProfileCover);
const canOpenProfilePhoto = Boolean(onOpenProfilePhoto);
const hasProfilePosts = postsSharedCount > 0;
- React.useLayoutEffect(() => {
- const grid = postGridRef.current;
- if (!grid) return;
-
- const observer = new ResizeObserver(([entry]) =>
- setPostGridWidth(entry!.contentRect.width),
- );
- setPostGridWidth(grid.getBoundingClientRect().width);
- observer.observe(grid);
- return () => observer.disconnect();
- }, [hasProfilePosts]);
const shouldShowPostLoadingIndicator =
isPostsLoading && (showPostLoadingIndicator ?? true);
const isCoverImageLoading = Boolean(
@@ -742,22 +499,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
[loadedPhotoDimensionsByID],
);
- const photoSections = profilePostSections(
- visiblePostItems.map((item, index) => {
- const { width, height } = dimensionsForPost(item);
- return {
- aspectRatio: width > 0 && height > 0 ? width / height : 1,
- index,
- item,
- timestampMs: item.timestampMs,
- };
- }),
- ).map(({ id, title, items }) => ({
- id,
- title,
- rows: profilePhotoRows(items, postGridWidth),
- }));
-
const profileViewerPhotos = viewerPostItems.flatMap((item) =>
viewerPhotosFromPost({
...item,
@@ -809,15 +550,16 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
};
const renderPostTile = (
- { aspectRatio, index, item }: ProfilePhotoTile,
- rowAspectRatio: number,
+ item: ProfilePostItem,
+ index: number,
+ flexGrow: number,
) => {
const imageUrl = loadedPostImageURLFor(item);
const isUnavailable = !viewerPostIndexByID.has(item.id);
return (
- <ProfilePostTile
+ <SpacePostTile
key={item.id}
- flexGrow={aspectRatio / rowAspectRatio}
+ flexGrow={flexGrow}
displayName={displayName}
imageUrl={imageUrl}
index={index}
@@ -1594,7 +1336,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
>
{hasProfilePosts ? (
<Box
- ref={postGridRef}
sx={{
display: "flex",
flexDirection: "column",
@@ -1604,56 +1345,11 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
width: "calc(100% - 32px)",
}}
>
- {photoSections.map(({ id, title, rows }) => (
- <Box
- component="section"
- key={id}
- aria-label={title}
- >
- <Box
- component="h2"
- sx={{
- color: textSoft,
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 13,
- fontWeight: 700,
- lineHeight: "18px",
- m: 0,
- pb: "8px",
- }}
- >
- {title}
- </Box>
- <Box
- sx={{
- display: "flex",
- flexDirection: "column",
- gap: `${profilePhotoGap}px`,
- }}
- >
- {rows.map((row) => (
- <Box
- key={row.tiles[0]!.item.id}
- sx={{
- display: "flex",
- flexShrink: 0,
- gap: `${profilePhotoGap}px`,
- height: row.height,
- width: row.width,
- }}
- >
- {row.tiles.map((tile) =>
- renderPostTile(
- tile,
- row.aspectRatio,
- ),
- )}
- </Box>
- ))}
- </Box>
- </Box>
- ))}
+ <SpacePostGrid
+ items={visiblePostItems}
+ postCount={displayedPostsCount}
+ renderTile={renderPostTile}
+ />
</Box>
) : shouldShowPostLoadingIndicator ? (
<ProfilePostLoadingIndicator />
diff --git a/web/apps/space/src/services/feed-cache.ts b/web/apps/space/src/services/feed-cache.ts
index 2feecc1c49..4f7324e892 100644
--- a/web/apps/space/src/services/feed-cache.ts
+++ b/web/apps/space/src/services/feed-cache.ts
@@ -7,11 +7,12 @@ import type { SpacePost, SpacePostPage } from "services/space";
import { z } from "zod";
const spaceFeedCacheVersion = 3;
-const spaceFeedCacheSize = 10;
+const spaceFeedCacheSize = 20;
const SpaceFeedCacheSnapshotSchema = z.object({
dirty: z.boolean(),
- items: CachedSpacePost.array().max(spaceFeedCacheSize),
+ items: CachedSpacePost.array(),
+ lastVisitedAtMs: z.number().optional(),
nextCursor: z.string().optional(),
spaceId: z.string(),
syncedAtMs: z.number(),
@@ -21,15 +22,24 @@ const SpaceFeedCacheSnapshotSchema = z.object({
export interface SpaceFeedCacheSnapshot {
dirty: boolean;
items: SpacePost[];
+ lastVisitedAtMs?: number;
nextCursor?: string;
spaceId: string;
syncedAtMs: number;
version: typeof spaceFeedCacheVersion;
}
+export interface SpaceFeedSession {
+ newPostsSinceMs: number;
+ latestPosts: SpacePost[];
+ presentedPostIdentities: Set<string>;
+}
+
const memoryCache = new Map<string, SpaceFeedCacheSnapshot | undefined>();
+const feedSessions = new Map<string, SpaceFeedSession>();
const cacheOperations = new Map<string, Promise<void>>();
let cacheGeneration = 0;
+let appOpenedAtMs = Date.now();
const cacheKey = async (spaceId: string) => {
const userID = savedPartialLocalUser()?.id;
@@ -78,8 +88,12 @@ const normalizedSnapshot = (
snapshot: SpaceFeedCacheSnapshot,
): SpaceFeedCacheSnapshot => ({
...snapshot,
+ dirty: snapshot.dirty || snapshot.items.length > spaceFeedCacheSize,
items: snapshot.items.slice(0, spaceFeedCacheSize).map(cacheablePost),
- nextCursor: snapshot.nextCursor || undefined,
+ nextCursor:
+ snapshot.items.length > spaceFeedCacheSize
+ ? undefined
+ : snapshot.nextCursor || undefined,
version: spaceFeedCacheVersion,
});
@@ -131,6 +145,63 @@ export const loadCachedSpaceFeed = async (
}
};
+const feedSessionForSnapshot = (
+ key: string,
+ cached: SpaceFeedCacheSnapshot | undefined,
+) => {
+ let session = feedSessions.get(key);
+ if (!session) {
+ const newPostsSinceMs = cached?.lastVisitedAtMs ?? appOpenedAtMs;
+ session = {
+ newPostsSinceMs,
+ latestPosts: (cached?.items ?? []).filter(
+ (post) => post.timestampMs > newPostsSinceMs,
+ ),
+ presentedPostIdentities: new Set(),
+ };
+ feedSessions.set(key, session);
+ }
+ return session;
+};
+
+export const loadSpaceFeedSession = async (spaceId: string) => {
+ const generation = cacheGeneration;
+ const key = await cacheKey(spaceId);
+ if (!key || generation != cacheGeneration) return undefined;
+ const cached = await loadCachedSpaceFeed(spaceId);
+ if (generation != cacheGeneration) return undefined;
+ return feedSessionForSnapshot(key, cached);
+};
+
+export const spaceFeedSessionItems = (
+ session: SpaceFeedSession | undefined,
+ items: SpacePost[],
+) =>
+ [
+ ...new Map(
+ [...(session?.latestPosts ?? []), ...items].map((post) => [
+ post.postId,
+ post,
+ ]),
+ ).values(),
+ ].sort(descendingPostOrder);
+
+const rememberSessionPosts = (
+ session: SpaceFeedSession,
+ items: SpacePost[],
+) => {
+ const latestPostIDs = new Set(
+ session.latestPosts.map((post) => post.postId),
+ );
+ session.latestPosts = spaceFeedSessionItems(session, items)
+ .filter(
+ (post) =>
+ post.timestampMs > session.newPostsSinceMs ||
+ latestPostIDs.has(post.postId),
+ )
+ .map(cacheablePost);
+};
+
const writeCachedSpaceFeed = async (
snapshot: SpaceFeedCacheSnapshot,
previous?: { syncedAtMs?: number },
@@ -146,7 +217,27 @@ const writeCachedSpaceFeed = async (
if (generation != cacheGeneration) return;
if (previous && memoryCache.get(key)?.syncedAtMs != previous.syncedAtMs)
return;
+ normalized.lastVisitedAtMs =
+ Math.max(
+ normalized.lastVisitedAtMs ?? 0,
+ memoryCache.get(key)?.lastVisitedAtMs ?? 0,
+ ) || undefined;
applied = true;
+ const session = feedSessions.get(key);
+ if (session) {
+ const refreshedPostIDs = new Set(
+ snapshot.items.map((post) => post.postId),
+ );
+ const oldestPost = snapshot.nextCursor
+ ? snapshot.items.at(-1)
+ : undefined;
+ session.latestPosts = session.latestPosts.filter(
+ (post) =>
+ refreshedPostIDs.has(post.postId) ||
+ (oldestPost && descendingPostOrder(post, oldestPost) > 0),
+ );
+ rememberSessionPosts(session, snapshot.items);
+ }
memoryCache.set(key, normalized);
await setKV(key, normalized);
if (generation != cacheGeneration) {
@@ -161,11 +252,13 @@ export const cacheCurrentSpaceFeedPage = async (
spaceId: string,
page: SpacePostPage,
previous?: { syncedAtMs?: number },
+ lastVisitedAtMs?: number,
) =>
writeCachedSpaceFeed(
{
dirty: false,
items: page.items,
+ lastVisitedAtMs,
nextCursor: page.nextCursor,
spaceId,
syncedAtMs: Date.now(),
@@ -211,6 +304,15 @@ const updateCachedSpaceFeed = async (
syncedAtMs: Math.max(Date.now(), snapshot.syncedAtMs + 1),
});
if (generation != cacheGeneration) return;
+ const session = createIfMissing
+ ? feedSessionForSnapshot(key, snapshot)
+ : feedSessions.get(key);
+ if (session) {
+ session.latestPosts = update({
+ ...cloneSnapshot(snapshot),
+ items: session.latestPosts.map(clonePost),
+ }).items.map(cacheablePost);
+ }
memoryCache.set(key, nextSnapshot);
await setKV(key, nextSnapshot);
if (generation != cacheGeneration) {
@@ -223,18 +325,36 @@ const updateCachedSpaceFeed = async (
const descendingPostOrder = (a: SpacePost, b: SpacePost) =>
b.timestampMs - a.timestampMs || b.postId - a.postId;
+export const rememberSpaceFeedSessionPosts = async (
+ spaceId: string,
+ posts: SpacePost[],
+) => {
+ const session = await loadSpaceFeedSession(spaceId);
+ if (session) rememberSessionPosts(session, posts);
+ await updateCachedSpaceFeed(spaceId, (snapshot) => ({
+ ...snapshot,
+ lastVisitedAtMs: Math.max(
+ snapshot.lastVisitedAtMs ?? 0,
+ Date.now(),
+ ...posts.map((post) => post.timestampMs),
+ ),
+ }));
+};
+
export const prependCachedSpaceFeedPost = (spaceId: string, post: SpacePost) =>
updateCachedSpaceFeed(
spaceId,
(snapshot) => ({
...snapshot,
dirty: true,
+ lastVisitedAtMs: Math.max(
+ snapshot.lastVisitedAtMs ?? 0,
+ post.timestampMs,
+ ),
items: [
post,
...snapshot.items.filter((item) => item.postId != post.postId),
- ]
- .sort(descendingPostOrder)
- .slice(0, spaceFeedCacheSize),
+ ].sort(descendingPostOrder),
nextCursor: undefined,
}),
true,
@@ -281,4 +401,6 @@ export const invalidateCachedSpaceFeed = (spaceId: string) =>
export const clearSpaceFeedMemoryCache = () => {
cacheGeneration += 1;
memoryCache.clear();
+ feedSessions.clear();
+ appOpenedAtMs = Date.now();
};
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index cf3aa57ea2..830194d0af 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -978,7 +978,11 @@ export const loadCurrentFeedPage = async (
): Promise<SpacePostPage> => {
const ctx = await ensureCurrentSpaceContext();
try {
- const page = await ctx.listFeed(spaceId, cursor ?? null, 10);
+ const page = await ctx.listFeed(
+ spaceId,
+ cursor ?? null,
+ cursor ? 10 : 20,
+ );
await persistCurrentOwnedSpaces(ctx);
return {
items: await Promise.all(
diff --git a/web/apps/space/src/styles/colors.ts b/web/apps/space/src/styles/colors.ts
index 1139e6fd13..8fa4fa6fce 100644
--- a/web/apps/space/src/styles/colors.ts
+++ b/web/apps/space/src/styles/colors.ts
@@ -1,15 +1,15 @@
-export const spaceAppBackgroundColor = "#1C1C1E";
+export const spaceAppBackgroundColor = "#000000";
export const spaceAppBackground = spaceAppBackgroundColor;
-export const spaceDialogBackground = "#323232";
-export const spaceSurface = "#28282B";
-export const spaceSurfaceHover = "#3A3A3A";
-export const spaceControlBackground = "#343434";
-export const spaceControlBackgroundHover = "#3E3E3E";
-export const spaceMenuBackground = "#424242";
-export const spaceMenuHover = "#505050";
-export const spaceText = "#F2F2F2";
-export const spaceTextMuted = "#B0B0B0";
+export const spaceDialogBackground = "#242424";
+export const spaceSurface = "#1A1A1A";
+export const spaceSurfaceHover = "#262626";
+export const spaceControlBackground = "#242424";
+export const spaceControlBackgroundHover = "#303030";
+export const spaceMenuBackground = "#262626";
+export const spaceMenuHover = "#333333";
+export const spaceText = "#FFFFFF";
+export const spaceTextMuted = "#A0A0A0";
export const spaceOnAccent = "#FFFFFF";
export const spaceDanger = "#F63A3A";
diff --git a/web/apps/space/src/utils/home-feed.ts b/web/apps/space/src/utils/home-feed.ts
new file mode 100644
index 0000000000..a8a6833c35
--- /dev/null
+++ b/web/apps/space/src/utils/home-feed.ts
@@ -0,0 +1,77 @@
+import type { SpacePost } from "services/space";
+import type { LocalSpaceFeedPost } from "state/app-state";
+
+export type HomeFeedEntry =
+ | {
+ identity: string;
+ item: LocalSpaceFeedPost;
+ kind: "local";
+ renderKey: string;
+ }
+ | { identity: string; item: SpacePost; kind: "remote"; renderKey: string };
+
+export const homeFeedEntries = (
+ feedItems: SpacePost[],
+ localFeedPosts: LocalSpaceFeedPost[],
+ newPostsSinceMs: number | undefined,
+ latestPostIDs?: ReadonlySet<number>,
+) => {
+ const localResolvedPostIds = new Set(
+ localFeedPosts.map((item) =>
+ item.status == "posted" || item.status == "ready"
+ ? item.post.postId
+ : item.postId,
+ ),
+ );
+ const entries: HomeFeedEntry[] = [
+ ...localFeedPosts.map(
+ (item): HomeFeedEntry => ({
+ identity:
+ item.status == "posted" || item.status == "ready"
+ ? `post:${item.post.postId}`
+ : item.postId
+ ? `post:${item.postId}`
+ : `local:${item.id}`,
+ item,
+ kind: "local",
+ renderKey: `local:${item.id}`,
+ }),
+ ),
+ ...feedItems
+ .filter((item) => !localResolvedPostIds.has(item.postId))
+ .map(
+ (item): HomeFeedEntry => ({
+ identity: `post:${item.postId}`,
+ item,
+ kind: "remote",
+ renderKey: `post:${item.postId}`,
+ }),
+ ),
+ ];
+ const latest: HomeFeedEntry[] = [];
+ const history: SpacePost[] = [];
+ for (const entry of entries) {
+ let post: SpacePost;
+ if (entry.kind == "remote") {
+ post = entry.item;
+ } else {
+ if (entry.item.status != "ready") {
+ latest.push(entry);
+ continue;
+ }
+ post = entry.item.post;
+ }
+ if (
+ latestPostIDs?.has(post.postId) ||
+ (newPostsSinceMs != undefined && post.timestampMs > newPostsSinceMs)
+ ) {
+ latest.push(entry);
+ } else {
+ history.push(post);
+ }
+ }
+ history.sort(
+ (a, b) => b.timestampMs - a.timestampMs || b.postId - a.postId,
+ );
+ return { latest, history };
+};
diff --git a/web/apps/space/src/utils/profile-photo-layout.ts b/web/apps/space/src/utils/profile-photo-layout.ts
index 9f006afe6d..85b647d9c2 100644
--- a/web/apps/space/src/utils/profile-photo-layout.ts
+++ b/web/apps/space/src/utils/profile-photo-layout.ts
@@ -3,16 +3,64 @@ import { minimumPostPhotoFrameAspectRatio } from "../styles/tiles";
export const profilePhotoGap = 6;
const profilePhotoMinRowHeight = 100;
-export const profilePhotoRows = <Tile extends { aspectRatio: number }>(
+interface PhotoRow<Tile> {
+ aspectRatio: number;
+ height: number;
+ width: number;
+ tiles: Tile[];
+}
+
+interface PostPhotoTile {
+ id: string;
+ aspectRatio: number;
+}
+
+interface PostPhotoLayout {
+ width: number;
+ fullWidth?: boolean;
+ rows: PhotoRow<PostPhotoTile>[];
+}
+
+export const postPhotoLayout = (
+ tiles: PostPhotoTile[],
+ width: number,
+ previous?: PostPhotoLayout,
+ postCount?: number,
+): PostPhotoLayout => {
+ const fullWidth =
+ previous?.fullWidth ??
+ (width > 0 && tiles.length > 0
+ ? postCount != undefined && Math.max(postCount, tiles.length) <= 7
+ : undefined);
+ const rows: PhotoRow<PostPhotoTile>[] = [];
+ let retainedCount = 0;
+ if (previous?.width == width) {
+ for (const row of previous.rows) {
+ if (
+ !row.tiles.every(
+ (tile, index) =>
+ tiles[retainedCount + index]?.id == tile.id,
+ )
+ )
+ break;
+ rows.push(row);
+ retainedCount += row.tiles.length;
+ }
+ }
+ const remaining = tiles.slice(retainedCount);
+ rows.push(
+ ...(fullWidth
+ ? remaining.flatMap((tile) => profilePhotoRows([tile], width))
+ : profilePhotoRows(remaining, width)),
+ );
+ return { width, fullWidth, rows };
+};
+
+const profilePhotoRows = <Tile extends { aspectRatio: number }>(
tiles: Tile[],
width: number,
) => {
- const rows: {
- aspectRatio: number;
- height: number;
- width: number;
- tiles: Tile[];
- }[] = [];
+ const rows: PhotoRow<Tile>[] = [];
if (width <= 0) return rows;
const targetRowHeight = width / 2;
diff --git a/web/apps/space/src/utils/profile-post-sections.ts b/web/apps/space/src/utils/profile-post-sections.ts
deleted file mode 100644
index afab2c07d9..0000000000
--- a/web/apps/space/src/utils/profile-post-sections.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-export const profilePostSections = <Item extends { timestampMs: number }>(
- items: Item[],
- now = new Date(),
-) => {
- const year = now.getFullYear();
- const month = now.getMonth();
- const day = now.getDate();
- // Weeks start on Monday. Construct local dates rather than subtracting
- // 24-hour periods so yesterday stays correct across daylight saving changes.
- const daysSinceMonday = (now.getDay() + 6) % 7;
- const recentSections = [
- { id: "today", title: "Today", since: new Date(year, month, day) },
- {
- id: "yesterday",
- title: "Yesterday",
- since: new Date(year, month, day - 1),
- },
- {
- id: "week",
- title: "This week",
- since: new Date(year, month, day - daysSinceMonday),
- },
- {
- id: "last-week",
- title: "Last week",
- since: new Date(year, month, day - daysSinceMonday - 7),
- },
- { id: "month", title: "This month", since: new Date(year, month, 1) },
- ].map((section) => ({ ...section, items: new Array<Item>() }));
- const months = new Map<
- number,
- { id: string; title: string; items: Item[] }
- >();
-
- for (const item of items) {
- const recentSection = recentSections.find(
- ({ since }) => item.timestampMs >= since.getTime(),
- );
- if (recentSection) {
- recentSection.items.push(item);
- continue;
- }
-
- const date = new Date(item.timestampMs);
- const monthStart = new Date(date.getFullYear(), date.getMonth(), 1);
- const key = monthStart.getTime();
- let section = months.get(key);
- if (!section) {
- section = {
- id: `${date.getFullYear()}-${date.getMonth() + 1}`,
- title: monthStart.toLocaleDateString("en-US", {
- month: "short",
- year: "numeric",
- }),
- items: [],
- };
- months.set(key, section);
- }
- section.items.push(item);
- }
-
- return [
- ...recentSections.filter(({ items }) => items.length > 0),
- ...[...months.entries()]
- .sort(([a], [b]) => b - a)
- .map(([, section]) => section),
- ];
-};
diff --git a/web/apps/space/tests/feed-cache.test.ts b/web/apps/space/tests/feed-cache.test.ts
index 0737ece239..6ffda903c2 100644
--- a/web/apps/space/tests/feed-cache.test.ts
+++ b/web/apps/space/tests/feed-cache.test.ts
@@ -6,10 +6,13 @@ import {
cacheCurrentSpaceFeedPage,
clearSpaceFeedMemoryCache,
loadCachedSpaceFeed,
+ loadSpaceFeedSession,
patchCachedSpaceFeedPost,
prependCachedSpaceFeedPost,
+ rememberSpaceFeedSessionPosts,
removeCachedSpaceFeedPost,
removeCachedSpaceFeedPostsBySpace,
+ spaceFeedSessionItems,
} from "../src/services/feed-cache";
import type { SpacePost } from "../src/services/space";
@@ -87,6 +90,52 @@ test("persists the first publication before a feed has been cached", async () =>
expect(cached?.dirty).toBe(true);
});
+test("restores all twenty posts and their cursor, then keeps the cache bounded when posting", async () => {
+ const posts = Array.from({ length: 20 }, (_, index) => post(20 - index));
+ await cacheCurrentSpaceFeedPage("self", {
+ items: posts,
+ nextCursor: "after-twenty",
+ });
+ clearSpaceFeedMemoryCache();
+ const restored = (await loadCachedSpaceFeed("self"))!;
+ expect(restored.items.map((post) => post.postId)).toEqual(
+ posts.map((post) => post.postId),
+ );
+ expect(restored.nextCursor).toBe("after-twenty");
+
+ await prependCachedSpaceFeedPost("self", post(21, "self"));
+ clearSpaceFeedMemoryCache();
+ const afterPosting = (await loadCachedSpaceFeed("self"))!;
+ expect(afterPosting.items.map((post) => post.postId)).toEqual([
+ 21,
+ ...posts.slice(0, 19).map((post) => post.postId),
+ ]);
+ expect(afterPosting.nextCursor).toBeUndefined();
+ expect(afterPosting.dirty).toBe(true);
+});
+
+test("shrinks an existing thirty-post cache without losing the visit cutoff or skipping posts", async () => {
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(30)] },
+ undefined,
+ 100,
+ );
+ const [key] = vi.mocked(setKV).mock.calls[0]!;
+ const snapshot = (await loadCachedSpaceFeed("self"))!;
+ const posts = Array.from({ length: 30 }, (_, index) => post(30 - index));
+ storage.set(key, { ...snapshot, items: posts, nextCursor: "after-thirty" });
+ clearSpaceFeedMemoryCache();
+ const restored = (await loadCachedSpaceFeed("self"))!;
+ expect(restored.items.map((post) => post.postId)).toEqual(
+ posts.slice(0, 20).map((post) => post.postId),
+ );
+ expect(restored.nextCursor).toBeUndefined();
+ expect(restored.dirty).toBe(true);
+ expect(restored.lastVisitedAtMs).toBe(100);
+ expect((await loadSpaceFeedSession("self"))?.newPostsSinceMs).toBe(100);
+});
+
test("restores every photo in order and preserves shared post edits", async () => {
const original = post(3);
original.photos = ["cover", "second", "third"].map((objectKey, index) => ({
@@ -181,3 +230,235 @@ test("a delayed refresh cannot overwrite a publication or deletion", async () =>
(await loadCachedSpaceFeed("self"))?.items.map((item) => item.postId),
).toEqual([3, 2]);
});
+
+test("remembers the previous visit across reloads and cache mutations", async () => {
+ await cacheCurrentSpaceFeedPage("self", { items: [post(2)] });
+ expect(
+ (await loadCachedSpaceFeed("self"))?.lastVisitedAtMs,
+ ).toBeUndefined();
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(2)] },
+ undefined,
+ 100,
+ );
+ clearSpaceFeedMemoryCache();
+ expect((await loadCachedSpaceFeed("self"))?.lastVisitedAtMs).toBe(100);
+ await prependCachedSpaceFeedPost("self", post(3, "self"));
+ await patchCachedSpaceFeedPost("self", 2, { viewerLiked: true });
+ await removeCachedSpaceFeedPost("self", 3);
+ await cacheCurrentSpaceFeedPage("self", { items: [post(2)] });
+ expect((await loadCachedSpaceFeed("self"))?.lastVisitedAtMs).toBe(100);
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(2)] },
+ undefined,
+ 200,
+ );
+ clearSpaceFeedMemoryCache();
+ expect((await loadCachedSpaceFeed("self"))?.lastVisitedAtMs).toBe(200);
+ expect(await loadCachedSpaceFeed("other")).toBeUndefined();
+});
+
+test("a rejected refresh does not consume a visit", async () => {
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(2)] },
+ undefined,
+ 100,
+ );
+ const cached = await loadCachedSpaceFeed("self");
+ await prependCachedSpaceFeedPost("self", post(3));
+ expect(
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(2)] },
+ { syncedAtMs: cached?.syncedAtMs },
+ 200,
+ ),
+ ).toBe(false);
+ expect((await loadCachedSpaceFeed("self"))?.lastVisitedAtMs).toBe(100);
+});
+
+test("the latest cutoff survives navigation and advances only on a new app session", async () => {
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(100)] },
+ undefined,
+ 100,
+ );
+ const session = (await loadSpaceFeedSession("self"))!;
+ expect(session.newPostsSinceMs).toBe(100);
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(150), post(100)] },
+ undefined,
+ 200,
+ );
+ session.presentedPostIdentities.add("post:150");
+ const returned = (await loadSpaceFeedSession("self"))!;
+ expect(returned).toBe(session);
+ expect(returned.newPostsSinceMs).toBe(100);
+ expect(returned.latestPosts.map((post) => post.postId)).toEqual([150]);
+ expect(returned.presentedPostIdentities.has("post:150")).toBe(true);
+
+ clearSpaceFeedMemoryCache();
+ const reopened = (await loadSpaceFeedSession("self"))!;
+ expect(reopened.newPostsSinceMs).toBe(200);
+ expect(reopened.latestPosts).toEqual([]);
+ expect(reopened.presentedPostIdentities.size).toBe(0);
+});
+
+test("returning to the feed retains more than twenty latest posts while disk caching stays bounded", async () => {
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(100)] },
+ undefined,
+ 100,
+ );
+ const session = (await loadSpaceFeedSession("self"))!;
+ const posts = Array.from({ length: 45 }, (_, index) => post(145 - index));
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: posts.slice(0, 20), nextCursor: "older" },
+ undefined,
+ 200,
+ );
+ await rememberSpaceFeedSessionPosts("self", posts.slice(20));
+ await cacheCurrentSpaceFeedPage("self", {
+ items: posts.slice(0, 20),
+ nextCursor: "older",
+ });
+ expect(await loadSpaceFeedSession("self")).toBe(session);
+ expect(
+ spaceFeedSessionItems(session, posts.slice(0, 20)).map(
+ (post) => post.postId,
+ ),
+ ).toEqual(posts.map((post) => post.postId));
+ expect((await loadCachedSpaceFeed("self"))?.items).toHaveLength(20);
+ clearSpaceFeedMemoryCache();
+ expect((await loadCachedSpaceFeed("self"))?.items).toHaveLength(20);
+ expect((await loadSpaceFeedSession("self"))?.latestPosts).toEqual([]);
+});
+
+test.each([{ remaining: [150] }, { remaining: [] }])(
+ "a complete refresh removes deleted latest posts when remaining IDs are $remaining",
+ async ({ remaining }) => {
+ await cacheCurrentSpaceFeedPage("self", { items: [] }, undefined, 100);
+ const session = (await loadSpaceFeedSession("self"))!;
+ await cacheCurrentSpaceFeedPage("self", {
+ items: [post(150), post(140)],
+ nextCursor: "older",
+ });
+ await rememberSpaceFeedSessionPosts("self", [post(120)]);
+
+ const items = remaining.map((id) => post(id));
+ await cacheCurrentSpaceFeedPage("self", { items });
+ expect(await loadSpaceFeedSession("self")).toBe(session);
+ expect(session.latestPosts.map((post) => post.postId)).toEqual(
+ remaining,
+ );
+ expect(
+ spaceFeedSessionItems(session, items).map((post) => post.postId),
+ ).toEqual(remaining);
+ },
+);
+
+test("a partial refresh removes missing latest posts in its range and retains older pages", async () => {
+ await cacheCurrentSpaceFeedPage("self", { items: [] }, undefined, 100);
+ const session = (await loadSpaceFeedSession("self"))!;
+ await cacheCurrentSpaceFeedPage("self", {
+ items: [post(160), post(150), post(140), post(130)],
+ nextCursor: "older",
+ });
+ await rememberSpaceFeedSessionPosts("self", [post(120), post(110)]);
+ session.presentedPostIdentities.add("post:150");
+
+ const items = [post(170), { ...post(150), caption: "Updated" }, post(130)];
+ await cacheCurrentSpaceFeedPage("self", { items, nextCursor: "older" });
+ expect(session.latestPosts.map((post) => post.postId)).toEqual([
+ 170, 150, 130, 120, 110,
+ ]);
+ expect(
+ spaceFeedSessionItems(session, items).map((post) => post.postId),
+ ).toEqual([170, 150, 130, 120, 110]);
+ expect(
+ session.latestPosts.find((post) => post.postId == 150)?.caption,
+ ).toBe("Updated");
+ expect(session.newPostsSinceMs).toBe(100);
+ expect(session.presentedPostIdentities.has("post:150")).toBe(true);
+});
+
+test("a refresh uses post IDs to distinguish posts at the same boundary timestamp", async () => {
+ await cacheCurrentSpaceFeedPage("self", { items: [] }, undefined, 100);
+ const session = (await loadSpaceFeedSession("self"))!;
+ await cacheCurrentSpaceFeedPage("self", {
+ items: [151, 150, 149].map((id) => ({ ...post(id), timestampMs: 150 })),
+ nextCursor: "older",
+ });
+ await rememberSpaceFeedSessionPosts("self", [post(140)]);
+
+ await cacheCurrentSpaceFeedPage("self", {
+ items: [post(160), post(150)],
+ nextCursor: "older",
+ });
+ expect(session.latestPosts.map((post) => post.postId)).toEqual([
+ 160, 150, 149, 140,
+ ]);
+});
+
+test("edits and deletions from other pages update retained latest posts outside the disk cache", async () => {
+ await cacheCurrentSpaceFeedPage(
+ "self",
+ { items: [post(100)] },
+ undefined,
+ 100,
+ );
+ const session = (await loadSpaceFeedSession("self"))!;
+ const posts = Array.from({ length: 15 }, (_, index) => post(115 - index));
+ await cacheCurrentSpaceFeedPage("self", {
+ items: posts.slice(0, 10),
+ nextCursor: "older",
+ });
+ await rememberSpaceFeedSessionPosts("self", posts.slice(10));
+ await patchCachedSpaceFeedPost("self", 101, {
+ caption: "Edited elsewhere",
+ viewerLiked: true,
+ });
+ expect(
+ session.latestPosts.find((post) => post.postId == 101),
+ ).toMatchObject({ caption: "Edited elsewhere", viewerLiked: true });
+ await removeCachedSpaceFeedPost("self", 101);
+ expect(session.latestPosts.some((post) => post.postId == 101)).toBe(false);
+ await removeCachedSpaceFeedPostsBySpace("self", "friend");
+ expect(session.latestPosts).toEqual([]);
+});
+
+test("a first-session publication stays latest until the next app opening", async () => {
+ const session = (await loadSpaceFeedSession("self"))!;
+ const ownPost = post(session.newPostsSinceMs + 1, "self");
+ await prependCachedSpaceFeedPost("self", ownPost);
+ expect(await loadSpaceFeedSession("self")).toBe(session);
+ expect(session.latestPosts.map((post) => post.postId)).toEqual([
+ ownPost.postId,
+ ]);
+ await cacheCurrentSpaceFeedPage("self", { items: [ownPost] });
+ expect(session.latestPosts.map((post) => post.postId)).toEqual([
+ ownPost.postId,
+ ]);
+ clearSpaceFeedMemoryCache();
+ expect((await loadSpaceFeedSession("self"))?.latestPosts).toEqual([]);
+});
+
+test("latest sessions are isolated between accounts, spaces and servers", async () => {
+ const session = (await loadSpaceFeedSession("self"))!;
+ await prependCachedSpaceFeedPost("self", post(1, "self"));
+ expect((await loadSpaceFeedSession("other"))?.latestPosts).toEqual([]);
+ vi.mocked(savedPartialLocalUser).mockReturnValue({ id: 2 });
+ expect((await loadSpaceFeedSession("self"))?.latestPosts).toEqual([]);
+ vi.mocked(savedPartialLocalUser).mockReturnValue({ id: 1 });
+ vi.mocked(apiOrigin).mockResolvedValue("https://other.example.com");
+ expect((await loadSpaceFeedSession("self"))?.latestPosts).toEqual([]);
+ vi.mocked(apiOrigin).mockResolvedValue("https://api.example.com");
+ expect(await loadSpaceFeedSession("self")).toBe(session);
+});
diff --git a/web/apps/space/tests/home-feed.test.ts b/web/apps/space/tests/home-feed.test.ts
new file mode 100644
index 0000000000..2799be2a26
--- /dev/null
+++ b/web/apps/space/tests/home-feed.test.ts
@@ -0,0 +1,110 @@
+import { expect, test } from "vitest";
+import type { SpacePost } from "../src/services/space";
+import type { LocalSpaceFeedPost } from "../src/state/app-state";
+import { homeFeedEntries } from "../src/utils/home-feed";
+
+const post = (postId: number, timestampMs: number): SpacePost => ({
+ friendID: "friend",
+ name: "Friend",
+ postId,
+ spaceId: "friend",
+ timestampMs,
+ viewerLiked: false,
+});
+
+test("the first visit puts all existing posts in the grid, including later pages", () => {
+ const posts = [post(3, 300), post(2, 200), post(1, 100)];
+ expect(homeFeedEntries(posts, [], undefined)).toEqual({
+ latest: [],
+ history: posts,
+ });
+ expect(homeFeedEntries(posts, [], 400)).toEqual({
+ latest: [],
+ history: posts,
+ });
+});
+
+test("new posts stay full size for the visit and join history on the next visit", () => {
+ const newest = post(3, 300);
+ const existing = post(2, 200);
+ const older = post(1, 100);
+ const firstPage = homeFeedEntries([newest, existing], [], 200);
+ expect(firstPage.latest.map((entry) => entry.identity)).toEqual(["post:3"]);
+ expect(firstPage.history).toEqual([existing]);
+ const nextPage = homeFeedEntries([newest, existing, older], [], 200);
+ expect(nextPage.latest).toEqual(firstPage.latest);
+ expect(nextPage.history).toEqual([existing, older]);
+ expect(homeFeedEntries([newest, existing, older], [], 400)).toEqual({
+ latest: [],
+ history: [newest, existing, older],
+ });
+});
+
+test("upload completion does not duplicate a post or move it into the grid", () => {
+ const uploaded = post(3, 300);
+ const existing = post(2, 200);
+ const local: LocalSpaceFeedPost = {
+ id: "upload",
+ post: uploaded,
+ status: "ready",
+ };
+ const uploading = homeFeedEntries([existing], [local], 200);
+ const refreshed = homeFeedEntries([uploaded, existing], [local], 200);
+ expect(refreshed).toEqual(uploading);
+ expect(refreshed.latest.map((entry) => entry.identity)).toEqual(["post:3"]);
+ expect(refreshed.history).toEqual([existing]);
+ const resolved = homeFeedEntries([uploaded, existing], [], 200);
+ expect(resolved.latest.map((entry) => entry.identity)).toEqual(["post:3"]);
+ expect(resolved.history).toEqual([existing]);
+ expect(homeFeedEntries([uploaded, existing], [local], 400)).toEqual({
+ latest: [],
+ history: [uploaded, existing],
+ });
+});
+
+test("pending and failed uploads remain cards even without a previous visit", () => {
+ const pending: LocalSpaceFeedPost = {
+ caption: "Uploading",
+ frameAspectRatio: 1,
+ friendID: "self",
+ id: "upload",
+ imageUrl: "blob:preview",
+ name: "Me",
+ photoCount: 1,
+ spaceId: "self",
+ status: "pending",
+ timestampMs: 300,
+ };
+ for (const status of ["pending", "failed"] as const) {
+ const result = homeFeedEntries([], [{ ...pending, status }], undefined);
+ expect(result.latest.map((entry) => entry.identity)).toEqual([
+ "local:upload",
+ ]);
+ expect(result.history).toEqual([]);
+ }
+});
+
+test("a post published in this session stays latest after the server replaces the local upload", () => {
+ const uploaded = post(3, 200);
+ const local: LocalSpaceFeedPost = {
+ id: "upload",
+ post: uploaded,
+ status: "ready",
+ };
+ const latestPostIDs = new Set([uploaded.postId]);
+ const localEntries = homeFeedEntries(
+ [uploaded],
+ [local],
+ 300,
+ latestPostIDs,
+ );
+ const remoteEntries = homeFeedEntries([uploaded], [], 300, latestPostIDs);
+ expect(localEntries.latest.map((entry) => entry.identity)).toEqual([
+ "post:3",
+ ]);
+ expect(remoteEntries.latest.map((entry) => entry.identity)).toEqual([
+ "post:3",
+ ]);
+ expect(remoteEntries.history).toEqual([]);
+ expect(homeFeedEntries([uploaded], [], 300).history).toEqual([uploaded]);
+});
diff --git a/web/apps/space/tests/profile-photo-layout.test.ts b/web/apps/space/tests/profile-photo-layout.test.ts
index c8a098b53c..8ef3c89e0e 100644
--- a/web/apps/space/tests/profile-photo-layout.test.ts
+++ b/web/apps/space/tests/profile-photo-layout.test.ts
@@ -1,42 +1,39 @@
import { expect, test } from "vitest";
import {
+ postPhotoLayout,
profilePhotoGap,
- profilePhotoRows,
} from "../src/utils/profile-photo-layout";
const photos = (ratios: number[]) =>
- ratios.map((aspectRatio, id) => ({ id, aspectRatio }));
+ ratios.map((aspectRatio, id) => ({ id: String(id), aspectRatio }));
test.each([
{ count: 2, rowSizes: [2] },
{ count: 3, rowSizes: [3] },
{ count: 4, rowSizes: [2, 2] },
-])(
- "a profile with $count photos uses the adaptive grid",
- ({ count, rowSizes }) => {
- const tiles = photos(new Array<number>(count).fill(2 / 3));
- const rows = profilePhotoRows(tiles, 352);
- expect(rows.map(({ tiles }) => tiles.length)).toEqual(rowSizes);
- expect(rows.flatMap(({ tiles }) => tiles)).toEqual(tiles);
- },
-);
+])("the adaptive grid fits $count photos into rows", ({ count, rowSizes }) => {
+ const tiles = photos(new Array<number>(count).fill(2 / 3));
+ const rows = postPhotoLayout(tiles, 352).rows;
+ expect(rows.map(({ tiles }) => tiles.length)).toEqual(rowSizes);
+ expect(rows.flatMap(({ tiles }) => tiles)).toEqual(tiles);
+});
-test("a profile with exactly five photos uses the adaptive grid throughout", () => {
+test("the adaptive grid arranges five landscape photos", () => {
const tiles = photos([3 / 2, 3 / 2, 3 / 2, 3 / 2, 3 / 2]);
- const rows = profilePhotoRows(tiles, 352);
+ const rows = postPhotoLayout(tiles, 352).rows;
expect(rows.map(({ tiles }) => tiles.map(({ id }) => id))).toEqual([
- [0, 1],
- [2, 3],
- [4],
+ ["0", "1"],
+ ["2", "3"],
+ ["4"],
]);
});
test("three portraits share a compact row", () => {
expect(
- profilePhotoRows(
+ postPhotoLayout(
photos([2 / 3, 3 / 4, 2 / 3, 2 / 3, 3 / 4, 2 / 3]),
328,
- ).map(({ tiles }) => tiles.length),
+ ).rows.map(({ tiles }) => tiles.length),
).toEqual([3, 3]);
});
@@ -47,7 +44,7 @@ test.each([
"a row of $count tall portraits fills the grid without cropping",
({ ratios }) => {
const width = 328;
- const rows = profilePhotoRows(photos(ratios), width);
+ const rows = postPhotoLayout(photos(ratios), width).rows;
expect(rows).toHaveLength(1);
const row = rows[0]!;
expect(row.width).toBe(width);
@@ -62,8 +59,8 @@ test.each([
},
);
-test("a lone portrait within a larger section keeps its height limit", () => {
- const rows = profilePhotoRows(photos([8, 0.25]), 328);
+test("a lone portrait within a larger grid keeps its height limit", () => {
+ const rows = postPhotoLayout(photos([8, 0.25]), 328).rows;
expect(rows.map(({ tiles }) => tiles.length)).toEqual([1, 1]);
expect(rows[1]!.height).toBe(246);
expect(rows[1]!.width).toBe(61.5);
@@ -72,32 +69,32 @@ test("a lone portrait within a larger section keeps its height limit", () => {
test("a landscape can share a row with two portraits to avoid a lone portrait", () => {
const tiles = photos([3 / 4, 3 / 4, 16 / 9, 3 / 4, 9 / 16]);
expect(
- profilePhotoRows(tiles, 363).map(({ tiles }) =>
+ postPhotoLayout(tiles, 363).rows.map(({ tiles }) =>
tiles.map(({ id }) => id),
),
).toEqual([
- [0, 1],
- [2, 3, 4],
+ ["0", "1"],
+ ["2", "3", "4"],
]);
});
-test("a single-post section fills the width with the feed's portrait height cap", () => {
+test("a single-post grid fills the width with the feed's portrait height cap", () => {
const tiles = photos([9 / 16]);
- expect(profilePhotoRows(tiles, 324)).toEqual([
+ expect(postPhotoLayout(tiles, 324).rows).toEqual([
{ aspectRatio: 9 / 16, height: 432, width: 324, tiles },
]);
});
test("similar landscapes are not forced into full-width rows", () => {
const tiles = photos(new Array<number>(10).fill(3 / 2));
- const rows = profilePhotoRows(tiles, 358);
+ const rows = postPhotoLayout(tiles, 358).rows;
expect(rows.map(({ tiles }) => tiles.length)).toEqual([2, 2, 2, 2, 2]);
expect(rows.flatMap(({ tiles }) => tiles)).toEqual(tiles);
});
test("wider photos stand alone when that fits better than a short paired row", () => {
const tiles = photos([3 / 2, 3 / 2, 5 / 3, 5 / 3, 3 / 2, 3 / 2]);
- const rows = profilePhotoRows(tiles, 358);
+ const rows = postPhotoLayout(tiles, 358).rows;
expect(rows.map(({ tiles }) => tiles.length)).toEqual([2, 1, 1, 2]);
expect(rows.flatMap(({ tiles }) => tiles)).toEqual(tiles);
});
@@ -105,23 +102,23 @@ test("wider photos stand alone when that fits better than a short paired row", (
test("row grouping adapts to the available width and accounts for gaps", () => {
const tiles = photos([1.5, 1.5, 1.5, 1.5, 1.5, 1.5]);
expect(
- profilePhotoRows(tiles, 299 + profilePhotoGap).map(
+ postPhotoLayout(tiles, 299 + profilePhotoGap).rows.map(
({ tiles }) => tiles.length,
),
).toEqual([1, 1, 1, 1, 1, 1]);
expect(
- profilePhotoRows(tiles, 300 + profilePhotoGap).map(
+ postPhotoLayout(tiles, 300 + profilePhotoGap).rows.map(
({ tiles }) => tiles.length,
),
).toEqual([2, 2, 2]);
expect(
- profilePhotoRows(tiles, 456).map(({ tiles }) => tiles.length),
+ postPhotoLayout(tiles, 456).rows.map(({ tiles }) => tiles.length),
).toEqual([2, 2, 2]);
});
test("a panorama keeps its aspect ratio even when it cannot reach the minimum", () => {
const tiles = photos([8, 1, 1, 1, 1]);
- const rows = profilePhotoRows(tiles, 328);
+ const rows = postPhotoLayout(tiles, 328).rows;
expect(rows.map(({ tiles }) => tiles.length)).toEqual([1, 2, 2]);
expect(rows[0]!.aspectRatio).toBe(8);
});
@@ -130,7 +127,7 @@ test.each([288, 328, 358, 568])(
"rows preserve order, fit a %ipx grid, and meet the minimum when possible",
(width) => {
const tiles = photos([1.5, 1.2, 1.8, 0.75, 0.6, 8, 0.05, 1, 2, 1.5]);
- const rows = profilePhotoRows(tiles, width);
+ const rows = postPhotoLayout(tiles, width).rows;
expect(rows.flatMap(({ tiles }) => tiles)).toEqual(tiles);
for (const row of rows) {
expect(row.tiles.length).toBeLessThanOrEqual(3);
@@ -152,9 +149,141 @@ test.each([288, 328, 358, 568])(
);
test("an empty grid has no rows", () => {
- expect(profilePhotoRows([], 328)).toEqual([]);
+ expect(postPhotoLayout([], 328).rows).toEqual([]);
});
test("the grid waits for its width to be measured", () => {
- expect(profilePhotoRows(photos([3 / 4, 3 / 2]), 0)).toEqual([]);
+ expect(postPhotoLayout(photos([3 / 4, 3 / 2]), 0).rows).toEqual([]);
+});
+
+test.each([1, 2, 3, 4, 5, 6, 7])(
+ "a complete collection of %i posts gives each photo its own full-width row",
+ (count) => {
+ const tiles = photos([16 / 9, 3 / 4, 1, 9 / 16, 2, 0.3, 1.5]).slice(
+ 0,
+ count,
+ );
+ const layout = postPhotoLayout(tiles, 324, undefined, count);
+ expect(layout.fullWidth).toBe(true);
+ expect(layout.rows).toHaveLength(count);
+ expect(layout.rows.flatMap((row) => row.tiles)).toEqual(tiles);
+ layout.rows.forEach((row) => {
+ expect(row.width).toBe(324);
+ expect(row.height).toBeCloseTo(
+ Math.min(324 / row.tiles[0]!.aspectRatio, 432),
+ );
+ });
+ },
+);
+
+test("eight posts use the adaptive grid", () => {
+ const tiles = photos(new Array<number>(8).fill(1));
+ const layout = postPhotoLayout(tiles, 352, undefined, 8);
+ expect(layout.fullWidth).toBe(false);
+ expect(layout.rows).toEqual(postPhotoLayout(tiles, 352).rows);
+});
+
+test.each([undefined, 8])(
+ "two loaded photos do not imply a small collection when the total is %s",
+ (postCount) => {
+ const tiles = photos([16 / 9, 3 / 4]);
+ const layout = postPhotoLayout(tiles, 352, undefined, postCount);
+ expect(layout.fullWidth).toBe(false);
+ expect(layout.rows).toHaveLength(1);
+ },
+);
+
+test("the layout decision waits for photos and a measured width", () => {
+ const tiles = photos([16 / 9, 3 / 4]);
+ const empty = postPhotoLayout([], 352, undefined, 0);
+ expect(empty.fullWidth).toBeUndefined();
+ const unmeasured = postPhotoLayout(tiles, 0, empty, 2);
+ expect(unmeasured.fullWidth).toBeUndefined();
+ expect(postPhotoLayout(tiles, 352, unmeasured, 2).fullWidth).toBe(true);
+});
+
+test("crossing seven posts keeps the chosen layout until the next opening", () => {
+ const tiles = photos(new Array<number>(8).fill(1));
+ const initial = postPhotoLayout(tiles.slice(0, 7), 352, undefined, 7);
+ const appended = postPhotoLayout(tiles, 352, initial, 8);
+ expect(appended.fullWidth).toBe(true);
+ expect(appended.rows.slice(0, 7)).toEqual(initial.rows);
+ expect(appended.rows.every((row) => row.tiles.length == 1)).toBe(true);
+
+ const reopened = postPhotoLayout(tiles, 352, undefined, 8);
+ expect(reopened.fullWidth).toBe(false);
+ const afterDeletion = postPhotoLayout(tiles.slice(0, 7), 352, reopened, 7);
+ expect(afterDeletion.fullWidth).toBe(false);
+});
+
+test("resizing retains the full-width layout for a small collection", () => {
+ const tiles = photos([16 / 9, 3 / 4]);
+ const initial = postPhotoLayout(tiles, 352, undefined, 2);
+ const resized = postPhotoLayout(tiles, 600, initial, 2);
+ expect(resized.fullWidth).toBe(true);
+ expect(resized.rows).toHaveLength(2);
+ expect(resized.rows.every((row) => row.width == 600)).toBe(true);
+});
+
+test.each([1, 3, 10])(
+ "appending pages preserves every row from the initial %i photos",
+ (initialCount) => {
+ const tiles = photos(
+ Array.from(
+ { length: 40 },
+ (_, index) => [3 / 4, 3 / 2, 9 / 16, 1, 8][index % 5]!,
+ ),
+ );
+ let layout = postPhotoLayout(tiles.slice(0, initialCount), 352);
+ for (let count = initialCount + 10; count < 50; count += 10) {
+ const loadedTiles = tiles.slice(0, count);
+ const next = postPhotoLayout(loadedTiles, 352, layout);
+ expect(next.rows.slice(0, layout.rows.length)).toEqual(layout.rows);
+ expect(next.rows.flatMap((row) => row.tiles)).toEqual(loadedTiles);
+ layout = next;
+ }
+ },
+);
+
+test("late dimensions do not resize existing rows or their tiles", () => {
+ const tiles = photos([1, 1, 1]);
+ const initial = postPhotoLayout(tiles, 352);
+ const updated = tiles.map((tile) => ({ ...tile, aspectRatio: 9 / 16 }));
+ const next = postPhotoLayout(
+ [...updated, { id: "older", aspectRatio: 3 / 2 }],
+ 352,
+ initial,
+ );
+ expect(next.rows.slice(0, initial.rows.length)).toEqual(initial.rows);
+ expect(next.rows.at(-1)!.tiles).toEqual([
+ { id: "older", aspectRatio: 3 / 2 },
+ ]);
+});
+
+test("deleting a photo retains preceding rows and removes the deleted tile", () => {
+ const tiles = photos([1, 1, 1, 1, 1, 1]);
+ const initial = postPhotoLayout(tiles, 352);
+ const remaining = tiles.filter((tile) => tile.id != "3");
+ const next = postPhotoLayout(remaining, 352, initial);
+ expect(next.rows[0]).toEqual(initial.rows[0]);
+ expect(next.rows.flatMap((row) => row.tiles)).toEqual(remaining);
+});
+
+test("a replaced or reordered list uses the current photo order", () => {
+ const tiles = photos([3 / 4, 3 / 2, 1, 9 / 16]);
+ const initial = postPhotoLayout(tiles, 352);
+ const reordered = [...tiles].reverse();
+ const next = postPhotoLayout(reordered, 352, initial);
+ expect(next.rows).toEqual(postPhotoLayout(reordered, 352).rows);
+ expect(next.rows.flatMap((row) => row.tiles)).toEqual(reordered);
+ expect(postPhotoLayout([], 352, next).rows).toEqual([]);
+});
+
+test("resizing recalculates rows to fit the new width", () => {
+ const tiles = photos([3 / 2, 3 / 2, 3 / 2, 3 / 2]);
+ const initial = postPhotoLayout(tiles, 352);
+ const next = postPhotoLayout(tiles, 600, initial);
+ expect(next.width).toBe(600);
+ expect(next.rows).toEqual(postPhotoLayout(tiles, 600).rows);
+ expect(next.rows).not.toEqual(initial.rows);
});
diff --git a/web/apps/space/tests/profile-post-sections.test.ts b/web/apps/space/tests/profile-post-sections.test.ts
deleted file mode 100644
index 73d5ed94be..0000000000
--- a/web/apps/space/tests/profile-post-sections.test.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { expect, test } from "vitest";
-import { profilePostSections } from "../src/utils/profile-post-sections";
-
-const post = (id: string, timestamp: Date) => ({
- id,
- timestampMs: timestamp.getTime(),
-});
-
-test("each post appears once in the first matching calendar section", () => {
- const now = new Date(2026, 8, 24, 12);
- const posts = [
- post("today", new Date(2026, 8, 24)),
- post("yesterday", new Date(2026, 8, 23)),
- post("this-week", new Date(2026, 8, 21)),
- post("last-week-end", new Date(2026, 8, 20, 23, 59, 59, 999)),
- post("last-week-start", new Date(2026, 8, 14)),
- post("this-month", new Date(2026, 8, 13, 23, 59, 59, 999)),
- post("august-1", new Date(2026, 7, 31)),
- post("august-2", new Date(2026, 7, 1)),
- post("july", new Date(2026, 6, 1)),
- post("last-year", new Date(2025, 7, 1)),
- ];
- const sections = profilePostSections(posts, now);
-
- expect(
- sections.map(({ title, items }) => [title, items.map((p) => p.id)]),
- ).toEqual([
- ["Today", ["today"]],
- ["Yesterday", ["yesterday"]],
- ["This week", ["this-week"]],
- ["Last week", ["last-week-end", "last-week-start"]],
- ["This month", ["this-month"]],
- ["Aug 2026", ["august-1", "august-2"]],
- ["Jul 2026", ["july"]],
- ["Aug 2025", ["last-year"]],
- ]);
- expect(sections.flatMap(({ items }) => items)).toEqual(posts);
- expect(new Set(sections.map(({ id }) => id)).size).toBe(sections.length);
-});
-
-test("a new month still gives yesterday and weekly sections priority", () => {
- const posts = [
- post("today", new Date(2026, 9, 1)),
- post("yesterday", new Date(2026, 8, 30)),
- post("monday", new Date(2026, 8, 28)),
- post("sunday", new Date(2026, 8, 27)),
- post("last-monday", new Date(2026, 8, 21)),
- post("older", new Date(2026, 8, 20)),
- ];
- expect(
- profilePostSections(posts, new Date(2026, 9, 1, 12)).map(
- ({ title, items }) => [title, items.map((p) => p.id)],
- ),
- ).toEqual([
- ["Today", ["today"]],
- ["Yesterday", ["yesterday"]],
- ["This week", ["monday"]],
- ["Last week", ["sunday", "last-monday"]],
- ["Sep 2026", ["older"]],
- ]);
-});
-
-test("Monday starts a new week while Sunday remains yesterday", () => {
- const posts = [
- post("monday", new Date(2026, 8, 28)),
- post("sunday", new Date(2026, 8, 27)),
- post("saturday", new Date(2026, 8, 26)),
- ];
- expect(
- profilePostSections(posts, new Date(2026, 8, 28, 12)).map(
- ({ title }) => title,
- ),
- ).toEqual(["Today", "Yesterday", "Last week"]);
-});
-
-test("Sunday is the last day of this week", () => {
- const posts = [
- post("friday", new Date(2026, 8, 25)),
- post("monday", new Date(2026, 8, 21)),
- post("last-sunday", new Date(2026, 8, 20)),
- ];
- expect(
- profilePostSections(posts, new Date(2026, 8, 27, 12)).map(
- ({ title, items }) => [title, items.map((p) => p.id)],
- ),
- ).toEqual([
- ["This week", ["friday", "monday"]],
- ["Last week", ["last-sunday"]],
- ]);
-});
-
-test("last week spans the year boundary", () => {
- const posts = [
- post("yesterday", new Date(2026, 0, 4)),
- post("saturday", new Date(2026, 0, 3)),
- post("last-monday", new Date(2025, 11, 29)),
- post("older", new Date(2025, 11, 28)),
- ];
- expect(
- profilePostSections(posts, new Date(2026, 0, 5, 12)).map(
- ({ title, items }) => [title, items.map((p) => p.id)],
- ),
- ).toEqual([
- ["Yesterday", ["yesterday"]],
- ["Last week", ["saturday", "last-monday"]],
- ["Dec 2025", ["older"]],
- ]);
-});
-
-test("month headings include the year and skip empty periods", () => {
- const posts = [
- post("december", new Date(2025, 11, 21)),
- post("october", new Date(2025, 9, 15)),
- post("older-december", new Date(2024, 11, 31)),
- ];
- expect(
- profilePostSections(posts, new Date(2026, 0, 1, 12)).map(
- ({ title }) => title,
- ),
- ).toEqual(["Dec 2025", "Oct 2025", "Dec 2024"]);
- expect(profilePostSections([], new Date(2026, 0, 1))).toEqual([]);
-});
-
-test.each([
- { now: new Date(2026, 2, 9, 12), olderTitle: "This month" },
- { now: new Date(2026, 10, 2, 12), olderTitle: "Oct 2026" },
-])(
- "uses local midnights across daylight saving changes: $now",
- ({ now, olderTitle }) => {
- const year = now.getFullYear();
- const month = now.getMonth();
- const day = now.getDate();
- const posts = [
- post("today", new Date(year, month, day)),
- post("late-yesterday", new Date(year, month, day - 1, 23, 59)),
- post("early-yesterday", new Date(year, month, day - 1)),
- post("before-yesterday", new Date(year, month, day - 2, 23, 59)),
- post("last-week-start", new Date(year, month, day - 7)),
- post("before-last-week", new Date(year, month, day - 8, 23, 59)),
- ];
- expect(
- profilePostSections(posts, now).map(({ title, items }) => [
- title,
- items.map((p) => p.id),
- ]),
- ).toEqual([
- ["Today", ["today"]],
- ["Yesterday", ["late-yesterday", "early-yesterday"]],
- ["Last week", ["before-yesterday", "last-week-start"]],
- [olderTitle, ["before-last-week"]],
- ]);
- },
-);