file.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { Entity } from '../../file-tree/hooks/use-project-entities'
  2. import { OutputEntity } from '../../file-tree/hooks/use-project-output-files'
  3. export type FileOrDirectory = {
  4. name: string
  5. id: string
  6. type: 'file' | 'doc' | 'folder'
  7. children?: FileOrDirectory[]
  8. }
  9. export type File = {
  10. path: string
  11. name: string
  12. id: string
  13. }
  14. function filterByType(type: 'file' | 'doc' | 'folder') {
  15. return (
  16. tree: FileOrDirectory,
  17. path = '',
  18. list: undefined | File[] = undefined
  19. ) => {
  20. if (!tree) {
  21. return list
  22. }
  23. if (list === undefined) {
  24. list = []
  25. }
  26. const isRootFolder = tree.name === 'rootFolder' && path === ''
  27. if (tree.children) {
  28. for (const child of tree.children) {
  29. filterByType(type)(
  30. child,
  31. `${isRootFolder ? '' : `${path ? path + '/' : path}${tree.name}/`}`,
  32. list
  33. )
  34. }
  35. }
  36. if (tree.type === type) {
  37. list.push({ path, id: tree.id, name: tree.name })
  38. }
  39. return list
  40. }
  41. }
  42. export const filterFiles = filterByType('file')
  43. export const filterDocs = filterByType('doc')
  44. export const filterFolders = filterByType('folder')
  45. const IMAGE_FILE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'pdf']
  46. export function isImageFile(file: File) {
  47. const parts = file.name.split('.')
  48. if (parts.length < 2) {
  49. return false
  50. }
  51. const extension = parts[parts.length - 1].toLowerCase()
  52. return IMAGE_FILE_EXTENSIONS.includes(extension)
  53. }
  54. export function isImageEntity(file: Entity | OutputEntity) {
  55. const parts = file.path.split('.')
  56. if (parts.length < 2) {
  57. return false
  58. }
  59. const extension = parts[parts.length - 1].toLowerCase()
  60. return IMAGE_FILE_EXTENSIONS.includes(extension)
  61. }