file.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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', 'svg']
  45. export const getFileExtension = (filename: string): string | null => {
  46. const parts = filename.split('.')
  47. if (parts.length < 2) {
  48. return null
  49. }
  50. return parts[parts.length - 1].toLowerCase()
  51. }
  52. export const hasImageExtension = (filename: string) => {
  53. const extension = getFileExtension(filename)
  54. return extension !== null && IMAGE_FILE_EXTENSIONS.includes(extension)
  55. }
  56. export const isSvgFile = (filename: string): boolean => {
  57. return getFileExtension(filename) === 'svg'
  58. }
  59. export function isImageFile(file: File) {
  60. return hasImageExtension(file.name)
  61. }
  62. export function isImageEntity(file: Entity | OutputEntity) {
  63. return hasImageExtension(file.path)
  64. }