Skip to content

Commit 1d42fbc

Browse files
committed
fix: cancel pending rAF in setFocusTarget on cleanup and re-invocation
Address CodeRabbit review feedback on PR #3100: track the requestAnimationFrame ID via a ref and cancel it before scheduling a new one or when the component unmounts. Signed-off-by: majiayu000 <1835304752@qq.com>
1 parent f90d576 commit 1d42fbc

1 file changed

Lines changed: 15 additions & 1 deletion

File tree

frontend/app/block/block.tsx

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ const BlockFull = memo(({ nodeModel, viewModel }: FullBlockProps) => {
144144
const focusElemRef = useRef<HTMLInputElement>(null);
145145
const blockRef = useRef<HTMLDivElement>(null);
146146
const contentRef = useRef<HTMLDivElement>(null);
147+
const pendingFocusRafRef = useRef<number | null>(null);
147148
const [blockClicked, setBlockClicked] = useState(false);
148149
const blockView = useAtomValue(waveEnv.getBlockMetaKeyAtom(nodeModel.blockId, "view")) ?? "";
149150
const isFocused = useAtomValue(nodeModel.isFocused);
@@ -156,6 +157,14 @@ const BlockFull = memo(({ nodeModel, viewModel }: FullBlockProps) => {
156157
const innerRect = useDebouncedNodeInnerRect(nodeModel);
157158
const noPadding = useAtomValueSafe(viewModel.noPadding);
158159

160+
useEffect(() => {
161+
return () => {
162+
if (pendingFocusRafRef.current != null) {
163+
cancelAnimationFrame(pendingFocusRafRef.current);
164+
}
165+
};
166+
}, []);
167+
159168
useLayoutEffect(() => {
160169
setBlockClicked(isFocused);
161170
}, [isFocused]);
@@ -221,12 +230,17 @@ const BlockFull = memo(({ nodeModel, viewModel }: FullBlockProps) => {
221230
);
222231

223232
const setFocusTarget = useCallback(() => {
233+
if (pendingFocusRafRef.current != null) {
234+
cancelAnimationFrame(pendingFocusRafRef.current);
235+
pendingFocusRafRef.current = null;
236+
}
224237
const ok = viewModel?.giveFocus?.();
225238
if (ok) {
226239
return;
227240
}
228241
focusElemRef.current?.focus({ preventScroll: true });
229-
requestAnimationFrame(() => {
242+
pendingFocusRafRef.current = requestAnimationFrame(() => {
243+
pendingFocusRafRef.current = null;
230244
viewModel?.giveFocus?.();
231245
});
232246
}, [viewModel]);

0 commit comments

Comments
 (0)