aboutsummaryrefslogtreecommitdiff
path: root/vnext/src/ui/MessageInput.js
blob: 3d24e728e31cc34aaf48f9df17534345e0888317 (plain) (blame)
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
import React, { useState, useEffect, useRef } from 'react';

import Icon from './Icon';
import Button from './Button';

import UploadButton from './UploadButton';
import toast from 'react-hot-toast';


/**
 * StackOverflow-driven development: https://stackoverflow.com/a/10158364/1097384
 * @param {HTMLTextAreaElement & {createTextRange?: Function}} el element
 */
function moveCaretToEnd(el) {
    if (typeof el.selectionStart == 'number') {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != 'undefined') {
        // Internet Explorer
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}


/** @external Promise */

/**
 * @typedef {object} MessageInputProps
 * @property {string} text text
 * @property {function({body:string, attach:string | File}):Promise<boolean>} onSend onSend
 * @property {number=} rows rows
 * @property {string=} placeholder placeholder
 */

/**
 * MessageInput
 * @param {React.ComponentProps<React.FC> & MessageInputProps} props props
 */
export default function MessageInput({ text, rows, placeholder, onSend }) {
    /**
     * @type {React.MutableRefObject<HTMLTextAreaElement?>}
     */
    let textareaRef = useRef(null);
    /**
     * @type {React.MutableRefObject<HTMLInputElement?>}
     */
    let fileinput = useRef(null);

    let updateFocus = () => {
        const isDesktop = window.matchMedia('(min-width: 62.5rem)');
        if (isDesktop.matches) {
            const textarea = textareaRef.current;
            if (textarea) {
                textarea.focus();
                moveCaretToEnd(textarea);
            }
        }
    };
    useEffect(() => {
        textChanged({
            target: {
                value: text
            }
        });
        updateFocus();
    }, [text]);

    let [body, setBody] = useState(text);

    let handleCtrlEnter = (event) => {
        if (event.ctrlKey && (event.charCode == 10 || event.charCode == 13)) {
            onSubmit({});
        }
    };
    const textChanged = (event) => {
        setBody(event.target.value);
        const el = textareaRef.current;
        if (el) {
            const offset = el.offsetHeight - el.clientHeight;
            const height = el.scrollHeight + offset;
            el.style.height = `${height + offset}px`;
        }
    };
    const [attach, setAttach] = useState('');
    let uploadValueChanged = (attach) => {
        setAttach(attach);
    };
    let onSubmit = (event) => {
        if (event.preventDefault) {
            event.preventDefault();
        }
        const input = fileinput.current;
        if (input && input.files) {
            onSend({
                body: body,
                attach: attach ? input.files[0] : ''
            }).then((success) => {
                if (success) {
                    setAttach('');
                    setBody('');
                    if (textareaRef.current) {
                        textareaRef.current.style.height = '';
                    }
                    updateFocus();
                } else {
                    toast('Can not update this message');
                }
            }).catch(console.log);
        }
    };
    return (
        <form className="msg-comment-target" style={{ padding: '12px', width: '100%' }} onSubmit={onSubmit}>
            <div style={commentStyle}>
                <textarea onChange={textChanged} onKeyPress={handleCtrlEnter}
                    ref={textareaRef} style={textInputStyle}
                    rows={rows || 1} placeholder={placeholder} value={body || ''} />
                <div style={inputBarStyle}>
                    <UploadButton inputRef={fileinput} value={attach} onChange={uploadValueChanged} />
                    <Button onClick={onSubmit}><Icon name="ei-envelope" size="s" />Send</Button>
                </div>
            </div>
        </form>
    );
}

/**
 * @type {React.CSSProperties}
 */
const commentStyle = {
    display: 'flex',
    flexDirection: 'column',
    width: '100%',
    marginTop: '10px'
};

/**
 * @type {React.CSSProperties}
 */
const inputBarStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '3px'
};

/**
 * @type {React.CSSProperties}
 */
const textInputStyle = {
    overflow: 'hidden',
    resize: 'none',
    display: 'block',
    boxSizing: 'border-box',
    border: 0,
    outline: 'none',
    padding: '4px'
};