use-convert-project.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { getJSON } from '@/infrastructure/fetch-json'
  2. import { useLocation } from '@/shared/hooks/use-location'
  3. import { debugConsole } from '@/utils/debugging'
  4. import { useProjectContext } from '@/shared/context/project-context'
  5. import { useCallback } from 'react'
  6. import {
  7. hidePreparingExportToast,
  8. showExportDocumentError,
  9. showExportDocumentSuccess,
  10. showPreparingExportToast,
  11. } from '../components/toolbar/export-document-toasts'
  12. const SLOW_CONVERSION_THRESHOLD = 2000
  13. export default function useConvertProject(type: 'docx' | 'markdown') {
  14. const { projectId } = useProjectContext()
  15. const location = useLocation()
  16. const triggerConversion = useCallback(async () => {
  17. let handle: string | undefined
  18. const toastTimer = setTimeout(() => {
  19. handle = showPreparingExportToast()
  20. }, SLOW_CONVERSION_THRESHOLD)
  21. const hidePreparingToast = () => {
  22. clearTimeout(toastTimer)
  23. if (handle) hidePreparingExportToast(handle)
  24. }
  25. try {
  26. const response = await getJSON(
  27. `/project/${projectId}/download/conversion/${type}?responseFormat=json`
  28. )
  29. hidePreparingToast()
  30. const { downloadUrl } = response
  31. if (downloadUrl) {
  32. const url = new URL(downloadUrl, window.location.origin)
  33. location.assign(url.toString())
  34. showExportDocumentSuccess(type)
  35. } else {
  36. showExportDocumentError()
  37. }
  38. } catch (error) {
  39. hidePreparingToast()
  40. showExportDocumentError()
  41. debugConsole.error(error)
  42. }
  43. }, [projectId, type, location])
  44. return triggerConversion
  45. }