use-project-output-files.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { useEffect, useState } from 'react'
  2. import { postJSON } from '../../../infrastructure/fetch-json'
  3. import { fileCollator } from '../util/file-collator'
  4. import useAbortController from '../../../shared/hooks/use-abort-controller'
  5. export type OutputEntity = {
  6. path: string
  7. clsiServerId: string
  8. compileGroup: string
  9. build: string
  10. }
  11. const alphabetical = (a: OutputEntity, b: OutputEntity) =>
  12. fileCollator.compare(a.path, b.path)
  13. export function useProjectOutputFiles(projectId?: string) {
  14. const [loading, setLoading] = useState<boolean>(false)
  15. const [data, setData] = useState<OutputEntity[] | null>(null)
  16. const [error, setError] = useState<any>(false)
  17. const { signal } = useAbortController()
  18. useEffect(() => {
  19. if (projectId) {
  20. setLoading(true)
  21. setError(false)
  22. setData(null)
  23. postJSON(`/project/${projectId}/compile`, {
  24. body: {
  25. check: 'silent',
  26. draft: false,
  27. incrementalCompilesEnabled: false,
  28. },
  29. signal,
  30. })
  31. .then(data => {
  32. if (data.status === 'success') {
  33. const filteredFiles = data.outputFiles.filter(
  34. (file: OutputEntity) =>
  35. file.path.match(/.*\.(pdf|png|jpeg|jpg|gif)/)
  36. )
  37. data.outputFiles.forEach((file: OutputEntity) => {
  38. file.clsiServerId = data.clsiServerId
  39. file.compileGroup = data.compileGroup
  40. })
  41. setData(filteredFiles.sort(alphabetical))
  42. } else {
  43. setError('linked-project-compile-error')
  44. }
  45. })
  46. .catch(error => setError(error))
  47. .finally(() => setLoading(false))
  48. }
  49. }, [projectId, signal])
  50. return { loading, data, error }
  51. }