Skip to content

Commit d9e8329

Browse files
re-fcursoragent
andcommitted
feat: auto-focus current file in the left file tree
Highlight the open document, expand its ancestor folders, and scroll it into view so the sidebar stays oriented when navigating. Co-authored-by: Cursor <[email protected]>
1 parent 0ab494c commit d9e8329

9 files changed

Lines changed: 231 additions & 34 deletions

File tree

‎packages/frontend/src/components/LeftPane/FileTree.tsx‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import React, { useCallback, useEffect } from 'react';
33
import { useDispatch, useSelector } from 'react-redux';
44
import useIsMobile from '../../hooks/useIsMobile';
55
import {
6+
ensureExpandedNodes,
67
expandAllNodes,
78
fetchFileTree,
89
FileTreeItem,
10+
getAncestorPaths,
911
setExpandedNodes,
1012
setSearchQuery
1113
} from '../../store/slices/fileTreeSlice';
@@ -21,7 +23,12 @@ interface FileTreeComponentProps {
2123
selectedFilePath: string | null;
2224
}
2325

24-
const FileTree: React.FC<FileTreeComponentProps> = ({ onFileSelect, isOpen, onToggle }) => {
26+
const FileTree: React.FC<FileTreeComponentProps> = ({
27+
onFileSelect,
28+
isOpen,
29+
onToggle,
30+
selectedFilePath,
31+
}) => {
2532
const dispatch = useDispatch<AppDispatch>();
2633
const theme = useTheme();
2734
const isMobile = useIsMobile();
@@ -38,6 +45,16 @@ const FileTree: React.FC<FileTreeComponentProps> = ({ onFileSelect, isOpen, onTo
3845
dispatch(fetchFileTree());
3946
}, [dispatch]);
4047

48+
// Reveal the current document in the tree: expand ancestors when path changes or tree finishes loading.
49+
useEffect(() => {
50+
if (!selectedFilePath || loading) return;
51+
52+
const ancestors = getAncestorPaths(selectedFilePath);
53+
if (ancestors.length > 0) {
54+
dispatch(ensureExpandedNodes(ancestors));
55+
}
56+
}, [selectedFilePath, loading, dispatch]);
57+
4158
const handleSearchChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
4259
dispatch(setSearchQuery(event.target.value));
4360
}, [dispatch]);
@@ -115,9 +132,9 @@ const FileTree: React.FC<FileTreeComponentProps> = ({ onFileSelect, isOpen, onTo
115132
loading={loading}
116133
error={error}
117134
expandedNodes={expandedNodes}
135+
selectedFilePath={selectedFilePath}
118136
onFileSelect={isMobile ? handleFileSelectWithClose : onFileSelect}
119137
onExpandedItemsChange={handleExpandedItemsChange}
120-
dispatch={dispatch}
121138
/>
122139
)}
123140
</>

‎packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeContent.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ interface FileTreeContentProps {
1010
loading: boolean;
1111
error: string | null;
1212
expandedNodes: string[];
13+
selectedFilePath: string | null;
1314
onFileSelect: (path: string) => void;
1415
onExpandedItemsChange: (event: React.SyntheticEvent, itemIds: string[]) => void;
1516
}
@@ -19,6 +20,7 @@ const FileTreeContent: React.FC<FileTreeContentProps> = ({
1920
loading,
2021
error,
2122
expandedNodes,
23+
selectedFilePath,
2224
onFileSelect,
2325
onExpandedItemsChange,
2426
}) => {
@@ -43,6 +45,7 @@ const FileTreeContent: React.FC<FileTreeContentProps> = ({
4345
<FileTreeView
4446
filteredFileTree={filteredFileTree}
4547
expandedNodes={expandedNodes}
48+
selectedFilePath={selectedFilePath}
4649
onFileSelect={onFileSelect}
4750
onExpandedItemsChange={onExpandedItemsChange}
4851
getStatusColor={getStatusColor}
Lines changed: 50 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
22
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
33
import { SimpleTreeView } from '@mui/x-tree-view/SimpleTreeView';
4-
import React from 'react';
4+
import { useSimpleTreeViewApiRef } from '@mui/x-tree-view/hooks';
5+
import React, { useEffect } from 'react';
56
import { RecursiveTreeItems } from './RecursiveTreeItems';
67
import { FileTree } from './types';
78

89
interface FileTreeViewProps {
910
filteredFileTree: FileTree | null;
1011
expandedNodes: string[];
12+
selectedFilePath: string | null;
1113
onFileSelect: (path: string) => void;
1214
onExpandedItemsChange: (event: React.SyntheticEvent, itemIds: string[]) => void;
1315
getStatusColor: (status: string) => string;
@@ -16,18 +18,53 @@ interface FileTreeViewProps {
1618
export const FileTreeView: React.FC<FileTreeViewProps> = ({
1719
filteredFileTree,
1820
expandedNodes,
21+
selectedFilePath,
1922
onFileSelect,
2023
onExpandedItemsChange,
2124
getStatusColor
22-
}) => (
23-
<SimpleTreeView
24-
className="custom-scrollbar"
25-
defaultCollapseIcon={<ExpandMoreIcon />}
26-
defaultExpandIcon={<ChevronRightIcon />}
27-
expandedItems={expandedNodes}
28-
onExpandedItemsChange={onExpandedItemsChange}
29-
sx={{ flexGrow: 1, maxWidth: 400, overflowY: 'auto', height: 'calc(100vh - 180px)', px: 2, pb: 2 }}
30-
>
31-
<RecursiveTreeItems tree={filteredFileTree} onFileSelect={onFileSelect} getStatusColor={getStatusColor} />
32-
</SimpleTreeView>
33-
);
25+
}) => {
26+
const apiRef = useSimpleTreeViewApiRef();
27+
28+
useEffect(() => {
29+
if (!selectedFilePath) return undefined;
30+
31+
let cancelled = false;
32+
const tryScroll = () => {
33+
if (cancelled) return true;
34+
const element = apiRef.current?.getItemDOMElement?.(selectedFilePath);
35+
if (element) {
36+
element.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
37+
return true;
38+
}
39+
return false;
40+
};
41+
42+
if (tryScroll()) {
43+
return () => {
44+
cancelled = true;
45+
};
46+
}
47+
48+
// Newly expanded parents may not have mounted the item yet.
49+
const timeoutId = window.setTimeout(tryScroll, 150);
50+
return () => {
51+
cancelled = true;
52+
window.clearTimeout(timeoutId);
53+
};
54+
}, [apiRef, selectedFilePath, expandedNodes]);
55+
56+
return (
57+
<SimpleTreeView
58+
apiRef={apiRef}
59+
className="custom-scrollbar"
60+
defaultCollapseIcon={<ExpandMoreIcon />}
61+
defaultExpandIcon={<ChevronRightIcon />}
62+
expandedItems={expandedNodes}
63+
selectedItems={selectedFilePath}
64+
onExpandedItemsChange={onExpandedItemsChange}
65+
sx={{ flexGrow: 1, maxWidth: 400, overflowY: 'auto', height: 'calc(100vh - 180px)', px: 2, pb: 2 }}
66+
>
67+
<RecursiveTreeItems tree={filteredFileTree} onFileSelect={onFileSelect} getStatusColor={getStatusColor} />
68+
</SimpleTreeView>
69+
);
70+
};

‎packages/frontend/src/store/slices/fileTreeSlice.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,18 @@ const loadExpandedNodes = (path: string): string[] => {
6868
}
6969
};
7070

71+
/** Parent directory paths that must be expanded for `path` to be visible in the tree. */
72+
export const getAncestorPaths = (path: string): string[] => {
73+
const segments = path.split('/').filter(Boolean);
74+
if (segments.length <= 1) return [];
75+
76+
const ancestors: string[] = [];
77+
for (let i = 1; i < segments.length; i += 1) {
78+
ancestors.push(segments.slice(0, i).join('/'));
79+
}
80+
return ancestors;
81+
};
82+
7183
const filterTree = (
7284
tree: (FileTreeItem | { [key: string]: (FileTreeItem | object)[] })[],
7385
searchQuery: string
@@ -134,6 +146,12 @@ const fileTreeSlice = createSlice({
134146
state.expandedNodes = action.payload;
135147
saveExpandedNodes(state.mountedDirectoryPath, state.expandedNodes);
136148
},
149+
ensureExpandedNodes: (state, action: { payload: string[] }) => {
150+
const missing = action.payload.filter((path) => !state.expandedNodes.includes(path));
151+
if (missing.length === 0) return;
152+
state.expandedNodes = [...state.expandedNodes, ...missing];
153+
saveExpandedNodes(state.mountedDirectoryPath, state.expandedNodes);
154+
},
137155
expandAllNodes: (
138156
state, action: { payload: (FileTreeItem | { [key: string]: (FileTreeItem | object)[] })[] | null }
139157
) => {
@@ -252,6 +270,7 @@ export const {
252270
setSearchQuery,
253271
toggleNode,
254272
setExpandedNodes,
273+
ensureExpandedNodes,
255274
expandAllNodes,
256275
setMountedDirectoryPath,
257276
} = fileTreeSlice.actions;

‎packages/frontend/test/unit/components/LeftPane/FileTree.test.tsx‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,13 @@ import { Provider } from 'react-redux';
44
import configureStore from 'redux-mock-store';
55
import { thunk } from 'redux-thunk';
66
import FileTree from '../../../../src/components/LeftPane/FileTree';
7-
import { fetchFileTree, setSearchQuery, expandAllNodes, setExpandedNodes } from '../../../../src/store/slices/fileTreeSlice';
7+
import {
8+
ensureExpandedNodes,
9+
expandAllNodes,
10+
fetchFileTree,
11+
setExpandedNodes,
12+
setSearchQuery,
13+
} from '../../../../src/store/slices/fileTreeSlice';
814

915
const mockStore = configureStore([thunk]);
1016

@@ -15,6 +21,7 @@ jest.mock('../../../../src/store/slices/fileTreeSlice', () => ({
1521
}),
1622
expandAllNodes: jest.fn((payload) => ({ type: 'fileTree/expandAllNodes', payload })),
1723
setExpandedNodes: jest.fn((payload) => ({ type: 'fileTree/setExpandedNodes', payload })),
24+
ensureExpandedNodes: jest.fn((payload) => ({ type: 'fileTree/ensureExpandedNodes', payload })),
1825
setFilteredFileTree: jest.fn((payload) => ({ type: 'fileTree/setFilteredFileTree', payload }))
1926
}));
2027

@@ -39,6 +46,7 @@ describe('FileTree', () => {
3946
};
4047

4148
beforeEach(() => {
49+
jest.clearAllMocks();
4250
store = mockStore(initialState);
4351
jest.spyOn(store, 'dispatch');
4452
});
@@ -184,4 +192,44 @@ describe('FileTree', () => {
184192
});
185193
});
186194
});
195+
196+
test('expands ancestor folders for the selected file path', () => {
197+
render(
198+
<Provider store={store}>
199+
<FileTree
200+
onFileSelect={jest.fn()}
201+
isOpen={true}
202+
onToggle={jest.fn()}
203+
selectedFilePath="folder1/nested/file1.md"
204+
/>
205+
</Provider>
206+
);
207+
208+
expect(store.dispatch).toHaveBeenCalledWith(
209+
ensureExpandedNodes(['folder1', 'folder1/nested'])
210+
);
211+
});
212+
213+
test('does not expand ancestors while the file tree is loading', () => {
214+
store = mockStore({
215+
fileTree: {
216+
...initialState.fileTree,
217+
loading: true,
218+
},
219+
});
220+
jest.spyOn(store, 'dispatch');
221+
222+
render(
223+
<Provider store={store}>
224+
<FileTree
225+
onFileSelect={jest.fn()}
226+
isOpen={true}
227+
onToggle={jest.fn()}
228+
selectedFilePath="folder1/file1.md"
229+
/>
230+
</Provider>
231+
);
232+
233+
expect(ensureExpandedNodes).not.toHaveBeenCalled();
234+
});
187235
});

‎packages/frontend/test/unit/components/LeftPane/FileTreeContent/FileTreeContent.test.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ describe('FileTreeContent', () => {
4444
loading={true}
4545
error={null}
4646
expandedNodes={[]}
47+
selectedFilePath={null}
4748
onFileSelect={jest.fn()}
4849
onExpandedItemsChange={jest.fn()}
4950
/>
@@ -58,6 +59,7 @@ describe('FileTreeContent', () => {
5859
loading={false}
5960
error="Failed to load tree"
6061
expandedNodes={[]}
62+
selectedFilePath={null}
6163
onFileSelect={jest.fn()}
6264
onExpandedItemsChange={jest.fn()}
6365
/>
@@ -72,6 +74,7 @@ describe('FileTreeContent', () => {
7274
loading={false}
7375
error={null}
7476
expandedNodes={['folder1']}
77+
selectedFilePath={null}
7578
onFileSelect={jest.fn()}
7679
onExpandedItemsChange={jest.fn()}
7780
/>
@@ -88,6 +91,7 @@ describe('FileTreeContent', () => {
8891
loading={true}
8992
error={null}
9093
expandedNodes={['folder1']}
94+
selectedFilePath={null}
9195
onFileSelect={jest.fn()}
9296
onExpandedItemsChange={jest.fn()}
9397
/>
@@ -104,6 +108,7 @@ describe('FileTreeContent', () => {
104108
loading={false}
105109
error={null}
106110
expandedNodes={[]}
111+
selectedFilePath={null}
107112
onFileSelect={jest.fn()}
108113
onExpandedItemsChange={jest.fn()}
109114
/>
@@ -131,6 +136,7 @@ describe('FileTreeContent', () => {
131136
loading={false}
132137
error={null}
133138
expandedNodes={[]}
139+
selectedFilePath={null}
134140
onFileSelect={onFileSelectMock}
135141
onExpandedItemsChange={jest.fn()}
136142
/>
@@ -147,6 +153,7 @@ describe('FileTreeContent', () => {
147153
loading={false}
148154
error={null}
149155
expandedNodes={[]}
156+
selectedFilePath={null}
150157
onFileSelect={jest.fn()}
151158
onExpandedItemsChange={onExpandedItemsChangeMock}
152159
/>

0 commit comments

Comments
 (0)