@@ -45,23 +45,45 @@ export function FileTree(props: { active: boolean }) {
4545 const cwd = selectedWorkspaceId
4646 ? workspaces [ selectedWorkspaceId ] ?. worktreePath
4747 : null ;
48+ const subscriptionRef = useRef < ( ( ) => void ) | null > ( null ) ;
4849
4950 useEffect ( ( ) => {
5051 inited . current = false ;
51- init ( true ) ;
52+ if ( cwd ) {
53+ init ( true ) ;
54+ return ( ) => {
55+ // stop watching to save system resources
56+ request < any > ( 'fs.unwatch' , { cwd } ) ;
57+ // stop waiting for notifications
58+ const messageBus = useStore . getState ( ) ?. messageBus ;
59+ if ( messageBus && subscriptionRef . current ) {
60+ messageBus . removeEventHandler ( 'fs-change' , subscriptionRef . current ) ;
61+ }
62+ } ;
63+ }
5264 } , [ cwd ] ) ;
5365
54- useEffect ( ( ) => {
55- if ( active && inited . current ) {
56- init ( false ) ;
66+ const waitForNotifications = ( cwd : string ) => {
67+ const messageBus = useStore . getState ( ) ?. messageBus ;
68+ if ( ! messageBus || ! cwd ) {
69+ return ;
70+ }
71+ if ( subscriptionRef . current ) {
72+ messageBus . removeEventHandler ( 'fs-change' , subscriptionRef . current ) ;
5773 }
58- } , [ active ] ) ;
74+ // recreate handler with new cwd
75+ subscriptionRef . current = ( ) => {
76+ console . log ( 'sth changed in' , cwd ) ;
77+ init ( ) ;
78+ } ;
79+ messageBus . onEvent ( 'fs-change' , subscriptionRef . current ) ;
80+ } ;
5981
60- const init = async ( clear = false ) => {
82+ const init = async ( reset = false ) => {
6183 if ( ! cwd ) {
6284 return ;
6385 }
64- if ( clear ) {
86+ if ( reset ) {
6587 setSelectedKey ( null ) ;
6688 setExpandedKeys ( new Set ( ) ) ;
6789 setItemToDelete ( null ) ;
@@ -71,6 +93,12 @@ export function FileTree(props: { active: boolean }) {
7193 if ( res ?. data ?. tree ) {
7294 setTreeData ( res . data . tree ) ;
7395 }
96+ // start watch and wait for notifications
97+ if ( reset ) {
98+ request < any > ( 'fs.watch' , { cwd } ) . then ( ( ) => {
99+ waitForNotifications ( cwd ) ;
100+ } ) ;
101+ }
74102 } ) ;
75103 } ;
76104
@@ -109,10 +137,7 @@ export function FileTree(props: { active: boolean }) {
109137 const handleRename = async ( oldPath : string , newPath : string ) => {
110138 try {
111139 const result = await request < any > ( 'fs.rename' , { oldPath, newPath } ) ;
112-
113140 if ( result . success ) {
114- init ( ) ;
115-
116141 // 如果当前选中的文件就是被重命名的文件
117142 if ( selectedKey === oldPath ) {
118143 setSelectedKey ( newPath ) ;
@@ -134,7 +159,6 @@ export function FileTree(props: { active: boolean }) {
134159 } ) ;
135160
136161 if ( result . success ) {
137- init ( ) ;
138162 if ( selectedKey === itemToDelete . fullPath ) {
139163 setSelectedKey ( null ) ;
140164 }
0 commit comments