use-convert-project.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. import { RootDocInfo } from '@/shared/hooks/use-root-doc'
  13. import { OpenDocuments } from '../editor/open-documents'
  14. const SLOW_CONVERSION_THRESHOLD = 2000
  15. export default function useConvertProject(
  16. type: 'docx' | 'markdown',
  17. openDocs: OpenDocuments,
  18. getRootDocInfo: () => RootDocInfo
  19. ) {
  20. const { projectId } = useProjectContext()
  21. const location = useLocation()
  22. return useCallback(async () => {
  23. let handle: string | undefined
  24. const toastTimer = setTimeout(() => {
  25. handle = showPreparingExportToast()
  26. }, SLOW_CONVERSION_THRESHOLD)
  27. const hidePreparingToast = () => {
  28. clearTimeout(toastTimer)
  29. if (handle) hidePreparingExportToast(handle)
  30. }
  31. const url = new URL(window.location.origin)
  32. url.pathname = `/project/${projectId}/download/conversion/${type}`
  33. url.searchParams.set('responseFormat', 'json')
  34. const { rootResourcePath } = getRootDocInfo()
  35. url.searchParams.set('rootResourcePath', rootResourcePath)
  36. try {
  37. await openDocs.awaitBufferedOps(AbortSignal.timeout(10_000))
  38. const response = await getJSON(url.href)
  39. hidePreparingToast()
  40. const { downloadUrl } = response
  41. if (downloadUrl) {
  42. const url = new URL(downloadUrl, window.location.origin)
  43. location.assign(url.toString())
  44. showExportDocumentSuccess(type)
  45. } else {
  46. showExportDocumentError()
  47. }
  48. } catch (error) {
  49. hidePreparingToast()
  50. showExportDocumentError()
  51. debugConsole.error(error)
  52. }
  53. }, [projectId, type, getRootDocInfo, openDocs, location])
  54. }