diff-view.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { useEffect, useState } from 'react'
  2. import Toolbar from './toolbar/toolbar'
  3. import Main from './main'
  4. import { Diff, DocDiffResponse } from '../../services/types/doc'
  5. import { Nullable } from '../../../../../../types/utils'
  6. import { useHistoryContext } from '../../context/history-context'
  7. import { diffDoc } from '../../services/api'
  8. import { highlightsFromDiffResponse } from '../../utils/highlights-from-diff-response'
  9. import useAsync from '../../../../shared/hooks/use-async'
  10. import ErrorMessage from '../error-message'
  11. function DiffView() {
  12. const [diff, setDiff] = useState<Nullable<Diff>>(null)
  13. const { selection, projectId, loadingState } = useHistoryContext()
  14. const loadingFileDiffs = loadingState === 'loadingFileDiffs'
  15. const { isLoading, runAsync, error } = useAsync<DocDiffResponse>()
  16. const { updateRange, selectedFile } = selection
  17. useEffect(() => {
  18. if (!updateRange || !selectedFile?.pathname || loadingFileDiffs) {
  19. return
  20. }
  21. const { fromV, toV } = updateRange
  22. runAsync(diffDoc(projectId, fromV, toV, selectedFile.pathname))
  23. .then(data => {
  24. let diff: Diff | undefined
  25. if (!data?.diff) {
  26. setDiff(null)
  27. }
  28. if ('binary' in data.diff) {
  29. diff = { binary: true }
  30. } else {
  31. diff = {
  32. binary: false,
  33. docDiff: highlightsFromDiffResponse(data.diff),
  34. }
  35. }
  36. setDiff(diff)
  37. })
  38. .catch(console.error)
  39. }, [projectId, runAsync, updateRange, selectedFile, loadingFileDiffs])
  40. return (
  41. <div className="doc-panel">
  42. {error ? (
  43. <ErrorMessage />
  44. ) : (
  45. <>
  46. <div className="history-header toolbar-container">
  47. <Toolbar diff={diff} selection={selection} />
  48. </div>
  49. <div className="doc-container">
  50. <Main diff={diff} isLoading={isLoading || loadingFileDiffs} />
  51. </div>
  52. </>
  53. )}
  54. </div>
  55. )
  56. }
  57. export default DiffView