1 import { Component, linkEvent } from 'inferno';
2 import { Subscription } from 'rxjs';
3 import { retryWhen, delay, take } from 'rxjs/operators';
4 import { Prompt } from 'inferno-router';
6 CommentNode as CommentNodeI,
7 CommentForm as CommentFormI,
11 } from '../interfaces';
13 capitalizeFirstLetter,
22 import { WebSocketService, UserService } from '../services';
23 import autosize from 'autosize';
24 import Tribute from 'tributejs/src/Tribute.js';
25 import emojiShortName from 'emoji-short-name';
26 import { i18n } from '../i18next';
28 interface CommentFormProps {
31 onReplyCancel?(): any;
36 interface CommentFormState {
37 commentForm: CommentFormI;
41 imageLoading: boolean;
44 export class CommentForm extends Component<CommentFormProps, CommentFormState> {
45 private id = `comment-textarea-${randomStr()}`;
46 private formId = `comment-form-${randomStr()}`;
47 private tribute: Tribute;
48 private subscription: Subscription;
49 private emptyState: CommentFormState = {
53 post_id: this.props.node
54 ? this.props.node.comment.post_id
56 creator_id: UserService.Instance.user
57 ? UserService.Instance.user.id
60 buttonTitle: !this.props.node
61 ? capitalizeFirstLetter(i18n.t('post'))
63 ? capitalizeFirstLetter(i18n.t('save'))
64 : capitalizeFirstLetter(i18n.t('reply')),
70 constructor(props: any, context: any) {
71 super(props, context);
73 this.tribute = setupTribute();
75 this.state = this.emptyState;
77 if (this.props.node) {
78 if (this.props.edit) {
79 this.state.commentForm.edit_id = this.props.node.comment.id;
80 this.state.commentForm.parent_id = this.props.node.comment.parent_id;
81 this.state.commentForm.content = this.props.node.comment.content;
82 this.state.commentForm.creator_id = this.props.node.comment.creator_id;
84 // A reply gets a new parent id
85 this.state.commentForm.parent_id = this.props.node.comment.id;
89 this.subscription = WebSocketService.Instance.subject
90 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
92 msg => this.parseMessage(msg),
93 err => console.error(err),
94 () => console.log('complete')
99 let textarea: any = document.getElementById(this.id);
101 this.tribute.attach(textarea);
102 textarea.addEventListener('tribute-replaced', () => {
103 this.state.commentForm.content = textarea.value;
104 this.setState(this.state);
105 autosize.update(textarea);
108 // Quoting of selected text
109 let selectedText = window.getSelection().toString();
115 .join('\n') + '\n\n';
116 this.state.commentForm.content = quotedText;
117 this.setState(this.state);
118 // Not sure why this needs a delay
119 setTimeout(() => autosize.update(textarea), 10);
125 componentDidUpdate() {
126 if (this.state.commentForm.content) {
127 window.onbeforeunload = () => true;
129 window.onbeforeunload = undefined;
133 componentWillUnmount() {
134 this.subscription.unsubscribe();
135 window.onbeforeunload = null;
142 when={this.state.commentForm.content}
143 message={i18n.t('block_leaving')}
147 onSubmit={linkEvent(this, this.handleCommentSubmit)}
149 <div class="form-group row">
150 <div className={`col-sm-12`}>
153 className={`form-control ${this.state.previewMode && 'd-none'}`}
154 value={this.state.commentForm.content}
155 onInput={linkEvent(this, this.handleCommentContentChange)}
156 onPaste={linkEvent(this, this.handleImageUploadPaste)}
158 disabled={this.props.disabled}
162 {this.state.previewMode && (
164 className="card card-body md-div"
165 dangerouslySetInnerHTML={mdToHtml(
166 this.state.commentForm.content
173 <div class="col-sm-12">
176 class="btn btn-sm btn-secondary mr-2"
177 disabled={this.props.disabled || this.state.loading}
179 {this.state.loading ? (
180 <svg class="icon icon-spinner spin">
181 <use xlinkHref="#icon-spinner"></use>
184 <span>{this.state.buttonTitle}</span>
187 {this.state.commentForm.content && (
189 className={`btn btn-sm mr-2 btn-secondary ${
190 this.state.previewMode && 'active'
192 onClick={linkEvent(this, this.handlePreviewToggle)}
197 {this.props.node && (
200 class="btn btn-sm btn-secondary mr-2"
201 onClick={linkEvent(this, this.handleReplyCancel)}
207 href={markdownHelpUrl}
209 class="d-inline-block float-right text-muted font-weight-bold"
210 title={i18n.t('formatting_help')}
213 <svg class="icon icon-inline">
214 <use xlinkHref="#icon-help-circle"></use>
217 <form class="d-inline-block mr-3 float-right text-muted font-weight-bold">
219 htmlFor={`file-upload-${this.id}`}
220 className={`${UserService.Instance.user && 'pointer'}`}
221 data-tippy-content={i18n.t('upload_image')}
223 <svg class="icon icon-inline">
224 <use xlinkHref="#icon-image"></use>
228 id={`file-upload-${this.id}`}
230 accept="image/*,video/*"
233 disabled={!UserService.Instance.user}
234 onChange={linkEvent(this, this.handleImageUpload)}
237 {this.state.imageLoading && (
238 <svg class="icon icon-spinner spin">
239 <use xlinkHref="#icon-spinner"></use>
249 handleFinished(op: UserOperation, data: CommentResponse) {
251 this.props.node !== undefined && data.comment.parent_id !== null;
253 +!(data.comment.parent_id !== null) ^ +(this.props.node !== undefined);
256 (data.comment.creator_id == UserService.Instance.user.id &&
257 ((op == UserOperation.CreateComment &&
258 // If its a reply, make sure parent child match
260 data.comment.parent_id == this.props.node.comment.id) ||
261 // Otherwise, check the XOR of the two
262 (!isReply && xor))) ||
263 // If its a comment edit, only check that its from your user, and that its a
266 (data.comment.creator_id == UserService.Instance.user.id &&
267 op == UserOperation.EditComment &&
268 data.comment.content)
270 this.state.previewMode = false;
271 this.state.loading = false;
272 this.state.commentForm.content = '';
273 this.setState(this.state);
274 let form: any = document.getElementById(this.formId);
276 if (this.props.node) {
277 this.props.onReplyCancel();
279 autosize.update(form);
280 this.setState(this.state);
284 handleCommentSubmit(i: CommentForm, event: any) {
285 event.preventDefault();
287 WebSocketService.Instance.editComment(i.state.commentForm);
289 WebSocketService.Instance.createComment(i.state.commentForm);
292 i.state.loading = true;
296 handleCommentContentChange(i: CommentForm, event: any) {
297 i.state.commentForm.content = event.target.value;
301 handlePreviewToggle(i: CommentForm, event: any) {
302 event.preventDefault();
303 i.state.previewMode = !i.state.previewMode;
307 handleReplyCancel(i: CommentForm) {
308 i.props.onReplyCancel();
311 handleImageUploadPaste(i: CommentForm, event: any) {
312 let image = event.clipboardData.files[0];
314 i.handleImageUpload(i, image);
318 handleImageUpload(i: CommentForm, event: any) {
321 event.preventDefault();
322 file = event.target.files[0];
327 const imageUploadUrl = `/pictrs/image`;
328 const formData = new FormData();
329 formData.append('images[]', file);
331 i.state.imageLoading = true;
334 fetch(imageUploadUrl, {
338 .then(res => res.json())
340 console.log('pictrs upload:');
342 if (res.msg == 'ok') {
343 let hash = res.files[0].file;
344 let url = `${window.location.origin}/pictrs/image/${hash}`;
345 let deleteToken = res.files[0].delete_token;
346 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
347 let imageMarkdown = `![](${url})`;
348 let content = i.state.commentForm.content;
349 content = content ? `${content}\n${imageMarkdown}` : imageMarkdown;
350 i.state.commentForm.content = content;
351 i.state.imageLoading = false;
353 let textarea: any = document.getElementById(i.id);
354 autosize.update(textarea);
356 i18n.t('click_to_delete_picture'),
357 i18n.t('picture_deleted'),
361 i.state.imageLoading = false;
363 toast(JSON.stringify(res), 'danger');
367 i.state.imageLoading = false;
369 toast(error, 'danger');
373 parseMessage(msg: WebSocketJsonResponse) {
374 let res = wsJsonToRes(msg);
376 // Only do the showing and hiding if logged in
377 if (UserService.Instance.user) {
378 if (res.op == UserOperation.CreateComment) {
379 let data = res.data as CommentResponse;
380 this.handleFinished(res.op, data);
381 } else if (res.op == UserOperation.EditComment) {
382 let data = res.data as CommentResponse;
383 this.handleFinished(res.op, data);