file.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 filterFolders = filterByType('folder')
  44. const IMAGE_FILE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'pdf', 'eps']
  45. export const hasImageExtension = (filename: string) => {
  46. const parts = filename.split('.')
  47. if (parts.length < 2) {
  48. return false
  49. }
  50. const extension = parts[parts.length - 1].toLowerCase()
  51. return IMAGE_FILE_EXTENSIONS.includes(extension)
  52. }
  53. export function isImageFile(file: File) {
  54. return hasImageExtension(file.name)
  55. }
  56. export function isImageEntity(file: Entity | OutputEntity) {
  57. return hasImageExtension(file.path)
  58. }