ide-context.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { createContext, FC, useContext, useEffect, useMemo } from 'react'
  2. import { ScopeValueStore } from '../../../../types/ide/scope-value-store'
  3. import { ScopeEventEmitter } from '../../../../types/ide/scope-event-emitter'
  4. export type Ide = {
  5. [key: string]: any // TODO: define the rest of the `ide` and `$scope` properties
  6. $scope: Record<string, any>
  7. }
  8. type IdeContextValue = Ide & {
  9. scopeStore: ScopeValueStore
  10. scopeEventEmitter: ScopeEventEmitter
  11. }
  12. export const IdeContext = createContext<IdeContextValue | undefined>(undefined)
  13. export const IdeProvider: FC<{
  14. ide: Ide
  15. scopeStore: ScopeValueStore
  16. scopeEventEmitter: ScopeEventEmitter
  17. }> = ({ ide, scopeStore, scopeEventEmitter, children }) => {
  18. /**
  19. * Expose scopeStore via `window.overleaf.unstable.store`, so it can be accessed by external extensions.
  20. *
  21. * These properties are expected to be available:
  22. * - `editor.view`
  23. * - `project.spellcheckLanguage`
  24. * - `editor.open_doc_name`,
  25. * - `editor.open_doc_id`,
  26. * - `settings.theme`
  27. * - `settings.keybindings`
  28. */
  29. useEffect(() => {
  30. window.overleaf = {
  31. ...window.overleaf,
  32. unstable: {
  33. ...window.overleaf?.unstable,
  34. store: scopeStore,
  35. },
  36. }
  37. }, [scopeStore])
  38. const value = useMemo<IdeContextValue>(() => {
  39. return {
  40. ...ide,
  41. scopeStore,
  42. scopeEventEmitter,
  43. }
  44. }, [ide, scopeStore, scopeEventEmitter])
  45. return <IdeContext.Provider value={value}>{children}</IdeContext.Provider>
  46. }
  47. export function useIdeContext(): IdeContextValue {
  48. const context = useContext(IdeContext)
  49. if (!context) {
  50. throw new Error('useIdeContext is only available inside IdeProvider')
  51. }
  52. return context
  53. }