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,
23 import { WebSocketService, UserService } from '../services';
24 import autosize from 'autosize';
25 import Tribute from 'tributejs/src/Tribute.js';
26 import emojiShortName from 'emoji-short-name';
27 import { i18n } from '../i18next';
28 import { T } from 'inferno-i18next';
30 interface CommentFormProps {
33 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();
78 this.state = this.emptyState;
80 if (this.props.node) {
81 if (this.props.edit) {
82 this.state.commentForm.edit_id = this.props.node.comment.id;
83 this.state.commentForm.parent_id = this.props.node.comment.parent_id;
84 this.state.commentForm.content = this.props.node.comment.content;
85 this.state.commentForm.creator_id = this.props.node.comment.creator_id;
87 // A reply gets a new parent id
88 this.state.commentForm.parent_id = this.props.node.comment.id;
92 this.subscription = WebSocketService.Instance.subject
93 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
95 msg => this.parseMessage(msg),
96 err => console.error(err),
97 () => console.log('complete')
101 componentDidMount() {
102 let textarea: any = document.getElementById(this.id);
105 this.tribute.attach(textarea);
106 textarea.addEventListener('tribute-replaced', () => {
107 this.state.commentForm.content = textarea.value;
108 this.setState(this.state);
109 autosize.update(textarea);
112 // Quoting of selected text
113 let selectedText = window.getSelection().toString();
119 .join('\n') + '\n\n';
120 this.state.commentForm.content = quotedText;
121 this.setState(this.state);
122 // Not sure why this needs a delay
123 setTimeout(() => autosize.update(textarea), 10);
126 if (this.props.focus) {
132 componentDidUpdate() {
133 if (this.state.commentForm.content) {
134 window.onbeforeunload = () => true;
136 window.onbeforeunload = undefined;
140 componentWillUnmount() {
141 this.subscription.unsubscribe();
142 window.onbeforeunload = null;
149 when={this.state.commentForm.content}
150 message={i18n.t('block_leaving')}
152 {UserService.Instance.user ? (
155 onSubmit={linkEvent(this, this.handleCommentSubmit)}
157 <div class="form-group row">
158 <div className={`col-sm-12`}>
161 className={`form-control ${
162 this.state.previewMode && 'd-none'
164 value={this.state.commentForm.content}
165 onInput={linkEvent(this, this.handleCommentContentChange)}
166 onPaste={linkEvent(this, this.handleImageUploadPaste)}
168 disabled={this.props.disabled}
172 {this.state.previewMode && (
174 className="card card-body md-div"
175 dangerouslySetInnerHTML={mdToHtml(
176 this.state.commentForm.content
183 <div class="col-sm-12">
186 class="btn btn-sm btn-secondary mr-2"
187 disabled={this.props.disabled || this.state.loading}
189 {this.state.loading ? (
190 <svg class="icon icon-spinner spin">
191 <use xlinkHref="#icon-spinner"></use>
194 <span>{this.state.buttonTitle}</span>
197 {this.state.commentForm.content && (
199 className={`btn btn-sm mr-2 btn-secondary ${
200 this.state.previewMode && 'active'
202 onClick={linkEvent(this, this.handlePreviewToggle)}
207 {this.props.node && (
210 class="btn btn-sm btn-secondary mr-2"
211 onClick={linkEvent(this, this.handleReplyCancel)}
217 href={markdownHelpUrl}
219 class="d-inline-block float-right text-muted font-weight-bold"
220 title={i18n.t('formatting_help')}
223 <svg class="icon icon-inline">
224 <use xlinkHref="#icon-help-circle"></use>
227 <form class="d-inline-block mr-3 float-right text-muted font-weight-bold">
229 htmlFor={`file-upload-${this.id}`}
230 className={`${UserService.Instance.user && 'pointer'}`}
231 data-tippy-content={i18n.t('upload_image')}
233 <svg class="icon icon-inline">
234 <use xlinkHref="#icon-image"></use>
238 id={`file-upload-${this.id}`}
240 accept="image/*,video/*"
243 disabled={!UserService.Instance.user}
244 onChange={linkEvent(this, this.handleImageUpload)}
247 {this.state.imageLoading && (
248 <svg class="icon icon-spinner spin">
249 <use xlinkHref="#icon-spinner"></use>
256 <div class="alert alert-warning" role="alert">
257 <svg class="icon icon-inline mr-2">
258 <use xlinkHref="#icon-alert-triangle"></use>
260 <T i18nKey="must_login" class="d-inline">
261 #<Link to="/login">#</Link>
269 handleFinished(op: UserOperation, data: CommentResponse) {
271 this.props.node !== undefined && data.comment.parent_id !== null;
273 +!(data.comment.parent_id !== null) ^ +(this.props.node !== undefined);
276 (data.comment.creator_id == UserService.Instance.user.id &&
277 ((op == UserOperation.CreateComment &&
278 // If its a reply, make sure parent child match
280 data.comment.parent_id == this.props.node.comment.id) ||
281 // Otherwise, check the XOR of the two
282 (!isReply && xor))) ||
283 // If its a comment edit, only check that its from your user, and that its a
286 (data.comment.creator_id == UserService.Instance.user.id &&
287 op == UserOperation.EditComment &&
288 data.comment.content)
290 this.state.previewMode = false;
291 this.state.loading = false;
292 this.state.commentForm.content = '';
293 this.setState(this.state);
294 let form: any = document.getElementById(this.formId);
296 if (this.props.node) {
297 this.props.onReplyCancel();
299 autosize.update(form);
300 this.setState(this.state);
304 handleCommentSubmit(i: CommentForm, event: any) {
305 event.preventDefault();
307 WebSocketService.Instance.editComment(i.state.commentForm);
309 WebSocketService.Instance.createComment(i.state.commentForm);
312 i.state.loading = true;
316 handleCommentContentChange(i: CommentForm, event: any) {
317 i.state.commentForm.content = event.target.value;
321 handlePreviewToggle(i: CommentForm, event: any) {
322 event.preventDefault();
323 i.state.previewMode = !i.state.previewMode;
327 handleReplyCancel(i: CommentForm) {
328 i.props.onReplyCancel();
331 handleImageUploadPaste(i: CommentForm, event: any) {
332 let image = event.clipboardData.files[0];
334 i.handleImageUpload(i, image);
338 handleImageUpload(i: CommentForm, event: any) {
341 event.preventDefault();
342 file = event.target.files[0];
347 const imageUploadUrl = `/pictrs/image`;
348 const formData = new FormData();
349 formData.append('images[]', file);
351 i.state.imageLoading = true;
354 fetch(imageUploadUrl, {
358 .then(res => res.json())
360 console.log('pictrs upload:');
362 if (res.msg == 'ok') {
363 let hash = res.files[0].file;
364 let url = `${window.location.origin}/pictrs/image/${hash}`;
365 let deleteToken = res.files[0].delete_token;
366 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
367 let imageMarkdown = `![](${url})`;
368 let content = i.state.commentForm.content;
369 content = content ? `${content}\n${imageMarkdown}` : imageMarkdown;
370 i.state.commentForm.content = content;
371 i.state.imageLoading = false;
373 let textarea: any = document.getElementById(i.id);
374 autosize.update(textarea);
376 i18n.t('click_to_delete_picture'),
377 i18n.t('picture_deleted'),
381 i.state.imageLoading = false;
383 toast(JSON.stringify(res), 'danger');
387 i.state.imageLoading = false;
389 toast(error, 'danger');
393 parseMessage(msg: WebSocketJsonResponse) {
394 let res = wsJsonToRes(msg);
396 // Only do the showing and hiding if logged in
397 if (UserService.Instance.user) {
398 if (res.op == UserOperation.CreateComment) {
399 let data = res.data as CommentResponse;
400 this.handleFinished(res.op, data);
401 } else if (res.op == UserOperation.EditComment) {
402 let data = res.data as CommentResponse;
403 this.handleFinished(res.op, data);