refactor: use ref to access latest focused document ID in applySelectedFolder callback to stabilize dependencies
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import type { Dispatch, MutableRefObject, SetStateAction } from 'react';
|
import type { Dispatch, MutableRefObject, SetStateAction } from 'react';
|
||||||
import { createRootNode, DEFAULT_FOLDER_NAME } from '../../app/workspaceUtils';
|
import { createRootNode, DEFAULT_FOLDER_NAME } from '../../app/workspaceUtils';
|
||||||
import {
|
import {
|
||||||
@@ -102,6 +102,11 @@ const useFolderTree = ({
|
|||||||
selectionAnchorRef,
|
selectionAnchorRef,
|
||||||
} = selectionHelpers;
|
} = selectionHelpers;
|
||||||
|
|
||||||
|
const focusedDocumentIdRef = useRef(focusedDocumentId);
|
||||||
|
useEffect(() => {
|
||||||
|
focusedDocumentIdRef.current = focusedDocumentId;
|
||||||
|
}, [focusedDocumentId]);
|
||||||
|
|
||||||
const applySelectedFolder = useCallback(
|
const applySelectedFolder = useCallback(
|
||||||
(folderId: FolderId, contents?: FolderContentsEntry | null) => {
|
(folderId: FolderId, contents?: FolderContentsEntry | null) => {
|
||||||
const subfolders = Array.isArray(contents?.subfolders) ? contents.subfolders : [];
|
const subfolders = Array.isArray(contents?.subfolders) ? contents.subfolders : [];
|
||||||
@@ -136,10 +141,11 @@ const useFolderTree = ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const nextFocus = (() => {
|
const nextFocus = (() => {
|
||||||
if (focusedDocumentId) {
|
const currentFocusedId = focusedDocumentIdRef.current;
|
||||||
const currentFocusedKey = createDocumentEntryKey(focusedDocumentId);
|
if (currentFocusedId) {
|
||||||
|
const currentFocusedKey = createDocumentEntryKey(currentFocusedId);
|
||||||
if (currentFocusedKey && availableDocKeySet.has(currentFocusedKey)) {
|
if (currentFocusedKey && availableDocKeySet.has(currentFocusedKey)) {
|
||||||
return focusedDocumentId;
|
return currentFocusedId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (nextDocKeys.length) {
|
if (nextDocKeys.length) {
|
||||||
@@ -156,7 +162,6 @@ const useFolderTree = ({
|
|||||||
setSelectionOrder(mergedSelection);
|
setSelectionOrder(mergedSelection);
|
||||||
},
|
},
|
||||||
[
|
[
|
||||||
focusedDocumentId,
|
|
||||||
selectionAnchorRef,
|
selectionAnchorRef,
|
||||||
selectionOrderRef,
|
selectionOrderRef,
|
||||||
setDocuments,
|
setDocuments,
|
||||||
|
|||||||
Reference in New Issue
Block a user