This repository has been archived by the owner on Oct 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathindex.js
582 lines (515 loc) · 15.4 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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
// @flow
import * as React from 'react';
import compose from 'recompose/compose';
import { withRouter, type History, type Location } from 'react-router';
import { connect } from 'react-redux';
import debounce from 'debounce';
import Icon from 'src/components/icon';
import { openModal, closeModal } from 'src/actions/modals';
import getThreadLink from 'src/helpers/get-thread-link';
import { addToastWithTimeout } from 'src/actions/toasts';
import getComposerCommunitiesAndChannels from 'shared/graphql/queries/composer/getComposerCommunitiesAndChannels';
import type { GetComposerType } from 'shared/graphql/queries/composer/getComposerCommunitiesAndChannels';
import publishThread from 'shared/graphql/mutations/thread/publishThread';
import { setTitlebarProps } from 'src/actions/titlebar';
import uploadImage, {
type UploadImageInput,
type UploadImageType,
} from 'shared/graphql/mutations/uploadImage';
import Head from 'src/components/head';
import { TextButton } from 'src/components/button';
import { PrimaryButton } from 'src/components/button';
import Tooltip from 'src/components/tooltip';
import {
MediaLabel,
MediaInput,
} from 'src/components/chatInput/components/style';
import type { Dispatch } from 'redux';
import {
Overlay,
Container,
Actions,
DisabledWarning,
InputHints,
DesktopLink,
ButtonRow,
Wrapper,
} from './style';
import { events, track } from 'src/helpers/analytics';
import { ESC, ENTER } from 'src/helpers/keycodes';
import Inputs from './inputs';
import ComposerLocationSelectors from './LocationSelectors';
import {
getDraftThread,
storeDraftThread,
clearDraftThread,
} from 'src/helpers/thread-draft-handling';
type State = {
title: string,
body: string,
isLoading: boolean,
postWasPublished: boolean,
preview: boolean,
selectedChannelId: ?string,
selectedCommunityId: ?string,
};
type Props = {
data: {
user: GetComposerType,
refetch: Function,
loading: boolean,
},
uploadImage: (input: UploadImageInput) => Promise<UploadImageType>,
dispatch: Dispatch<Object>,
publishThread: Function,
history: History,
location: Location,
websocketConnection: string,
networkOnline: boolean,
isEditing: boolean,
isModal?: boolean,
previousLocation?: Location,
};
export const DISCARD_DRAFT_MESSAGE =
'Are you sure you want to discard this draft?';
// We persist the body and title to localStorage
// so in case the app crashes users don't loose content
class ComposerWithData extends React.Component<Props, State> {
bodyEditor: any;
constructor(props) {
super(props);
this.state = {
title: '',
body: '',
isLoading: false,
postWasPublished: false,
preview: false,
selectedChannelId: '',
selectedCommunityId: '',
};
this.persistBodyToLocalStorageWithDebounce = debounce(
this.persistBodyToLocalStorageWithDebounce,
500
);
this.persistTitleToLocalStorageWithDebounce = debounce(
this.persistTitleToLocalStorageWithDebounce,
500
);
}
removeStorage = async () => {
await clearDraftThread();
};
getTitleAndBody = () => {
const { body: storedBody, title: storedTitle } = getDraftThread();
return {
storedBody,
storedTitle,
};
};
componentWillMount() {
let { storedBody, storedTitle } = this.getTitleAndBody();
this.setState({
title: this.state.title || storedTitle || '',
body: this.state.body || storedBody || '',
});
}
componentDidMount() {
const { dispatch } = this.props;
dispatch(
setTitlebarProps({
title: 'New post',
})
);
track(events.THREAD_CREATED_INITED);
// $FlowIssue
document.addEventListener('keydown', this.handleGlobalKeyPress, false);
}
componentWillUnmount() {
// $FlowIssue
document.removeEventListener('keydown', this.handleGlobalKeyPress, false);
const { postWasPublished } = this.state;
// if a post was published, in this session, clear redux so that the next
// composer open will start fresh
if (postWasPublished) return;
// otherwise, clear the composer normally and save the state
return;
}
handleGlobalKeyPress = e => {
const esc = e && e.keyCode === ESC;
const enter = e.keyCode === ENTER;
const cmdEnter = e.keyCode === ENTER && e.metaKey;
// we need to verify the source of the keypress event
// so that if it comes from the discard draft modal, it should not
// listen to the events for composer
const innerText = e.target.innerText;
const modalIsOpen = innerText.indexOf(DISCARD_DRAFT_MESSAGE) >= 0;
if (esc && modalIsOpen) {
e.stopPropagation();
this.props.dispatch(closeModal());
return;
}
if (enter && modalIsOpen) {
e.stopPropagation();
this.discardDraft();
return;
}
const composerHasContent = this.composerHasContent();
if (esc && composerHasContent) {
this.discardDraft();
return;
}
if (esc && !composerHasContent) {
return this.closeComposer();
}
if (cmdEnter && !modalIsOpen) return this.publishThread();
};
composerHasContent = () => {
const { title, body } = this.state;
return title !== '' || body !== '';
};
changeTitle = e => {
const title = e.target.value;
this.persistTitleToLocalStorageWithDebounce();
if (/\n$/g.test(title)) {
this.bodyEditor.focus && this.bodyEditor.focus();
return;
}
this.setState({
title,
});
};
changeBody = evt => {
const body = evt.target.value;
this.persistBodyToLocalStorageWithDebounce();
this.setState({
body,
});
};
closeComposer = (clear?: any) => {
this.persistBodyToLocalStorage();
this.persistTitleToLocalStorage();
// we will clear the composer if it unmounts as a result of a post
// being published or draft discarded, that way the next composer open will start fresh
if (clear) {
this.clearEditorStateAfterPublish();
this.setState({
title: '',
body: '',
preview: false,
});
}
if (this.props.previousLocation)
return this.props.history.push({
...this.props.previousLocation,
state: { modal: false },
});
return this.props.history.goBack({ state: { modal: false } });
};
discardDraft = () => {
const composerHasContent = this.composerHasContent();
if (!composerHasContent) {
return this.closeComposer();
}
this.props.dispatch(
openModal('CLOSE_COMPOSER_CONFIRMATION_MODAL', {
message: DISCARD_DRAFT_MESSAGE,
closeComposer: () => this.closeComposer('clear'),
})
);
};
clearEditorStateAfterPublish = () => {
try {
this.removeStorage();
} catch (err) {
console.error(err);
}
};
onCancelClick = () => {
this.discardDraft();
};
handleTitleBodyChange = (key: 'title' | 'body') => {
storeDraftThread({
[key]: this.state[key],
});
};
persistBodyToLocalStorageWithDebounce = () => {
if (!localStorage) return;
this.handleTitleBodyChange('body');
};
persistTitleToLocalStorageWithDebounce = () => {
if (!localStorage) return;
this.handleTitleBodyChange('title');
};
persistTitleToLocalStorage = () => {
if (!localStorage) return;
this.handleTitleBodyChange('title');
};
persistBodyToLocalStorage = () => {
if (!localStorage) return;
this.handleTitleBodyChange('body');
};
uploadFile = evt => {
this.uploadFiles(evt.target.files);
};
uploadFiles = files => {
const uploading = `![Uploading ${files[0].name}...]()`;
let caretPos = this.bodyEditor.selectionStart;
this.setState(
({ body }) => ({
isLoading: true,
body:
body.substring(0, caretPos) +
uploading +
body.substring(this.bodyEditor.selectionEnd, this.state.body.length),
}),
() => {
caretPos = caretPos + uploading.length;
this.bodyEditor.selectionStart = caretPos;
this.bodyEditor.selectionEnd = caretPos;
this.bodyEditor.focus();
}
);
return this.props
.uploadImage({
image: files[0],
type: 'threads',
})
.then(({ data }) => {
this.setState({
isLoading: false,
});
this.changeBody({
target: {
value: this.state.body.replace(
uploading,
`![${files[0].name}](${data.uploadImage})`
),
},
});
})
.catch(err => {
console.error({ err });
this.setState({
isLoading: false,
});
this.changeBody({
target: {
value: this.state.body.replace(uploading, ''),
},
});
this.props.dispatch(
addToastWithTimeout(
'error',
`Uploading image failed - ${err.message}`
)
);
});
};
publishThread = () => {
// if no title and no channel is set, don't allow a thread to be published
if (
!this.state.title ||
!this.state.selectedCommunityId ||
!this.state.selectedChannelId
) {
return;
}
// isLoading will change the publish button to a loading spinner
this.setState({
isLoading: true,
});
const { dispatch, networkOnline, websocketConnection } = this.props;
if (!networkOnline) {
return dispatch(
addToastWithTimeout(
'error',
'Not connected to the internet - check your internet connection or try again'
)
);
}
if (
websocketConnection !== 'connected' &&
websocketConnection !== 'reconnected'
) {
return dispatch(
addToastWithTimeout(
'error',
'Error connecting to the server - hang tight while we try to reconnect'
)
);
}
// define new constants in order to construct the proper shape of the
// input for the publishThread mutation
const { selectedChannelId, selectedCommunityId, title, body } = this.state;
const channelId = selectedChannelId;
const communityId = selectedCommunityId;
const content = {
title: title.trim(),
// workaround react-mentions bug by replacing @[username] with @username
// @see withspectrum/spectrum#4587
body: body.replace(/@\[([a-z0-9_-]+)\]/g, '@$1'),
};
// this.props.mutate comes from a higher order component defined at the
// bottom of this file
const thread = {
channelId,
communityId,
// NOTE(@mxstbr): On android we send plain text content
// which is parsed as markdown to draftjs on the server
type: 'TEXT',
content,
// filesToUpload,
};
// one last save to localstorage
this.persistBodyToLocalStorage();
this.persistTitleToLocalStorage();
this.props
.publishThread(thread)
// after the mutation occurs, it will either return an error or the new
// thread that was published
.then(({ data }) => {
this.clearEditorStateAfterPublish();
// stop the loading spinner on the publish button
this.setState({
isLoading: false,
postWasPublished: true,
title: '',
body: '',
});
// redirect the user to the thread
// if they are in the inbox, select it
this.props.dispatch(
addToastWithTimeout('success', 'Thread published!')
);
if (this.props.location.pathname === '/new/thread') {
this.props.history.replace(getThreadLink(data.publishThread));
} else {
this.props.history.push(getThreadLink(data.publishThread));
}
return;
})
.catch(err => {
this.setState({
isLoading: false,
});
this.props.dispatch(addToastWithTimeout('error', err.message));
});
};
setSelectedCommunity = (id: string) => {
return this.setState({ selectedCommunityId: id });
};
setSelectedChannel = (id: string) => {
return this.setState({ selectedChannelId: id });
};
render() {
const {
title,
isLoading,
selectedChannelId,
selectedCommunityId,
} = this.state;
const {
networkOnline,
websocketConnection,
isEditing,
isModal,
} = this.props;
const networkDisabled =
!networkOnline ||
(websocketConnection !== 'connected' &&
websocketConnection !== 'reconnected');
return (
<Wrapper data-cy="thread-composer-wrapper">
<Head title={'New post'} description={'Write a new post'} />
<Overlay
isModal={isModal}
onClick={this.discardDraft}
data-cy="overlay"
/>
<Container data-cy="modal-container" isModal={isModal}>
<ComposerLocationSelectors
selectedChannelId={selectedChannelId}
selectedCommunityId={selectedCommunityId}
onCommunitySelectionChanged={this.setSelectedCommunity}
onChannelSelectionChanged={this.setSelectedChannel}
/>
<Inputs
title={this.state.title}
body={this.state.body}
changeBody={this.changeBody}
changeTitle={this.changeTitle}
uploadFiles={this.uploadFiles}
autoFocus={true}
bodyRef={ref => (this.bodyEditor = ref)}
onKeyDown={this.handleGlobalKeyPress}
isEditing={isEditing}
/>
{networkDisabled && (
<DisabledWarning>
Lost connection to the internet or server...
</DisabledWarning>
)}
<Actions>
<InputHints>
<Tooltip content={'Upload photo'}>
<MediaLabel>
<MediaInput
type="file"
accept={'.png, .jpg, .jpeg, .gif, .mp4'}
multiple={false}
onChange={this.uploadFile}
/>
<Icon glyph="photo" />
</MediaLabel>
</Tooltip>
<Tooltip content={'Style with Markdown'}>
<DesktopLink
target="_blank"
href="https://guides.github.com/features/mastering-markdown/"
>
<Icon glyph="markdown" />
</DesktopLink>
</Tooltip>
</InputHints>
<ButtonRow>
<TextButton
data-cy="composer-cancel-button"
hoverColor="warn.alt"
onClick={this.discardDraft}
>
Cancel
</TextButton>
<PrimaryButton
data-cy="composer-publish-button"
onClick={this.publishThread}
loading={isLoading}
disabled={
!title ||
title.trim().length === 0 ||
isLoading ||
networkDisabled ||
!selectedChannelId ||
!selectedCommunityId
}
>
{isLoading ? 'Publishing...' : 'Publish'}
</PrimaryButton>
</ButtonRow>
</Actions>
</Container>
</Wrapper>
);
}
}
// $FlowIssue
const mapStateToProps = state => ({
websocketConnection: state.connectionStatus.websocketConnection,
networkOnline: state.connectionStatus.networkOnline,
});
export default compose(
uploadImage,
getComposerCommunitiesAndChannels,
publishThread,
withRouter,
connect(mapStateToProps)
)(ComposerWithData);