SQLEditorNav.utils.ts79 lines · main
1import { SnippetFolderResponse } from '@/data/content/sql-folders-query'
2
3export interface TreeViewItemProps {
4 id: string | number
5 name: string
6 parent: number | string | null
7 children: any[]
8 metadata?: any
9}
10
11export const ROOT_NODE: TreeViewItemProps = { id: 0, name: '', parent: null, children: [] }
12
13// [Joshen] At the moment this is only tuned for single level folders
14// Will need to relook at this for multi level folders,
15export const formatFolderResponseForTreeView = (
16 response?: SnippetFolderResponse
17): TreeViewItemProps[] => {
18 if (response === undefined) return [ROOT_NODE]
19
20 const { folders, contents } = response
21
22 const formattedFolders =
23 folders?.map((folder) => {
24 const { id, name } = folder
25 return {
26 id,
27 name,
28 parent: 0,
29 isBranch: true,
30 children:
31 contents?.filter((content) => content.folder_id === id).map((content) => content.id) ??
32 [],
33 metadata: folder,
34 }
35 }) || []
36
37 const formattedContents =
38 contents?.map((content) => {
39 const { id, name, folder_id } = content
40 return { id, name, parent: folder_id ?? 0, children: [], metadata: content }
41 }) || []
42
43 const root = {
44 id: 0,
45 name: '',
46 parent: null,
47 children: [
48 ...(folders || [])?.map((folder) => folder.id),
49 ...(contents || []).filter((content) => !content.folder_id)?.map((content) => content.id),
50 ],
51 }
52
53 return [root, ...formattedFolders, ...formattedContents]
54}
55
56export function getLastItemIds(items: TreeViewItemProps[]) {
57 let lastItemIds = new Set<string>()
58
59 const topLevelItems = items.filter((item) => item.parent === 0)
60
61 if (topLevelItems.length > 0) {
62 const lastItem = topLevelItems[topLevelItems.length - 1]
63 if (typeof lastItem.id === 'string') {
64 lastItemIds.add(lastItem.id)
65 }
66
67 topLevelItems.forEach((item) => {
68 if (item.children.length > 0) {
69 const childrenLastItem = item.children[item.children.length - 1]
70
71 if (typeof childrenLastItem === 'string') {
72 lastItemIds.add(childrenLastItem)
73 }
74 }
75 })
76 }
77
78 return lastItemIds
79}