references-context.tsx 4.2 KB

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