Skip to content

armgit / ente

Public Imported from GitHub
0

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

Preload and cache Space Rive likes without replaying early taps

Anand Baburajan52f9859438e5
diff --git a/web/apps/space/next.config.js b/web/apps/space/next.config.js
index 0d1a12a7c7..8f522cbd82 100644
--- a/web/apps/space/next.config.js
+++ b/web/apps/space/next.config.js
@@ -2,6 +2,15 @@ const baseConfig = require("ente-base/next.config.base.js");
module.exports = {
...baseConfig,
+ webpack: (config, options) => {
+ config = baseConfig.webpack(config, options);
+ config.module.rules.push({
+ test: /(?:like\.riv|@rive-app[\\/]canvas-lite[\\/]rive\.wasm)$/,
+ type: "asset/resource",
+ generator: { filename: "static/media/[name].[contenthash][ext]" },
+ });
+ return config;
+ },
transpilePackages: Array.from(
new Set([
...(baseConfig.transpilePackages || []),
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/_headers b/web/apps/space/public/_headers
index dd716a39e0..79ac727249 100644
--- a/web/apps/space/public/_headers
+++ b/web/apps/space/public/_headers
@@ -9,3 +9,7 @@
Referrer-Policy: no-referrer
Reporting-Endpoints: csp-endpoint="https://csp-reporter.ente.com"
Content-Security-Policy: default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; font-src 'self'; script-src 'self' 'wasm-unsafe-eval' https://assets.ente.com/ffmpeg-core-9.0.2/ffmpeg-core.js; worker-src 'self' blob:; manifest-src 'self'; child-src 'self' blob:; object-src 'none'; connect-src 'self' https://*.ente.com https://*.ente.io https://space-api.ente-dev.com data: blob: https://*.s3.eu-central-003.backblazeb2.com https://*.s3.eu-central-2.wasabisys.com; base-uri 'self'; frame-ancestors 'none'; form-action 'none'; report-uri https://csp-reporter.ente.com; report-to csp-endpoint;
+
+/_next/static/*
+ ! Cache-Control
+ Cache-Control: public, max-age=31536000, immutable
diff --git a/web/apps/space/src/assets/like.riv b/web/apps/space/src/assets/like.riv
new file mode 100644
index 0000000000..1f2cbec1e0
Binary files /dev/null and b/web/apps/space/src/assets/like.riv differ
diff --git a/web/apps/space/src/components/AppNavigation.tsx b/web/apps/space/src/components/AppNavigation.tsx
index b11cbc3975..a3c548a2a3 100644
--- a/web/apps/space/src/components/AppNavigation.tsx
+++ b/web/apps/space/src/components/AppNavigation.tsx
@@ -7,6 +7,7 @@ import {
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { Box } from "@mui/material";
+import { preloadPostLikeAnimation } from "components/post-like-rive";
import { SpacePostPhotoInput } from "components/PostPhotoInput";
import log from "ente-base/log";
import { isSpaceIOS } from "hooks/use-pwa-install-prompt";
@@ -53,6 +54,10 @@ export const SpaceAppLayout = ({ children }: { children: React.ReactNode }) => {
const postInputRef = React.useRef<HTMLInputElement>(null);
const path = router.asPath.split(/[?#]/)[0] ?? router.pathname;
+ React.useEffect(() => {
+ if (showNavigation) void preloadPostLikeAnimation();
+ }, [showNavigation]);
+
React.useEffect(() => {
if (!spaceID) {
setUnreadStatus(emptySpaceUnreadStatus);
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsx
index 2758877549..cb5e43c69e 100644
--- a/web/apps/space/src/components/FileViewer.tsx
+++ b/web/apps/space/src/components/FileViewer.tsx
@@ -567,6 +567,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 ?? "",
@@ -807,6 +808,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);
@@ -2656,6 +2658,8 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
isReplyMode={isReplyMode}
liked={isPhotoLiked}
likePopID={photoLikePopID}
+ likeToggleID={photoLikeToggleID}
+ postKey={activePostKey}
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..c10e4a909a
--- /dev/null
+++ b/web/apps/space/src/components/PostLikeHeart.tsx
@@ -0,0 +1,165 @@
+import { Box } from "@mui/material";
+import type { Rive, ViewModelInstance } from "@rive-app/canvas-lite";
+import { pickLikeVariant } from "components/post-like-animation";
+import { preloadPostLikeAnimation } from "components/post-like-rive";
+import log from "ente-base/log";
+import React from "react";
+
+const jumpVariant = -1;
+const likeAnimationMs = 1600;
+
+interface SpacePostLikeHeartProps {
+ liked: boolean;
+ toggleID: number;
+ popID: number;
+ size: number;
+ fallback: React.ReactNode;
+}
+
+export const SpacePostLikeHeart: React.FC<SpacePostLikeHeartProps> = ({
+ liked,
+ toggleID,
+ popID,
+ size,
+ fallback,
+}) => {
+ const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
+ const riveRef = React.useRef<Rive | undefined>(undefined);
+ const pauseTimerRef = React.useRef(0);
+ const readyRef = React.useRef(false);
+ const shownRef = React.useRef({ liked, toggleID, variant: jumpVariant });
+ const [viewModel, setViewModel] = React.useState<ViewModelInstance>();
+ const [ready, setReady] = React.useState(false);
+ const canvasSize = Math.round((160 * size) / 22);
+
+ 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 (window.matchMedia("(prefers-reduced-motion: reduce)").matches)
+ return;
+ let disposed = false;
+ let started = false;
+ let firstFrame = 0;
+ let didDraw = false;
+ const prepare = async () => {
+ if (started) return;
+ started = true;
+ const prepared = await preloadPostLikeAnimation();
+ if (!prepared || disposed) return;
+ const { runtime, file } = prepared;
+ const rive = new runtime.Rive({
+ autoBind: true,
+ autoplay: false,
+ canvas,
+ enableRiveAssetCDN: false,
+ layout: new runtime.Layout({ fit: runtime.Fit.Contain }),
+ riveFile: file,
+ stateMachine: "Like",
+ onLoad: () => {
+ if (disposed) return;
+ rive.resizeDrawingSurfaceToCanvas();
+ const instance = rive.viewModelInstance;
+ if (!instance) return;
+ instance.number("variant")!.value = jumpVariant;
+ instance.boolean("liked")!.value = shownRef.current.liked;
+ playFor(150);
+ },
+ onAdvance: () => {
+ if (disposed || didDraw) return;
+ didDraw = true;
+ firstFrame = requestAnimationFrame(() => {
+ if (!disposed)
+ setViewModel(rive.viewModelInstance ?? undefined);
+ });
+ },
+ onLoadError: () =>
+ log.warn("Failed to load the like animation"),
+ });
+ riveRef.current = rive;
+ };
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ observer.disconnect();
+ void prepare();
+ }
+ },
+ { rootMargin: "200px" },
+ );
+ observer.observe(canvas.parentElement!);
+ return () => {
+ disposed = true;
+ observer.disconnect();
+ cancelAnimationFrame(firstFrame);
+ window.clearTimeout(pauseTimerRef.current);
+ riveRef.current?.cleanup();
+ riveRef.current = undefined;
+ };
+ }, [playFor]);
+
+ React.useLayoutEffect(() => {
+ const shown = shownRef.current;
+ const animate = readyRef.current && toggleID != shown.toggleID;
+ if (viewModel) {
+ const variant = viewModel.number("variant")!;
+ if (!animate) {
+ variant.value = jumpVariant;
+ } else if (liked) {
+ shown.variant = pickLikeVariant(shown.variant);
+ variant.value = shown.variant;
+ } else if (variant.value < 0) {
+ variant.value = 0;
+ }
+ viewModel.boolean("liked")!.value = liked;
+ playFor(animate ? likeAnimationMs : 150);
+ }
+ shown.liked = liked;
+ shown.toggleID = toggleID;
+ }, [liked, toggleID, viewModel, playFor]);
+
+ React.useEffect(() => {
+ if (viewModel && popID == 0) {
+ readyRef.current = true;
+ setReady(true);
+ }
+ }, [viewModel, popID]);
+
+ return (
+ <Box
+ component="span"
+ sx={{ display: "flex", lineHeight: 0, position: "relative" }}
+ >
+ <Box
+ component="span"
+ sx={{
+ display: "flex",
+ visibility: ready ? "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: ready ? "visible" : "hidden",
+ width: canvasSize,
+ }}
+ />
+ </Box>
+ );
+};
diff --git a/web/apps/space/src/components/PostReplyControls.tsx b/web/apps/space/src/components/PostReplyControls.tsx
index 817cef2187..f4338be02b 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,8 @@ interface SpacePostReplyControlsProps {
isReplyMode: boolean;
liked: boolean;
likePopID: number;
+ likeToggleID: number;
+ postKey: string;
onLike: () => void;
onSendReply: () => void;
replyActionPhase: SpaceActionPhase | null;
@@ -74,6 +77,8 @@ export const SpacePostReplyControls: React.FC<SpacePostReplyControlsProps> = ({
isReplyMode,
liked,
likePopID,
+ likeToggleID,
+ postKey,
onLike,
onSendReply,
replyActionPhase,
@@ -236,29 +241,41 @@ 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
+ key={postKey}
+ liked={liked}
+ toggleID={likeToggleID}
+ popID={likePopID}
+ size={26}
+ 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/post-like-animation.ts b/web/apps/space/src/components/post-like-animation.ts
index d064cd104d..7966b818f5 100644
--- a/web/apps/space/src/components/post-like-animation.ts
+++ b/web/apps/space/src/components/post-like-animation.ts
@@ -1,5 +1,10 @@
import { keyframes } from "@mui/material/styles";
+export const pickLikeVariant = (previous: number, random = Math.random) => {
+ const choices = [0, 2, 4].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/post-like-rive.ts b/web/apps/space/src/components/post-like-rive.ts
new file mode 100644
index 0000000000..d545632baa
--- /dev/null
+++ b/web/apps/space/src/components/post-like-rive.ts
@@ -0,0 +1,45 @@
+import log from "ente-base/log";
+import { preload } from "react-dom";
+
+const prepareLikeAnimation = async () => {
+ const wasmURL = new URL("@rive-app/canvas-lite/rive.wasm", import.meta.url)
+ .href;
+ preload(wasmURL, {
+ as: "fetch",
+ crossOrigin: "anonymous",
+ fetchPriority: "low",
+ });
+ const [runtime, buffer] = await Promise.all([
+ import("@rive-app/canvas-lite").then(async (runtime) => {
+ runtime.RuntimeLoader.setWasmUrl(wasmURL);
+ runtime.RuntimeLoader.setWasmFallbackUrl(null);
+ await runtime.RuntimeLoader.awaitInstance();
+ return runtime;
+ }),
+ fetch(new URL("../assets/like.riv", import.meta.url)).then(
+ (response) => {
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ return response.arrayBuffer();
+ },
+ ),
+ ]);
+ const file = new runtime.RiveFile({ buffer, enableRiveAssetCDN: false });
+ await file.init();
+ file.getInstance();
+ return { runtime, file };
+};
+
+let likeAnimation:
+ | Promise<Awaited<ReturnType<typeof prepareLikeAnimation>> | undefined>
+ | undefined;
+
+export const preloadPostLikeAnimation = () => {
+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches)
+ return Promise.resolve(undefined);
+ likeAnimation ??= prepareLikeAnimation().catch((error: unknown) => {
+ likeAnimation = undefined;
+ log.warn("Failed to prepare the like animation", error);
+ return undefined;
+ });
+ return likeAnimation;
+};
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index 78fb1c6e23..ce31708238 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -30,6 +30,7 @@ import {
import { paintStretchingDot } from "components/post-photos-dots";
import { SpacePostAvatar } from "components/PostAvatar";
import { SpacePostGrid } from "components/PostGrid";
+import { SpacePostLikeHeart } from "components/PostLikeHeart";
import { SpacePostPhotosCounter } from "components/PostPhotosCounter";
import { SpacePostPhotosDots } from "components/PostPhotosDots";
import { SpacePostTile } from "components/PostTile";
@@ -512,12 +513,14 @@ interface FeedLikeButtonProps {
isLiked: boolean;
onClick: () => void;
popID: number;
+ toggleID: number;
}
const FeedLikeButton: React.FC<FeedLikeButtonProps> = ({
isLiked,
onClick,
popID,
+ toggleID,
}) => {
const isPopping = isLiked && popID > 0;
@@ -564,31 +567,41 @@ const FeedLikeButton: React.FC<FeedLikeButtonProps> = ({
},
}}
>
- <Box
- key={isPopping ? `heart-${popID}` : "heart"}
- component="span"
- sx={{
- animation: isPopping
- ? `${spacePostLikeHeartPop} ${spacePostLikePopDurationMs}ms ${spacePostLikePopTiming} both`
- : undefined,
- display: "flex",
- lineHeight: 0,
- position: "relative",
- transformOrigin: "50% 58%",
- zIndex: 1,
- "@media (prefers-reduced-motion: reduce)": {
- animation: "none",
- },
- }}
- >
- <HugeiconsIcon
- fill={isLiked ? green : "none"}
- icon={FavouriteIcon}
- primaryColor={isLiked ? green : feedActionForeground}
- size={feedActionIconSize}
- strokeWidth={2.2}
- />
- </Box>
+ <SpacePostLikeHeart
+ liked={isLiked}
+ toggleID={toggleID}
+ popID={popID}
+ size={feedActionIconSize}
+ fallback={
+ <Box
+ key={isPopping ? `heart-${popID}` : "heart"}
+ component="span"
+ sx={{
+ animation: isPopping
+ ? `${spacePostLikeHeartPop} ${spacePostLikePopDurationMs}ms ${spacePostLikePopTiming} both`
+ : undefined,
+ display: "flex",
+ lineHeight: 0,
+ position: "relative",
+ transformOrigin: "50% 58%",
+ zIndex: 1,
+ "@media (prefers-reduced-motion: reduce)": {
+ animation: "none",
+ },
+ }}
+ >
+ <HugeiconsIcon
+ fill={isLiked ? green : "none"}
+ icon={FavouriteIcon}
+ primaryColor={
+ isLiked ? green : feedActionForeground
+ }
+ size={feedActionIconSize}
+ strokeWidth={2.2}
+ />
+ </Box>
+ }
+ />
</Box>
);
};
@@ -856,6 +869,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
const [isLiked, setIsLiked] = useState(viewerLiked);
const [muted, setMuted] = useState(true);
const [likePopID, setLikePopID] = useState(0);
+ const [likeToggleID, setLikeToggleID] = useState(0);
const [shouldLoadMedia, setShouldLoadMedia] = useState(
!isUnavailable && Boolean(imageUrl) && !isAvatarPending,
);
@@ -1078,6 +1092,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
const nextLiked = !isLiked;
setIsLiked(nextLiked);
+ setLikeToggleID((id) => id + 1);
if (nextLiked) setLikePopID((id) => id + 1);
void onSetPostLiked?.(postId, nextLiked).catch((error: unknown) => {
log.error("Failed to update post like", error);
@@ -1731,6 +1746,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
isLiked={isLiked}
onClick={handleLikeClick}
popID={likePopID}
+ toggleID={likeToggleID}
/>
</Box>
)}
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",