references-context.tsx 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. indexAllReferences: (shouldBroadcast: boolean) => void
  30. }
  31. type IndexReferencesResponse = References
  32. const ReferencesContext = createContext<ReferencesContextValue | undefined>(
  33. undefined
  34. )
  35. export function populateReferenceScope(store: ReactScopeValueStore) {
  36. store.set('$root._references', { keys: [] })
  37. }
  38. export const ReferencesProvider: FC = ({ children }) => {
  39. const { fileTreeData } = useFileTreeData()
  40. const { eventEmitter, projectId } = useIdeReactContext()
  41. const { socket } = useConnectionContext()
  42. const [references, setReferences] =
  43. useScopeValue<References>('$root._references')
  44. const [existingIndexHash, setExistingIndexHash] = useState<
  45. Record<string, { hash: string; timestamp: number }>
  46. >({})
  47. const storeReferencesKeys = useCallback(
  48. (newKeys: string[], replaceExistingKeys: boolean) => {
  49. const oldKeys = references.keys
  50. const keys = replaceExistingKeys ? newKeys : _.union(oldKeys, newKeys)
  51. window.dispatchEvent(
  52. new CustomEvent('project:references', {
  53. detail: keys,
  54. })
  55. )
  56. setReferences({ keys })
  57. },
  58. [references.keys, setReferences]
  59. )
  60. const indexAllReferences = useCallback(
  61. (shouldBroadcast: boolean) => {
  62. postJSON(`/project/${projectId}/references/indexAll`, {
  63. body: {
  64. shouldBroadcast,
  65. },
  66. }).then((response: IndexReferencesResponse) => {
  67. storeReferencesKeys(response.keys, true)
  68. })
  69. },
  70. [projectId, storeReferencesKeys]
  71. )
  72. const indexReferencesIfDocModified = useCallback(
  73. (doc: ShareJsDoc, shouldBroadcast: boolean) => {
  74. // avoid reindexing references if the bib file has not changed since the
  75. // last time they were indexed
  76. const docId = doc.doc_id
  77. const snapshot = doc._doc.snapshot
  78. const now = Date.now()
  79. const sha1 = CryptoJSSHA1(
  80. 'blob ' + snapshot.length + '\x00' + snapshot
  81. ).toString()
  82. const CACHE_LIFETIME = 6 * 3600 * 1000 // allow reindexing every 6 hours
  83. const cacheEntry = existingIndexHash[docId]
  84. const isCached =
  85. cacheEntry &&
  86. cacheEntry.timestamp > now - CACHE_LIFETIME &&
  87. cacheEntry.hash === sha1
  88. if (!isCached) {
  89. indexAllReferences(shouldBroadcast)
  90. setExistingIndexHash(existingIndexHash => ({
  91. ...existingIndexHash,
  92. [docId]: { hash: sha1, timestamp: now },
  93. }))
  94. }
  95. },
  96. [existingIndexHash, indexAllReferences]
  97. )
  98. useEffect(() => {
  99. const handleDocClosed = (doc: ShareJsDoc) => {
  100. if (
  101. doc.doc_id &&
  102. findDocEntityById(fileTreeData, doc.doc_id)?.name?.endsWith('.bib')
  103. ) {
  104. indexReferencesIfDocModified(doc, true)
  105. }
  106. }
  107. eventEmitter.on('document:closed', handleDocClosed)
  108. return () => {
  109. eventEmitter.off('document:closed', handleDocClosed)
  110. }
  111. }, [eventEmitter, fileTreeData, indexReferencesIfDocModified])
  112. useEffect(() => {
  113. const handleShouldReindex = () => {
  114. indexAllReferences(true)
  115. }
  116. eventEmitter.on('references:should-reindex', handleShouldReindex)
  117. return () => {
  118. eventEmitter.off('references:should-reindex', handleShouldReindex)
  119. }
  120. }, [eventEmitter, indexAllReferences])
  121. useEffect(() => {
  122. const handleProjectJoined = () => {
  123. // We only need to grab the references when the editor first loads,
  124. // not on every reconnect
  125. socket.on('references:keys:updated', (keys, allDocs) =>
  126. storeReferencesKeys(keys, allDocs)
  127. )
  128. indexAllReferences(false)
  129. }
  130. eventEmitter.once('project:joined', handleProjectJoined)
  131. return () => {
  132. eventEmitter.off('project:joined', handleProjectJoined)
  133. }
  134. }, [eventEmitter, indexAllReferences, socket, storeReferencesKeys])
  135. const value = useMemo<ReferencesContextValue>(
  136. () => ({
  137. indexReferencesIfDocModified,
  138. indexAllReferences,
  139. }),
  140. [indexReferencesIfDocModified, indexAllReferences]
  141. )
  142. return (
  143. <ReferencesContext.Provider value={value}>
  144. {children}
  145. </ReferencesContext.Provider>
  146. )
  147. }
  148. export function useReferencesContext(): ReferencesContextValue {
  149. const context = useContext(ReferencesContext)
  150. if (!context) {
  151. throw new Error(
  152. 'useReferencesContext is only available inside ReferencesProvider'
  153. )
  154. }
  155. return context
  156. }