Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add photo viewer motion and Rive likes to Space

Pragba133f0eac73
diff --git a/web/apps/space/package.json b/web/apps/space/package.json
index c823156904..6451f521ca 100644
--- a/web/apps/space/package.json
+++ b/web/apps/space/package.json
@@ -12,6 +12,7 @@
"@fontsource/nunito": "5.3.0",
"@hugeicons/core-free-icons": "4.3.5",
"@hugeicons/react": "1.1.10",
+ "@rive-app/canvas-lite": "2.43.1",
"ente-accounts": "*",
"ente-base": "*",
"ente-media": "*",
diff --git a/web/apps/space/public/images/like.riv b/web/apps/space/public/images/like.riv
new file mode 100644
index 0000000000..1f2cbec1e0
Binary files /dev/null and b/web/apps/space/public/images/like.riv differ
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsx
index ba8993350b..866e00b750 100644
--- a/web/apps/space/src/components/FileViewer.tsx
+++ b/web/apps/space/src/components/FileViewer.tsx
@@ -23,10 +23,16 @@ import { SpaceBottomSheetTransition } from "components/BottomSheetTransition";
import { SpaceCaptionText } from "components/CaptionText";
import { ConfirmationActionSheet } from "components/ConfirmationActionSheet";
import { spacePostLikePopDurationMs } from "components/post-like-animation";
-import { SpacePostPhotosDots } from "components/PostPhotosDots";
+import { photoDotStep, SpacePostPhotosDots } from "components/PostPhotosDots";
import { SpacePostReplyControls } from "components/PostReplyControls";
import { createSpaceVideoContent } from "components/PostVideoContent";
import { SpaceVideoError } from "components/VideoError";
+import {
+ findViewerOrigin,
+ playViewerClose,
+ playViewerOpen,
+ viewerOriginKey,
+} from "components/viewer-transition";
import log from "ente-base/log";
import type PhotoSwipe from "photoswipe";
import React from "react";
@@ -48,6 +54,12 @@ import {
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom, formatSpaceDate } from "utils/display";
import { clampSpaceMessageText } from "utils/message-limits";
+import {
+ shownPhotoState,
+ viewerBackgroundOpacity,
+ type ViewerPhotoState,
+ type ViewerRect,
+} from "utils/viewer-geometry";
const green = "#08C225";
const textBase = spaceText;
@@ -182,6 +194,89 @@ interface SpaceFileViewerProps {
postActionMode?: SpaceViewerPostActionMode;
}
+const setViewerBackground = (root: HTMLElement, opacity: number) =>
+ root.style.setProperty("--space-viewer-bg-opacity", String(opacity));
+
+const viewerPadding = (hasDraftPhotoControls: boolean) => {
+ const isDesktop = window.innerWidth >= viewerDesktopMinWidth;
+ return {
+ bottom: hasDraftPhotoControls
+ ? 176
+ : isDesktop
+ ? 0
+ : viewerBottomPadding,
+ left: 0,
+ right: 0,
+ top: isDesktop ? 0 : viewerHeaderHeight,
+ };
+};
+
+// index is the photo whose dots are shown, position the gallery index as a float.
+const paintStretchingDot = (
+ root: HTMLElement,
+ photos: SpaceViewerPhoto[],
+ index: number,
+ position: number,
+) => {
+ const dot = root.querySelector<HTMLElement>(
+ "[data-space-photo-dots-indicator]",
+ );
+ const photo = photos[index];
+ if (!dot || !photo) return;
+ const count = photo.postPhotoCount ?? 1;
+ const neighbour = photos[position > index ? index + 1 : index - 1];
+ const offset = neighbour?.postId == photo.postId ? position - index : 0;
+ const p = Math.min(
+ count - 1,
+ Math.max(0, (photo.postPhotoIndex ?? 0) + offset),
+ );
+ const from = Math.min(Math.floor(p), count - 2);
+ const head =
+ (from + Math.min(1, Math.max(0, (p - from) * 2))) * photoDotStep;
+ const tail =
+ (from + Math.min(1, Math.max(0, (p - from) * 2 - 1))) * photoDotStep;
+ dot.style.transform = `translate(${tail - 0.5}px, -50%)`;
+ dot.style.width = `${head - tail + 6}px`;
+};
+
+interface ViewerMotion {
+ closing: boolean;
+ landed: boolean;
+ flight?: ReturnType<typeof playViewerOpen>;
+ reveal?: () => void;
+ stopClose?: () => void;
+}
+
+const endOpenFlight = (motion: ViewerMotion, root: HTMLElement) => {
+ motion.flight?.release();
+ motion.flight = undefined;
+ delete root.dataset.spaceViewerFlying;
+ setViewerBackground(root, 1);
+};
+
+// The flying photo stays until PhotoSwipe shows its own, which Safari only does
+// once the image has decoded.
+const handOverOpenFlight = (
+ motion: ViewerMotion,
+ root: HTMLElement,
+ pswp: PhotoSwipe | undefined,
+ attempt = 0,
+) => {
+ if (!motion.flight || !motion.landed || !pswp) return;
+ const content = pswp.currSlide?.content;
+ const isShown =
+ !content?.element ||
+ content.isError() ||
+ (content.element.isConnected && !content.isDecoding);
+ if (!isShown && attempt < 120) {
+ requestAnimationFrame(() =>
+ handOverOpenFlight(motion, root, pswp, attempt + 1),
+ );
+ return;
+ }
+ endOpenFlight(motion, root);
+};
+
const viewerTouchPoint = (event: Event) => {
if ("changedTouches" in event) {
const touch = (event as TouchEvent).changedTouches[0];
@@ -319,7 +414,11 @@ const SpaceViewerPhotoOverlay: React.FC<{
zIndex: 2,
}}
>
- <SpacePostPhotosDots index={photoIndex} count={photoCount} />
+ <SpacePostPhotosDots
+ index={photoIndex}
+ count={photoCount}
+ stretches
+ />
{caption && (
<Box
component={isCaptionTruncated ? "button" : "div"}
@@ -459,6 +558,10 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
const initialPhotoIndexRef = React.useRef(activePhotoIndex);
const fallbackPhotoRef = React.useRef(activePhoto);
const pswpRef = React.useRef<PhotoSwipe | undefined>(undefined);
+ const motionRef = React.useRef<ViewerMotion>({
+ closing: false,
+ landed: false,
+ });
const isSyncingPhotosRef = React.useRef(false);
const videoContentsRef = React.useRef(
new Map<object, ReturnType<typeof createSpaceVideoContent>>(),
@@ -478,6 +581,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
activePhoto.viewerLiked ?? false,
);
const [photoLikePopID, setPhotoLikePopID] = React.useState(0);
+ const [photoLikeToggleID, setPhotoLikeToggleID] = React.useState(0);
const [caption, setCaption] = React.useState(activePhoto.caption ?? "");
const [captionEditValue, setCaptionEditValue] = React.useState(
activePhoto.caption ?? "",
@@ -606,6 +710,102 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
return nextSize;
}, []);
+ const viewerPhotoRect = React.useCallback(
+ (width: number, height: number): ViewerRect => {
+ const viewport = viewerViewportSize();
+ const { top, bottom } = viewerPadding(
+ hasDraftPhotoControlsRef.current,
+ );
+ const areaHeight = viewport.y - top - bottom;
+ const scale = Math.min(1, viewport.x / width, areaHeight / height);
+ const w = width * scale;
+ const h = height * scale;
+ return {
+ x: (viewport.x - w) / 2,
+ y: top + (areaHeight - h) / 2,
+ w,
+ h,
+ };
+ },
+ [viewerViewportSize],
+ );
+
+ const requestCloseRef = React.useRef<
+ (throwVelocity?: { x: number; y: number }) => void
+ >(() => undefined);
+ requestCloseRef.current = (throwVelocity = { x: 0, y: 0 }) => {
+ const motion = motionRef.current;
+ if (motion.closing) return;
+ const root = viewerRootRef.current;
+ const pswp = pswpRef.current;
+ const item =
+ viewerPhotosRef.current[pswp?.currIndex ?? activePhotoIndex];
+ const element = pswp?.currSlide?.content.element;
+ let from: ViewerPhotoState | undefined = motion.flight?.current();
+ let src = from ? item?.imageUrl : undefined;
+ const rect = element?.getBoundingClientRect();
+ if (
+ !from &&
+ rect &&
+ rect.width > 0 &&
+ rect.height > 0 &&
+ element instanceof HTMLImageElement &&
+ element.complete &&
+ element.naturalWidth > 0
+ ) {
+ const scale = Number(pswp?.currSlide?.container.style.scale) || 1;
+ from = shownPhotoState(
+ { x: rect.left, y: rect.top, w: rect.width, h: rect.height },
+ { x: 0, y: 0, w: window.innerWidth, h: window.innerHeight },
+ (parseFloat(element.style.borderRadius) || 0) * scale,
+ );
+ src = element.currentSrc || element.src;
+ }
+ const origin =
+ item && !isDraftPost && !item.video
+ ? findViewerOrigin(viewerOriginKey(item.spaceId, item.postId))
+ : null;
+ const background = root?.style.getPropertyValue(
+ "--space-viewer-bg-opacity",
+ );
+ const startBackground = background ? Number(background) : 1;
+ motion.flight?.stop();
+ motion.flight = undefined;
+ motion.reveal?.();
+ motion.reveal = undefined;
+ if (root) delete root.dataset.spaceViewerFlying;
+ const stop =
+ root && item && origin && from && src
+ ? playViewerClose(
+ root,
+ {
+ origin,
+ src,
+ photo: {
+ width: item.width ?? defaultPhotoWidth,
+ height: item.height ?? defaultPhotoHeight,
+ },
+ },
+ from,
+ throwVelocity,
+ (t) =>
+ setViewerBackground(
+ root,
+ startBackground * viewerBackgroundOpacity(t),
+ ),
+ () => onCloseRef.current(),
+ )
+ : undefined;
+ if (!stop || !root) {
+ onCloseRef.current();
+ return;
+ }
+ motion.closing = true;
+ motion.stopClose = stop;
+ root.dataset.spaceViewerFlying = "true";
+ root.dataset.spaceViewerLeaving = "true";
+ };
+
const requestAddFriendForPostAction = (intent: SpaceInviteIntent) => {
if (!onAddFriendForPostAction) return;
setAddFriendIntent(intent);
@@ -619,6 +819,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
}
const nextLiked = !isPhotoLiked;
+ setPhotoLikeToggleID((id) => id + 1);
if (!activePhoto.postId || !onSetPostLiked) {
setIsPhotoLiked(nextLiked);
if (nextLiked) setPhotoLikePopID((id) => id + 1);
@@ -659,7 +860,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
cancelCaptionEdit();
return;
}
- onClose();
+ requestCloseRef.current();
};
const updateCaption = () => {
@@ -1126,6 +1327,47 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
root.removeEventListener("pointerdown", blockPhotoGesture, true);
}, [isCaptionEditing]);
+ React.useLayoutEffect(() => {
+ const motion = motionRef.current;
+ const root = viewerRootRef.current;
+ const stopMotion = () => {
+ motion.flight?.stop();
+ motion.flight = undefined;
+ motion.stopClose?.();
+ motion.stopClose = undefined;
+ motion.reveal?.();
+ motion.reveal = undefined;
+ if (root) delete root.dataset.spaceViewerFlying;
+ };
+ const item = fallbackPhotoRef.current;
+ if (!root || isDraftPost || item.video || !item.imageUrl)
+ return stopMotion;
+ const origin = findViewerOrigin(
+ viewerOriginKey(item.spaceId, item.postId),
+ );
+ if (!origin) return stopMotion;
+
+ const width = item.width ?? defaultPhotoWidth;
+ const height = item.height ?? defaultPhotoHeight;
+ const flight = playViewerOpen(
+ root,
+ { origin, src: item.imageUrl, photo: { width, height } },
+ viewerPhotoRect(width, height),
+ (t) => setViewerBackground(root, viewerBackgroundOpacity(t)),
+ () => {
+ motion.landed = true;
+ handOverOpenFlight(motion, root, pswpRef.current);
+ },
+ );
+ if (flight) {
+ motion.flight = flight;
+ motion.landed = false;
+ motion.reveal = flight.reveal;
+ root.dataset.spaceViewerFlying = "true";
+ }
+ return stopMotion;
+ }, [isDraftPost, viewerPhotoRect]);
+
React.useEffect(() => {
const root = viewerRootRef.current;
if (!root) return;
@@ -1136,7 +1378,12 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
let swipeStart:
{ x: number; y: number; photoIndex: number } | undefined;
- void import("photoswipe").then(({ default: PhotoSwipeClass }) => {
+ const loadPhotoSwipe = import("photoswipe");
+ void loadPhotoSwipe.catch((error: unknown) => {
+ log.error("Failed to load the photo viewer", error);
+ endOpenFlight(motionRef.current, root);
+ });
+ void loadPhotoSwipe.then(({ default: PhotoSwipeClass }) => {
if (disposed || !viewerRootRef.current) return;
pswp = new PhotoSwipeClass({
@@ -1159,23 +1406,13 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
index: initialPhotoIndexRef.current,
loop: false,
mainClass: "pswp-space-viewer",
- paddingFn: () => ({
- bottom: hasDraftPhotoControlsRef.current
- ? 176
- : window.innerWidth >= viewerDesktopMinWidth
- ? 0
- : viewerBottomPadding,
- left: 0,
- right: 0,
- top:
- window.innerWidth >= viewerDesktopMinWidth
- ? 0
- : viewerHeaderHeight,
- }),
+ paddingFn: () =>
+ viewerPadding(hasDraftPhotoControlsRef.current),
pinchToClose: false,
returnFocus: false,
showHideAnimationType: "none",
- spacing: 0,
+ // A 16px gap between photos on a phone.
+ spacing: 0.04,
tapAction: false,
trapFocus: false,
wheelToZoom: true,
@@ -1246,18 +1483,87 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
};
});
pswp.on("close", () => {
- if (!closedByReact) onCloseRef.current();
+ if (!closedByReact)
+ requestCloseRef.current(pswp!.gestures.velocity);
});
pswp.on("verticalDrag", (event) => {
if (isDismissBlockedRef.current) event.preventDefault();
});
+ const reduceMotion = window.matchMedia(
+ "(prefers-reduced-motion: reduce)",
+ ).matches;
+ // The drag pose and the parallax use the separate `scale` and
+ // `translate` properties, which leave PhotoSwipe's transform alone.
+ let posed:
+ { container: HTMLElement; element?: HTMLElement } | undefined;
+ const clearDismissPose = () => {
+ if (!posed) return;
+ posed.container.style.scale = "";
+ posed.container.style.translate = "";
+ if (posed.element) posed.element.style.borderRadius = "";
+ posed = undefined;
+ };
+ const applyDismissPose = () => {
+ const slide = pswp!.currSlide;
+ if (!slide || reduceMotion) return;
+ if (posed?.container != slide.container) clearDismissPose();
+ const isAtFit =
+ slide.currZoomLevel <= slide.zoomLevels.fit + 0.001;
+ const dy = isAtFit ? slide.pan.y - slide.bounds.center.y : 0;
+ const element = slide.content.element;
+ if (Math.abs(dy) < 0.5) {
+ clearDismissPose();
+ return;
+ }
+ posed = { container: slide.container, element };
+ const scale =
+ 1 -
+ 0.32 *
+ Math.min(
+ 1,
+ Math.abs(dy) / (pswp!.viewportSize.y * 0.55),
+ );
+ const { x, y } = pswp!.gestures.startP1;
+ slide.container.style.scale = String(scale);
+ slide.container.style.translate = `${x * (1 - scale)}px ${y * (1 - scale)}px`;
+ if (element)
+ element.style.borderRadius = `${(24 * Math.min(1, Math.abs(dy) / 140)) / scale}px`;
+ };
pswp.on("zoomPanUpdate", () => {
+ applyDismissPose();
+ if (motionRef.current.flight || motionRef.current.closing)
+ return;
root.style.setProperty(
"--space-viewer-bg-opacity",
String(pswp!.bgOpacity),
);
});
+ pswp.on("moveMainScroll", () => {
+ if (reduceMotion) return;
+ const { currIndex, mainScroll, potentialIndex, viewportSize } =
+ pswp!;
+ const drift =
+ (mainScroll.x - mainScroll.getCurrSlideX()) /
+ mainScroll.slideWidth;
+ for (const { slide } of mainScroll.itemHolders) {
+ if (!slide) continue;
+ const offset = slide.index - potentialIndex + drift;
+ const isAtRest =
+ slide.currZoomLevel <= slide.zoomLevels.initial + 0.001;
+ slide.container.style.translate =
+ isAtRest && Math.abs(offset) > 0.001
+ ? `${-offset * viewportSize.x * 0.4}px 0`
+ : "";
+ }
+ paintStretchingDot(
+ root,
+ viewerPhotosRef.current,
+ currIndex,
+ potentialIndex - drift,
+ );
+ });
pswp.on("change", () => {
+ clearDismissPose();
const nextIndex = pswp?.currIndex;
if (nextIndex != undefined) {
setLocalPhotoIndex(nextIndex);
@@ -1268,6 +1574,8 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
pswp.on("keydown", (event) => {
if (
isSwipeBlockedRef.current ||
+ motionRef.current.flight ||
+ motionRef.current.closing ||
event.originalEvent.target instanceof HTMLTextAreaElement
) {
event.preventDefault();
@@ -1319,10 +1627,20 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
viewerPhotosRef.current.length - 1) ||
(dx > 0 && start.photoIndex == 0))
) {
- onCloseRef.current();
+ requestCloseRef.current();
}
});
pswp.init();
+ const shown =
+ pswp.currSlide?.content.element?.getBoundingClientRect();
+ if (shown && shown.width > 0)
+ motionRef.current.flight?.retarget({
+ x: shown.left,
+ y: shown.top,
+ w: shown.width,
+ h: shown.height,
+ });
+ handOverOpenFlight(motionRef.current, root, pswp);
});
return () => {
@@ -1360,7 +1678,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
cancelCaptionEdit();
return;
}
- onCloseRef.current();
+ requestCloseRef.current();
};
window.addEventListener("keydown", closeOnEscape);
@@ -1421,7 +1739,18 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
fontSize: 14,
},
"& [data-space-viewer-chrome='true'], & [data-space-viewer-bottom='true']":
- { opacity: "var(--space-viewer-bg-opacity, 1)" },
+ {
+ opacity:
+ "calc((var(--space-viewer-bg-opacity, 1) - 0.5) * 2)",
+ },
+ "&[data-space-viewer-leaving='true'] [data-space-viewer-chrome='true'], &[data-space-viewer-leaving='true'] [data-space-viewer-bottom='true']":
+ { opacity: 0, transition: "opacity 140ms ease" },
+ // PhotoSwipe sets an inline opacity, so hide it with visibility.
+ "&[data-space-viewer-flying='true'] .pswp": {
+ visibility: "hidden !important",
+ },
+ "&[data-space-viewer-flying='true'] :is([data-space-viewer-chrome='true'], [data-space-viewer-bottom='true'], [data-space-viewer-chrome='true'] *, [data-space-viewer-bottom='true'] *)":
+ { pointerEvents: "none !important" },
"@media (prefers-reduced-motion: reduce)": {
transition: "none",
},
@@ -2325,6 +2654,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
isReplyMode={isReplyMode}
liked={isPhotoLiked}
likePopID={photoLikePopID}
+ likeToggleID={photoLikeToggleID}
onLike={handlePhotoLikeClick}
onSendReply={sendReply}
replyActionPhase={replyActionPhase}
diff --git a/web/apps/space/src/components/PostLikeHeart.tsx b/web/apps/space/src/components/PostLikeHeart.tsx
new file mode 100644
index 0000000000..d11c1ee39c
--- /dev/null
+++ b/web/apps/space/src/components/PostLikeHeart.tsx
@@ -0,0 +1,168 @@
+import { Box } from "@mui/material";
+import type { Rive, ViewModelInstance } from "@rive-app/canvas-lite";
+import {
+ likeAnimationVariants,
+ pickLikeVariant,
+} from "components/post-like-animation";
+import log from "ente-base/log";
+import React from "react";
+
+// Shows the liked or unliked state without animating.
+const jumpVariant = -1;
+const likeAnimationMs = 1600;
+// The 160px artboard draws a 22px heart; scale it to the 26px icon it replaces.
+const canvasSize = Math.round((160 * 26) / 22);
+
+let likeFile: Promise<ArrayBuffer> | undefined;
+const loadLikeFile = () => {
+ if (!likeFile) {
+ likeFile = fetch("/images/like.riv").then((response) => {
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ return response.arrayBuffer();
+ });
+ void likeFile.catch(() => {
+ likeFile = undefined;
+ });
+ }
+ return likeFile;
+};
+
+interface SpacePostLikeHeartProps {
+ liked: boolean;
+ // Changes on each like or unlike. Other changes of liked do not animate.
+ toggleID: number;
+ fallback: React.ReactNode;
+}
+
+export const SpacePostLikeHeart: React.FC<SpacePostLikeHeartProps> = ({
+ liked,
+ toggleID,
+ fallback,
+}) => {
+ const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
+ const riveRef = React.useRef<Rive | undefined>(undefined);
+ const pauseTimerRef = React.useRef(0);
+ const shownRef = React.useRef({ liked, toggleID, variant: jumpVariant });
+ const [viewModel, setViewModel] = React.useState<ViewModelInstance>();
+
+ // Rive draws every frame while playing, so pause it when idle.
+ const playFor = React.useCallback((ms: number) => {
+ const rive = riveRef.current;
+ if (!rive) return;
+ window.clearTimeout(pauseTimerRef.current);
+ rive.play();
+ pauseTimerRef.current = window.setTimeout(() => rive.pause(), ms);
+ }, []);
+
+ React.useEffect(() => {
+ const canvas = canvasRef.current;
+ if (
+ !canvas ||
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ )
+ return;
+
+ let disposed = false;
+ void Promise.all([import("@rive-app/canvas-lite"), loadLikeFile()])
+ .then(([{ Fit, Layout, Rive, RuntimeLoader }, file]) => {
+ if (disposed) return;
+ // The default is a public CDN, which the CSP blocks.
+ RuntimeLoader.setWasmUrl(
+ new URL("@rive-app/canvas-lite/rive.wasm", import.meta.url)
+ .href,
+ );
+ RuntimeLoader.setWasmFallbackUrl(null);
+ const rive = new Rive({
+ autoBind: true,
+ autoplay: true,
+ buffer: file.slice(0),
+ canvas,
+ enableRiveAssetCDN: false,
+ layout: new Layout({ fit: Fit.Contain }),
+ onLoad: () => {
+ if (disposed) return;
+ rive.resizeDrawingSurfaceToCanvas();
+ const instance = rive.viewModelInstance;
+ if (!instance) {
+ rive.cleanup();
+ riveRef.current = undefined;
+ return;
+ }
+ const variant = instance.number("variant");
+ const isLiked = instance.boolean("liked");
+ if (variant) variant.value = jumpVariant;
+ if (isLiked) isLiked.value = shownRef.current.liked;
+ playFor(150);
+ setViewModel(instance);
+ },
+ onLoadError: () =>
+ log.warn("Failed to load the like animation"),
+ stateMachine: "Like",
+ });
+ riveRef.current = rive;
+ })
+ .catch((error: unknown) => {
+ log.warn("Failed to load the like animation", error);
+ });
+ return () => {
+ disposed = true;
+ window.clearTimeout(pauseTimerRef.current);
+ riveRef.current?.cleanup();
+ riveRef.current = undefined;
+ };
+ }, [playFor]);
+
+ React.useEffect(() => {
+ const shown = shownRef.current;
+ if (viewModel) {
+ const variant = viewModel.number("variant");
+ const isLiked = viewModel.boolean("liked");
+ const isToggle = toggleID != shown.toggleID;
+ if (!isToggle) {
+ if (variant) variant.value = jumpVariant;
+ } else if (liked) {
+ shown.variant = pickLikeVariant(shown.variant);
+ if (variant) variant.value = shown.variant;
+ } else if (variant && variant.value < 0) {
+ // A jump would skip the unlike animation.
+ variant.value = likeAnimationVariants[0]!;
+ }
+ if (isLiked) isLiked.value = liked;
+ playFor(isToggle ? likeAnimationMs : 150);
+ }
+ shown.liked = liked;
+ shown.toggleID = toggleID;
+ }, [liked, toggleID, viewModel, playFor]);
+
+ return (
+ <Box
+ component="span"
+ sx={{ display: "flex", lineHeight: 0, position: "relative" }}
+ >
+ <Box
+ component="span"
+ sx={{
+ display: "flex",
+ visibility: viewModel ? "hidden" : "visible",
+ }}
+ >
+ {fallback}
+ </Box>
+ <Box
+ ref={canvasRef}
+ component="canvas"
+ aria-hidden
+ sx={{
+ height: canvasSize,
+ left: "50%",
+ pointerEvents: "none",
+ position: "absolute",
+ top: "50%",
+ transform: "translate(-50%, -50%)",
+ visibility: viewModel ? "visible" : "hidden",
+ width: canvasSize,
+ }}
+ />
+ </Box>
+ );
+};
diff --git a/web/apps/space/src/components/PostPhotosDots.tsx b/web/apps/space/src/components/PostPhotosDots.tsx
index e978e4365d..7173981335 100644
--- a/web/apps/space/src/components/PostPhotosDots.tsx
+++ b/web/apps/space/src/components/PostPhotosDots.tsx
@@ -1,13 +1,18 @@
import { Box } from "@mui/material";
+// A 5px dot and the 6px gap after it.
+export const photoDotStep = 11;
+
export const SpacePostPhotosDots = ({
index,
count,
activeColor = "#08C225",
+ stretches = false,
}: {
index: number;
count: number;
activeColor?: string;
+ stretches?: boolean;
}) =>
count > 1 ? (
<Box
@@ -20,20 +25,43 @@ export const SpacePostPhotosDots = ({
flexShrink: 0,
gap: "6px",
pointerEvents: "none",
+ position: "relative",
}}
>
- {Array.from({ length: count }, (_, photoIndex) => (
+ {Array.from({ length: count }, (_, photoIndex) => {
+ const isActive = !stretches && photoIndex == index;
+ return (
+ <Box
+ key={photoIndex}
+ component="span"
+ sx={{
+ bgcolor: isActive ? activeColor : "#FFFFFF",
+ borderRadius: "50%",
+ boxShadow: "0 1px 2px rgba(0, 0, 0, 0.4)",
+ height: isActive ? 6 : 5,
+ width: isActive ? 6 : 5,
+ }}
+ />
+ );
+ })}
+ {stretches && (
<Box
- key={photoIndex}
component="span"
+ data-space-photo-dots-indicator
+ style={{
+ transform: `translate(${index * photoDotStep - 0.5}px, -50%)`,
+ width: 6,
+ }}
sx={{
- bgcolor: photoIndex == index ? activeColor : "#FFFFFF",
- borderRadius: "50%",
+ bgcolor: activeColor,
+ borderRadius: "3px",
boxShadow: "0 1px 2px rgba(0, 0, 0, 0.4)",
- height: photoIndex == index ? 6 : 5,
- width: photoIndex == index ? 6 : 5,
+ height: 6,
+ left: 0,
+ position: "absolute",
+ top: "50%",
}}
/>
- ))}
+ )}
</Box>
) : null;
diff --git a/web/apps/space/src/components/PostReplyControls.tsx b/web/apps/space/src/components/PostReplyControls.tsx
index 817cef2187..6175b5ad92 100644
--- a/web/apps/space/src/components/PostReplyControls.tsx
+++ b/web/apps/space/src/components/PostReplyControls.tsx
@@ -14,6 +14,7 @@ import {
spacePostLikePopDurationMs,
spacePostLikePopTiming,
} from "components/post-like-animation";
+import { SpacePostLikeHeart } from "components/PostLikeHeart";
import React from "react";
import {
spaceControlBackground,
@@ -60,6 +61,7 @@ interface SpacePostReplyControlsProps {
isReplyMode: boolean;
liked: boolean;
likePopID: number;
+ likeToggleID: number;
onLike: () => void;
onSendReply: () => void;
replyActionPhase: SpaceActionPhase | null;
@@ -74,6 +76,7 @@ export const SpacePostReplyControls: React.FC<SpacePostReplyControlsProps> = ({
isReplyMode,
liked,
likePopID,
+ likeToggleID,
onLike,
onSendReply,
replyActionPhase,
@@ -236,29 +239,38 @@ export const SpacePostReplyControls: React.FC<SpacePostReplyControlsProps> = ({
/>
)
) : (
- <Box
- key={isLikePopping ? `heart-${likePopID}` : "heart"}
- component="span"
- sx={{
- animation: isLikePopping
- ? `${spacePostLikeHeartPop} ${spacePostLikePopDurationMs}ms ${spacePostLikePopTiming} both`
- : undefined,
- display: "flex",
- lineHeight: 0,
- transformOrigin: "50% 58%",
- "@media (prefers-reduced-motion: reduce)": {
- animation: "none",
- },
- }}
- >
- <HugeiconsIcon
- fill={liked ? green : "none"}
- icon={FavouriteIcon}
- primaryColor={liked ? green : undefined}
- size={26}
- strokeWidth={1.8}
- />
- </Box>
+ <SpacePostLikeHeart
+ liked={liked}
+ toggleID={likeToggleID}
+ fallback={
+ <Box
+ key={
+ isLikePopping
+ ? `heart-${likePopID}`
+ : "heart"
+ }
+ component="span"
+ sx={{
+ animation: isLikePopping
+ ? `${spacePostLikeHeartPop} ${spacePostLikePopDurationMs}ms ${spacePostLikePopTiming} both`
+ : undefined,
+ display: "flex",
+ lineHeight: 0,
+ transformOrigin: "50% 58%",
+ "@media (prefers-reduced-motion: reduce)":
+ { animation: "none" },
+ }}
+ >
+ <HugeiconsIcon
+ fill={liked ? green : "none"}
+ icon={FavouriteIcon}
+ primaryColor={liked ? green : undefined}
+ size={26}
+ strokeWidth={1.8}
+ />
+ </Box>
+ }
+ />
)}
</Box>
</Box>
diff --git a/web/apps/space/src/components/PostTile.tsx b/web/apps/space/src/components/PostTile.tsx
index c93f38bab1..afd02da1af 100644
--- a/web/apps/space/src/components/PostTile.tsx
+++ b/web/apps/space/src/components/PostTile.tsx
@@ -4,6 +4,7 @@ import {
SpacePostPhotosBadge,
SpacePostVideoBadge,
} from "components/PostPhotosBadge";
+import { viewerOriginKey } from "components/viewer-transition";
import log from "ente-base/log";
import { useDecodedImage } from "hooks/use-decoded-image";
import React from "react";
@@ -50,6 +51,7 @@ interface SpacePostTileProps {
onOpen: (imageUrl: string) => void;
onOpenProfile?: () => void;
onRememberDimensions?: (itemID: string, image: HTMLImageElement) => void;
+ photoIndex?: number;
}
export const SpacePostTile: React.FC<SpacePostTileProps> = ({
@@ -68,21 +70,25 @@ export const SpacePostTile: React.FC<SpacePostTileProps> = ({
onOpen,
onOpenProfile,
onRememberDimensions,
+ photoIndex = 0,
}) => {
const [shouldLoad, setShouldLoad] = React.useState(Boolean(imageUrl));
const [readyImageUrl, setReadyImageUrl] = React.useState<string>();
- const [imageDecodeFailed, setImageDecodeFailed] = React.useState(false);
+ const [failedImageUrl, setFailedImageUrl] = React.useState<string>();
const decodedAvatar = useDecodedImage(
showAvatar ? item.avatarUrl : undefined,
true,
);
const tileRef = React.useRef<HTMLButtonElement | null>(null);
+ const shownPhoto = item.photos?.[photoIndex];
+ const thumbHash = photoIndex > 0 ? shownPhoto?.thumbHash : item.thumbHash;
const thumbHashDataURL = React.useMemo(
- () => thumbHashDataURLFromBase64(item.thumbHash),
- [item.thumbHash],
+ () => thumbHashDataURLFromBase64(thumbHash),
+ [thumbHash],
);
const isCurrentImageReady = Boolean(imageUrl && readyImageUrl == imageUrl);
- const isUnavailable = isPostUnavailable || imageDecodeFailed;
+ const isUnavailable =
+ isPostUnavailable || Boolean(imageUrl && failedImageUrl == imageUrl);
const photoCount = item.photos?.length ?? 1;
React.useEffect(() => {
@@ -150,6 +156,10 @@ export const SpacePostTile: React.FC<SpacePostTileProps> = ({
}`
}
disabled={!imageUrl || isUnavailable}
+ data-space-viewer-origin={viewerOriginKey(
+ item.spaceId,
+ item.postId,
+ )}
onClick={() => {
if (imageUrl && !isUnavailable) onOpen(imageUrl);
}}
@@ -209,16 +219,17 @@ export const SpacePostTile: React.FC<SpacePostTileProps> = ({
alt={`${displayName} post ${index + 1}`}
onLoad={(event) => {
setReadyImageUrl(imageUrl);
- onRememberDimensions?.(
- item.id,
- event.currentTarget,
- );
+ if (photoIndex == 0)
+ onRememberDimensions?.(
+ item.id,
+ event.currentTarget,
+ );
}}
onError={() => {
log.warn(
`Post ${item.postId} is unavailable because the browser could not decode its image`,
);
- setImageDecodeFailed(true);
+ setFailedImageUrl(imageUrl);
onImageDecodeError();
}}
src={imageUrl}
@@ -252,7 +263,9 @@ export const SpacePostTile: React.FC<SpacePostTileProps> = ({
subtle={subtlePhotosBadge}
/>
<SpacePostVideoBadge
- durationMs={item.photos?.[0]?.video?.durationMs}
+ durationMs={
+ item.photos?.[photoIndex]?.video?.durationMs
+ }
size={18}
/>
</>
@@ -279,6 +292,7 @@ export const SpacePostTile: React.FC<SpacePostTileProps> = ({
component="button"
type="button"
aria-label={`Open ${displayName}'s profile`}
+ data-space-viewer-avatar
disabled={!onOpenProfile}
onClick={onOpenProfile}
sx={{
diff --git a/web/apps/space/src/components/post-like-animation.ts b/web/apps/space/src/components/post-like-animation.ts
index d064cd104d..60052ffcdd 100644
--- a/web/apps/space/src/components/post-like-animation.ts
+++ b/web/apps/space/src/components/post-like-animation.ts
@@ -1,5 +1,15 @@
import { keyframes } from "@mui/material/styles";
+// The burst, draw and flip animations in like.riv.
+export const likeAnimationVariants = [0, 2, 4];
+
+export const pickLikeVariant = (previous: number, random = Math.random) => {
+ const choices = likeAnimationVariants.filter(
+ (variant) => variant != previous,
+ );
+ return choices[Math.floor(random() * choices.length)]!;
+};
+
export const spacePostLikePopDurationMs = 520;
export const spacePostLikePopTiming = "cubic-bezier(0.2, 0.82, 0.22, 1)";
diff --git a/web/apps/space/src/components/viewer-transition.ts b/web/apps/space/src/components/viewer-transition.ts
new file mode 100644
index 0000000000..e576a7d711
--- /dev/null
+++ b/web/apps/space/src/components/viewer-transition.ts
@@ -0,0 +1,327 @@
+import {
+ fullPhotoState,
+ mixPhotoState,
+ photoStateTravel,
+ tilePhotoState,
+ type ViewerPhotoState,
+ type ViewerRect,
+} from "utils/viewer-geometry";
+
+const originAttribute = "data-space-viewer-origin";
+const openDuration = 0.6;
+const openBounce = 0.26;
+const closeDuration = 0.46;
+const swapFadeMs = 220;
+
+export const viewerOriginKey = (spaceId?: string, postId?: number) =>
+ spaceId && postId != undefined ? `${spaceId}:${postId}` : undefined;
+
+export const findViewerOrigin = (key: string | undefined) =>
+ key
+ ? document.querySelector<HTMLElement>(
+ `[${originAttribute}="${CSS.escape(key)}"]`,
+ )
+ : null;
+
+interface ViewerFlightTarget {
+ origin: HTMLElement;
+ src: string;
+ photo: { width: number; height: number };
+}
+
+const rectOf = (element: Element): ViewerRect => {
+ const { left, top, width, height } = element.getBoundingClientRect();
+ return { x: left, y: top, w: width, h: height };
+};
+
+const isOnScreen = (element: Element) => {
+ const { x, y, w, h } = rectOf(element);
+ return (
+ w > 0 &&
+ h > 0 &&
+ x + w > 0 &&
+ y + h > 0 &&
+ x < window.innerWidth &&
+ y < window.innerHeight
+ );
+};
+
+const prefersReducedMotion = () =>
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+
+const tileRadius = (tile: Element) =>
+ parseFloat(getComputedStyle(tile).borderTopLeftRadius) || 0;
+
+const runSpring = ({
+ from,
+ to,
+ velocity,
+ duration,
+ bounce,
+ restDelta,
+ onUpdate,
+ onDone,
+}: {
+ from: number;
+ to: number;
+ velocity: number;
+ duration: number;
+ bounce: number;
+ restDelta: number;
+ onUpdate: (value: number) => void;
+ onDone: () => void;
+}) => {
+ const stiffness = ((2 * Math.PI) / duration) ** 2;
+ const damping = ((1 - bounce) * 4 * Math.PI) / duration;
+ let value = from;
+ let speed = velocity;
+ let last = performance.now();
+ let frame = requestAnimationFrame(function tick(now) {
+ const dt = Math.min(0.064, Math.max(0, (now - last) / 1000));
+ last = now;
+ const steps = Math.max(1, Math.ceil(dt / 0.002));
+ for (let i = 0; i < steps; i++) {
+ speed +=
+ (-stiffness * (value - to) - damping * speed) * (dt / steps);
+ value += speed * (dt / steps);
+ }
+ if (
+ Math.abs(value - to) < restDelta &&
+ Math.abs(speed) < restDelta * 20
+ ) {
+ onUpdate(to);
+ onDone();
+ return;
+ }
+ onUpdate(value);
+ frame = requestAnimationFrame(tick);
+ });
+ return () => cancelAnimationFrame(frame);
+};
+
+// A cropping window and the photo inside it, both moved with transforms.
+const createFlyer = (root: HTMLElement, src: string, base: ViewerRect) => {
+ const flyer = document.createElement("div");
+ flyer.setAttribute("aria-hidden", "true");
+ Object.assign(flyer.style, {
+ height: `${base.h}px`,
+ left: "0",
+ overflow: "hidden",
+ pointerEvents: "none",
+ position: "absolute",
+ top: "0",
+ transformOrigin: "0 0",
+ width: `${base.w}px`,
+ willChange: "transform",
+ zIndex: "1",
+ });
+ const image = document.createElement("img");
+ image.alt = "";
+ image.src = src;
+ Object.assign(image.style, {
+ display: "block",
+ height: `${base.h}px`,
+ left: "0",
+ position: "absolute",
+ top: "0",
+ transformOrigin: "0 0",
+ width: `${base.w}px`,
+ willChange: "transform",
+ });
+ flyer.append(image);
+ root.prepend(flyer);
+
+ const draw = ({ image: i, visible: v, radius }: ViewerPhotoState) => {
+ const sx = v.w / base.w;
+ const sy = v.h / base.h;
+ flyer.style.transform = `translate3d(${v.x}px, ${v.y}px, 0) scale(${sx}, ${sy})`;
+ flyer.style.borderRadius = `${radius / sx}px / ${radius / sy}px`;
+ image.style.transform = `translate3d(${(i.x - v.x) / sx}px, ${(i.y - v.y) / sy}px, 0) scale(${i.w / v.w}, ${i.h / v.h})`;
+ };
+ return { flyer, draw };
+};
+
+const createRider = (flyer: HTMLElement, tile: HTMLElement) => {
+ const button = tile.parentElement?.querySelector<HTMLElement>(
+ "[data-space-viewer-avatar]",
+ );
+ const avatar = button?.firstElementChild;
+ if (!button || !(avatar instanceof HTMLElement)) return undefined;
+ const tileRect = rectOf(tile);
+ const avatarRect = rectOf(avatar);
+ const left = avatarRect.x - tileRect.x;
+ const fromBottom = tileRect.y + tileRect.h - avatarRect.y;
+ const rider = avatar.cloneNode(true) as HTMLElement;
+ for (const element of [rider, ...rider.querySelectorAll("*")])
+ if (element instanceof HTMLElement) element.style.animation = "none";
+ rider.setAttribute("aria-hidden", "true");
+ Object.assign(rider.style, {
+ left: "0",
+ pointerEvents: "none",
+ position: "absolute",
+ top: "0",
+ zIndex: "1",
+ });
+ flyer.after(rider);
+ button.style.opacity = "0";
+
+ return {
+ draw: ({ visible: v }: ViewerPhotoState, t: number) => {
+ rider.style.transform = `translate3d(${v.x + left}px, ${v.y + v.h - fromBottom}px, 0)`;
+ rider.style.opacity = String(
+ 1 - Math.min(1, Math.max(0, t / 0.35)),
+ );
+ },
+ remove: () => rider.remove(),
+ reveal: () => {
+ button.style.opacity = "";
+ },
+ };
+};
+
+// The tile stays empty until reveal, and the flying photo stays until release.
+export const playViewerOpen = (
+ root: HTMLElement,
+ { origin, src, photo }: ViewerFlightTarget,
+ to: ViewerRect,
+ setProgress: (t: number) => void,
+ onLanded: () => void,
+) => {
+ if (prefersReducedMotion() || !isOnScreen(origin)) return undefined;
+
+ const from = tilePhotoState(rectOf(origin), photo, tileRadius(origin));
+ let end = fullPhotoState(to);
+ let t = 0;
+ const { flyer, draw } = createFlyer(root, src, to);
+ const rider = createRider(flyer, origin);
+ const drawAt = (value: number) => {
+ const state = mixPhotoState(from, end, value);
+ draw(state);
+ rider?.draw(state, value);
+ };
+ origin.style.opacity = "0";
+ drawAt(0);
+ setProgress(0);
+
+ const release = () => {
+ flyer.remove();
+ rider?.remove();
+ };
+ const reveal = () => {
+ origin.style.opacity = "";
+ rider?.reveal();
+ };
+ const stopSpring = runSpring({
+ from: 0,
+ to: 1,
+ velocity: 0,
+ duration: openDuration,
+ bounce: openBounce,
+ restDelta: 1.5 / Math.max(1, photoStateTravel(from, end)),
+ onUpdate: (value) => {
+ t = value;
+ drawAt(t);
+ setProgress(t);
+ },
+ onDone: onLanded,
+ });
+ return {
+ current: () => mixPhotoState(from, end, t),
+ release,
+ reveal,
+ retarget: (rect: ViewerRect) => {
+ end = fullPhotoState(rect);
+ drawAt(t);
+ },
+ stop: () => {
+ stopSpring();
+ release();
+ reveal();
+ },
+ };
+};
+
+// throwVelocity is in px per ms. A photo other than the tile's fades into it.
+export const playViewerClose = (
+ root: HTMLElement,
+ { origin, src, photo }: ViewerFlightTarget,
+ from: ViewerPhotoState,
+ throwVelocity: { x: number; y: number },
+ setProgress: (t: number) => void,
+ onDone: () => void,
+) => {
+ if (prefersReducedMotion() || !isOnScreen(origin)) return undefined;
+
+ const end = tilePhotoState(rectOf(origin), photo, tileRadius(origin));
+ const { flyer, draw } = createFlyer(root, src, from.image);
+ const rider = createRider(flyer, origin);
+ const drawAt = (t: number) => {
+ const state = mixPhotoState(end, from, t);
+ draw(state);
+ rider?.draw(state, t);
+ };
+ origin.style.opacity = "0";
+ drawAt(1);
+
+ const dx =
+ end.visible.x +
+ end.visible.w / 2 -
+ (from.visible.x + from.visible.w / 2);
+ const dy =
+ end.visible.y +
+ end.visible.h / 2 -
+ (from.visible.y + from.visible.h / 2);
+ const distance = Math.max(1, Math.hypot(dx, dy));
+ const toward =
+ ((throwVelocity.x * dx + throwVelocity.y * dy) / distance) * 1000;
+ const tileImage = origin.querySelector<HTMLImageElement>(
+ "img:not([aria-hidden])",
+ );
+ const isTilePhoto = tileImage?.currentSrc == src || tileImage?.src == src;
+
+ const cleanUp = () => {
+ origin.style.opacity = "";
+ rider?.remove();
+ rider?.reveal();
+ };
+ const stopSpring = runSpring({
+ from: 1,
+ to: 0,
+ velocity: Math.min(1.2, Math.max(-8, -toward / distance)),
+ duration: closeDuration,
+ bounce: 0,
+ restDelta: 0.5 / Math.max(1, photoStateTravel(from, end)),
+ onUpdate: (t) => {
+ drawAt(t);
+ setProgress(t);
+ },
+ onDone: () => {
+ cleanUp();
+ if (isTilePhoto) {
+ flyer.remove();
+ } else {
+ // The viewer unmounts next, so fade a copy.
+ const ghost = flyer.cloneNode(true) as HTMLElement;
+ Object.assign(ghost.style, {
+ position: "fixed",
+ zIndex: "1301",
+ });
+ document.body.append(ghost);
+ flyer.remove();
+ ghost
+ .animate([{ opacity: 1 }, { opacity: 0 }], {
+ duration: swapFadeMs,
+ easing: "ease",
+ fill: "forwards",
+ })
+ .addEventListener("finish", () => ghost.remove());
+ }
+ onDone();
+ },
+ });
+ return () => {
+ stopSpring();
+ cleanUp();
+ flyer.remove();
+ };
+};
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index 3d629ea445..6a6a4d9a76 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -2313,11 +2313,26 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
};
})}
renderTile={(item, index) => {
- const photo = {
- ...spacePostPhotos(item)[0]!,
+ const postPhotos = spacePostPhotos(item);
+ const photoAt = (index: number) => ({
+ ...postPhotos[index]!,
postId: item.postId,
spaceId: item.spaceId,
- };
+ });
+ const remembered = Math.min(
+ feedPhotoIndices[item.postId] ?? 0,
+ postPhotos.length - 1,
+ );
+ const photoIndex =
+ remembered > 0 &&
+ unavailableFeedPostsByKey[
+ feedPostImageCacheKey(
+ photoAt(remembered),
+ )
+ ]
+ ? 0
+ : remembered;
+ const photo = photoAt(photoIndex);
const imageUrl =
loadedFeedImageURLFor(photo);
const avatarUrl =
@@ -2335,6 +2350,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
<SpacePostTile
key={item.id}
item={{ ...item, avatarUrl }}
+ photoIndex={photoIndex}
displayName={item.name}
showAvatar
subtlePhotosBadge
@@ -2384,14 +2400,17 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
const post = {
...item,
avatarUrl,
- imageUrl,
+ imageUrl:
+ photoIndex == 0
+ ? imageUrl
+ : item.imageUrl,
};
- openFeedPhoto(
- post,
- viewerPhotosFromPost(
+ openFeedPhoto(post, {
+ ...viewerPhotosFromPost(
post,
- )[0]!,
- );
+ )[photoIndex]!,
+ imageUrl,
+ });
}}
/>
);
diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsx
index 5ea323f7d7..cf1a737e79 100644
--- a/web/apps/space/src/screens/ProfileScreen.tsx
+++ b/web/apps/space/src/screens/ProfileScreen.tsx
@@ -87,6 +87,13 @@ interface SelectedProfilePost {
const profilePostImageCacheKey = (item: ProfilePostItem) =>
[item.id, item.imageAsset?.objectKey ?? item.imageUrl ?? ""].join(":");
+const profilePostPhoto = (item: ProfilePostItem, index: number) => {
+ const photo = item.photos?.[index];
+ return index > 0 && photo
+ ? { ...item, ...photo, imageUrl: photo.imageUrl }
+ : item;
+};
+
const ProfileStatsSkeleton: React.FC = () => (
<Box
role="status"
@@ -275,6 +282,9 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
}) => {
const [selectedPost, setSelectedPost] =
useState<SelectedProfilePost | null>(null);
+ const [tilePhotoIndices, setTilePhotoIndices] = useState<
+ Record<string, number>
+ >({});
const [isInviteLinkCopied, setIsInviteLinkCopied] = useState(false);
const [deletedPostIDs, setDeletedPostIDs] = useState<Set<string>>(
() => new Set(),
@@ -516,7 +526,13 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
avatarUrl: profile.avatarUrl,
imageUrl: loadedPostImageURLFor(item),
name: displayName,
- }).map((photo) => ({ ...photo, id: item.id })),
+ }).map((photo, index) => ({
+ ...photo,
+ id: item.id,
+ imageUrl:
+ photo.imageUrl ||
+ (loadedPostImageURLFor(profilePostPhoto(item, index)) ?? ""),
+ })),
);
const selectedPhotoIndex = selectedPost
? profileViewerPhotos.findIndex(
@@ -527,12 +543,16 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
: 0;
const handleSelectedPostIndexChange = (photoIndex: number) => {
const photo = profileViewerPhotos[photoIndex];
- if (photo)
- setSelectedPost({
- id: photo.id,
- photo,
- photoIndex: photo.postPhotoIndex!,
- });
+ if (!photo) return;
+ setSelectedPost({
+ id: photo.id,
+ photo,
+ photoIndex: photo.postPhotoIndex!,
+ });
+ setTilePhotoIndices((current) => ({
+ ...current,
+ [photo.id]: photo.postPhotoIndex ?? 0,
+ }));
};
const shareInvite = async () => {
@@ -568,7 +588,19 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
};
const renderPostTile = (item: ProfilePostItem, index: number) => {
- const imageUrl = loadedPostImageURLFor(item);
+ const remembered = Math.min(
+ tilePhotoIndices[item.id] ?? 0,
+ (item.photos?.length || 1) - 1,
+ );
+ const photoIndex =
+ remembered > 0 &&
+ unavailablePostsByKey[
+ profilePostImageCacheKey(profilePostPhoto(item, remembered))
+ ]
+ ? 0
+ : remembered;
+ const shown = profilePostPhoto(item, photoIndex);
+ const imageUrl = loadedPostImageURLFor(shown);
const isUnavailable = !viewerPostIDs.has(item.id);
return (
<SpacePostTile
@@ -578,22 +610,25 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
index={index}
isUnavailable={isUnavailable}
item={item}
+ photoIndex={photoIndex}
loadRootMargin={postImageLoadRootMargin}
- onLoadImage={() => loadPostImage(item)}
+ onLoadImage={() => loadPostImage(shown)}
onImageDecodeError={() =>
setUnavailablePostsByKey((current) => ({
...current,
- [profilePostImageCacheKey(item)]: true,
+ [profilePostImageCacheKey(shown)]: true,
}))
}
onOpen={(openedImageUrl) => {
const photo = profileViewerPhotos.find(
- (photo) => photo.id == item.id,
+ (photo) =>
+ photo.id == item.id &&
+ (photo.postPhotoIndex ?? 0) == photoIndex,
);
if (!photo) return;
setSelectedPost({
id: item.id,
- photoIndex: 0,
+ photoIndex,
photo: { ...photo, imageUrl: openedImageUrl },
});
}}
diff --git a/web/apps/space/src/utils/viewer-geometry.ts b/web/apps/space/src/utils/viewer-geometry.ts
new file mode 100644
index 0000000000..f0048493d3
--- /dev/null
+++ b/web/apps/space/src/utils/viewer-geometry.ts
@@ -0,0 +1,89 @@
+export interface ViewerRect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+// image is where the whole photo is, visible is the part of it that shows.
+export interface ViewerPhotoState {
+ image: ViewerRect;
+ visible: ViewerRect;
+ radius: number;
+}
+
+export const tilePhotoState = (
+ tile: ViewerRect,
+ photo: { width: number; height: number },
+ radius: number,
+): ViewerPhotoState => {
+ const scale = Math.max(tile.w / photo.width, tile.h / photo.height);
+ const w = photo.width * scale;
+ const h = photo.height * scale;
+ return {
+ image: {
+ x: tile.x + (tile.w - w) / 2,
+ y: tile.y + (tile.h - h) / 2,
+ w,
+ h,
+ },
+ visible: { ...tile },
+ radius,
+ };
+};
+
+export const fullPhotoState = (
+ rect: ViewerRect,
+ radius = 0,
+): ViewerPhotoState => ({ image: { ...rect }, visible: { ...rect }, radius });
+
+// A photo zoomed in past the viewport is cut to it.
+export const shownPhotoState = (
+ image: ViewerRect,
+ viewport: ViewerRect,
+ radius: number,
+): ViewerPhotoState => {
+ if (image.w <= viewport.w && image.h <= viewport.h)
+ return fullPhotoState(image, radius);
+ const x = Math.max(image.x, viewport.x);
+ const y = Math.max(image.y, viewport.y);
+ const w = Math.min(image.x + image.w, viewport.x + viewport.w) - x;
+ const h = Math.min(image.y + image.h, viewport.y + viewport.h) - y;
+ return {
+ image: { ...image },
+ visible: { x, y, w: Math.max(0, w), h: Math.max(0, h) },
+ radius,
+ };
+};
+
+const mix = (a: number, b: number, t: number) => a + (b - a) * t;
+
+const mixRect = (a: ViewerRect, b: ViewerRect, t: number): ViewerRect => ({
+ x: mix(a.x, b.x, t),
+ y: mix(a.y, b.y, t),
+ w: mix(a.w, b.w, t),
+ h: mix(a.h, b.h, t),
+});
+
+export const mixPhotoState = (
+ from: ViewerPhotoState,
+ to: ViewerPhotoState,
+ t: number,
+): ViewerPhotoState => ({
+ image: mixRect(from.image, to.image, t),
+ visible: mixRect(from.visible, to.visible, t),
+ radius: Math.max(0, mix(from.radius, to.radius, t)),
+});
+
+export const photoStateTravel = (a: ViewerPhotoState, b: ViewerPhotoState) =>
+ Math.max(
+ Math.abs(a.visible.x - b.visible.x),
+ Math.abs(a.visible.y - b.visible.y),
+ Math.abs(a.visible.x + a.visible.w - b.visible.x - b.visible.w),
+ Math.abs(a.visible.y + a.visible.h - b.visible.y - b.visible.h),
+ );
+
+export const viewerBackgroundOpacity = (t: number) => {
+ const k = Math.min(1, Math.max(0, t));
+ return 1 - (1 - k) ** 2;
+};
diff --git a/web/apps/space/tests/post-like-animation.test.ts b/web/apps/space/tests/post-like-animation.test.ts
new file mode 100644
index 0000000000..7b5856ce53
--- /dev/null
+++ b/web/apps/space/tests/post-like-animation.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from "vitest";
+import { pickLikeVariant } from "../src/components/post-like-animation";
+
+test("a like never plays the same animation twice in a row", () => {
+ for (const previous of [0, 2, 4]) {
+ for (const random of [0, 0.4, 0.99]) {
+ expect(pickLikeVariant(previous, () => random)).not.toBe(previous);
+ }
+ }
+});
+
+test("the first like can play any of the three animations", () => {
+ const picked = new Set(
+ [0, 0.4, 0.99].map((random) => pickLikeVariant(-1, () => random)),
+ );
+
+ expect(picked).toEqual(new Set([0, 2, 4]));
+});
diff --git a/web/apps/space/tests/viewer-geometry.test.ts b/web/apps/space/tests/viewer-geometry.test.ts
new file mode 100644
index 0000000000..0e70c20111
--- /dev/null
+++ b/web/apps/space/tests/viewer-geometry.test.ts
@@ -0,0 +1,87 @@
+import { expect, test } from "vitest";
+import {
+ fullPhotoState,
+ mixPhotoState,
+ photoStateTravel,
+ shownPhotoState,
+ tilePhotoState,
+ viewerBackgroundOpacity,
+} from "../src/utils/viewer-geometry";
+
+const tile = { x: 10, y: 20, w: 100, h: 100 };
+
+test("a tile crops a wide photo to its centre", () => {
+ expect(tilePhotoState(tile, { width: 200, height: 100 }, 12)).toEqual({
+ image: { x: -40, y: 20, w: 200, h: 100 },
+ visible: tile,
+ radius: 12,
+ });
+});
+
+test("a tile crops a tall photo to its centre", () => {
+ expect(tilePhotoState(tile, { width: 300, height: 900 }, 0).image).toEqual({
+ x: 10,
+ y: -80,
+ w: 100,
+ h: 300,
+ });
+});
+
+test("a flight starts and ends exactly on its endpoints", () => {
+ const from = tilePhotoState(tile, { width: 200, height: 100 }, 12);
+ const to = fullPhotoState({ x: 0, y: 100, w: 400, h: 200 });
+
+ expect(mixPhotoState(from, to, 0)).toEqual(from);
+ expect(mixPhotoState(from, to, 1)).toEqual(to);
+ expect(mixPhotoState(from, to, 0.5)).toEqual({
+ image: { x: -20, y: 60, w: 300, h: 150 },
+ visible: { x: 5, y: 60, w: 250, h: 150 },
+ radius: 6,
+ });
+});
+
+test("a spring overshoot never makes the corner radius negative", () => {
+ const from = fullPhotoState(tile, 12);
+ const to = fullPhotoState(tile);
+
+ expect(mixPhotoState(from, to, 1.2).radius).toBe(0);
+});
+
+test("a photo that fits on screen closes whole", () => {
+ const viewport = { x: 0, y: 0, w: 390, h: 844 };
+ const dragged = { x: 40, y: 700, w: 300, h: 400 };
+
+ expect(shownPhotoState(dragged, viewport, 8)).toEqual(
+ fullPhotoState(dragged, 8),
+ );
+});
+
+test("a zoomed-in photo closes from the part on screen", () => {
+ const viewport = { x: 0, y: 0, w: 390, h: 844 };
+ const zoomed = { x: -500, y: -200, w: 1800, h: 2400 };
+
+ expect(shownPhotoState(zoomed, viewport, 0)).toEqual({
+ image: zoomed,
+ visible: viewport,
+ radius: 0,
+ });
+});
+
+test("travel is the furthest any visible edge moves", () => {
+ const from = fullPhotoState(tile);
+ const to = fullPhotoState({ x: 0, y: 20, w: 300, h: 50 });
+
+ expect(photoStateTravel(from, to)).toBe(190);
+ expect(photoStateTravel(from, from)).toBe(0);
+});
+
+test("the background comes in ahead of the photo", () => {
+ expect(viewerBackgroundOpacity(0)).toBe(0);
+ expect(viewerBackgroundOpacity(0.5)).toBe(0.75);
+ expect(viewerBackgroundOpacity(1)).toBe(1);
+});
+
+test("a spring overshoot never takes the background past its ends", () => {
+ expect(viewerBackgroundOpacity(1.1)).toBe(1);
+ expect(viewerBackgroundOpacity(-0.1)).toBe(0);
+});
diff --git a/web/apps/space/tests/viewer-transition.test.ts b/web/apps/space/tests/viewer-transition.test.ts
new file mode 100644
index 0000000000..c4ab55f51e
--- /dev/null
+++ b/web/apps/space/tests/viewer-transition.test.ts
@@ -0,0 +1,9 @@
+import { expect, test } from "vitest";
+import { viewerOriginKey } from "../src/components/viewer-transition";
+
+test("tiles are matched by space and post", () => {
+ expect(viewerOriginKey("space", 12)).toBe("space:12");
+ expect(viewerOriginKey("space", 0)).toBe("space:0");
+ expect(viewerOriginKey(undefined, 12)).toBeUndefined();
+ expect(viewerOriginKey("space", undefined)).toBeUndefined();
+});
diff --git a/web/package-lock.json b/web/package-lock.json
index 76be026854..f35eb339d2 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -352,6 +352,7 @@
"@fontsource/nunito": "5.3.0",
"@hugeicons/core-free-icons": "4.3.5",
"@hugeicons/react": "1.1.10",
+ "@rive-app/canvas-lite": "2.43.1",
"ente-accounts": "*",
"ente-base": "*",
"ente-media": "*",
@@ -3262,6 +3263,12 @@
"react-dom": "^19.0.0"
}
},
+ "node_modules/@rive-app/canvas-lite": {
+ "version": "2.43.1",
+ "resolved": "https://registry.npmjs.org/@rive-app/canvas-lite/-/canvas-lite-2.43.1.tgz",
+ "integrity": "sha512-6Hb9J3Yfz3JKgLYv1pU/K14kEpj6RUAFKJV/lI1LmogFsLJibA69TQLIk6NoNUUTDmrbqGc4/8ZrEmhpwf0Z9Q==",
+ "license": "MIT"
+ },
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.12",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz",