forked from zulip/zulip-mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ComposeBox.js
525 lines (467 loc) · 15.4 KB
/
ComposeBox.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/* @flow strict-local */
import React, { PureComponent } from 'react';
import { Platform, View, TextInput, findNodeHandle } from 'react-native';
import type { LayoutEvent } from 'react-native/Libraries/Types/CoreEventTypes';
import TextInputReset from 'react-native-text-input-reset';
import type { ThemeData } from '../styles';
import { ThemeContext } from '../styles';
import type {
Auth,
Narrow,
EditMessage,
InputSelection,
UserOrBot,
Dispatch,
Dimensions,
CaughtUp,
GetText,
Subscription,
Stream,
} from '../types';
import { connect } from '../react-redux';
import { withGetText } from '../boot/TranslationProvider';
import {
addToOutbox,
draftUpdate,
fetchTopicsForStream,
sendTypingStart,
sendTypingStop,
} from '../actions';
import * as api from '../api';
import { FloatingActionButton, Input } from '../common';
import { showErrorAlert } from '../utils/info';
import { IconDone, IconSend } from '../common/Icons';
import { isStreamNarrow, isStreamOrTopicNarrow, topicNarrow } from '../utils/narrow';
import ComposeMenu from './ComposeMenu';
import getComposeInputPlaceholder from './getComposeInputPlaceholder';
import NotSubscribed from '../message/NotSubscribed';
import AnnouncementOnly from '../message/AnnouncementOnly';
import MentionWarnings from './MentionWarnings';
import {
getAuth,
getIsAdmin,
getSession,
getLastMessageTopic,
getActiveUsersByEmail,
getCaughtUpForNarrow,
getStreamInNarrow,
getJitsiServerUrl,
} from '../selectors';
import {
getIsActiveStreamSubscribed,
getIsActiveStreamAnnouncementOnly,
} from '../subscriptions/subscriptionSelectors';
import { getDraftForNarrow } from '../drafts/draftsSelectors';
import TopicAutocomplete from '../autocomplete/TopicAutocomplete';
import AutocompleteView from '../autocomplete/AutocompleteView';
import { getOwnEmail } from '../users/userSelectors';
type SelectorProps = {|
auth: Auth,
ownEmail: string,
usersByEmail: Map<string, UserOrBot>,
safeAreaInsets: Dimensions,
isAdmin: boolean,
isAnnouncementOnly: boolean,
isSubscribed: boolean,
draft: string,
lastMessageTopic: string,
caughtUp: CaughtUp,
jitsiServerUrl: string | null,
stream: Subscription | {| ...Stream, in_home_view: boolean |},
|};
type Props = $ReadOnly<{|
narrow: Narrow,
editMessage: EditMessage | null,
completeEditMessage: () => void,
dispatch: Dispatch,
...SelectorProps,
// From 'withGetText'
_: GetText,
|}>;
type State = {|
isMessageFocused: boolean,
isTopicFocused: boolean,
/** Almost the same as isMessageFocused || isTopicFocused ... except
* debounced, to stay true while those flip from false/true to true/false
* and back. */
isFocused: boolean,
isMenuExpanded: boolean,
topic: string,
message: string,
height: number,
selection: InputSelection,
|};
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
export const updateTextInput = (textInput: typeof TextInput | null, text: string): void => {
if (textInput === null) {
// Depending on the lifecycle events this function is called from,
// this might not be set yet.
return;
}
// See point 2 at
// https://github.com/facebook/react-native/issues/28459#issuecomment-609957836
// $FlowFixMe
textInput.setNativeProps({ text });
if (text.length === 0 && TextInputReset) {
// React Native has problems with some custom keyboards when clearing
// the input's contents. Force reset to make sure it works.
TextInputReset.resetKeyboardInput(findNodeHandle(textInput));
}
};
class ComposeBox extends PureComponent<Props, State> {
static contextType = ThemeContext;
context: ThemeData;
messageInputRef = React.createRef<typeof TextInput>();
topicInputRef = React.createRef<typeof TextInput>();
// TODO: Type-check this, once we've adjusted our `react-redux`
// wrapper to do the right thing. It should be
//
// mentionWarnings = React.createRef<typeof MentionWarnings>()
//
// but we need our `react-redux` wrapper to be aware of
// `getWrappedInstance`, since we need to access that.
mentionWarnings = React.createRef();
inputBlurTimeoutId: ?TimeoutID = null;
state = {
isMessageFocused: false,
isTopicFocused: false,
isFocused: false,
isMenuExpanded: false,
height: 20,
topic: this.props.lastMessageTopic,
message: this.props.draft,
selection: { start: 0, end: 0 },
};
componentWillUnmount() {
clearTimeout(this.inputBlurTimeoutId);
this.inputBlurTimeoutId = null;
}
updateIsFocused = () => {
this.setState(state => ({
...state,
isFocused: state.isMessageFocused || state.isTopicFocused,
}));
};
getCanSelectTopic = () => {
const { editMessage, narrow } = this.props;
if (editMessage) {
return isStreamOrTopicNarrow(narrow);
}
if (!isStreamNarrow(narrow)) {
return false;
}
return this.state.isFocused;
};
setMessageInputValue = (message: string) => {
updateTextInput(this.messageInputRef.current, message);
this.handleMessageChange(message);
};
setTopicInputValue = (topic: string) => {
updateTextInput(this.topicInputRef.current, topic);
this.handleTopicChange(topic);
};
insertMessageTextAtCursorPosition = (text: string) => {
const { message, selection } = this.state;
this.setMessageInputValue(
message.slice(0, selection.start) + text + message.slice(selection.end, message.length),
);
};
insertVideoCallLink = (jitsiServerUrl: string) => {
const { _ } = this.props;
// This is meant to align with the way the webapp generates jitsi video
// call IDs. That logic can be found in the ".video_link" click handler
// in static/js/compose.js.
const videoCallId = randomInt(100000000000000, 999999999999999);
const videoCallUrl = `${jitsiServerUrl}/${videoCallId}`;
const linkMessage = _('Click to join video call');
const linkText = `[${linkMessage}](${videoCallUrl})`;
this.insertMessageTextAtCursorPosition(linkText);
};
handleComposeMenuToggle = () => {
this.setState(({ isMenuExpanded }) => ({
isMenuExpanded: !isMenuExpanded,
}));
};
handleLayoutChange = (event: LayoutEvent) => {
this.setState({
height: event.nativeEvent.layout.height,
});
};
handleTopicChange = (topic: string) => {
this.setState({ topic, isMenuExpanded: false });
};
handleTopicAutocomplete = (topic: string) => {
this.setTopicInputValue(topic);
};
handleMessageChange = (message: string) => {
this.setState({ message, isMenuExpanded: false });
const { dispatch, narrow } = this.props;
dispatch(sendTypingStart(narrow));
dispatch(draftUpdate(narrow, message));
};
// See JSDoc on 'onAutocomplete' in 'AutocompleteView.js'.
handleMessageAutocomplete = (
completedText: string,
completion: string,
lastWordPrefix: string,
) => {
this.setMessageInputValue(completedText);
if (lastWordPrefix === '@') {
if (this.mentionWarnings.current) {
this.mentionWarnings.current.getWrappedInstance().handleMentionSubscribedCheck(completion);
}
}
};
handleMessageSelectionChange = (event: { +nativeEvent: { +selection: InputSelection } }) => {
const { selection } = event.nativeEvent;
this.setState({ selection });
};
handleMessageFocus = () => {
this.setState((state, { lastMessageTopic }) => ({
...state,
topic: state.topic || lastMessageTopic,
isMessageFocused: true,
isFocused: true,
isMenuExpanded: false,
}));
};
handleMessageBlur = () => {
this.setState({
isMessageFocused: false,
isMenuExpanded: false,
});
// give a chance to the topic input to get the focus
clearTimeout(this.inputBlurTimeoutId);
this.inputBlurTimeoutId = setTimeout(this.updateIsFocused, 200);
};
handleTopicFocus = () => {
const { dispatch, narrow } = this.props;
this.setState({
isTopicFocused: true,
isFocused: true,
isMenuExpanded: false,
});
dispatch(fetchTopicsForStream(narrow));
};
handleTopicBlur = () => {
this.setState({
isTopicFocused: false,
isMenuExpanded: false,
});
// give a chance to the message input to get the focus
clearTimeout(this.inputBlurTimeoutId);
this.inputBlurTimeoutId = setTimeout(this.updateIsFocused, 200);
};
handleInputTouchStart = () => {
this.setState({ isMenuExpanded: false });
};
getDestinationNarrow = (): Narrow => {
const { narrow } = this.props;
const topic = this.state.topic.trim();
return isStreamNarrow(narrow) ? topicNarrow(narrow[0].operand, topic || '(no topic)') : narrow;
};
handleSend = () => {
const { dispatch, narrow, caughtUp, _ } = this.props;
const { message } = this.state;
if (!caughtUp.newer) {
showErrorAlert(_('Failed to send message'));
return;
}
dispatch(addToOutbox(this.getDestinationNarrow(), message));
this.setMessageInputValue('');
if (this.mentionWarnings.current) {
this.mentionWarnings.current.getWrappedInstance().clearMentionWarnings();
}
dispatch(sendTypingStop(narrow));
};
handleEdit = () => {
const { auth, editMessage, completeEditMessage, _ } = this.props;
if (!editMessage) {
throw new Error('expected editMessage');
}
const { message, topic } = this.state;
const content = editMessage.content !== message ? message : undefined;
const subject = topic !== editMessage.topic ? topic : undefined;
if ((content !== undefined && content !== '') || (subject !== undefined && subject !== '')) {
api.updateMessage(auth, { content, subject }, editMessage.id).catch(error => {
showErrorAlert(_('Failed to edit message'), error.message);
});
}
completeEditMessage();
if (this.messageInputRef.current !== null) {
// See point 2 at
// https://github.com/facebook/react-native/issues/28459#issuecomment-609957836
// $FlowFixMe
this.messageInputRef.current.blur();
}
};
UNSAFE_componentWillReceiveProps(nextProps: Props) {
if (nextProps.editMessage !== this.props.editMessage) {
const topic =
isStreamNarrow(nextProps.narrow) && nextProps.editMessage
? nextProps.editMessage.topic
: '';
const message = nextProps.editMessage ? nextProps.editMessage.content : '';
this.setMessageInputValue(message);
this.setTopicInputValue(topic);
if (this.messageInputRef.current !== null) {
// See point 2 at
// https://github.com/facebook/react-native/issues/28459#issuecomment-609957836
// $FlowFixMe
this.messageInputRef.current.focus();
}
}
}
inputMarginPadding = {
paddingHorizontal: 8,
paddingVertical: Platform.select({
ios: 8,
android: 2,
}),
};
styles = {
wrapper: {
flexShrink: 1,
maxHeight: '60%',
},
autocompleteWrapper: {
position: 'absolute',
bottom: 0,
width: '100%',
},
composeBox: {
flexDirection: 'row',
alignItems: 'flex-end',
flexShrink: 1,
},
composeText: {
flex: 1,
paddingVertical: 8,
},
composeSendButton: {
padding: 8,
},
topicInput: {
borderWidth: 0,
borderRadius: 5,
marginBottom: 8,
...this.inputMarginPadding,
},
composeTextInput: {
borderWidth: 0,
borderRadius: 5,
fontSize: 15,
flexShrink: 1,
...this.inputMarginPadding,
},
};
render() {
const { isTopicFocused, isMenuExpanded, height, message, topic, selection } = this.state;
const {
ownEmail,
narrow,
usersByEmail,
editMessage,
safeAreaInsets,
isAdmin,
isAnnouncementOnly,
isSubscribed,
jitsiServerUrl,
stream,
} = this.props;
const insertVideoCallLink =
jitsiServerUrl !== null ? () => this.insertVideoCallLink(jitsiServerUrl) : null;
if (!isSubscribed) {
return <NotSubscribed narrow={narrow} />;
} else if (isAnnouncementOnly && !isAdmin) {
return <AnnouncementOnly />;
}
const placeholder = getComposeInputPlaceholder(narrow, ownEmail, usersByEmail);
const style = {
paddingBottom: safeAreaInsets.bottom,
backgroundColor: 'hsla(0, 0%, 50%, 0.1)',
};
return (
<View style={this.styles.wrapper}>
<MentionWarnings narrow={narrow} stream={stream} ref={this.mentionWarnings} />
<View style={[this.styles.autocompleteWrapper, { marginBottom: height }]}>
<TopicAutocomplete
isFocused={isTopicFocused}
narrow={narrow}
text={topic}
onAutocomplete={this.handleTopicAutocomplete}
/>
<AutocompleteView
isFocused={this.state.isMessageFocused}
selection={selection}
text={message}
onAutocomplete={this.handleMessageAutocomplete}
/>
</View>
<View style={[this.styles.composeBox, style]} onLayout={this.handleLayoutChange}>
<ComposeMenu
destinationNarrow={this.getDestinationNarrow()}
expanded={isMenuExpanded}
insertVideoCallLink={insertVideoCallLink}
onExpandContract={this.handleComposeMenuToggle}
/>
<View style={this.styles.composeText}>
{this.getCanSelectTopic() && (
<Input
style={[this.styles.topicInput, { backgroundColor: this.context.backgroundColor }]}
underlineColorAndroid="transparent"
placeholder="Topic"
defaultValue={topic}
selectTextOnFocus
textInputRef={this.topicInputRef}
onChangeText={this.handleTopicChange}
onFocus={this.handleTopicFocus}
onBlur={this.handleTopicBlur}
onTouchStart={this.handleInputTouchStart}
/>
)}
<Input
multiline={!isMenuExpanded}
style={[
this.styles.composeTextInput,
{ backgroundColor: this.context.backgroundColor },
]}
underlineColorAndroid="transparent"
placeholder={placeholder}
defaultValue={message}
textInputRef={this.messageInputRef}
onBlur={this.handleMessageBlur}
onChangeText={this.handleMessageChange}
onFocus={this.handleMessageFocus}
onSelectionChange={this.handleMessageSelectionChange}
onTouchStart={this.handleInputTouchStart}
/>
</View>
<FloatingActionButton
style={this.styles.composeSendButton}
Icon={editMessage === null ? IconSend : IconDone}
size={32}
disabled={message.trim().length === 0}
onPress={editMessage === null ? this.handleSend : this.handleEdit}
/>
</View>
</View>
);
}
}
export default connect<SelectorProps, _, _>((state, props) => ({
auth: getAuth(state),
ownEmail: getOwnEmail(state),
usersByEmail: getActiveUsersByEmail(state),
safeAreaInsets: getSession(state).safeAreaInsets,
isAdmin: getIsAdmin(state),
isAnnouncementOnly: getIsActiveStreamAnnouncementOnly(state, props.narrow),
isSubscribed: getIsActiveStreamSubscribed(state, props.narrow),
draft: getDraftForNarrow(state, props.narrow),
lastMessageTopic: getLastMessageTopic(state, props.narrow),
caughtUp: getCaughtUpForNarrow(state, props.narrow),
jitsiServerUrl: getJitsiServerUrl(state),
stream: getStreamInNarrow(state, props.narrow),
}))(withGetText(ComposeBox));