1
1
import { Meta } from '@storybook/react' ;
2
- import { useEffect , useMemo } from 'react' ;
2
+ import { useEffect , useMemo , useRef } from 'react' ;
3
3
import * as React from 'react' ;
4
4
import { shortTree } from 'demodata' ;
5
5
import { Tree } from '../tree/Tree' ;
@@ -8,6 +8,7 @@ import { UncontrolledTreeEnvironment } from '../uncontrolledEnvironment/Uncontro
8
8
import {
9
9
Disposable ,
10
10
TreeDataProvider ,
11
+ TreeEnvironmentRef ,
11
12
TreeItem ,
12
13
TreeItemIndex ,
13
14
} from '../types' ;
@@ -17,6 +18,7 @@ export default {
17
18
} as Meta ;
18
19
19
20
export const InjectingDataFromOutside = ( ) => {
21
+ const treeEnv = useRef < TreeEnvironmentRef > ( null ) ;
20
22
const items = useMemo ( ( ) => ( { ...shortTree . items } ) , [ ] ) ;
21
23
const dataProvider = useMemo (
22
24
( ) =>
@@ -36,15 +38,24 @@ export const InjectingDataFromOutside = () => {
36
38
37
39
const removeItem = ( ) => {
38
40
if ( items . root . children . length === 0 ) return ;
39
- items . root . children . pop ( ) ;
41
+ const item = items . root . children . pop ( ) ;
42
+ delete items [ item ] ;
40
43
dataProvider . onDidChangeTreeDataEmitter . emit ( [ 'root' ] ) ;
41
44
} ;
42
45
43
- useEffect ( ( ) => {
44
- dataProvider . onDidChangeTreeData ( changedItemIds => {
45
- console . log ( changedItemIds ) ;
46
- } ) ;
47
- } , [ dataProvider ] ) ;
46
+ useEffect (
47
+ ( ) =>
48
+ dataProvider . onDidChangeTreeData ( changedItemIds => {
49
+ console . log ( 'Changed Item IDs:' , changedItemIds ) ;
50
+
51
+ const focusedItem = treeEnv . current ?. viewState [ 'tree-1' ] ?. focusedItem ;
52
+ if ( focusedItem && ! items [ focusedItem ] ) {
53
+ console . log ( 'Focused item was deleted, refocusing new item...' ) ;
54
+ treeEnv . current . focusItem ( items . root . children [ 0 ] , 'tree-1' ) ;
55
+ }
56
+ } ) . dispose ,
57
+ [ dataProvider , items ]
58
+ ) ;
48
59
49
60
return (
50
61
< UncontrolledTreeEnvironment < string >
@@ -58,6 +69,7 @@ export const InjectingDataFromOutside = () => {
58
69
expandedItems : [ ] ,
59
70
} ,
60
71
} }
72
+ ref = { treeEnv }
61
73
>
62
74
< button type = "button" onClick = { injectItem } >
63
75
Inject item
0 commit comments