-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathuseMessageInputText.ts
More file actions
58 lines (51 loc) · 1.75 KB
/
useMessageInputText.ts
File metadata and controls
58 lines (51 loc) · 1.75 KB
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
import { useCallback, useEffect, useRef } from 'react';
import { type TextComposerState } from 'stream-chat';
import type { MessageInputProps } from '../MessageInput';
import { useMessageComposer } from './useMessageComposer';
import { useStateStore } from '../../../store';
const messageComposerStateSelector = (state: TextComposerState) => ({
text: state.text,
});
export const useMessageInputText = (props: MessageInputProps) => {
const { focus } = props;
const messageComposer = useMessageComposer();
const textareaRef = useRef<HTMLTextAreaElement>(undefined);
const { text } = useStateStore(
messageComposer.textComposer.state,
messageComposerStateSelector,
);
// Focus
useEffect(() => {
if (focus && textareaRef.current) {
textareaRef.current.focus();
}
}, [focus]);
// Text + cursor position
const newCursorPosition = useRef<number>(undefined);
const insertText = useCallback(
(textToInsert: string) => {
const selection = textareaRef?.current && {
end: textareaRef.current.selectionEnd,
start: textareaRef.current.selectionStart,
};
messageComposer.textComposer.insertText({
selection,
text: textToInsert,
});
if (selection) newCursorPosition.current = selection.start + textToInsert.length;
},
[messageComposer, newCursorPosition, textareaRef],
);
useEffect(() => {
const textareaElement = textareaRef.current;
if (textareaElement && newCursorPosition.current !== undefined) {
textareaElement.selectionStart = newCursorPosition.current;
textareaElement.selectionEnd = newCursorPosition.current;
newCursorPosition.current = undefined;
}
}, [text, newCursorPosition]);
return {
insertText,
textareaRef,
};
};