use-project-ranges.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { useCallback, useEffect, useState } from 'react'
  2. import { Ranges } from '../context/ranges-context'
  3. import { useProjectContext } from '@/shared/context/project-context'
  4. import { getJSON } from '@/infrastructure/fetch-json'
  5. import useSocketListener from '@/features/ide-react/hooks/use-socket-listener'
  6. import { useConnectionContext } from '@/features/ide-react/context/connection-context'
  7. import getMeta from '@/utils/meta'
  8. import { buildProjectRangesFromSnapshot } from '@/features/review-panel/utils/snapshot-ranges'
  9. export default function useProjectRanges() {
  10. const { projectId } = useProjectContext()
  11. const [error, setError] = useState<Error>()
  12. const [projectRanges, setProjectRanges] = useState<Map<string, Ranges>>()
  13. const [loading, setLoading] = useState(true)
  14. const { socket } = useConnectionContext()
  15. const otMigrationStage = getMeta('ol-otMigrationStage')
  16. const { projectSnapshot } = useProjectContext()
  17. useEffect(() => {
  18. if (otMigrationStage === 1) {
  19. projectSnapshot.refresh().then(() => {
  20. setProjectRanges(buildProjectRangesFromSnapshot(projectSnapshot))
  21. setLoading(false)
  22. })
  23. } else {
  24. setLoading(true)
  25. getJSON<{ id: string; ranges: Ranges }[]>(`/project/${projectId}/ranges`)
  26. .then(data => {
  27. setProjectRanges(
  28. new Map(
  29. data.map(item => [
  30. item.id,
  31. {
  32. docId: item.id,
  33. changes: item.ranges.changes ?? [],
  34. comments: item.ranges.comments ?? [],
  35. },
  36. ])
  37. )
  38. )
  39. })
  40. .catch(error => setError(error))
  41. .finally(() => setLoading(false))
  42. }
  43. }, [projectId, otMigrationStage, projectSnapshot])
  44. useSocketListener(
  45. socket,
  46. 'accept-changes',
  47. useCallback((docId: string, entryIds: string[]) => {
  48. setProjectRanges(prevProjectRanges => {
  49. if (!prevProjectRanges) {
  50. return prevProjectRanges
  51. }
  52. const ranges = prevProjectRanges.get(docId)
  53. if (!ranges) {
  54. return prevProjectRanges
  55. }
  56. const updatedProjectRanges = new Map(prevProjectRanges)
  57. updatedProjectRanges.set(docId, {
  58. ...ranges,
  59. changes: ranges.changes.filter(
  60. change => !entryIds.includes(change.id)
  61. ),
  62. })
  63. return updatedProjectRanges
  64. })
  65. }, [])
  66. )
  67. useSocketListener(
  68. socket,
  69. 'new-comment',
  70. useCallback(() => {
  71. if (otMigrationStage === 1) {
  72. projectSnapshot.refresh().then(() => {
  73. setProjectRanges(buildProjectRangesFromSnapshot(projectSnapshot))
  74. setLoading(false)
  75. })
  76. }
  77. }, [otMigrationStage, projectSnapshot])
  78. )
  79. return { projectRanges, error, loading }
  80. }