references-context.tsx 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import { generateSHA1Hash } from '../../../shared/utils/sha1'
  2. import {
  3. createContext,
  4. useContext,
  5. useEffect,
  6. FC,
  7. useCallback,
  8. useMemo,
  9. useState,
  10. } from 'react'
  11. import { useIdeReactContext } from '@/features/ide-react/context/ide-react-context'
  12. import { useConnectionContext } from '@/features/ide-react/context/connection-context'
  13. import { postJSON } from '@/infrastructure/fetch-json'
  14. import { ShareJsDoc } from '@/features/ide-react/editor/share-js-doc'
  15. import { useFileTreeData } from '@/shared/context/file-tree-data-context'
  16. import { findDocEntityById } from '@/features/ide-react/util/find-doc-entity-by-id'
  17. import { IdeEvents } from '@/features/ide-react/create-ide-event-emitter'
  18. import { debugConsole } from '@/utils/debugging'
  19. import useEventListener from '@/shared/hooks/use-event-listener'
  20. export const ReferencesContext = createContext<
  21. | {
  22. referenceKeys: Set<string>
  23. indexAllReferences: (shouldBroadcast: boolean) => void
  24. }
  25. | undefined
  26. >(undefined)
  27. export const ReferencesProvider: FC = ({ children }) => {
  28. const { fileTreeData } = useFileTreeData()
  29. const { eventEmitter, projectId } = useIdeReactContext()
  30. const { socket } = useConnectionContext()
  31. const [referenceKeys, setReferenceKeys] = useState(new Set<string>())
  32. const [existingIndexHash, setExistingIndexHash] = useState<
  33. Record<string, { hash: string; timestamp: number }>
  34. >({})
  35. const indexAllReferences = useCallback(
  36. (shouldBroadcast: boolean) => {
  37. postJSON(`/project/${projectId}/references/indexAll`, {
  38. body: {
  39. shouldBroadcast,
  40. },
  41. })
  42. .then((response: { keys: string[] }) => {
  43. setReferenceKeys(new Set(response.keys))
  44. })
  45. .catch(error => {
  46. // allow the request to fail
  47. debugConsole.error(error)
  48. })
  49. },
  50. [projectId]
  51. )
  52. const indexReferencesIfDocModified = useCallback(
  53. (doc: ShareJsDoc, shouldBroadcast: boolean) => {
  54. // avoid reindexing references if the bib file has not changed since the
  55. // last time they were indexed
  56. const docId = doc.doc_id
  57. const snapshot = doc._doc.snapshot
  58. const now = Date.now()
  59. const sha1 = generateSHA1Hash(
  60. 'blob ' + snapshot.length + '\x00' + snapshot
  61. )
  62. const CACHE_LIFETIME = 6 * 3600 * 1000 // allow reindexing every 6 hours
  63. const cacheEntry = existingIndexHash[docId]
  64. const isCached =
  65. cacheEntry &&
  66. cacheEntry.timestamp > now - CACHE_LIFETIME &&
  67. cacheEntry.hash === sha1
  68. if (!isCached) {
  69. indexAllReferences(shouldBroadcast)
  70. setExistingIndexHash(existingIndexHash => ({
  71. ...existingIndexHash,
  72. [docId]: { hash: sha1, timestamp: now },
  73. }))
  74. }
  75. },
  76. [existingIndexHash, indexAllReferences]
  77. )
  78. useEffect(() => {
  79. const handleDocClosed = ({
  80. detail: [doc],
  81. }: CustomEvent<IdeEvents['document:closed']>) => {
  82. if (
  83. doc.doc_id &&
  84. findDocEntityById(fileTreeData, doc.doc_id)?.name?.endsWith('.bib')
  85. ) {
  86. indexReferencesIfDocModified(doc, true)
  87. }
  88. }
  89. eventEmitter.on('document:closed', handleDocClosed)
  90. return () => {
  91. eventEmitter.off('document:closed', handleDocClosed)
  92. }
  93. }, [eventEmitter, fileTreeData, indexReferencesIfDocModified])
  94. useEventListener(
  95. 'reference:added',
  96. useCallback(() => {
  97. indexAllReferences(true)
  98. }, [indexAllReferences])
  99. )
  100. useEffect(() => {
  101. const handleProjectJoined = () => {
  102. // We only need to grab the references when the editor first loads,
  103. // not on every reconnect
  104. socket.on('references:keys:updated', (keys, allDocs) => {
  105. setReferenceKeys(oldKeys =>
  106. allDocs ? new Set(keys) : new Set([...oldKeys, ...keys])
  107. )
  108. })
  109. indexAllReferences(false)
  110. }
  111. eventEmitter.once('project:joined', handleProjectJoined)
  112. return () => {
  113. eventEmitter.off('project:joined', handleProjectJoined)
  114. }
  115. }, [eventEmitter, indexAllReferences, socket])
  116. const value = useMemo(
  117. () => ({
  118. referenceKeys,
  119. indexAllReferences,
  120. }),
  121. [indexAllReferences, referenceKeys]
  122. )
  123. return (
  124. <ReferencesContext.Provider value={value}>
  125. {children}
  126. </ReferencesContext.Provider>
  127. )
  128. }
  129. export function useReferencesContext() {
  130. const context = useContext(ReferencesContext)
  131. if (!context) {
  132. throw new Error(
  133. 'useReferencesContext is only available inside ReferencesProvider'
  134. )
  135. }
  136. return context
  137. }