Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(issues): preserve in-progress annotation drafts and yield landing scroll on user input (MUL-9818) (#11165)

Jiayuan Zhang812cecb2430d
diff --git a/packages/core/issues/stores/comment-draft-store.test.ts b/packages/core/issues/stores/comment-draft-store.test.ts
index dcf6f938ef..1386505954 100644
--- a/packages/core/issues/stores/comment-draft-store.test.ts
+++ b/packages/core/issues/stores/comment-draft-store.test.ts
@@ -454,4 +454,28 @@ describe("reply annotations", () => {
setCurrentWorkspace(null, null);
});
+ it("persists an in-progress pending annotation across rehydration and clears it on dismiss or clearDraft", async () => {
+ const store = useCommentDraftStore.getState();
+ store.setPendingAnnotation(key, { annotation, existing: false });
+ expect(store.getAnnotations(key)).toHaveLength(0);
+ expect(useCommentDraftStore.getState().drafts[key]?.replyTarget).toBeUndefined();
+ expect(store.getPendingAnnotation(key)).toEqual({ annotation, existing: false });
+
+ const before = useCommentDraftStore.getState().drafts[key];
+ store.setPendingAnnotation(key, { annotation: { ...annotation }, existing: false });
+ expect(useCommentDraftStore.getState().drafts[key]).toBe(before);
+
+ await flush();
+ useCommentDraftStore.getState().drafts = {};
+ await useCommentDraftStore.persist.rehydrate();
+ expect(useCommentDraftStore.getState().getPendingAnnotation(key)).toEqual({ annotation, existing: false });
+
+ useCommentDraftStore.getState().clearPendingAnnotation(key);
+ expect(useCommentDraftStore.getState().drafts[key]).toBeUndefined();
+
+ useCommentDraftStore.getState().setPendingAnnotation(key, { annotation, existing: false });
+ useCommentDraftStore.getState().clearDraft(key);
+ expect(useCommentDraftStore.getState().getPendingAnnotation(key)).toBeUndefined();
+ });
+
});
diff --git a/packages/core/issues/stores/comment-draft-store.ts b/packages/core/issues/stores/comment-draft-store.ts
index 6047910b72..5d7721c7a7 100644
--- a/packages/core/issues/stores/comment-draft-store.ts
+++ b/packages/core/issues/stores/comment-draft-store.ts
@@ -40,11 +40,18 @@ export type CommentDraftKey =
| `edit:${string}:${string}` // inline edit on existing comment, key = `edit:${issueId}:${commentId}`
| `chat:${string}`; // chat composer annotations only, key = `chat:${sessionId}`; text lives in the chat store
+export interface PendingAnnotationDraft {
+ annotation: ReplyAnnotation;
+ existing: boolean;
+}
+
interface CommentDraft {
content: string;
/** Uploads (placeholders + completed) for this composer session. */
attachments: DraftUpload[];
annotations?: ReplyAnnotation[];
+ /** Unconfirmed selection-annotation note kept across virtualization unmount / tab switches. */
+ pendingAnnotation?: PendingAnnotationDraft;
replyTarget?: { commentId: string; actorName: string };
updatedAt: number;
}
@@ -78,6 +85,9 @@ interface CommentDraftStore {
addAnnotation: (key: CommentDraftKey, annotation: ReplyAnnotation) => string | undefined;
updateAnnotation: (key: CommentDraftKey, id: string, note: string) => void;
removeAnnotation: (key: CommentDraftKey, id: string) => void;
+ getPendingAnnotation: (key: CommentDraftKey) => PendingAnnotationDraft | undefined;
+ setPendingAnnotation: (key: CommentDraftKey, draft: PendingAnnotationDraft) => void;
+ clearPendingAnnotation: (key: CommentDraftKey) => void;
clearDraft: (key: CommentDraftKey) => void;
}
@@ -110,14 +120,45 @@ function deriveUploaded(uploads: DraftUpload[]): Attachment[] {
// upload (in any state). Upload-only drafts (text deleted, a file still pending
// or failed) are meaningful — pruning or dropping them would silently discard
// the upload the whole persistence exists to protect.
-function isMeaningful(content: string, uploads: DraftUpload[], annotations: ReplyAnnotation[] = EMPTY_REPLY_ANNOTATIONS): boolean {
- return content.trim().length > 0 || uploads.length > 0 || annotations.length > 0;
+function isMeaningful(
+ content: string,
+ uploads: DraftUpload[],
+ annotations: ReplyAnnotation[] = EMPTY_REPLY_ANNOTATIONS,
+ pendingAnnotation?: PendingAnnotationDraft,
+): boolean {
+ return content.trim().length > 0 || uploads.length > 0 || annotations.length > 0 || !!pendingAnnotation;
+}
+
+function normalizePendingAnnotation(value: unknown): PendingAnnotationDraft | undefined {
+ if (!value || typeof value !== "object") return undefined;
+ const candidate = value as { annotation?: unknown; existing?: unknown };
+ if (typeof candidate.existing !== "boolean") return undefined;
+ const annotation = normalizeReplyAnnotations([candidate.annotation])[0];
+ return annotation ? { annotation, existing: candidate.existing } : undefined;
+}
+
+function samePendingAnnotation(a?: PendingAnnotationDraft, b?: PendingAnnotationDraft): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ return (
+ a.existing === b.existing &&
+ a.annotation.id === b.annotation.id &&
+ a.annotation.sourceCommentId === b.annotation.sourceCommentId &&
+ a.annotation.sourceActorName === b.annotation.sourceActorName &&
+ a.annotation.sourceRevision === b.annotation.sourceRevision &&
+ a.annotation.quote === b.annotation.quote &&
+ a.annotation.note === b.annotation.note &&
+ a.annotation.start === b.annotation.start &&
+ a.annotation.prefix === b.annotation.prefix &&
+ a.annotation.suffix === b.annotation.suffix
+ );
}
// Shared writer for setDraft/setAttachments/upload mutations: an entry with
// neither text nor uploads carries nothing to recover, so drop it instead of
// leaving a blank record behind (parity with the old onUpdate "clear on empty
-// text").
+// text"). Pass `pendingArg = null` to clear `pendingAnnotation`; omit it
+// (`undefined`) to preserve the existing value.
function writeDraft(
drafts: Record<string, CommentDraft>,
key: string,
@@ -125,8 +166,11 @@ function writeDraft(
uploads: DraftUpload[],
annotations = drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS,
replyTarget = key.startsWith("reply:") && annotations.length ? drafts[key]?.replyTarget : undefined,
+ pendingArg?: PendingAnnotationDraft | null,
): Record<string, CommentDraft> {
- if (!isMeaningful(content, uploads, annotations)) {
+ const pendingAnnotation =
+ pendingArg === undefined ? drafts[key]?.pendingAnnotation : (pendingArg ?? undefined);
+ if (!isMeaningful(content, uploads, annotations, pendingAnnotation)) {
if (!(key in drafts)) return drafts;
const next = { ...drafts };
delete next[key];
@@ -137,10 +181,20 @@ function writeDraft(
// guard compares entry identity — a fresh-but-equal entry would read as "the
// user edited during the request" and wrongly keep a submitted draft alive.
const existing = drafts[key];
- if (existing && existing.content === content && existing.replyTarget === replyTarget && (existing.annotations ?? EMPTY_REPLY_ANNOTATIONS) === annotations && existing.attachments === uploads) {
+ if (
+ existing &&
+ existing.content === content &&
+ existing.replyTarget === replyTarget &&
+ (existing.annotations ?? EMPTY_REPLY_ANNOTATIONS) === annotations &&
+ existing.attachments === uploads &&
+ samePendingAnnotation(existing.pendingAnnotation, pendingAnnotation)
+ ) {
return drafts;
}
- return { ...drafts, [key]: { content, attachments: uploads, annotations, replyTarget, updatedAt: Date.now() } };
+ return {
+ ...drafts,
+ [key]: { content, attachments: uploads, annotations, pendingAnnotation, replyTarget, updatedAt: Date.now() },
+ };
}
function uploadsOf(drafts: Record<string, CommentDraft>, key: string): DraftUpload[] {
@@ -156,11 +210,12 @@ function pruneStaleDrafts(drafts: Record<string, CommentDraft>): Record<string,
// were never persisted, so the upload cannot resume).
const uploads = normalizeStoredUploads(v.attachments);
const annotations = normalizeReplyAnnotations(v.annotations);
- if (v.updatedAt >= cutoff && isMeaningful(v.content, uploads, annotations)) {
+ const pendingAnnotation = normalizePendingAnnotation(v.pendingAnnotation);
+ if (v.updatedAt >= cutoff && isMeaningful(v.content, uploads, annotations, pendingAnnotation)) {
const first = annotations[0];
const replyTarget = k.startsWith("reply:") && first ? (v.replyTarget && typeof v.replyTarget.commentId === "string" && typeof v.replyTarget.actorName === "string"
? v.replyTarget : { commentId: first.sourceCommentId, actorName: first.sourceActorName }) : undefined;
- out[k] = { ...v, attachments: uploads, annotations, replyTarget };
+ out[k] = { ...v, attachments: uploads, annotations, pendingAnnotation, replyTarget };
}
}
return out;
@@ -269,7 +324,53 @@ export const useCommentDraftStore = create<CommentDraftStore>()(
removeAnnotation: (key, id) => set((s) => {
const current = s.drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS;
if (!current.some((a) => a.id === id)) return s;
- return { drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", uploadsOf(s.drafts, key), current.filter((a) => a.id !== id)) };
+ const pending = s.drafts[key]?.pendingAnnotation;
+ const nextPending = pending?.annotation.id === id ? null : pending;
+ return {
+ drafts: writeDraft(
+ s.drafts,
+ key,
+ s.drafts[key]?.content ?? "",
+ uploadsOf(s.drafts, key),
+ current.filter((a) => a.id !== id),
+ undefined,
+ nextPending,
+ ),
+ };
+ }),
+ getPendingAnnotation: (key) => get().drafts[key]?.pendingAnnotation,
+ setPendingAnnotation: (key, draft) => {
+ if (!key.startsWith("reply:") && !key.startsWith("new:") && !key.startsWith("chat:")) return;
+ const normalized = normalizePendingAnnotation(draft);
+ set((s) => ({
+ drafts: writeDraft(
+ s.drafts,
+ key,
+ s.drafts[key]?.content ?? "",
+ uploadsOf(s.drafts, key),
+ s.drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS,
+ key.startsWith("reply:") && (s.drafts[key]?.annotations?.length ?? 0) > 0
+ ? s.drafts[key]?.replyTarget
+ : undefined,
+ normalized ?? null,
+ ),
+ }));
+ },
+ clearPendingAnnotation: (key) => set((s) => {
+ if (!s.drafts[key]?.pendingAnnotation) return s;
+ return {
+ drafts: writeDraft(
+ s.drafts,
+ key,
+ s.drafts[key]?.content ?? "",
+ uploadsOf(s.drafts, key),
+ s.drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS,
+ key.startsWith("reply:") && (s.drafts[key]?.annotations?.length ?? 0) > 0
+ ? s.drafts[key]?.replyTarget
+ : undefined,
+ null,
+ ),
+ };
}),
clearDraft: (key) =>
set((s) => {
diff --git a/packages/core/issues/stores/index.ts b/packages/core/issues/stores/index.ts
index 8745d03b9a..dc36689fde 100644
--- a/packages/core/issues/stores/index.ts
+++ b/packages/core/issues/stores/index.ts
@@ -37,7 +37,7 @@ export {
selectExpandedResolved,
} from "./resolved-expand-store";
export { useCommentComposerStore, type CommentImageLayout, type RunningAgentReply } from "./comment-composer-store";
-export { useCommentDraftStore, type CommentDraftKey } from "./comment-draft-store";
+export { useCommentDraftStore, type CommentDraftKey, type PendingAnnotationDraft } from "./comment-draft-store";
export {
myIssuesViewStore,
type MyIssuesViewState,
diff --git a/packages/views/issues/components/annotation-composer.tsx b/packages/views/issues/components/annotation-composer.tsx
index 17a2a6ad99..6c8d5fe144 100644
--- a/packages/views/issues/components/annotation-composer.tsx
+++ b/packages/views/issues/components/annotation-composer.tsx
@@ -76,12 +76,20 @@ export function AnnotationComposer({
const save = () => {
if (busy || inFlight.current || !canSave) return;
const note = editorRef.current?.getMarkdown() ?? "";
- if (note.trim()) onSave(note, true);
+ if (!note.trim()) return;
+ // Cancel any armed 100ms debounce so a late onUpdate cannot write a stale
+ // pendingAnnotation after confirmNote clears it.
+ editorRef.current?.flushPendingUpdate?.();
+ onSave(note, true);
};
const send = async () => {
if (!controls || controls.targetMissing || busy || inFlight.current || !canSave) return;
const note = editorRef.current?.getMarkdown() ?? "";
if (!note.trim()) return;
+ // Cancel any armed 100ms debounce before confirmNote + submit snapshot,
+ // matching ReplyInput/CommentInput so a late onUpdate cannot mutate the
+ // draft entry mid-flight and defeat the post-submit cleanup guard.
+ editorRef.current?.flushPendingUpdate?.();
inFlight.current = true;
onBusyChange(true);
setSending(true);
@@ -110,6 +118,7 @@ export function AnnotationComposer({
placeholder={t(($) => $.reply.annotations.note_placeholder)}
className="min-h-8 max-h-32 overflow-y-auto px-2 py-1.5"
currentIssueId={issueId} showBubbleMenu={false} debounceMs={100}
+ flushPendingOnUnmount
onUpdate={onChange} onEnter={save} onSubmit={send} />
</div>
<VoiceHud voice={voice} />
diff --git a/packages/views/issues/components/annotation-reply-interactions.test.tsx b/packages/views/issues/components/annotation-reply-interactions.test.tsx
index 1ad2a88a09..fcd5bd7f5b 100644
--- a/packages/views/issues/components/annotation-reply-interactions.test.tsx
+++ b/packages/views/issues/components/annotation-reply-interactions.test.tsx
@@ -116,6 +116,25 @@ describe("annotation draft submission through the real composer", () => {
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2));
});
+ it.each([false, true])("clears the draft when Ctrl+Enter sends within the 100ms editor debounce (description: %s)", async (description) => {
+ const draftKey = description ? "new:issue" as const : key;
+ const onSubmit = vi.fn<Submit>(() => new Promise((resolve) => {
+ window.setTimeout(() => resolve("published"), 200);
+ }));
+ const view = renderWithI18n(<Fixture onSubmit={onSubmit} description={description} />);
+ selectText(view.container);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const input = await screen.findByRole("textbox", { name: "Comment" });
+ // Type and send immediately before the 100ms ContentEditor debounce fires.
+ await act(async () => {
+ (input as HTMLElement & { editor: Editor }).editor.commands.setContent("Fast send", { contentType: "markdown" });
+ });
+ fireEvent.keyDown(input, { key: "Enter", ctrlKey: true });
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("> Child text\n\nFast send", undefined, undefined, undefined));
+ await waitFor(() => expect(useCommentDraftStore.getState().drafts[draftKey]).toBeUndefined());
+ expect(screen.queryByRole("textbox", { name: "Comment" })).not.toBeInTheDocument();
+ });
+
it("keeps the popover compact: icon send, short confirm label with a descriptive name", async () => {
const view = renderWithI18n(<Fixture onSubmit={vi.fn<Submit>(async () => "published")} />);
const input = await open(view.container, "Compact note");
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 7e02b3ce7c..6d6d725c6f 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -1365,10 +1365,14 @@ function CommentCardImpl({
const anchorId = "run" in row
? (row.reply && !isDeletedComment(row.reply) ? row.reply.id : row.run.task.id)
: row.id;
+ const rowCommentId = "run" in row
+ ? (row.reply && !isDeletedComment(row.reply) ? row.reply.id : undefined)
+ : row.id;
+ const rowEngaged = !!rowCommentId && annotation.activeSourceCommentId === rowCommentId;
// Keyed like the inline rows: a run slot keeps its task key when its reply
// arrives, so the slot (and its open activity panel) stays mounted.
return <VirtualThreadRow key={"run" in row ? row.run.task.id : row.id} id={`comment-${anchorId}`} virtualize={virtualizeRows}
- taskId={"run" in row ? row.run.task.id : undefined} scrollParent={replyScrollParent}>
+ engaged={rowEngaged} taskId={"run" in row ? row.run.task.id : undefined} scrollParent={replyScrollParent}>
{() => renderThreadRow(row, virtualizeRows)}
</VirtualThreadRow>;
});
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 5b371ea220..4fc88244bd 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -3110,6 +3110,55 @@ describe("IssueDetail (shared)", () => {
}
});
+ it("does not restart a comment landing after the user scrolls away and another thread receives a reply", async () => {
+ mockApiObj.listTasksByIssue.mockResolvedValue([]);
+ let driftStart = 0;
+ const drift = () => {
+ driftStart ||= performance.now();
+ return Math.min(performance.now() - driftStart, 300);
+ };
+ let userScrolled = false;
+ const rect = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
+ const container = this.closest<HTMLElement>("[data-tab-scroll-root]");
+ if (this === container) return new DOMRect(0, 0, 400, 200);
+ if (this.id === "comment-comment-2" && container) {
+ return new DOMRect(0, 250 + drift() - container.scrollTop, 400, 100);
+ }
+ return new DOMRect(0, 0, 0, 0);
+ });
+ try {
+ const { queryClient } = renderIssueDetailWithHighlight("comment-2");
+ await waitFor(() => expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-2"))).toBe(true));
+ const container = document.querySelector<HTMLElement>("[data-tab-scroll-root]")!;
+
+ // User scrolls up to read/annotate an earlier thread before landing settles.
+ container.scrollTop = 40;
+ container.dispatchEvent(new Event("wheel"));
+ userScrolled = true;
+
+ // An agent posts a new reply in another thread, rebuilding timeline items.
+ act(() => {
+ queryClient.setQueryData<TimelineEntry[]>(["issues", "timeline", "issue-1"], (old) => [
+ ...(old ?? []),
+ {
+ ...mockTimeline[0]!,
+ id: "agent-reply-other-thread",
+ parent_id: "comment-2",
+ actor_type: "agent",
+ actor_id: "agent-1",
+ content: "Fast agent reply in thread 2",
+ created_at: "2026-01-18T00:00:00Z",
+ },
+ ]);
+ });
+ await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 120)); });
+ expect(userScrolled).toBe(true);
+ expect(container.scrollTop).toBe(40);
+ } finally {
+ rect.mockRestore();
+ }
+ });
+
it("folds an assignment reply with its resolved parent and unfolds that thread for a notification", async () => {
const run: AgentTask = { id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
kind: "direct", status: "completed", priority: 0, created_at: "2026-01-16T00:00:00Z", started_at: null, dispatched_at: null,
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index c47f9432d5..7ae87ede8d 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -1957,24 +1957,49 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
previousCommentRuns.current = next.runs;
return next;
}, [commentTasks, timeline]);
+ // Scope entering run IDs per thread and reuse unchanged Sets so a new run in
+ // one thread never busts React.memo on sibling CommentCards.
+ const prevThreadEnteringRef = useRef(new Map<string, ReadonlySet<string>>());
+ const enteringRunIdsByThread = useMemo(() => {
+ const next = new Map<string, ReadonlySet<string>>();
+ if (enteringRunIds.size > 0) {
+ const prev = prevThreadEnteringRef.current;
+ for (const [rootId, runs] of commentRuns) {
+ const matched = runs.filter((run) => enteringRunIds.has(run.task.id)).map((run) => run.task.id);
+ if (matched.length === 0) continue;
+ const prior = prev.get(rootId);
+ if (prior && prior.size === matched.length && matched.every((taskId) => prior.has(taskId))) {
+ next.set(rootId, prior);
+ } else {
+ next.set(rootId, new Set(matched));
+ }
+ }
+ }
+ prevThreadEnteringRef.current = next;
+ return next;
+ }, [commentRuns, enteringRunIds]);
// Resolve / unresolve must always clear the per-session expand entry so
// re-resolving an already-expanded thread folds it back to the bar (the
// expand Set is keyed only on commentId, not on resolution state). Without
// this wrapper, an expand → unresolve → resolve sequence keeps the thread
- // visually expanded after the second resolve.
+ // visually expanded after the second resolve. Read displayTimeline via ref
+ // so every timeline mutation does not mint a new callback and bust React.memo
+ // on every mounted CommentCard.
+ const displayTimelineRef = useRef(displayTimeline);
+ displayTimelineRef.current = displayTimeline;
const handleResolveToggle = useCallback(
(commentId: string, resolved: boolean) => {
// Fold the thread back on any resolve change: clear the thread ROOT's
// expand entry (expand state is keyed on root id, but a resolve target
// can be a reply). Walk parent_id up to the root.
- const byId = new Map(displayTimeline.map((e) => [e.id, e]));
+ const byId = new Map(displayTimelineRef.current.map((e) => [e.id, e]));
let cur = byId.get(commentId);
while (cur?.parent_id && byId.get(cur.parent_id)) cur = byId.get(cur.parent_id)!;
clearResolvedExpand(cur?.id ?? commentId);
toggleResolveComment(commentId, resolved);
},
- [displayTimeline, clearResolvedExpand, toggleResolveComment],
+ [clearResolvedExpand, toggleResolveComment],
);
// Memoized timeline grouping. Each render rebuilds the per-parent map from
@@ -2328,16 +2353,29 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
// The extra `offset` lifts the row's bottom clear of the sticky composer.
// `scrollContainerEl` stays out of the deps: a container re-measure would
// cancel the scroll mid-flight.
+ const scrollContainerElRef = useRef<HTMLDivElement | null>(null);
+ scrollContainerElRef.current = scrollContainerEl;
useEffect(() => {
if (!pendingPostedCommentId) return;
const rootId = replyToRoot.get(pendingPostedCommentId) ?? pendingPostedCommentId;
const index = items.findIndex((item) => item.id === rootId);
if (index < 0) return;
let timer: number | undefined;
+ let cancelled = false;
const scrollEnd = () => {
+ if (cancelled) return;
const composerHeight = composerRef.current?.getBoundingClientRect().height ?? 0;
virtuosoRef.current?.scrollToIndex({ index, align: "end", offset: composerHeight });
};
+ const container = scrollContainerElRef.current;
+ const stopOnUserInput = () => {
+ cancelled = true;
+ cancelAnimationFrame(frame);
+ if (timer !== undefined) window.clearTimeout(timer);
+ setPendingPostedCommentId(null);
+ };
+ const userEvents = ["wheel", "touchstart", "pointerdown"] as const;
+ for (const type of userEvents) container?.addEventListener(type, stopOnUserInput, { passive: true });
const frame = requestAnimationFrame(() => {
scrollEnd();
timer = window.setTimeout(() => {
@@ -2346,8 +2384,10 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
}, 100);
});
return () => {
+ cancelled = true;
cancelAnimationFrame(frame);
if (timer !== undefined) window.clearTimeout(timer);
+ for (const type of userEvents) container?.removeEventListener(type, stopOnUserInput);
};
}, [pendingPostedCommentId, items, replyToRoot]);
const jumpFlashTimerRef = useRef<number | null>(null);
@@ -2772,15 +2812,24 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
const container = scrollContainerEl;
if (!container) return;
if (targetIdx < 0) return;
+ const markUserCancelled = () => {
+ completed = true;
+ interruptedLandingRef.current = null;
+ didHighlightRef.current = highlightCommentId;
+ writeViewState(issueHighlightMementoKey(id), highlightCommentId);
+ onHighlightLandedRef.current?.();
+ releaseLandingChrome();
+ releaseLandingOverscan();
+ };
+ let completed = false;
if (!timelineSized) {
// Virtuoso measures nothing while the list is below the viewport, and
// without height estimates it cannot place the target until it does.
const list = virtualTimelineRef.current;
- return list ? revealTimelineList(container, list) : undefined;
+ return list ? revealTimelineList(container, list, markUserCancelled) : undefined;
}
interruptedLandingRef.current = null;
- let completed = false;
const cancel = scrollToTimelineComment({
container, virtualizer: virtuosoRef.current,
index: targetIdx, commentId: landingId,
@@ -2799,6 +2848,7 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
// After the aligned frame paints, not inside it.
window.setTimeout(releaseLandingOverscan, 0);
},
+ onUserCancel: markUserCancelled,
});
return () => {
cancel();
@@ -3718,7 +3768,8 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
onCollapseResolved: reply.resolved_at ? () => toggleResolvedExpand(reply.id, false) : undefined,
expandedResolvedIds: expandedResolved, onResolvedExpandChange: toggleResolvedExpand,
highlightedCommentId: highlightedId,
- runs: commentRuns.get(reply.id) ?? EMPTY_COMMENT_RUNS, enteringRunIds,
+ runs: commentRuns.get(reply.id) ?? EMPTY_COMMENT_RUNS,
+ enteringRunIds: enteringRunIdsByThread.get(reply.id),
} : undefined} />}
</div>;
}
@@ -3741,7 +3792,7 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
issueId={id}
replyScrollParent={scrollContainerEl}
runs={commentRuns.get(item.id) ?? EMPTY_COMMENT_RUNS}
- enteringRunIds={enteringRunIds}
+ enteringRunIds={enteringRunIdsByThread.get(item.id)}
entry={item.entry}
replies={timelineView.threadReplies.get(item.id) ?? EMPTY_REPLIES}
currentUserId={user?.id}
diff --git a/packages/views/issues/components/use-comment-annotations.test.tsx b/packages/views/issues/components/use-comment-annotations.test.tsx
index 34eb6cafb4..1dd061e863 100644
--- a/packages/views/issues/components/use-comment-annotations.test.tsx
+++ b/packages/views/issues/components/use-comment-annotations.test.tsx
@@ -379,4 +379,49 @@ describe("selection to reply", () => {
action.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
});
+
+ it("preserves an in-progress annotation note across unmount and remount without stealing focus", async () => {
+ vi.spyOn(window, "matchMedia").mockReturnValue({ matches: true } as MediaQueryList);
+ const first = renderWithI18n(<Fixture child />);
+ selectText(first.container, "mouse", '[data-comment-content="child"]');
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const input = await screen.findByRole("textbox", { name: "Comment" });
+ fireEvent.change(input, { target: { value: "In-progress draft note" } });
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(0);
+
+ // Simulate Virtuoso unmounting the thread card on scroll-out.
+ first.unmount();
+ expect(useCommentDraftStore.getState().getPendingAnnotation(key)?.annotation.note).toBe("In-progress draft note");
+
+ // Remounting the card restores the open popup with the typed draft intact.
+ renderWithI18n(<Fixture child />);
+ const restored = await screen.findByRole("textbox", { name: "Comment" });
+ expect(restored).toHaveValue("In-progress draft note");
+ expect(restored).not.toHaveFocus();
+
+ // Explicit dismiss clears the persisted pending draft so it does not reopen.
+ fireEvent.pointerDown(document.body);
+ await waitFor(() => expect(screen.queryByRole("textbox", { name: "Comment" })).not.toBeInTheDocument());
+ expect(useCommentDraftStore.getState().drafts[key]).toBeUndefined();
+ });
+
+ it("preserves unsaved edits to an existing annotation across unmount and remount", async () => {
+ useCommentDraftStore.getState().addAnnotation(key, {
+ id: "saved-1", sourceCommentId: "root", sourceActorName: "agent",
+ quote: "Selected text", start: 0, prefix: "", suffix: "", note: "Original note",
+ });
+ const first = renderWithI18n(<Fixture />);
+ fireEvent.click(await screen.findByRole("button", { name: "Edit annotation 1" }));
+ const edit = await screen.findByRole("textbox", { name: "Comment" });
+ fireEvent.change(edit, { target: { value: "Half-finished revision" } });
+ expect(useCommentDraftStore.getState().getAnnotations(key)[0]?.note).toBe("Original note");
+
+ first.unmount();
+ renderWithI18n(<Fixture />);
+ const restored = await screen.findByRole("textbox", { name: "Comment" });
+ expect(restored).toHaveValue("Half-finished revision");
+ fireEvent.click(screen.getByRole("button", { name: "Save annotation" }));
+ expect(useCommentDraftStore.getState().getAnnotations(key)[0]?.note).toBe("Half-finished revision");
+ expect(useCommentDraftStore.getState().getPendingAnnotation(key)).toBeUndefined();
+ });
});
diff --git a/packages/views/issues/components/use-comment-annotations.tsx b/packages/views/issues/components/use-comment-annotations.tsx
index d2e0b2a698..e974ba33be 100644
--- a/packages/views/issues/components/use-comment-annotations.tsx
+++ b/packages/views/issues/components/use-comment-annotations.tsx
@@ -43,12 +43,25 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
const pendingFocusId = useRef<string | null>(null);
const actionRef = useRef<HTMLButtonElement>(null);
const [selection, setSelection] = useState<CapturedSelection | null>(null);
+ const selectionRef = useRef(selection);
+ selectionRef.current = selection;
const [editor, setEditor] = useState<{ annotation: ReplyAnnotation; existing: boolean } | null>(null);
+ const editorRef = useRef(editor);
+ editorRef.current = editor;
const editing = editor?.annotation;
const editingExisting = editor?.existing === true;
const editingRef = useRef(editing);
editingRef.current = editing;
const editingId = editing?.id;
+ // Distinguishes an explicit dismiss/commit from an unexpected unmount
+ // (Virtuoso scroll-out, tab switch), so an unmount flush from ContentEditor
+ // never resurrects a dismissed note while still rescuing typed bytes.
+ const dismissedRef = useRef(false);
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => { mountedRef.current = false; };
+ }, []);
const [error, setError] = useState(false);
const [anchors, setAnchors] = useState<SourceAnchor[]>([]);
const markerRanges = useMemo(() => {
@@ -60,6 +73,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
return groups;
}, [anchors]);
const annotations = useCommentDraftStore((s) => s.getAnnotations(draftKey));
+ const pendingSourceCommentId = useCommentDraftStore((s) => s.drafts[draftKey]?.pendingAnnotation?.annotation.sourceCommentId ?? null);
const annotationsRef = useRef(annotations);
annotationsRef.current = annotations;
const sourcesRef = useRef(sources);
@@ -71,13 +85,19 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
const anchorKey = annotations.map((a) => a.id).join(",");
const highlightName = `reply-annotation-${useId().replace(/[^a-zA-Z0-9-]/g, "")}`;
+ const dismiss = useCallback((clearStored = true) => {
+ dismissedRef.current = true;
+ if (clearStored) useCommentDraftStore.getState().clearPendingAnnotation(draftKey);
+ setSelection(null); setEditor(null); setError(false);
+ }, [draftKey]);
+
const close = (restoreFocus = false) => {
if (submittingRef.current) return;
if (restoreFocus && selection?.root.isConnected) {
const target = editable ? selection.root.querySelector<HTMLElement>("[contenteditable=true]") ?? selection.root : selection.root;
target.focus({ preventScroll: true });
}
- setSelection(null); setEditor(null); setError(false);
+ dismiss();
};
const readSelection = useCallback(() => {
if (!enabled || submittingRef.current || !cardRef.current) return null;
@@ -86,19 +106,33 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
}, [enabled, editable]);
const capture = () => {
const captured = readSelection();
- if (captured) { setSelection(captured); setEditor(null); setError(false); }
+ if (captured) {
+ dismissedRef.current = true;
+ useCommentDraftStore.getState().clearPendingAnnotation(draftKey);
+ setSelection(captured); setEditor(null); setError(false);
+ }
};
- useEffect(() => { setSelection(null); setEditor(null); setError(false); submittingRef.current = null; }, [draftKey, enabled]);
+ // Reset local popup state when switching targets or disabling, without
+ // wiping persisted pending drafts so returning to the previous key can
+ // recover them.
+ const prevContextRef = useRef({ draftKey, enabled });
+ useEffect(() => {
+ const prev = prevContextRef.current;
+ prevContextRef.current = { draftKey, enabled };
+ if (prev.draftKey === draftKey && prev.enabled === enabled) return;
+ setSelection(null); setEditor(null); setError(false); submittingRef.current = null;
+ }, [draftKey, enabled]);
// Dismiss on the next press, never on the click completing the opening drag.
useEffect(() => {
if (!selection) return;
+ let active = true;
const onPointerDown = (event: PointerEvent) => {
if (submittingRef.current) return;
if (event.target instanceof Element &&
event.target.closest("[data-editor-overlay-owner]")?.getAttribute("data-editor-overlay-owner") === draftKey) return;
- setSelection(null); setEditor(null); setError(false);
+ dismiss();
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || isImeComposing(event) || submittingRef.current) return;
@@ -110,7 +144,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
const target = editable ? selection.root.querySelector<HTMLElement>("[contenteditable=true]") ?? selection.root : selection.root;
target.focus({ preventScroll: true });
}
- setSelection(null); setEditor(null); setError(false);
+ dismiss();
};
const onFocusIn = (event: FocusEvent) => {
if (submittingRef.current) return;
@@ -119,21 +153,23 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
// Clipboard fallback briefly focuses a hidden textarea, then restores
// the owned control synchronously. Only dismiss if focus stays outside.
queueMicrotask(() => {
+ if (!active || !mountedRef.current) return;
const target = document.activeElement;
if (submittingRef.current || selection.root.contains(target) ||
target?.closest("[data-editor-overlay-owner]")?.getAttribute("data-editor-overlay-owner") === draftKey) return;
- setSelection(null); setEditor(null); setError(false);
+ dismiss();
});
};
document.addEventListener("pointerdown", onPointerDown);
document.addEventListener("keydown", onKeyDown);
document.addEventListener("focusin", onFocusIn);
return () => {
+ active = false;
document.removeEventListener("pointerdown", onPointerDown);
document.removeEventListener("keydown", onKeyDown);
document.removeEventListener("focusin", onFocusIn);
};
- }, [selection, draftKey, editable]);
+ }, [selection, draftKey, editable, dismiss]);
const focusNote = useCallback(() => {
if (!editingId || pendingFocusId.current !== editingId) return;
@@ -142,7 +178,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
}, [editingId]);
useEffect(() => {
- if ((!anchorKey && !editingId) || !enabled) {
+ if ((!anchorKey && !editingId && !pendingSourceCommentId) || !enabled) {
setAnchors((current) => current.length ? [] : current);
return;
}
@@ -155,6 +191,25 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
return root && range ? [{ id: a.id, range, root }] : [];
});
setAnchors((current) => !current.length && !next.length ? current : next);
+ // Restore an in-progress note that survived Virtuoso scroll-out or tab
+ // switch without stealing focus or scrolling the page.
+ if (!editingRef.current && !selectionRef.current) {
+ const pending = useCommentDraftStore.getState().getPendingAnnotation(draftKey);
+ if (pending) {
+ if (pending.existing && !annotationsRef.current.some((a) => a.id === pending.annotation.id)) {
+ useCommentDraftStore.getState().clearPendingAnnotation(draftKey);
+ } else {
+ const root = findAnnotationSource(card, pending.annotation.sourceCommentId);
+ const range = root && annotationRange(root, pending.annotation, editable);
+ if (root && range) {
+ dismissedRef.current = false;
+ setSelection({ ...pending.annotation, range, root });
+ setEditor({ annotation: pending.annotation, existing: pending.existing });
+ setError(false);
+ }
+ }
+ }
+ }
// Expanding a resolved thread may remount the selected comment's body.
// Keep the note editor attached to its saved quote, never a detached Range.
setSelection((current) => {
@@ -186,13 +241,17 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
});
observer.observe(card, { childList: true, subtree: true, characterData: true });
return () => { observer.disconnect(); if (canHighlight) CSS.highlights.delete(highlightName); };
- }, [anchorKey, highlightName, draftKey, editable, enabled, editingId, card]);
+ }, [anchorKey, highlightName, draftKey, editable, enabled, editingId, pendingSourceCommentId, card]);
useEffect(() => {
if (!selection || (editor?.existing && !annotations.some((a) => a.id === editingId))) {
+ if (editor?.existing) {
+ dismissedRef.current = true;
+ useCommentDraftStore.getState().clearPendingAnnotation(draftKey);
+ }
setSelection(null); setEditor(null);
}
- }, [annotations, editor?.existing, editingId, selection]);
+ }, [annotations, editor?.existing, editingId, selection, draftKey]);
const editAnnotation = (id: string, scrollToSource = false): boolean => {
if (submittingRef.current) return false;
@@ -205,6 +264,8 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
element?.scrollIntoView({ block: "center", behavior: "instant" });
}
onOpenRef.current?.();
+ dismissedRef.current = false;
+ useCommentDraftStore.getState().clearPendingAnnotation(draftKey);
pendingFocusId.current = id;
setSelection({ ...annotation, range, root }); setEditor({ annotation, existing: true }); setError(false);
return true;
@@ -226,6 +287,8 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
return false;
}
onOpenRef.current?.();
+ dismissedRef.current = false;
+ useCommentDraftStore.getState().clearPendingAnnotation(draftKey);
setSelection(captured);
const next = duplicate ?? {
id: crypto.randomUUID(), sourceCommentId, sourceActorName: source.name,
@@ -236,16 +299,17 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
setError(false);
window.getSelection()?.removeAllRanges();
return true;
- }, [t]);
+ }, [t, draftKey]);
const addSelection = useCallback(() => add(readSelection()), [add, readSelection]);
- const confirmNote = (note: string, dismiss: boolean): boolean => {
+ const confirmNote = (note: string, dismissAfter: boolean): boolean => {
if (!editing || !note.trim()) return false;
const store = useCommentDraftStore.getState();
const id = editingExisting ? editing.id : store.addAnnotation(draftKey, { ...editing, note });
if (!id) { setError(true); return false; }
store.updateAnnotation(draftKey, id, note);
- if (dismiss) close(true);
+ store.clearPendingAnnotation(draftKey);
+ if (dismissAfter) close(true);
else setEditor({ annotation: { ...editing, id, note }, existing: true });
if (!editingExisting) onAddedRef.current?.();
return true;
@@ -263,7 +327,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
const renderComposer = (controls?: AnnotationSendControls) => {
return enabled && selection ? <CommentSelectionBubble range={selection.range} source={selection.root} owner={draftKey} onPositioned={focusNote} keepVisibleWhenDetached={!!editing}>
<div className="bubble-menu max-w-[calc(100vw-16px)] focus-within:outline-1 focus-within:outline-ring">
- {editing ? <AnnotationComposer key={editing.id} issueId={issueId} owner={draftKey}
+ {editing ? <AnnotationComposer key={`${draftKey}:${editing.id}`} issueId={issueId} owner={draftKey}
annotation={editing} existing={editingExisting}
number={annotations.findIndex((a) => a.id === editing.id) + 1}
editorRef={inputRef} controls={controls}
@@ -271,7 +335,17 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
sourceChanged={sources.some((source) => source.id === editing.sourceCommentId &&
source.revision !== undefined && editing.sourceRevision !== undefined && source.revision !== editing.sourceRevision)}
canSave={editingExisting || annotations.length < MAX_REPLY_ANNOTATIONS}
- onChange={(note) => { setEditor({ annotation: { ...editing, note }, existing: editingExisting }); setError(false); }}
+ onChange={(note) => {
+ if (dismissedRef.current || submittingRef.current) return;
+ const nextAnnotation = { ...editing, note };
+ const store = useCommentDraftStore.getState();
+ if (note.trim()) store.setPendingAnnotation(draftKey, { annotation: nextAnnotation, existing: editingExisting });
+ else store.clearPendingAnnotation(draftKey);
+ if (mountedRef.current) {
+ setEditor({ annotation: nextAnnotation, existing: editingExisting });
+ setError(false);
+ }
+ }}
onSave={confirmNote} onBusyChange={(busy) => {
if (busy && editingRef.current?.id === editing.id) submittingRef.current = editing.id;
else if (!busy && submittingRef.current === editing.id) submittingRef.current = null;
@@ -296,6 +370,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
cardRef: setCardRef,
editAnnotation,
addSelection,
+ activeSourceCommentId: editing?.sourceCommentId ?? pendingSourceCommentId,
composer: editing ? { pending: editing, render: renderComposer } : undefined,
captureProps: {
"data-annotation-thread": draftKey,
diff --git a/packages/views/issues/components/virtual-thread-row.test.tsx b/packages/views/issues/components/virtual-thread-row.test.tsx
index 7db08d8a61..89b1fea2e6 100644
--- a/packages/views/issues/components/virtual-thread-row.test.tsx
+++ b/packages/views/issues/components/virtual-thread-row.test.tsx
@@ -41,6 +41,21 @@ describe("VirtualThreadRow", () => {
expect(screen.getByText("Unsaved draft")).toBeInTheDocument();
});
+ it("keeps a row mounted when an external portaled control marks it engaged", () => {
+ const { rerender } = render(<VirtualThreadRow id="comment-annotated" scrollParent={document.body} engaged>
+ {() => <p>Quoted reply body</p>}
+ </VirtualThreadRow>);
+ expect(screen.getByText("Quoted reply body")).toBeInTheDocument();
+ intersect(false);
+ expect(screen.getByText("Quoted reply body")).toBeInTheDocument();
+
+ rerender(<VirtualThreadRow id="comment-annotated" scrollParent={document.body} engaged={false}>
+ {() => <p>Quoted reply body</p>}
+ </VirtualThreadRow>);
+ intersect(false);
+ expect(screen.queryByText("Quoted reply body")).toBeNull();
+ });
+
it("renders all content without a scroll parent for in-page find", () => {
render(<VirtualThreadRow id="comment-find">{() => <p>Findable history</p>}</VirtualThreadRow>);
expect(screen.getByText("Findable history")).toBeInTheDocument();
diff --git a/packages/views/issues/components/virtual-thread-row.tsx b/packages/views/issues/components/virtual-thread-row.tsx
index 4414e11f31..f4a8ce026c 100644
--- a/packages/views/issues/components/virtual-thread-row.tsx
+++ b/packages/views/issues/components/virtual-thread-row.tsx
@@ -72,21 +72,25 @@ export function resetRememberedThreadRowHeights() {
* The anchor `id` lives on the wrapper only while virtualized; otherwise the
* row content carries it as before.
*/
-export function VirtualThreadRow({ id, taskId, scrollParent, virtualize = true, children }: {
+export function VirtualThreadRow({ id, taskId, scrollParent, virtualize = true, engaged: forceEngaged = false, children }: {
id: string;
taskId?: string;
scrollParent?: HTMLElement | null;
/** False renders the row inline; switching it never remounts the row. */
virtualize?: boolean;
+ /** True while an external control (e.g. a portaled annotation editor) targets this row. */
+ engaged?: boolean;
children: () => ReactNode;
}) {
const ref = useRef<HTMLDivElement>(null);
const height = useRef(rememberedHeights.get(id) ?? UNMEASURED_ROW_HEIGHT);
const active = !!scrollParent && virtualize;
+ const forceEngagedRef = useRef(forceEngaged);
+ forceEngagedRef.current = forceEngaged;
// A row that starts inline counts as visible, so turning virtualization on
// later keeps it mounted until the observer reports it offscreen.
- const [visible, setVisible] = useState(!active);
- const mounted = !active || visible;
+ const [visible, setVisible] = useState(!active || forceEngaged);
+ const mounted = !active || visible || forceEngaged;
useEffect(() => {
const node = ref.current;
@@ -102,7 +106,8 @@ export function VirtualThreadRow({ id, taskId, scrollParent, virtualize = true,
const observer = new IntersectionObserver((entries) => {
const intersecting = entries.at(-1)?.isIntersecting ?? false;
// Editing and open controls own transient state; don't discard it on scroll.
- const engaged = node.contains(document.activeElement)
+ const engaged = forceEngagedRef.current
+ || node.contains(document.activeElement)
|| !!node.querySelector('[contenteditable="true"], [aria-expanded="true"]');
setVisible(intersecting || engaged);
}, { root: scrollParent, rootMargin: "800px 0px" });
diff --git a/packages/views/issues/utils/scroll-to-timeline-comment.test.ts b/packages/views/issues/utils/scroll-to-timeline-comment.test.ts
index ad36ef6c81..437b5e720e 100644
--- a/packages/views/issues/utils/scroll-to-timeline-comment.test.ts
+++ b/packages/views/issues/utils/scroll-to-timeline-comment.test.ts
@@ -37,11 +37,58 @@ describe("scrollToTimelineComment", () => {
// 5000 - (600 - 100) / 2: the replacement row, centred.
expect(container.scrollTop).toBe(4750);
});
+
+ it("yields immediately when the user scrolls during alignment", async () => {
+ const container = document.createElement("div");
+ container.getBoundingClientRect = () => new DOMRect(0, 0, 400, 600);
+ Object.defineProperty(container, "clientHeight", { value: 600 });
+ document.body.append(container);
+ let driftingTop = 5000;
+ const el = document.createElement("div");
+ el.id = "comment-target";
+ el.getBoundingClientRect = () => new DOMRect(0, (driftingTop += 50) - container.scrollTop, 400, 100);
+ container.append(el);
+
+ const onComplete = vi.fn();
+ const onUserCancel = vi.fn();
+ scrollToTimelineComment({ container, virtualizer: null, index: 0, commentId: "target", onComplete, onUserCancel });
+ await frame();
+ await frame();
+
+ // User scrolls elsewhere mid-alignment.
+ container.scrollTop = 120;
+ container.dispatchEvent(new Event("wheel"));
+ await frame();
+ await frame();
+
+ expect(onUserCancel).toHaveBeenCalledTimes(1);
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ expect(container.scrollTop).toBe(120);
+ });
});
describe("revealTimelineList", () => {
afterEach(() => { vi.unstubAllGlobals(); });
+ it("stops revealing as soon as the user scrolls", () => {
+ const pending = new Map<number, FrameRequestCallback>();
+ let nextId = 0;
+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => { pending.set(++nextId, cb); return nextId; });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => { pending.delete(id); });
+ const container = document.createElement("div");
+ container.getBoundingClientRect = () => new DOMRect(0, 0, 400, 600);
+ const list = document.createElement("div");
+ list.getBoundingClientRect = () => new DOMRect(0, 2000, 400, 100);
+ const onUserCancel = vi.fn();
+
+ revealTimelineList(container, list, onUserCancel);
+ expect(pending.size).toBe(1);
+
+ container.dispatchEvent(new Event("wheel"));
+ expect(onUserCancel).toHaveBeenCalledTimes(1);
+ expect(pending.size).toBe(0);
+ });
+
it("keeps one frame budget per list across the effect re-runs that restart it", () => {
const pending = new Map<number, FrameRequestCallback>();
let nextId = 0;
diff --git a/packages/views/issues/utils/scroll-to-timeline-comment.ts b/packages/views/issues/utils/scroll-to-timeline-comment.ts
index 495f1de9c9..2977745fd9 100644
--- a/packages/views/issues/utils/scroll-to-timeline-comment.ts
+++ b/packages/views/issues/utils/scroll-to-timeline-comment.ts
@@ -10,6 +10,27 @@ const REVEAL_LIST_MAX_FRAMES = 120;
*/
const revealFramesLeft = new WeakMap<HTMLElement, number>();
+const USER_SCROLL_EVENTS = ["wheel", "touchstart", "pointerdown"] as const;
+const SCROLL_KEYS = new Set(["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "]);
+const MODIFIER_KEYS = new Set(["Meta", "Control", "Alt", "Shift"]);
+
+/** Attach user-takeover listeners so programmatic scrolling yields to the reader. */
+function listenForUserScroll(container: HTMLElement, onUserInput: () => void): () => void {
+ const doc = container.ownerDocument;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (MODIFIER_KEYS.has(event.key)) return;
+ if (SCROLL_KEYS.has(event.key) || (event.target instanceof Node && container.contains(event.target))) {
+ onUserInput();
+ }
+ };
+ for (const type of USER_SCROLL_EVENTS) container.addEventListener?.(type, onUserInput, { passive: true });
+ doc?.addEventListener?.("keydown", onKeyDown, { capture: true, passive: true });
+ return () => {
+ for (const type of USER_SCROLL_EVENTS) container.removeEventListener?.(type, onUserInput);
+ doc?.removeEventListener?.("keydown", onKeyDown, true);
+ };
+}
+
/**
* Hold the virtualized timeline's top at the top of the viewport until the
* caller sees the list report a measured height and cancels.
@@ -21,22 +42,41 @@ const revealFramesLeft = new WeakMap<HTMLElement, number>();
* while its address is canonicalized), which leaves the list out of range
* again and the reader parked in the description.
*/
-export function revealTimelineList(container: HTMLElement, list: HTMLElement) {
+export function revealTimelineList(
+ container: HTMLElement,
+ list: HTMLElement,
+ onUserCancel?: () => void,
+) {
let rafId = 0;
+ let cancelled = false;
+ const stop = () => {
+ if (cancelled) return;
+ cancelled = true;
+ cancelAnimationFrame(rafId);
+ detachListeners();
+ };
+ const detachListeners = listenForUserScroll(container, () => {
+ stop();
+ onUserCancel?.();
+ });
const reveal = () => {
+ if (cancelled) return;
const left = revealFramesLeft.get(list) ?? REVEAL_LIST_MAX_FRAMES;
- if (left <= 0) return;
+ if (left <= 0) {
+ stop();
+ return;
+ }
revealFramesLeft.set(list, left - 1);
container.scrollTop += list.getBoundingClientRect().top - container.getBoundingClientRect().top;
rafId = requestAnimationFrame(reveal);
};
reveal();
- return () => cancelAnimationFrame(rafId);
+ return stop;
}
/** Reveal a nested anchor before aligning it against measured reply content. */
export function scrollToTimelineComment({
- container, virtualizer, index, commentId, offset, onMounted, onComplete,
+ container, virtualizer, index, commentId, offset, onMounted, onComplete, onUserCancel,
}: {
container: HTMLElement;
virtualizer: VirtuosoHandle | null;
@@ -46,6 +86,8 @@ export function scrollToTimelineComment({
offset?: number;
onMounted?: () => void;
onComplete?: () => void;
+ /** Called if the user scrolls or interacts before the landing settles. */
+ onUserCancel?: () => void;
}) {
let rafId = 0;
let mountFrames = 0;
@@ -53,6 +95,23 @@ export function scrollToTimelineComment({
let last = -1;
let cancelled = false;
let mounted = false;
+ const stop = () => {
+ if (cancelled) return;
+ cancelled = true;
+ cancelAnimationFrame(rafId);
+ detachListeners();
+ };
+ const finish = () => {
+ if (cancelled) return;
+ stop();
+ onComplete?.();
+ };
+ const detachListeners = listenForUserScroll(container, () => {
+ if (cancelled) return;
+ stop();
+ onUserCancel?.();
+ onComplete?.();
+ });
const alignTarget = (el: HTMLElement, reveal = false) => {
const c = container.getBoundingClientRect();
const e = el.getBoundingClientRect();
@@ -78,22 +137,24 @@ export function scrollToTimelineComment({
};
const findAnchor = () => container.querySelector<HTMLElement>(`[id="comment-${commentId}"]`);
const land = () => {
+ if (cancelled) return;
const el = findAnchor();
if (!el || el.dataset.virtualThreadMounted === "false") {
if (el) alignTarget(el, true);
if (++mountFrames < 60) rafId = requestAnimationFrame(land);
- else onComplete?.();
+ else finish();
return;
}
if (!mounted) { mounted = true; onMounted?.(); }
const align = () => {
+ if (cancelled) return;
// Look the anchor up again every frame. A commit between frames can
// unmount or replace it (Virtuoso re-ranging rows while a realtime update
// lands); a detached node measures as zero, which would scroll the
// timeline to the top and pass for a settled landing (MUL-9068).
const current = findAnchor();
if (!current || current.dataset.virtualThreadMounted === "false") {
- if (++frames >= 30) { onComplete?.(); return; }
+ if (++frames >= 30) { finish(); return; }
if (!current) virtualizer?.scrollIntoView({ index, align: "start", done: queueLanding });
queueLanding();
return;
@@ -102,7 +163,7 @@ export function scrollToTimelineComment({
if (Math.abs(target - last) > 1 && ++frames < 30) {
last = target;
rafId = requestAnimationFrame(align);
- } else onComplete?.();
+ } else finish();
};
rafId = requestAnimationFrame(align);
};
@@ -114,5 +175,5 @@ export function scrollToTimelineComment({
virtualizer?.scrollIntoView({ index, align: "start", done: queueLanding });
// Reply bodies can resize the thread before Virtuoso calls done.
queueLanding();
- return () => { cancelled = true; cancelAnimationFrame(rafId); };
+ return stop;
}