references-context.tsx 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. // @ts-ignore
  2. import CryptoJSSHA1 from 'crypto-js/sha1'
  3. import {
  4. createContext,
  5. useContext,
  6. useEffect,
  7. FC,
  8. useCallback,
  9. useMemo,
  10. useState,
  11. } from 'react'
  12. import { useIdeReactContext } from '@/features/ide-react/context/ide-react-context'
  13. import { useConnectionContext } from '@/features/ide-react/context/connection-context'
  14. import _ from 'lodash'
  15. import { postJSON } from '@/infrastructure/fetch-json'
  16. import { ShareJsDoc } from '@/features/ide-react/editor/share-js-doc'
  17. import useScopeValue from '@/shared/hooks/use-scope-value'
  18. import { ReactScopeValueStore } from '@/features/ide-react/scope-value-store/react-scope-value-store'
  19. import { useFileTreeData } from '@/shared/context/file-tree-data-context'
  20. import { findDocEntityById } from '@/features/ide-react/util/find-doc-entity-by-id'
  21. type References = {
  22. keys: string[]
  23. }
  24. type ReferencesContextValue = {
  25. indexReferencesIfDocModified: (
  26. doc: ShareJsDoc,
  27. shouldBroadcast: boolean
  28. ) => void
  29. indexReferences: (docIds: string[], shouldBroadcast: boolean) => void
  30. indexAllReferences: (shouldBroadcast: boolean) => void
  31. }
  32. type IndexReferencesResponse = References
  33. const ReferencesContext = createContext<ReferencesContextValue | undefined>(
  34. undefined
  35. )
  36. export function populateReferenceScope(store: ReactScopeValueStore) {
  37. store.set('$root._references', { keys: [] })
  38. }
  39. export const ReferencesProvider: FC = ({ children }) => {
  40. const { fileTreeData } = useFileTreeData()
  41. const { eventEmitter, projectId } = useIdeReactContext()
  42. const { socket } = useConnectionContext()
  43. const [references, setReferences] =
  44. useScopeValue<References>('$root._references')
  45. const [existingIndexHash, setExistingIndexHash] = useState<
  46. Record<string, { hash: string; timestamp: number }>
  47. >({})
  48. const storeReferencesKeys = useCallback(
  49. (newKeys: string[], replaceExistingKeys: boolean) => {
  50. const oldKeys = references.keys
  51. const keys = replaceExistingKeys ? newKeys : _.union(oldKeys, newKeys)
  52. window.dispatchEvent(
  53. new CustomEvent('project:references', {
  54. detail: keys,
  55. })
  56. )
  57. setReferences({ keys })
  58. },
  59. [references.keys, setReferences]
  60. )
  61. const indexReferences = useCallback(
  62. (docIds: string[], shouldBroadcast: boolean) => {
  63. postJSON(`/project/${projectId}/references/index`, {
  64. body: {
  65. docIds,
  66. shouldBroadcast,
  67. },
  68. }).then((response: IndexReferencesResponse) => {
  69. storeReferencesKeys(response.keys, false)
  70. })
  71. },
  72. [projectId, storeReferencesKeys]
  73. )
  74. const indexAllReferences = useCallback(
  75. (shouldBroadcast: boolean) => {
  76. postJSON(`/project/${projectId}/references/indexAll`, {
  77. body: {
  78. shouldBroadcast,
  79. },
  80. }).then((response: IndexReferencesResponse) => {
  81. storeReferencesKeys(response.keys, true)
  82. })
  83. },
  84. [projectId, storeReferencesKeys]
  85. )
  86. const indexReferencesIfDocModified = useCallback(
  87. (doc: ShareJsDoc, shouldBroadcast: boolean) => {
  88. // avoid reindexing references if the bib file has not changed since the
  89. // last time they were indexed
  90. const docId = doc.doc_id
  91. const snapshot = doc._doc.snapshot
  92. const now = Date.now()
  93. const sha1 = CryptoJSSHA1(
  94. 'blob ' + snapshot.length + '\x00' + snapshot
  95. ).toString()
  96. const CACHE_LIFETIME = 6 * 3600 * 1000 // allow reindexing every 6 hours
  97. const cacheEntry = existingIndexHash[docId]
  98. const isCached =
  99. cacheEntry &&
  100. cacheEntry.timestamp > now - CACHE_LIFETIME &&
  101. cacheEntry.hash === sha1
  102. if (!isCached) {
  103. indexReferences([docId], shouldBroadcast)
  104. setExistingIndexHash(existingIndexHash => ({
  105. ...existingIndexHash,
  106. [docId]: { hash: sha1, timestamp: now },
  107. }))
  108. }
  109. },
  110. [existingIndexHash, indexReferences]
  111. )
  112. useEffect(() => {
  113. const handleDocClosed = (doc: ShareJsDoc) => {
  114. if (
  115. doc.doc_id &&
  116. findDocEntityById(fileTreeData, doc.doc_id)?.name?.endsWith('.bib')
  117. ) {
  118. indexReferencesIfDocModified(doc, true)
  119. }
  120. }
  121. eventEmitter.on('document:closed', handleDocClosed)
  122. return () => {
  123. eventEmitter.off('document:closed', handleDocClosed)
  124. }
  125. }, [eventEmitter, fileTreeData, indexReferencesIfDocModified])
  126. useEffect(() => {
  127. const handleShouldReindex = () => {
  128. indexAllReferences(true)
  129. }
  130. eventEmitter.on('references:should-reindex', handleShouldReindex)
  131. return () => {
  132. eventEmitter.off('references:should-reindex', handleShouldReindex)
  133. }
  134. }, [eventEmitter, indexAllReferences])
  135. useEffect(() => {
  136. const handleProjectJoined = () => {
  137. // We only need to grab the references when the editor first loads,
  138. // not on every reconnect
  139. socket.on('references:keys:updated', (keys, allDocs) =>
  140. storeReferencesKeys(keys, allDocs)
  141. )
  142. indexAllReferences(false)
  143. }
  144. eventEmitter.once('project:joined', handleProjectJoined)
  145. return () => {
  146. eventEmitter.off('project:joined', handleProjectJoined)
  147. }
  148. }, [eventEmitter, indexAllReferences, socket, storeReferencesKeys])
  149. const value = useMemo<ReferencesContextValue>(
  150. () => ({
  151. indexReferencesIfDocModified,
  152. indexReferences,
  153. indexAllReferences,
  154. }),
  155. [indexReferencesIfDocModified, indexReferences, indexAllReferences]
  156. )
  157. return (
  158. <ReferencesContext.Provider value={value}>
  159. {children}
  160. </ReferencesContext.Provider>
  161. )
  162. }
  163. export function useReferencesContext(): ReferencesContextValue {
  164. const context = useContext(ReferencesContext)
  165. if (!context) {
  166. throw new Error(
  167. 'useReferencesContext is only available inside ReferencesProvider'
  168. )
  169. }
  170. return context
  171. }