-
Notifications
You must be signed in to change notification settings - Fork 3k
/
index.js
executable file
·396 lines (335 loc) · 14.5 KB
/
index.js
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
import React from 'react';
import {StyleSheet} from 'react-native';
import PropTypes from 'prop-types';
import _ from 'underscore';
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import Str from 'expensify-common/lib/str';
import RNTextInput from '../RNTextInput';
import withLocalize, {withLocalizePropTypes} from '../withLocalize';
import Growl from '../../libs/Growl';
import themeColors from '../../styles/themes/default';
import updateIsFullComposerAvailable from '../../libs/ComposerUtils/updateIsFullComposerAvailable';
import getNumberOfLines from '../../libs/ComposerUtils/index';
import * as Browser from '../../libs/Browser';
import Clipboard from '../../libs/Clipboard';
import withWindowDimensions, {windowDimensionsPropTypes} from '../withWindowDimensions';
import compose from '../../libs/compose';
import styles from '../../styles/styles';
const propTypes = {
/** Maximum number of lines in the text input */
maxLines: PropTypes.number,
/** The default value of the comment box */
defaultValue: PropTypes.string,
/** The value of the comment box */
value: PropTypes.string,
/** Number of lines for the comment */
numberOfLines: PropTypes.number,
/** Callback method to update number of lines for the comment */
onNumberOfLinesChange: PropTypes.func,
/** Callback method to handle pasting a file */
onPasteFile: PropTypes.func,
/** A ref to forward to the text input */
forwardedRef: PropTypes.func,
/** General styles to apply to the text input */
// eslint-disable-next-line react/forbid-prop-types
style: PropTypes.any,
/** If the input should clear, it actually gets intercepted instead of .clear() */
shouldClear: PropTypes.bool,
/** When the input has cleared whoever owns this input should know about it */
onClear: PropTypes.func,
/** Whether or not this TextInput is disabled. */
isDisabled: PropTypes.bool,
/** Set focus to this component the first time it renders.
Override this in case you need to set focus on one field out of many, or when you want to disable autoFocus */
autoFocus: PropTypes.bool,
/** Update selection position on change */
onSelectionChange: PropTypes.func,
/** Selection Object */
selection: PropTypes.shape({
start: PropTypes.number,
end: PropTypes.number,
}),
/** Whether the full composer can be opened */
isFullComposerAvailable: PropTypes.bool,
/** Allow the full composer to be opened */
setIsFullComposerAvailable: PropTypes.func,
/** Whether the composer is full size */
isComposerFullSize: PropTypes.bool,
...withLocalizePropTypes,
...windowDimensionsPropTypes,
};
const defaultProps = {
defaultValue: undefined,
value: undefined,
numberOfLines: 1,
onNumberOfLinesChange: () => {},
maxLines: -1,
onPasteFile: () => {},
shouldClear: false,
onClear: () => {},
style: null,
isDisabled: false,
autoFocus: false,
forwardedRef: null,
onSelectionChange: () => {},
selection: {
start: 0,
end: 0,
},
isFullComposerAvailable: false,
setIsFullComposerAvailable: () => {},
isComposerFullSize: false,
};
const IMAGE_EXTENSIONS = {
'image/bmp': 'bmp',
'image/gif': 'gif',
'image/jpeg': 'jpg',
'image/png': 'png',
'image/svg+xml': 'svg',
'image/tiff': 'tiff',
'image/webp': 'webp',
};
/**
* Enable Markdown parsing.
* On web we like to have the Text Input field always focused so the user can easily type a new chat
*/
class Composer extends React.Component {
constructor(props) {
super(props);
const initialValue = props.defaultValue
? `${props.defaultValue}`
: `${props.value || ''}`;
this.state = {
numberOfLines: props.numberOfLines,
selection: {
start: initialValue.length,
end: initialValue.length,
},
};
this.paste = this.paste.bind(this);
this.handlePaste = this.handlePaste.bind(this);
this.handlePastedHTML = this.handlePastedHTML.bind(this);
this.handleWheel = this.handleWheel.bind(this);
this.putSelectionInClipboard = this.putSelectionInClipboard.bind(this);
this.shouldCallUpdateNumberOfLines = this.shouldCallUpdateNumberOfLines.bind(this);
}
componentDidMount() {
this.updateNumberOfLines();
// This callback prop is used by the parent component using the constructor to
// get a ref to the inner textInput element e.g. if we do
// <constructor ref={el => this.textInput = el} /> this will not
// return a ref to the component, but rather the HTML element by default
if (this.props.forwardedRef && _.isFunction(this.props.forwardedRef)) {
this.props.forwardedRef(this.textInput);
}
// There is no onPaste or onDrag for TextInput in react-native so we will add event
// listeners here and unbind when the component unmounts
if (this.textInput) {
this.textInput.addEventListener('paste', this.handlePaste);
this.textInput.addEventListener('wheel', this.handleWheel);
this.textInput.addEventListener('keydown', this.putSelectionInClipboard);
}
}
componentDidUpdate(prevProps) {
if (!prevProps.shouldClear && this.props.shouldClear) {
this.textInput.clear();
// eslint-disable-next-line react/no-did-update-set-state
this.setState({numberOfLines: 1});
this.props.onClear();
}
if (prevProps.value !== this.props.value
|| prevProps.defaultValue !== this.props.defaultValue
|| prevProps.isComposerFullSize !== this.props.isComposerFullSize
|| prevProps.windowWidth !== this.props.windowWidth
|| prevProps.numberOfLines !== this.props.numberOfLines) {
this.updateNumberOfLines();
}
if (prevProps.selection !== this.props.selection) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({selection: this.props.selection});
}
}
componentWillUnmount() {
if (!this.textInput) {
return;
}
this.textInput.removeEventListener('paste', this.handlePaste);
this.textInput.removeEventListener('wheel', this.handleWheel);
}
/**
* Set pasted text to clipboard
* @param {String} text
*/
paste(text) {
try {
document.execCommand('insertText', false, text);
this.updateNumberOfLines();
// Pointer will go out of sight when a large paragraph is pasted on the web. Refocusing the input keeps the cursor in view.
this.textInput.blur();
this.textInput.focus();
// eslint-disable-next-line no-empty
} catch (e) {}
}
/**
* Manually place the pasted HTML into Composer
*
* @param {String} html - pasted HTML
*/
handlePastedHTML(html) {
const parser = new ExpensiMark();
this.paste(parser.htmlToMarkdown(html));
}
/**
* Check the paste event for an attachment, parse the data and call onPasteFile from props with the selected file,
* Otherwise, convert pasted HTML to Markdown and set it on the composer.
*
* @param {ClipboardEvent} event
*/
handlePaste(event) {
event.preventDefault();
const {files, types} = event.clipboardData;
const TEXT_HTML = 'text/html';
// If paste contains files, then trigger file management
if (files.length > 0) {
// Prevent the default so we do not post the file name into the text box
this.props.onPasteFile(event.clipboardData.files[0]);
return;
}
// If paste contains HTML
if (types.includes(TEXT_HTML)) {
const pastedHTML = event.clipboardData.getData(TEXT_HTML);
const domparser = new DOMParser();
const embeddedImages = domparser.parseFromString(pastedHTML, TEXT_HTML).images;
// If HTML has img tag, then fetch images from it.
if (embeddedImages.length > 0 && embeddedImages[0].src) {
// If HTML has emoji, then treat this as plain text.
if (embeddedImages[0].dataset && embeddedImages[0].dataset.stringifyType === 'emoji') {
const plainText = event.clipboardData.getData('text/plain');
this.paste(Str.htmlDecode(plainText));
return;
}
fetch(embeddedImages[0].src)
.then((response) => {
if (!response.ok) { throw Error(response.statusText); }
return response.blob();
})
.then((x) => {
const extension = IMAGE_EXTENSIONS[x.type];
if (!extension) {
throw new Error(this.props.translate('composer.noExtensionFoundForMimeType'));
}
return new File([x], `pasted_image.${extension}`, {});
})
.then(this.props.onPasteFile)
.catch(() => {
const errorDesc = this.props.translate('composer.problemGettingImageYouPasted');
Growl.error(errorDesc);
/*
* Since we intercepted the user-triggered paste event to check for attachments,
* we need to manually set the value and call the `onChangeText` handler.
* Synthetically-triggered paste events do not affect the document's contents.
* See https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event for more details.
*/
this.handlePastedHTML(pastedHTML);
});
return;
}
this.handlePastedHTML(pastedHTML);
return;
}
const plainText = event.clipboardData.getData('text/plain');
this.paste(Str.htmlDecode(plainText));
}
/**
* Manually scrolls the text input, then prevents the event from being passed up to the parent.
* @param {Object} event native Event
*/
handleWheel(event) {
if (event.target !== document.activeElement) {
return;
}
this.textInput.scrollTop += event.deltaY;
event.preventDefault();
event.stopPropagation();
}
putSelectionInClipboard(event) {
// If anything happens that isn't cmd+c or cmd+x, ignore the event because it's not a copy command
if (!event.metaKey || (event.key !== 'c' && event.key !== 'x')) {
return;
}
// The user might have only highlighted a portion of the message to copy, so using the selection will ensure that
// the only stuff put into the clipboard is what the user selected.
const selectedText = event.target.value.substring(this.state.selection.start, this.state.selection.end);
Clipboard.setHtml(selectedText, selectedText);
}
/**
* We want to call updateNumberOfLines only when the parent doesn't provide value in props
* as updateNumberOfLines is already being called when value changes in componentDidUpdate
*/
shouldCallUpdateNumberOfLines() {
if (!_.isEmpty(this.props.value)) {
return;
}
this.updateNumberOfLines();
}
/**
* Check the current scrollHeight of the textarea (minus any padding) and
* divide by line height to get the total number of rows for the textarea.
*/
updateNumberOfLines() {
// Hide the composer expand button so we can get an accurate reading of
// the height of the text input
this.props.setIsFullComposerAvailable(false);
// We have to reset the rows back to the minimum before updating so that the scrollHeight is not
// affected by the previous row setting. If we don't, rows will be added but not removed on backspace/delete.
this.setState({numberOfLines: 1}, () => {
const computedStyle = window.getComputedStyle(this.textInput);
const lineHeight = parseInt(computedStyle.lineHeight, 10) || 20;
const paddingTopAndBottom = parseInt(computedStyle.paddingBottom, 10)
+ parseInt(computedStyle.paddingTop, 10);
const computedNumberOfLines = getNumberOfLines(this.props.maxLines, lineHeight, paddingTopAndBottom, this.textInput.scrollHeight);
const numberOfLines = computedNumberOfLines === 0 ? this.props.numberOfLines : computedNumberOfLines;
updateIsFullComposerAvailable(this.props, numberOfLines);
this.setState({
numberOfLines,
});
this.props.onNumberOfLinesChange(numberOfLines);
});
}
render() {
const propStyles = StyleSheet.flatten(this.props.style);
propStyles.outline = 'none';
const propsWithoutStyles = _.omit(this.props, 'style');
// We're disabling autoCorrect for iOS Safari until Safari fixes this issue. See https://github.com/Expensify/App/issues/8592
return (
<RNTextInput
autoComplete="off"
autoCorrect={!Browser.isMobileSafari()}
placeholderTextColor={themeColors.placeholderText}
ref={el => this.textInput = el}
selection={this.state.selection}
onChange={this.shouldCallUpdateNumberOfLines}
onSelectionChange={this.onSelectionChange}
style={[
propStyles,
// We are hiding the scrollbar to prevent it from reducing the text input width,
// so we can get the correct scroll height while calculating the number of lines.
this.state.numberOfLines < this.props.maxLines ? styles.overflowHidden : {},
]}
/* eslint-disable-next-line react/jsx-props-no-spreading */
{...propsWithoutStyles}
numberOfLines={this.state.numberOfLines}
disabled={this.props.isDisabled}
/>
);
}
}
Composer.propTypes = propTypes;
Composer.defaultProps = defaultProps;
export default compose(
withLocalize,
withWindowDimensions,
)(React.forwardRef((props, ref) => (
/* eslint-disable-next-line react/jsx-props-no-spreading */
<Composer {...props} forwardedRef={ref} />
)));