file-tree-path.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { createContext, FC, useCallback, useContext, useMemo } from 'react'
  2. import { Folder } from '../../../../../types/folder'
  3. import { useFileTreeData } from '@/shared/context/file-tree-data-context'
  4. import getMeta from '@/utils/meta'
  5. import {
  6. findEntityByPath,
  7. previewByPath,
  8. dirname,
  9. FindResult,
  10. pathInFolder,
  11. } from '@/features/file-tree/util/path'
  12. import { PreviewPath } from '../../../../../types/preview-path'
  13. type FileTreePathContextValue = {
  14. pathInFolder: (id: string) => string | null
  15. findEntityByPath: (path: string) => FindResult | null
  16. previewByPath: (path: string) => PreviewPath | null
  17. dirname: (id: string) => string | null
  18. }
  19. export const FileTreePathContext = createContext<
  20. FileTreePathContextValue | undefined
  21. >(undefined)
  22. export const FileTreePathProvider: FC = ({ children }) => {
  23. const { fileTreeData }: { fileTreeData: Folder } = useFileTreeData()
  24. const projectId = getMeta('ol-project_id') as string
  25. const pathInFileTree = useCallback(
  26. (id: string) => pathInFolder(fileTreeData, id),
  27. [fileTreeData]
  28. )
  29. const findEntityByPathInFileTree = useCallback(
  30. (path: string) => findEntityByPath(fileTreeData, path),
  31. [fileTreeData]
  32. )
  33. const previewByPathInFileTree = useCallback(
  34. (path: string) => previewByPath(fileTreeData, projectId, path),
  35. [fileTreeData, projectId]
  36. )
  37. const dirnameInFileTree = useCallback(
  38. (id: string) => dirname(fileTreeData, id),
  39. [fileTreeData]
  40. )
  41. const value = useMemo<FileTreePathContextValue>(
  42. () => ({
  43. pathInFolder: pathInFileTree,
  44. findEntityByPath: findEntityByPathInFileTree,
  45. previewByPath: previewByPathInFileTree,
  46. dirname: dirnameInFileTree,
  47. }),
  48. [
  49. pathInFileTree,
  50. findEntityByPathInFileTree,
  51. previewByPathInFileTree,
  52. dirnameInFileTree,
  53. ]
  54. )
  55. return (
  56. <FileTreePathContext.Provider value={value}>
  57. {children}
  58. </FileTreePathContext.Provider>
  59. )
  60. }
  61. export function useFileTreePathContext(): FileTreePathContextValue {
  62. const context = useContext(FileTreePathContext)
  63. if (!context) {
  64. throw new Error(
  65. 'useFileTreePathContext is only available inside FileTreePathProvider'
  66. )
  67. }
  68. return context
  69. }