π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Prune more public album comments
Manav Rathi5cfb0afc9275
diff --git a/web/apps/albums/src/public-album/download/services/download-manager.ts b/web/apps/albums/src/public-album/download/services/download-manager.tsindex 9fef1005e8..8c14cded58 100644--- a/web/apps/albums/src/public-album/download/services/download-manager.ts+++ b/web/apps/albums/src/public-album/download/services/download-manager.ts@@ -26,12 +26,6 @@ import type { EnteFile } from "ente-media/file";export { NetworkDownloadError, isNetworkDownloadError };export type { FileDownloadOpts, RenderableSourceURLs };-/**- * A class that tracks the state of in-progress downloads and conversions,- * including caching them for subsequent retrieval if appropriate.- *- * External code can use it via its singleton instance, {@link downloadManager}.- */class DownloadManager {private core = createDownloadManager({downloadThumbnail: (file) => this.downloadThumbnail(file),@@ -44,71 +38,41 @@ class DownloadManager {return getPublicAlbumsCredentials();}- /**- * Reset the internal state of the download manager.- */logout() {setPublicAlbumsCredentials(undefined);this.core.logout();}- /**- * Set the credentials that should be used for download files when we're- * running in the context of the public albums app.- */setPublicAlbumsCredentials(credentials: PublicAlbumsCredentials | undefined,) {setPublicAlbumsCredentials(credentials);}- /**- * See: [Note: Tracking active file download progress in the UI]- */fileDownloadProgressSubscribe(onChange: () => void) {return this.core.fileDownloadProgressSubscribe(onChange);}- /**- * See: [Note: Tracking active file download progress in the UI]- */fileDownloadProgressSnapshot() {return this.core.fileDownloadProgressSnapshot();}- /**- * Resolves with an URL that points to the file's thumbnail.- */renderableThumbnailURL(file: EnteFile, cachedOnly = false) {return this.core.renderableThumbnailURL(file, cachedOnly);}- /**- * Returns the thumbnail data for a file, downloading it if needed.- */thumbnailData(file: EnteFile, cachedOnly = false) {return this.core.thumbnailData(file, cachedOnly);}- /**- * Return a URL (and associated metadata) that can be used to show the given- * {@link file} within the app, converting its format (on the fly) if needed- * (if possible).- */renderableSourceURLs(file: EnteFile): Promise<RenderableSourceURLs> {return this.core.renderableSourceURLs(file);}- /**- * Return a blob to the file's contents, downloading it needed.- */fileBlob(file: EnteFile, opts?: FileDownloadOpts) {return this.core.fileBlob(file, opts);}- /**- * Return an stream to the file's contents, downloading it needed.- */fileStream(file: EnteFile, opts?: FileDownloadOpts) {return this.core.fileStream(file, opts);}@@ -120,10 +84,6 @@ class DownloadManager {);}- /**- * Download the full contents of {@link file} using the current public album- * credentials.- */private async downloadFile(file: EnteFile) {return publicAlbums_downloadFile(file,@@ -132,15 +92,8 @@ class DownloadManager {}}-/**- * Singleton instance of {@link DownloadManager}.- */export const downloadManager = new DownloadManager();-/**- * The various publicAlbums_* functions are used for the actual downloads when- * we're running in the context of the the public albums app.- */const publicAlbums_downloadThumbnail = async (file: EnteFile,credentials: PublicAlbumsCredentials,diff --git a/web/apps/albums/src/public-album/download/services/save.ts b/web/apps/albums/src/public-album/download/services/save.tsindex 65c3ce179b..2d425cfb57 100644--- a/web/apps/albums/src/public-album/download/services/save.ts+++ b/web/apps/albums/src/public-album/download/services/save.ts@@ -3,22 +3,6 @@ import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";import { downloadAndSaveFilesWeb } from "ente-gallery/services/save-core";import type { EnteFile } from "ente-media/file";-/**- * Save the given {@link files} to the user's device.- *- * Files are saved to the browser's download destination.- *- * @param files The files to save.- *- * @param title A title to show in the UI notification that indicates the- * progress of the save.- *- * @param onAddSaveGroup A function that can be used to create a save group- * associated with the save. The newly added save group will correspond to a- * notification shown in the UI, and the progress and status of the save can be- * communicated by updating the save group's state using the updater function- * obtained when adding the save group.- */export const downloadAndSaveFiles = (files: EnteFile[],title: string,@@ -31,18 +15,6 @@ export const downloadAndSaveFiles = (onAddSaveGroup,});-/**- * Save all the files of a collection to the user's device.- *- * This is a variant of {@link downloadAndSaveFiles}, except instead of taking a- * list of files to save, this variant is tailored for saving saves all the- * files that belong to a collection. Otherwise, it broadly behaves similarly;- * see that method's documentation for more details.- *- * @param isHiddenCollectionSummary `true` if the collection is associated with- * a "hidden" collection or pseudo-collection in the app. Only relevant when- * running in the context of the photos app, can be `undefined` otherwise.- */export const downloadAndSaveCollectionFiles = async (collectionSummaryName: string,collectionSummaryID: number,diff --git a/web/apps/albums/src/public-album/social/api/public-comment.ts b/web/apps/albums/src/public-album/social/api/public-comment.tsindex 8fbbfde51b..ff5f1aaf2c 100644--- a/web/apps/albums/src/public-album/social/api/public-comment.ts+++ b/web/apps/albums/src/public-album/social/api/public-comment.ts@@ -8,9 +8,6 @@ import { apiURL } from "ente-base/origins";import { z } from "zod";import { type AnonIdentity, getStoredAnonIdentity } from "./public-reaction";-/**- * A decrypted public comment.- */export interface PublicComment {id: string;collectionID: number;@@ -18,25 +15,12 @@ export interface PublicComment {parentCommentID?: string;userID: number;anonUserID?: string;- /** The decrypted comment text. */text: string;isDeleted: boolean;createdAt: number;updatedAt: number;}-/**- * Add a comment to a file in a public album (as an anonymous user).- *- * @param credentials Public album credentials (access token).- * @param collectionID The collection ID for looking up stored identity.- * @param fileID The ID of the file to comment on.- * @param text The comment text.- * @param collectionKey The decrypted collection key (base64 encoded).- * @param parentCommentID Optional parent comment ID for replies.- * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.- * @returns The ID of the created comment.- */export const addPublicComment = async (credentials: PublicAlbumsCredentials,collectionID: number,@@ -76,14 +60,6 @@ export const addPublicComment = async (return id;};-/**- * Delete a comment from a public album (as an anonymous user).- *- * @param credentials Public album credentials (access token).- * @param collectionID The collection ID for looking up stored identity.- * @param commentID The ID of the comment to delete.- * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.- */export const deletePublicComment = async (credentials: PublicAlbumsCredentials,collectionID: number,@@ -112,14 +88,6 @@ export const deletePublicComment = async (ensureOk(res);};-/**- * Get comments for a file in a public album.- *- * @param credentials Public album credentials (access token).- * @param fileID The ID of the file to get comments for.- * @param collectionKey The decrypted collection key (base64 encoded).- * @returns Array of decrypted comments for the file.- */export const getPublicFileComments = async (credentials: PublicAlbumsCredentials,fileID: number,@@ -138,7 +106,6 @@ export const getPublicFileComments = async (const decryptedComments: PublicComment[] = [];for (const comment of comments) {- // Include deleted comments with empty textif (comment.isDeleted || !comment.cipher || !comment.nonce) {decryptedComments.push({id: comment.id,diff --git a/web/apps/albums/src/public-album/social/api/public-reaction.ts b/web/apps/albums/src/public-album/social/api/public-reaction.tsindex 3eaffec009..289619bda1 100644--- a/web/apps/albums/src/public-album/social/api/public-reaction.ts+++ b/web/apps/albums/src/public-album/social/api/public-reaction.ts@@ -7,55 +7,27 @@ import {import { apiURL } from "ente-base/origins";import { z } from "zod";-/**- * Fixed length for padded reaction types.- * All reactions are padded to this length before encryption to prevent- * length-based analysis of the ciphertext.- * Max emoji name is ~70 chars, so 100 provides a safe buffer.- */+// Fixed-size plaintext prevents ciphertext length from revealing the reaction.+// The longest reaction name is about 70 characters.const paddedReactionLength = 100;-/**- * Pad a reaction type to a fixed length using null bytes.- */const padReaction = (reactionType: string): string =>reactionType.padEnd(paddedReactionLength, "\0");-/**- * Remove null byte padding from a decrypted reaction type.- */const unpadReaction = (paddedReaction: string): string =>paddedReaction.replace(/\0+$/, "");-/**- * Anonymous user identity returned when creating an anon identity.- */export interface AnonIdentity {anonUserID: string;token: string;expiresAt: number;}-/**- * Storage key prefix for anonymous identity in local storage.- * The full key is `${prefix}_${collectionID}`.- */const ANON_IDENTITY_STORAGE_KEY_PREFIX = "ente_anon_identity";-/**- * Get the storage key for a specific collection's anonymous identity.- */const getStorageKey = (collectionID: number): string =>`${ANON_IDENTITY_STORAGE_KEY_PREFIX}_${collectionID}`;-/**- * Get the stored anonymous identity for a specific collection from local storage.- *- * Returns undefined if no identity is stored or if the stored identity has expired.- * Expired identities are automatically cleared from storage.- *- * @param collectionID The collection ID to get the identity for.- */export const getStoredAnonIdentity = (collectionID: number,): AnonIdentity | undefined => {@@ -64,11 +36,9 @@ export const getStoredAnonIdentity = (if (!stored) return undefined;try {const identity = JSON.parse(stored) as AnonIdentity;- // Check if the identity has expired.- // Server returns expiresAt in microseconds, Date.now() returns milliseconds.+ // expiresAt is in microseconds.const nowMicroseconds = Date.now() * 1000;if (identity.expiresAt && nowMicroseconds > identity.expiresAt) {- // Clear expired identity so user can create a fresh oneclearAnonIdentity(collectionID);return undefined;}@@ -78,12 +48,6 @@ export const getStoredAnonIdentity = (}};-/**- * Store the anonymous identity for a specific collection in local storage.- *- * @param collectionID The collection ID to store the identity for.- * @param identity The anonymous identity to store.- */export const storeAnonIdentity = (collectionID: number,identity: AnonIdentity,@@ -92,36 +56,17 @@ export const storeAnonIdentity = (localStorage.setItem(getStorageKey(collectionID), JSON.stringify(identity));};-/**- * Clear the stored anonymous identity for a specific collection from local storage.- *- * @param collectionID The collection ID to clear the identity for.- */export const clearAnonIdentity = (collectionID: number): void => {if (typeof window === "undefined") return;localStorage.removeItem(getStorageKey(collectionID));};-/**- * Create an anonymous identity for a public album.- *- * The server will return a unique anonymous user ID and a token that can be- * used to authenticate future requests (reactions, comments) from this- * anonymous user.- *- * @param credentials Public album credentials (access token).- * @param collectionID The collection ID this identity is for.- * @param userName The name entered by the user.- * @param collectionKey The decrypted collection key (base64 encoded).- * @returns The anonymous identity containing anonUserID and token.- */export const createAnonIdentity = async (credentials: PublicAlbumsCredentials,collectionID: number,userName: string,collectionKey: string,): Promise<AnonIdentity> => {- // Encrypt the user name using the collection keyconst { encryptedData: cipher, nonce } = await encryptBox(new TextEncoder().encode(userName),collectionKey,@@ -138,7 +83,6 @@ export const createAnonIdentity = async (ensureOk(res);const identity = AnonIdentityResponse.parse(await res.json());- // Store the identity for this collectionstoreAnonIdentity(collectionID, identity);return identity;@@ -150,17 +94,6 @@ const AnonIdentityResponse = z.object({expiresAt: z.number(),});-/**- * Add a reaction to a file in a public album (as an anonymous user).- *- * @param credentials Public album credentials (access token).- * @param collectionID The collection ID for looking up stored identity.- * @param fileID The ID of the file to react to.- * @param reactionType The type of reaction (e.g., "green_heart").- * @param collectionKey The decrypted collection key (base64 encoded).- * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.- * @returns The ID of the created reaction.- */export const addPublicReaction = async (credentials: PublicAlbumsCredentials,collectionID: number,@@ -198,18 +131,6 @@ export const addPublicReaction = async (return id;};-/**- * Add a reaction to a comment in a public album (as an anonymous user).- *- * @param credentials Public album credentials (access token).- * @param collectionID The collection ID for looking up stored identity.- * @param commentID The ID of the comment to react to.- * @param reactionType The type of reaction (e.g., "green_heart").- * @param collectionKey The decrypted collection key (base64 encoded).- * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.- * @param fileID Optional file ID, required for file-scoped comments.- * @returns The ID of the created reaction.- */export const addPublicCommentReaction = async (credentials: PublicAlbumsCredentials,collectionID: number,@@ -249,14 +170,6 @@ export const addPublicCommentReaction = async (return id;};-/**- * Delete a reaction from a public album (as an anonymous user).- *- * @param credentials Public album credentials (access token).- * @param collectionID The collection ID for looking up stored identity.- * @param reactionID The ID of the reaction to delete.- * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.- */export const deletePublicReaction = async (credentials: PublicAlbumsCredentials,collectionID: number,@@ -287,9 +200,6 @@ export const deletePublicReaction = async (const UpsertReactionResponse = z.object({ id: z.string() });-/**- * A decrypted public reaction.- */export interface PublicReaction {id: string;fileID: number;@@ -302,14 +212,6 @@ export interface PublicReaction {updatedAt: number;}-/**- * Get reactions for a file in a public album.- *- * @param credentials Public album credentials (access token).- * @param fileID The ID of the file to get reactions for.- * @param collectionKey The decrypted collection key (base64 encoded).- * @returns Array of decrypted reactions for the file.- */export const getPublicFileReactions = async (credentials: PublicAlbumsCredentials,fileID: number,@@ -328,7 +230,6 @@ export const getPublicFileReactions = async (const decryptedReactions: PublicReaction[] = [];for (const reaction of reactions) {- // Skip deleted reactions (they have null cipher/nonce)if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;try {const decryptedB64 = await decryptBox(@@ -377,21 +278,11 @@ const GetPublicReactionsResponse = z.object({hasMore: z.boolean(),});-/**- * An anonymous user profile (encrypted).- */export interface AnonProfile {anonUserID: string;userName: string;}-/**- * Get anonymous user profiles for a public album.- *- * @param credentials Public album credentials (access token).- * @param collectionKey The decrypted collection key (base64 encoded).- * @returns Map of anonUserID to decrypted userName.- */export const getPublicAnonProfiles = async (credentials: PublicAlbumsCredentials,collectionKey: string,@@ -439,23 +330,11 @@ const GetAnonProfilesResponse = z.object({.transform((v) => v ?? []),});-/**- * A participant with masked email.- */export interface Participant {userID: number;emailMasked: string;}-/**- * Get registered participants' masked emails for a public album.- *- * This returns masked emails for registered users (album owner/collaborators)- * who have interacted with the album (comments/reactions).- *- * @param credentials Public album credentials (access token).- * @returns Map of userID to masked email.- */export const getPublicParticipantsMaskedEmails = async (credentials: PublicAlbumsCredentials,): Promise<Map<number, string>> => {@@ -482,13 +361,6 @@ const GetParticipantsResponse = z.object({participants: z.array(RemoteParticipant),});-// =============================================================================-// Unified Social Diff-// =============================================================================--/**- * A decrypted public comment.- */export interface PublicComment {id: string;collectionID: number;@@ -502,22 +374,11 @@ export interface PublicComment {updatedAt: number;}-/**- * Result of fetching unified social diff.- */export interface PublicSocialDiff {comments: PublicComment[];reactions: PublicReaction[];}-/**- * Get both comments and reactions for a file in a public album in a single API call.- *- * @param credentials Public album credentials (access token).- * @param fileID The ID of the file to get social data for.- * @param collectionKey The decrypted collection key (base64 encoded).- * @returns Object containing both decrypted comments and reactions.- */export const getPublicSocialDiff = async (credentials: PublicAlbumsCredentials,fileID: number,@@ -534,10 +395,8 @@ export const getPublicSocialDiff = async (ensureOk(res);const data = GetPublicSocialDiffResponse.parse(await res.json());- // Decrypt commentsconst comments: PublicComment[] = [];for (const comment of data.comments) {- // Include deleted comments with empty textif (comment.isDeleted || !comment.cipher || !comment.nonce) {comments.push({id: comment.id,@@ -578,10 +437,8 @@ export const getPublicSocialDiff = async (}}- // Decrypt reactionsconst reactions: PublicReaction[] = [];for (const reaction of data.reactions) {- // Skip deleted reactions (they have null cipher/nonce)if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;try {const decryptedB64 = await decryptBox(@@ -633,49 +490,23 @@ const GetPublicSocialDiffResponse = z.object({hasMoreReactions: z.boolean(),});-// =============================================================================-// Public Album Feed-// =============================================================================--/**- * A public comment extended with isReply flag for feed processing.- */export interface PublicFeedComment extends PublicComment {- /** True if this comment is a reply to another comment. */isReply: boolean;}-/**- * A public reaction extended with isCommentReply flag for feed processing.- */export interface PublicFeedReaction extends PublicReaction {- /** True if this reaction is on a reply (comment with parent). */isCommentReply?: boolean;}-/**- * Result of fetching all social data for a public album feed.- */export interface PublicAlbumFeed {comments: PublicFeedComment[];reactions: PublicFeedReaction[];}-/**- * Get all comments and reactions for a public album (for the feed).- *- * Unlike getPublicSocialDiff which is per-file, this fetches ALL social data- * for the entire album without filtering by file.- *- * @param credentials Public album credentials (access token).- * @param collectionKey The decrypted collection key (base64 encoded).- * @returns Object containing all decrypted comments and reactions for the album.- */export const getPublicAlbumFeed = async (credentials: PublicAlbumsCredentials,collectionKey: string,): Promise<PublicAlbumFeed> => {- // Fetch all social data without fileID filterconst res = await fetch(await apiURL("/public-collection/social/diff", {sinceTime: 0,@@ -686,16 +517,13 @@ export const getPublicAlbumFeed = async (ensureOk(res);const data = GetPublicSocialDiffResponse.parse(await res.json());- // Build a map of comment IDs to their parent status for determining isCommentReplyconst commentParentMap = new Map<string, boolean>();- // Decrypt commentsconst comments: PublicFeedComment[] = [];for (const comment of data.comments) {const isReply = !!comment.parentCommentID;commentParentMap.set(comment.id, isReply);- // Include deleted comments with empty textif (comment.isDeleted || !comment.cipher || !comment.nonce) {comments.push({id: comment.id,@@ -738,10 +566,8 @@ export const getPublicAlbumFeed = async (}}- // Decrypt reactionsconst reactions: PublicFeedReaction[] = [];for (const reaction of data.reactions) {- // Skip deleted reactions (they have null cipher/nonce)if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;try {const decryptedB64 = await decryptBox(@@ -754,7 +580,6 @@ export const getPublicAlbumFeed = async (),);- // Determine if this reaction is on a reply by checking the comment's parent statuslet isCommentReply: boolean | undefined;if (reaction.commentID) {isCommentReply = commentParentMap.get(reaction.commentID);diff --git a/web/apps/albums/src/public-album/viewer/components/AddNameModal.tsx b/web/apps/albums/src/public-album/viewer/components/AddNameModal.tsxindex 36ebec050f..6217cf9041 100644--- a/web/apps/albums/src/public-album/viewer/components/AddNameModal.tsx+++ b/web/apps/albums/src/public-album/viewer/components/AddNameModal.tsx@@ -13,10 +13,6 @@ import type { ModalVisibilityProps } from "ente-base/components/utils/modal";import { t } from "i18next";import React, { useRef, useState } from "react";-// =============================================================================-// Icons-// =============================================================================-const LikeIllustration: React.FC = () => (<svgwidth="126"@@ -156,24 +152,11 @@ const CommentIllustration: React.FC = () => ();export interface AddNameModalProps extends ModalVisibilityProps {- /**- * Called when user submits their name.- */onSubmit: (name: string) => void;- /**- * The type of action being performed (like or comment).- * Defaults to 'like'.- */actionType?: "like" | "comment";- /**- * Called after the modal's exit animation completes.- */onExited?: () => void;}-/**- * Modal dialog for adding a name when liking or commenting on a photo anonymously.- */export const AddNameModal: React.FC<AddNameModalProps> = ({open,onClose,@@ -290,10 +273,6 @@ export const AddNameModal: React.FC<AddNameModalProps> = ({);};-// =============================================================================-// Styled Components-// =============================================================================-const StyledDialog = styled(Dialog)(({ theme }) => ({"& .MuiDialog-paper": {width: 381,diff --git a/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsxindex 909269ea1e..1b8b71246b 100644--- a/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsx+++ b/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsx@@ -43,10 +43,6 @@ import { AddNameModal } from "./AddNameModal";import { PublicCommentModal } from "./PublicCommentModal";import { PublicLikeModal } from "./PublicLikeModal";-// =============================================================================-// Icons-// =============================================================================-const SendIcon: React.FC = () => (<svgwidth="18"@@ -151,11 +147,6 @@ const PersonIcon: React.FC = () => (</svg>);-// =============================================================================-// Types-// =============================================================================--/** Collection info for the dropdown. */interface CollectionInfo {id: number;name: string;@@ -163,10 +154,6 @@ interface CollectionInfo {coverFile?: EnteFile;}-// =============================================================================-// Utility Functions-// =============================================================================-const getParentComment = (parentID: string | undefined,comments: Comment[],@@ -175,10 +162,6 @@ const getParentComment = (return comments.find((c) => c.id === parentID);};-/**- * Truncates comment text to first 100 characters of the first line.- * Adds "..." if multiline or if first line exceeds 100 chars.- */const truncateCommentText = (text: string): string => {const lines = text.split("\n");const firstLine = lines[0] ?? text;@@ -189,23 +172,14 @@ const truncateCommentText = (text: string): string => {return isMultiline ? firstLine + "..." : firstLine;};-// =============================================================================-// Shared Comment Components-// =============================================================================-interface CommentHeaderProps {userName: string;timestamp: number;avatarSize?: number;isMaskedEmail?: boolean;- /** Key used for computing avatar color (e.g., anonUserID for anonymous users). */avatarColorKey?: string;}-/**- * Header component showing avatar, username, and timestamp.- * Used consistently for both root comments and replies.- */const CommentHeader: React.FC<CommentHeaderProps> = ({userName,timestamp,@@ -240,9 +214,6 @@ interface QuotedReplyProps {currentAnonUserID?: string;}-/**- * Shows the quoted parent comment inside a reply bubble.- */const QuotedReply: React.FC<QuotedReplyProps> = ({parentComment,isOwn,@@ -251,9 +222,7 @@ const QuotedReply: React.FC<QuotedReplyProps> = ({anonUserNames,currentAnonUserID,}) => {- // Get the author nameconst getAuthorName = (): string => {- // Check if this is the current user (logged in or anonymous)if (parentComment.userID === currentUserID) {return t("you");}@@ -264,7 +233,6 @@ const QuotedReply: React.FC<QuotedReplyProps> = ({return t("you");}- // For anonymous users, look up in anonUserNamesif (parentComment.anonUserID) {return (anonUserNames?.get(parentComment.anonUserID) ??@@ -272,7 +240,6 @@ const QuotedReply: React.FC<QuotedReplyProps> = ({);}- // For registered users, look up emailconst email = userIDToEmail?.get(parentComment.userID);return email ?? t("user");};@@ -324,96 +291,29 @@ const QuotedReply: React.FC<QuotedReplyProps> = ({);};-// =============================================================================-// Main Component-// =============================================================================-export interface CommentsSidebarProps extends ModalVisibilityProps {- /**- * The file whose comments are being displayed.- */file?: EnteFile;- /**- * True while the parent is fetching the initial social payload for the- * current file.- */isSocialDataLoading?: boolean;- /**- * The currently active collection ID (when viewing from within a collection).- */activeCollectionID?: number;- /**- * The current user's ID.- */currentUserID?: number;- /**- * Pre-fetched comments by collection ID.- */prefetchedComments?: Map<number, Comment[]>;- /**- * Pre-fetched reactions by collection ID (includes both file and comment reactions).- */prefetchedReactions?: Map<number, UnifiedReaction[]>;- /**- * Pre-fetched user ID to email mapping.- */prefetchedUserIDToEmail?: Map<number, string>;- /**- * Called when a comment is successfully added. The parent should update its- * comments state to include this new comment.- */onCommentAdded?: (comment: Comment) => void;- /**- * Called when a comment is successfully deleted. The parent should update its- * comments state to mark this comment as deleted.- */onCommentDeleted?: (collectionID: number, commentID: string) => void;- /**- * Called when a comment reaction is added. The parent should update its- * reactions state to include this new reaction.- */onCommentReactionAdded?: (reaction: UnifiedReaction) => void;- /**- * Called when a comment reaction is deleted. The parent should update its- * reactions state to remove this reaction.- */onCommentReactionDeleted?: (collectionID: number,reactionID: string,) => void;- /**- * If set, the sidebar will scroll to and highlight this comment.- */highlightCommentID?: string;- /**- * Public album credentials for anonymous commenting.- * Required when viewing a public album (no logged in user).- */publicAlbumsCredentials?: PublicAlbumsCredentials;- /**- * The decrypted collection key (base64 encoded) for encrypting comments.- * Required when viewing a public album (no logged in user).- */collectionKey?: string;- /**- * Map of anonymous user ID to decrypted user name.- */anonUserNames?: Map<string, string>;- /**- * Called when user clicks "Join album to like" in the public like modal.- * Should trigger the join album flow (with mobile deep link fallback).- */onJoinAlbum?: () => void;- /**- * Whether the "Join album" option is enabled for this public link.- * When false, the "Join album and like/comment" buttons will be hidden.- */enableJoin?: boolean;}-/**- * A sidebar panel for displaying and managing comments on a file.- */interface ContextMenuState {comment: Comment;anchorEl: HTMLElement;@@ -459,55 +359,45 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const [showPublicLikeModal, setShowPublicLikeModal] = useState(false);const [pendingCommentLike, setPendingCommentLike] =useState<Comment | null>(null);- /** Tracks whether the AddNameModal was triggered by a comment like action */const [addNameForCommentLike, setAddNameForCommentLike] = useState(false);- /** Tracks whether the user has set up their anonymous identity for commenting */const [hasAnonIdentity, setHasAnonIdentity] = useState(false);const [loading, setLoading] = useState(false);const [sending, setSending] = useState(false);const hasLoadedRef = useRef(false);const inputRef = useRef<HTMLInputElement>(null);const commentsContainerRef = useRef<HTMLDivElement>(null);- // Ref to preserve isLiked state during context menu close animation+ // Keep the label stable during the menu's close animation.const contextMenuIsLikedRef = useRef(false);const showLoading = loading || isSocialDataLoading;- // Comments grouped by collection: collectionID -> commentsconst [commentsByCollection, setCommentsByCollection] = useState<Map<number, Comment[]>>(new Map());- // Selected collection for viewing comments (when in gallery view)const [selectedCollectionID, setSelectedCollectionID] = useState<number | undefined>(undefined);- // Thumbnail URLs for each collection's cover file: collectionID -> URLconst [thumbnailURLs, setThumbnailURLs] = useState<Map<number, string>>(new Map(),);- // Comment reactions: commentID -> reactionID (for current user's likes)const [likedComments, setLikedComments] = useState<Map<string, string>>(new Map(),);- // All reactions by collection: collectionID -> reactions arrayconst [reactionsByCollection, setReactionsByCollection] = useState<Map<number, UnifiedReaction[]>>(new Map());- // Track whether we've scrolled to the highlight comment for this openconst hasScrolledToHighlightRef = useRef(false);- // Focus input when replying to a commentuseEffect(() => {if (replyingTo && inputRef.current) {inputRef.current.focus();}}, [replyingTo]);- // Reset tracking refs when sidebar closesuseEffect(() => {if (!open) {hasScrolledToHighlightRef.current = false;@@ -515,7 +405,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({}}, [open]);- // Scroll to and highlight the target comment when opening from feeduseEffect(() => {if (!open ||@@ -533,7 +422,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({let cleanupTimeout: ReturnType<typeof setTimeout> | undefined;let blinkInterval: ReturnType<typeof setInterval> | undefined;- // Wait for DOM to update after comments state change+ // Let the comments render before locating the target.const initialTimeout = setTimeout(() => {const commentWrapper = commentsContainerRef.current?.querySelector(`[data-comment-id="${highlightCommentID}"]`,@@ -541,24 +430,21 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({if (commentWrapper) {hasScrolledToHighlightRef.current = true;- // Scroll to the commentcommentWrapper.scrollIntoView({behavior: "smooth",block: "center",});- // Find the bubble element inside the wrapperconst bubbleElement = commentWrapper.querySelector<HTMLElement>("[data-comment-bubble]",);if (bubbleElement) {- // Wait for scroll to mostly complete, then apply blink highlight+ // Start highlighting after smooth scrolling settles.highlightTimeout = setTimeout(() => {const computedStyle = getComputedStyle(bubbleElement);const originalBg = computedStyle.backgroundColor;- // Parse the RGB values to create 80% opacity versionconst rgbMatch = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(originalBg,);@@ -578,12 +464,10 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({: originalBg;}, 300);- // Stop blinking after 1.5 secondsfadeTimeout = setTimeout(() => {if (blinkInterval) clearInterval(blinkInterval);bubbleElement.style.backgroundColor = originalBg;- // Clean up transition stylecleanupTimeout = setTimeout(() => {bubbleElement.style.transition = "";bubbleElement.style.backgroundColor = "";@@ -603,7 +487,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({};}, [open, highlightCommentID, showLoading, comments]);- // Reset state when the file changes to avoid showing stale datauseEffect(() => {setSelectedCollectionID(undefined);setComments([]);@@ -613,11 +496,9 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({hasLoadedRef.current = false;}, [file?.id]);- // Check if opened from a collection contextconst hasCollectionContext =activeCollectionID !== undefined && activeCollectionID !== 0;- // Build collection info for the current public album.const collectionsInfo = useMemo((): CollectionInfo[] => {if (!file) return [];@@ -634,14 +515,12 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({];}, [file, commentsByCollection]);- // Collections sorted by comment count (descending) for dropdownconst sortedCollectionsInfo = useMemo(() => {return [...collectionsInfo].sort((a, b) => b.commentCount - a.commentCount,);}, [collectionsInfo]);- // Currently selected collection infoconst selectedCollectionInfo = useMemo(() => {const targetID = hasCollectionContext? activeCollectionID@@ -658,16 +537,12 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({sortedCollectionsInfo,]);- // Check if the current user can delete a given comment.- // In public albums, only the original author can delete their comment.+ // Only the original author may delete a public comment.const canDeleteComment = useCallback((comment: Comment): boolean => {- // Comment author can always delete their own comment- // For logged-in users, check userIDif (comment.userID === currentUserID) {return true;}- // For anonymous users, check anonUserIDif (selectedCollectionInfo) {const storedIdentity = getStoredAnonIdentity(selectedCollectionInfo.id,@@ -684,39 +559,30 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({[currentUserID, selectedCollectionInfo],);- // Load comments and reactions from prefetched data.const loadComments = useCallback(() => {if (!file || !open || !prefetchedComments) return;- // Only show loading spinner on initial load, not during polling refresh+ // Polling refreshes must not replace the list with a spinner.const isInitialLoad = !hasLoadedRef.current;if (isInitialLoad) {setLoading(true);}try {- // Use prefetched datasetCommentsByCollection(prefetchedComments);setReactionsByCollection(prefetchedReactions ?? new Map());- // Set comments for the currently selected collectionif (hasCollectionContext && activeCollectionID) {const activeComments =prefetchedComments.get(activeCollectionID) ?? [];setComments(activeComments);} else {- // For gallery view, only auto-select on initial load.- // Use functional update to check current selection without- // adding selectedCollectionID as a dependency.+ // Polling must preserve the user's collection selection.setSelectedCollectionID((currentSelection) => {if (currentSelection !== undefined) {- // Already have a selection, don't change it.- // The useEffect that watches selectedCollectionID will- // update the displayed comments.return currentSelection;}- // Initial selection: find collection with most comments.let maxCount = -1;let bestCollectionID: number | undefined;for (const [@@ -756,14 +622,12 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({activeCollectionID,]);- // Load comments when the sidebar opensuseEffect(() => {if (open) {loadComments();}}, [open, loadComments]);- // Set initial selected collection to the one with most comments (gallery view)useEffect(() => {if (open &&@@ -771,7 +635,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({selectedCollectionID === undefined &&commentsByCollection.size > 0) {- // Find the collection with the most comments.let maxCount = -1;let bestCollectionID: number | undefined;for (const [@@ -797,7 +660,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({commentsByCollection,]);- // Update displayed comments when selected collection changes (gallery view)useEffect(() => {if (!hasCollectionContext && selectedCollectionID !== undefined) {const collectionComments =@@ -806,7 +668,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({}}, [hasCollectionContext, selectedCollectionID, commentsByCollection]);- // Update hasAnonIdentity when collection changes.useEffect(() => {if (selectedCollectionInfo) {const storedIdentity = getStoredAnonIdentity(@@ -816,7 +677,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({}}, [selectedCollectionInfo]);- // Fetch thumbnails for each collection's cover fileuseEffect(() => {if (!open || collectionsInfo.length === 0) {return;@@ -856,9 +716,8 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({};}, [open, collectionsInfo]);- // Build liked comments map from reactions when selected collection changesuseEffect(() => {- // Don't reset state on close - preserves UI during exit animation+ // Keep reaction state through the close animation.if (!open) return;if (!selectedCollectionInfo) {setLikedComments(new Map());@@ -873,11 +732,9 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const storedIdentity = getStoredAnonIdentity(selectedCollectionInfo.id);- // Find comment reactions that are likes from the current user (or anon user)const newLikedComments = new Map<string, string>();for (const reaction of reactions) {if (reaction.commentID && reaction.reactionType === "green_heart") {- // Check if this is the current user's reactionconst isCurrentUserReaction =reaction.userID === currentUserID ||(storedIdentity &&@@ -901,9 +758,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({}};- /**- * Send a comment to the public album API using stored anonymous identity.- */const sendPublicComment = async (text: string) => {if (!file ||@@ -933,7 +787,8 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({storedIdentity,);- // Add the new comment to local state+ // Anonymous users use userID 0.+ // Local timestamps mirror the server's microseconds.const newComment: Comment = {id: newCommentID,collectionID,@@ -941,9 +796,9 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({text,parentCommentID: replyingTo?.id,isDeleted: false,- userID: 0, // Anonymous user+ userID: 0,anonUserID: storedIdentity.anonUserID,- createdAt: Date.now() * 1000, // Microseconds to match server format+ createdAt: Date.now() * 1000,updatedAt: Date.now() * 1000,};setComments((prev) => [...prev, newComment]);@@ -957,10 +812,9 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({setCommentText("");setReplyingTo(null);- // Notify parent to update its comments stateonCommentAdded?.(newComment);- // Scroll to bottom after adding comment+ // column-reverse puts the bottom at scrollTop 0.setTimeout(() => {if (commentsContainerRef.current) {commentsContainerRef.current.scrollTop = 0;@@ -1010,10 +864,8 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const collectionID = selectedCollectionInfo.id;- // Check if this is for a comment like actionif (addNameForCommentLike && pendingCommentLike) {try {- // Create anonymous identity with the provided nameconst identity = await createAnonIdentity(publicAlbumsCredentials,collectionID,@@ -1021,7 +873,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({collectionKey,);- // Now like the comment using the new identityconst reactionID = await addPublicCommentReaction(publicAlbumsCredentials,collectionID,@@ -1064,8 +915,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({return;}- // Handle comment action - just create identity, don't send comment- // User will type and send the comment afterwards+ // Naming only unlocks the input; it does not submit a comment.try {await createAnonIdentity(publicAlbumsCredentials,@@ -1073,33 +923,28 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({name,collectionKey,);- // Identity created, user can now type and send commentssetHasAnonIdentity(true);} catch (e) {log.error("Failed to create anonymous identity", e);}};- // Check if user needs to set up identity before commenting.const needsIdentityToComment = !!selectedCollectionInfo && !hasAnonIdentity;const handleReply = (commentToReply: Comment) => {setReplyingTo(commentToReply);- // For public albums, check if we have an identityif (needsIdentityToComment) {setShowPublicCommentModal(true);}};- // Handler for clicking the comment input area on public albumsconst handleInputClick = () => {if (needsIdentityToComment) {setShowPublicCommentModal(true);}};- // Handler for keydown: Enter to send, Shift+Enter for new lineconst handleCommentKeyDown = (e: React.KeyboardEvent) => {if (e.key === "Enter" && !e.shiftKey) {e.preventDefault();@@ -1255,7 +1100,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({return;}- // Update local statesetComments((prev) =>prev.map((c) =>c.id === targetComment.id@@ -1278,7 +1122,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({return next;});- // Notify parent to update its comments stateonCommentDeleted?.(targetComment.collectionID,targetComment.id,@@ -1290,7 +1133,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({}};- // Filter out deleted comments and sort by timestamp (newest first for column-reverse layout)+ // column-reverse expects newest comments first.const sortedComments = [...comments].filter((c) => !c.isDeleted).sort((a, b) => b.createdAt - a.createdAt);@@ -1445,9 +1288,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({<EmptyMessage>{t("no_comments_yet")}</EmptyMessage>) : (sortedComments.map((comment, index) => {- // Check if this is the current user's comment- // For logged-in users, check userID- // For anonymous users, check anonUserID against stored identityconst storedIdentity = selectedCollectionInfo? getStoredAnonIdentity(selectedCollectionInfo.id,@@ -1461,16 +1301,14 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({comment.userID === currentUserID ||isCurrentAnonUser;- // With column-reverse, visual order is reversed from array order- // Visual "above" = higher index, visual "below" = lower index+ // column-reverse puts the higher index above this comment.const prevComment = sortedComments[index + 1];const nextComment = sortedComments[index - 1];- // 10 minutes in microseconds (server timestamps are in microseconds)+ // Server timestamps are microseconds.+ // Consecutive comments group within ten minutes.const GROUP_TIME_THRESHOLD = 10 * 60 * 1000 * 1000;- // Comments are in same sequence if same user AND within 10 minutes- // For anon users, also check if they have the same anonUserIDconst isSameUser = (a: Comment, b: Comment) => {if (a.anonUserID && b.anonUserID) {return a.anonUserID === b.anonUserID;@@ -1502,13 +1340,11 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const showOwnTimestamp =commentIsOwn && isFirstInSequence;- // Get the display name, avatar color key, and masked email status for the comment authorconst getCommentAuthorInfo = (): {name: string;avatarColorKey: string;isMaskedEmail: boolean;} => {- // If anonymous user, check anonUserNames mapif (comment.anonUserID) {const anonName =anonUserNames?.get(@@ -1517,12 +1353,10 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({`${t("anonymous")} ${comment.anonUserID.slice(-4)}`;return {name: anonName,- // Use name for avatar color (varying length like mobile emails)avatarColorKey: anonName,isMaskedEmail: false,};}- // For registered users, use emailconst emailFromMap =prefetchedUserIDToEmail?.get(comment.userID,@@ -1530,7 +1364,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({const email = emailFromMap ?? t("user");return {name: email,- // Use email or userID for avatar coloravatarColorKey: emailFromMap? emailFromMap: String(comment.userID),@@ -1699,7 +1532,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({>Replying to{" "}{(() => {- // Check for anonymous userif (replyingTo.anonUserID) {const storedIdentity =selectedCollectionInfo@@ -1719,7 +1551,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({) ?? t("user"));}- // Regular userreturn replyingTo.userID ===currentUserID? t("yourself")@@ -1819,7 +1650,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({</InputContainer></DrawerContentWrapper>- {/* Public album modals */}<PublicCommentModalopen={showPublicCommentModal}onClose={() => setShowPublicCommentModal(false)}@@ -1844,8 +1674,7 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({setPendingCommentLike(null);}}onExited={() => {- // Reset actionType after modal has fully closed to avoid- // visual glitch of icon changing during exit animation+ // Keep the modal variant stable through its exit animation.setAddNameForCommentLike(false);}}onSubmit={handleNameSubmit}@@ -1855,11 +1684,6 @@ export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({);};-// =============================================================================-// Styled Components-// =============================================================================--// Drawer & Layoutconst SidebarDrawer = styled(Drawer)(({ theme }) => ({"& .MuiDrawer-paper": {width: "23vw",@@ -1918,7 +1742,6 @@ const CloseButton = styled(IconButton)(({ theme }) => ({}),}));-// Collection Dropdownconst CollectionDropdownButton = styled(Box)(({ theme }) => ({display: "inline-flex",alignItems: "center",@@ -1968,13 +1791,13 @@ const CollectionThumbnailPlaceholder = styled(Box)(() => ({backgroundColor: "#08C225",}));+// The negative margin centers these states below the 56px header offset.const LoadingContainer = styled(Box)(() => ({display: "flex",justifyContent: "center",alignItems: "center",height: "100%",paddingRight: 24,- // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halvedmarginTop: -28,}));@@ -1984,7 +1807,6 @@ const EmptyMessage = styled(Typography)(({ theme }) => ({alignItems: "center",height: "100%",paddingRight: 24,- // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halvedmarginTop: -28,color: "#666",...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.5)" }),@@ -2049,7 +1871,6 @@ const CommentsContainer = styled(Box)(({ theme }) => ({}),}));-// Comment Headerconst CommentHeaderContainer = styled(Box)(() => ({display: "flex",alignItems: "center",@@ -2087,7 +1908,6 @@ const OwnTimestamp = styled(Typography)(({ theme }) => ({...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),}));-// Comment Bubblesconst CommentBubbleWrapper = styled(Box, {shouldForwardProp: (prop) =>!["isOwn", "isFirstOwn", "isLastOwn", "isHighlighted"].includes(@@ -2149,7 +1969,6 @@ const QuotedReplyContainer = styled(Box, {})),}));-// Input Areaconst InputContainer = styled(Box)(({ theme }) => ({position: "relative",backgroundColor: "#F3F3F3",@@ -2229,7 +2048,6 @@ const SendButton = styled(IconButton)(({ theme }) => ({}),}));-// Context Menuconst ContextMenuOverlay = styled(Box)(() => ({position: "absolute",top: -25,diff --git a/web/apps/albums/src/public-album/viewer/components/FileViewer.tsx b/web/apps/albums/src/public-album/viewer/components/FileViewer.tsxindex 7f7af560a0..caaf3e38c9 100644--- a/web/apps/albums/src/public-album/viewer/components/FileViewer.tsx+++ b/web/apps/albums/src/public-album/viewer/components/FileViewer.tsx@@ -61,12 +61,6 @@ const hasFileViewerBackStateMarker = (state: unknown, marker: string) =>typeof state == "object" &&(state as Record<string, unknown>)[fileViewerBackStateKey] == marker;-/**- * Derived data for a file that is needed to display the file viewer controls- * etc associated with the file.- *- * This is recomputed on-demand each time the slide changes.- */export interface FileViewerFileAnnotation {fileID: number;showFavorite: boolean;@@ -76,16 +70,12 @@ export interface FileViewerFileAnnotation {showCopyImage: boolean;}-/**- * A file, its annotation, and its item data, in a nice cosy box.- */export interface FileViewerAnnotatedFile {file: EnteFile;annotation: FileViewerFileAnnotation;itemData: ItemData;}-/** The type of sidebar to open initially in the file viewer. */export type FileViewerInitialSidebar = "likes" | "comments";export type FileViewerProps = ModalVisibilityProps & {@@ -101,10 +91,6 @@ export type FileViewerProps = ModalVisibilityProps & {publicAlbumsCredentials?: PublicAlbumsCredentials;shouldCloseOnBrowserBack?: boolean;disableEscapeClose?: boolean;- /**- * Disable PhotoSwipe's gesture-driven dismissals, such as pinch-to-close- * and vertical drag close.- */disableGestureClose?: boolean;collectionKey?: string;onJoinAlbum?: () => void;@@ -112,9 +98,6 @@ export type FileViewerProps = ModalVisibilityProps & {enableJoin?: boolean;};-/**- * A PhotoSwipe based image, live photo and video viewer.- */export const FileViewer: React.FC<FileViewerProps> = ({open,onClose,@@ -139,45 +122,23 @@ export const FileViewer: React.FC<FileViewerProps> = ({const { onGenericError } = useBaseContext();const shouldCloseOnBrowserBack = shouldCloseOnBrowserBackOverride ?? true;- // There are 3 things involved in this dance:- //- // 1. Us, "FileViewer". We're a React component.- // 2. The custom PhotoSwipe wrapper, "FileViewerPhotoSwipe". It is a class.- // 3. The delegate, "FileViewerPhotoSwipeDelegate".- //- // The delegate acts as a bridge between us and (our custom) photoswipe- // class, to avoid recreating the class each time a "dynamic" prop changes.- // The delegate has a stable identity, we just keep updating the callback- // functions that it holds.- //- // The word "dynamic" here means a prop on whose change we should not- // recreate the photoswipe dialog.+ // PhotoSwipe keeps one delegate for its lifetime.+ // Update its callbacks instead of recreating the viewer when props change.const delegateRef = useRef<FileViewerPhotoSwipeDelegate<FileViewerAnnotatedFile> | undefined>(undefined);- // We also need to maintain a ref to the currently displayed dialog since we- // might need to ask it to refresh its contents.const psRef = useRef<FileViewerPhotoSwipe<FileViewerAnnotatedFile> | undefined>(undefined);const handleCloseRef = useRef<() => void>(() => undefined);const browserBackStateRef = useRef<string | undefined>(undefined);- // Whenever we get a callback from our custom PhotoSwipe instance, we also- // get the active file on which that action was performed as an argument. We- // save it as the `activeAnnotatedFile` state so that the rest of our React- // tree can use it.- //- // This is not guaranteed, or even intended, to be in sync with the active- // file shown within the file viewer. All that this guarantees is this will- // refer to the file on which the last user initiated action was performed.+ // This is the last action target, not necessarily the visible slide.const [activeAnnotatedFile, setActiveAnnotatedFile] = useState<FileViewerAnnotatedFile | undefined>(undefined);- // With semantics similar to `activeAnnotatedFile`, this is the exif data- // associated with the `activeAnnotatedFile`, if any.const [activeFileExif, setActiveFileExif] = useState<FileInfoExif | undefined>(undefined);@@ -193,26 +154,18 @@ export const FileViewer: React.FC<FileViewerProps> = ({const [isFullscreen, setIsFullscreen] = useState(false);- // Map of file ID to map of collection ID to array of comments.- // For gallery view, we fetch comments from all collections.- // For collection view, we only fetch comments from that collection.const [fileComments, setFileComments] = useState<Map<number, Map<number, Comment[]>>>(new Map());- // Map of file ID to map of collection ID to array of all reactions.- // Includes both file reactions and comment reactions.const [allReactions, setAllReactions] = useState<Map<number, Map<number, UnifiedReaction[]>>>(new Map());- // Map of user ID to email for displaying reaction/comment authors.- // Built from collection owner and sharees when fetching social data.const [userIDToEmail, setUserIDToEmail] = useState<Map<number, string>>(new Map(),);- // Map of anon user ID to decrypted user name for anonymous users.const [anonUserNames, setAnonUserNames] = useState<Map<string, string>>(() =>initialAnonUserNames ? new Map(initialAnonUserNames) : new Map(),@@ -237,16 +190,13 @@ export const FileViewer: React.FC<FileViewerProps> = ({});}, [initialAnonUserNames]);- // Ref for allReactions to use in callbacksconst allReactionsRef = useRef(allReactions);useEffect(() => {allReactionsRef.current = allReactions;}, [allReactions]);- // Track whether we've already opened the initial sidebar for this openconst hasOpenedInitialSidebarRef = useRef(false);- // Open the initial sidebar when the file viewer opens with initialSidebar setuseEffect(() => {if (open && initialSidebar && !hasOpenedInitialSidebarRef.current) {hasOpenedInitialSidebarRef.current = true;@@ -256,7 +206,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({setOpenLikes(true);}}- // Reset the flag when the viewer closesif (!open) {hasOpenedInitialSidebarRef.current = false;}@@ -268,16 +217,12 @@ export const FileViewer: React.FC<FileViewerProps> = ({setOpenComments(false);setOpenLikes(false);setOpenPublicLikeModal(false);- // No need to `resetMoreMenuButtonOnMenuClose` since we're closing- // anyway and it'll be removed from the DOM.setMoreMenuAnchorEl(null);setOpenShortcuts(false);setIsFullscreen(false);onClose();}, [onClose]);- // Keep the latest close callback available to non-react event handlers- // without forcing effects that register handlers to re-run.handleCloseRef.current = handleClose;const handleViewInfo = useCallback(@@ -298,7 +243,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({const handleCommentsClose = useCallback(() => setOpenComments(false), []);- // Handle a new comment being addedconst handleCommentAdded = useCallback((comment: Comment) => {const fileID = comment.fileID;if (!fileID) return;@@ -319,7 +263,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({});}, []);- // Handle a comment being deletedconst handleCommentDeleted = useCallback((collectionID: number, commentID: string) => {const fileID = activeAnnotatedFile?.file.id;@@ -346,7 +289,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({[activeAnnotatedFile],);- // Handle a comment reaction being addedconst handleCommentReactionAdded = useCallback((reaction: UnifiedReaction) => {const fileID = activeAnnotatedFile?.file.id;@@ -370,7 +312,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({[activeAnnotatedFile],);- // Handle a comment reaction being deletedconst handleCommentReactionDeleted = useCallback((collectionID: number, reactionID: string) => {const fileID = activeAnnotatedFile?.file.id;@@ -399,14 +340,11 @@ export const FileViewer: React.FC<FileViewerProps> = ({const handleLikesClose = useCallback(() => setOpenLikes(false), []);- // Refs to access current state without causing re-renders- // when used in callbacks that are dependencies of the PhotoSwipe effect.const activeAnnotatedFileRef = useRef(activeAnnotatedFile);activeAnnotatedFileRef.current = activeAnnotatedFile;const haveUser = false;- // Called when the like button (heart) is clicked in public album mode.const handleLikeClick = useCallback(() => {const file = activeAnnotatedFileRef.current?.file;if (!file || !publicAlbumsCredentials) {@@ -418,7 +356,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({const collectionId = file.collectionID;const storedAnonIdentity = getStoredAnonIdentity(collectionId);- // Check if already liked by current anon user (file-level only, not comment likes)const fileReactionsMap = allReactionsRef.current.get(fileId);const collectionReactions = fileReactionsMap?.get(collectionId) ?? [];const existingReaction = collectionReactions.find(@@ -430,7 +367,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({);if (existingReaction) {- // Already liked - unlike (delete reaction)void (async () => {try {await deletePublicReaction(@@ -439,7 +375,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({existingReaction.id,);- // Update local statesetAllReactions((prev) => {const next = new Map(prev);const fileReactionsMap = new Map<@@ -458,7 +393,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({}})();} else if (storedAnonIdentity) {- // Has identity but not liked - add reaction directlyvoid (async () => {try {if (!collectionKey) {@@ -473,7 +407,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({collectionKey,);- // Update local statesetAllReactions((prev) => {const next = new Map(prev);const fileReactionsMap = new Map<@@ -504,7 +437,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({}})();} else {- // No identity - show modal to get namesetOpenPublicLikeModal(true);}}, [publicAlbumsCredentials, collectionKey]);@@ -541,7 +473,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({}const fileId = file.id;- // Use file.collectionID for public albums since activeCollectionID is a pseudo ID (0)+ // Public album gallery mode uses collection ID 0 as a sentinel.const collectionId =activeCollectionID && activeCollectionID > 0? activeCollectionID@@ -549,7 +481,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({void (async () => {try {- // Check if we already have an anon identity for this collection, otherwise create onelet identity = getStoredAnonIdentity(collectionId);if (!identity) {identity = await createAnonIdentity(@@ -560,7 +491,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({);}- // Add the public reactionconst reactionId = await addPublicReaction(publicAlbumsCredentials,collectionId,@@ -570,7 +500,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({identity,);- // Update local statesetAllReactions((prev) => {const next = new Map(prev);const fileReactionsMap = new Map<@@ -586,7 +515,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({collectionID: collectionId,fileID: fileId,reactionType: "green_heart",- // Use a special userID for anonymous users (derived from anonUserID)+ // Anonymous users use userID 0.userID: 0,anonUserID: identity.anonUserID,isDeleted: false,@@ -598,7 +527,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({return next;});- // Update anonUserNames so the name shows immediately in likers listsetAnonUserNames((prev) => {const next = new Map(prev);next.set(identity.anonUserID, name);@@ -622,8 +550,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({],);- // Callback invoked when the download action is triggered by activating the- // download button in the PhotoSwipe bar.const handleDownloadBarAction = useCallback((annotatedFile: FileViewerAnnotatedFile) => {onDownload!(annotatedFile.file);@@ -643,15 +569,13 @@ export const FileViewer: React.FC<FileViewerProps> = ({});}, []);- // Not memoized since it uses the frequently changing `activeAnnotatedFile`.const handleCopyImage = useCallback(() => {handleMoreMenuCloseIfNeeded();if (!activeAnnotatedFile) return;const { imageURL } = activeAnnotatedFile.itemData;if (!imageURL) return;- // Safari does not copy if we do not call `navigator.clipboard.write`- // synchronously within the click event handler, but it does supports- // passing a promise in lieu of the blob.+ // Safari requires clipboard.write during the click event.+ // It accepts a promise for the blob.void window.navigator.clipboard.write([new ClipboardItem({@@ -695,7 +619,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({);const showSocialButtons = true;- // Delegate callback to check if social buttons should be shown for a file.const shouldShowSocialButtons_ = useCallback((): boolean => false, []);const getFiles = useCallback(() => files, [files]);@@ -711,15 +634,12 @@ export const FileViewer: React.FC<FileViewerProps> = ({const fileReactionsMap = allReactions.get(file.id);if (!fileReactionsMap) return false;- // Check if user has liked this file in any collectionfor (const [collectionId, reactions] of fileReactionsMap) {- // Get stored anonymous identity for this specific collectionconst storedAnonIdentity = getStoredAnonIdentity(collectionId);const hasUserLike = reactions.some((r) => {if (r.commentID || r.reactionType !== "green_heart")return false;- // Check for anonymous userif (storedAnonIdentity &&r.anonUserID === storedAnonIdentity.anonUserID@@ -742,7 +662,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({const isGalleryView =!activeCollectionID || activeCollectionID === 0;if (isGalleryView) {- // Return the count from the collection with most commentslet maxCount = 0;for (const comments of commentsMap.values()) {const count = comments.filter((c) => !c.isDeleted).length;@@ -750,7 +669,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({}return maxCount;} else {- // Return count from the active collectionconst comments = commentsMap.get(activeCollectionID);return comments?.filter((c) => !c.isDeleted).length ?? 0;}@@ -779,7 +697,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({const handleShortcutsClose = useCallback(() => setOpenShortcuts(false), []);const shouldIgnoreKeyboardEvent = useCallback(() => {- // Don't handle keydowns if any of the viewer's own modals are open.if (openFileInfo ||openComments ||@@ -791,8 +708,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({return true;}- // Also ignore keydowns if keyboard focus is inside an editable field- // (e.g., when the CollectionSelector dialog's search TextField is focused)const activeElement = document.activeElement as HTMLElement | null;if (activeElement) {const tagName = activeElement.tagName;@@ -854,7 +769,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({],);- // Initial value of delegate.if (!delegateRef.current) {delegateRef.current = {getFiles,@@ -869,7 +783,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({};}- // Updates to delegate callbacks.useEffect(() => {const delegate = delegateRef.current!;delegate.getFiles = getFiles;@@ -895,17 +808,13 @@ export const FileViewer: React.FC<FileViewerProps> = ({useEffect(() => {if (!files.length) {- // If there are no more files left, close the viewer.handleClose();} else if (open && activeAnnotatedFile) {- // Only refresh if the viewer is still open and we have an active file.- // This prevents race conditions when navigating away (e.g., when clicking- // the navigate button in AlbumAddedNotification while the viewer is open).+ // Refreshing while the viewer closes can race navigation.psRef.current?.refreshSlideOnFilesUpdateIfNeeded();}}, [handleClose, files, open, activeAnnotatedFile]);- // Refresh like button when allReactions changes.useEffect(() => {if (open && files.length) {psRef.current?.refreshCurrentSlideLikeButtonIfNeeded();@@ -924,7 +833,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({shouldFetchPublicSocialData &&publicSocialDataStatusByFileID.get(activeFileID) !== "ready";- // Fetch social data (comments + reactions) for public albums (when viewing as anonymous user).useEffect(() => {if (!open ||@@ -948,14 +856,12 @@ export const FileViewer: React.FC<FileViewerProps> = ({void (async () => {try {- // Fetch both comments and reactions in a single API callconst { comments, reactions } = await getPublicSocialDiff(publicAlbumsCredentials,activeFileID,collectionKey,);- // Convert PublicComment to Comment formatconst commentsForFile: Comment[] = comments.map((c) => ({id: c.id,collectionID: c.collectionID,@@ -978,7 +884,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({return next;});- // Convert PublicReaction to UnifiedReaction formatconst unifiedReactions: UnifiedReaction[] = reactions.map((r) => ({id: r.id,@@ -1003,7 +908,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({return next;});- // Fetch anonymous user profiles for public albumstry {const anonProfiles = await getPublicAnonProfiles(publicAlbumsCredentials,@@ -1017,10 +921,9 @@ export const FileViewer: React.FC<FileViewerProps> = ({return next;});} catch {- // Ignore anon profiles fetch failures+ // Names are optional enrichment.}- // Fetch registered participants' masked emails for public albumstry {const participantEmails =await getPublicParticipantsMaskedEmails(@@ -1034,7 +937,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({return next;});} catch {- // Ignore participants fetch failures+ // Names are optional enrichment.}} catch (e) {log.error("Failed to fetch public social data", e);@@ -1057,7 +960,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({files,]);- // Refresh comment count when fileComments changes.useEffect(() => {if (open && files.length) {psRef.current?.refreshCurrentSlideCommentCountIfNeeded();@@ -1066,7 +968,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({const SOCIAL_REFRESH_INTERVAL_MS = 5_000;- // Refresh social data for public albumsconst refreshPublicSocialData = useCallback(async () => {if (!activeFileID ||@@ -1130,7 +1031,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({return next;});- // Fetch anon profiles (new anonymous users may have commented)try {const anonProfiles = await getPublicAnonProfiles(publicAlbumsCredentials,@@ -1144,10 +1044,9 @@ export const FileViewer: React.FC<FileViewerProps> = ({return next;});} catch {- // Ignore+ // Names are optional enrichment.}- // Note: Masked emails for registered participants are fetched only- // on initial load since they rarely change during a session.+ // Masked participant emails are stable enough to fetch only on open.} catch (e) {log.error("Failed to refresh public social data", e);}@@ -1159,7 +1058,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({files,]);- // Poll for social data when comments or likes sidebar is open (public albums)useInterval(refreshPublicSocialData,(openComments || openLikes) && publicAlbumsCredentials@@ -1169,7 +1067,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({useEffect(() => {if (open) {- // We're open. Create psRef. This will show the file viewer dialog.log.debug(() => "Opening file viewer");const pswp = new FileViewerPhotoSwipe({@@ -1195,22 +1092,14 @@ export const FileViewer: React.FC<FileViewerProps> = ({psRef.current = pswp;return () => {- // Close dialog in the effect callback.log.debug(() => "Closing file viewer");pswp.closeIfNeeded();};} else {return undefined;}- // Be careful with adding new dependencies here, or changing the source- // of existing ones. If any of these dependencies change unnecessarily,- // then the file viewer will start getting reloaded even when it is- // already open.- //- // Note: showSocialButtons and enableComment are intentionally NOT included- // here even though they're passed to the constructor. The delegate's- // public-album branch is static, and these values should not trigger a- // full recreation.+ // Changing these dependencies recreates PhotoSwipe.+ // showSocialButtons and enableComment deliberately stay out.// eslint-disable-next-line react-hooks/exhaustive-deps}, [open,@@ -1233,8 +1122,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({useEffect(() => {if (!open || !shouldCloseOnBrowserBack) return;- // In public albums, consume one browser-back action to close the- // viewer overlay instead of navigating away from the shared link.+ // Back closes the overlay without leaving the shared link.const stateMarker = `${Date.now()}-${Math.random().toString(36).slice(2)}`;browserBackStateRef.current = stateMarker;@@ -1341,7 +1229,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({<MoreMenuItemTitle>{t("copy_as_png")}</MoreMenuItemTitle>- {/* Tweak icon size to visually fit better with neighbours */}<ContentCopyIcon sx={{ "&&": { fontSize: "18px" } }} /></MoreMenuItem>)}@@ -1396,14 +1283,11 @@ const MoreMenu = styled(Menu)(`,);+// Override MUI's responsive min-height so menu rows remain 44px.const MoreMenuItem = styled(MenuItem)(({ theme }) => `min-width: 210px;- /* MUI MenuItem default implementation has a minHeight of "48px" below the- "sm" breakpoint, and auto after it. We always want the same height, so- set minHeight auto and use an explicit padding always to come out to 44px- (20px (icon or Typography height + 12 + 12) */padding-block: 12px;min-height: auto;@@ -1411,7 +1295,6 @@ const MoreMenuItem = styled(MenuItem)(justify-content: space-between;align-items: center;- /* Same as other controls on the PhotoSwipe UI */color: rgba(255 255 255 / 0.85);&:hover {color: rgba(255 255 255 / 1);@@ -1429,12 +1312,7 @@ const MoreMenuItemTitle: React.FC<React.PropsWithChildren> = ({ children }) => ();type ShortcutsProps = ModalVisibilityProps &- Pick<FileViewerProps, "disableDownload"> & {- /**- * `true` if we're running in a context where there is a logged in user.- */- haveUser: boolean;- };+ Pick<FileViewerProps, "disableDownload"> & { haveUser: boolean };const Shortcuts: React.FC<ShortcutsProps> = ({open,@@ -1545,10 +1423,6 @@ const Shortcut: React.FC<ShortcutProps> = ({ action, shortcut }) => (</tr>);-/**- * Return a promise that resolves with a "image/png" blob derived from the given- * {@link imageURL} that can be written to the navigator's clipboard.- */const createImagePNGBlob = async (imageURL: string): Promise<Blob> =>new Promise((resolve, reject) => {const image = new Image();diff --git a/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsxindex 3080885eea..28d55c1800 100644--- a/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsx+++ b/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsx@@ -26,10 +26,6 @@ import React, {} from "react";import type { UnifiedReaction } from "../lib/social-types";-// =============================================================================-// Icons-// =============================================================================-const ChevronDownIcon: React.FC = () => (<svgwidth="22"@@ -80,25 +76,16 @@ const PersonIcon: React.FC = () => (</svg>);-// =============================================================================-// Types-// =============================================================================--/** A liker with display info. */interface Liker {id: string;userID: number;anonUserID?: string;userName: string;- /** The actual email for avatar color, even when userName is "You". */email: string;- /** The first letter of the actual name (not "You") for the avatar. */avatarInitial: string;- /** True if this is a registered user with masked email (show person icon). */isMaskedEmail: boolean;}-/** Collection info for the dropdown. */interface CollectionInfo {id: number;name: string;@@ -106,45 +93,16 @@ interface CollectionInfo {coverFile?: EnteFile;}-// =============================================================================-// Main Component-// =============================================================================-export interface LikesSidebarProps extends ModalVisibilityProps {- /**- * The file whose likes are being displayed.- */file?: EnteFile;- /**- * True while the parent is fetching the initial social payload for the- * current file.- */isSocialDataLoading?: boolean;- /**- * The currently active collection ID (when viewing from within a collection).- */activeCollectionID?: number;- /**- * The current user's ID.- */currentUserID?: number;- /**- * Pre-fetched reactions by collection ID (includes both file and comment reactions).- */prefetchedReactions?: Map<number, UnifiedReaction[]>;- /**- * Pre-fetched user ID to email mapping.- */prefetchedUserIDToEmail?: Map<number, string>;- /**- * Map of anonymous user ID to decrypted user name.- */anonUserNames?: Map<string, string>;}-/**- * A sidebar panel for displaying users who liked a file.- */export const LikesSidebar: React.FC<LikesSidebarProps> = ({open,onClose,@@ -166,26 +124,21 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({const [collectionDropdownOpen, setCollectionDropdownOpen] = useState(false);const showLoading = loading || isSocialDataLoading;- // Reactions grouped by collection: collectionID -> reactionsconst [reactionsByCollection, setReactionsByCollection] = useState<Map<number, UnifiedReaction[]>>(new Map());- // Selected collection for viewing likes (when in gallery view)const [selectedCollectionID, setSelectedCollectionID] = useState<number | undefined>(undefined);- // Thumbnail URLs for each collection's cover file: collectionID -> URLconst [thumbnailURLs, setThumbnailURLs] = useState<Map<number, string>>(new Map(),);- // Check if opened from a collection contextconst hasCollectionContext =activeCollectionID !== undefined && activeCollectionID !== 0;- // Build collection info for the current public album.const collectionsInfo = useMemo((): CollectionInfo[] => {if (!file) return [];@@ -203,12 +156,10 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({];}, [file, reactionsByCollection]);- // Collections sorted by like count (descending) for dropdownconst sortedCollectionsInfo = useMemo(() => {return [...collectionsInfo].sort((a, b) => b.likeCount - a.likeCount);}, [collectionsInfo]);- // Currently selected collection infoconst selectedCollectionInfo = useMemo(() => {const targetID = hasCollectionContext? activeCollectionID@@ -225,26 +176,22 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({sortedCollectionsInfo,]);- // Get likers for the selected collectionconst likers = useMemo((): Liker[] => {if (!selectedCollectionInfo) return [];const reactions =reactionsByCollection.get(selectedCollectionInfo.id) ?? [];- // Get stored anonymous identity for this collection to check if current anon userconst storedAnonIdentity = getStoredAnonIdentity(selectedCollectionInfo.id,);return reactions.filter((r) => r.reactionType === "green_heart")- .sort((a, b) => b.createdAt - a.createdAt) // Most recent first+ .sort((a, b) => b.createdAt - a.createdAt).map((r) => {- // Check if this is an anonymous userconst isAnonymous =r.anonUserID || r.userID === 0 || r.userID === -1;- // Check if this is the current user (logged-in or anonymous)const isCurrentUser = r.userID === currentUserID;const isCurrentAnonUser =storedAnonIdentity &&@@ -255,27 +202,21 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({let actualName: string;if (isAnonymous) {- // Use decrypted name from anonUserNames if availableconst decryptedName = r.anonUserID? anonUserNames?.get(r.anonUserID): undefined;actualName =decryptedName ??`${t("anonymous")} ${r.anonUserID?.slice(-4) ?? ""}`;- // Use actualName for avatar color (varying length like mobile emails)email = actualName;userName = isCurrentAnonUser ? t("you") : actualName;} else {const emailFromMap = prefetchedUserIDToEmail?.get(r.userID);- // Use userID as string for unique avatar coloremail = emailFromMap ?? String(r.userID);- // In public albums (no currentUserID), non-anonymous- // users are album owner or collaboratorsactualName = emailFromMap ?? t("anonymous");userName = isCurrentUser ? t("you") : actualName;}- // Check if email is masked (starts with *)const isMaskedEmail =!isAnonymous && actualName.startsWith("*");@@ -297,14 +238,12 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({anonUserNames,]);- // Load reactions from prefetched dataconst loadReactions = useCallback(() => {if (!file || !open || !prefetchedReactions) return;setLoading(true);try {- // Use prefetched reactions (filter to only file reactions, not comment reactions)const filteredReactions = new Map<number, UnifiedReaction[]>();for (const [collectionID, reactions] of prefetchedReactions) {const fileReactions = reactions.filter(@@ -321,16 +260,12 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({}}, [file, open, prefetchedReactions]);- // Track previous open state to detect when sidebar opensconst prevOpenRef = useRef(false);- // Load reactions and set initial selection when the sidebar opensuseEffect(() => {if (open && !prevOpenRef.current) {- // Sidebar just opened - load reactions and set initial selectionloadReactions();- // Set initial selection to album with most likes (gallery view only)if (!hasCollectionContext &&prefetchedReactions &&@@ -364,11 +299,9 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({file?.id,]);- // Update local state when prefetchedReactions changes (e.g., like/unlike from heart button)useEffect(() => {if (!open || !file || !prefetchedReactions) return;- // Filter to only file reactions (not comment reactions)const filteredReactions = new Map<number, UnifiedReaction[]>();for (const [collectionID, reactions] of prefetchedReactions) {const fileReactions = reactions.filter(@@ -380,9 +313,8 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({setReactionsByCollection(filteredReactions);}, [open, file, prefetchedReactions]);- // Fetch thumbnails for each collection's cover fileuseEffect(() => {- // Only fetch when open, don't clear when closing (avoids flash during animation)+ // Keep thumbnails through the close animation.if (!open || collectionsInfo.length === 0) {return;}@@ -601,11 +533,6 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({);};-// =============================================================================-// Styled Components-// =============================================================================--// Drawer & Layoutconst SidebarDrawer = styled(Drawer)(({ theme }) => ({"& .MuiDrawer-paper": {width: "23vw",@@ -664,7 +591,6 @@ const CloseButton = styled(IconButton)(({ theme }) => ({}),}));-// Collection Dropdownconst CollectionDropdownButton = styled(Box)(({ theme }) => ({display: "inline-flex",alignItems: "center",@@ -784,12 +710,12 @@ const LikerName = styled(Typography)(({ theme }) => ({...theme.applyStyles("dark", { color: "#fff" }),}));+// The negative margin centers these states below the 56px header offset.const LoadingContainer = styled(Box)(() => ({display: "flex",justifyContent: "center",alignItems: "center",height: "100%",- // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halvedmarginTop: -28,}));@@ -798,13 +724,11 @@ const EmptyMessage = styled(Typography)(({ theme }) => ({justifyContent: "center",alignItems: "center",height: "100%",- // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halvedmarginTop: -28,color: "#666",...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.5)" }),}));-// Context Menu Overlayconst ContextMenuOverlay = styled(Box)(() => ({position: "absolute",top: -25,diff --git a/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsx b/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsxindex 801c7ab7e3..133cfe71cd 100644--- a/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsx+++ b/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsx@@ -64,11 +64,6 @@ const inlineFileViewerIconPath = (name: "live" | "vol") =>const liveIconPath = inlineFileViewerIconPath("live");const volumeIconPath = inlineFileViewerIconPath("vol");-/**- * A dedicated public-album single-file viewer mode with a bespoke header/menu.- *- * This wraps the regular FileViewer but overlays its own controls.- */export const PublicAlbumSingleFileViewer: React.FC<PublicAlbumSingleFileViewerProps> = ({@@ -371,7 +366,7 @@ export const PublicAlbumSingleFileViewer: React.FC<useEffect(() => {if (!needsOriginalPrime) return;- // Give thumbnail fetch a brief head-start, then warm the original.+ // Let the thumbnail start before warming the original.const prefetchTimer = window.setTimeout(() => {void downloadManager.renderableSourceURLs(file)@@ -906,9 +901,6 @@ const FileViewerStyleButton = styled("button")`}`;-/**- * Return an "image/png" blob derived from the given source URL.- */const createImagePNGBlob = async (imageURL: string): Promise<Blob> =>new Promise((resolve, reject) => {const image = new Image();diff --git a/web/apps/albums/src/public-album/viewer/components/PublicCommentModal.tsx b/web/apps/albums/src/public-album/viewer/components/PublicCommentModal.tsxindex 5c7963269e..93806e7153 100644--- a/web/apps/albums/src/public-album/viewer/components/PublicCommentModal.tsx+++ b/web/apps/albums/src/public-album/viewer/components/PublicCommentModal.tsx@@ -11,10 +11,6 @@ import type { ModalVisibilityProps } from "ente-base/components/utils/modal";import { t } from "i18next";import React from "react";-// =============================================================================-// Icons-// =============================================================================-const CommentIllustration: React.FC = () => (<svgwidth="146"@@ -90,30 +86,12 @@ const CommentIllustration: React.FC = () => (</svg>);-// =============================================================================-// Types-// =============================================================================-export interface PublicCommentModalProps extends ModalVisibilityProps {- /**- * Called when user clicks "Comment anonymously".- */onCommentAnonymously: () => void;- /**- * Called when user clicks "Join album and comment".- */onJoinAlbumToComment: () => void;- /**- * Whether the "Join album" option is enabled for this public link.- * When false, the "Join album and comment" button will be hidden.- */enableJoin?: boolean;}-/**- * Modal dialog for commenting on a photo in a public album.- * Shows options to comment anonymously or sign in to comment.- */export const PublicCommentModal: React.FC<PublicCommentModalProps> = ({open,onClose,@@ -174,10 +152,6 @@ export const PublicCommentModal: React.FC<PublicCommentModalProps> = ({);};-// =============================================================================-// Styled Components-// =============================================================================-const StyledDialog = styled(Dialog)(({ theme }) => ({"& .MuiDialog-paper": {width: 381,diff --git a/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsxindex 84f4ea1f0e..5b0e4d0248 100644--- a/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsx+++ b/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsx@@ -35,10 +35,6 @@ import React, {useState,} from "react";-// =============================================================================-// Icons-// =============================================================================-const LikedPhotoIcon: React.FC = () => (<svgwidth="17"@@ -128,73 +124,34 @@ const LikedCommentIcon: React.FC<{ heartStroke?: string }> = ({</svg>);-// =============================================================================-// Types-// =============================================================================--/**- * Information about a feed item click for navigation purposes.- */export interface PublicFeedItemClickInfo {- /** The type of feed item. */type: PublicFeedItem["type"];- /** The file ID to navigate to. */fileID: number;- /**- * The comment ID to highlight (for comment-related items).- * For `replied_comment`, this is the reply's comment ID.- * For `liked_comment`, this is the target comment ID.- */commentID?: string;- /**- * Snapshot of resolved anonymous display names from the feed.- * This lets the viewer open with stable names instead of briefly falling- * back to anonymous placeholders before its own profile fetch completes.- */+ // Snapshot names so navigation does not flash anonymous placeholders.anonUserNames?: Map<string, string>;}export interface PublicFeedSidebarProps extends ModalVisibilityProps {- /**- * The files in the album, used to display thumbnails and determine file type.- */files?: EnteFile[];- /**- * Public album credentials for API access.- */credentials: PublicAlbumsCredentials;- /**- * The decrypted collection key (base64 encoded).- */collectionKey: string;- /**- * Called when a feed item is clicked for navigation.- */onItemClick?: (info: PublicFeedItemClickInfo) => void;- /**- * Called after the drawer finishes its close transition.- */onExited?: () => void;}-/** A user who performed an action in the feed. */interface FeedUser {userID: number;anonUserID?: string;userName: string;- /** Email/identifier used for avatar color. */email: string;}-/** Base interface for all feed items. */interface BaseFeedItem {- /** Unique identifier for this feed item (for React keys). */id: string;- /** Timestamp of the most recent action in this item. */timestamp: number;}-/** Someone liked a photo/video (grouped by file). */interface LikedFileFeedItem extends BaseFeedItem {type: "liked_photo" | "liked_video";fileID: number;@@ -202,29 +159,23 @@ interface LikedFileFeedItem extends BaseFeedItem {users: FeedUser[];}-/** Someone commented on a photo/video. */interface CommentedFileFeedItem extends BaseFeedItem {type: "commented_photo" | "commented_video";fileID: number;- /** The ID of the comment for navigation. */commentID: string;thumbnailURL?: string;user: FeedUser;}-/** Someone replied to a comment. */interface RepliedCommentFeedItem extends BaseFeedItem {type: "replied_comment";- /** The parent comment ID. */parentCommentID: string;- /** The ID of the reply for navigation. */replyID: string;fileID?: number;thumbnailURL?: string;user: FeedUser;}-/** Someone liked a comment (grouped by comment, includes reply likes). */interface LikedCommentFeedItem extends BaseFeedItem {type: "liked_comment";commentID: string;@@ -239,21 +190,10 @@ type PublicFeedItem =| RepliedCommentFeedItem| LikedCommentFeedItem;-/** Thumbnail URL cache for files. */type ThumbnailCache = Map<number, string>;-/** File type cache for determining photo vs video. */type FileTypeCache = Map<number, number>;-// =============================================================================-// Utility Functions-// =============================================================================--/**- * Get the display name for a user.- * For anonymous users, uses their entered name from userName.- * Falls back to "Anonymous" only if userName is empty.- */const getUserDisplayName = (userID: number,userName: string,@@ -265,15 +205,6 @@ const getUserDisplayName = (return userName;};-/**- * Process feed items from public album data.- *- * For public albums, we show ALL actions from everyone:- * - X liked a photo/video- * - A liked a comment (includes reply likes)- * - M commented on a photo/video- * - C replied to a comment- */const processFeedItems = (comments: PublicFeedComment[],reactions: PublicFeedReaction[],@@ -284,7 +215,6 @@ const processFeedItems = (): PublicFeedItem[] => {const feedItems: PublicFeedItem[] = [];- // Build a map from commentID to fileID for looking up comment likesconst commentFileIDMap = new Map<string, number>();for (const c of comments) {if (c.fileID) {@@ -292,7 +222,6 @@ const processFeedItems = (}}- // Helper to get display name for a userconst getUserName = (userID: number, anonUserID?: string): string => {if (anonUserID) {return (@@ -303,7 +232,6 @@ const processFeedItems = (return maskedEmails.get(userID) ?? t("unknown_user");};- // Helper to get avatar color keyconst getAvatarColorKey = (userID: number, anonUserID?: string): string => {if (anonUserID) {return anonUserNames.get(anonUserID) ?? anonUserID;@@ -311,18 +239,15 @@ const processFeedItems = (return maskedEmails.get(userID) ?? String(userID);};- // Helper to get thumbnail URL from cacheconst getThumbnailURL = (fileID: number | undefined): string | undefined =>fileID ? thumbnailCache.get(fileID) : undefined;- // Helper to determine if file is videoconst isVideo = (fileID: number | undefined): boolean => {if (!fileID) return false;const fileType = fileTypeCache.get(fileID);return fileType === FileType.video;};- // 1. Process comments - categorize as "commented_photo/video" or "replied_comment"for (const c of comments) {if (c.isDeleted) continue;@@ -330,7 +255,6 @@ const processFeedItems = (const avatarColorKey = getAvatarColorKey(c.userID, c.anonUserID);if (c.isReply && c.parentCommentID) {- // This is a reply to a commentfeedItems.push({id: `replied_comment_${c.id}`,type: "replied_comment",@@ -347,7 +271,6 @@ const processFeedItems = (},});} else if (c.fileID) {- // This is a comment on a photo/videoconst fileIsVideo = isVideo(c.fileID);feedItems.push({id: `commented_file_${c.id}`,@@ -366,13 +289,10 @@ const processFeedItems = (}}- // 2. Process reactions - group by file or comment- // Group file likes by fileIDconst fileLikes = new Map<number,{ users: FeedUser[]; latestTimestamp: number; isVideo: boolean }>();- // Group comment likes by commentID (includes reply likes)const commentLikes = new Map<string,{ users: FeedUser[]; latestTimestamp: number; fileID?: number }@@ -391,14 +311,12 @@ const processFeedItems = (};if (r.fileID && !r.commentID) {- // Reaction on a file (photo/video)const fileID = r.fileID;const existing = fileLikes.get(fileID);if (existing) {existing.users.push(user);if (r.createdAt > existing.latestTimestamp) {existing.latestTimestamp = r.createdAt;- // Move most recent user to frontexisting.users.pop();existing.users.unshift(user);}@@ -410,9 +328,7 @@ const processFeedItems = (});}} else if (r.commentID) {- // Reaction on a comment (treat reply likes as comment likes)const commentID = r.commentID;- // Look up fileID from comment if not present in reactionconst fileID = r.fileID || commentFileIDMap.get(commentID);const existing = commentLikes.get(commentID);if (existing) {@@ -432,7 +348,6 @@ const processFeedItems = (}}- // Add grouped file likes to feedfor (const [fileID, data] of fileLikes) {feedItems.push({id: `liked_file_${fileID}`,@@ -444,7 +359,6 @@ const processFeedItems = (});}- // Add grouped comment likes to feed (includes reply likes)for (const [commentID, data] of commentLikes) {feedItems.push({id: `liked_comment_${commentID}`,@@ -457,13 +371,9 @@ const processFeedItems = (});}- // Sort by timestamp (newest first)return feedItems.sort((a, b) => b.timestamp - a.timestamp);};-/**- * Get the action text for a feed item.- */const getActionText = (item: PublicFeedItem): string => {switch (item.type) {case "liked_photo":@@ -481,9 +391,6 @@ const getActionText = (item: PublicFeedItem): string => {}};-/**- * Get the users string for display (e.g., "John and 2 others").- */const getUsersDisplayText = (users: FeedUser[]): string => {if (users.length === 0) return "";const firstName = getUserDisplayName(@@ -498,9 +405,6 @@ const getUsersDisplayText = (users: FeedUser[]): string => {return `${firstName} and ${othersCount} ${othersCount === 1 ? "other" : "others"}`;};-/**- * Get the icon component for a feed item type.- */const getFeedIcon = (type: PublicFeedItem["type"],heartStroke: string,@@ -519,18 +423,11 @@ const getFeedIcon = (}};-// =============================================================================-// Feed Item Row Component-// =============================================================================-interface FeedItemRowProps {item: PublicFeedItem;onClick?: () => void;}-/**- * Get the users array from a feed item.- */const getFeedItemUsers = (item: PublicFeedItem): FeedUser[] => {switch (item.type) {case "commented_photo":@@ -544,9 +441,6 @@ const getFeedItemUsers = (item: PublicFeedItem): FeedUser[] => {}};-/**- * A single row in the feed showing an action.- */const FeedItemRow: React.FC<FeedItemRowProps> = ({ item, onClick }) => {const { mode, systemMode } = useColorScheme();const users = getFeedItemUsers(item);@@ -591,13 +485,6 @@ const FeedItemRow: React.FC<FeedItemRowProps> = ({ item, onClick }) => {);};-// =============================================================================-// Main Component-// =============================================================================--/**- * Extracts navigation info from a feed item for click handling.- */const getFeedItemClickInfo = (item: PublicFeedItem,anonUserNames: Map<string, string>,@@ -633,9 +520,6 @@ const getFeedItemClickInfo = (}};-/**- * A sidebar panel for displaying the activity feed for a public album.- */export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({open,onClose,@@ -685,7 +569,6 @@ export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({[],);- // Build file type cache from filesuseEffect(() => {if (!open) return;@@ -696,8 +579,7 @@ export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({setFileTypeCache(cache);}, [open, files]);- // Load thumbnails for active feed items in parallel and show each one as- // soon as it is ready instead of waiting for the entire batch to finish.+ // Publish each thumbnail as soon as it loads.useEffect(() => {if (!open || (comments.length === 0 && reactions.length === 0)) return;@@ -752,10 +634,9 @@ export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({);}, [open, comments, reactions, files]);- // Polling interval for refreshing feed data (5 seconds)const FEED_REFRESH_INTERVAL_MS = 5_000;- // Refresh social data (used for periodic refresh - excludes masked emails)+ // Masked participant emails are stable enough to fetch only on open.const refreshSocialData = useCallback(async () => {try {const [feedData, anonProfiles] = await Promise.all([@@ -765,14 +646,11 @@ export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({setComments(feedData.comments);setReactions(feedData.reactions);setAnonUserNames(anonProfiles);- // Note: Masked emails for registered participants are fetched only- // on initial load since they rarely change during a session.} catch (e) {log.error("Failed to refresh public album feed", e);}}, [credentials, collectionKey]);- // Initial fetch when sidebar opens (includes masked emails)useEffect(() => {if (!open) return;@@ -797,7 +675,6 @@ export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({void fetchInitialData().finally(() => setIsLoading(false));}, [open, credentials, collectionKey]);- // Periodic refresh while sidebar is openuseInterval(refreshSocialData,open && !isLoading ? FEED_REFRESH_INTERVAL_MS : null,@@ -880,13 +757,9 @@ export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({);};-// =============================================================================-// Styled Components-// =============================================================================--// Drawer & Layout+// Keep the feed above TripLayout controls at z-index 2000.const SidebarDrawer = styled(Drawer)(({ theme }) => ({- zIndex: 2100, // Above TripLayout nav buttons (z-index: 2000)+ zIndex: 2100,"& .MuiDrawer-paper": {width: "23vw",minWidth: "520px",@@ -965,7 +838,6 @@ const ContentContainer = styled(Box)(({ theme }) => ({}),}));-// Feed Item Componentsconst FeedItemContainer = styled(Box)(({ theme }) => ({display: "flex",alignItems: "flex-start",@@ -1057,12 +929,12 @@ const ThumbnailImage = styled("img")(() => ({flexShrink: 0,}));+// The negative margin centers these states below the 56px header offset.const LoadingContainer = styled(Box)(() => ({display: "flex",justifyContent: "center",alignItems: "center",height: "100%",- // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halvedmarginTop: -28,}));@@ -1071,7 +943,6 @@ const EmptyStateText = styled(Typography)(({ theme }) => ({justifyContent: "center",alignItems: "center",height: "100%",- // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halvedmarginTop: -28,color: "#666",...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.6)" }),diff --git a/web/apps/albums/src/public-album/viewer/components/PublicLikeModal.tsx b/web/apps/albums/src/public-album/viewer/components/PublicLikeModal.tsxindex 64d3006b09..a23fbd39e4 100644--- a/web/apps/albums/src/public-album/viewer/components/PublicLikeModal.tsx+++ b/web/apps/albums/src/public-album/viewer/components/PublicLikeModal.tsx@@ -11,10 +11,6 @@ import type { ModalVisibilityProps } from "ente-base/components/utils/modal";import { t } from "i18next";import React from "react";-// =============================================================================-// Icons-// =============================================================================-const LikeIllustration: React.FC = () => (<svgwidth="126"@@ -78,30 +74,12 @@ const LikeIllustration: React.FC = () => (</svg>);-// =============================================================================-// Types-// =============================================================================-export interface PublicLikeModalProps extends ModalVisibilityProps {- /**- * Called when user clicks "Like anonymously".- */onLikeAnonymously: () => void;- /**- * Called when user clicks "Join album to like".- */onJoinAlbumToLike: () => void;- /**- * Whether the "Join album" option is enabled for this public link.- * When false, the "Join album and like" button will be hidden.- */enableJoin?: boolean;}-/**- * Modal dialog for liking a photo in a public album.- * Shows options to like anonymously or sign in to like.- */export const PublicLikeModal: React.FC<PublicLikeModalProps> = ({open,onClose,@@ -162,10 +140,6 @@ export const PublicLikeModal: React.FC<PublicLikeModalProps> = ({);};-// =============================================================================-// Styled Components-// =============================================================================-const StyledDialog = styled(Dialog)(({ theme }) => ({"& .MuiDialog-paper": {width: 381,