SQLEditorNav.utils.ts 2.1 KB

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