use-convert-project.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. showPreparingExportToast,
  10. } from '../components/toolbar/export-document-toasts'
  11. const SLOW_CONVERSION_THRESHOLD = 2000
  12. export default function useConvertProject(type: 'docx' | 'markdown') {
  13. const { projectId } = useProjectContext()
  14. const location = useLocation()
  15. const triggerConversion = useCallback(async () => {
  16. let handle: string | undefined
  17. const toastTimer = setTimeout(() => {
  18. handle = showPreparingExportToast()
  19. }, SLOW_CONVERSION_THRESHOLD)
  20. const hidePreparingToast = () => {
  21. clearTimeout(toastTimer)
  22. if (handle) hidePreparingExportToast(handle)
  23. }
  24. try {
  25. const response = await getJSON(
  26. `/project/${projectId}/download/conversion/${type}?responseFormat=json`
  27. )
  28. hidePreparingToast()
  29. const { downloadUrl } = response
  30. if (downloadUrl) {
  31. const url = new URL(downloadUrl, window.location.origin)
  32. location.assign(url.toString())
  33. }
  34. } catch (error) {
  35. hidePreparingToast()
  36. showExportDocumentError()
  37. debugConsole.error(error)
  38. }
  39. }, [projectId, type, location])
  40. return triggerConversion
  41. }