Skip to content

feat: auto-focus current file in the left file tree - #849

Merged
unhappychoice merged 1 commit into
unhappychoice:mainfrom
re-f:feature/file-tree-auto-focus
Jul 25, 2026
Merged

unhappychoice merged 1 commit into
unhappychoice:mainfrom
re-f:feature/file-tree-auto-focus

Conversation

@re-f

@re-f re-f commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Highlight the currently open document in the left file tree via selectedItems
  • Expand ancestor folders when the path changes or the tree finishes loading (ensureExpandedNodes)
  • Scroll the selected item into view so deep files stay visible after navigation

Test plan

  • Open a nested markdown file (e.g. docs/a/b/file.md) and confirm the sidebar expands parents, selects the file, and scrolls it into view
  • Navigate between files and confirm selection follows currentPath without collapsing unrelated expanded folders
  • Manually collapse a parent while a nested file is open; confirm it is not forcibly re-expanded until the path changes
  • cd packages/frontend && npm test -- --testPathPatterns='FileTree|fileTreeSlice'

Made with Cursor

Summary by CodeRabbit

  • New Features

    • Automatically expands folders leading to the currently selected file.
    • Scrolls the selected file into view in the file tree with smooth positioning.
    • Preserves expanded folder state for easier navigation.
  • Tests

    • Added coverage for automatic folder expansion, selected-file scrolling, loading states, and expanded-state persistence.

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]>
@re-f
re-f requested a review from unhappychoice as a code owner July 22, 2026 04:43
@netlify

netlify Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for mdts-unhappychoice ready!

Name Link
🔨 Latest commit d9e8329
🔍 Latest deploy log https://app.netlify.com/projects/mdts-unhappychoice/deploys/6a604a5a6706d9000899a3e4
😎 Deploy Preview https://deploy-preview-849--mdts-unhappychoice.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The file tree now expands ancestor directories for the selected document and scrolls that document into view. Selection state is passed from FileTree through FileTreeContent to FileTreeView, with Redux persistence and unit-test coverage added.

Changes

Selected file tree handling

Layer / File(s) Summary
Ancestor expansion state
packages/frontend/src/store/slices/fileTreeSlice.ts, packages/frontend/test/unit/store/fileTreeSlice.test.ts
Adds ancestor-path calculation and an idempotent reducer that merges and persists expanded directories.
Selected path expansion wiring
packages/frontend/src/components/LeftPane/FileTree.tsx, packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeContent.tsx, packages/frontend/test/unit/components/LeftPane/FileTree*.test.tsx
Expands selected-file ancestors after loading and propagates selectedFilePath through the tree components.
Selected item scrolling
packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeView.tsx, packages/frontend/test/unit/components/LeftPane/FileTreeContent/FileTreeView.test.tsx
Locates the selected tree item, retries when necessary, and scrolls it into view with cleanup handling.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant FileTree
  participant fileTreeSlice
  participant FileTreeContent
  participant FileTreeView
  participant TreeDOM
  FileTree->>fileTreeSlice: dispatch ancestor expansion
  fileTreeSlice->>fileTreeSlice: persist expanded nodes
  FileTree->>FileTreeContent: pass selectedFilePath
  FileTreeContent->>FileTreeView: pass selectedFilePath
  FileTreeView->>TreeDOM: locate selected item
  TreeDOM-->>FileTreeView: return item element
  FileTreeView->>TreeDOM: scroll selected item into view
Loading

Suggested reviewers: unhappychoice, unhappychoice

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: keeping the current file visible in the left tree via selection, expansion, and scrolling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeView.tsx (1)

28-54: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Single fixed-delay retry may miss deeply-nested or slow-mounting items.

The scroll effect tries once immediately, then once more after a hardcoded 150ms. If ancestor expansion cascades across multiple levels (e.g., a deeply nested file needs several ensureExpandedNodes dispatches to fully mount), the item may still not exist in the DOM after 150ms, and scrolling silently fails with no further retries.

♻️ Suggested approach: bounded retry loop
-    if (tryScroll()) {
-      return () => {
-        cancelled = true;
-      };
-    }
-
-    // Newly expanded parents may not have mounted the item yet.
-    const timeoutId = window.setTimeout(tryScroll, 150);
-    return () => {
-      cancelled = true;
-      window.clearTimeout(timeoutId);
-    };
+    if (tryScroll()) {
+      return () => {
+        cancelled = true;
+      };
+    }
+
+    // Newly expanded parents may not have mounted the item yet; retry a few times.
+    let attempts = 0;
+    const maxAttempts = 5;
+    const intervalId = window.setInterval(() => {
+      attempts += 1;
+      if (tryScroll() || attempts >= maxAttempts) {
+        window.clearInterval(intervalId);
+      }
+    }, 100);
+    return () => {
+      cancelled = true;
+      window.clearInterval(intervalId);
+    };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeView.tsx`
around lines 28 - 54, Replace the single 150ms retry in the selectedFilePath
scroll effect with a bounded retry loop that continues checking
getItemDOMElement while ancestor expansion and mounting complete, stopping when
the element is found or the retry limit is reached. Preserve cancellation and
timeout cleanup so stale effects cannot scroll after dependencies change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/frontend/test/unit/components/LeftPane/FileTreeContent/FileTreeView.test.tsx`:
- Around line 19-31: Stub element.scrollIntoView for the FileTreeView tests
before the “should render correctly” render, reusing the existing stub from the
following test if available; otherwise add the stub to shared test setup. Ensure
the selected item mount path can execute without calling the unimplemented DOM
method.

---

Nitpick comments:
In `@packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeView.tsx`:
- Around line 28-54: Replace the single 150ms retry in the selectedFilePath
scroll effect with a bounded retry loop that continues checking
getItemDOMElement while ancestor expansion and mounting complete, stopping when
the element is found or the retry limit is reached. Preserve cancellation and
timeout cleanup so stale effects cannot scroll after dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 16a9c518-bd32-439f-b417-12b5e0d84dfa

📥 Commits

Reviewing files that changed from the base of the PR and between 0ab494c and d9e8329.

⛔ Files ignored due to path filters (1)
  • packages/frontend/test/unit/components/LeftPane/FileTreeContent/__snapshots__/FileTreeView.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (8)
  • packages/frontend/src/components/LeftPane/FileTree.tsx
  • packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeContent.tsx
  • packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeView.tsx
  • packages/frontend/src/store/slices/fileTreeSlice.ts
  • packages/frontend/test/unit/components/LeftPane/FileTree.test.tsx
  • packages/frontend/test/unit/components/LeftPane/FileTreeContent/FileTreeContent.test.tsx
  • packages/frontend/test/unit/components/LeftPane/FileTreeContent/FileTreeView.test.tsx
  • packages/frontend/test/unit/store/fileTreeSlice.test.ts

Comment on lines +19 to 31
it('should render correctly', () => {
const { asFragment } = render(
<FileTreeView
filteredFileTree={filteredFileTree}
expandedNodes={expandedNodes}
selectedFilePath="dir1/file2.md"
onFileSelect={onFileSelect}
onExpandedItemsChange={onExpandedItemsChange}
getStatusColor={getStatusColor}
/>
);
expect(asFragment()).toMatchSnapshot();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n "scrollIntoView" --type=ts --type=js packages/frontend
fd -i 'jest.setup' packages/frontend
fd -i 'setupFilesAfterEnv' packages/frontend
cat packages/frontend/jest.config.* 2>/dev/null

Repository: unhappychoice/mdts

Length of output: 2258


🏁 Script executed:

#!/bin/bash
set -e
wc -l packages/frontend/test/setupTests.ts packages/frontend/test/unit/components/LeftPane/FileTreeContent/FileTreeView.test.tsx packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeView.tsx
cat -n packages/frontend/test/setupTests.ts
printf '\n--- FileTreeView.test.tsx ---\n'
sed -n '1,120p' packages/frontend/test/unit/components/LeftPane/FileTreeContent/FileTreeView.test.tsx
printf '\n--- FileTreeView.tsx ---\n'
sed -n '1,120p' packages/frontend/src/components/LeftPane/FileTreeContent/FileTreeView.tsx

Repository: unhappychoice/mdts

Length of output: 5641


🏁 Script executed:

#!/bin/bash
set -e
ls -l packages/frontend/test/setupTests.ts
cat -n packages/frontend/test/setupTests.ts | sed -n '1,200p'

Repository: unhappychoice/mdts

Length of output: 1434


Stub scrollIntoView here
This render path can call element.scrollIntoView(...) when the selected item mounts, but the test doesn’t mock it locally and there’s no shared stub in packages/frontend/test/setupTests.ts. Reuse the stub from the next test or add one to shared setup.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/frontend/test/unit/components/LeftPane/FileTreeContent/FileTreeView.test.tsx`
around lines 19 - 31, Stub element.scrollIntoView for the FileTreeView tests
before the “should render correctly” render, reusing the existing stub from the
following test if available; otherwise add the stub to shared test setup. Ensure
the selected item mount path can execute without calling the unimplemented DOM
method.

@codecov

codecov Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.87179% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.30%. Comparing base (0ab494c) to head (d9e8329).
⚠️ Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
...mponents/LeftPane/FileTreeContent/FileTreeView.tsx 90.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #849      +/-   ##
==========================================
- Coverage   99.41%   99.30%   -0.12%     
==========================================
  Files          69       69              
  Lines        1549     1586      +37     
  Branches      374      379       +5     
==========================================
+ Hits         1540     1575      +35     
- Misses          8       10       +2     
  Partials        1        1              
Flag Coverage Δ
frontend 99.27% <94.87%> (-0.17%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@unhappychoice unhappychoice left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the clean, well-tested change. ensureExpandedNodes being idempotent and skipping the localStorage write when there is nothing new is a nice touch, and I like that user-collapsed folders are only re-expanded on path change.

One small concern before I merge: in FileTreeView.tsx, the scroll useEffect lists expandedNodes in its dependency array. This means the selected file will scroll back into view any time the user expands or collapses an unrelated folder elsewhere in the tree, which may feel a bit unexpected during manual browsing. Would it make sense to drop expandedNodes from the deps and rely on selectedFilePath alone, or gate the scroll so it only runs on selection changes?

Approving so this is not blocking. Happy to merge as-is if you prefer to keep the current behavior.

@unhappychoice
unhappychoice merged commit a92efb2 into unhappychoice:main Jul 25, 2026
7 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants