Skip to content

Commit d6e961d

Browse files
author
Marosvölgyi Zoltán
committed
fix tree
1 parent cccc9d9 commit d6e961d

File tree

3 files changed

+196
-129
lines changed

3 files changed

+196
-129
lines changed

apps/sensenet/src/components/contentprovider/GlobalContentCollection.tsx

Lines changed: 0 additions & 39 deletions
This file was deleted.
Lines changed: 72 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,82 @@
1-
import React, { createContext, ReactNode, useState } from 'react'
1+
import { ODataCollectionResponse } from '@sensenet/client-core'
2+
import { GenericContent } from '@sensenet/default-content-types'
3+
import { useRepository } from '@sensenet/hooks-react'
4+
import React, { createContext, ReactNode, useEffect, useRef, useState } from 'react'
25
// Meghatározzuk a Context típusát: egy string tömb és egy setter függvény
3-
type ExpandItemsContextType = [Set<string>, React.Dispatch<React.SetStateAction<Set<string>>>]
6+
type ExpandItemsContextType = [
7+
Set<string>,
8+
React.Dispatch<React.SetStateAction<Set<string>>>,
9+
(path: string) => Promise<GenericContent[] | undefined>,
10+
React.Dispatch<React.SetStateAction<number>>,
11+
]
412

513
// Létrehozzuk a Context-et alapértelmezett értékekkel
614
export const ExpandItemsContext = createContext<ExpandItemsContextType | undefined>(undefined)
715

816
const ExpandedItemsProvider = ({ children }: { children: ReactNode }) => {
917
const [expandItems, setExpandItems] = useState<Set<string>>(new Set())
10-
return <ExpandItemsContext.Provider value={[expandItems, setExpandItems]}>{children}</ExpandItemsContext.Provider>
18+
const cache = useRef<{ [key: string]: { data: GenericContent[] | undefined; timestamp: number } }>({}) // Globális cache objektum
19+
const [cacheTime, setCacheTime] = useState<number>(6000)
20+
const repo = useRepository()
21+
const loadChildren = async (path: string): Promise<GenericContent[] | undefined> => {
22+
//letölti a connteneteket a megadott path alapján
23+
const loadCollection = function loadCollection(
24+
contentPath: string,
25+
): Promise<ODataCollectionResponse<GenericContent>> {
26+
return repo.loadCollection<GenericContent>({
27+
path: contentPath,
28+
oDataOptions: {
29+
select: ['Id', 'Path', 'Name', 'DisplayName', 'Type', 'Actions', 'Icon', 'ParentId'],
30+
onlyselectList: true,
31+
},
32+
})
33+
}
34+
//cache logika
35+
if (path === undefined || path === '') return undefined
36+
const now = Date.now()
37+
//ha a cachben nincs elem akkor tovább megyünk
38+
if (cache.current[path] !== undefined) {
39+
//ha a cacheben van elem és undefined akkor várunk
40+
let i = 0
41+
while (cache.current[path].data === undefined) {
42+
setTimeout(() => {}, 200)
43+
console.log('#globalfetch: waiting for response', path)
44+
i++
45+
if (i > 10) {
46+
console.log('#globalfetch: max iteration exceeded', path)
47+
return undefined
48+
}
49+
}
50+
51+
//ha a cacheben van elem és nem undefined akkor visszadjuk azt
52+
if (now - cache.current[path].timestamp < cacheTime) {
53+
console.log('#globalfetch: from cache', path)
54+
return (
55+
cache.current[path] as {
56+
data: GenericContent[] | undefined
57+
timestamp: number
58+
}
59+
)?.data
60+
}
61+
}
62+
try {
63+
const response = await loadCollection(path)
64+
//itt megkéne várni, esetleg egy await async meoldaná a problémát
65+
const result = response?.d.results
66+
cache.current[path] = { data: result, timestamp: now }
67+
console.log('#globalfetch: miss cache', path)
68+
return result
69+
//ezt nem várja meg
70+
} catch (error) {
71+
console.error('#globalfetch: Fetch error:', error)
72+
}
73+
}
74+
75+
return (
76+
<ExpandItemsContext.Provider value={[expandItems, setExpandItems, loadChildren, setCacheTime]}>
77+
{children}
78+
</ExpandItemsContext.Provider>
79+
)
1180
}
1281

1382
export default ExpandedItemsProvider
Lines changed: 124 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
1-
import { Collapse, ListItemIcon, ListItemText } from '@material-ui/core'
1+
import { ListItemIcon, ListItemText } from '@material-ui/core'
22
// @ts-ignore
33
import { createStyles, Theme, withStyles } from '@material-ui/core/styles'
44
import TreeItem from '@material-ui/lab/TreeItem'
5-
import { ODataCollectionResponse } from '@sensenet/client-core'
65
import { GenericContent } from '@sensenet/default-content-types'
7-
import { useRepository } from '@sensenet/hooks-react'
8-
//import { useQueryClient } from 'react-query'
96
import React, { useCallback, useContext, useEffect, useState } from 'react'
10-
import { useGlobalCacheFetch } from '../contentprovider/GlobalContentCollection'
117
import { Icon } from '../Icon'
128
import { ExpandItemsContext } from './Contexts/ExpandedItemsProvider'
139
import StyledTreeItemProps from './Props/StyledTreeItemProps'
@@ -26,41 +22,18 @@ export const StyledTreeItem = withStyles((theme: Theme) =>
2622
},
2723
}),
2824
)((props: StyledTreeItemProps) => {
29-
const repo = useRepository()
30-
//const queryClient = useQueryClient()
31-
const [innerElements, setInnerElements] = useState<[]>()
32-
const [childrenLoaded, setChildrenLoaded] = useState<boolean>(false)
25+
const [hasChildren, setHasChildren] = useState<boolean>(true)
26+
const [innerElements, setInnerElements] = useState<React.JSX.Element[]>()
3327
const expContext = useContext(ExpandItemsContext)
3428
if (!expContext) {
3529
throw new Error('MyComponent must be used within a ExpandItemsProvider')
3630
}
37-
// const fetchCollection = (contentPath: string): Promise<ODataCollectionResponse<GenericContent>> => {
38-
// return repo.loadCollection<GenericContent>({
39-
// path: contentPath,
40-
// oDataOptions: {
41-
// select: ['Id', 'Path', 'Name', 'DisplayName', 'Type', 'Actions', 'Icon', 'ParentId'],
42-
// onlyselectList: true,
43-
// },
44-
// })
45-
// }
4631

47-
const { data } = useGlobalCacheFetch('https://jsonplaceholder.typicode.com/todos', 60000)
48-
const [expandItems, setExpandItems] = expContext
32+
const [expandItems, setExpandItems, loadChildren] = expContext
4933
const loadCollectionCB = useCallback(() => {
50-
function loadCollection(contentPath: string): Promise<ODataCollectionResponse<GenericContent>> {
51-
return repo.loadCollection<GenericContent>({
52-
path: contentPath,
53-
oDataOptions: {
54-
select: ['Id', 'Path', 'Name', 'DisplayName', 'Type', 'Actions', 'Icon', 'ParentId'],
55-
onlyselectList: true,
56-
},
57-
})
58-
}
59-
60-
setChildrenLoaded(true)
61-
const respRequest = loadCollection(props.contentvalue.Path)
62-
respRequest.then((result: any) => {
63-
const elements = result?.d.results.map((innerChild: GenericContent) => {
34+
const children = loadChildren(props.contentvalue.Path)
35+
children.then((result: GenericContent[] | undefined) => {
36+
const elements = result?.map((innerChild: GenericContent) => {
6437
return (
6538
<StyledTreeItem
6639
id="1"
@@ -73,57 +46,123 @@ export const StyledTreeItem = withStyles((theme: Theme) =>
7346
isOpen={true}
7447
parentisopen={true}
7548
onNavigate={props.onNavigate}
76-
// addItemToExpanded={props.addItemToExpanded}
77-
// expandedItems={props.expandedItems}
78-
// getExpandedItems={props.getExpandedItems}
7949
/>
8050
)
8151
})
82-
setInnerElements(elements)
83-
//}
52+
if (elements !== undefined) {
53+
setHasChildren(elements.length > 0)
54+
setInnerElements(elements)
55+
}
8456
})
85-
}, [props.activeItemPath, props.contentvalue.Path, props.onNavigate, repo])
86-
57+
}, [loadChildren, props.activeItemPath, props.contentvalue.Path, props.onNavigate])
8758
useEffect(() => {
88-
console.log('#exptree: 2nd 0cb', props.contentvalue.Id, props.activeItemPath, props.contentvalue.Path)
89-
//első gyerekeke letöltése
90-
if (!childrenLoaded && props.id !== undefined && props.id === '0') {
91-
console.log('#exptree: 1st lcb', props.contentvalue.Id)
92-
loadCollectionCB()
93-
}
94-
//A currentpath-t tartalmazó elemeket kinyitjuk
95-
if (props.activeItemPath.startsWith(props.contentvalue.Path)) {
96-
console.log('#exptree: 2nd lcb', props.contentvalue.Id, props.activeItemPath, props.contentvalue.Path)
59+
if (props.id === '0') {
9760
loadCollectionCB()
98-
// const { data, fetchData, loading } = useGlobalCacheFetch('https://jsonplaceholder.typicode.com/todos', 60000)
99-
// fetchData().then(() => {
100-
// console.log('fetchData result', data)
101-
// })
102-
setExpandItems((eItems) => eItems.add(props.contentvalue.Id.toString()))
10361
}
62+
}, [props.id, loadCollectionCB])
63+
// const loadCollectionCB = useCallback(() => {
64+
// function loadCollection(contentPath: string): Promise<ODataCollectionResponse<GenericContent>> {
65+
// return repo.loadCollection<GenericContent>({
66+
// path: contentPath,
67+
// oDataOptions: {
68+
// select: ['Id', 'Path', 'Name', 'DisplayName', 'Type', 'Actions', 'Icon', 'ParentId'],
69+
// onlyselectList: true,
70+
// },
71+
// })
72+
// }
10473

105-
//Első betöltésre: Ha a parent parentje closed akkor nem töltök be gyerek elemeket, amikor a treeitem nincs nyitva, de a parent igen
106-
console.log('#exptree: 3rd lcb', props.contentvalue, expandItems)
107-
let parentIdString = ''
108-
const parentId = props.contentvalue.ParentId?.toString()
109-
if (parentId !== undefined) {
110-
parentIdString = parentId
111-
}
112-
if (expandItems.has(parentIdString)) {
113-
//loadCollectionCB()
114-
console.log('#exptree: parent opened', props.contentvalue, expandItems)
115-
}
116-
}, [
117-
props,
118-
childrenLoaded,
119-
loadCollectionCB,
120-
expandItems,
121-
setExpandItems,
122-
props.contentvalue.Path,
123-
props.isOpen,
124-
props.parentisopen,
125-
repo,
126-
])
74+
// setChildrenLoaded(true)
75+
// const respRequest = loadCollection(props.contentvalue.Path)
76+
// respRequest.then((result: any) => {
77+
// const elements = result?.d.results.map((innerChild: GenericContent) => {
78+
// return (
79+
// <StyledTreeItem
80+
// id="1"
81+
// key={innerChild.Id}
82+
// activeItemPath={props.activeItemPath}
83+
// itemID={innerChild.Id.toString()}
84+
// nodeId={innerChild.Id.toString()}
85+
// label={`${innerChild.Name} ${innerChild.Id}`}
86+
// contentvalue={innerChild}
87+
// isOpen={true}
88+
// parentisopen={true}
89+
// onNavigate={props.onNavigate}
90+
// // addItemToExpanded={props.addItemToExpanded}
91+
// // expandedItems={props.expandedItems}
92+
// // getExpandedItems={props.getExpandedItems}
93+
// />
94+
// )
95+
// })
96+
// setInnerElements(elements)
97+
// //}
98+
// })
99+
// }, [props.activeItemPath, props.contentvalue.Path, props.onNavigate, repo])
100+
101+
// useEffect(() => {
102+
// const childs = loadChildren(props.contentvalue.Path)
103+
// const elements = childs?.map((innerChild: GenericContent) => {
104+
// return (
105+
// <StyledTreeItem
106+
// id="1"
107+
// key={innerChild.Id}
108+
// activeItemPath={props.activeItemPath}
109+
// itemID={innerChild.Id.toString()}
110+
// nodeId={innerChild.Id.toString()}
111+
// label={`${innerChild.Name} ${innerChild.Id}`}
112+
// contentvalue={innerChild}
113+
// isOpen={true}
114+
// parentisopen={true}
115+
// onNavigate={props.onNavigate}
116+
// // addItemToExpanded={props.addItemToExpanded}
117+
// // expandedItems={props.expandedItems}
118+
// // getExpandedItems={props.getExpandedItems}
119+
// />
120+
// )
121+
// })
122+
// if (elements !== undefined) {
123+
// setInnerElements(elements)
124+
// }
125+
// }, [props.activeItemPath, props.contentvalue.Path, props.onNavigate, loadChildren])
126+
// useEffect(() => {
127+
// console.log('#exptree: 2nd 0cb', props.contentvalue.Id, props.activeItemPath, props.contentvalue.Path)
128+
// //első gyerekeke letöltése
129+
// if (!childrenLoaded && props.id !== undefined && props.id === '0') {
130+
// console.log('#exptree: 1st lcb', props.contentvalue.Id)
131+
// loadCollectionCB()
132+
// }
133+
// //A currentpath-t tartalmazó elemeket kinyitjuk
134+
// if (props.activeItemPath.startsWith(props.contentvalue.Path)) {
135+
// console.log('#exptree: 2nd lcb', props.contentvalue.Id, props.activeItemPath, props.contentvalue.Path)
136+
// // loadCollectionCB()
137+
// // const { data, fetchData, loading } = useGlobalCacheFetch('https://jsonplaceholder.typicode.com/todos', 60000)
138+
// // fetchData().then(() => {
139+
// // console.log('fetchData result', data)
140+
// // })
141+
// setExpandItems((eItems) => eItems.add(props.contentvalue.Id.toString()))
142+
// }
143+
144+
// //Első betöltésre: Ha a parent parentje closed akkor nem töltök be gyerek elemeket, amikor a treeitem nincs nyitva, de a parent igen
145+
// console.log('#exptree: 3rd lcb', props.contentvalue, expandItems)
146+
// let parentIdString = ''
147+
// const parentId = props.contentvalue.ParentId?.toString()
148+
// if (parentId !== undefined) {
149+
// parentIdString = parentId
150+
// }
151+
// if (expandItems.has(parentIdString)) {
152+
// //loadCollectionCB()
153+
// console.log('#exptree: parent opened', props.contentvalue, expandItems)
154+
// }
155+
// }, [
156+
// props,
157+
// childrenLoaded,
158+
// loadCollectionCB,
159+
// expandItems,
160+
// setExpandItems,
161+
// props.contentvalue.Path,
162+
// props.isOpen,
163+
// props.parentisopen,
164+
// repo,
165+
// ])
127166
//console.log('#exptree on render', expandItems, props.contentvalue.Id)
128167
if (props.activeItemPath.startsWith(props.contentvalue.Path)) {
129168
console.log('#exptree: treeitem root render', props.contentvalue.Id, props.activeItemPath, props.contentvalue.Path)
@@ -138,33 +177,31 @@ export const StyledTreeItem = withStyles((theme: Theme) =>
138177
<ListItemIcon key={props.contentvalue.Id}>
139178
<Icon item={props.contentvalue} />
140179
</ListItemIcon>
141-
<ListItemText
142-
style={{ fontSize: '11px!important' }}
143-
primary={`${props.contentvalue.Name} ${props.contentvalue.Id} `}
144-
/>
180+
<ListItemText style={{ fontSize: '11px!important' }} primary={`${props.contentvalue.Name}`} />
145181
</>
146182
}
147-
// id="1"
148-
183+
id={props.contentvalue.Id.toString()}
149184
onIconClick={() => {
150185
//Ha a lenyílóra kattintasz akkor hozzáadjuk hogy őt ki kell nyitni
151186
if (expandItems.has(props.contentvalue.Id.toString())) {
152187
const deleteResult = expandItems.delete(props.contentvalue.Id.toString())
153188
if (deleteResult) {
154-
// setExpandItems((eItems) => eItems)
189+
setExpandItems((eItems) => eItems)
155190
console.log('#exptree: close', props.contentvalue.Id, expandItems)
156191
}
157-
loadCollectionCB()
158192
} else {
159-
//setExpandItems((eItems) => eItems.add(props.contentvalue.Id.toString()))
193+
loadCollectionCB()
194+
setExpandItems((eItems) => eItems.add(props.contentvalue.Id.toString()))
160195
console.log('#exptree: open', props.contentvalue.Id, expandItems)
161196
}
162197
}}
163198
onLabelClick={() => {
164199
//On click-re csak contextust kell válltani
165200
props.onNavigate(props.contentvalue)
166-
}}>
201+
}}
202+
collapseIcon={!hasChildren && <></>}>
167203
{innerElements}
204+
<></>
168205
</TreeItem>
169206
)
170207
})

0 commit comments

Comments
 (0)