π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat(web): update memory lane viewer
AmanRajSinghMourya700b207d445c
diff --git a/web/apps/memories/package.json b/web/apps/memories/package.jsonindex b5e3df38aa..d976a290eb 100644--- a/web/apps/memories/package.json+++ b/web/apps/memories/package.json@@ -6,6 +6,7 @@"build:post": "rm -f out/404.html"},"dependencies": {+ "@fontsource/itim": "^5.2.7","ente-base": "*","ente-gallery": "*","ente-media": "*",diff --git a/web/apps/memories/public/images/ente-brand-tag.svg b/web/apps/memories/public/images/ente-brand-tag.svgnew file mode 100644index 0000000000..995aea2dff--- /dev/null+++ b/web/apps/memories/public/images/ente-brand-tag.svg@@ -0,0 +1,13 @@+<svg width="59" height="43" viewBox="0 0 59 43" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M15.4509 14.3803L5.70528 15.1086C6.26193 16.2222 7.35946 16.7178 8.99786 16.5953C9.99596 16.5207 10.8282 16.1271 11.4946 15.4145L15.0617 17.534C13.8178 19.3882 11.8588 20.4151 9.18465 20.615C6.79297 20.7937 4.82001 20.2405 3.26579 18.9553C1.72899 17.6499 0.880363 15.9237 0.719914 13.7769C0.560872 11.6488 1.13407 9.81641 2.43952 8.27961C3.74496 6.74281 5.48995 5.89277 7.67448 5.72951C9.78367 5.57187 11.5784 6.14789 13.0587 7.45756C14.5376 8.74839 15.3573 10.4672 15.5178 12.6141C15.567 13.2732 15.5447 13.8619 15.4509 14.3803ZM5.40599 11.8643L10.8296 11.459C10.3733 10.1674 9.43895 9.57448 8.02654 9.68003C6.57646 9.78841 5.70295 10.5165 5.40599 11.8643Z" fill="white"/>+<path d="M24.1796 4.49597C25.7427 4.37916 27.0351 4.82228 28.0569 5.82534C29.0962 6.80816 29.6876 8.26 29.8312 10.1809L30.4624 18.6271L25.7732 18.9776L25.1863 11.1245C25.1328 10.4089 24.9037 9.87687 24.4989 9.52838C24.0927 9.16105 23.56 9.00202 22.9009 9.05128C22.1664 9.10617 21.609 9.37508 21.2284 9.85802C20.8653 10.3207 20.7147 10.9664 20.7767 11.795L21.3382 19.309L16.649 19.6595L15.5934 5.53536L20.2826 5.1849L20.3882 6.59731C21.1456 5.32872 22.4094 4.62827 24.1796 4.49597Z" fill="white"/>+<path d="M39.2966 3.76387L39.6322 8.25533L36.6944 8.47489L37.0005 12.5709C37.0456 13.1735 37.2816 13.5441 37.7086 13.6826C38.153 13.8009 38.9286 13.7903 40.0355 13.6507L40.3521 17.888C37.5903 18.4353 35.5939 18.3288 34.363 17.5686C33.1669 16.768 32.4859 15.2565 32.3198 13.0343L32.0052 8.82535L29.8866 8.98369L29.5509 4.49222L31.6695 4.33389L31.4795 1.79155L36.1687 1.44104L36.3587 3.98343L39.2966 3.76387Z" fill="white"/>+<path d="M54.386 11.4704L44.6403 12.1988C45.197 13.3123 46.2945 13.8079 47.9329 13.6854C48.931 13.6108 49.7633 13.2172 50.4296 12.5046L53.9968 14.6241C52.7529 16.4783 50.7939 17.5053 48.1197 17.7051C45.728 17.8839 43.7551 17.3307 42.2009 16.0454C40.6641 14.74 39.8154 13.0138 39.655 10.867C39.4959 8.73895 40.0691 6.90654 41.3746 5.36974C42.68 3.83293 44.425 2.9829 46.6095 2.81964C48.7187 2.662 50.5135 3.23802 51.9938 4.54769C53.4727 5.83852 54.2924 7.55737 54.4528 9.70423C54.5021 10.3634 54.4798 10.9521 54.386 11.4704ZM44.3411 8.95443L49.7647 8.54909C49.3084 7.25758 48.374 6.6646 46.9616 6.77016C45.5115 6.87854 44.638 7.60663 44.3411 8.95443Z" fill="white"/>+<rect x="10.1494" y="24.6061" width="45.8613" height="17.198" rx="8.33792" transform="rotate(-8.52032 10.1494 24.6061)" fill="#08C225"/>+<path d="M23.2928 28.7342C23.8825 28.6413 24.4103 28.7878 24.876 29.1738C25.3476 29.5588 25.6354 30.0815 25.7395 30.742C25.8436 31.4025 25.7309 31.9913 25.4014 32.5086C25.0701 33.0141 24.6125 33.3128 24.0287 33.4048C23.4921 33.4893 23.0455 33.3784 22.689 33.0719L23.0318 35.248L21.5634 35.4793L20.5879 29.2873L22.0563 29.056L22.1204 29.4629C22.3654 29.0617 22.7562 28.8188 23.2928 28.7342ZM22.7713 31.9258C22.9702 32.0758 23.2082 32.1289 23.4854 32.0852C23.7626 32.0416 23.9727 31.9178 24.1158 31.7139C24.2581 31.5042 24.3069 31.2578 24.2623 30.9747C24.2177 30.6917 24.0955 30.4722 23.8956 30.3163C23.6968 30.1664 23.4587 30.1132 23.1816 30.1569C22.9044 30.2005 22.6942 30.3243 22.5511 30.5282C22.4089 30.7379 22.3601 30.9843 22.4047 31.2674C22.4493 31.5505 22.5715 31.7699 22.7713 31.9258Z" fill="white"/>+<path d="M28.2662 27.9506C28.7557 27.8735 29.1743 27.9798 29.5221 28.2695C29.8749 28.5523 30.0987 28.9945 30.1934 29.596L30.6102 32.2409L29.1418 32.4723L28.7543 30.0131C28.719 29.7891 28.6331 29.6273 28.4966 29.528C28.3591 29.4227 28.1872 29.3863 27.9808 29.4189C27.7508 29.4551 27.5821 29.5542 27.4747 29.7162C27.3722 29.8713 27.3414 30.0786 27.3823 30.3381L27.753 32.6911L26.2846 32.9224L25.309 26.7304L26.7774 26.4991L27.1258 28.7105C27.3317 28.2913 27.7119 28.038 28.2662 27.9506Z" fill="white"/>+<path d="M33.1253 31.9715C32.4648 32.0756 31.8722 31.9393 31.3475 31.5627C30.8169 31.187 30.4996 30.6689 30.3955 30.0084C30.2933 29.3597 30.4364 28.7721 30.8249 28.2455C31.2192 27.7181 31.7407 27.4032 32.3894 27.301C33.0499 27.197 33.6429 27.3362 34.1685 27.7187C34.7001 28.1003 35.0169 28.6155 35.1191 29.2642C35.2232 29.9246 35.0805 30.5152 34.6912 31.0359C34.3136 31.5547 33.7916 31.8666 33.1253 31.9715ZM32.9023 30.5562C33.1617 30.5154 33.3606 30.3964 33.4987 30.1994C33.6428 30.0014 33.6935 29.7668 33.6507 29.4955C33.608 29.2243 33.4876 29.0166 33.2897 28.8725C33.0976 28.7275 32.8719 28.6754 32.6124 28.7163C32.3588 28.7563 32.1604 28.8782 32.0173 29.082C31.8791 29.2791 31.8309 29.5103 31.8728 29.7757C31.9146 30.041 32.032 30.2492 32.225 30.4001C32.4229 30.5441 32.6487 30.5962 32.9023 30.5562Z" fill="white"/>+<path d="M37.63 26.6022L37.8516 28.0087L36.9317 28.1537L37.1337 29.4363C37.1635 29.625 37.2474 29.7357 37.3855 29.7683C37.5285 29.7941 37.7727 29.7708 38.1178 29.6982L38.3268 31.0251C37.4708 31.2688 36.8391 31.2867 36.4316 31.0789C36.0341 30.8575 35.7806 30.3989 35.6709 29.703L35.4633 28.385L34.7998 28.4895L34.5782 27.0831L35.2417 26.9785L35.1162 26.1824L36.5149 25.5088L36.7101 26.7472L37.63 26.6022Z" fill="white"/>+<path d="M40.6545 30.7853C39.994 30.8893 39.4014 30.7531 38.8767 30.3764C38.3461 30.0007 38.0288 29.4826 37.9247 28.8221C37.8225 28.1734 37.9656 27.5858 38.3541 27.0593C38.7484 26.5318 39.2699 26.217 39.9186 26.1148C40.5791 26.0107 41.1721 26.1499 41.6978 26.5325C42.2293 26.9141 42.5461 27.4292 42.6483 28.0779C42.7524 28.7384 42.6097 29.3289 42.2204 29.8496C41.8428 30.3684 41.3208 30.6803 40.6545 30.7853ZM40.4315 29.37C40.691 29.3291 40.8898 29.2101 41.028 29.0131C41.172 28.8151 41.2227 28.5805 41.18 28.3093C41.1372 28.038 41.0169 27.8303 40.8189 27.6862C40.6268 27.5412 40.4011 27.4892 40.1416 27.5301C39.888 27.57 39.6897 27.6919 39.5465 27.8958C39.4083 28.0928 39.3602 28.324 39.402 28.5894C39.4438 28.8548 39.5612 29.0629 39.7542 29.2138C39.9521 29.3579 40.1779 29.4099 40.4315 29.37Z" fill="white"/>+<path d="M44.0097 26.9206C44.0218 26.9973 44.0939 27.0524 44.2261 27.086C44.3633 27.1127 44.5663 27.1351 44.835 27.1532C45.0175 27.1607 45.1871 27.1823 45.3439 27.2181C45.5055 27.247 45.6685 27.3029 45.8326 27.3858C46.0017 27.4619 46.142 27.5849 46.2533 27.7547C46.3697 27.9177 46.446 28.1141 46.4822 28.3441C46.563 28.8572 46.4333 29.2614 46.0931 29.5567C45.7478 29.8589 45.3187 30.0504 44.8057 30.1312C43.8149 30.2873 43.0992 30.0405 42.6584 29.3908L43.8393 28.543C44.0024 28.8497 44.2579 28.9756 44.6059 28.9208C44.8712 28.879 44.9914 28.7784 44.9663 28.6192C44.9542 28.5426 44.8826 28.4904 44.7513 28.4627C44.625 28.4282 44.424 28.3995 44.1484 28.3764C43.9659 28.3689 43.7963 28.3473 43.6396 28.3115C43.4879 28.269 43.3274 28.2096 43.1583 28.1335C42.9951 28.0565 42.8592 27.9419 42.7506 27.7898C42.6411 27.6318 42.5692 27.4437 42.5348 27.2255C42.4605 26.7538 42.5768 26.3607 42.8839 26.0464C43.1909 25.7321 43.5892 25.5364 44.0786 25.4593C44.9455 25.3227 45.6068 25.5691 46.0625 26.1983L44.9119 26.9507C44.7422 26.7176 44.5394 26.6196 44.3036 26.6568C44.0854 26.6911 43.9874 26.7791 44.0097 26.9206Z" fill="white"/>+</svg>diff --git a/web/apps/memories/src/components/LaneMemoryViewer.tsx b/web/apps/memories/src/components/LaneMemoryViewer.tsxnew file mode 100644index 0000000000..c98de7ec2c--- /dev/null+++ b/web/apps/memories/src/components/LaneMemoryViewer.tsx@@ -0,0 +1 @@+export { LaneMemoryViewer } from "./PublicMemoryViewerShared";diff --git a/web/apps/memories/src/components/MemoryViewer.tsx b/web/apps/memories/src/components/MemoryViewer.tsxnew file mode 100644index 0000000000..5ea8054033--- /dev/null+++ b/web/apps/memories/src/components/MemoryViewer.tsx@@ -0,0 +1 @@+export { MemoryViewer } from "./PublicMemoryViewerShared";diff --git a/web/apps/memories/src/components/PublicMemoryControls.tsx b/web/apps/memories/src/components/PublicMemoryControls.tsxnew file mode 100644index 0000000000..5dbbdacb38--- /dev/null+++ b/web/apps/memories/src/components/PublicMemoryControls.tsx@@ -0,0 +1,399 @@+import { keyframes } from "@emotion/react";+import { Box, styled } from "@mui/material";+import { useCallback, useMemo, useState } from "react";+import type { LaneCaptionModel } from "../utils/lane";++const MOBILE_LAYOUT_BREAKPOINT_PX = 600;+const DESKTOP_PROGRESS_MAX_WIDTH_PX = 448;+const MOBILE_PROGRESS_MAX_WIDTH_PX = 326;++const progressFillAnimation = keyframes`+ from { width: 0%; }+ to { width: 100%; }+`;++const LaneCaptionInline = styled("span")({+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ flexWrap: "wrap",+ textAlign: "center",+});++const LaneCaptionNumber = styled("span")({+ color: "rgba(255, 255, 255, 0.9)",+ fontFamily: "var(--font-itim), cursive",+ fontSize: "24px",+ fontStyle: "normal",+ fontWeight: 400,+ lineHeight: "7.801px",+ display: "inline-flex",+ minWidth: "2ch",+ justifyContent: "center",+});++const LaneProgressTrack = styled("div")({+ position: "relative",+ width: "100%",+ maxWidth: "640px",+ height: "8px",+ borderRadius: "999px",+ backgroundColor: "rgba(193, 246, 235, 0.32)",+ cursor: "pointer",+ "@media (max-width: 900px)": { maxWidth: "320px" },+ [`@media (max-width: ${MOBILE_LAYOUT_BREAKPOINT_PX}px)`]: {+ maxWidth: "248px",+ },+});++const LaneProgressFill = styled("div")({+ position: "absolute",+ left: 0,+ top: 0,+ bottom: 0,+ borderRadius: "999px",+ backgroundColor: "#62d049",+});++const LaneProgressThumb = styled("div")({+ position: "absolute",+ top: "50%",+ width: "20px",+ height: "20px",+ borderRadius: "999px",+ backgroundColor: "white",+ boxShadow: "0 2px 12px rgba(0, 0, 0, 0.35)",+ transform: "translate(-50%, -50%)",+});++export const PlaybackGlyph: React.FC<{ paused: boolean }> = ({ paused }) => {+ if (paused) {+ return (+ <Box+ sx={{+ width: 0,+ height: 0,+ borderTop: "10px solid transparent",+ borderBottom: "10px solid transparent",+ borderLeft: "14px solid white",+ ml: "3px",+ }}+ />+ );+ }++ return (+ <Box sx={{ display: "flex", gap: "6px" }}>+ <Box+ sx={{+ width: "6px",+ height: "18px",+ borderRadius: "2px",+ backgroundColor: "white",+ }}+ />+ <Box+ sx={{+ width: "6px",+ height: "18px",+ borderRadius: "2px",+ backgroundColor: "white",+ }}+ />+ </Box>+ );+};++export const LanePlaybackGlyph: React.FC<{ paused: boolean }> = ({+ paused,+}) => {+ if (paused) {+ return (+ <Box+ sx={{+ width: 0,+ height: 0,+ borderTop: "5px solid transparent",+ borderBottom: "5px solid transparent",+ borderLeft: "8px solid white",+ ml: "2px",+ }}+ />+ );+ }++ return (+ <Box sx={{ display: "flex", gap: "3px" }}>+ <Box+ sx={{+ width: "3px",+ height: "10px",+ borderRadius: "1px",+ backgroundColor: "white",+ }}+ />+ <Box+ sx={{+ width: "3px",+ height: "10px",+ borderRadius: "1px",+ backgroundColor: "white",+ }}+ />+ </Box>+ );+};++export const LaneCaptionText: React.FC<{+ model: LaneCaptionModel;+ previousValue?: number;+}> = ({ model, previousValue }) => {+ if (typeof model.value !== "number") {+ return <>{model.text}</>;+ }++ const currentValue = model.value;+ const formattedValue = new Intl.NumberFormat().format(currentValue);+ const formattedPrevious = new Intl.NumberFormat().format(+ previousValue ?? currentValue,+ );++ return (+ <LaneCaptionInline>+ {model.prefix}+ <LaneCaptionNumber+ key={`${formattedPrevious}->${formattedValue}`}+ style={{+ transition:+ "transform 320ms cubic-bezier(0.22, 1, 0.36, 1)",+ transform:+ previousValue === currentValue+ ? "translateY(0)"+ : "translateY(0)",+ }}+ >+ {formattedValue}+ </LaneCaptionNumber>+ {model.suffix}+ </LaneCaptionInline>+ );+};++interface LaneProgressSliderProps {+ total: number;+ current?: number;+ currentProgress?: number;+ onSeek: (index: number) => void;+ onScrubStart?: () => void;+ onScrub?: (value: number) => void;+ onScrubEnd?: (value: number) => void;+}++export const LaneProgressSlider: React.FC<LaneProgressSliderProps> = ({+ total,+ current,+ currentProgress,+ onSeek,+ onScrubStart,+ onScrub,+ onScrubEnd,+}) => {+ const progressPercentage = useMemo(() => {+ if (total <= 1) {+ return 0;+ }+ const value = currentProgress ?? current ?? 0;+ return (value / (total - 1)) * 100;+ }, [current, currentProgress, total]);++ const [draggingPointerId, setDraggingPointerId] = useState<number | null>(+ null,+ );++ const getScrubValue = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ const rect = event.currentTarget.getBoundingClientRect();+ if (rect.width <= 0 || total <= 1) {+ return 0;+ }+ const ratio = (event.clientX - rect.left) / rect.width;+ return Math.min(Math.max(ratio, 0), 1) * (total - 1);+ },+ [total],+ );++ const handlePointerDown = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ event.stopPropagation();+ if (total <= 1) {+ return;+ }+ setDraggingPointerId(event.pointerId);+ event.currentTarget.setPointerCapture(event.pointerId);+ const value = getScrubValue(event);+ onScrubStart?.();+ onScrub?.(value);+ },+ [getScrubValue, onScrub, onScrubStart, total],+ );++ const handlePointerMove = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ if (draggingPointerId !== event.pointerId) {+ return;+ }+ event.stopPropagation();+ onScrub?.(getScrubValue(event));+ },+ [draggingPointerId, getScrubValue, onScrub],+ );++ const endScrub = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ if (draggingPointerId !== event.pointerId) {+ return;+ }+ event.stopPropagation();+ const value = getScrubValue(event);+ event.currentTarget.releasePointerCapture(event.pointerId);+ setDraggingPointerId(null);+ onScrubEnd?.(value);+ if (!onScrubEnd) {+ onSeek(Math.round(value));+ }+ },+ [draggingPointerId, getScrubValue, onScrubEnd, onSeek],+ );++ return (+ <LaneProgressTrack+ data-memory-control="true"+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={endScrub}+ onPointerCancel={endScrub}+ >+ <LaneProgressFill style={{ width: `${progressPercentage}%` }} />+ <LaneProgressThumb style={{ left: `${progressPercentage}%` }} />+ </LaneProgressTrack>+ );+};++interface ProgressIndicatorProps {+ total: number;+ current: number;+ paused: boolean;+ duration: number;+ onComplete: () => void;+ isVideo?: boolean;+ compact?: boolean;+}++export const ProgressIndicator: React.FC<ProgressIndicatorProps> = ({+ total,+ current,+ paused,+ duration,+ onComplete,+ isVideo,+ compact,+}) => {+ const segments = useMemo(+ () => Array.from({ length: total }, (_, i) => i),+ [total],+ );+ const progressGap = total > 15 ? "4px" : "12px";++ return (+ <Box+ sx={{+ display: "flex",+ gap: progressGap,+ alignItems: "center",+ width: "100%",+ maxWidth: compact+ ? `${MOBILE_PROGRESS_MAX_WIDTH_PX}px`+ : `${DESKTOP_PROGRESS_MAX_WIDTH_PX}px`,+ minWidth: 0,+ height: "4px",+ }}+ >+ {segments.map((i) => (+ <ProgressBar+ key={+ i === current+ ? `active-${current}-${duration}`+ : `segment-${i}`+ }+ state={+ i < current+ ? "past"+ : i === current+ ? "active"+ : "future"+ }+ paused={paused}+ duration={duration}+ onComplete={+ i === current && !isVideo ? onComplete : undefined+ }+ />+ ))}+ </Box>+ );+};++interface ProgressBarProps {+ state: "past" | "active" | "future";+ paused: boolean;+ duration: number;+ onComplete?: () => void;+}++const ProgressBar: React.FC<ProgressBarProps> = ({+ state,+ paused,+ duration,+ onComplete,+}) => {+ return (+ <Box+ sx={{+ position: "relative",+ flex: 1,+ minWidth: 0,+ height: "4px",+ borderRadius: "14px",+ backgroundColor: "rgba(255, 255, 255, 0.45)",+ overflow: "hidden",+ }}+ >+ <Box+ onAnimationEnd={state === "active" ? onComplete : undefined}+ style={+ state === "active"+ ? { animationPlayState: paused ? "paused" : "running" }+ : undefined+ }+ sx={{+ position: "absolute",+ top: 0,+ left: 0,+ height: "100%",+ borderRadius: "14px",+ backgroundColor: "white",+ width:+ state === "past"+ ? "100%"+ : state === "active"+ ? "100%"+ : "0%",+ ...(state === "active" && {+ animation: `${progressFillAnimation} ${duration}ms linear forwards`,+ }),+ ...(state === "past" && { transition: "none" }),+ }}+ />+ </Box>+ );+};diff --git a/web/apps/memories/src/components/PublicMemoryMedia.tsx b/web/apps/memories/src/components/PublicMemoryMedia.tsxnew file mode 100644index 0000000000..7b0cdb0701--- /dev/null+++ b/web/apps/memories/src/components/PublicMemoryMedia.tsx@@ -0,0 +1,473 @@+import { Box, Typography } from "@mui/material";+import { LoadingIndicator } from "ente-base/components/loaders";+import log from "ente-base/log";+import {+ downloadManager,+ type RenderableSourceURLs,+} from "ente-gallery/services/download";+import type { HLSPlaylistData } from "ente-gallery/services/video";+import type { EnteFile } from "ente-media/file";+import type { PublicMemoryShareFrameCrop } from "ente-new/albums/services/public-memory";+import "hls-video-element";+import {+ type CSSProperties,+ type RefObject,+ useCallback,+ useEffect,+ useRef,+ useState,+} from "react";+import { computeMediaCropStyle } from "../utils/lane";++const DEFAULT_MEDIA_MAX_WIDTH_CSS = "min(1264px, calc(100vw - 48px))";+const DEFAULT_MEDIA_MAX_HEIGHT_CSS = "calc(min(100vh, 100dvh) - 220px)";++const buildMediaStyle = ({+ cropRect,+ cropContainerAspectRatio,+ fillFrame,+ mediaAspectRatio,+ objectFit,+}: {+ cropRect?: PublicMemoryShareFrameCrop;+ cropContainerAspectRatio?: number;+ fillFrame?: boolean;+ mediaAspectRatio?: number;+ objectFit: "contain" | "cover";+}): CSSProperties => {+ const cropStyle = computeMediaCropStyle({+ cropRect,+ mediaAspectRatio,+ containerAspectRatio: cropContainerAspectRatio,+ });++ return {+ display: "block",+ ...(cropStyle ?? {+ width: fillFrame ? "100%" : "auto",+ height: fillFrame ? "100%" : "auto",+ maxWidth: fillFrame ? "100%" : DEFAULT_MEDIA_MAX_WIDTH_CSS,+ maxHeight: fillFrame ? "100%" : DEFAULT_MEDIA_MAX_HEIGHT_CSS,+ objectFit,+ }),+ userSelect: "none",+ pointerEvents: "none",+ };+};++function MediaLoadingOverlay() {+ return (+ <Box+ sx={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: "rgba(0, 0, 0, 0.5)",+ zIndex: 2,+ }}+ >+ <LoadingIndicator />+ </Box>+ );+}++export interface PhotoImageProps {+ file: EnteFile;+ onFullLoad?: () => void;+ fillFrame?: boolean;+ objectFit?: "contain" | "cover";+ thumbnailOnly?: boolean;+ cropRect?: PublicMemoryShareFrameCrop;+ cropContainerAspectRatio?: number;+ mediaAspectRatio?: number;+ onAspectRatio?: (width: number, height: number) => void;+ showLoadingOverlay?: boolean;+}++export function PhotoImage({+ file,+ onFullLoad,+ fillFrame,+ objectFit = "contain",+ thumbnailOnly = false,+ cropRect,+ cropContainerAspectRatio,+ mediaAspectRatio,+ onAspectRatio,+ showLoadingOverlay = true,+}: PhotoImageProps) {+ const [thumbnailURL, setThumbnailURL] = useState<string | undefined>(+ undefined,+ );+ const [fullImageURL, setFullImageURL] = useState<string | undefined>(+ undefined,+ );+ const [isLoading, setIsLoading] = useState(true);+ const imageRef = useRef<HTMLImageElement | null>(null);+ const onFullLoadRef = useRef(onFullLoad);+ const onAspectRatioRef = useRef(onAspectRatio);+ const mediaReadyRef = useRef(false);+ const hasNotifiedDisplayReadyRef = useRef(false);++ onFullLoadRef.current = onFullLoad;+ onAspectRatioRef.current = onAspectRatio;++ const signalReady = useCallback(() => {+ mediaReadyRef.current = true;+ if (hasNotifiedDisplayReadyRef.current || !onFullLoadRef.current) {+ return;+ }+ hasNotifiedDisplayReadyRef.current = true;+ onFullLoadRef.current();+ }, []);++ useEffect(() => {+ let cancelled = false;+ setIsLoading(true);+ setThumbnailURL(undefined);+ setFullImageURL(undefined);+ mediaReadyRef.current = false;+ hasNotifiedDisplayReadyRef.current = false;++ const loadThumbnail = async () => {+ try {+ const nextThumbnailURL =+ await downloadManager.renderableThumbnailURL(file);+ if (!cancelled && nextThumbnailURL) {+ setThumbnailURL(nextThumbnailURL);+ } else if (!cancelled) {+ setIsLoading(false);+ }+ } catch (error) {+ log.error("Failed to load thumbnail", error);+ if (!cancelled) {+ setIsLoading(false);+ }+ }+ };++ const loadFullImage = async () => {+ if (thumbnailOnly) {+ return;+ }+ try {+ const sourceURLs =+ await downloadManager.renderableSourceURLs(file);+ if (cancelled) {+ return;+ }+ if (sourceURLs.type === "image") {+ setFullImageURL(sourceURLs.imageURL);+ } else {+ signalReady();+ }+ } catch (error) {+ log.error("Failed to load full image", error);+ if (!cancelled) {+ signalReady();+ }+ }+ };++ void loadThumbnail();+ void loadFullImage();++ return () => {+ cancelled = true;+ };+ }, [file, signalReady, thumbnailOnly]);++ useEffect(() => {+ if (!onFullLoad) {+ hasNotifiedDisplayReadyRef.current = false;+ return;+ }+ if (mediaReadyRef.current && !hasNotifiedDisplayReadyRef.current) {+ hasNotifiedDisplayReadyRef.current = true;+ onFullLoad();+ }+ }, [onFullLoad]);++ useEffect(() => {+ if (thumbnailOnly || !fullImageURL) {+ return;+ }+ const image = imageRef.current;+ if (!image?.complete) {+ return;+ }+ if (image.naturalWidth > 0 && image.naturalHeight > 0) {+ onAspectRatioRef.current?.(image.naturalWidth, image.naturalHeight);+ }+ }, [fullImageURL, thumbnailOnly]);++ const displayURL = fullImageURL ?? thumbnailURL;+ const mediaStyle = buildMediaStyle({+ cropRect,+ cropContainerAspectRatio,+ fillFrame,+ mediaAspectRatio,+ objectFit,+ });++ return (+ <Box+ sx={{+ position: "relative",+ display: fillFrame ? "block" : "inline-block",+ width: fillFrame ? "100%" : "auto",+ height: fillFrame ? "100%" : "auto",+ overflow: "hidden",+ }}+ >+ {isLoading && showLoadingOverlay && <MediaLoadingOverlay />}++ {displayURL && (+ <img+ ref={imageRef}+ src={displayURL}+ alt=""+ draggable={false}+ onLoad={(event) => {+ const isFullImageLoad =+ !thumbnailOnly &&+ !!fullImageURL &&+ event.currentTarget.src === fullImageURL;+ if (isFullImageLoad) {+ onAspectRatioRef.current?.(+ event.currentTarget.naturalWidth,+ event.currentTarget.naturalHeight,+ );+ }+ setIsLoading(false);+ if (thumbnailOnly || isFullImageLoad) {+ signalReady();+ }+ }}+ style={mediaStyle}+ />+ )}+ </Box>+ );+}++export interface VideoPlayerProps {+ file: EnteFile;+ onReady?: () => void;+ onDuration?: (durationSeconds: number) => void;+ onEnded?: () => void;+ paused?: boolean;+ mediaRef?: RefObject<HTMLVideoElement | null>;+ fillFrame?: boolean;+ objectFit?: "contain" | "cover";+ cropRect?: PublicMemoryShareFrameCrop;+ cropContainerAspectRatio?: number;+ mediaAspectRatio?: number;+ onAspectRatio?: (width: number, height: number) => void;+ showLoadingOverlay?: boolean;+}++export function VideoPlayer({+ file,+ onReady,+ onDuration,+ onEnded,+ paused,+ mediaRef,+ fillFrame,+ objectFit = "contain",+ cropRect,+ cropContainerAspectRatio,+ mediaAspectRatio,+ onAspectRatio,+ showLoadingOverlay = true,+}: VideoPlayerProps) {+ const [hlsData, setHlsData] = useState<HLSPlaylistData | undefined>(+ undefined,+ );+ const [videoURL, setVideoURL] = useState<string | undefined>(undefined);+ const [thumbnailURL, setThumbnailURL] = useState<string | undefined>(+ undefined,+ );+ const [isLoading, setIsLoading] = useState(true);+ const [error, setError] = useState(false);+ const videoRef = useRef<HTMLVideoElement>(null);+ const onReadyRef = useRef(onReady);+ const onDurationRef = useRef(onDuration);+ const onEndedRef = useRef(onEnded);++ onReadyRef.current = onReady;+ onDurationRef.current = onDuration;+ onEndedRef.current = onEnded;++ const setVideoElementRef = useCallback(+ (node: HTMLVideoElement | null) => {+ videoRef.current = node;+ if (mediaRef) {+ mediaRef.current = node;+ }+ },+ [mediaRef],+ );++ useEffect(() => {+ let cancelled = false;+ setIsLoading(true);+ setError(false);+ setVideoURL(undefined);+ setHlsData(undefined);+ setThumbnailURL(undefined);++ const load = async () => {+ try {+ const nextThumbnailURL =+ await downloadManager.renderableThumbnailURL(file);+ if (!cancelled && nextThumbnailURL) {+ setThumbnailURL(nextThumbnailURL);+ }++ const nextHlsData =+ await downloadManager.hlsPlaylistDataForPublicMemory(file);+ if (+ !cancelled &&+ typeof nextHlsData === "object" &&+ nextHlsData.playlistURL+ ) {+ setHlsData(nextHlsData);+ return;+ }++ const sourceURLs: RenderableSourceURLs =+ await downloadManager.renderableSourceURLs(file);+ if (!cancelled && sourceURLs.type === "video") {+ setVideoURL(sourceURLs.videoURL);+ } else if (!cancelled) {+ setIsLoading(false);+ }+ } catch (error) {+ log.error("Failed to load video", error);+ if (!cancelled) {+ setError(true);+ setIsLoading(false);+ }+ }+ };++ void load();++ return () => {+ cancelled = true;+ };+ }, [file]);++ useEffect(() => {+ const video = videoRef.current;+ if (!video || (!videoURL && !hlsData)) {+ return;+ }++ if (paused) {+ video.pause();+ } else {+ video.play().catch(() => {+ // Autoplay may be blocked; ignore.+ });+ }+ }, [hlsData, paused, videoURL]);++ const handleLoadedMetadata = useCallback(() => {+ const video = videoRef.current;+ if (video && !Number.isNaN(video.duration) && video.duration > 0) {+ onAspectRatio?.(video.videoWidth, video.videoHeight);+ onDurationRef.current?.(video.duration);+ }+ }, [onAspectRatio]);++ const handleCanPlay = useCallback(() => {+ setIsLoading(false);+ onReadyRef.current?.();+ const video = videoRef.current;+ if (video && !paused) {+ video.play().catch(() => {+ // Autoplay may be blocked.+ });+ }+ }, [paused]);++ const handleEnded = useCallback(() => {+ onEndedRef.current?.();+ }, []);++ const mediaStyle = buildMediaStyle({+ cropRect,+ cropContainerAspectRatio,+ fillFrame,+ mediaAspectRatio,+ objectFit,+ });++ if (error) {+ return (+ <Box+ sx={{+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ width: "100%",+ height: "100%",+ }}+ >+ <Typography sx={{ color: "rgba(255,255,255,0.7)" }}>+ Unable to play video+ </Typography>+ </Box>+ );+ }++ return (+ <Box+ sx={{+ position: "relative",+ display: fillFrame ? "block" : "inline-block",+ width: fillFrame ? "100%" : "auto",+ height: fillFrame ? "100%" : "auto",+ overflow: "hidden",+ }}+ >+ {isLoading && showLoadingOverlay && <MediaLoadingOverlay />}++ {hlsData && (+ <hls-video+ ref={setVideoElementRef}+ src={hlsData.playlistURL}+ poster={thumbnailURL}+ playsInline+ onLoadedMetadata={handleLoadedMetadata}+ onCanPlay={handleCanPlay}+ onEnded={handleEnded}+ style={mediaStyle}+ />+ )}++ {!hlsData && videoURL && (+ <video+ ref={setVideoElementRef}+ src={videoURL}+ poster={thumbnailURL}+ playsInline+ muted={false}+ onLoadedMetadata={handleLoadedMetadata}+ onCanPlay={handleCanPlay}+ onEnded={handleEnded}+ style={mediaStyle}+ />+ )}++ {!videoURL && !hlsData && thumbnailURL && (+ <img src={thumbnailURL} alt="" style={mediaStyle} />+ )}+ </Box>+ );+}diff --git a/web/apps/memories/src/components/PublicMemoryPageShell.tsx b/web/apps/memories/src/components/PublicMemoryPageShell.tsxnew file mode 100644index 0000000000..518abdcf4e--- /dev/null+++ b/web/apps/memories/src/components/PublicMemoryPageShell.tsx@@ -0,0 +1,56 @@+import { Typography } from "@mui/material";+import { Stack100vhCenter } from "ente-base/components/containers";+import { CustomHead } from "ente-base/components/Head";+import { LoadingIndicator } from "ente-base/components/loaders";+import Head from "next/head";+import type { PropsWithChildren } from "react";++function PublicMemoryDocumentHead() {+ return (+ <>+ <CustomHead title="Ente Memories" />+ <Head>+ <meta name="robots" content="noindex, nofollow" />+ </Head>+ </>+ );+}++export function PublicMemoryPageShell({ children }: PropsWithChildren) {+ return (+ <>+ <PublicMemoryDocumentHead />+ {children}+ </>+ );+}++export function PublicMemoryLoadingState() {+ return (+ <PublicMemoryPageShell>+ <LoadingIndicator />+ </PublicMemoryPageShell>+ );+}++export function PublicMemoryErrorState({ message }: { message: string }) {+ return (+ <PublicMemoryPageShell>+ <Stack100vhCenter>+ <Typography sx={{ color: "critical.main" }}>+ {message}+ </Typography>+ </Stack100vhCenter>+ </PublicMemoryPageShell>+ );+}++export function PublicMemoryEmptyState() {+ return (+ <PublicMemoryPageShell>+ <Stack100vhCenter>+ <Typography>No photos found in this memory.</Typography>+ </Stack100vhCenter>+ </PublicMemoryPageShell>+ );+}diff --git a/web/apps/memories/src/components/PublicMemoryViewerShared.tsx b/web/apps/memories/src/components/PublicMemoryViewerShared.tsxnew file mode 100644index 0000000000..eaa95433e0--- /dev/null+++ b/web/apps/memories/src/components/PublicMemoryViewerShared.tsx@@ -0,0 +1,2295 @@+import { keyframes } from "@emotion/react";+import { Box, Typography, styled } from "@mui/material";+import { downloadManager } from "ente-gallery/services/download";+import type { EnteFile } from "ente-media/file";+import { fileCreationPhotoDate } from "ente-media/file-metadata";+import { FileType } from "ente-media/file-type";+import {+ type PublicMemoryShareFrame,+ type PublicMemoryShareMetadata,+} from "ente-new/albums/services/public-memory";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ buildLaneCaptionModel,+ buildLaneTitle,+ calculateLaneBlur,+ calculateLaneOpacity,+ calculateLaneOverlayOpacity,+ calculateLaneRotation,+ calculateLaneScale,+ calculateLaneYOffset,+ easeInOutCubic,+ formatLaneCaption,+ getFileAspectRatio,+ getFrameCreationDate,+ getLaneStackSlices,+ laneCardShadow,+ lerp,+ resolveLaneCropRect,+} from "../utils/lane";+import {+ LaneCaptionText,+ LanePlaybackGlyph,+ LaneProgressSlider,+ PlaybackGlyph,+ ProgressIndicator,+} from "./PublicMemoryControls";+import { PhotoImage, VideoPlayer } from "./PublicMemoryMedia";++interface MemoryViewerProps {+ files: EnteFile[];+ currentIndex: number;+ memoryName: string;+ memoryMetadata?: PublicMemoryShareMetadata;+ laneFrames?: (PublicMemoryShareFrame | undefined)[];+ variant: "share" | "lane";+ onNext: () => void;+ onPrev: () => void;+ onSeek: (index: number) => void;+}++const IMAGE_AUTO_PROGRESS_DURATION_MS = 5000;+const LANE_FRAME_INTERVAL_MS = 800;+const LANE_CARD_TRANSITION_DURATION_MS = 520;+const MOBILE_LAYOUT_BREAKPOINT_PX = 600;+const SHARE_FOOTER_ACTIONS_BREAKPOINT_PX = 960;+const LANE_COMPACT_LAYOUT_BREAKPOINT_PX = 900;+const EDGE_NAV_TAP_ZONE_RATIO = 0.2;+const HOLD_TO_PAUSE_NAV_SUPPRESSION_MS = 250;+const MOBILE_MEDIA_RESERVED_VERTICAL_SPACE_PX = 280;+const LANE_MOBILE_MEDIA_RESERVED_VERTICAL_SPACE_PX = 340;+const DESKTOP_MEDIA_MAX_WIDTH_PX = 1264;+const DESKTOP_MEDIA_HORIZONTAL_PADDING_PX = 48;+const DESKTOP_MEDIA_VERTICAL_RESERVED_PX = 220;+const DESKTOP_LANE_MEDIA_VERTICAL_RESERVED_PX = 320;+const LANE_CARD_ASPECT_RATIO = 0.68;+const LANE_MOBILE_CARD_MAX_WIDTH_PX = 326;+const LANE_MOBILE_CARD_MIN_WIDTH_PX = 220;+const LANE_DESKTOP_CARD_MAX_WIDTH_PX = 420;+const LANE_DESKTOP_CARD_MIN_WIDTH_PX = 280;+const MEDIA_SWITCH_TRANSITION_DURATION_MS = 380;+const DESKTOP_MEDIA_MAX_WIDTH_CSS = `min(${DESKTOP_MEDIA_MAX_WIDTH_PX}px, calc(100vw - ${DESKTOP_MEDIA_HORIZONTAL_PADDING_PX}px))`;+const DESKTOP_MEDIA_MAX_HEIGHT_CSS = `calc(min(100vh, 100dvh) - ${DESKTOP_MEDIA_VERTICAL_RESERVED_PX}px)`;+const DESKTOP_BACKGROUND_IMAGE_PATH = "/images/desktop-bg.svg";+const MOBILE_BACKGROUND_IMAGE_PATH = "/images/mobile-bg.svg";+const ENTE_BRAND_TAG_IMAGE_PATH = "/images/ente-brand-tag.svg";+const LANE_GRID_CELL_SIZE_PX = 80;+const LANE_GRID_LINE_COLOR = "#08c225";+const LANE_GRID_LINE_OPACITY = 0.06;+const LANE_GRID_DISPLACEMENT_SCALE = 9;++interface LaneMemoryViewerProps {+ files: EnteFile[];+ currentIndex: number;+ memoryName: string;+ memoryMetadata?: PublicMemoryShareMetadata;+ laneFrames?: (PublicMemoryShareFrame | undefined)[];+ onNext: () => void;+ onPrev: () => void;+ onSeek: (index: number) => void;+}++export const LaneMemoryViewer: React.FC<LaneMemoryViewerProps> = ({+ files,+ currentIndex,+ memoryName,+ memoryMetadata,+ laneFrames,+ onNext,+ onPrev,+ onSeek,+}) => {+ const [paused, setPaused] = useState(false);+ const [fileLoaded, setFileLoaded] = useState(false);+ const [videoDurationKnown, setVideoDurationKnown] = useState(false);+ const [viewport, setViewport] = useState({ width: 1280, height: 720 });+ const [stackProgress, setStackProgress] = useState(currentIndex);+ const [displayIndex, setDisplayIndex] = useState(currentIndex);+ const [isScrubbing, setIsScrubbing] = useState(false);+ const [isAnimatingStack, setIsAnimatingStack] = useState(false);+ const [activeMediaAspectRatio, setActiveMediaAspectRatio] = useState<+ number | undefined+ >(undefined);+ const [previousCaptionValue, setPreviousCaptionValue] = useState<+ number | undefined+ >(() => {+ const initialModel = buildLaneCaptionModel({+ frame: laneFrames?.[currentIndex],+ metadata: memoryMetadata,+ fallbackLabel: memoryName || "Memory lane",+ });+ return initialModel.value;+ });+ const pressStartedAtRef = useRef<number | null>(null);+ const suppressTapNavigationRef = useRef(false);+ const shouldResumeAfterHoldRef = useRef(false);+ const finishedLanePlaybackRef = useRef(false);+ const restartOnResumeRef = useRef(false);+ const animationFrameRef = useRef<number | null>(null);+ const animationStartTimestampRef = useRef<number | null>(null);+ const stackProgressRef = useRef(currentIndex);+ const displayIndexRef = useRef(currentIndex);+ const currentIndexRef = useRef(currentIndex);+ const pausedRef = useRef(paused);+ const isVideoRef = useRef(false);+ const isAnimatingStackRef = useRef(false);+ const isScrubbingRef = useRef(false);+ const fileLoadedRef = useRef(false);+ const videoDurationKnownRef = useRef(false);+ const onNextRef = useRef(onNext);+ const laneAdvanceTimeoutRef = useRef<number | null>(null);+ const activeVideoElementRef = useRef<HTMLVideoElement | null>(null);++ const currentFile = files[displayIndex]!;+ const currentLaneFrame = laneFrames?.[displayIndex];+ const isVideo = currentFile.metadata.fileType === FileType.video;+ const isMobileLayout = viewport.width <= MOBILE_LAYOUT_BREAKPOINT_PX;+ const isCompactLaneLayout =+ viewport.width <= LANE_COMPACT_LAYOUT_BREAKPOINT_PX;++ onNextRef.current = onNext;+ currentIndexRef.current = currentIndex;+ pausedRef.current = paused;+ stackProgressRef.current = stackProgress;+ displayIndexRef.current = displayIndex;+ isVideoRef.current = currentFile.metadata.fileType === FileType.video;+ isAnimatingStackRef.current = isAnimatingStack;+ isScrubbingRef.current = isScrubbing;+ fileLoadedRef.current = fileLoaded;+ videoDurationKnownRef.current = videoDurationKnown;+ const laneCaptionModel = buildLaneCaptionModel({+ frame: currentLaneFrame,+ metadata: memoryMetadata,+ fallbackLabel: memoryName || "Memory lane",+ });++ const cancelStackAnimation = useCallback(() => {+ if (animationFrameRef.current !== null) {+ window.cancelAnimationFrame(animationFrameRef.current);+ animationFrameRef.current = null;+ }+ animationStartTimestampRef.current = null;+ setIsAnimatingStack(false);+ }, []);++ const clearLaneAdvanceTimeout = useCallback(() => {+ if (laneAdvanceTimeoutRef.current !== null) {+ window.clearTimeout(laneAdvanceTimeoutRef.current);+ laneAdvanceTimeoutRef.current = null;+ }+ }, []);++ const scheduleLaneAdvance = useCallback(() => {+ clearLaneAdvanceTimeout();+ if (files.length <= 1 || pausedRef.current || isVideoRef.current) {+ return;+ }+ if (isScrubbingRef.current || isAnimatingStackRef.current) {+ return;+ }+ if (!fileLoadedRef.current) {+ return;+ }+ if (currentIndexRef.current >= files.length - 1) {+ return;+ }++ laneAdvanceTimeoutRef.current = window.setTimeout(() => {+ laneAdvanceTimeoutRef.current = null;+ onNextRef.current();+ }, LANE_FRAME_INTERVAL_MS);+ }, [clearLaneAdvanceTimeout, files.length]);++ const commitDisplayIndex = useCallback(+ (nextIndex: number) => {+ const previousModel = buildLaneCaptionModel({+ frame: laneFrames?.[displayIndexRef.current],+ metadata: memoryMetadata,+ fallbackLabel: memoryName || "Memory lane",+ });+ const nextModel = buildLaneCaptionModel({+ frame: laneFrames?.[nextIndex],+ metadata: memoryMetadata,+ fallbackLabel: memoryName || "Memory lane",+ });+ setPreviousCaptionValue(previousModel.value ?? nextModel.value);+ setFileLoaded(false);+ setVideoDurationKnown(false);+ setActiveMediaAspectRatio(undefined);+ setDisplayIndex(nextIndex);+ },+ [laneFrames, memoryMetadata, memoryName],+ );++ useEffect(+ () => () => {+ cancelStackAnimation();+ clearLaneAdvanceTimeout();+ },+ [cancelStackAnimation, clearLaneAdvanceTimeout],+ );++ useEffect(() => {+ const updateViewport = () =>+ setViewport({+ width: window.innerWidth,+ height: window.innerHeight,+ });++ updateViewport();+ window.addEventListener("resize", updateViewport);+ return () => window.removeEventListener("resize", updateViewport);+ }, []);++ useEffect(() => {+ if (isScrubbing) {+ return;+ }++ finishedLanePlaybackRef.current = false;++ const targetIndex = Math.min(+ Math.max(currentIndex, 0),+ files.length - 1,+ );+ const startProgress = stackProgressRef.current;+ cancelStackAnimation();++ if (Math.abs(targetIndex - startProgress) < 0.0001) {+ setStackProgress(targetIndex);+ if (displayIndexRef.current !== targetIndex) {+ commitDisplayIndex(targetIndex);+ }+ return;+ }++ const duration =+ LANE_CARD_TRANSITION_DURATION_MS *+ Math.min(Math.max(Math.abs(targetIndex - startProgress), 1), 4);+ setIsAnimatingStack(true);++ const tick = (timestamp: number) => {+ if (animationStartTimestampRef.current === null) {+ animationStartTimestampRef.current = timestamp;+ }+ const elapsed = timestamp - animationStartTimestampRef.current;+ const progress = Math.min(elapsed / duration, 1);+ const eased = easeInOutCubic(progress);+ setStackProgress(lerp(startProgress, targetIndex, eased));++ if (progress < 1) {+ animationFrameRef.current = window.requestAnimationFrame(tick);+ return;+ }++ animationFrameRef.current = null;+ animationStartTimestampRef.current = null;+ setIsAnimatingStack(false);+ setStackProgress(targetIndex);+ if (displayIndexRef.current !== targetIndex) {+ commitDisplayIndex(targetIndex);+ }+ };++ animationFrameRef.current = window.requestAnimationFrame(tick);+ }, [+ cancelStackAnimation,+ commitDisplayIndex,+ currentIndex,+ files.length,+ isScrubbing,+ ]);++ useEffect(() => {+ if (paused) {+ clearLaneAdvanceTimeout();+ activeVideoElementRef.current?.pause();+ return;+ }++ if (restartOnResumeRef.current) {+ restartOnResumeRef.current = false;+ if (currentIndexRef.current > 0) {+ onSeek(0);+ return;+ }++ const activeVideo = activeVideoElementRef.current;+ if (activeVideo) {+ activeVideo.currentTime = 0;+ }+ }++ if (isAnimatingStack || isScrubbing || !fileLoaded) {+ return;+ }++ if (isVideo) {+ const activeVideo = activeVideoElementRef.current;+ if (activeVideo) {+ void activeVideo.play().catch(() => {+ // Browser playback policies may still reject here.+ });+ }+ return;+ }++ if (currentIndex >= files.length - 1) {+ clearLaneAdvanceTimeout();+ laneAdvanceTimeoutRef.current = window.setTimeout(() => {+ laneAdvanceTimeoutRef.current = null;+ finishedLanePlaybackRef.current = true;+ setPaused(true);+ }, LANE_FRAME_INTERVAL_MS);+ return clearLaneAdvanceTimeout;+ }++ scheduleLaneAdvance();+ return clearLaneAdvanceTimeout;+ }, [+ clearLaneAdvanceTimeout,+ currentIndex,+ fileLoaded,+ files.length,+ isAnimatingStack,+ isScrubbing,+ isVideo,+ onSeek,+ paused,+ scheduleLaneAdvance,+ videoDurationKnown,+ ]);++ const handleFullLoad = useCallback(() => {+ setFileLoaded(true);+ }, []);++ const handleVideoDuration = useCallback((durationSeconds: number) => {+ void durationSeconds;+ setVideoDurationKnown(true);+ }, []);++ const handleActiveAspectRatio = useCallback(+ (width: number, height: number) => {+ if (width <= 0 || height <= 0) {+ return;+ }+ setActiveMediaAspectRatio(width / height);+ },+ [],+ );++ const handlePlaybackToggle = useCallback(+ (event: React.MouseEvent<HTMLButtonElement>) => {+ event.stopPropagation();+ setPaused((previous) => {+ const nextPaused = !previous;+ restartOnResumeRef.current =+ !nextPaused && finishedLanePlaybackRef.current;+ if (!nextPaused) {+ finishedLanePlaybackRef.current = false;+ }+ return nextPaused;+ });+ },+ [],+ );++ const handleVideoEnded = useCallback(() => {+ if (currentIndexRef.current >= files.length - 1) {+ finishedLanePlaybackRef.current = true;+ setPaused(true);+ return;+ }+ onNext();+ }, [files.length, onNext]);++ const handleScreenTap = useCallback(+ (event: React.MouseEvent<HTMLDivElement>) => {+ if (suppressTapNavigationRef.current) {+ suppressTapNavigationRef.current = false;+ return;+ }+ if (isInteractiveTapTarget(event.target)) {+ return;+ }+ if (isAnimatingStackRef.current || isScrubbingRef.current) {+ return;+ }++ const clickX = event.clientX;+ if (clickX <= viewport.width * EDGE_NAV_TAP_ZONE_RATIO) {+ onPrev();+ } else if (+ clickX >=+ viewport.width * (1 - EDGE_NAV_TAP_ZONE_RATIO)+ ) {+ onNext();+ }+ },+ [onNext, onPrev, viewport.width],+ );++ const laneFrameSize = useMemo(() => {+ const availableWidth = Math.max(+ isCompactLaneLayout+ ? LANE_MOBILE_CARD_MIN_WIDTH_PX+ : LANE_DESKTOP_CARD_MIN_WIDTH_PX,+ viewport.width - (isCompactLaneLayout ? 56 : 96),+ );+ const availableHeight = Math.max(+ 200,+ viewport.height -+ (isCompactLaneLayout+ ? LANE_MOBILE_MEDIA_RESERVED_VERTICAL_SPACE_PX - 24+ : DESKTOP_LANE_MEDIA_VERTICAL_RESERVED_PX),+ );+ const preferredWidth = isCompactLaneLayout+ ? Math.min(LANE_MOBILE_CARD_MAX_WIDTH_PX + 28, availableWidth)+ : Math.min(+ LANE_DESKTOP_CARD_MAX_WIDTH_PX,+ Math.max(+ LANE_DESKTOP_CARD_MIN_WIDTH_PX,+ availableWidth * 0.34,+ ),+ );++ let width = preferredWidth;+ let height = width / LANE_CARD_ASPECT_RATIO;++ if (height > availableHeight) {+ height = availableHeight;+ width = height * LANE_CARD_ASPECT_RATIO;+ }++ return { width: Math.round(width), height: Math.round(height) };+ }, [isCompactLaneLayout, viewport.height, viewport.width]);++ const laneTitle = useMemo(() => {+ return buildLaneTitle({+ memoryName,+ personName: memoryMetadata?.personName,+ });+ }, [memoryMetadata?.personName, memoryName]);++ const laneSlices = useMemo(+ () => getLaneStackSlices(files.length, stackProgress),+ [files.length, stackProgress],+ );++ const trackScrubValue = useCallback(+ (value: number) => {+ if (files.length <= 1) {+ return 0;+ }+ return Math.min(Math.max(value, 0), files.length - 1);+ },+ [files.length],+ );++ const handleScrubStart = useCallback(() => {+ setPaused(true);+ setIsScrubbing(true);+ cancelStackAnimation();+ }, [cancelStackAnimation]);++ const handleScrub = useCallback(+ (value: number) => {+ const clampedValue = trackScrubValue(value);+ const roundedIndex = Math.min(+ Math.max(Math.round(clampedValue), 0),+ files.length - 1,+ );+ setStackProgress(clampedValue);+ if (displayIndexRef.current !== roundedIndex) {+ commitDisplayIndex(roundedIndex);+ }+ onSeek(roundedIndex);+ },+ [commitDisplayIndex, files.length, onSeek, trackScrubValue],+ );++ const handleScrubEnd = useCallback(+ (value: number) => {+ const clampedValue = trackScrubValue(value);+ const roundedIndex = Math.min(+ Math.max(Math.round(clampedValue), 0),+ files.length - 1,+ );+ setIsScrubbing(false);+ setStackProgress(roundedIndex);+ if (displayIndexRef.current !== roundedIndex) {+ commitDisplayIndex(roundedIndex);+ }+ onSeek(roundedIndex);+ },+ [commitDisplayIndex, files.length, onSeek, trackScrubValue],+ );++ return (+ <ViewerRoot onClick={handleScreenTap}>+ <LaneBackground isMobileLayout={isCompactLaneLayout} />+ <LaneContentContainer+ style={+ isCompactLaneLayout+ ? {+ maxWidth: isMobileLayout ? "375px" : "440px",+ padding: isMobileLayout+ ? "24px 24px 26px"+ : "32px 28px 30px",+ gap: isMobileLayout ? "16px" : "20px",+ }+ : undefined+ }+ >+ {isCompactLaneLayout ? (+ <LaneMobileHeaderSection>+ <LaneMobileTitle variant="h6">+ {laneTitle}+ </LaneMobileTitle>+ </LaneMobileHeaderSection>+ ) : (+ <LaneTopBar>+ <LaneDesktopTitle variant="h6">+ {laneTitle}+ </LaneDesktopTitle>+ <LaneTopBrandSection>+ <LaneSharedUsingLabel>+ Shared using+ </LaneSharedUsingLabel>+ <BrandLink+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ data-memory-control="true"+ >+ <EnteBrandTagImage+ src={ENTE_BRAND_TAG_IMAGE_PATH}+ alt="Ente Photos"+ />+ </BrandLink>+ </LaneTopBrandSection>+ </LaneTopBar>+ )}++ <LaneCenterSection>+ <PhotoContainer+ style={{ flex: "0 0 auto", minHeight: "auto" }}+ onContextMenu={(event) => event.preventDefault()}+ onDragStart={(event) => event.preventDefault()}+ onPointerDown={+ isCompactLaneLayout+ ? () => {+ pressStartedAtRef.current = Date.now();+ suppressTapNavigationRef.current = false;+ shouldResumeAfterHoldRef.current =+ !paused;+ setPaused(true);+ }+ : undefined+ }+ onPointerUp={+ isCompactLaneLayout+ ? () => {+ const startedAt =+ pressStartedAtRef.current;+ pressStartedAtRef.current = null;+ if (+ startedAt &&+ Date.now() - startedAt >+ HOLD_TO_PAUSE_NAV_SUPPRESSION_MS+ ) {+ suppressTapNavigationRef.current = true;+ }+ if (shouldResumeAfterHoldRef.current) {+ setPaused(false);+ }+ shouldResumeAfterHoldRef.current = false;+ }+ : undefined+ }+ onPointerCancel={+ isCompactLaneLayout+ ? () => {+ pressStartedAtRef.current = null;+ if (shouldResumeAfterHoldRef.current) {+ setPaused(false);+ }+ shouldResumeAfterHoldRef.current = false;+ }+ : undefined+ }+ onPointerLeave={+ isCompactLaneLayout+ ? () => {+ if (pressStartedAtRef.current !== null) {+ pressStartedAtRef.current = null;+ if (+ shouldResumeAfterHoldRef.current+ ) {+ setPaused(false);+ }+ shouldResumeAfterHoldRef.current = false;+ }+ }+ : undefined+ }+ >+ <LaneCardStack+ style={{+ width: `${laneFrameSize.width}px`,+ height: `${laneFrameSize.height}px`,+ }}+ >+ {laneSlices.map((slice) => {+ const file = files[slice.index]!;+ const frame = laneFrames?.[slice.index];+ const scale = calculateLaneScale(+ slice.distance,+ );+ const yOffset = calculateLaneYOffset(+ slice.distance,+ laneFrameSize.height,+ );+ const opacity = calculateLaneOpacity(+ slice.distance,+ );+ const blurSigma = isScrubbing+ ? 0+ : calculateLaneBlur(slice.distance);+ const rotation =+ (calculateLaneRotation(slice.distance) *+ 180) /+ Math.PI;+ const overlayOpacity =+ calculateLaneOverlayOpacity(slice.distance);+ const cropRect = resolveLaneCropRect(frame);+ const containerAspectRatio =+ laneFrameSize.width / laneFrameSize.height;+ const isDisplayCard =+ slice.index === displayIndex;+ const prefersRichImage =+ file.metadata.fileType === FileType.video+ ? isDisplayCard+ : Math.abs(slice.distance) < 1.1;+ const mediaAspectRatio = isDisplayCard+ ? (activeMediaAspectRatio ??+ getFileAspectRatio(file))+ : getFileAspectRatio(file);++ return (+ <LaneStackSlice+ key={`lane-slice-${slice.index}`}+ style={{+ opacity,+ transform: `translateY(${yOffset}px) rotate(${rotation}deg) scale(${scale})`,+ }}+ >+ <LaneCardSurface+ style={{+ boxShadow: laneCardShadow(+ slice.distance,+ ),+ }}+ >+ <LaneCardMediaLayer+ style={{+ filter:+ blurSigma > 0+ ? `blur(${blurSigma}px)`+ : undefined,+ }}+ >+ {file.metadata.fileType ===+ FileType.video &&+ isDisplayCard ? (+ <VideoPlayer+ file={file}+ paused={paused}+ mediaRef={+ activeVideoElementRef+ }+ fillFrame+ objectFit="cover"+ cropRect={cropRect}+ cropContainerAspectRatio={+ containerAspectRatio+ }+ mediaAspectRatio={+ mediaAspectRatio+ }+ onReady={handleFullLoad}+ onDuration={+ handleVideoDuration+ }+ onEnded={+ handleVideoEnded+ }+ onAspectRatio={+ handleActiveAspectRatio+ }+ />+ ) : (+ <PhotoImage+ file={file}+ fillFrame+ objectFit="cover"+ cropRect={cropRect}+ cropContainerAspectRatio={+ containerAspectRatio+ }+ mediaAspectRatio={+ mediaAspectRatio+ }+ onFullLoad={+ isDisplayCard+ ? handleFullLoad+ : undefined+ }+ onAspectRatio={+ isDisplayCard+ ? handleActiveAspectRatio+ : undefined+ }+ showLoadingOverlay={+ isDisplayCard+ }+ thumbnailOnly={+ !prefersRichImage+ }+ />+ )}+ </LaneCardMediaLayer>+ {overlayOpacity > 0 && (+ <LaneCardOverlayLayer+ style={{+ opacity: overlayOpacity,+ }}+ />+ )}+ </LaneCardSurface>+ </LaneStackSlice>+ );+ })}+ </LaneCardStack>+ </PhotoContainer>++ <LaneBottomSection>+ <LaneCaptionRow>+ <LanePlaybackButton+ type="button"+ data-memory-control="true"+ onClick={handlePlaybackToggle}+ >+ <LanePlaybackGlyph paused={paused} />+ </LanePlaybackButton>+ <LaneCaption>+ <LaneCaptionText+ model={laneCaptionModel}+ previousValue={previousCaptionValue}+ />+ </LaneCaption>+ </LaneCaptionRow>+ <LaneProgressSlider+ total={files.length}+ currentProgress={stackProgress}+ onSeek={onSeek}+ onScrubStart={handleScrubStart}+ onScrub={handleScrub}+ onScrubEnd={handleScrubEnd}+ />+ </LaneBottomSection>+ </LaneCenterSection>+ <LaneFooter>+ {isMobileLayout ? (+ <LaneMobileFooterBar>+ <BrandLink+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ data-memory-control="true"+ >+ <EnteBrandTagImage+ src={ENTE_BRAND_TAG_IMAGE_PATH}+ alt="Ente Photos"+ />+ </BrandLink>+ <MobileJoinNowButton+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ >+ Join now+ </MobileJoinNowButton>+ </LaneMobileFooterBar>+ ) : (+ <JoinNowButton+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ >+ Join now+ </JoinNowButton>+ )}+ </LaneFooter>+ </LaneContentContainer>+ </ViewerRoot>+ );+};++const isInteractiveTapTarget = (target: EventTarget | null) => {+ if (!(target instanceof Element)) return false;+ return Boolean(+ target.closest(+ "button, a, input, textarea, select, [role='button'], [data-memory-control='true']",+ ),+ );+};++const mediaSwitchInAnimation = keyframes`+ from {+ opacity: 0;+ transform: translateY(4px) scale(0.996);+ }+ to {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+`;++const mediaSwitchOutAnimation = keyframes`+ from {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+ to {+ opacity: 0;+ transform: translateY(-2px) scale(1.005);+ }+`;++const laneBackCardPrimaryEnterAnimation = keyframes`+ from {+ opacity: 0;+ transform: translate(26px, -26px) rotate(6.4deg);+ }+ to {+ opacity: 1;+ transform: translate(14px, -16px) rotate(3.1deg);+ }+`;++const laneBackCardSecondaryEnterAnimation = keyframes`+ from {+ opacity: 0;+ transform: translate(16px, -14px) rotate(-4.2deg);+ }+ to {+ opacity: 1;+ transform: translate(6px, -8px) rotate(-1.3deg);+ }+`;++const laneMediaSwitchInAnimation = keyframes`+ from {+ opacity: 0;+ transform: translateY(-22px) scale(0.97);+ }+ to {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+`;++const laneMediaSwitchOutAnimation = keyframes`+ from {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+ to {+ opacity: 0;+ transform: translateY(76px) scale(1.02);+ }+`;++export const MemoryViewer: React.FC<MemoryViewerProps> = ({+ files,+ currentIndex,+ memoryName,+ memoryMetadata,+ laneFrames,+ variant,+ onNext,+ onPrev,+ onSeek,+}) => {+ const currentFile = files[currentIndex]!;+ const currentLaneFrame = laneFrames?.[currentIndex];+ const [paused, setPaused] = useState(false);+ const [fileLoaded, setFileLoaded] = useState(false);+ // For videos, track if duration is known (prevents premature animation start).+ const [videoDurationKnown, setVideoDurationKnown] = useState(false);+ // For videos, we track the duration in ms; for images, use the constant.+ const [progressDuration, setProgressDuration] = useState(+ IMAGE_AUTO_PROGRESS_DURATION_MS,+ );+ const [mediaAspectRatio, setMediaAspectRatio] = useState<number>();+ const [viewport, setViewport] = useState({ width: 1280, height: 720 });+ const [outgoingFile, setOutgoingFile] = useState<EnteFile | null>(null);+ const [outgoingIsVideo, setOutgoingIsVideo] = useState(false);+ const [outgoingIndex, setOutgoingIndex] = useState<number | null>(null);+ const pressStartedAtRef = useRef<number | null>(null);+ const suppressTapNavigationRef = useRef(false);+ const previousFileRef = useRef(currentFile);+ const previousIndexRef = useRef(currentIndex);+ const outgoingClearTimeoutRef = useRef<number | null>(null);++ const isVideo = currentFile.metadata.fileType === FileType.video;+ const isMobileLayout = viewport.width <= MOBILE_LAYOUT_BREAKPOINT_PX;+ const useFooterShareActions =+ viewport.width <= SHARE_FOOTER_ACTIONS_BREAKPOINT_PX;+ const isCompactLaneLayout =+ viewport.width <= LANE_COMPACT_LAYOUT_BREAKPOINT_PX;++ // Reset loaded state and duration when file changes.+ useEffect(() => {+ setPaused(false);+ setFileLoaded(false);+ setVideoDurationKnown(false);+ setMediaAspectRatio(undefined);+ // Reset to image duration; video will update this when it loads.+ setProgressDuration(+ variant === "lane"+ ? LANE_FRAME_INTERVAL_MS+ : IMAGE_AUTO_PROGRESS_DURATION_MS,+ );+ }, [currentIndex, variant]);++ useEffect(() => {+ const previousIndex = previousIndexRef.current;+ const previousFile = previousFileRef.current;+ if (previousIndex !== currentIndex) {+ setOutgoingFile(previousFile);+ setOutgoingIsVideo(+ previousFile.metadata.fileType === FileType.video,+ );+ setOutgoingIndex(previousIndex);++ if (outgoingClearTimeoutRef.current !== null) {+ window.clearTimeout(outgoingClearTimeoutRef.current);+ }+ outgoingClearTimeoutRef.current = window.setTimeout(() => {+ setOutgoingFile(null);+ setOutgoingIndex(null);+ outgoingClearTimeoutRef.current = null;+ }, MEDIA_SWITCH_TRANSITION_DURATION_MS);+ }++ previousIndexRef.current = currentIndex;+ previousFileRef.current = currentFile;+ }, [currentFile, currentIndex]);++ useEffect(+ () => () => {+ if (outgoingClearTimeoutRef.current !== null) {+ window.clearTimeout(outgoingClearTimeoutRef.current);+ }+ },+ [],+ );++ const handleFullLoad = useCallback(() => {+ setFileLoaded(true);+ }, []);++ const handleVideoDuration = useCallback((durationSeconds: number) => {+ // Convert seconds to milliseconds for the progress bar.+ setProgressDuration(durationSeconds * 1000);+ setVideoDurationKnown(true);+ }, []);++ const handleMediaAspectRatio = useCallback(+ (width: number, height: number) => {+ if (width <= 0 || height <= 0) return;+ setMediaAspectRatio(width / height);+ },+ [],+ );++ // Preload next file's thumbnail for smoother navigation.+ useEffect(() => {+ if (currentIndex < files.length - 1) {+ const nextFile = files[currentIndex + 1]!;+ void downloadManager.renderableThumbnailURL(nextFile);+ }+ }, [currentIndex, files]);++ useEffect(() => {+ const updateViewport = () =>+ setViewport({+ width: window.innerWidth,+ height: window.innerHeight,+ });++ updateViewport();+ window.addEventListener("resize", updateViewport);+ return () => window.removeEventListener("resize", updateViewport);+ }, []);++ const currentFileDate = useMemo(() => {+ const frameDate = getFrameCreationDate(currentLaneFrame);+ if (frameDate) {+ return formatMemoryDate(frameDate);+ }+ try {+ return formatMemoryDate(fileCreationPhotoDate(currentFile));+ } catch {+ return "";+ }+ }, [currentFile, currentLaneFrame]);++ const headerTitle = useMemo(() => {+ if (memoryName && currentFileDate)+ return `${memoryName} β’ ${currentFileDate}`;+ return memoryName || currentFileDate || "Memory";+ }, [memoryName, currentFileDate]);++ const handleScreenTap = (e: React.MouseEvent<HTMLDivElement>) => {+ if (suppressTapNavigationRef.current) {+ suppressTapNavigationRef.current = false;+ return;+ }+ if (isInteractiveTapTarget(e.target)) return;++ const screenWidth = viewport.width;+ const clickX = e.clientX;+ if (clickX <= screenWidth * EDGE_NAV_TAP_ZONE_RATIO) {+ onPrev();+ } else if (clickX >= screenWidth * (1 - EDGE_NAV_TAP_ZONE_RATIO)) {+ onNext();+ }+ };++ const resolvedMediaAspectRatio = useMemo(() => {+ if (typeof mediaAspectRatio === "number" && mediaAspectRatio > 0) {+ return mediaAspectRatio;+ }++ const width = currentFile.pubMagicMetadata?.data.w;+ const height = currentFile.pubMagicMetadata?.data.h;+ if (+ typeof width === "number" &&+ width > 0 &&+ typeof height === "number" &&+ height > 0+ ) {+ return width / height;+ }++ return undefined;+ }, [currentFile, mediaAspectRatio]);++ const mobileFrameSize = useMemo(() => {+ const availableWidth = Math.max(220, viewport.width - 48);+ const maxWidth = Math.min(326, availableWidth);+ const maxHeight = Math.max(+ 180,+ viewport.height - MOBILE_MEDIA_RESERVED_VERTICAL_SPACE_PX,+ );+ const ratio = resolvedMediaAspectRatio ?? 4 / 3;++ let width = maxWidth;+ let height = width / ratio;++ if (height > maxHeight) {+ height = maxHeight;+ width = height * ratio;+ }++ return { width: Math.round(width), height: Math.round(height) };+ }, [resolvedMediaAspectRatio, viewport.height, viewport.width]);++ const desktopFrameSize = useMemo(() => {+ const availableWidth = Math.max(+ 360,+ viewport.width - DESKTOP_MEDIA_HORIZONTAL_PADDING_PX,+ );+ const availableHeight = Math.max(+ 240,+ viewport.height - DESKTOP_MEDIA_VERTICAL_RESERVED_PX,+ );+ const maxWidth = Math.min(DESKTOP_MEDIA_MAX_WIDTH_PX, availableWidth);+ const ratio =+ typeof resolvedMediaAspectRatio === "number"+ ? resolvedMediaAspectRatio+ : 4 / 3;++ let width = maxWidth;+ let height = width / ratio;++ if (height > availableHeight) {+ height = availableHeight;+ width = height * ratio;+ }++ return { width: Math.round(width), height: Math.round(height) };+ }, [resolvedMediaAspectRatio, viewport.height, viewport.width]);++ const laneFrameSize = useMemo(() => {+ const availableWidth = Math.max(+ isCompactLaneLayout+ ? LANE_MOBILE_CARD_MIN_WIDTH_PX+ : LANE_DESKTOP_CARD_MIN_WIDTH_PX,+ viewport.width - (isCompactLaneLayout ? 56 : 96),+ );+ const availableHeight = Math.max(+ 200,+ viewport.height -+ (isCompactLaneLayout+ ? LANE_MOBILE_MEDIA_RESERVED_VERTICAL_SPACE_PX - 24+ : DESKTOP_LANE_MEDIA_VERTICAL_RESERVED_PX),+ );+ const preferredWidth = isCompactLaneLayout+ ? Math.min(LANE_MOBILE_CARD_MAX_WIDTH_PX + 28, availableWidth)+ : Math.min(+ LANE_DESKTOP_CARD_MAX_WIDTH_PX,+ Math.max(+ LANE_DESKTOP_CARD_MIN_WIDTH_PX,+ availableWidth * 0.34,+ ),+ );++ let width = preferredWidth;+ let height = width / LANE_CARD_ASPECT_RATIO;++ if (height > availableHeight) {+ height = availableHeight;+ width = height * LANE_CARD_ASPECT_RATIO;+ }++ return { width: Math.round(width), height: Math.round(height) };+ }, [isCompactLaneLayout, viewport.height, viewport.width]);++ const mediaFrameStyle = isMobileLayout+ ? {+ width: `${mobileFrameSize.width}px`,+ aspectRatio: `${resolvedMediaAspectRatio ?? 4 / 3}`,+ }+ : {+ width: `${desktopFrameSize.width}px`,+ aspectRatio: `${resolvedMediaAspectRatio ?? 4 / 3}`,+ };++ const laneMediaFrameStyle = {+ width: `${laneFrameSize.width}px`,+ height: `${laneFrameSize.height}px`,+ };++ const isLaneVariant = variant === "lane";+ const isProgressPaused =+ paused || !fileLoaded || (isVideo && !videoDurationKnown);+ const laneTitle = useMemo(() => {+ return buildLaneTitle({+ memoryName,+ personName: memoryMetadata?.personName,+ });+ }, [memoryMetadata?.personName, memoryName]);+ const laneCaption = useMemo(() => {+ return formatLaneCaption({+ frame: currentLaneFrame,+ metadata: memoryMetadata,+ fallbackLabel: currentFileDate || memoryName || "Memory lane",+ });+ }, [currentFileDate, currentLaneFrame, memoryMetadata, memoryName]);+ const mediaObjectFit: "contain" | "cover" = isLaneVariant+ ? "cover"+ : "contain";+ const laneContainerAspectRatio = laneFrameSize.width / laneFrameSize.height;+ const currentCropRect = isLaneVariant+ ? resolveLaneCropRect(currentLaneFrame)+ : undefined;+ const outgoingLaneFrame =+ outgoingIndex !== null ? laneFrames?.[outgoingIndex] : undefined;+ const outgoingCropRect = isLaneVariant+ ? resolveLaneCropRect(outgoingLaneFrame)+ : undefined;+ const mediaLayers = (+ <>+ <MediaSwitchLayer+ phase="in"+ variant={isLaneVariant ? "lane" : "share"}+ key={`memory-file-${currentIndex}`}+ >+ {isVideo ? (+ <VideoPlayer+ file={currentFile}+ onReady={handleFullLoad}+ onDuration={handleVideoDuration}+ onEnded={onNext}+ paused={paused}+ fillFrame+ objectFit={mediaObjectFit}+ cropRect={currentCropRect}+ cropContainerAspectRatio={laneContainerAspectRatio}+ mediaAspectRatio={resolvedMediaAspectRatio}+ onAspectRatio={handleMediaAspectRatio}+ />+ ) : (+ <PhotoImage+ file={currentFile}+ onFullLoad={handleFullLoad}+ fillFrame+ objectFit={mediaObjectFit}+ cropRect={currentCropRect}+ cropContainerAspectRatio={laneContainerAspectRatio}+ mediaAspectRatio={resolvedMediaAspectRatio}+ onAspectRatio={handleMediaAspectRatio}+ />+ )}+ </MediaSwitchLayer>+ {outgoingFile && (+ <MediaSwitchLayer+ phase="out"+ variant={isLaneVariant ? "lane" : "share"}+ key={`memory-file-out-${outgoingIndex ?? currentIndex}`}+ >+ {outgoingIsVideo ? (+ <VideoPlayer+ file={outgoingFile}+ paused+ fillFrame+ objectFit={mediaObjectFit}+ cropRect={outgoingCropRect}+ cropContainerAspectRatio={laneContainerAspectRatio}+ mediaAspectRatio={getFileAspectRatio(outgoingFile)}+ showLoadingOverlay={false}+ />+ ) : (+ <PhotoImage+ file={outgoingFile}+ fillFrame+ objectFit={mediaObjectFit}+ cropRect={outgoingCropRect}+ cropContainerAspectRatio={laneContainerAspectRatio}+ mediaAspectRatio={getFileAspectRatio(outgoingFile)}+ showLoadingOverlay={false}+ />+ )}+ </MediaSwitchLayer>+ )}+ </>+ );++ if (isLaneVariant) {+ return (+ <ViewerRoot onClick={handleScreenTap}>+ <LaneBackground isMobileLayout={isCompactLaneLayout} />+ <LaneContentContainer+ style={+ isCompactLaneLayout+ ? {+ maxWidth: isMobileLayout ? "375px" : "440px",+ padding: isMobileLayout+ ? "24px 24px 26px"+ : "32px 28px 30px",+ gap: isMobileLayout ? "16px" : "20px",+ }+ : undefined+ }+ >+ {isCompactLaneLayout ? (+ <LaneMobileHeaderSection>+ <LaneMobileTitle variant="h6">+ {laneTitle}+ </LaneMobileTitle>+ </LaneMobileHeaderSection>+ ) : (+ <LaneTopBar>+ <LaneDesktopTitle variant="h6">+ {laneTitle}+ </LaneDesktopTitle>+ <LaneTopBrandSection>+ <LaneSharedUsingLabel>+ Shared using+ </LaneSharedUsingLabel>+ <BrandLink+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ data-memory-control="true"+ >+ <EnteBrandTagImage+ src={ENTE_BRAND_TAG_IMAGE_PATH}+ alt="Ente Photos"+ />+ </BrandLink>+ </LaneTopBrandSection>+ </LaneTopBar>+ )}++ <LaneCenterSection>+ <PhotoContainer+ style={{ flex: "0 0 auto", minHeight: "auto" }}+ onContextMenu={(event) => event.preventDefault()}+ onDragStart={(event) => event.preventDefault()}+ onPointerDown={+ isCompactLaneLayout+ ? () => {+ pressStartedAtRef.current =+ Date.now();+ suppressTapNavigationRef.current = false;+ setPaused(true);+ }+ : undefined+ }+ onPointerUp={+ isCompactLaneLayout+ ? () => {+ const startedAt =+ pressStartedAtRef.current;+ pressStartedAtRef.current = null;+ if (+ startedAt &&+ Date.now() - startedAt >+ HOLD_TO_PAUSE_NAV_SUPPRESSION_MS+ ) {+ suppressTapNavigationRef.current = true;+ }+ setPaused(false);+ }+ : undefined+ }+ onPointerCancel={+ isCompactLaneLayout+ ? () => {+ pressStartedAtRef.current = null;+ setPaused(false);+ }+ : undefined+ }+ onPointerLeave={+ isCompactLaneLayout+ ? () => {+ if (+ pressStartedAtRef.current !== null+ ) {+ pressStartedAtRef.current = null;+ setPaused(false);+ }+ }+ : undefined+ }+ >+ <LaneCardStack style={laneMediaFrameStyle}>+ <LaneBackCardPrimary+ key={`lane-back-primary-${currentIndex}`}+ />+ <LaneBackCardSecondary+ key={`lane-back-secondary-${currentIndex}`}+ />+ <LaneFrontCard>+ <MediaFrame+ style={{+ width: "100%",+ height: "100%",+ maxWidth: "100%",+ maxHeight: "100%",+ borderRadius: isCompactLaneLayout+ ? "18px"+ : "22px",+ }}+ >+ {mediaLayers}+ </MediaFrame>+ </LaneFrontCard>+ </LaneCardStack>+ </PhotoContainer>++ <LaneBottomSection>+ <Box+ sx={{+ position: "absolute",+ width: 1,+ height: 1,+ opacity: 0,+ overflow: "hidden",+ pointerEvents: "none",+ }}+ >+ <ProgressIndicator+ total={files.length}+ current={currentIndex}+ paused={isProgressPaused}+ duration={progressDuration}+ onComplete={onNext}+ isVideo={isVideo}+ />+ </Box>+ <LaneCaptionRow>+ <LanePlaybackButton+ type="button"+ data-memory-control="true"+ onClick={(event) => {+ event.stopPropagation();+ setPaused((state) => !state);+ }}+ >+ <LanePlaybackGlyph paused={paused} />+ </LanePlaybackButton>+ <LaneCaption>{laneCaption}</LaneCaption>+ </LaneCaptionRow>+ <LaneProgressSlider+ total={files.length}+ current={currentIndex}+ onSeek={onSeek}+ />+ </LaneBottomSection>+ </LaneCenterSection>+ <LaneFooter>+ {isCompactLaneLayout ? (+ <LaneMobileFooterBar>+ <BrandLink+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ data-memory-control="true"+ >+ <EnteBrandTagImage+ src={ENTE_BRAND_TAG_IMAGE_PATH}+ alt="Ente Photos"+ />+ </BrandLink>+ <MobileJoinNowButton+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ >+ Join now+ </MobileJoinNowButton>+ </LaneMobileFooterBar>+ ) : (+ <JoinNowButton+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ >+ Join now+ </JoinNowButton>+ )}+ </LaneFooter>+ </LaneContentContainer>+ </ViewerRoot>+ );+ }++ return (+ <ViewerRoot onClick={handleScreenTap}>+ <BackgroundPattern />+ <ContentContainer+ style={+ isMobileLayout+ ? {+ maxWidth: "375px",+ padding: "24px 24px 26px",+ gap: "16px",+ }+ : undefined+ }+ >+ {isMobileLayout ? (+ <MobileHeaderSection>+ <MobileTitle variant="h6">{headerTitle}</MobileTitle>+ <ProgressIndicator+ total={files.length}+ current={currentIndex}+ paused={isProgressPaused}+ duration={progressDuration}+ onComplete={onNext}+ isVideo={isVideo}+ compact+ />+ </MobileHeaderSection>+ ) : (+ <TopControls>+ <PlaybackControl+ type="button"+ onClick={(event) => {+ event.stopPropagation();+ setPaused((state) => !state);+ }}+ aria-label={paused ? "Play" : "Pause"}+ data-memory-control="true"+ >+ <PlaybackGlyph paused={paused} />+ </PlaybackControl>++ <HeaderSection>+ <MemoryTitle variant="h6">+ {headerTitle}+ </MemoryTitle>+ <ProgressIndicator+ total={files.length}+ current={currentIndex}+ paused={isProgressPaused}+ duration={progressDuration}+ onComplete={onNext}+ isVideo={isVideo}+ />+ </HeaderSection>++ {!useFooterShareActions && (+ <TopRightActions>+ <BrandLink+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ data-memory-control="true"+ >+ <EnteBrandTagImage+ src={ENTE_BRAND_TAG_IMAGE_PATH}+ alt="Ente Photos"+ />+ </BrandLink>+ <JoinNowButton+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ >+ Join now+ </JoinNowButton>+ </TopRightActions>+ )}+ </TopControls>+ )}++ <PhotoContainer+ onContextMenu={(event) => event.preventDefault()}+ onDragStart={(event) => event.preventDefault()}+ onPointerDown={+ isMobileLayout+ ? () => {+ pressStartedAtRef.current = Date.now();+ suppressTapNavigationRef.current = false;+ setPaused(true);+ }+ : undefined+ }+ onPointerUp={+ isMobileLayout+ ? () => {+ const startedAt = pressStartedAtRef.current;+ pressStartedAtRef.current = null;+ if (+ startedAt &&+ Date.now() - startedAt >+ HOLD_TO_PAUSE_NAV_SUPPRESSION_MS+ ) {+ suppressTapNavigationRef.current = true;+ }+ setPaused(false);+ }+ : undefined+ }+ onPointerCancel={+ isMobileLayout+ ? () => {+ pressStartedAtRef.current = null;+ setPaused(false);+ }+ : undefined+ }+ onPointerLeave={+ isMobileLayout+ ? () => {+ if (pressStartedAtRef.current !== null) {+ pressStartedAtRef.current = null;+ setPaused(false);+ }+ }+ : undefined+ }+ >+ <MediaFrame style={mediaFrameStyle}>+ {mediaLayers}+ </MediaFrame>+ </PhotoContainer>++ {useFooterShareActions && (+ <MobileBottomBar>+ <BrandLink+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ data-memory-control="true"+ >+ <EnteBrandTagImage+ src={ENTE_BRAND_TAG_IMAGE_PATH}+ alt="Ente Photos"+ />+ </BrandLink>+ <MobileJoinNowButton+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ >+ Join now+ </MobileJoinNowButton>+ </MobileBottomBar>+ )}+ </ContentContainer>+ </ViewerRoot>+ );+};++const ViewerRoot = styled("div")({+ position: "relative",+ width: "100vw",+ minHeight: "100vh",+ height: "100dvh",+ overflow: "hidden",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+});++const BackgroundPattern = styled("div")({+ position: "fixed",+ inset: 0,+ backgroundColor: "#1f1f1f",+ backgroundImage: `url(${DESKTOP_BACKGROUND_IMAGE_PATH})`,+ backgroundRepeat: "no-repeat",+ backgroundSize: "cover",+ backgroundPosition: "center",+ zIndex: 1,+ [`@media (max-width: ${MOBILE_LAYOUT_BREAKPOINT_PX}px)`]: {+ backgroundImage: `url(${MOBILE_BACKGROUND_IMAGE_PATH})`,+ backgroundRepeat: "no-repeat",+ backgroundSize: "cover",+ backgroundPosition: "center",+ },+});++const LaneDesktopBackgroundPattern = styled("div")({+ position: "fixed",+ inset: 0,+ overflow: "hidden",+ backgroundColor: "#000000",+ zIndex: 1,+ pointerEvents: "none",+ "&::before": {+ content: '""',+ position: "absolute",+ inset: 0,+ background: [+ "radial-gradient(ellipse 102% 138% at 50% 60%, rgba(7, 102, 81, 0.36) 0%, rgba(6, 86, 73, 0.28) 32%, rgba(4, 60, 59, 0.17) 54%, rgba(2, 33, 35, 0.08) 76%, transparent 100%)",+ "radial-gradient(ellipse 82% 120% at 50% 60%, rgba(8, 123, 91, 0.5) 0%, rgba(7, 104, 83, 0.38) 30%, rgba(5, 78, 69, 0.24) 52%, rgba(3, 48, 48, 0.11) 74%, transparent 100%)",+ "radial-gradient(ellipse 56% 86% at 50% 60%, rgba(10, 133, 95, 0.24) 0%, rgba(7, 103, 82, 0.14) 42%, transparent 100%)",+ ].join(", "),+ },+ "&::after": {+ content: '""',+ position: "absolute",+ inset: 0,+ background: [+ "linear-gradient(180deg, rgba(0, 0, 0, 0.98) 0%, rgba(0, 0, 0, 0.62) 14%, rgba(0, 0, 0, 0.14) 32%, rgba(0, 0, 0, 0.10) 68%, rgba(0, 0, 0, 0.62) 88%, rgba(0, 0, 0, 0.98) 100%)",+ "radial-gradient(ellipse 62% 30% at 50% 9%, rgba(28, 51, 96, 0.26) 0%, rgba(13, 23, 48, 0.18) 42%, transparent 100%)",+ "radial-gradient(ellipse 124% 132% at 50% 58%, transparent 24%, rgba(0, 0, 0, 0.18) 48%, rgba(0, 0, 0, 0.86) 100%)",+ ].join(", "),+ },+});++const LaneDesktopBackgroundAtmosphere = styled("div")({+ position: "absolute",+ inset: "-6% 0 34%",+ background:+ "repeating-linear-gradient(90deg, rgba(34, 60, 112, 0.12) 0px, rgba(34, 60, 112, 0.12) 20px, transparent 20px, transparent 94px)",+ opacity: 0.11,+ filter: "blur(26px)",+ maskImage:+ "linear-gradient(180deg, rgba(0, 0, 0, 0.98) 0%, rgba(0, 0, 0, 0.86) 18%, rgba(0, 0, 0, 0.30) 50%, transparent 100%)",+});++const LaneDesktopBackgroundGrid = styled("svg")({+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ maskImage:+ "radial-gradient(ellipse 82% 84% at 50% 56%, rgba(0, 0, 0, 0.9) 0%, rgba(0, 0, 0, 0.74) 44%, rgba(0, 0, 0, 0.32) 72%, transparent 100%)",+});++const LaneBackgroundGridFill: React.FC<{+ patternId: string;+ filterId: string;+}> = ({ patternId, filterId }) => (+ <>+ <defs>+ <pattern+ id={patternId}+ width={LANE_GRID_CELL_SIZE_PX}+ height={LANE_GRID_CELL_SIZE_PX}+ patternUnits="userSpaceOnUse"+ >+ <rect+ width={LANE_GRID_CELL_SIZE_PX}+ height="1"+ fill={LANE_GRID_LINE_COLOR}+ fillOpacity={LANE_GRID_LINE_OPACITY}+ />+ <rect+ width="1"+ height={LANE_GRID_CELL_SIZE_PX}+ fill={LANE_GRID_LINE_COLOR}+ fillOpacity={LANE_GRID_LINE_OPACITY}+ />+ </pattern>+ <filter+ id={filterId}+ x="-6%"+ y="-6%"+ width="112%"+ height="112%"+ colorInterpolationFilters="sRGB"+ >+ <feTurbulence+ type="turbulence"+ baseFrequency="0.009"+ numOctaves="3"+ seed="3"+ result="laneGridNoise"+ />+ <feDisplacementMap+ in="SourceGraphic"+ in2="laneGridNoise"+ scale={LANE_GRID_DISPLACEMENT_SCALE}+ xChannelSelector="R"+ yChannelSelector="G"+ />+ </filter>+ </defs>+ <rect+ width="100%"+ height="100%"+ fill={`url(#${patternId})`}+ filter={`url(#${filterId})`}+ />+ </>+);++const LaneDesktopBackgroundGridOverlay = () => (+ <LaneDesktopBackgroundGrid aria-hidden preserveAspectRatio="none">+ <LaneBackgroundGridFill+ patternId="lane-desktop-grid-pattern"+ filterId="lane-desktop-grid-filter"+ />+ </LaneDesktopBackgroundGrid>+);++const LaneMobileBackgroundPattern = styled("div")({+ position: "fixed",+ inset: 0,+ overflow: "hidden",+ backgroundColor: "#000000",+ zIndex: 1,+ pointerEvents: "none",+ "&::before": {+ content: '""',+ position: "absolute",+ inset: 0,+ background: [+ "linear-gradient(180deg, rgba(8, 37, 32, 0.96) 0%, rgba(19, 78, 59, 0.88) 16%, rgba(46, 95, 95, 0.94) 50%, rgba(16, 70, 64, 0.88) 72%, rgba(5, 47, 34, 0.94) 100%)",+ "radial-gradient(ellipse 82% 26% at 50% 16%, rgba(24, 120, 80, 0.42) 0%, rgba(14, 80, 58, 0.24) 46%, transparent 100%)",+ "radial-gradient(ellipse 100% 34% at 50% 54%, rgba(76, 123, 145, 0.38) 0%, rgba(43, 90, 107, 0.22) 42%, transparent 100%)",+ "radial-gradient(ellipse 84% 28% at 50% 86%, rgba(18, 96, 54, 0.34) 0%, rgba(9, 58, 39, 0.18) 46%, transparent 100%)",+ ].join(", "),+ },+ "&::after": {+ content: '""',+ position: "absolute",+ inset: 0,+ background: [+ "linear-gradient(180deg, rgba(0, 0, 0, 0.96) 0%, rgba(0, 0, 0, 0.34) 12%, rgba(0, 0, 0, 0.08) 24%, rgba(0, 0, 0, 0.10) 48%, rgba(0, 0, 0, 0.16) 68%, rgba(0, 0, 0, 0.46) 88%, rgba(0, 0, 0, 0.96) 100%)",+ "linear-gradient(90deg, rgba(0, 0, 0, 0.94) 0%, rgba(0, 0, 0, 0.52) 16%, rgba(0, 0, 0, 0.14) 32%, rgba(0, 0, 0, 0.14) 68%, rgba(0, 0, 0, 0.52) 84%, rgba(0, 0, 0, 0.94) 100%)",+ ].join(", "),+ },+});++const LaneMobileBackgroundGrid = styled("svg")({+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ maskImage:+ "linear-gradient(180deg, rgba(0, 0, 0, 0.96) 0%, rgba(0, 0, 0, 0.78) 10%, rgba(0, 0, 0, 0.42) 24%, rgba(0, 0, 0, 0.30) 52%, rgba(0, 0, 0, 0.52) 76%, rgba(0, 0, 0, 0.92) 100%)",+});++const LaneMobileBackgroundGridOverlay = () => (+ <LaneMobileBackgroundGrid aria-hidden preserveAspectRatio="none">+ <LaneBackgroundGridFill+ patternId="lane-mobile-grid-pattern"+ filterId="lane-mobile-grid-filter"+ />+ </LaneMobileBackgroundGrid>+);++const LaneBackground: React.FC<{ isMobileLayout?: boolean }> = ({+ isMobileLayout = false,+}) =>+ isMobileLayout ? (+ <LaneMobileBackgroundPattern>+ <LaneMobileBackgroundGridOverlay />+ </LaneMobileBackgroundPattern>+ ) : (+ <LaneDesktopBackgroundPattern>+ <LaneDesktopBackgroundAtmosphere />+ <LaneDesktopBackgroundGridOverlay />+ </LaneDesktopBackgroundPattern>+ );++const ContentContainer = styled("div")({+ position: "relative",+ zIndex: 2,+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: "32px",+ width: "100%",+ maxWidth: `${DESKTOP_MEDIA_MAX_WIDTH_PX}px`,+ minHeight: "100vh",+ height: "100dvh",+ padding: "42px 24px 24px",+ boxSizing: "border-box",+});++const LaneContentContainer = styled("div")({+ position: "relative",+ zIndex: 2,+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: "26px",+ width: "100%",+ maxWidth: `${DESKTOP_MEDIA_MAX_WIDTH_PX}px`,+ minHeight: "100vh",+ height: "100dvh",+ padding: "56px 48px 40px",+ boxSizing: "border-box",+ [`@media (max-width: ${MOBILE_LAYOUT_BREAKPOINT_PX}px)`]: {+ padding: "24px 24px 26px",+ },+});++const LaneMobileHeaderSection = styled("div")({+ width: "100%",+ display: "flex",+ alignItems: "center",+ justifyContent: "flex-start",+ minHeight: "40px",+});++const LaneMobileTitle = styled(Typography)({+ color: "white",+ fontWeight: 700,+ fontSize: "16px",+ lineHeight: "17px",+ letterSpacing: 0,+ textAlign: "left",+ maxWidth: "326px",+ whiteSpace: "normal",+ overflowWrap: "anywhere",+});++const LaneTopBar = styled("div")({+ width: "calc(100% + 48px)",+ marginLeft: "-24px",+ marginRight: "-24px",+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ minHeight: "48px",+});++const LaneDesktopTitle = styled(Typography)({+ color: "white",+ fontFamily: "'Inter', sans-serif",+ fontWeight: 500,+ fontSize: "27px",+ lineHeight: "24px",+ letterSpacing: "-1px",+ textAlign: "left",+ whiteSpace: "normal",+ overflowWrap: "anywhere",+ maxWidth: "70%",+ "@media (max-width: 900px)": {+ fontSize: "22px",+ lineHeight: "22px",+ letterSpacing: "0px",+ },+});++const LaneTopBrandSection = styled("div")({+ display: "flex",+ alignItems: "center",+ gap: "12px",+});++const LaneCenterSection = styled("div")({+ width: "100%",+ flex: 1,+ minHeight: 0,+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ gap: "38px",+ "@media (max-width: 900px)": { gap: "28px" },+});++const LaneFooter = styled("div")({+ width: "100%",+ flexShrink: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ paddingBottom: "max(8px, env(safe-area-inset-bottom, 0px))",+});++const LaneSharedUsingLabel = styled("span")({+ color: "rgba(255, 255, 255, 0.53)",+ fontFamily: "var(--font-itim), cursive",+ fontStyle: "normal",+ fontWeight: 400,+ fontSize: "24px",+ lineHeight: "13px",+ textAlign: "center",+ whiteSpace: "nowrap",+});++const LaneCardStack = styled("div")({ position: "relative", flexShrink: 0 });++const LaneStackSlice = styled("div")({+ position: "absolute",+ inset: 0,+ pointerEvents: "none",+ willChange: "transform, opacity",+});++const LaneCardSurface = styled("div")({+ position: "relative",+ width: "100%",+ height: "100%",+ overflow: "hidden",+ borderRadius: "28px",+ border: "3px solid white",+ boxSizing: "border-box",+ backgroundColor: "black",+});++const LaneCardMediaLayer = styled("div")({ position: "absolute", inset: 0 });++const LaneCardOverlayLayer = styled("div")({+ position: "absolute",+ inset: 0,+ backgroundColor: "rgba(0, 0, 0, 1)",+});++const LaneBackCardBase = styled("div")({+ position: "absolute",+ inset: 0,+ borderRadius: "22px",+ border: "4px solid rgba(255, 255, 255, 0.82)",+ backgroundColor: "rgba(255, 255, 255, 0.2)",+});++const LaneBackCardPrimary = styled(LaneBackCardBase)({+ transform: "translate(14px, -16px) rotate(3.1deg)",+ transformOrigin: "center",+ zIndex: 1,+ animation: `${laneBackCardPrimaryEnterAnimation} 320ms cubic-bezier(0.2, 0.8, 0.2, 1)`,+});++const LaneBackCardSecondary = styled(LaneBackCardBase)({+ transform: "translate(6px, -8px) rotate(-1.3deg)",+ transformOrigin: "center",+ zIndex: 2,+ animation: `${laneBackCardSecondaryEnterAnimation} 280ms cubic-bezier(0.2, 0.8, 0.2, 1)`,+});++const LaneFrontCard = styled("div")({+ position: "relative",+ zIndex: 3,+ width: "100%",+ height: "100%",+ borderRadius: "22px",+ border: "4px solid rgba(255, 255, 255, 0.92)",+ overflow: "hidden",+ backgroundColor: "black",+});++const LaneBottomSection = styled("div")({+ position: "relative",+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "flex-end",+ gap: "20px",+ width: "100%",+ paddingBottom: 0,+});++const LaneCaptionRow = styled("div")({+ display: "flex",+ alignItems: "center",+ gap: "10px",+});++const LanePlaybackButton = styled("button")({+ border: 0,+ outline: "none",+ width: "28px",+ height: "28px",+ borderRadius: "999px",+ padding: 0,+ cursor: "pointer",+ backgroundColor: "rgba(255, 255, 255, 0.2)",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ color: "white",+});++const LaneCaption = styled("div")({+ color: "rgba(255, 255, 255, 0.53)",+ fontFamily: "var(--font-itim), cursive",+ fontStyle: "normal",+ fontWeight: 400,+ fontSize: "24px",+ lineHeight: "7.801px",+ textAlign: "center",+ whiteSpace: "normal",+ overflowWrap: "anywhere",+});++const MobileHeaderSection = styled("div")({+ width: "100%",+ display: "flex",+ flexDirection: "column",+ alignItems: "flex-start",+ gap: "12px",+});++const MobileTitle = styled(Typography)({+ color: "white",+ fontWeight: 700,+ fontSize: "16px",+ lineHeight: "17px",+ letterSpacing: 0,+ textAlign: "left",+ maxWidth: "326px",+ whiteSpace: "normal",+ overflowWrap: "anywhere",+});++const TopControls = styled("div")({+ position: "relative",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ minHeight: "64px",+ width: "100%",+ boxSizing: "border-box",+ "@media (max-width: 900px)": { minHeight: "56px" },+});++const HeaderSection = styled("div")({+ width: "min(100%, 448px)",+ minWidth: 0,+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: "24px",+});++const MemoryTitle = styled(Typography)({+ color: "white",+ fontWeight: 700,+ fontSize: "24px",+ lineHeight: 1.25,+ letterSpacing: "0px",+ textAlign: "center",+ whiteSpace: "normal",+ overflowWrap: "anywhere",+ maxWidth: "100%",+ "@media (max-width: 900px)": { fontSize: "20px" },+ "@media (max-width: 700px)": { fontSize: "17px", lineHeight: 1.3 },+});++const PlaybackControl = styled("button")({+ position: "absolute",+ left: 0,+ top: "50%",+ transform: "translateY(-50%)",+ width: "64px",+ height: "64px",+ borderRadius: "19px",+ border: 0,+ cursor: "pointer",+ backgroundColor: "rgba(255, 255, 255, 0.2)",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ color: "white",+ padding: 0,+ transition: "background-color 150ms ease",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.28)" },+ "@media (max-width: 900px)": {+ width: "56px",+ height: "56px",+ borderRadius: "16px",+ },+});++const JoinNowButton = styled("a")({+ backgroundColor: "#08c225",+ color: "white",+ textDecoration: "none",+ borderRadius: "39px",+ padding: "18px 32px",+ fontWeight: 700,+ fontSize: "16px",+ lineHeight: "14px",+ whiteSpace: "nowrap",+ transition: "filter 150ms ease",+ "&:hover": { filter: "brightness(1.08)" },+ "@media (max-width: 900px)": { padding: "14px 24px", fontSize: "14px" },+});++const TopRightActions = styled("div")({+ position: "absolute",+ right: "-72px",+ top: "50%",+ transform: "translateY(-50%)",+ display: "flex",+ alignItems: "center",+ gap: "16px",+ "@media (max-width: 1200px)": { right: "-36px" },+ "@media (max-width: 1000px)": { right: 0 },+ "@media (max-width: 900px)": { gap: "10px" },+});++const BrandLink = styled("a")({+ color: "inherit",+ textDecoration: "none",+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ flexShrink: 0,+});++const EnteBrandTagImage = styled("img")({+ width: "58px",+ height: "42px",+ display: "block",+ userSelect: "none",+});++const MobileBottomBar = styled("div")({+ width: "100%",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ gap: "10px",+ marginTop: "auto",+ paddingBottom: "2px",+});++const LaneMobileFooterBar = styled("div")({+ width: "100%",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ gap: "10px",+ paddingBottom: "2px",+});++const MobileJoinNowButton = styled("a")({+ backgroundColor: "#08c225",+ color: "white",+ textDecoration: "none",+ borderRadius: "33px",+ padding: "16px 28px",+ fontWeight: 700,+ fontSize: "14px",+ lineHeight: "12px",+ whiteSpace: "nowrap",+});++const PhotoContainer = styled("div")({+ position: "relative",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ flex: 1,+ minHeight: 0,+ width: "100%",+ cursor: "pointer",+ userSelect: "none",+ WebkitUserSelect: "none",+ WebkitTouchCallout: "none",+ touchAction: "manipulation",+});++const MediaFrame = styled("div")({+ position: "relative",+ borderRadius: "24px",+ overflow: "hidden",+ isolation: "isolate",+ backgroundColor: "transparent",+ width: "fit-content",+ height: "fit-content",+ maxWidth: DESKTOP_MEDIA_MAX_WIDTH_CSS,+ maxHeight: DESKTOP_MEDIA_MAX_HEIGHT_CSS,+ flexShrink: 0,+ lineHeight: 0,+});++const MediaSwitchLayer = styled("div", {+ shouldForwardProp: (prop) => prop !== "phase" && prop !== "variant",+})<{ phase: "in" | "out"; variant?: "share" | "lane" }>(+ ({ phase, variant = "share" }) => ({+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ zIndex: phase === "out" ? (variant === "lane" ? 3 : 2) : 1,+ animation: (() => {+ if (variant === "lane") {+ return phase === "out"+ ? `${laneMediaSwitchOutAnimation} ${MEDIA_SWITCH_TRANSITION_DURATION_MS}ms cubic-bezier(0.22, 0.9, 0.2, 1) forwards`+ : `${laneMediaSwitchInAnimation} ${MEDIA_SWITCH_TRANSITION_DURATION_MS}ms cubic-bezier(0.22, 0.9, 0.2, 1) both`;+ }+ return phase === "out"+ ? `${mediaSwitchOutAnimation} ${MEDIA_SWITCH_TRANSITION_DURATION_MS}ms cubic-bezier(0.16, 1, 0.3, 1) forwards`+ : `${mediaSwitchInAnimation} ${MEDIA_SWITCH_TRANSITION_DURATION_MS}ms cubic-bezier(0.16, 1, 0.3, 1) both`;+ })(),+ willChange: "opacity, transform",+ pointerEvents: "none",+ }),+);++/**+ * Format a date in the style "12th jan, 2022".+ */+const formatMemoryDate = (date: Date): string => {+ const day = date.getDate();+ const month = date.toLocaleString("en", { month: "short" }).toLowerCase();+ const year = date.getFullYear();+ const ordinal = getOrdinalSuffix(day);+ return `${day}${ordinal} ${month}, ${year}`;+};++const getOrdinalSuffix = (n: number): string => {+ const s = ["th", "st", "nd", "rd"];+ const v = n % 100;+ return s[(v - 20) % 10] || s[v] || s[0]!;+};diff --git a/web/apps/memories/src/hooks/usePublicMemoryPage.ts b/web/apps/memories/src/hooks/usePublicMemoryPage.tsnew file mode 100644index 0000000000..64879fbd6a--- /dev/null+++ b/web/apps/memories/src/hooks/usePublicMemoryPage.ts@@ -0,0 +1,129 @@+import { useCallback, useEffect, useState } from "react";++import { downloadManager } from "ente-gallery/services/download";+import type { EnteFile } from "ente-media/file";+import type {+ PublicMemoryShareFrame,+ PublicMemoryShareMetadata,+} from "ente-new/albums/services/public-memory";+import {+ loadPublicMemoryPage,+ type PublicMemoryViewerVariant,+} from "../services/public-memory-page";++export interface UsePublicMemoryPageResult {+ currentIndex: number;+ errorMessage: string;+ files: EnteFile[] | undefined;+ goToNext: () => void;+ goToPrev: () => void;+ handleSeek: (index: number) => void;+ hideContent: boolean;+ laneFrames: (PublicMemoryShareFrame | undefined)[] | undefined;+ loading: boolean;+ memoryMetadata: PublicMemoryShareMetadata | undefined;+ memoryName: string;+ viewerVariant: PublicMemoryViewerVariant;+}++export const usePublicMemoryPage = (): UsePublicMemoryPageResult => {+ const [memoryName, setMemoryName] = useState<string>("");+ const [files, setFiles] = useState<EnteFile[] | undefined>(undefined);+ const [laneFrames, setLaneFrames] = useState<+ (PublicMemoryShareFrame | undefined)[] | undefined+ >(undefined);+ const [memoryMetadata, setMemoryMetadata] = useState<+ PublicMemoryShareMetadata | undefined+ >(undefined);+ const [viewerVariant, setViewerVariant] =+ useState<PublicMemoryViewerVariant>("share");+ const [errorMessage, setErrorMessage] = useState<string>("");+ const [loading, setLoading] = useState(true);+ const [currentIndex, setCurrentIndex] = useState(0);+ const [hideContent, setHideContent] = useState(false);++ useEffect(() => {+ let cancelled = false;++ const main = async () => {+ const result = await loadPublicMemoryPage(+ new URL(window.location.href),+ );++ if (cancelled) {+ return;+ }++ switch (result.kind) {+ case "redirect":+ setHideContent(true);+ window.location.href = result.redirectURL;+ return;+ case "error":+ setErrorMessage(result.errorMessage);+ setLoading(false);+ return;+ case "loaded":+ downloadManager.setPublicMemoryCredentials({+ accessToken: result.data.accessToken,+ });+ setMemoryMetadata(result.data.memoryMetadata);+ setMemoryName(result.data.memoryName);+ setViewerVariant(result.data.viewerVariant);+ setFiles(result.data.files);+ setLaneFrames(result.data.laneFrames);+ setLoading(false);+ return;+ }+ };++ void main();+ return () => {+ cancelled = true;+ downloadManager.setPublicMemoryCredentials(undefined);+ };+ }, []);++ const goToNext = useCallback(() => {+ if (!files) return;+ setCurrentIndex((prev) => (prev < files.length - 1 ? prev + 1 : prev));+ }, [files]);++ const goToPrev = useCallback(() => {+ setCurrentIndex((prev) => (prev > 0 ? prev - 1 : prev));+ }, []);++ const handleSeek = useCallback(+ (index: number) => {+ if (!files) return;+ const max = files.length - 1;+ const clampedIndex = Math.min(Math.max(index, 0), max);+ setCurrentIndex(clampedIndex);+ },+ [files],+ );++ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === "ArrowRight") goToNext();+ else if (e.key === "ArrowLeft") goToPrev();+ };+ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [goToNext, goToPrev]);++ return {+ currentIndex,+ errorMessage,+ files,+ goToNext,+ goToPrev,+ handleSeek,+ hideContent,+ laneFrames,+ loading,+ memoryMetadata,+ memoryName,+ viewerVariant,+ };+};diff --git a/web/apps/memories/src/pages/_app.tsx b/web/apps/memories/src/pages/_app.tsxindex fe853cc9d6..e12ea93b11 100644--- a/web/apps/memories/src/pages/_app.tsx+++ b/web/apps/memories/src/pages/_app.tsx@@ -1,4 +1,5 @@import "@fontsource-variable/inter";+import "@fontsource/itim";import { CssBaseline } from "@mui/material";import { ThemeProvider } from "@mui/material/styles";import { staticAppTitle } from "ente-base/app";@@ -8,20 +9,24 @@ import { shareTheme } from "ente-base/components/utils/theme";import type { AppProps } from "next/app";import React from "react";+const memoriesAppStyle = { "--font-itim": "'Itim'" } as React.CSSProperties;+const App: React.FC<AppProps> = ({ Component, pageProps }) => {useSetupLogs({ disableDiskLogs: true });return (- <ThemeProvider- theme={shareTheme}- defaultMode="system"- // Avoid persisting a manual override; always follow the system theme.- storageManager={null}- >- <CustomHead title={staticAppTitle} />- <CssBaseline enableColorScheme />- <Component {...pageProps} />- </ThemeProvider>+ <div style={memoriesAppStyle}>+ <ThemeProvider+ theme={shareTheme}+ defaultMode="system"+ // Avoid persisting a manual override; always follow the system theme.+ storageManager={null}+ >+ <CustomHead title={staticAppTitle} />+ <CssBaseline enableColorScheme />+ <Component {...pageProps} />+ </ThemeProvider>+ </div>);};diff --git a/web/apps/memories/src/pages/index.tsx b/web/apps/memories/src/pages/index.tsxindex 1d7ca29f16..2c828436d5 100644--- a/web/apps/memories/src/pages/index.tsx+++ b/web/apps/memories/src/pages/index.tsx@@ -1,74 +1,12 @@-import { keyframes } from "@emotion/react";-import { Box, Typography, styled } from "@mui/material";-import { Stack100vhCenter } from "ente-base/components/containers";-import { EnteLogo } from "ente-base/components/EnteLogo";-import { CustomHead } from "ente-base/components/Head";-import { LoadingIndicator } from "ente-base/components/loaders";-import { toB64 } from "ente-base/crypto";-import { isHTTPErrorWithStatus } from "ente-base/http";-import log from "ente-base/log";+import { LaneMemoryViewer } from "../components/LaneMemoryViewer";+import { MemoryViewer } from "../components/MemoryViewer";import {- downloadManager,- type RenderableSourceURLs,-} from "ente-gallery/services/download";-import { extractCollectionKeyFromShareURL } from "ente-gallery/services/share";-import type { HLSPlaylistData } from "ente-gallery/services/video";-import type { EnteFile } from "ente-media/file";-import { fileCreationPhotoDate } from "ente-media/file-metadata";-import { FileType } from "ente-media/file-type";-import {- decryptMemoryShareName,- getPublicMemoryFiles,- getPublicMemoryInfo,-} from "ente-new/albums/services/public-memory";-import "hls-video-element";-import Head from "next/head";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";--const shortMemorySecretPattern = /^[0-9A-Za-z]{12}$/;--const extractMemoryShareKeyFromURL = async (- url: URL,-): Promise<string | null> => {- const fragment = url.hash.slice(1).trim();- if (!fragment) return null;-- if (shortMemorySecretPattern.test(fragment)) {- const digest = await globalThis.crypto.subtle.digest(- "SHA-256",- new TextEncoder().encode(fragment),- );- return await toB64(new Uint8Array(digest));- }-- return await extractCollectionKeyFromShareURL(url);-};--const extractAccessTokenFromURL = (url: URL): string | null => {- const tokenFromQuery =- url.searchParams.get("t") ?? url.searchParams.get("accessToken");- if (tokenFromQuery) {- return tokenFromQuery;- }-- // Ignore route prefixes and pick the final non-prefix path segment.- // Supports:- // - /<TOKEN>#<SECRET>- // - /memory/<TOKEN>#<SECRET>- // - /memories/<TOKEN>#<SECRET>- const routePrefixes = new Set(["memory", "memories"]);- const pathSegments = url.pathname- .split("/")- .filter((segment) => segment.length > 0);- for (let i = pathSegments.length - 1; i >= 0; i--) {- const segment = pathSegments[i]!;- if (!routePrefixes.has(segment.toLowerCase())) {- return segment;- }- }-- return null;-};+ PublicMemoryEmptyState,+ PublicMemoryErrorState,+ PublicMemoryLoadingState,+ PublicMemoryPageShell,+} from "../components/PublicMemoryPageShell";+import { usePublicMemoryPage } from "../hooks/usePublicMemoryPage";/*** Index page that handles both root redirect and memory share links@@ -82,1478 +20,55 @@ const extractAccessTokenFromURL = (url: URL): string | null => {* - nginx try_files for Docker deployment*/export default function PublicMemoryPage() {- const [memoryName, setMemoryName] = useState<string>("");- const [files, setFiles] = useState<EnteFile[] | undefined>(undefined);- const [errorMessage, setErrorMessage] = useState<string>("");- const [loading, setLoading] = useState(true);- const [currentIndex, setCurrentIndex] = useState(0);- const [hideContent, setHideContent] = useState(false);-- useEffect(() => {- const main = async () => {- try {- const currentURL = new URL(window.location.href);-- const token = extractAccessTokenFromURL(currentURL);-- // Root path β redirect to ente.io/memories (or show landing)- if (!token) {- setHideContent(true);- window.location.href = "https://ente.io/memories";- return;- }- const shareKey = await extractMemoryShareKeyFromURL(currentURL);-- if (!shareKey) {- setErrorMessage("Invalid memory link. Missing secret.");- setLoading(false);- return;- }-- const info = await getPublicMemoryInfo(token);-- if (info.metadataCipher && info.metadataNonce) {- const name = await decryptMemoryShareName(- info.metadataCipher,- info.metadataNonce,- shareKey,- );- setMemoryName(name);- }-- downloadManager.setPublicMemoryCredentials({- accessToken: token,- });-- const enteFiles = await getPublicMemoryFiles(token, shareKey);-- // Preserve the order from the server (matches mobile app's intended order)- setFiles(enteFiles);- } catch (e) {- if (- isHTTPErrorWithStatus(e, 401) ||- isHTTPErrorWithStatus(e, 410)- ) {- setErrorMessage(- "This memory link has expired or is no longer available.",- );- } else if (isHTTPErrorWithStatus(e, 429)) {- setErrorMessage(- "Too many requests. Please try again later.",- );- } else {- log.error("Failed to load public memory share", e);- setErrorMessage(- "Something went wrong. Please try again later.",- );- }- } finally {- setLoading(false);- }- };- void main();- return () => downloadManager.setPublicMemoryCredentials(undefined);- }, []);+ const {+ currentIndex,+ errorMessage,+ files,+ goToNext,+ goToPrev,+ handleSeek,+ hideContent,+ laneFrames,+ loading,+ memoryMetadata,+ memoryName,+ viewerVariant,+ } = usePublicMemoryPage();- const goToNext = useCallback(() => {- if (!files) return;- setCurrentIndex((prev) => (prev < files.length - 1 ? prev + 1 : prev));- }, [files]);-- const goToPrev = useCallback(() => {- setCurrentIndex((prev) => (prev > 0 ? prev - 1 : prev));- }, []);-- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- if (e.key === "ArrowRight") goToNext();- else if (e.key === "ArrowLeft") goToPrev();- };- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [goToNext, goToPrev]);-- // Render custom head for SSRif (hideContent) {- return (- <>- <CustomHead title="Ente Memories" />- <Head>- <meta name="robots" content="noindex, nofollow" />- </Head>- </>- );+ return <PublicMemoryPageShell />;}if (loading) {- return (- <>- <CustomHead title="Ente Memories" />- <Head>- <meta name="robots" content="noindex, nofollow" />- </Head>- <LoadingIndicator />- </>- );+ return <PublicMemoryLoadingState />;}if (errorMessage) {- return (- <>- <CustomHead title="Ente Memories" />- <Head>- <meta name="robots" content="noindex, nofollow" />- </Head>- <Stack100vhCenter>- <Typography sx={{ color: "critical.main" }}>- {errorMessage}- </Typography>- </Stack100vhCenter>- </>- );+ return <PublicMemoryErrorState message={errorMessage} />;}if (!files || files.length === 0) {- return (- <>- <CustomHead title="Ente Memories" />- <Head>- <meta name="robots" content="noindex, nofollow" />- </Head>- <Stack100vhCenter>- <Typography>No photos found in this memory.</Typography>- </Stack100vhCenter>- </>- );- }-- return (- <>- <CustomHead title="Ente Memories" />- <Head>- <meta name="robots" content="noindex, nofollow" />- </Head>- <MemoryViewer- files={files}- currentIndex={currentIndex}- memoryName={memoryName}- onNext={goToNext}- onPrev={goToPrev}- />- </>- );-}--interface MemoryViewerProps {- files: EnteFile[];- currentIndex: number;- memoryName: string;- onNext: () => void;- onPrev: () => void;-}--const IMAGE_AUTO_PROGRESS_DURATION_MS = 5000;-const MOBILE_LAYOUT_BREAKPOINT_PX = 600;-const EDGE_NAV_TAP_ZONE_RATIO = 0.2;-const HOLD_TO_PAUSE_NAV_SUPPRESSION_MS = 250;-const MOBILE_MEDIA_RESERVED_VERTICAL_SPACE_PX = 280;-const DESKTOP_MEDIA_MAX_WIDTH_PX = 1264;-const DESKTOP_MEDIA_HORIZONTAL_PADDING_PX = 48;-const DESKTOP_MEDIA_VERTICAL_RESERVED_PX = 220;-const MEDIA_SWITCH_TRANSITION_DURATION_MS = 380;-const DESKTOP_PROGRESS_MAX_WIDTH_PX = 448;-const MOBILE_PROGRESS_MAX_WIDTH_PX = 326;-const DESKTOP_MEDIA_MAX_WIDTH_CSS = `min(${DESKTOP_MEDIA_MAX_WIDTH_PX}px, calc(100vw - ${DESKTOP_MEDIA_HORIZONTAL_PADDING_PX}px))`;-const DESKTOP_MEDIA_MAX_HEIGHT_CSS = `calc(min(100vh, 100dvh) - ${DESKTOP_MEDIA_VERTICAL_RESERVED_PX}px)`;-const DESKTOP_BACKGROUND_IMAGE_PATH = "/images/desktop-bg.svg";-const MOBILE_BACKGROUND_IMAGE_PATH = "/images/mobile-bg.svg";--const isInteractiveTapTarget = (target: EventTarget | null) => {- if (!(target instanceof Element)) return false;- return Boolean(- target.closest(- "button, a, input, textarea, select, [role='button'], [data-memory-control='true']",- ),- );-};--const progressFillAnimation = keyframes`- from { width: 0%; }- to { width: 100%; }-`;--const mediaSwitchInAnimation = keyframes`- from {- opacity: 0;- transform: translateY(4px) scale(0.996);+ return <PublicMemoryEmptyState />;}- to {- opacity: 1;- transform: translateY(0) scale(1);- }-`;-const mediaSwitchOutAnimation = keyframes`- from {- opacity: 1;- transform: translateY(0) scale(1);- }- to {- opacity: 0;- transform: translateY(-2px) scale(1.005);- }-`;--const MemoryViewer: React.FC<MemoryViewerProps> = ({- files,- currentIndex,- memoryName,- onNext,- onPrev,-}) => {- const currentFile = files[currentIndex]!;- const [paused, setPaused] = useState(false);- const [fileLoaded, setFileLoaded] = useState(false);- // For videos, track if duration is known (prevents premature animation start).- const [videoDurationKnown, setVideoDurationKnown] = useState(false);- // For videos, we track the duration in ms; for images, use the constant.- const [progressDuration, setProgressDuration] = useState(- IMAGE_AUTO_PROGRESS_DURATION_MS,- );- const [mediaAspectRatio, setMediaAspectRatio] = useState<number>();- const [viewport, setViewport] = useState({ width: 1280, height: 720 });- const [outgoingFile, setOutgoingFile] = useState<EnteFile | null>(null);- const [outgoingIsVideo, setOutgoingIsVideo] = useState(false);- const [outgoingIndex, setOutgoingIndex] = useState<number | null>(null);- const pressStartedAtRef = useRef<number | null>(null);- const suppressTapNavigationRef = useRef(false);- const previousFileRef = useRef(currentFile);- const previousIndexRef = useRef(currentIndex);- const outgoingClearTimeoutRef = useRef<number | null>(null);-- const isVideo = currentFile.metadata.fileType === FileType.video;- const isMobileLayout = viewport.width <= MOBILE_LAYOUT_BREAKPOINT_PX;-- // Reset loaded state and duration when file changes.- useEffect(() => {- setPaused(false);- setFileLoaded(false);- setVideoDurationKnown(false);- setMediaAspectRatio(undefined);- // Reset to image duration; video will update this when it loads.- setProgressDuration(IMAGE_AUTO_PROGRESS_DURATION_MS);- }, [currentIndex]);-- useEffect(() => {- const previousIndex = previousIndexRef.current;- const previousFile = previousFileRef.current;- if (previousIndex !== currentIndex) {- setOutgoingFile(previousFile);- setOutgoingIsVideo(- previousFile.metadata.fileType === FileType.video,- );- setOutgoingIndex(previousIndex);-- if (outgoingClearTimeoutRef.current !== null) {- window.clearTimeout(outgoingClearTimeoutRef.current);- }- outgoingClearTimeoutRef.current = window.setTimeout(() => {- setOutgoingFile(null);- setOutgoingIndex(null);- outgoingClearTimeoutRef.current = null;- }, MEDIA_SWITCH_TRANSITION_DURATION_MS);- }-- previousIndexRef.current = currentIndex;- previousFileRef.current = currentFile;- }, [currentFile, currentIndex]);-- useEffect(- () => () => {- if (outgoingClearTimeoutRef.current !== null) {- window.clearTimeout(outgoingClearTimeoutRef.current);- }- },- [],- );-- const handleFullLoad = useCallback(() => {- setFileLoaded(true);- }, []);-- const handleVideoDuration = useCallback((durationSeconds: number) => {- // Convert seconds to milliseconds for the progress bar.- setProgressDuration(durationSeconds * 1000);- setVideoDurationKnown(true);- }, []);-- const handleMediaAspectRatio = useCallback(- (width: number, height: number) => {- if (width <= 0 || height <= 0) return;- setMediaAspectRatio(width / height);- },- [],- );-- // Preload next file's thumbnail for smoother navigation.- useEffect(() => {- if (currentIndex < files.length - 1) {- const nextFile = files[currentIndex + 1]!;- void downloadManager.renderableThumbnailURL(nextFile);- }- }, [currentIndex, files]);-- useEffect(() => {- const updateViewport = () =>- setViewport({- width: window.innerWidth,- height: window.innerHeight,- });-- updateViewport();- window.addEventListener("resize", updateViewport);- return () => window.removeEventListener("resize", updateViewport);- }, []);-- const currentFileDate = useMemo(() => {- try {- return formatMemoryDate(fileCreationPhotoDate(currentFile));- } catch {- return "";- }- }, [currentFile]);-- const headerTitle = useMemo(() => {- if (memoryName && currentFileDate)- return `${memoryName} β’ ${currentFileDate}`;- return memoryName || currentFileDate || "Memory";- }, [memoryName, currentFileDate]);-- const handleScreenTap = (e: React.MouseEvent<HTMLDivElement>) => {- if (suppressTapNavigationRef.current) {- suppressTapNavigationRef.current = false;- return;- }- if (isInteractiveTapTarget(e.target)) return;-- const screenWidth = viewport.width;- const clickX = e.clientX;- if (clickX <= screenWidth * EDGE_NAV_TAP_ZONE_RATIO) {- onPrev();- } else if (clickX >= screenWidth * (1 - EDGE_NAV_TAP_ZONE_RATIO)) {- onNext();- }+ const sharedViewerProps = {+ files,+ currentIndex,+ memoryName,+ memoryMetadata,+ laneFrames,+ onNext: goToNext,+ onPrev: goToPrev,+ onSeek: handleSeek,};- const resolvedMediaAspectRatio = useMemo(() => {- if (typeof mediaAspectRatio === "number" && mediaAspectRatio > 0) {- return mediaAspectRatio;- }-- const width = currentFile.pubMagicMetadata?.data.w;- const height = currentFile.pubMagicMetadata?.data.h;- if (- typeof width === "number" &&- width > 0 &&- typeof height === "number" &&- height > 0- ) {- return width / height;- }-- return undefined;- }, [currentFile, mediaAspectRatio]);-- const mobileFrameSize = useMemo(() => {- const availableWidth = Math.max(220, viewport.width - 48);- const maxWidth = Math.min(326, availableWidth);- const maxHeight = Math.max(- 180,- viewport.height - MOBILE_MEDIA_RESERVED_VERTICAL_SPACE_PX,- );- const ratio = resolvedMediaAspectRatio ?? 4 / 3;-- let width = maxWidth;- let height = width / ratio;-- if (height > maxHeight) {- height = maxHeight;- width = height * ratio;- }-- return { width: Math.round(width), height: Math.round(height) };- }, [resolvedMediaAspectRatio, viewport.height, viewport.width]);-- const desktopFrameSize = useMemo(() => {- const availableWidth = Math.max(- 360,- viewport.width - DESKTOP_MEDIA_HORIZONTAL_PADDING_PX,- );- const availableHeight = Math.max(- 240,- viewport.height - DESKTOP_MEDIA_VERTICAL_RESERVED_PX,- );- const maxWidth = Math.min(DESKTOP_MEDIA_MAX_WIDTH_PX, availableWidth);- const ratio =- typeof resolvedMediaAspectRatio === "number"- ? resolvedMediaAspectRatio- : 4 / 3;-- let width = maxWidth;- let height = width / ratio;-- if (height > availableHeight) {- height = availableHeight;- width = height * ratio;- }-- return { width: Math.round(width), height: Math.round(height) };- }, [resolvedMediaAspectRatio, viewport.height, viewport.width]);-- const mediaFrameStyle = isMobileLayout- ? {- width: `${mobileFrameSize.width}px`,- aspectRatio: `${resolvedMediaAspectRatio ?? 4 / 3}`,- }- : {- width: `${desktopFrameSize.width}px`,- aspectRatio: `${resolvedMediaAspectRatio ?? 4 / 3}`,- };-return (- <ViewerRoot onClick={handleScreenTap}>- <BackgroundPattern />- <ContentContainer- style={- isMobileLayout- ? {- maxWidth: "375px",- padding: "24px 24px 26px",- gap: "16px",- }- : undefined- }- >- {isMobileLayout ? (- <MobileHeaderSection>- <MobileTitle variant="h6">{headerTitle}</MobileTitle>- <ProgressIndicator- total={files.length}- current={currentIndex}- paused={- paused ||- !fileLoaded ||- (isVideo && !videoDurationKnown)- }- duration={progressDuration}- onComplete={onNext}- isVideo={isVideo}- compact- />- </MobileHeaderSection>- ) : (- <TopControls>- <PlaybackControl- type="button"- onClick={(event) => {- event.stopPropagation();- setPaused((state) => !state);- }}- aria-label={paused ? "Play" : "Pause"}- data-memory-control="true"- >- <PlaybackGlyph paused={paused} />- </PlaybackControl>-- <HeaderSection>- <MemoryTitle variant="h6">- {headerTitle}- </MemoryTitle>- <ProgressIndicator- total={files.length}- current={currentIndex}- paused={- paused ||- !fileLoaded ||- (isVideo && !videoDurationKnown)- }- duration={progressDuration}- onComplete={onNext}- isVideo={isVideo}- />- </HeaderSection>-- <TopRightActions>- <BrandLink- href="https://ente.io"- target="_blank"- rel="noreferrer"- data-memory-control="true"- >- <DesktopBrandFigma>- <DesktopBrandWordmark>- <EnteLogo height={16.4} />- </DesktopBrandWordmark>- <DesktopBrandTag>photos</DesktopBrandTag>- </DesktopBrandFigma>- </BrandLink>- <JoinNowButton- href="https://ente.io"- target="_blank"- rel="noreferrer"- >- Join now- </JoinNowButton>- </TopRightActions>- </TopControls>- )}-- <PhotoContainer- onContextMenu={(event) => event.preventDefault()}- onDragStart={(event) => event.preventDefault()}- onPointerDown={- isMobileLayout- ? () => {- pressStartedAtRef.current = Date.now();- suppressTapNavigationRef.current = false;- setPaused(true);- }- : undefined- }- onPointerUp={- isMobileLayout- ? () => {- const startedAt = pressStartedAtRef.current;- pressStartedAtRef.current = null;- if (- startedAt &&- Date.now() - startedAt >- HOLD_TO_PAUSE_NAV_SUPPRESSION_MS- ) {- suppressTapNavigationRef.current = true;- }- setPaused(false);- }- : undefined- }- onPointerCancel={- isMobileLayout- ? () => {- pressStartedAtRef.current = null;- setPaused(false);- }- : undefined- }- onPointerLeave={- isMobileLayout- ? () => {- if (pressStartedAtRef.current !== null) {- pressStartedAtRef.current = null;- setPaused(false);- }- }- : undefined- }- >- <MediaFrame style={mediaFrameStyle}>- <MediaSwitchLayer- phase="in"- key={`memory-file-${currentIndex}`}- >- {isVideo ? (- <VideoPlayer- file={currentFile}- onReady={handleFullLoad}- onDuration={handleVideoDuration}- onEnded={onNext}- paused={paused}- fillFrame- onAspectRatio={handleMediaAspectRatio}- />- ) : (- <PhotoImage- file={currentFile}- onFullLoad={handleFullLoad}- fillFrame- onAspectRatio={handleMediaAspectRatio}- />- )}- </MediaSwitchLayer>- {outgoingFile && (- <MediaSwitchLayer- phase="out"- key={`memory-file-out-${outgoingIndex ?? currentIndex}`}- >- {outgoingIsVideo ? (- <VideoPlayer- file={outgoingFile}- paused- fillFrame- showLoadingOverlay={false}- />- ) : (- <PhotoImage- file={outgoingFile}- fillFrame- showLoadingOverlay={false}- />- )}- </MediaSwitchLayer>- )}- </MediaFrame>- </PhotoContainer>-- {isMobileLayout && (- <MobileBottomBar>- <BrandLink- href="https://ente.io"- target="_blank"- rel="noreferrer"- data-memory-control="true"- >- <DesktopBrandFigma>- <DesktopBrandWordmark>- <EnteLogo height={16.4} />- </DesktopBrandWordmark>- <DesktopBrandTag>photos</DesktopBrandTag>- </DesktopBrandFigma>- </BrandLink>- <MobileJoinNowButton- href="https://ente.io"- target="_blank"- rel="noreferrer"- >- Join now- </MobileJoinNowButton>- </MobileBottomBar>- )}- </ContentContainer>- </ViewerRoot>- );-};--const ViewerRoot = styled("div")({- position: "relative",- width: "100vw",- minHeight: "100vh",- height: "100dvh",- overflow: "hidden",- display: "flex",- alignItems: "center",- justifyContent: "center",-});--const BackgroundPattern = styled("div")({- position: "fixed",- inset: 0,- backgroundColor: "#1f1f1f",- backgroundImage: `url(${DESKTOP_BACKGROUND_IMAGE_PATH})`,- backgroundRepeat: "no-repeat",- backgroundSize: "cover",- backgroundPosition: "center",- zIndex: 1,- [`@media (max-width: ${MOBILE_LAYOUT_BREAKPOINT_PX}px)`]: {- backgroundImage: `url(${MOBILE_BACKGROUND_IMAGE_PATH})`,- backgroundRepeat: "no-repeat",- backgroundSize: "cover",- backgroundPosition: "center",- },-});--const ContentContainer = styled("div")({- position: "relative",- zIndex: 2,- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: "32px",- width: "100%",- maxWidth: `${DESKTOP_MEDIA_MAX_WIDTH_PX}px`,- minHeight: "100vh",- height: "100dvh",- padding: "42px 24px 24px",- boxSizing: "border-box",-});--const MobileHeaderSection = styled("div")({- width: "100%",- display: "flex",- flexDirection: "column",- alignItems: "flex-start",- gap: "12px",-});--const MobileTitle = styled(Typography)({- color: "white",- fontWeight: 700,- fontSize: "16px",- lineHeight: "17px",- letterSpacing: 0,- textAlign: "left",- maxWidth: "326px",- whiteSpace: "normal",- overflowWrap: "anywhere",-});--const TopControls = styled("div")({- position: "relative",- display: "flex",- alignItems: "center",- justifyContent: "center",- minHeight: "64px",- width: "100%",- boxSizing: "border-box",- "@media (max-width: 900px)": { minHeight: "56px" },-});--const HeaderSection = styled("div")({- width: "min(100%, 448px)",- maxWidth: `${DESKTOP_PROGRESS_MAX_WIDTH_PX}px`,- minWidth: 0,- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: "24px",-});--const MemoryTitle = styled(Typography)({- color: "white",- fontWeight: 700,- fontSize: "24px",- lineHeight: 1.25,- letterSpacing: "-0.48px",- textAlign: "center",- whiteSpace: "normal",- overflowWrap: "anywhere",- maxWidth: "100%",- "@media (max-width: 900px)": { fontSize: "20px" },- "@media (max-width: 700px)": { fontSize: "17px", lineHeight: 1.3 },-});--const PlaybackControl = styled("button")({- position: "absolute",- left: 0,- top: "50%",- transform: "translateY(-50%)",- width: "64px",- height: "64px",- borderRadius: "19.2px",- border: 0,- cursor: "pointer",- backgroundColor: "rgba(255, 255, 255, 0.2)",- display: "flex",- alignItems: "center",- justifyContent: "center",- color: "white",- padding: 0,- transition: "background-color 150ms ease",- "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.28)" },- "@media (max-width: 900px)": {- width: "56px",- height: "56px",- borderRadius: "16px",- },-});--const JoinNowButton = styled("a")({- backgroundColor: "#08c225",- color: "white",- textDecoration: "none",- borderRadius: "39.459px",- padding: "18px 32px",- fontWeight: 700,- fontSize: "16px",- lineHeight: "14px",- whiteSpace: "nowrap",- transition: "filter 150ms ease",- "&:hover": { filter: "brightness(1.08)" },- "@media (max-width: 900px)": { padding: "14px 24px", fontSize: "14px" },-});--const TopRightActions = styled("div")({- position: "absolute",- right: "-72px",- top: "50%",- transform: "translateY(-50%)",- display: "flex",- alignItems: "center",- gap: "16px",- "@media (max-width: 1200px)": { right: "-36px" },- "@media (max-width: 1000px)": { right: 0 },- "@media (max-width: 900px)": { gap: "10px" },-});--const BrandLink = styled("a")({- color: "inherit",- textDecoration: "none",- display: "inline-flex",- alignItems: "center",- justifyContent: "center",- flexShrink: 0,-});--const DesktopBrandFigma = styled("div")({- position: "relative",- width: "58px",- height: "42px",- lineHeight: 0,- flexShrink: 0,-});--const DesktopBrandWordmark = styled("div")({- position: "absolute",- top: "0",- left: "0",- color: "white",- transform: "rotate(-4.27deg)",- transformOrigin: "left center",-});--const BrandTagBase = styled("div")({- borderRadius: "999px",- padding: "2px 8px",- fontSize: "9px",- lineHeight: "11px",- fontWeight: 700,- backgroundColor: "#08c225",- color: "white",- whiteSpace: "nowrap",-});--const DesktopBrandTag = styled(BrandTagBase)({- position: "absolute",- right: "0",- top: "14px",- transform: "rotate(-8.52deg)",- transformOrigin: "right top",-});--const MobileBottomBar = styled("div")({- width: "100%",- display: "flex",- alignItems: "center",- justifyContent: "center",- gap: "10px",- marginTop: "auto",- paddingBottom: "2px",-});--const MobileJoinNowButton = styled("a")({- backgroundColor: "#08c225",- color: "white",- textDecoration: "none",- borderRadius: "32.836px",- padding: "15.636px 28.145px",- fontWeight: 700,- fontSize: "14px",- lineHeight: "12px",- whiteSpace: "nowrap",-});--const PlaybackGlyph: React.FC<{ paused: boolean }> = ({ paused }) => {- if (paused) {- return (- <Box- sx={{- width: 0,- height: 0,- borderTop: "10px solid transparent",- borderBottom: "10px solid transparent",- borderLeft: "14px solid white",- ml: "3px",- }}- />- );- }-- return (- <Box sx={{ display: "flex", gap: "6px" }}>- <Box- sx={{- width: "6px",- height: "18px",- borderRadius: "2px",- backgroundColor: "white",- }}- />- <Box- sx={{- width: "6px",- height: "18px",- borderRadius: "2px",- backgroundColor: "white",- }}- />- </Box>- );-};--interface ProgressIndicatorProps {- total: number;- current: number;- paused: boolean;- duration: number;- onComplete: () => void;- /** If true, the progress bar won't auto-advance (video handles its own end). */- isVideo?: boolean;- compact?: boolean;-}--const ProgressIndicator: React.FC<ProgressIndicatorProps> = ({- total,- current,- paused,- duration,- onComplete,- isVideo,- compact,-}) => {- const segments = useMemo(- () => Array.from({ length: total }, (_, i) => i),- [total],- );- const progressGap = total > 15 ? "4px" : "12px";-- return (- <Box- sx={{- display: "flex",- gap: progressGap,- alignItems: "center",- width: "100%",- maxWidth: compact- ? `${MOBILE_PROGRESS_MAX_WIDTH_PX}px`- : `${DESKTOP_PROGRESS_MAX_WIDTH_PX}px`,- minWidth: 0,- height: "4px",- }}- >- {segments.map((i) => (- <ProgressBar- key={- i === current- ? `active-${current}-${duration}`- : `segment-${i}`- }- state={- i < current- ? "past"- : i === current- ? "active"- : "future"- }- paused={paused}- duration={duration}- onComplete={- i === current && !isVideo ? onComplete : undefined- }- />- ))}- </Box>- );-};--interface ProgressBarProps {- state: "past" | "active" | "future";- paused: boolean;- duration: number;- onComplete?: () => void;-}--const ProgressBar: React.FC<ProgressBarProps> = ({- state,- paused,- duration,- onComplete,-}) => {- return (- <Box- sx={{- position: "relative",- flex: 1,- minWidth: 0,- height: "4px",- borderRadius: "14px",- backgroundColor: "rgba(255, 255, 255, 0.45)",- overflow: "hidden",- }}- >- <Box- onAnimationEnd={state === "active" ? onComplete : undefined}- style={- state === "active"- ? { animationPlayState: paused ? "paused" : "running" }- : undefined- }- sx={{- position: "absolute",- top: 0,- left: 0,- height: "100%",- borderRadius: "14px",- backgroundColor: "white",- width:- state === "past"- ? "100%"- : state === "active"- ? "100%"- : "0%",- ...(state === "active" && {- animation: `${progressFillAnimation} ${duration}ms linear forwards`,- }),- ...(state === "past" && { transition: "none" }),- }}- />- </Box>- );-};--const PhotoContainer = styled("div")({- position: "relative",- display: "flex",- alignItems: "center",- justifyContent: "center",- flex: 1,- minHeight: 0,- width: "100%",- cursor: "pointer",- userSelect: "none",- WebkitUserSelect: "none",- WebkitTouchCallout: "none",- touchAction: "manipulation",-});--const MediaFrame = styled("div")({- position: "relative",- borderRadius: "24px",- overflow: "hidden",- isolation: "isolate",- backgroundColor: "transparent",- width: "fit-content",- height: "fit-content",- maxWidth: DESKTOP_MEDIA_MAX_WIDTH_CSS,- maxHeight: DESKTOP_MEDIA_MAX_HEIGHT_CSS,- flexShrink: 0,- lineHeight: 0,-});--const MediaSwitchLayer = styled("div", {- shouldForwardProp: (prop) => prop !== "phase",-})<{ phase: "in" | "out" }>(({ phase }) => ({- position: "absolute",- inset: 0,- width: "100%",- height: "100%",- zIndex: phase === "out" ? 2 : 1,- animation:- phase === "out"- ? `${mediaSwitchOutAnimation} ${MEDIA_SWITCH_TRANSITION_DURATION_MS}ms cubic-bezier(0.16, 1, 0.3, 1) forwards`- : `${mediaSwitchInAnimation} ${MEDIA_SWITCH_TRANSITION_DURATION_MS}ms cubic-bezier(0.16, 1, 0.3, 1) both`,- willChange: "opacity, transform",- pointerEvents: "none",-}));--interface PhotoImageProps {- file: EnteFile;- onFullLoad?: () => void;- fillFrame?: boolean;- onAspectRatio?: (width: number, height: number) => void;- showLoadingOverlay?: boolean;-}--const PhotoImage: React.FC<PhotoImageProps> = ({- file,- onFullLoad,- fillFrame,- onAspectRatio,- showLoadingOverlay = true,-}) => {- const [thumbnailURL, setThumbnailURL] = useState<string | undefined>(- undefined,- );- const [fullImageURL, setFullImageURL] = useState<string | undefined>(- undefined,- );- const [isLoading, setIsLoading] = useState(true);- const onFullLoadRef = useRef(onFullLoad);- const hasSignaledReadyRef = useRef(false);- onFullLoadRef.current = onFullLoad;- const signalReady = useCallback(() => {- if (hasSignaledReadyRef.current) return;- hasSignaledReadyRef.current = true;- onFullLoadRef.current?.();- }, []);-- useEffect(() => {- let cancelled = false;- setIsLoading(true);- setThumbnailURL(undefined);- setFullImageURL(undefined);- hasSignaledReadyRef.current = false;-- const loadThumbnail = async () => {- try {- const thumbnailURL =- await downloadManager.renderableThumbnailURL(file);- if (!cancelled && thumbnailURL) {- setThumbnailURL(thumbnailURL);- } else if (!cancelled) {- setIsLoading(false);- }- } catch (e) {- log.error("Failed to load thumbnail", e);- setIsLoading(false);- }- };-- const loadFullImage = async () => {- try {- const sourceURLs =- await downloadManager.renderableSourceURLs(file);- if (cancelled) return;- if (sourceURLs.type === "image") {- setFullImageURL(sourceURLs.imageURL);- } else {- signalReady();- }- } catch (e) {- log.error("Failed to load full image", e);- if (!cancelled) signalReady();- }- };-- void loadThumbnail();- void loadFullImage();- return () => {- cancelled = true;- };- }, [file, signalReady]);-- const displayURL = fullImageURL ?? thumbnailURL;-- return (- <Box- sx={{- position: "relative",- display: fillFrame ? "block" : "inline-block",- width: fillFrame ? "100%" : "auto",- height: fillFrame ? "100%" : "auto",- overflow: "hidden",- }}- >- {isLoading && showLoadingOverlay && (- <Box- sx={{- position: "absolute",- inset: 0,- display: "flex",- alignItems: "center",- justifyContent: "center",- backgroundColor: "rgba(0, 0, 0, 0.5)",- zIndex: 2,- }}- >- <LoadingIndicator />- </Box>+ <PublicMemoryPageShell>+ {viewerVariant === "lane" ? (+ <LaneMemoryViewer {...sharedViewerProps} />+ ) : (+ <MemoryViewer {...sharedViewerProps} variant={viewerVariant} />)}-- {displayURL && (- <img- src={displayURL}- alt=""- draggable={false}- onLoad={(event) => {- const isFullImageLoad =- !!fullImageURL &&- event.currentTarget.src === fullImageURL;- if (isFullImageLoad) {- onAspectRatio?.(- event.currentTarget.naturalWidth,- event.currentTarget.naturalHeight,- );- }- setIsLoading(false);- if (isFullImageLoad) {- signalReady();- }- }}- style={{- display: "block",- width: fillFrame ? "100%" : "auto",- height: fillFrame ? "100%" : "auto",- maxWidth: fillFrame- ? "100%"- : DESKTOP_MEDIA_MAX_WIDTH_CSS,- maxHeight: fillFrame- ? "100%"- : DESKTOP_MEDIA_MAX_HEIGHT_CSS,- objectFit: "contain",- userSelect: "none",- pointerEvents: "none",- }}- />- )}- </Box>+ </PublicMemoryPageShell>);-};--interface VideoPlayerProps {- file: EnteFile;- onReady?: () => void;- onDuration?: (durationSeconds: number) => void;- onEnded?: () => void;- paused?: boolean;- fillFrame?: boolean;- onAspectRatio?: (width: number, height: number) => void;- showLoadingOverlay?: boolean;}--const VideoPlayer: React.FC<VideoPlayerProps> = ({- file,- onReady,- onDuration,- onEnded,- paused,- fillFrame,- onAspectRatio,- showLoadingOverlay = true,-}) => {- const [hlsData, setHlsData] = useState<HLSPlaylistData | undefined>(- undefined,- );- const [videoURL, setVideoURL] = useState<string | undefined>(undefined);- const [thumbnailURL, setThumbnailURL] = useState<string | undefined>(- undefined,- );- const [isLoading, setIsLoading] = useState(true);- const [error, setError] = useState(false);- const videoRef = useRef<HTMLVideoElement>(null);- const onReadyRef = useRef(onReady);- const onDurationRef = useRef(onDuration);- const onEndedRef = useRef(onEnded);-- onReadyRef.current = onReady;- onDurationRef.current = onDuration;- onEndedRef.current = onEnded;-- useEffect(() => {- let cancelled = false;- setIsLoading(true);- setError(false);- setVideoURL(undefined);- setHlsData(undefined);- setThumbnailURL(undefined);-- const load = async () => {- try {- const thumbURL =- await downloadManager.renderableThumbnailURL(file);- if (!cancelled && thumbURL) {- setThumbnailURL(thumbURL);- }-- const hlsPlaylistData =- await downloadManager.hlsPlaylistDataForPublicMemory(file);- if (- !cancelled &&- typeof hlsPlaylistData === "object" &&- hlsPlaylistData.playlistURL- ) {- setHlsData(hlsPlaylistData);- return;- }-- const sourceURLs: RenderableSourceURLs =- await downloadManager.renderableSourceURLs(file);- if (!cancelled && sourceURLs.type === "video") {- setVideoURL(sourceURLs.videoURL);- } else if (!cancelled) {- setIsLoading(false);- }- } catch (e) {- log.error("Failed to load video", e);- if (!cancelled) {- setError(true);- setIsLoading(false);- }- }- };- void load();- return () => {- cancelled = true;- };- }, [file]);-- useEffect(() => {- const video = videoRef.current;- if (!video || (!videoURL && !hlsData)) return;-- if (paused) {- video.pause();- } else {- video.play().catch(() => {- // Autoplay may be blocked; ignore.- });- }- }, [paused, videoURL, hlsData]);-- const handleLoadedMetadata = useCallback(() => {- const video = videoRef.current;- if (video && !isNaN(video.duration) && video.duration > 0) {- onAspectRatio?.(video.videoWidth, video.videoHeight);- onDurationRef.current?.(video.duration);- }- }, [onAspectRatio]);-- const handleCanPlay = useCallback(() => {- setIsLoading(false);- onReadyRef.current?.();- const video = videoRef.current;- if (video && !paused) {- video.play().catch(() => {- // Autoplay may be blocked.- });- }- }, [paused]);-- const handleEnded = useCallback(() => {- onEndedRef.current?.();- }, []);-- if (error) {- return (- <Box- sx={{- display: "flex",- alignItems: "center",- justifyContent: "center",- width: "100%",- height: "100%",- }}- >- <Typography sx={{ color: "rgba(255,255,255,0.7)" }}>- Unable to play video- </Typography>- </Box>- );- }-- return (- <Box- sx={{- position: "relative",- display: fillFrame ? "block" : "inline-block",- width: fillFrame ? "100%" : "auto",- height: fillFrame ? "100%" : "auto",- overflow: "hidden",- }}- >- {isLoading && showLoadingOverlay && (- <Box- sx={{- position: "absolute",- inset: 0,- display: "flex",- alignItems: "center",- justifyContent: "center",- backgroundColor: "rgba(0, 0, 0, 0.5)",- zIndex: 2,- }}- >- <LoadingIndicator />- </Box>- )}-- {hlsData && (- <hls-video- ref={videoRef as React.RefObject<HTMLVideoElement>}- src={hlsData.playlistURL}- poster={thumbnailURL}- playsInline- onLoadedMetadata={handleLoadedMetadata}- onCanPlay={handleCanPlay}- onEnded={handleEnded}- style={{- display: "block",- width: fillFrame ? "100%" : "auto",- height: fillFrame ? "100%" : "auto",- maxWidth: fillFrame- ? "100%"- : DESKTOP_MEDIA_MAX_WIDTH_CSS,- maxHeight: fillFrame- ? "100%"- : DESKTOP_MEDIA_MAX_HEIGHT_CSS,- objectFit: "contain",- userSelect: "none",- pointerEvents: "none",- }}- />- )}-- {!hlsData && videoURL && (- <video- ref={videoRef}- src={videoURL}- poster={thumbnailURL}- playsInline- muted={false}- onLoadedMetadata={handleLoadedMetadata}- onCanPlay={handleCanPlay}- onEnded={handleEnded}- style={{- display: "block",- width: fillFrame ? "100%" : "auto",- height: fillFrame ? "100%" : "auto",- maxWidth: fillFrame- ? "100%"- : DESKTOP_MEDIA_MAX_WIDTH_CSS,- maxHeight: fillFrame- ? "100%"- : DESKTOP_MEDIA_MAX_HEIGHT_CSS,- objectFit: "contain",- userSelect: "none",- pointerEvents: "none",- }}- />- )}-- {!videoURL && !hlsData && thumbnailURL && (- <img- src={thumbnailURL}- alt=""- style={{- display: "block",- width: fillFrame ? "100%" : "auto",- height: fillFrame ? "100%" : "auto",- maxWidth: fillFrame- ? "100%"- : DESKTOP_MEDIA_MAX_WIDTH_CSS,- maxHeight: fillFrame- ? "100%"- : DESKTOP_MEDIA_MAX_HEIGHT_CSS,- objectFit: "contain",- userSelect: "none",- pointerEvents: "none",- }}- />- )}- </Box>- );-};--/**- * Format a date in the style "12th jan, 2022".- */-const formatMemoryDate = (date: Date): string => {- const day = date.getDate();- const month = date.toLocaleString("en", { month: "short" }).toLowerCase();- const year = date.getFullYear();- const ordinal = getOrdinalSuffix(day);- return `${day}${ordinal} ${month}, ${year}`;-};--const getOrdinalSuffix = (n: number): string => {- const s = ["th", "st", "nd", "rd"];- const v = n % 100;- return s[(v - 20) % 10] || s[v] || s[0]!;-};diff --git a/web/apps/memories/src/services/public-memory-page.ts b/web/apps/memories/src/services/public-memory-page.tsnew file mode 100644index 0000000000..f786af2de6--- /dev/null+++ b/web/apps/memories/src/services/public-memory-page.ts@@ -0,0 +1,123 @@+import { isHTTPErrorWithStatus } from "ente-base/http";+import log from "ente-base/log";+import type { EnteFile } from "ente-media/file";+import {+ decryptMemoryShareMetadata,+ getPublicMemoryFiles,+ getPublicMemoryInfo,+ type PublicMemoryShareFrame,+ type PublicMemoryShareMetadata,+} from "ente-new/albums/services/public-memory";+import { alignLaneFilesWithMetadata } from "../utils/lane";+import {+ extractAccessTokenFromURL,+ extractMemoryShareKeyFromURL,+} from "../utils/public-memory-url";++export type PublicMemoryViewerVariant = "share" | "lane";++export interface LoadedPublicMemoryPageData {+ accessToken: string;+ files: EnteFile[];+ laneFrames?: (PublicMemoryShareFrame | undefined)[];+ memoryMetadata?: PublicMemoryShareMetadata;+ memoryName: string;+ viewerVariant: PublicMemoryViewerVariant;+}++export type LoadPublicMemoryPageResult =+ | { kind: "redirect"; redirectURL: string }+ | { kind: "error"; errorMessage: string }+ | { kind: "loaded"; data: LoadedPublicMemoryPageData };++export const loadPublicMemoryPage = async (+ currentURL: URL,+): Promise<LoadPublicMemoryPageResult> => {+ try {+ const accessToken = extractAccessTokenFromURL(currentURL);++ if (!accessToken) {+ return {+ kind: "redirect",+ redirectURL: "https://ente.io/memories",+ };+ }++ const shareKey = await extractMemoryShareKeyFromURL(currentURL);+ if (!shareKey) {+ return {+ kind: "error",+ errorMessage: "Invalid memory link. Missing secret.",+ };+ }++ const info = await getPublicMemoryInfo(accessToken);++ let memoryMetadata: PublicMemoryShareMetadata | undefined;+ if (info.metadataCipher && info.metadataNonce) {+ memoryMetadata = await decryptMemoryShareMetadata(+ info.metadataCipher,+ info.metadataNonce,+ shareKey,+ );+ }++ const viewerVariant: PublicMemoryViewerVariant =+ info.type === "lane" || memoryMetadata?.kind === "lane"+ ? "lane"+ : "share";++ const publicFiles = await getPublicMemoryFiles(accessToken, shareKey);+ const isLaneShare = viewerVariant === "lane";++ if (isLaneShare && memoryMetadata?.frames.length) {+ const aligned = alignLaneFilesWithMetadata(+ publicFiles,+ memoryMetadata.frames,+ );+ return {+ kind: "loaded",+ data: {+ accessToken,+ files: aligned.files,+ laneFrames: aligned.frames,+ memoryMetadata,+ memoryName: memoryMetadata.name,+ viewerVariant,+ },+ };+ }++ return {+ kind: "loaded",+ data: {+ accessToken,+ files: publicFiles.map(({ file }) => file),+ laneFrames: undefined,+ memoryMetadata,+ memoryName: memoryMetadata?.name ?? "",+ viewerVariant,+ },+ };+ } catch (e) {+ if (isHTTPErrorWithStatus(e, 401) || isHTTPErrorWithStatus(e, 410)) {+ return {+ kind: "error",+ errorMessage:+ "This memory link has expired or is no longer available.",+ };+ }+ if (isHTTPErrorWithStatus(e, 429)) {+ return {+ kind: "error",+ errorMessage: "Too many requests. Please try again later.",+ };+ }++ log.error("Failed to load public memory share", e);+ return {+ kind: "error",+ errorMessage: "Something went wrong. Please try again later.",+ };+ }+};diff --git a/web/apps/memories/src/utils/lane.ts b/web/apps/memories/src/utils/lane.tsnew file mode 100644index 0000000000..486cdf16a5--- /dev/null+++ b/web/apps/memories/src/utils/lane.ts@@ -0,0 +1,387 @@+import type { CSSProperties } from "react";++import type { EnteFile } from "ente-media/file";+import type {+ PublicMemoryFile,+ PublicMemoryShareFrame,+ PublicMemoryShareFrameCrop,+ PublicMemoryShareMetadata,+} from "ente-new/albums/services/public-memory";++const LANE_CROP_REGULAR_PADDING = 0.4;+const LANE_CROP_MINIMUM_PADDING = 0.1;++export interface LaneCaptionModel {+ prefix?: string;+ suffix?: string;+ text: string;+ value?: number;+}++export interface LaneCardSlice {+ index: number;+ distance: number;+}++const sortLaneFrames = (frames: PublicMemoryShareFrame[]) =>+ [...frames].sort((a, b) => {+ const aPosition = a.position ?? Number.MAX_SAFE_INTEGER;+ const bPosition = b.position ?? Number.MAX_SAFE_INTEGER;+ return aPosition - bPosition;+ });++export const alignLaneFilesWithMetadata = (+ publicFiles: PublicMemoryFile[],+ frames: PublicMemoryShareFrame[],+) => {+ const framesByPosition = new Map<number, PublicMemoryShareFrame>();+ for (const frame of sortLaneFrames(frames)) {+ if (+ typeof frame.position === "number" &&+ frame.position >= 0 &&+ !framesByPosition.has(frame.position)+ ) {+ framesByPosition.set(frame.position, frame);+ }+ }++ const orderedFiles: EnteFile[] = [];+ const orderedFrames: (PublicMemoryShareFrame | undefined)[] = [];++ publicFiles.forEach(({ file, position }) => {+ orderedFiles.push(file);+ orderedFrames.push(framesByPosition.get(position));+ });++ return { files: orderedFiles, frames: orderedFrames };+};++const yearsBetween = (start: Date, end: Date) =>+ (end.getTime() - start.getTime()) / (365.25 * 24 * 60 * 60 * 1000);++export const getFileAspectRatio = (file: EnteFile): number | undefined => {+ const width = file.pubMagicMetadata?.data.w;+ const height = file.pubMagicMetadata?.data.h;+ if (+ typeof width === "number" &&+ width > 0 &&+ typeof height === "number" &&+ height > 0+ ) {+ return width / height;+ }+ return undefined;+};++const clampCropRect = (+ crop: PublicMemoryShareFrameCrop,+): PublicMemoryShareFrameCrop => {+ const x = Math.min(Math.max(crop.x, 0), 1);+ const y = Math.min(Math.max(crop.y, 0), 1);+ const width = Math.min(Math.max(crop.width, 0.00001), 1 - x);+ const height = Math.min(Math.max(crop.height, 0.00001), 1 - y);+ return { x, y, width, height };+};++const computePaddedLaneCrop = (+ faceBox: PublicMemoryShareFrameCrop,+): PublicMemoryShareFrameCrop => {+ const normalizedBox = clampCropRect(faceBox);+ const xCrop =+ normalizedBox.x - normalizedBox.width * LANE_CROP_REGULAR_PADDING;+ const xOvershoot = Math.abs(Math.min(0, xCrop)) / normalizedBox.width;+ const widthCrop =+ normalizedBox.width * (1 + 2 * LANE_CROP_REGULAR_PADDING) -+ 2 *+ Math.min(+ xOvershoot,+ LANE_CROP_REGULAR_PADDING - LANE_CROP_MINIMUM_PADDING,+ ) *+ normalizedBox.width;++ const yCrop =+ normalizedBox.y - normalizedBox.height * LANE_CROP_REGULAR_PADDING;+ const yOvershoot = Math.abs(Math.min(0, yCrop)) / normalizedBox.height;+ const heightCrop =+ normalizedBox.height * (1 + 2 * LANE_CROP_REGULAR_PADDING) -+ 2 *+ Math.min(+ yOvershoot,+ LANE_CROP_REGULAR_PADDING - LANE_CROP_MINIMUM_PADDING,+ ) *+ normalizedBox.height;++ return clampCropRect({+ x: xCrop,+ y: yCrop,+ width: widthCrop,+ height: heightCrop,+ });+};++export const resolveLaneCropRect = (+ frame?: PublicMemoryShareFrame,+): PublicMemoryShareFrameCrop | undefined => {+ if (!frame) return undefined;+ if (frame.crop) return clampCropRect(frame.crop);+ if (frame.faceBox) return computePaddedLaneCrop(frame.faceBox);+ return undefined;+};++export const computeMediaCropStyle = ({+ cropRect,+ mediaAspectRatio,+ containerAspectRatio,+}: {+ cropRect?: PublicMemoryShareFrameCrop;+ mediaAspectRatio?: number;+ containerAspectRatio?: number;+}): CSSProperties | undefined => {+ if (+ !cropRect ||+ typeof mediaAspectRatio !== "number" ||+ mediaAspectRatio <= 0 ||+ typeof containerAspectRatio !== "number" ||+ containerAspectRatio <= 0+ ) {+ return undefined;+ }++ const safeCrop = clampCropRect(cropRect);+ const scale = Math.max(+ containerAspectRatio / (safeCrop.width * mediaAspectRatio),+ 1 / safeCrop.height,+ );+ const renderedWidthPercent =+ (scale * mediaAspectRatio * 100) / containerAspectRatio;+ const renderedHeightPercent = scale * 100;+ const centerX = safeCrop.x + safeCrop.width / 2;+ const centerY = safeCrop.y + safeCrop.height / 2;++ return {+ position: "absolute",+ width: `${renderedWidthPercent}%`,+ height: `${renderedHeightPercent}%`,+ maxWidth: "none",+ maxHeight: "none",+ left: `calc(50% - ${centerX * renderedWidthPercent}%)`,+ top: `calc(50% - ${centerY * renderedHeightPercent}%)`,+ objectFit: "fill",+ };+};++export const getFrameCreationDate = (frame?: PublicMemoryShareFrame) => {+ if (typeof frame?.creationTime !== "number") {+ return undefined;+ }+ const date = new Date(frame.creationTime / 1000);+ return Number.isNaN(date.getTime()) ? undefined : date;+};++export const formatLaneCaption = ({+ frame,+ metadata,+ fallbackLabel,+}: {+ frame?: PublicMemoryShareFrame;+ metadata?: PublicMemoryShareMetadata;+ fallbackLabel: string;+}) => {+ const creationDate = getFrameCreationDate(frame);+ if (!creationDate) {+ return fallbackLabel;+ }++ const personName = metadata?.personName?.trim() ?? "";+ const captionType =+ metadata?.captionType ?? (metadata?.birthDate ? "age" : "yearsAgo");+ const roundedValue = (() => {+ if (captionType === "age" && metadata?.birthDate) {+ const birthDate = new Date(metadata.birthDate);+ if (!Number.isNaN(birthDate.getTime())) {+ return Math.max(+ 0,+ Math.round(yearsBetween(birthDate, creationDate)),+ );+ }+ }+ return Math.max(0, Math.round(yearsBetween(creationDate, new Date())));+ })();+ const yearsLabel = `${roundedValue} year${roundedValue === 1 ? "" : "s"}`;++ if (captionType === "age") {+ return personName+ ? `${personName} ${yearsLabel} old`+ : `${yearsLabel} old`;+ }++ return personName ? `${personName} ${yearsLabel} ago` : `${yearsLabel} ago`;+};++export const buildLaneCaptionModel = ({+ frame,+ metadata,+ fallbackLabel,+}: {+ frame?: PublicMemoryShareFrame;+ metadata?: PublicMemoryShareMetadata;+ fallbackLabel: string;+}): LaneCaptionModel => {+ const creationDate = getFrameCreationDate(frame);+ if (!creationDate) {+ return { text: fallbackLabel };+ }++ const personName = metadata?.personName?.trim() ?? "";+ const captionType =+ metadata?.captionType ?? (metadata?.birthDate ? "age" : "yearsAgo");+ const roundedValue = (() => {+ if (captionType === "age" && metadata?.birthDate) {+ const birthDate = new Date(metadata.birthDate);+ if (!Number.isNaN(birthDate.getTime())) {+ return Math.max(+ 0,+ Math.round(yearsBetween(birthDate, creationDate)),+ );+ }+ }+ return Math.max(0, Math.round(yearsBetween(creationDate, new Date())));+ })();+ const prefix = personName ? `${personName} ` : "";+ const suffix =+ captionType === "age"+ ? ` year${roundedValue === 1 ? "" : "s"} old`+ : ` year${roundedValue === 1 ? "" : "s"} ago`;+ return {+ prefix,+ suffix,+ text: `${prefix}${roundedValue}${suffix}`,+ value: roundedValue,+ };+};++export const buildLaneTitle = ({+ memoryName,+ personName,+}: {+ memoryName: string;+ personName?: string;+}) => {+ const trimmedTitle = memoryName.trim();+ const trimmedPersonName = personName?.trim() ?? "";+ const baseTitle = trimmedTitle || "Memory lane";++ if (!trimmedPersonName) {+ if (baseTitle.toLowerCase().includes("memory lane")) {+ return baseTitle;+ }+ return `${baseTitle} memory lane`;+ }++ const possessiveName = trimmedPersonName.endsWith("s")+ ? `${trimmedPersonName}'`+ : `${trimmedPersonName}'s`;+ return `${possessiveName} memory lane`;+};++export const easeInOutCubic = (value: number) =>+ value < 0.5+ ? 4 * value * value * value+ : 1 - Math.pow(-2 * value + 2, 3) / 2;++export const lerp = (start: number, end: number, t: number) =>+ start + (end - start) * t;++export const getLaneStackSlices = (+ frameCount: number,+ stackProgress: number,+): LaneCardSlice[] => {+ const slices: LaneCardSlice[] = [];+ const clampedProgress = Math.min(+ Math.max(stackProgress, 0),+ frameCount - 1,+ );+ const startIndex = Math.max(0, Math.floor(clampedProgress) - 3);+ const endIndex = Math.min(frameCount - 1, Math.ceil(clampedProgress) + 4);++ for (let index = startIndex; index <= endIndex; index++) {+ const distance = index - clampedProgress;+ if (distance < -4.5 || distance > 5.5) {+ continue;+ }+ slices.push({ index, distance });+ }++ const futureSlices = slices+ .filter((slice) => slice.distance >= 0)+ .sort((a, b) => b.distance - a.distance);+ const presentAndPastSlices = slices+ .filter((slice) => slice.distance < 0)+ .sort((a, b) => a.distance - b.distance);++ return [...futureSlices, ...presentAndPastSlices];+};++export const calculateLaneScale = (distance: number) => {+ if (distance >= 0) {+ return Math.max(0.84, 1.0 - distance * 0.05);+ }+ return Math.min(Math.max(1.0 - Math.abs(distance) * 0.02, 0.82), 1.02);+};++export const calculateLaneYOffset = (distance: number, cardHeight: number) => {+ if (distance >= 0) {+ const compression = Math.pow(0.72, distance);+ return -cardHeight * 0.14 * distance * compression;+ }+ const downward = Math.abs(distance);+ const easedComponent = Math.pow(downward, 1.45);+ const travel = downward * (2.8 + 1.8 * downward);+ return cardHeight * (travel + easedComponent * 0.65);+};++export const calculateLaneBlur = (distance: number) => {+ if (distance <= 0) {+ return 0;+ }+ const effective = Math.max(0, distance - 0.15);+ return Math.min(20, (effective + 0.05) * 10);+};++export const calculateLaneRotation = (distance: number) => {+ if (distance <= 0) {+ return 0;+ }+ const clamped = Math.min(Math.max(distance, 0), 3);+ const falloff = Math.max(0.2, 1 - clamped * 0.18);+ return 0.035 * clamped * falloff;+};++export const calculateLaneOpacity = (distance: number) => {+ if (distance >= 0) {+ return Math.max(0.35, 1 - distance * 0.22);+ }+ const drop = Math.abs(distance);+ if (drop <= 0.9) {+ return 1;+ }+ const t = Math.min(Math.max((drop - 0.9) / 0.55, 0), 1);+ return Math.max(0, 1 - t);+};++export const calculateLaneOverlayOpacity = (distance: number) => {+ if (distance <= 0) {+ return 0;+ }+ const normalized = Math.min(Math.max(distance / 3, 0), 1);+ return 0.45 * (1 - Math.pow(1 - normalized, 3));+};++export const laneCardShadow = (distance: number) => {+ const baseOpacity = 0.55;+ if (distance > 0) {+ return `0 26px 38px -6px rgba(0, 0, 0, ${Math.max(0, baseOpacity - distance * 0.12)})`;+ }+ const dampening = Math.max(0.2, 1 - Math.abs(distance) * 0.25);+ return `0 24px 34px -12px rgba(0, 0, 0, ${baseOpacity * dampening})`;+};diff --git a/web/apps/memories/src/utils/public-memory-url.ts b/web/apps/memories/src/utils/public-memory-url.tsnew file mode 100644index 0000000000..94df9fb51a--- /dev/null+++ b/web/apps/memories/src/utils/public-memory-url.ts@@ -0,0 +1,47 @@+import { toB64 } from "ente-base/crypto";+import { extractCollectionKeyFromShareURL } from "ente-gallery/services/share";++const shortMemorySecretPattern = /^[0-9A-Za-z]{12}$/;++export const extractMemoryShareKeyFromURL = async (+ url: URL,+): Promise<string | null> => {+ const fragment = url.hash.slice(1).trim();+ if (!fragment) return null;++ if (shortMemorySecretPattern.test(fragment)) {+ const digest = await globalThis.crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(fragment),+ );+ return await toB64(new Uint8Array(digest));+ }++ return await extractCollectionKeyFromShareURL(url);+};++export const extractAccessTokenFromURL = (url: URL): string | null => {+ const tokenFromQuery =+ url.searchParams.get("t") ?? url.searchParams.get("accessToken");+ if (tokenFromQuery) {+ return tokenFromQuery;+ }++ // Support:+ // - /<TOKEN>#<SECRET>+ // - /memory/<TOKEN>#<SECRET>+ // - /memories/<TOKEN>#<SECRET>+ // while treating bare /memory and /memories as no-token landing routes.+ const routePrefixes = new Set(["memory", "memories"]);+ const pathSegments = url.pathname+ .split("/")+ .filter((segment) => segment.length > 0);+ for (let i = pathSegments.length - 1; i >= 0; i--) {+ const segment = pathSegments[i]!;+ if (!routePrefixes.has(segment.toLowerCase())) {+ return segment;+ }+ }++ return null;+};diff --git a/web/packages/new/albums/services/public-memory.ts b/web/packages/new/albums/services/public-memory.tsindex 264b18cd4e..d218b253d0 100644--- a/web/packages/new/albums/services/public-memory.ts+++ b/web/packages/new/albums/services/public-memory.ts@@ -7,6 +7,7 @@ import {type EnteFile,} from "ente-media/file";import { z } from "zod";+import { gunzip } from "../../photos/utils/gzip";/*** Credentials needed to make public memory share related API requests.@@ -79,6 +80,7 @@ export const getPublicMemoryInfo = async (*/const PublicMemoryShareFile = z.object({file: RemoteEnteFile,+ position: z.number(),encryptedKey: z.string(),keyDecryptionNonce: z.string(),});@@ -87,6 +89,65 @@ const PublicMemoryShareFilesResponse = z.object({files: PublicMemoryShareFile.array(),});+export interface PublicMemoryFile {+ file: EnteFile;+ position: number;+}++export interface PublicMemoryShareFrameCrop {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface PublicMemoryShareFrame {+ fileID: number;+ position?: number;+ faceID?: string;+ faceBox?: PublicMemoryShareFrameCrop;+ crop?: PublicMemoryShareFrameCrop;+ creationTime?: number;+ year?: number;+}++export interface PublicMemoryShareMetadata {+ name: string;+ kind?: "share" | "lane";+ captionType?: "age" | "yearsAgo";+ personID?: string;+ personName?: string;+ birthDate?: string;+ frames: PublicMemoryShareFrame[];+}++const PublicMemoryShareFrameCropSchema = z.object({+ x: z.number(),+ y: z.number(),+ width: z.number(),+ height: z.number(),+});++const PublicMemoryShareFrameSchema = z.object({+ fileID: z.number(),+ position: z.number().optional(),+ faceID: z.string().optional(),+ faceBox: PublicMemoryShareFrameCropSchema.optional(),+ crop: PublicMemoryShareFrameCropSchema.optional(),+ creationTime: z.number().optional(),+ year: z.number().optional(),+});++const PublicMemoryShareMetadataBaseSchema = z.looseObject({+ name: z.string().optional(),+ kind: z.enum(["share", "lane"]).optional(),+ captionType: z.enum(["age", "yearsAgo"]).optional(),+ personID: z.string().optional(),+ personName: z.string().optional(),+ birthDate: z.string().optional(),+ frames: z.array(z.unknown()).optional(),+});+/*** Fetch the files in a public memory share, decrypt them using the provided* share key, and return them as {@link EnteFile}s.@@ -97,46 +158,92 @@ const PublicMemoryShareFilesResponse = z.object({export const getPublicMemoryFiles = async (accessToken: string,shareKey: string,-): Promise<EnteFile[]> => {+): Promise<PublicMemoryFile[]> => {const res = await fetch(await apiURL("/public-memory/files"), {headers: authenticatedPublicMemoryRequestHeaders({ accessToken }),});ensureOk(res);const { files } = PublicMemoryShareFilesResponse.parse(await res.json());- const enteFiles: EnteFile[] = [];- for (const { file, encryptedKey, keyDecryptionNonce } of files) {+ const publicFiles: PublicMemoryFile[] = [];+ for (const { file, position, encryptedKey, keyDecryptionNonce } of files) {// The file's key is re-encrypted to the per-share key.// Override the file's encryptedKey/nonce with the share-level values// so that decryptRemoteFile can decrypt using the shareKey.const remoteFile = { ...file, encryptedKey, keyDecryptionNonce };const decrypted = await decryptRemoteFile(remoteFile, shareKey);- enteFiles.push(decrypted);+ publicFiles.push({ file: decrypted, position });+ }+ return publicFiles.sort((a, b) => a.position - b.position);+};++const decryptMemoryShareMetadataJSON = async (+ metadataCipher: string,+ metadataNonce: string,+ shareKey: string,+): Promise<string> => {+ const metadataBytes = await decryptBoxBytes(+ { encryptedData: metadataCipher, nonce: metadataNonce },+ shareKey,+ );+ let metadataJson: string;+ try {+ metadataJson = new TextDecoder().decode(metadataBytes);+ JSON.parse(metadataJson);+ } catch {+ metadataJson = await gunzip(metadataBytes);}- return enteFiles;+ return metadataJson;};/**- * Decrypt the memory share's metadata and extract the name.+ * Decrypt the memory share's metadata.** The metadata is a JSON object encrypted with the per-share key.- * Currently contains: { "name": "..." }- *- * @param metadataCipher Base64 encrypted metadata JSON.- * @param metadataNonce Base64 nonce for decryption.- * @param shareKey Base64 encoded per-share key.- * @returns The decrypted name string, or empty string if not present.+ * For lane shares, it can include per-frame crop data that the web app can use+ * directly for rendering without recomputing face placement.+ */+export const decryptMemoryShareMetadata = async (+ metadataCipher: string,+ metadataNonce: string,+ shareKey: string,+): Promise<PublicMemoryShareMetadata> => {+ const metadataJson = await decryptMemoryShareMetadataJSON(+ metadataCipher,+ metadataNonce,+ shareKey,+ );+ const metadata = PublicMemoryShareMetadataBaseSchema.parse(+ JSON.parse(metadataJson),+ );+ const frames = (metadata.frames ?? []).flatMap((frame) => {+ const parsed = PublicMemoryShareFrameSchema.safeParse(frame);+ return parsed.success ? [parsed.data] : [];+ });++ return {+ name: metadata.name ?? "",+ kind: metadata.kind,+ captionType: metadata.captionType,+ personID: metadata.personID,+ personName: metadata.personName,+ birthDate: metadata.birthDate,+ frames,+ };+};++/**+ * Decrypt the memory share's metadata and extract the name.*/export const decryptMemoryShareName = async (metadataCipher: string,metadataNonce: string,shareKey: string,): Promise<string> => {- const metadataBytes = await decryptBoxBytes(- { encryptedData: metadataCipher, nonce: metadataNonce },+ const metadata = await decryptMemoryShareMetadata(+ metadataCipher,+ metadataNonce,shareKey,);- const metadataJson = new TextDecoder().decode(metadataBytes);- const metadata = JSON.parse(metadataJson) as { name?: string };- return metadata.name ?? "";+ return metadata.name;};diff --git a/web/yarn.lock b/web/yarn.lockindex fdd5baf593..4c4e8b03dc 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -650,6 +650,11 @@resolved "https://registry.npmjs.org/@fontsource/cormorant-garamond/-/cormorant-garamond-5.2.11.tgz"integrity sha512-5JjpN023lhA5soijgVT0BdRGzmlijm402ppjccMd6h+vRE0mX2lJnE+41UPfnlidrkV9/rCo1mf58WZlHnB0CA==+"@fontsource/itim@^5.2.7":+ version "5.2.7"+ resolved "https://registry.yarnpkg.com/@fontsource/itim/-/itim-5.2.7.tgz#c966f5d12688057821599f8a2b9f6342bb661251"+ integrity sha512-ssx6eGnPXJ1grG1/nWjZWvv0bMvCHOf6L7iRqA00Hz0QGukZjETH6tJV7ps/998YdhHFgCQ8KzsBHwQrsNt7EQ==+"@fontsource/jetbrains-mono@^5.2.7":version "5.2.8"resolved "https://registry.npmjs.org/@fontsource/jetbrains-mono/-/jetbrains-mono-5.2.8.tgz"