-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathInput.tsx
409 lines (349 loc) · 12.8 KB
/
Input.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
397
398
399
400
401
402
403
404
405
406
407
408
409
import { cn } from '@/lib/utils';
import React, {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
useState
} from 'react';
import { useRecoilValue } from 'recoil';
import { ICommand, commandsState } from '@chainlit/react-client';
import Icon from '@/components/Icon';
import {
Command,
CommandGroup,
CommandItem,
CommandList
} from '@/components/ui/command';
interface Props {
id?: string;
className?: string;
autoFocus?: boolean;
placeholder?: string;
selectedCommand?: ICommand;
setSelectedCommand: (command: ICommand | undefined) => void;
onChange: (value: string) => void;
onPaste?: (event: any) => void;
onEnter?: (event: React.KeyboardEvent<HTMLDivElement>) => void;
}
export interface InputMethods {
reset: () => void;
}
const escapeHtml = (unsafe: string) => {
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
const Input = forwardRef<InputMethods, Props>(
(
{
placeholder,
id,
className,
autoFocus,
selectedCommand,
setSelectedCommand,
onChange,
onEnter,
onPaste
},
ref
) => {
const commands = useRecoilValue(commandsState);
const [isComposing, setIsComposing] = useState(false);
const [showCommands, setShowCommands] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(0);
const [commandInput, setCommandInput] = useState('');
const contentEditableRef = useRef<HTMLDivElement>(null);
const lastCommandSpanRef = useRef<HTMLElement | null>(null);
const mutationObserverRef = useRef<MutationObserver | null>(null);
const isUpdatingRef = useRef(false);
const getContentWithoutCommand = () => {
if (!contentEditableRef.current) return '';
// Create a clone of the content
const clone = contentEditableRef.current.cloneNode(
true
) as HTMLDivElement;
// Remove command span from clone
const commandSpan = clone.querySelector('.command-span');
if (commandSpan) {
commandSpan.remove();
}
return (
clone.innerHTML
?.replace(/<br\s*\/?>/g, '\n') // Convert <br> to newlines
.replace(/<div>/g, '\n') // Convert <div> to newlines
.replace(/<\/div>/g, '') // Remove closing div tags
.replace(/ /g, ' ') // Convert to spaces
.replace(/<[^>]*>/g, '') // Remove any other HTML tags
.replace(/</g, '<') // Convert < back to
.replace(/>/g, '>') // Convert > back to >
.replace(/&/g, '&')
.replace('\u200B', '') || ''
);
};
const reset = () => {
setSelectedCommand(undefined);
setSelectedIndex(0);
setCommandInput('');
if (contentEditableRef.current) {
contentEditableRef.current.innerHTML = '';
}
onChange('');
};
useImperativeHandle(ref, () => ({
reset
}));
// Set up mutation observer to detect command span removal
useEffect(() => {
if (!contentEditableRef.current) return;
contentEditableRef.current.focus();
mutationObserverRef.current = new MutationObserver((mutations) => {
if (isUpdatingRef.current) return;
mutations.forEach((mutation) => {
if (
mutation.type === 'childList' &&
mutation.removedNodes.length > 0
) {
// Check if the removed node was our command span
const wasCommandSpanRemoved = Array.from(
mutation.removedNodes
).some((node) =>
(node as HTMLElement).classList?.contains('command-span')
);
if (wasCommandSpanRemoved && !mutation.addedNodes.length) {
handleCommandSelect(undefined);
}
}
});
});
mutationObserverRef.current.observe(contentEditableRef.current, {
childList: true,
subtree: true
});
return () => {
mutationObserverRef.current?.disconnect();
};
}, []);
// Handle selectedCommand prop changes
useEffect(() => {
const content = contentEditableRef.current;
if (!content) return;
isUpdatingRef.current = true;
try {
// Find existing command span
const existingCommandSpan = content.querySelector('.command-span');
if (selectedCommand && !selectedCommand.button) {
// Create new command block
const newCommandBlock = document.createElement('div');
newCommandBlock.className =
'command-span font-bold inline-flex text-[#08f] items-center mr-1';
newCommandBlock.contentEditable = 'false';
newCommandBlock.innerHTML = `<span>${selectedCommand.id}</span>`;
// Store reference to the command span
lastCommandSpanRef.current = newCommandBlock;
if (existingCommandSpan) {
existingCommandSpan.replaceWith(newCommandBlock);
} else {
// Add new command span at the start
if (content.firstChild) {
content.insertBefore(newCommandBlock, content.firstChild);
} else {
content.appendChild(newCommandBlock);
}
}
let textNode;
// Create a text node after the command span if none exists
if (!newCommandBlock.nextSibling) {
textNode = document.createTextNode('\u200B');
content.appendChild(textNode); // Zero-width space
}
// Ensure cursor is placed after the command span
const selection = window.getSelection();
const range = document.createRange();
// Set cursor after the command span
range.setStartAfter(textNode || newCommandBlock);
range.collapse(true);
// Apply the selection
selection?.removeAllRanges();
selection?.addRange(range);
// Force focus on the content editable
content.focus();
selection?.addRange(range);
// Trigger onChange with content excluding command
onChange(getContentWithoutCommand());
} else if (existingCommandSpan) {
// Remove existing command span
existingCommandSpan.remove();
lastCommandSpanRef.current = null;
onChange(getContentWithoutCommand());
}
} finally {
// Use setTimeout to ensure all DOM updates are complete
setTimeout(() => {
isUpdatingRef.current = false;
}, 0);
}
}, [selectedCommand, onChange]);
const normalizedInput = commandInput.toLowerCase().slice(1);
const filteredCommands = commands
.filter((command) => command.id.toLowerCase().includes(normalizedInput))
.sort((a, b) => {
const indexA = a.id.toLowerCase().indexOf(normalizedInput);
const indexB = b.id.toLowerCase().indexOf(normalizedInput);
return indexA - indexB;
});
useEffect(() => {
const textarea = contentEditableRef.current;
if (!textarea || !onPaste) return;
const _onPaste = (event: ClipboardEvent) => {
event.preventDefault();
const textData = event.clipboardData?.getData('text/plain');
if (textData) {
const escapedText = escapeHtml(textData);
const textWithNewLines = escapedText.replace(/\n/g, '<br>');
const selection = window.getSelection();
if (selection?.rangeCount) {
const range = selection.getRangeAt(0);
range.deleteContents();
// Insert the HTML content
const tempDiv = document.createElement('div');
tempDiv.innerHTML = textWithNewLines;
const fragment = document.createDocumentFragment();
while (tempDiv.firstChild) {
fragment.appendChild(tempDiv.firstChild);
}
range.insertNode(fragment);
// Move cursor to end of pasted content
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
// Force focus back to the content editable
textarea.focus();
textarea.scrollTop = textarea.scrollHeight;
}
// Trigger input event to update state
const inputEvent = new Event('input', { bubbles: true });
textarea.dispatchEvent(inputEvent);
}
onPaste(event);
};
textarea.addEventListener('paste', _onPaste);
return () => {
textarea.removeEventListener('paste', _onPaste);
};
}, [onPaste]);
const handleInput = (e: React.FormEvent<HTMLDivElement>) => {
if (isUpdatingRef.current) return;
const textContent = getContentWithoutCommand();
onChange(textContent);
// For command detection, use the full content including command input
const fullContent = e.currentTarget.textContent || '';
const words = fullContent.split(' ');
if (words.length === 1 && words[0].startsWith('/')) {
setShowCommands(true);
setCommandInput(words[0]);
} else {
setShowCommands(false);
setCommandInput('');
}
// If there's no real content, remove the <br>
if (!fullContent.trim() || fullContent.trim() === '\u200B') {
e.currentTarget.innerHTML = '';
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (!showCommands) {
if (e.key === 'Enter' && !e.shiftKey && onEnter && !isComposing) {
e.preventDefault();
onEnter(e);
}
return;
}
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedIndex((prev) =>
prev < filteredCommands.length - 1 ? prev + 1 : prev
);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
} else if (e.key === 'Enter' && filteredCommands.length > 0) {
e.preventDefault();
const selectedCommand = filteredCommands[selectedIndex];
handleCommandSelect(selectedCommand);
} else if (e.key === 'Escape') {
setShowCommands(false);
}
};
const handleCommandSelect = (command?: ICommand) => {
setShowCommands(false);
// Set a small timeout to ensure state updates are processed
setTimeout(() => {
setSelectedCommand(command);
// Clean up the command input from contentEditable
if (contentEditableRef.current && command && commandInput) {
const content = contentEditableRef.current.textContent || '';
const cleanedContent = content.replace(commandInput, '').trimStart();
contentEditableRef.current.textContent = cleanedContent;
}
setSelectedIndex(0);
setCommandInput('');
}, 0);
};
return (
<div className="relative w-full">
<div
id={id}
autoFocus={autoFocus}
ref={contentEditableRef}
contentEditable
data-placeholder={placeholder}
className={cn(
'min-h-10 max-h-[250px] overflow-y-auto w-full focus:outline-none focus:ring-0 focus:ring-offset-0 focus-visible:ring-0 focus-visible:ring-offset-0 empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground',
className
)}
onInput={handleInput}
onKeyDown={handleKeyDown}
onCompositionStart={() => setIsComposing(true)}
onCompositionEnd={() => setIsComposing(false)}
/>
{showCommands && filteredCommands.length ? (
<div className="absolute z-50 -top-4 left-0 -translate-y-full">
<Command className="rounded-lg border shadow-md">
<CommandList>
<CommandGroup>
{filteredCommands.map((command, index) => (
<CommandItem
key={command.id}
onSelect={() => handleCommandSelect(command)}
className={cn(
'cursor-pointer command-item flex items-center space-x-2 p-2',
index === selectedIndex ? 'bg-accent' : ''
)}
>
<Icon
name={command.icon}
className="!size-5 text-muted-foreground"
/>
<div>
<div className="font-medium">{command.id}</div>
<div className="text-sm text-muted-foreground">
{command.description}
</div>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</div>
) : null}
</div>
);
}
);
export default Input;