fix(web): persist file explorer expanded tree and scroll position across navigation (#911)

* fix(web): persist file explorer expanded tree and scroll position across navigation

Expanded folder state and scroll position in the Directories tab were
stored only in local React state, so navigating to a file and back
would reset the tree to the root and scroll to top.

Now both are saved to sessionStorage (keyed by sessionId) on every
change and restored on remount, so the explorer resumes exactly where
the user left off.

Closes #910

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* fix(web): key DirectoryTree by sessionId to prevent stale expanded state across sessions

When navigating between sessions, React can reuse the same DirectoryTree
instance. The useState lazy initializer only runs on first mount, so the
tree would hydrate with the wrong session's expanded set and then
overwrite the new session's storage key.

Adding key={sessionId} forces a fresh mount per session.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

---------

Co-authored-by: HAPI <noreply@hapi.run>
This commit is contained in:
SSU-WEI HUANG
2026-06-18 10:16:32 +08:00
committed by GitHub
co-authored by HAPI
parent a8e08e8014
commit 22bf7e04d2
2 changed files with 55 additions and 4 deletions
@@ -1,4 +1,4 @@
import { useCallback, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import type { ApiClient } from '@/api/client'
import { FileIcon } from '@/components/FileIcon'
import { useSessionDirectory } from '@/hooks/queries/useSessionDirectory'
@@ -171,13 +171,40 @@ function DirectoryNode(props: {
)
}
const STORAGE_KEY_PREFIX = 'hapi-dir-expanded-'
function readExpanded(sessionId: string): Set<string> {
try {
const raw = sessionStorage.getItem(STORAGE_KEY_PREFIX + sessionId)
if (raw) {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed)) return new Set(parsed as string[])
}
} catch {
// ignore
}
return new Set([''])
}
function writeExpanded(sessionId: string, expanded: Set<string>) {
try {
sessionStorage.setItem(STORAGE_KEY_PREFIX + sessionId, JSON.stringify([...expanded]))
} catch {
// ignore
}
}
export function DirectoryTree(props: {
api: ApiClient | null
sessionId: string
rootLabel: string
onOpenFile: (path: string) => void
}) {
const [expanded, setExpanded] = useState<Set<string>>(() => new Set(['']))
const [expanded, setExpanded] = useState<Set<string>>(() => readExpanded(props.sessionId))
useEffect(() => {
writeExpanded(props.sessionId, expanded)
}, [props.sessionId, expanded])
const handleToggle = useCallback((path: string) => {
setExpanded((prev) => {