Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

[space][web] Improve post and comment interactions

Anand Baburajan6acb2922e25b
diff --git a/web/apps/space/src/components/CommentComposer.tsx b/web/apps/space/src/components/CommentComposer.tsx
index 5187372271..be80e4f5cc 100644
--- a/web/apps/space/src/components/CommentComposer.tsx
+++ b/web/apps/space/src/components/CommentComposer.tsx
@@ -1,11 +1,6 @@
import { Navigation03Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { Box } from "@mui/material";
-import {
- spaceActionDoneDurationMs,
- SpaceActionFeedbackIcon,
- type SpaceActionPhase,
-} from "components/ActionFeedback";
import React from "react";
import {
spaceControlBackground,
@@ -101,7 +96,7 @@ export const SpaceCommentComposer: React.FC<{
const [localText, setLocalText] = React.useState("");
const text = draftText ?? localText;
const setText = onTextChange ?? setLocalText;
- const [phase, setPhase] = React.useState<SpaceActionPhase | null>(null);
+ const [isSending, setIsSending] = React.useState(false);
const [error, setError] = React.useState(false);
const internalRef = React.useRef<HTMLTextAreaElement>(null);
const ref = inputRef ?? internalRef;
@@ -111,25 +106,17 @@ export const SpaceCommentComposer: React.FC<{
input.style.height = "46px";
input.style.height = `${Math.min(input.scrollHeight, 112)}px`;
}, [ref, text]);
- React.useEffect(() => {
- if (phase != "done") return;
- const timer = window.setTimeout(
- () => setPhase(null),
- spaceActionDoneDurationMs,
- );
- return () => window.clearTimeout(timer);
- }, [phase]);
const send = async () => {
- if (!text.trim() || phase || disabled || sendDisabled) return;
- setPhase("busy");
+ if (!text.trim() || isSending || disabled || sendDisabled) return;
+ setIsSending(true);
setError(false);
try {
await onSend(text);
if (!onTextChange) setLocalText("");
- setPhase("done");
} catch {
setError(true);
- setPhase(null);
+ } finally {
+ setIsSending(false);
}
};
return (
@@ -163,7 +150,7 @@ export const SpaceCommentComposer: React.FC<{
placeholder={placeholder}
rows={1}
value={text}
- disabled={disabled || phase != null}
+ disabled={disabled || isSending}
onChange={(event) =>
setText(clampSpaceMessageText(event.target.value))
}
@@ -194,28 +181,24 @@ export const SpaceCommentComposer: React.FC<{
"&::placeholder": { color: spaceTextMuted },
}}
/>
- {(text.trim() || phase) && (
+ {text.trim() && (
<Box
component="button"
type="submit"
- className={phase == "done" ? undefined : "green-bg"}
+ className="green-bg"
aria-label={
- phase == "done"
- ? "Comment sent"
- : phase == "busy"
- ? "Sending comment"
- : "Send comment"
+ isSending ? "Sending comment" : "Send comment"
}
- disabled={disabled || sendDisabled || phase != null}
+ disabled={disabled || sendDisabled || isSending}
+ onPointerDown={(event) => event.preventDefault()}
sx={{
alignItems: "center",
- bgcolor:
- phase == "done" ? "transparent" : "#08C225",
+ bgcolor: "#08C225",
border: 0,
borderRadius: "50%",
color: spaceText,
cursor:
- disabled || sendDisabled || phase
+ disabled || sendDisabled || isSending
? "default"
: "pointer",
display: "flex",
@@ -225,23 +208,17 @@ export const SpaceCommentComposer: React.FC<{
m: "5px",
width: 36,
opacity:
- (disabled || sendDisabled) && !phase ? 0.4 : 1,
+ disabled || sendDisabled || isSending ? 0.4 : 1,
"&:focus-visible": {
outline: "2px solid #08C225",
outlineOffset: 2,
},
}}
>
- <SpaceActionFeedbackIcon
- phase={phase}
- size={22}
- idleIcon={
- <HugeiconsIcon
- icon={Navigation03Icon}
- size={20}
- strokeWidth={1.8}
- />
- }
+ <HugeiconsIcon
+ icon={Navigation03Icon}
+ size={20}
+ strokeWidth={1.8}
/>
</Box>
)}
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsx
index 61ca31a9d5..496d8f11ae 100644
--- a/web/apps/space/src/components/FileViewer.tsx
+++ b/web/apps/space/src/components/FileViewer.tsx
@@ -2913,6 +2913,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
{commentsOpen && canComment && (
<PostComments
key={activePhoto.postId}
+ container={() => viewerRootRef.current}
autoFocus={focusCommentOnOpen}
targetCommentId={targetCommentId}
viewer={profile!.spaceId!}
diff --git a/web/apps/space/src/components/PostComments.tsx b/web/apps/space/src/components/PostComments.tsx
index 2a666db029..b9332f5cb3 100644
--- a/web/apps/space/src/components/PostComments.tsx
+++ b/web/apps/space/src/components/PostComments.tsx
@@ -30,7 +30,6 @@ import { emojiName } from "data/emojis";
import type { FriendProfile } from "data/friends";
import log from "ente-base/log";
import { useBrowserBackClose } from "hooks/use-browser-back-close";
-import { isSpaceIOS } from "hooks/use-pwa-install-prompt";
import React from "react";
import { flushSync } from "react-dom";
import {
@@ -46,7 +45,6 @@ import {
import {
spaceControlBackgroundHover,
spaceDialogBackground,
- spaceSurface,
spaceText,
spaceTextMuted,
} from "styles/colors";
@@ -173,6 +171,7 @@ const CommentRow: React.FC<{
disabled: boolean;
ownReaction: string | undefined;
onReact: (emoji: string) => void;
+ onReply: () => void;
onOpenReactions: () => void;
onOpenActions: (
anchor: HTMLElement,
@@ -186,14 +185,27 @@ const CommentRow: React.FC<{
disabled,
ownReaction,
onReact,
+ onReply,
onOpenReactions,
onOpenActions,
}) => {
const timer = React.useRef<number | undefined>(undefined);
const start = React.useRef<
- { pointerId: number; x: number; y: number } | undefined
+ | {
+ pointerId: number;
+ x: number;
+ y: number;
+ canReply: boolean;
+ active: boolean;
+ thresholdPx: number;
+ maxOffsetPx: number;
+ resistancePx: number;
+ }
+ | undefined
>(undefined);
const didOpen = React.useRef(false);
+ const didSwipe = React.useRef(false);
+ const [swipeOffset, setSwipeOffset] = React.useState(0);
const canOpenActions = !disabled && !comment.deleted;
const reactions = commentReactionGroups(comment.reactions, ownReaction);
const reactionColumns = Math.min(reactions.length, 6);
@@ -208,14 +220,18 @@ const CommentRow: React.FC<{
const clearLongPress = React.useCallback(() => {
window.clearTimeout(timer.current);
timer.current = undefined;
- start.current = undefined;
}, []);
React.useEffect(() => clearLongPress, [clearLongPress]);
+ const cancelGesture = () => {
+ clearLongPress();
+ start.current = undefined;
+ setSwipeOffset(0);
+ };
const openContextAction = (
anchor: HTMLElement,
source: "touch" | "contextmenu",
) => {
- clearLongPress();
+ cancelGesture();
window.getSelection()?.removeAllRanges();
if (anchor.hasAttribute("data-comment-reaction")) onOpenReactions();
else onOpenActions(anchor, source);
@@ -251,6 +267,7 @@ const CommentRow: React.FC<{
}}
onKeyDown={(event) => {
didOpen.current = false;
+ didSwipe.current = false;
const reaction = reactionTarget(event.target);
if (
!canOpenActions ||
@@ -270,20 +287,43 @@ const CommentRow: React.FC<{
}
}}
onPointerDown={(event) => {
- clearLongPress();
+ cancelGesture();
didOpen.current = false;
+ didSwipe.current = false;
const reaction = reactionTarget(event.target);
if (
!canOpenActions ||
+ !event.isPrimary ||
event.button != 0 ||
- (isInteractiveTarget(event.target) && !reaction)
+ (event.pointerType != "touch" &&
+ isInteractiveTarget(event.target) &&
+ !reaction)
)
return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ const availableRightPx = Math.max(
+ 0,
+ Math.min(window.innerWidth - 8, rect.right + 8) -
+ event.clientX,
+ );
+ const resistancePx = rect.width * 0.42;
start.current = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY,
+ canReply: event.pointerType == "touch",
+ active: false,
+ thresholdPx: Math.min(
+ 64,
+ Math.max(20, availableRightPx * 0.65),
+ availableRightPx,
+ ),
+ maxOffsetPx:
+ resistancePx *
+ Math.log1p(availableRightPx / resistancePx),
+ resistancePx,
};
+ if (isInteractiveTarget(event.target) && !reaction) return;
const anchor = reaction ?? event.currentTarget;
anchor.setPointerCapture(event.pointerId);
timer.current = window.setTimeout(() => {
@@ -292,33 +332,63 @@ const CommentRow: React.FC<{
}, 520);
}}
onPointerMove={(event) => {
- if (start.current?.pointerId != event.pointerId) return;
- if (
- Math.hypot(
- event.clientX - start.current.x,
- event.clientY - start.current.y,
- ) > 10
- )
- clearLongPress();
+ const gesture = start.current;
+ if (gesture?.pointerId != event.pointerId) return;
+ const dx = event.clientX - gesture.x;
+ const dy = event.clientY - gesture.y;
+ if (Math.hypot(dx, dy) > 10) clearLongPress();
+ if (!gesture.canReply || !canOpenActions) return;
+ if (!gesture.active) {
+ if (
+ (Math.abs(dy) > 10 && Math.abs(dy) >= Math.abs(dx)) ||
+ dx < -10
+ ) {
+ cancelGesture();
+ return;
+ }
+ if (dx <= 10 || dx <= Math.abs(dy) * 1.2) return;
+ gesture.active = true;
+ didSwipe.current = true;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }
+ setSwipeOffset(
+ Math.min(
+ gesture.maxOffsetPx,
+ gesture.resistancePx *
+ Math.log1p(Math.max(dx, 0) / gesture.resistancePx),
+ ),
+ );
}}
onPointerUp={(event) => {
- clearLongPress();
+ const gesture = start.current;
+ if (gesture && gesture.pointerId != event.pointerId) return;
+ cancelGesture();
if (didOpen.current) {
event.preventDefault();
event.stopPropagation();
+ return;
}
+ if (!gesture?.active || !canOpenActions) return;
+ const dx = event.clientX - gesture.x;
+ const dy = event.clientY - gesture.y;
+ if (dx < gesture.thresholdPx || dx <= Math.abs(dy) * 1.2)
+ return;
+ if (event.cancelable) event.preventDefault();
+ event.stopPropagation();
+ onReply();
}}
- onPointerCancel={clearLongPress}
+ onPointerCancel={cancelGesture}
onTouchEnd={(event) => {
- if (!didOpen.current) return;
+ if (!didOpen.current && !didSwipe.current) return;
if (event.cancelable) event.preventDefault();
event.stopPropagation();
}}
onClickCapture={(event) => {
- if (!didOpen.current) return;
+ if (!didOpen.current && !didSwipe.current) return;
event.preventDefault();
event.stopPropagation();
didOpen.current = false;
+ didSwipe.current = false;
}}
sx={{
bgcolor: highlighted
@@ -329,7 +399,7 @@ const CommentRow: React.FC<{
? `${commentEnter} 240ms ease-out`
: undefined,
position: "relative",
- py: 1,
+ py: 0.75,
px: 2,
flexShrink: 0,
cursor: canOpenActions ? "context-menu" : "default",
@@ -347,12 +417,38 @@ const CommentRow: React.FC<{
},
}}
>
+ {canOpenActions && (
+ <Box
+ aria-hidden
+ sx={{
+ alignItems: "center",
+ color: "#888888",
+ display: "flex",
+ height: "100%",
+ justifyContent: "center",
+ left: comment.parentId ? 56 : 16,
+ opacity: Math.min(swipeOffset / 24, 1),
+ position: "absolute",
+ top: 0,
+ width: 40,
+ "& svg": { height: 12, width: 16 },
+ }}
+ >
+ <ReplyIcon />
+ </Box>
+ )}
<Box
sx={{
position: "relative",
pl: 5,
ml: comment.parentId ? 5 : 0,
containerType: "inline-size",
+ transform: `translateX(${swipeOffset}px)`,
+ transition:
+ swipeOffset > 0 ? "none" : "transform 160ms ease-out",
+ "@media (prefers-reduced-motion: reduce)": {
+ transition: "none",
+ },
}}
>
<Box
@@ -471,13 +567,8 @@ const CommentRow: React.FC<{
aria-hidden
sx={{
alignItems: "center",
- bgcolor: isOwn
- ? "#233C28"
- : spaceSurface,
+ bgcolor: isOwn ? "#28462F" : "#333333",
borderRadius: "999px",
- boxShadow: isOwn
- ? "inset 0 0 0 1px #08C225"
- : undefined,
display: "flex",
gap: 0.5,
height: 24,
@@ -503,6 +594,9 @@ const CommentRow: React.FC<{
<Box
component="span"
sx={{
+ color: isOwn
+ ? "#A1D5AB"
+ : "#C2C2C2",
fontVariantNumeric: "tabular-nums",
}}
>
@@ -519,6 +613,7 @@ const CommentRow: React.FC<{
};
export const PostComments: React.FC<{
+ container: () => HTMLElement | null;
autoFocus?: boolean;
targetCommentId?: string;
viewer: string;
@@ -528,6 +623,7 @@ export const PostComments: React.FC<{
setDraft: React.Dispatch<React.SetStateAction<CommentDraft>>;
onClose: () => void;
}> = ({
+ container,
autoFocus,
targetCommentId,
viewer,
@@ -877,6 +973,7 @@ export const PostComments: React.FC<{
?.emoji
}
onReact={(emoji) => react(comment, emoji)}
+ onReply={() => replyTo(comment)}
onOpenReactions={() =>
setAction({
type: "reactions",
@@ -899,6 +996,7 @@ export const PostComments: React.FC<{
);
return (
<Dialog
+ container={container}
open={open}
onClose={() => setOpen(false)}
maxWidth={false}
@@ -913,13 +1011,15 @@ export const PostComments: React.FC<{
"--space-dialog-backdrop": "rgba(0 0 0 / 0.64)",
"& .MuiDialog-container": {
alignItems: "flex-end",
- pb: isSpaceIOS() ? "var(--space-keyboard-inset, 0px)" : 0,
+ pb: "var(--space-keyboard-inset, 0px)",
},
}}
slotProps={{
container: { ref: dialogContainer },
paper: {
style: {
+ maxHeight:
+ "calc(100dvh - var(--space-keyboard-inset, 0px) - env(safe-area-inset-top) - 16px)",
translate: `0 ${dragOffset}px`,
transition:
isDragging || prefersReducedMotion
@@ -936,9 +1036,6 @@ export const PostComments: React.FC<{
flexDirection: "column",
height: "min(72dvh, 640px)",
m: 0,
- maxHeight: isSpaceIOS()
- ? "calc(100dvh - var(--space-keyboard-inset, 0px) - env(safe-area-inset-top) - 16px)"
- : "calc(100dvh - env(safe-area-inset-top) - 16px)",
maxWidth: { xs: "none", sm: 480 },
overflow: "hidden",
width: "100%",
@@ -1054,6 +1151,7 @@ export const PostComments: React.FC<{
py: 0.5,
display: "flex",
flexDirection: "column",
+ overflowX: "hidden",
overflowY: "auto",
overscrollBehavior: "contain",
flex: "1 1 auto",
@@ -1134,7 +1232,7 @@ export const PostComments: React.FC<{
sx={{
flexShrink: 0,
py: 0.5,
- mt: index > 0 ? 1 : 0,
+ mt: index > 0 ? 0.75 : 0,
}}
>
{renderComment(comment)}
@@ -1143,8 +1241,8 @@ export const PostComments: React.FC<{
sx={{
display: "flex",
flexDirection: "column",
- gap: 0.5,
- mt: 0.5,
+ gap: 0.25,
+ mt: 0.25,
}}
>
{replies.map(renderComment)}
@@ -1213,15 +1311,12 @@ export const PostComments: React.FC<{
? "Comment instead"
: "Cancel reply"
}
- onCancel={() => {
- flushSync(() =>
- setDraft((value) => ({
- ...value,
- replyTarget: undefined,
- })),
- );
- input.current?.focus({ preventScroll: true });
- }}
+ onCancel={() =>
+ setDraft((value) => ({
+ ...value,
+ replyTarget: undefined,
+ }))
+ }
/>
)}
<SpaceCommentComposer
@@ -1470,7 +1565,7 @@ export const PostComments: React.FC<{
container={() => dialogContainer.current}
transition
modifiers={[
- { name: "offset", options: { offset: [0, 8] } },
+ { name: "offset", options: { offset: [16, 8] } },
{
name: "preventOverflow",
options: {
diff --git a/web/apps/space/src/components/PostLikes.tsx b/web/apps/space/src/components/PostLikes.tsx
index 42d50ccb8c..9a293973f6 100644
--- a/web/apps/space/src/components/PostLikes.tsx
+++ b/web/apps/space/src/components/PostLikes.tsx
@@ -1,6 +1,6 @@
import { FavouriteIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { Box, Dialog, Skeleton, useMediaQuery } from "@mui/material";
+import { Box, CircularProgress, Dialog, useMediaQuery } from "@mui/material";
import { SpaceActivityAvatar } from "components/ActivityList";
import { SpaceBottomSheetTransition } from "components/BottomSheetTransition";
import type { FriendProfile } from "data/friends";
@@ -224,7 +224,7 @@ export const SpacePostLikes = ({
display: "flex",
flexDirection: "column",
fontFamily: '"Inter Variable", Inter, sans-serif',
- height: "min(72dvh, 640px)",
+ height: "min(40dvh, 360px)",
left: 0,
m: 0,
maxHeight:
@@ -384,26 +384,19 @@ export const SpacePostLikes = ({
</Box>
</Box>
) : !actors ? (
- <Box role="status" aria-label="Loading likes">
- {[0, 1, 2].map((index) => (
- <Box
- key={index}
- sx={{
- alignItems: "center",
- display: "flex",
- gap: "12px",
- minHeight: 56,
- py: "8px",
- }}
- >
- <Skeleton
- variant="circular"
- width={32}
- height={32}
- />
- <Skeleton width={120} height={24} />
- </Box>
- ))}
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ height: "100%",
+ justifyContent: "center",
+ }}
+ >
+ <CircularProgress
+ aria-label="Loading likes"
+ size={20}
+ sx={{ color: spaceTextMuted }}
+ />
</Box>
) : actors.length == 0 ? (
<Box
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index 9dd1ca7d92..5ab14da4a9 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -914,6 +914,8 @@ const FeedItem: React.FC<FeedItemProps> = ({
dragging: boolean;
} | null>(null);
const suppressPhotoClickRef = React.useRef(false);
+ const photoClickTimeoutRef =
+ React.useRef<ReturnType<typeof setTimeout>>(undefined);
const scrollToPhoto = React.useCallback(
(index: number) => {
const carousel = carouselRef.current;
@@ -970,6 +972,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
() => () => {
if (photoAnimationRef.current != null)
cancelAnimationFrame(photoAnimationRef.current);
+ clearTimeout(photoClickTimeoutRef.current);
},
[],
);
@@ -1374,6 +1377,8 @@ const FeedItem: React.FC<FeedItemProps> = ({
if (!swipe.dragging) {
if (Math.max(Math.abs(dx), Math.abs(dy)) < 8)
return;
+ clearTimeout(photoClickTimeoutRef.current);
+ photoClickTimeoutRef.current = undefined;
if (Math.abs(dy) >= Math.abs(dx)) {
swipeRef.current = null;
scrollToPhoto(swipe.index);
@@ -1397,15 +1402,39 @@ const FeedItem: React.FC<FeedItemProps> = ({
);
}}
onPointerUp={finishPhotoSwipe}
- onPointerCancel={finishPhotoSwipe}
+ onPointerCancel={(event) => {
+ clearTimeout(photoClickTimeoutRef.current);
+ photoClickTimeoutRef.current = undefined;
+ finishPhotoSwipe(event);
+ }}
onClickCapture={(event) => {
- if (!suppressPhotoClickRef.current || event.detail == 0)
+ if (event.detail == 0) return;
+ if (suppressPhotoClickRef.current) {
+ suppressPhotoClickRef.current = false;
+ event.preventDefault();
+ event.stopPropagation();
return;
- suppressPhotoClickRef.current = false;
+ }
+ if (isOwnPost || !showFooter) return;
event.preventDefault();
event.stopPropagation();
+ if (photoClickTimeoutRef.current != undefined) {
+ clearTimeout(photoClickTimeoutRef.current);
+ photoClickTimeoutRef.current = undefined;
+ if (!isLiked) handleLikeClick();
+ return;
+ }
+ const target = (event.target as Element).closest<
+ HTMLButtonElement | HTMLVideoElement
+ >("button, video");
+ photoClickTimeoutRef.current = setTimeout(() => {
+ photoClickTimeoutRef.current = undefined;
+ target?.click();
+ }, 180);
}}
onScroll={(event) => {
+ clearTimeout(photoClickTimeoutRef.current);
+ photoClickTimeoutRef.current = undefined;
const carousel = event.currentTarget;
paintStretchingDot(
rootRef.current!,
diff --git a/web/apps/space/tests/comment-mutations.test.tsx b/web/apps/space/tests/comment-mutations.test.tsx
index 1d8225da83..f7b32e30fa 100644
--- a/web/apps/space/tests/comment-mutations.test.tsx
+++ b/web/apps/space/tests/comment-mutations.test.tsx
@@ -1,5 +1,5 @@
import React, { type EffectCallback, type SetStateAction } from "react";
-import { beforeEach, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { PostComments } from "../src/components/PostComments";
import type { SpaceComment } from "../src/services/space";
import type { CommentDraft } from "../src/utils/comments";
@@ -79,7 +79,6 @@ vi.mock("data/emojis", () => ({ emojiName: () => "emoji" }));
vi.mock("hooks/use-browser-back-close", () => ({
useBrowserBackClose: vi.fn(),
}));
-vi.mock("hooks/use-pwa-install-prompt", () => ({ isSpaceIOS: () => false }));
vi.mock("styles/colors", () => import("../src/styles/colors"));
vi.mock("utils/route-transitions", () => ({ useSpaceRouter: vi.fn() }));
vi.mock("services/space", () => ({
@@ -128,6 +127,7 @@ const render = () => {
mocks.index = 0;
return elements(
PostComments({
+ container: () => null,
viewer: "viewer",
owner: "owner",
postId: 42,
@@ -168,6 +168,11 @@ beforeEach(async () => {
await vi.waitFor(() => expect(composer().props.sendDisabled).toBe(false));
});
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
test("a lost creation response keeps the submission ID through reopening and retry", async () => {
mocks.create.mockRejectedValueOnce(new Error("Response lost"));
await expect(
@@ -251,3 +256,315 @@ test("a failed refresh still disables the unavailable discussion after a mutatio
"Discussion unavailable. Access may have changed or the post may have been deleted.",
);
});
+
+test.each(["selected", "unavailable"] as const)(
+ "cancelling a %s reply preserves the draft without focusing the input",
+ (status) => {
+ draft.replyTarget =
+ status == "selected"
+ ? { status, commentId: comment.commentId }
+ : { status };
+ const focus = vi.fn();
+ const inputRef = composer().props.inputRef as React.RefObject<{
+ focus: typeof focus;
+ }>;
+ inputRef.current = { focus };
+ const preview = render().find((node) => node.type == "preview")!;
+
+ (preview.props.onCancel as () => void)();
+
+ expect(draft.replyTarget).toBeUndefined();
+ expect(draft.text).toBe("New comment");
+ expect(focus).not.toHaveBeenCalled();
+ expect(composer().props.disabled).toBeFalsy();
+ expect(composer().props.placeholder).toBe("Add a comment…");
+ expect(render().find((node) => node.type == "preview")).toBeUndefined();
+ },
+);
+
+const commentGesture = (
+ overrides: Record<string, unknown> = {},
+ commentId = comment.commentId,
+) => {
+ vi.useFakeTimers();
+ class Target {
+ constructor(readonly kind: "body" | "button" | "reaction" = "body") {}
+ closest(selector: string) {
+ return (
+ selector == "a, button"
+ ? this.kind != "body"
+ : this.kind == "reaction"
+ )
+ ? this
+ : null;
+ }
+ hasAttribute() {
+ return this.kind == "reaction";
+ }
+ getBoundingClientRect() {
+ return { width: 390, right: 390 };
+ }
+ setPointerCapture = vi.fn();
+ }
+ vi.stubGlobal("Element", Target);
+ vi.stubGlobal("window", {
+ innerWidth: 390,
+ setTimeout,
+ clearTimeout,
+ getSelection: () => null,
+ });
+ const parent = render();
+ const focus = vi.fn();
+ const inputRef = parent.find((node) => node.type == "composer")!.props
+ .inputRef as React.RefObject<{ focus: typeof focus }>;
+ inputRef.current = { focus };
+ const element = parent.find(
+ (node) =>
+ (node.props.comment as SpaceComment | undefined)?.commentId ==
+ commentId,
+ )!;
+ const Component = element.type as (
+ props: Record<string, unknown>,
+ ) => Element;
+ const hookOffset = mocks.index;
+ const row = () => {
+ mocks.index = hookOffset;
+ return Component({ ...element.props, ...overrides });
+ };
+ const target = new Target();
+ const pointer = (
+ type:
+ | "onPointerDown"
+ | "onPointerMove"
+ | "onPointerUp"
+ | "onPointerCancel",
+ x: number,
+ y = 0,
+ options: Record<string, unknown> = {},
+ ) => {
+ const event = {
+ pointerId: 1,
+ pointerType: "touch",
+ isPrimary: true,
+ button: 0,
+ clientX: x,
+ clientY: y,
+ target,
+ currentTarget: target,
+ cancelable: true,
+ preventDefault: vi.fn(),
+ stopPropagation: vi.fn(),
+ ...options,
+ };
+ (row().props[type] as (event: unknown) => void)(event);
+ return event;
+ };
+ const click = (target: Target) => {
+ const event = {
+ target,
+ preventDefault: vi.fn(),
+ stopPropagation: vi.fn(),
+ };
+ (row().props.onClickCapture as (event: unknown) => void)(event);
+ return event;
+ };
+ return { focus, pointer, click, Target };
+};
+
+test("swiping a comment right selects it for reply and focuses the existing draft", () => {
+ const { pointer, focus } = commentGesture();
+ pointer("onPointerDown", 100);
+ pointer("onPointerMove", 180);
+ expect(draft.replyTarget).toBeUndefined();
+ pointer("onPointerUp", 180);
+ expect(draft.replyTarget).toEqual({
+ status: "selected",
+ commentId: "comment",
+ });
+ expect(draft.text).toBe("New comment");
+ expect(focus).toHaveBeenCalledWith({ preventScroll: true });
+ vi.runAllTimers();
+ expect(render().find((node) => node.type == "popper")!.props.open).toBe(
+ false,
+ );
+});
+
+test("swiping a threaded reply selects that reply rather than the root comment", async () => {
+ const reply: SpaceComment = {
+ ...comment,
+ commentId: "nested-reply",
+ parentId: "comment",
+ replyToId: "comment",
+ };
+ mocks.hooks = [];
+ mocks.effects = [];
+ mocks.load.mockResolvedValue([comment, reply]);
+ render();
+ mocks.effects[0]!();
+ await vi.waitFor(() => expect(composer().props.sendDisabled).toBe(false));
+ const { pointer } = commentGesture({}, reply.commentId);
+ pointer("onPointerDown", 100);
+ pointer("onPointerMove", 180);
+ pointer("onPointerUp", 180);
+ expect(draft.replyTarget).toEqual({
+ status: "selected",
+ commentId: "nested-reply",
+ });
+});
+
+test.each([
+ ["short", 130, 0],
+ ["leftward", 20, 0],
+ ["vertical", 110, 80],
+ ["diagonal", 180, 100],
+] as const)(
+ "a %s drag does not reply or open the long-press menu",
+ (_, x, y) => {
+ const { pointer, focus } = commentGesture();
+ pointer("onPointerDown", 100);
+ pointer("onPointerMove", x, y);
+ pointer("onPointerUp", x, y);
+ vi.runAllTimers();
+ expect(draft.replyTarget).toBeUndefined();
+ expect(focus).not.toHaveBeenCalled();
+ expect(render().find((node) => node.type == "popper")!.props.open).toBe(
+ false,
+ );
+ },
+);
+
+test("a swipe near the right edge uses the available space", () => {
+ const { pointer } = commentGesture();
+ pointer("onPointerDown", 350);
+ pointer("onPointerMove", 375);
+ pointer("onPointerUp", 375);
+ expect(draft.replyTarget).toEqual({
+ status: "selected",
+ commentId: "comment",
+ });
+});
+
+test("cancelled swipes and unrelated pointer releases do not reply", () => {
+ const { pointer } = commentGesture();
+ pointer("onPointerDown", 100);
+ pointer("onPointerMove", 180);
+ pointer("onPointerUp", 180, 0, { pointerId: 2 });
+ expect(draft.replyTarget).toBeUndefined();
+ pointer("onPointerCancel", 180);
+ pointer("onPointerUp", 180);
+ expect(draft.replyTarget).toBeUndefined();
+});
+
+test.each(["mouse", "pen"])(
+ "%s dragging does not trigger a touch reply",
+ (pointerType) => {
+ const { pointer } = commentGesture();
+ pointer("onPointerDown", 100, 0, { pointerType });
+ pointer("onPointerMove", 180, 0, { pointerType });
+ pointer("onPointerUp", 180, 0, { pointerType });
+ expect(draft.replyTarget).toBeUndefined();
+ },
+);
+
+test.each(["button", "reaction"] as const)(
+ "swiping from a %s replies without activating the original control",
+ (kind) => {
+ const { pointer, click, Target } = commentGesture();
+ const target = new Target(kind);
+ pointer("onPointerDown", 100, 0, { target });
+ pointer("onPointerMove", 180, 0, { target });
+ pointer("onPointerUp", 180, 0, { target });
+ expect(draft.replyTarget).toEqual({
+ status: "selected",
+ commentId: "comment",
+ });
+ const event = click(target);
+ expect(event.preventDefault).toHaveBeenCalled();
+ expect(event.stopPropagation).toHaveBeenCalled();
+ },
+);
+
+test.each(["button", "reaction"] as const)(
+ "tapping a %s still activates the control without replying",
+ (kind) => {
+ const { pointer, click, Target } = commentGesture();
+ const target = new Target(kind);
+ const down = pointer("onPointerDown", 100, 0, { target });
+ pointer("onPointerUp", 100, 0, { target });
+ expect(down.currentTarget.setPointerCapture).not.toHaveBeenCalled();
+ const event = click(target);
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(event.stopPropagation).not.toHaveBeenCalled();
+ expect(draft.replyTarget).toBeUndefined();
+ },
+);
+
+test("a short horizontal drag on a control does not activate it or reply", () => {
+ const { pointer, click, Target } = commentGesture();
+ const target = new Target("button");
+ pointer("onPointerDown", 100, 0, { target });
+ pointer("onPointerMove", 130, 0, { target });
+ pointer("onPointerUp", 130, 0, { target });
+ const event = click(target);
+ expect(event.preventDefault).toHaveBeenCalled();
+ expect(event.stopPropagation).toHaveBeenCalled();
+ expect(draft.replyTarget).toBeUndefined();
+});
+
+test.each(["button", "reaction"] as const)(
+ "a vertical drag starting on a %s scrolls without replying",
+ (kind) => {
+ const { pointer, Target } = commentGesture();
+ const target = new Target(kind);
+ pointer("onPointerDown", 100, 0, { target });
+ const move = pointer("onPointerMove", 110, 80, { target });
+ pointer("onPointerUp", 110, 80, { target });
+ expect(move.preventDefault).not.toHaveBeenCalled();
+ vi.runAllTimers();
+ expect(draft.replyTarget).toBeUndefined();
+ },
+);
+
+test.each([{ disabled: true }, { comment: { ...comment, deleted: true } }])(
+ "inactive comments cannot be swiped to reply",
+ (overrides) => {
+ const { pointer } = commentGesture(overrides);
+ pointer("onPointerDown", 100);
+ pointer("onPointerMove", 180);
+ pointer("onPointerUp", 180);
+ expect(draft.replyTarget).toBeUndefined();
+ },
+);
+
+test("long-pressing still opens comment actions without replying", () => {
+ const { pointer } = commentGesture();
+ pointer("onPointerDown", 100);
+ vi.advanceTimersByTime(520);
+ pointer("onPointerMove", 180);
+ const release = pointer("onPointerUp", 180);
+ expect(release.preventDefault).toHaveBeenCalled();
+ expect(draft.replyTarget).toBeUndefined();
+ expect(render().find((node) => node.type == "popper")!.props.open).toBe(
+ true,
+ );
+});
+
+test("replying from the long-press menu focuses the input and preserves the draft", () => {
+ const { pointer, focus } = commentGesture();
+ pointer("onPointerDown", 100);
+ vi.advanceTimersByTime(520);
+ pointer("onPointerUp", 100);
+ const reply = render().find((node) => node.props.label == "Reply")!;
+
+ (reply.props.onClick as () => void)();
+
+ expect(draft.replyTarget).toEqual({
+ status: "selected",
+ commentId: comment.commentId,
+ });
+ expect(draft.text).toBe("New comment");
+ expect(focus).toHaveBeenCalledWith({ preventScroll: true });
+ expect(render().find((node) => node.type == "popper")!.props.open).toBe(
+ false,
+ );
+});