references-context.tsx 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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('reference:added', function () {
  95. indexAllReferences(true)
  96. })
  97. useEffect(() => {
  98. const handleProjectJoined = () => {
  99. // We only need to grab the references when the editor first loads,
  100. // not on every reconnect
  101. socket.on('references:keys:updated', (keys, allDocs) => {
  102. setReferenceKeys(oldKeys =>
  103. allDocs ? new Set(keys) : new Set([...oldKeys, ...keys])
  104. )
  105. })
  106. indexAllReferences(false)
  107. }
  108. eventEmitter.once('project:joined', handleProjectJoined)
  109. return () => {
  110. eventEmitter.off('project:joined', handleProjectJoined)
  111. }
  112. }, [eventEmitter, indexAllReferences, socket])
  113. const value = useMemo(
  114. () => ({
  115. referenceKeys,
  116. indexAllReferences,
  117. }),
  118. [indexAllReferences, referenceKeys]
  119. )
  120. return (
  121. <ReferencesContext.Provider value={value}>
  122. {children}
  123. </ReferencesContext.Provider>
  124. )
  125. }
  126. export function useReferencesContext() {
  127. const context = useContext(ReferencesContext)
  128. if (!context) {
  129. throw new Error(
  130. 'useReferencesContext is only available inside ReferencesProvider'
  131. )
  132. }
  133. return context
  134. }