-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathRichTextEditor.tsx
396 lines (342 loc) · 11.6 KB
/
RichTextEditor.tsx
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useCallback, useEffect, useMemo, useRef, ClipboardEvent } from 'react'
import { MessageStatus } from '@janhq/core'
import { useAtom, useAtomValue } from 'jotai'
import { BaseEditor, createEditor, Editor, Range, Transforms } from 'slate'
import { withHistory } from 'slate-history' // Import withHistory
import {
Editable,
ReactEditor,
Slate,
withReact,
RenderLeafProps,
} from 'slate-react'
import { twMerge } from 'tailwind-merge'
import { currentPromptAtom } from '@/containers/Providers/Jotai'
import { useActiveModel } from '@/hooks/useActiveModel'
import useSendChatMessage from '@/hooks/useSendChatMessage'
import { getCurrentChatMessagesAtom } from '@/helpers/atoms/ChatMessage.atom'
import { selectedModelAtom } from '@/helpers/atoms/Model.atom'
import {
getActiveThreadIdAtom,
activeSettingInputBoxAtom,
} from '@/helpers/atoms/Thread.atom'
type CustomElement = {
type: 'paragraph' | 'code' | null
children: CustomText[]
language?: string // Store the language for code blocks
}
type CustomText = {
text: string
code?: boolean
language?: string
className?: string
type?: 'paragraph' | 'code' // Add the type property
format?: 'bold' | 'italic'
}
declare module 'slate' {
interface CustomTypes {
Editor: BaseEditor & ReactEditor
Element: CustomElement
Text: CustomText
}
}
const initialValue: CustomElement[] = [
{
type: 'paragraph',
children: [{ text: '' }],
},
]
type RichTextEditorProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
const RichTextEditor = ({
className,
style,
disabled,
placeholder,
spellCheck,
}: RichTextEditorProps) => {
const editor = useMemo(() => withHistory(withReact(createEditor())), [])
const currentLanguage = useRef<string>('plaintext')
const hasStartBackticks = useRef<boolean>(false)
const hasEndBackticks = useRef<boolean>(false)
const [currentPrompt, setCurrentPrompt] = useAtom(currentPromptAtom)
const textareaRef = useRef<HTMLDivElement>(null)
const activeThreadId = useAtomValue(getActiveThreadIdAtom)
const activeSettingInputBox = useAtomValue(activeSettingInputBoxAtom)
const messages = useAtomValue(getCurrentChatMessagesAtom)
const { sendChatMessage } = useSendChatMessage()
const { stopInference } = useActiveModel()
const selectedModel = useAtomValue(selectedModelAtom)
const largeContentThreshold = 1000
// The decorate function identifies code blocks and marks the ranges
const decorate = useCallback(
(entry: [any, any]) => {
const ranges: any[] = []
const [node, path] = entry
if (Editor.isBlock(editor, node) && node.type === 'paragraph') {
node.children.forEach((child: { text: any }, childIndex: number) => {
const text = child.text
// Match bold text pattern *text*
const boldMatches = [...text.matchAll(/(\*.*?\*)/g)] // Find bold patterns
boldMatches.forEach((match) => {
const startOffset = match.index + 1 || 0
const length = match[0].length - 2
ranges.push({
anchor: { path: [...path, childIndex], offset: startOffset },
focus: {
path: [...path, childIndex],
offset: startOffset + length,
},
format: 'italic',
className: 'italic',
})
})
})
}
if (Editor.isBlock(editor, node) && node.type === 'paragraph') {
node.children.forEach((child: { text: any }, childIndex: number) => {
const text = child.text
// Match bold text pattern **text**
const boldMatches = [...text.matchAll(/(\*\*.*?\*\*)/g)] // Find bold patterns
boldMatches.forEach((match) => {
const startOffset = match.index + 2 || 0
const length = match[0].length - 4
ranges.push({
anchor: { path: [...path, childIndex], offset: startOffset },
focus: {
path: [...path, childIndex],
offset: startOffset + length,
},
format: 'bold',
className: 'font-bold',
})
})
})
}
return ranges
},
[editor]
)
// RenderLeaf applies the decoration styles
const renderLeaf = useCallback(
({ attributes, children, leaf }: RenderLeafProps) => {
if (leaf.format === 'italic') {
return (
<i className={leaf.className} {...attributes}>
{children}
</i>
)
}
if (leaf.format === 'bold') {
return (
<strong className={leaf.className} {...attributes}>
{children}
</strong>
)
}
if (leaf.code) {
// Apply syntax highlighting to code blocks
return (
<code className={leaf.className} {...attributes}>
{children}
</code>
)
}
return <span {...attributes}>{children}</span>
},
[]
)
useEffect(() => {
if (!ReactEditor.isFocused(editor)) {
ReactEditor.focus(editor)
}
if (textareaRef.current) {
textareaRef.current.focus()
}
}, [activeThreadId, editor])
useEffect(() => {
if (textareaRef.current?.clientHeight) {
textareaRef.current.style.height = activeSettingInputBox
? '100px'
: '40px'
textareaRef.current.style.height =
textareaRef.current.scrollHeight + 2 + 'px'
textareaRef.current.style.overflow =
textareaRef.current.clientHeight >= 390 ? 'auto' : 'hidden'
}
if (currentPrompt.length === 0) {
resetEditor()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [textareaRef.current?.clientHeight, currentPrompt, activeSettingInputBox])
const onStopInferenceClick = async () => {
stopInference()
}
const resetEditor = useCallback(() => {
Transforms.delete(editor, {
at: {
anchor: Editor.start(editor, []),
focus: Editor.end(editor, []),
},
})
// Adjust the height of the textarea to its initial state
if (textareaRef.current) {
textareaRef.current.style.height = activeSettingInputBox
? '100px'
: '44px'
textareaRef.current.style.overflow = 'hidden' // Reset overflow style
}
// Ensure the editor re-renders decorations
editor.onChange()
}, [activeSettingInputBox, editor])
const handleKeyDown = useCallback(
(event: React.KeyboardEvent) => {
if (
event.key === 'Enter' &&
!event.shiftKey &&
event.nativeEvent.isComposing === false
) {
event.preventDefault()
if (messages[messages.length - 1]?.status !== MessageStatus.Pending) {
sendChatMessage(currentPrompt)
if (selectedModel) {
resetEditor()
}
} else onStopInferenceClick()
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[currentPrompt, editor, messages]
)
const handlePaste = (event: ClipboardEvent<HTMLDivElement>) => {
const clipboardData = event.clipboardData || (window as any).clipboardData
const pastedData = clipboardData.getData('text')
if (pastedData.length > largeContentThreshold) {
event.preventDefault() // Prevent the default paste behavior
Transforms.insertText(editor, pastedData) // Insert the content directly into the editor
}
}
return (
<Slate
editor={editor}
initialValue={initialValue}
onChange={(value) => {
const combinedText = value
.map((block) => {
if ('children' in block) {
return block.children.map((child) => child.text).join('')
}
return ''
})
.join('\n')
setCurrentPrompt(combinedText)
if (combinedText.trim() === '') {
currentLanguage.current = 'plaintext'
}
const hasCodeBlockStart = combinedText.match(/^```(\w*)/m)
const hasCodeBlockEnd = combinedText.match(/^```$/m)
// Set language to plaintext if no code block with language identifier is found
if (!hasCodeBlockStart) {
currentLanguage.current = 'plaintext'
hasStartBackticks.current = false
} else {
hasStartBackticks.current = true
}
if (!hasCodeBlockEnd) {
currentLanguage.current = 'plaintext'
hasEndBackticks.current = false
} else {
hasEndBackticks.current = true
}
}}
>
<Editable
ref={textareaRef}
decorate={(entry) => {
// Skip decorate if content exceeds threshold
if (
currentPrompt.length > largeContentThreshold ||
!currentPrompt.length
)
return []
return decorate(entry)
}}
renderLeaf={renderLeaf} // Pass the renderLeaf function
scrollSelectionIntoView={scrollSelectionIntoView}
onKeyDown={handleKeyDown}
onPaste={handlePaste} // Add the custom paste handler
className={twMerge(
className,
disabled &&
'cursor-not-allowed border-none bg-[hsla(var(--disabled-bg))] text-[hsla(var(--disabled-fg))]'
)}
placeholder={placeholder}
style={style}
disabled={disabled}
readOnly={disabled}
spellCheck={spellCheck}
/>
</Slate>
)
function scrollSelectionIntoView(
editor: ReactEditor,
domRange: globalThis.Range
) {
// This was affecting the selection of multiple blocks and dragging behavior,
// so enabled only if the selection has been collapsed.
if (editor.selection && Range.isExpanded(editor.selection)) return
const minTop = 80 // sticky header height
const leafEl = domRange.startContainer.parentElement
const scrollParent = getScrollParent(leafEl)
// Check if browser supports getBoundingClientRect
if (typeof domRange.getBoundingClientRect !== 'function') return
const { top: elementTop, height: elementHeight } =
domRange.getBoundingClientRect()
const { height: parentHeight } = scrollParent.getBoundingClientRect()
const isChildAboveViewport = elementTop < minTop
const isChildBelowViewport = elementTop + elementHeight > parentHeight
if (isChildAboveViewport && isChildBelowViewport) {
// Child spans through all visible area which means it's already in view.
return
}
if (isChildAboveViewport) {
const y = scrollParent.scrollTop + elementTop - minTop
scrollParent.scroll({ left: scrollParent.scrollLeft, top: y })
return
}
if (isChildBelowViewport) {
const y = Math.min(
scrollParent.scrollTop + elementTop - minTop,
scrollParent.scrollTop + elementTop + elementHeight - parentHeight
)
scrollParent.scroll({ left: scrollParent.scrollLeft, top: y })
}
}
function getScrollParent(element: any) {
const elementStyle = window.getComputedStyle(element)
const excludeStaticParent = elementStyle.position === 'absolute'
if (elementStyle.position === 'fixed') {
return document.body
}
let parent = element
while (parent) {
const parentStyle = window.getComputedStyle(parent)
if (parentStyle.position !== 'static' || !excludeStaticParent) {
const overflowAttributes = [
parentStyle.overflow,
parentStyle.overflowY,
parentStyle.overflowX,
]
if (
overflowAttributes.includes('auto') ||
overflowAttributes.includes('hidden')
) {
return parent
}
}
parent = parent.parentElement
}
return document.documentElement
}
}
export default RichTextEditor