1 import { Component, linkEvent } from 'inferno';
2 import { Link } from 'inferno-router';
3 import { Subscription } from 'rxjs';
4 import { retryWhen, delay, take } from 'rxjs/operators';
5 import { Prompt } from 'inferno-router';
7 CommentNode as CommentNodeI,
8 CommentForm as CommentFormI,
12 } from '../interfaces';
14 capitalizeFirstLetter,
24 import { WebSocketService, UserService } from '../services';
25 import autosize from 'autosize';
26 import Tribute from 'tributejs/src/Tribute.js';
27 import emojiShortName from 'emoji-short-name';
28 import { i18n } from '../i18next';
29 import { T } from 'inferno-i18next';
31 interface CommentFormProps {
34 onReplyCancel?(): any;
39 interface CommentFormState {
40 commentForm: CommentFormI;
44 imageLoading: boolean;
47 export class CommentForm extends Component<CommentFormProps, CommentFormState> {
48 private id = `comment-textarea-${randomStr()}`;
49 private formId = `comment-form-${randomStr()}`;
50 private tribute: Tribute;
51 private subscription: Subscription;
52 private emptyState: CommentFormState = {
56 post_id: this.props.node
57 ? this.props.node.comment.post_id
59 creator_id: UserService.Instance.user
60 ? UserService.Instance.user.id
63 buttonTitle: !this.props.node
64 ? capitalizeFirstLetter(i18n.t('post'))
66 ? capitalizeFirstLetter(i18n.t('save'))
67 : capitalizeFirstLetter(i18n.t('reply')),
73 constructor(props: any, context: any) {
74 super(props, context);
76 this.tribute = setupTribute();
77 this.setupEmojiPicker();
79 this.state = this.emptyState;
81 if (this.props.node) {
82 if (this.props.edit) {
83 this.state.commentForm.edit_id = this.props.node.comment.id;
84 this.state.commentForm.parent_id = this.props.node.comment.parent_id;
85 this.state.commentForm.content = this.props.node.comment.content;
86 this.state.commentForm.creator_id = this.props.node.comment.creator_id;
88 // A reply gets a new parent id
89 this.state.commentForm.parent_id = this.props.node.comment.id;
93 this.subscription = WebSocketService.Instance.subject
94 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
96 msg => this.parseMessage(msg),
97 err => console.error(err),
98 () => console.log('complete')
102 componentDidMount() {
103 let textarea: any = document.getElementById(this.id);
106 this.tribute.attach(textarea);
107 textarea.addEventListener('tribute-replaced', () => {
108 this.state.commentForm.content = textarea.value;
109 this.setState(this.state);
110 autosize.update(textarea);
113 // Quoting of selected text
114 let selectedText = window.getSelection().toString();
120 .join('\n') + '\n\n';
121 this.state.commentForm.content = quotedText;
122 this.setState(this.state);
123 // Not sure why this needs a delay
124 setTimeout(() => autosize.update(textarea), 10);
131 componentDidUpdate() {
132 if (this.state.commentForm.content) {
133 window.onbeforeunload = () => true;
135 window.onbeforeunload = undefined;
139 componentWillUnmount() {
140 this.subscription.unsubscribe();
141 window.onbeforeunload = null;
148 when={this.state.commentForm.content}
149 message={i18n.t('block_leaving')}
151 {UserService.Instance.user ? (
154 onSubmit={linkEvent(this, this.handleCommentSubmit)}
156 <div class="form-group row">
157 <div className={`col-sm-12`}>
160 className={`form-control ${
161 this.state.previewMode && 'd-none'
163 value={this.state.commentForm.content}
164 onInput={linkEvent(this, this.handleCommentContentChange)}
165 onPaste={linkEvent(this, this.handleImageUploadPaste)}
167 disabled={this.props.disabled}
171 {this.state.previewMode && (
173 className="card card-body md-div"
174 dangerouslySetInnerHTML={mdToHtml(
175 this.state.commentForm.content
182 <div class="col-sm-12">
185 class="btn btn-sm btn-secondary mr-2"
186 disabled={this.props.disabled || this.state.loading}
188 {this.state.loading ? (
189 <svg class="icon icon-spinner spin">
190 <use xlinkHref="#icon-spinner"></use>
193 <span>{this.state.buttonTitle}</span>
196 {this.state.commentForm.content && (
198 className={`btn btn-sm mr-2 btn-secondary ${
199 this.state.previewMode && 'active'
201 onClick={linkEvent(this, this.handlePreviewToggle)}
206 {this.props.node && (
209 class="btn btn-sm btn-secondary mr-2"
210 onClick={linkEvent(this, this.handleReplyCancel)}
216 href={markdownHelpUrl}
218 class="d-inline-block float-right text-muted font-weight-bold"
219 title={i18n.t('formatting_help')}
222 <svg class="icon icon-inline">
223 <use xlinkHref="#icon-help-circle"></use>
226 <form class="d-inline-block mr-3 float-right text-muted font-weight-bold">
228 htmlFor={`file-upload-${this.id}`}
229 className={`${UserService.Instance.user && 'pointer'}`}
230 data-tippy-content={i18n.t('upload_image')}
232 <svg class="icon icon-inline">
233 <use xlinkHref="#icon-image"></use>
237 id={`file-upload-${this.id}`}
239 accept="image/*,video/*"
242 disabled={!UserService.Instance.user}
243 onChange={linkEvent(this, this.handleImageUpload)}
246 {this.state.imageLoading && (
247 <svg class="icon icon-spinner spin">
248 <use xlinkHref="#icon-spinner"></use>
252 onClick={linkEvent(this, this.handleEmojiPickerClick)}
253 class="pointer unselectable d-inline-block mr-3 float-right text-muted font-weight-bold"
254 data-tippy-content={i18n.t('emoji_picker')}
256 <svg class="icon icon-inline">
257 <use xlinkHref="#icon-smile"></use>
264 <div class="alert alert-warning" role="alert">
265 <svg class="icon icon-inline mr-2">
266 <use xlinkHref="#icon-alert-triangle"></use>
268 <T i18nKey="must_login" class="d-inline">
269 #<Link to="/login">#</Link>
278 emojiPicker.on('emoji', twemojiHtmlStr => {
279 if (this.state.commentForm.content == null) {
280 this.state.commentForm.content = '';
282 var el = document.createElement('div');
283 el.innerHTML = twemojiHtmlStr;
284 let nativeUnicode = (el.childNodes[0] as HTMLElement).getAttribute('alt');
285 let shortName = `:${emojiShortName[nativeUnicode]}:`;
286 this.state.commentForm.content += shortName;
287 this.setState(this.state);
291 handleFinished(op: UserOperation, data: CommentResponse) {
293 this.props.node !== undefined && data.comment.parent_id !== null;
295 +!(data.comment.parent_id !== null) ^ +(this.props.node !== undefined);
298 (data.comment.creator_id == UserService.Instance.user.id &&
299 ((op == UserOperation.CreateComment &&
300 // If its a reply, make sure parent child match
302 data.comment.parent_id == this.props.node.comment.id) ||
303 // Otherwise, check the XOR of the two
304 (!isReply && xor))) ||
305 // If its a comment edit, only check that its from your user, and that its a
308 (data.comment.creator_id == UserService.Instance.user.id &&
309 op == UserOperation.EditComment &&
310 data.comment.content)
312 this.state.previewMode = false;
313 this.state.loading = false;
314 this.state.commentForm.content = '';
315 this.setState(this.state);
316 let form: any = document.getElementById(this.formId);
318 if (this.props.node) {
319 this.props.onReplyCancel();
321 autosize.update(form);
322 this.setState(this.state);
326 handleCommentSubmit(i: CommentForm, event: any) {
327 event.preventDefault();
329 WebSocketService.Instance.editComment(i.state.commentForm);
331 WebSocketService.Instance.createComment(i.state.commentForm);
334 i.state.loading = true;
338 handleEmojiPickerClick(_i: CommentForm, event: any) {
339 emojiPicker.togglePicker(event.target);
342 handleCommentContentChange(i: CommentForm, event: any) {
343 i.state.commentForm.content = event.target.value;
347 handlePreviewToggle(i: CommentForm, event: any) {
348 event.preventDefault();
349 i.state.previewMode = !i.state.previewMode;
353 handleReplyCancel(i: CommentForm) {
354 i.props.onReplyCancel();
357 handleImageUploadPaste(i: CommentForm, event: any) {
358 let image = event.clipboardData.files[0];
360 i.handleImageUpload(i, image);
364 handleImageUpload(i: CommentForm, event: any) {
367 event.preventDefault();
368 file = event.target.files[0];
373 const imageUploadUrl = `/pictrs/image`;
374 const formData = new FormData();
375 formData.append('images[]', file);
377 i.state.imageLoading = true;
380 fetch(imageUploadUrl, {
384 .then(res => res.json())
386 console.log('pictrs upload:');
388 if (res.msg == 'ok') {
389 let hash = res.files[0].file;
390 let url = `${window.location.origin}/pictrs/image/${hash}`;
391 let deleteToken = res.files[0].delete_token;
392 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
393 let imageMarkdown = `![](${url})`;
394 let content = i.state.commentForm.content;
395 content = content ? `${content}\n${imageMarkdown}` : imageMarkdown;
396 i.state.commentForm.content = content;
397 i.state.imageLoading = false;
399 let textarea: any = document.getElementById(i.id);
400 autosize.update(textarea);
402 i18n.t('click_to_delete_picture'),
403 i18n.t('picture_deleted'),
407 i.state.imageLoading = false;
409 toast(JSON.stringify(res), 'danger');
413 i.state.imageLoading = false;
415 toast(error, 'danger');
419 parseMessage(msg: WebSocketJsonResponse) {
420 let res = wsJsonToRes(msg);
422 // Only do the showing and hiding if logged in
423 if (UserService.Instance.user) {
424 if (res.op == UserOperation.CreateComment) {
425 let data = res.data as CommentResponse;
426 this.handleFinished(res.op, data);
427 } else if (res.op == UserOperation.EditComment) {
428 let data = res.data as CommentResponse;
429 this.handleFinished(res.op, data);