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