context.tsx 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use client'
  2. import {
  3. createContext,
  4. memo,
  5. useRef,
  6. } from 'react'
  7. import { LexicalComposer } from '@lexical/react/LexicalComposer'
  8. import { LinkNode } from '@lexical/link'
  9. import {
  10. ListItemNode,
  11. ListNode,
  12. } from '@lexical/list'
  13. import { createNoteEditorStore } from './store'
  14. import theme from './theme'
  15. type NoteEditorStore = ReturnType<typeof createNoteEditorStore>
  16. const NoteEditorContext = createContext<NoteEditorStore | null>(null)
  17. type NoteEditorContextProviderProps = {
  18. value: string
  19. children: JSX.Element | string | (JSX.Element | string)[]
  20. }
  21. export const NoteEditorContextProvider = memo(({
  22. value,
  23. children,
  24. }: NoteEditorContextProviderProps) => {
  25. const storeRef = useRef<NoteEditorStore>()
  26. if (!storeRef.current)
  27. storeRef.current = createNoteEditorStore()
  28. let initialValue = null
  29. try {
  30. initialValue = JSON.parse(value)
  31. }
  32. catch (e) {
  33. }
  34. const initialConfig = {
  35. namespace: 'note-editor',
  36. nodes: [
  37. LinkNode,
  38. ListNode,
  39. ListItemNode,
  40. ],
  41. editorState: !initialValue?.root.children.length ? null : JSON.stringify(initialValue),
  42. onError: (error: Error) => {
  43. throw error
  44. },
  45. theme,
  46. }
  47. return (
  48. <NoteEditorContext.Provider value={storeRef.current}>
  49. <LexicalComposer initialConfig={{ ...initialConfig }}>
  50. {children}
  51. </LexicalComposer>
  52. </NoteEditorContext.Provider>
  53. )
  54. })
  55. NoteEditorContextProvider.displayName = 'NoteEditorContextProvider'
  56. export default NoteEditorContext