main.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { useHistoryContext } from '../../context/history-context'
  2. import { diffDoc } from '../../services/api'
  3. import { useEffect } from 'react'
  4. import { DocDiffResponse, Highlight } from '../../services/types/doc'
  5. import { highlightsFromDiffResponse } from '../../utils/highlights-from-diff-response'
  6. import DocumentDiffViewer from './document-diff-viewer'
  7. import useAsync from '../../../../shared/hooks/use-async'
  8. import { useTranslation } from 'react-i18next'
  9. type Diff = {
  10. binary: boolean
  11. docDiff?: {
  12. doc: string
  13. highlights: Highlight[]
  14. }
  15. }
  16. function Main() {
  17. const { t } = useTranslation()
  18. const { projectId, updateSelection, fileSelection } = useHistoryContext()
  19. const { isLoading, runAsync, data } = useAsync<DocDiffResponse>()
  20. let diff: Diff | undefined
  21. if (data?.diff) {
  22. if ('binary' in data.diff) {
  23. diff = { binary: true }
  24. } else {
  25. diff = { binary: false, docDiff: highlightsFromDiffResponse(data.diff) }
  26. }
  27. }
  28. useEffect(() => {
  29. if (!updateSelection || !fileSelection || !fileSelection.pathname) {
  30. return
  31. }
  32. const { fromV, toV } = updateSelection.update
  33. // TODO: Error handling
  34. runAsync(diffDoc(projectId, fromV, toV, fileSelection.pathname))
  35. }, [fileSelection, projectId, runAsync, updateSelection])
  36. if (isLoading) {
  37. return (
  38. <div className="history-loading-panel">
  39. <i className="fa fa-spin fa-refresh" />
  40. &nbsp;&nbsp;
  41. {t('loading')}…
  42. </div>
  43. )
  44. }
  45. if (!diff) {
  46. return <div>No document</div>
  47. }
  48. if (diff.binary) {
  49. return <div>Binary file</div>
  50. }
  51. if (diff.docDiff) {
  52. const { doc, highlights } = diff.docDiff
  53. return <DocumentDiffViewer doc={doc} highlights={highlights} />
  54. }
  55. return <div>No document</div>
  56. }
  57. export default Main