references-context.tsx 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. import { IdeEvents } from '@/features/ide-react/create-ide-event-emitter'
  22. type References = {
  23. keys: string[]
  24. }
  25. type ReferencesContextValue = {
  26. indexReferencesIfDocModified: (
  27. doc: ShareJsDoc,
  28. shouldBroadcast: boolean
  29. ) => 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 indexAllReferences = useCallback(
  62. (shouldBroadcast: boolean) => {
  63. postJSON(`/project/${projectId}/references/indexAll`, {
  64. body: {
  65. shouldBroadcast,
  66. },
  67. }).then((response: IndexReferencesResponse) => {
  68. storeReferencesKeys(response.keys, true)
  69. })
  70. },
  71. [projectId, storeReferencesKeys]
  72. )
  73. const indexReferencesIfDocModified = useCallback(
  74. (doc: ShareJsDoc, shouldBroadcast: boolean) => {
  75. // avoid reindexing references if the bib file has not changed since the
  76. // last time they were indexed
  77. const docId = doc.doc_id
  78. const snapshot = doc._doc.snapshot
  79. const now = Date.now()
  80. const sha1 = CryptoJSSHA1(
  81. 'blob ' + snapshot.length + '\x00' + snapshot
  82. ).toString()
  83. const CACHE_LIFETIME = 6 * 3600 * 1000 // allow reindexing every 6 hours
  84. const cacheEntry = existingIndexHash[docId]
  85. const isCached =
  86. cacheEntry &&
  87. cacheEntry.timestamp > now - CACHE_LIFETIME &&
  88. cacheEntry.hash === sha1
  89. if (!isCached) {
  90. indexAllReferences(shouldBroadcast)
  91. setExistingIndexHash(existingIndexHash => ({
  92. ...existingIndexHash,
  93. [docId]: { hash: sha1, timestamp: now },
  94. }))
  95. }
  96. },
  97. [existingIndexHash, indexAllReferences]
  98. )
  99. useEffect(() => {
  100. const handleDocClosed = ({
  101. detail: [doc],
  102. }: CustomEvent<IdeEvents['document:closed']>) => {
  103. if (
  104. doc.doc_id &&
  105. findDocEntityById(fileTreeData, doc.doc_id)?.name?.endsWith('.bib')
  106. ) {
  107. indexReferencesIfDocModified(doc, true)
  108. }
  109. }
  110. eventEmitter.on('document:closed', handleDocClosed)
  111. return () => {
  112. eventEmitter.off('document:closed', handleDocClosed)
  113. }
  114. }, [eventEmitter, fileTreeData, indexReferencesIfDocModified])
  115. useEffect(() => {
  116. const handleShouldReindex = () => {
  117. indexAllReferences(true)
  118. }
  119. eventEmitter.on('references:should-reindex', handleShouldReindex)
  120. return () => {
  121. eventEmitter.off('references:should-reindex', handleShouldReindex)
  122. }
  123. }, [eventEmitter, indexAllReferences])
  124. useEffect(() => {
  125. const handleProjectJoined = () => {
  126. // We only need to grab the references when the editor first loads,
  127. // not on every reconnect
  128. socket.on('references:keys:updated', (keys, allDocs) =>
  129. storeReferencesKeys(keys, allDocs)
  130. )
  131. indexAllReferences(false)
  132. }
  133. eventEmitter.once('project:joined', handleProjectJoined)
  134. return () => {
  135. eventEmitter.off('project:joined', handleProjectJoined)
  136. }
  137. }, [eventEmitter, indexAllReferences, socket, storeReferencesKeys])
  138. const value = useMemo<ReferencesContextValue>(
  139. () => ({
  140. indexReferencesIfDocModified,
  141. indexAllReferences,
  142. }),
  143. [indexReferencesIfDocModified, indexAllReferences]
  144. )
  145. return (
  146. <ReferencesContext.Provider value={value}>
  147. {children}
  148. </ReferencesContext.Provider>
  149. )
  150. }
  151. export function useReferencesContext(): ReferencesContextValue {
  152. const context = useContext(ReferencesContext)
  153. if (!context) {
  154. throw new Error(
  155. 'useReferencesContext is only available inside ReferencesProvider'
  156. )
  157. }
  158. return context
  159. }