-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
cursorPositionInsert.ts
31 lines (26 loc) · 1.2 KB
/
cursorPositionInsert.ts
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
// This function is used to insert text at the cursor position in the text area
export const insertTextAtCursor = async (textArea: HTMLTextAreaElement, text: string) => {
let length = 0;
const typewriter = setInterval(() => {
textArea.setRangeText(text[length++], textArea.selectionStart, textArea.selectionEnd, "end");
if (length >= text.length) {
clearInterval(typewriter);
textArea.setRangeText("\n\n_Description generated using [OpenSauced](https://opensauced.ai/)._", textArea.selectionStart, textArea.selectionEnd, "end");
}
}, 10);
};
export const insertAtCursorFromStream = async (textArea: HTMLTextAreaElement, stream: ReadableStream<Uint8Array>) => {
const reader = stream.getReader();
const decoder = new TextDecoder("utf-8");
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
} else {
const chunk = decoder.decode(value);
const [start, end] = [textArea.selectionStart, textArea.selectionEnd];
textArea.setRangeText(chunk, start, end, "end");
}
}
textArea.setRangeText("\n\n_Description generated using [OpenSauced](https://opensauced.ai/)._", textArea.selectionStart, textArea.selectionEnd, "end");
};