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">
262 <Link class="alert-link" to="/login">
272 handleFinished(op: UserOperation, data: CommentResponse) {
274 this.props.node !== undefined && data.comment.parent_id !== null;
276 +!(data.comment.parent_id !== null) ^ +(this.props.node !== undefined);
279 (data.comment.creator_id == UserService.Instance.user.id &&
280 ((op == UserOperation.CreateComment &&
281 // If its a reply, make sure parent child match
283 data.comment.parent_id == this.props.node.comment.id) ||
284 // Otherwise, check the XOR of the two
285 (!isReply && xor))) ||
286 // If its a comment edit, only check that its from your user, and that its a
289 (data.comment.creator_id == UserService.Instance.user.id &&
290 op == UserOperation.EditComment &&
291 data.comment.content)
293 this.state.previewMode = false;
294 this.state.loading = false;
295 this.state.commentForm.content = '';
296 this.setState(this.state);
297 let form: any = document.getElementById(this.formId);
299 if (this.props.node) {
300 this.props.onReplyCancel();
302 autosize.update(form);
303 this.setState(this.state);
307 handleCommentSubmit(i: CommentForm, event: any) {
308 event.preventDefault();
310 WebSocketService.Instance.editComment(i.state.commentForm);
312 WebSocketService.Instance.createComment(i.state.commentForm);
315 i.state.loading = true;
319 handleCommentContentChange(i: CommentForm, event: any) {
320 i.state.commentForm.content = event.target.value;
324 handlePreviewToggle(i: CommentForm, event: any) {
325 event.preventDefault();
326 i.state.previewMode = !i.state.previewMode;
330 handleReplyCancel(i: CommentForm) {
331 i.props.onReplyCancel();
334 handleImageUploadPaste(i: CommentForm, event: any) {
335 let image = event.clipboardData.files[0];
337 i.handleImageUpload(i, image);
341 handleImageUpload(i: CommentForm, event: any) {
344 event.preventDefault();
345 file = event.target.files[0];
350 const imageUploadUrl = `/pictrs/image`;
351 const formData = new FormData();
352 formData.append('images[]', file);
354 i.state.imageLoading = true;
357 fetch(imageUploadUrl, {
361 .then(res => res.json())
363 console.log('pictrs upload:');
365 if (res.msg == 'ok') {
366 let hash = res.files[0].file;
367 let url = `${window.location.origin}/pictrs/image/${hash}`;
368 let deleteToken = res.files[0].delete_token;
369 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
370 let imageMarkdown = `![](${url})`;
371 let content = i.state.commentForm.content;
372 content = content ? `${content}\n${imageMarkdown}` : imageMarkdown;
373 i.state.commentForm.content = content;
374 i.state.imageLoading = false;
376 let textarea: any = document.getElementById(i.id);
377 autosize.update(textarea);
379 i18n.t('click_to_delete_picture'),
380 i18n.t('picture_deleted'),
384 i.state.imageLoading = false;
386 toast(JSON.stringify(res), 'danger');
390 i.state.imageLoading = false;
392 toast(error, 'danger');
396 parseMessage(msg: WebSocketJsonResponse) {
397 let res = wsJsonToRes(msg);
399 // Only do the showing and hiding if logged in
400 if (UserService.Instance.user) {
401 if (res.op == UserOperation.CreateComment) {
402 let data = res.data as CommentResponse;
403 this.handleFinished(res.op, data);
404 } else if (res.op == UserOperation.EditComment) {
405 let data = res.data as CommentResponse;
406 this.handleFinished(res.op, data);