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;
38 interface CommentFormState {
39 commentForm: CommentFormI;
43 imageLoading: boolean;
46 export class CommentForm extends Component<CommentFormProps, CommentFormState> {
47 private id = `comment-textarea-${randomStr()}`;
48 private formId = `comment-form-${randomStr()}`;
49 private tribute: Tribute;
50 private subscription: Subscription;
51 private emptyState: CommentFormState = {
55 post_id: this.props.node
56 ? this.props.node.comment.post_id
58 creator_id: UserService.Instance.user
59 ? UserService.Instance.user.id
62 buttonTitle: !this.props.node
63 ? capitalizeFirstLetter(i18n.t('post'))
65 ? capitalizeFirstLetter(i18n.t('save'))
66 : capitalizeFirstLetter(i18n.t('reply')),
72 constructor(props: any, context: any) {
73 super(props, context);
75 this.tribute = setupTribute();
77 this.state = this.emptyState;
79 if (this.props.node) {
80 if (this.props.edit) {
81 this.state.commentForm.edit_id = this.props.node.comment.id;
82 this.state.commentForm.parent_id = this.props.node.comment.parent_id;
83 this.state.commentForm.content = this.props.node.comment.content;
84 this.state.commentForm.creator_id = this.props.node.comment.creator_id;
86 // A reply gets a new parent id
87 this.state.commentForm.parent_id = this.props.node.comment.id;
91 this.subscription = WebSocketService.Instance.subject
92 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
94 msg => this.parseMessage(msg),
95 err => console.error(err),
96 () => console.log('complete')
100 componentDidMount() {
101 let textarea: any = document.getElementById(this.id);
104 this.tribute.attach(textarea);
105 textarea.addEventListener('tribute-replaced', () => {
106 this.state.commentForm.content = textarea.value;
107 this.setState(this.state);
108 autosize.update(textarea);
111 // Quoting of selected text
112 let selectedText = window.getSelection().toString();
118 .join('\n') + '\n\n';
119 this.state.commentForm.content = quotedText;
120 this.setState(this.state);
121 // Not sure why this needs a delay
122 setTimeout(() => autosize.update(textarea), 10);
129 componentDidUpdate() {
130 if (this.state.commentForm.content) {
131 window.onbeforeunload = () => true;
133 window.onbeforeunload = undefined;
137 componentWillUnmount() {
138 this.subscription.unsubscribe();
139 window.onbeforeunload = null;
146 when={this.state.commentForm.content}
147 message={i18n.t('block_leaving')}
149 {UserService.Instance.user ? (
152 onSubmit={linkEvent(this, this.handleCommentSubmit)}
154 <div class="form-group row">
155 <div className={`col-sm-12`}>
158 className={`form-control ${
159 this.state.previewMode && 'd-none'
161 value={this.state.commentForm.content}
162 onInput={linkEvent(this, this.handleCommentContentChange)}
163 onPaste={linkEvent(this, this.handleImageUploadPaste)}
165 disabled={this.props.disabled}
169 {this.state.previewMode && (
171 className="card card-body md-div"
172 dangerouslySetInnerHTML={mdToHtml(
173 this.state.commentForm.content
180 <div class="col-sm-12">
183 class="btn btn-sm btn-secondary mr-2"
184 disabled={this.props.disabled || this.state.loading}
186 {this.state.loading ? (
187 <svg class="icon icon-spinner spin">
188 <use xlinkHref="#icon-spinner"></use>
191 <span>{this.state.buttonTitle}</span>
194 {this.state.commentForm.content && (
196 className={`btn btn-sm mr-2 btn-secondary ${
197 this.state.previewMode && 'active'
199 onClick={linkEvent(this, this.handlePreviewToggle)}
204 {this.props.node && (
207 class="btn btn-sm btn-secondary mr-2"
208 onClick={linkEvent(this, this.handleReplyCancel)}
214 href={markdownHelpUrl}
216 class="d-inline-block float-right text-muted font-weight-bold"
217 title={i18n.t('formatting_help')}
220 <svg class="icon icon-inline">
221 <use xlinkHref="#icon-help-circle"></use>
224 <form class="d-inline-block mr-3 float-right text-muted font-weight-bold">
226 htmlFor={`file-upload-${this.id}`}
227 className={`${UserService.Instance.user && 'pointer'}`}
228 data-tippy-content={i18n.t('upload_image')}
230 <svg class="icon icon-inline">
231 <use xlinkHref="#icon-image"></use>
235 id={`file-upload-${this.id}`}
237 accept="image/*,video/*"
240 disabled={!UserService.Instance.user}
241 onChange={linkEvent(this, this.handleImageUpload)}
244 {this.state.imageLoading && (
245 <svg class="icon icon-spinner spin">
246 <use xlinkHref="#icon-spinner"></use>
253 <div class="alert alert-warning" role="alert">
254 <svg class="icon icon-inline mr-2">
255 <use xlinkHref="#icon-alert-triangle"></use>
257 <T i18nKey="must_login" class="d-inline">
258 #<Link to="/login">#</Link>
266 handleFinished(op: UserOperation, data: CommentResponse) {
268 this.props.node !== undefined && data.comment.parent_id !== null;
270 +!(data.comment.parent_id !== null) ^ +(this.props.node !== undefined);
273 (data.comment.creator_id == UserService.Instance.user.id &&
274 ((op == UserOperation.CreateComment &&
275 // If its a reply, make sure parent child match
277 data.comment.parent_id == this.props.node.comment.id) ||
278 // Otherwise, check the XOR of the two
279 (!isReply && xor))) ||
280 // If its a comment edit, only check that its from your user, and that its a
283 (data.comment.creator_id == UserService.Instance.user.id &&
284 op == UserOperation.EditComment &&
285 data.comment.content)
287 this.state.previewMode = false;
288 this.state.loading = false;
289 this.state.commentForm.content = '';
290 this.setState(this.state);
291 let form: any = document.getElementById(this.formId);
293 if (this.props.node) {
294 this.props.onReplyCancel();
296 autosize.update(form);
297 this.setState(this.state);
301 handleCommentSubmit(i: CommentForm, event: any) {
302 event.preventDefault();
304 WebSocketService.Instance.editComment(i.state.commentForm);
306 WebSocketService.Instance.createComment(i.state.commentForm);
309 i.state.loading = true;
313 handleCommentContentChange(i: CommentForm, event: any) {
314 i.state.commentForm.content = event.target.value;
318 handlePreviewToggle(i: CommentForm, event: any) {
319 event.preventDefault();
320 i.state.previewMode = !i.state.previewMode;
324 handleReplyCancel(i: CommentForm) {
325 i.props.onReplyCancel();
328 handleImageUploadPaste(i: CommentForm, event: any) {
329 let image = event.clipboardData.files[0];
331 i.handleImageUpload(i, image);
335 handleImageUpload(i: CommentForm, event: any) {
338 event.preventDefault();
339 file = event.target.files[0];
344 const imageUploadUrl = `/pictrs/image`;
345 const formData = new FormData();
346 formData.append('images[]', file);
348 i.state.imageLoading = true;
351 fetch(imageUploadUrl, {
355 .then(res => res.json())
357 console.log('pictrs upload:');
359 if (res.msg == 'ok') {
360 let hash = res.files[0].file;
361 let url = `${window.location.origin}/pictrs/image/${hash}`;
362 let deleteToken = res.files[0].delete_token;
363 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
364 let imageMarkdown = `![](${url})`;
365 let content = i.state.commentForm.content;
366 content = content ? `${content}\n${imageMarkdown}` : imageMarkdown;
367 i.state.commentForm.content = content;
368 i.state.imageLoading = false;
370 let textarea: any = document.getElementById(i.id);
371 autosize.update(textarea);
373 i18n.t('click_to_delete_picture'),
374 i18n.t('picture_deleted'),
378 i.state.imageLoading = false;
380 toast(JSON.stringify(res), 'danger');
384 i.state.imageLoading = false;
386 toast(error, 'danger');
390 parseMessage(msg: WebSocketJsonResponse) {
391 let res = wsJsonToRes(msg);
393 // Only do the showing and hiding if logged in
394 if (UserService.Instance.user) {
395 if (res.op == UserOperation.CreateComment) {
396 let data = res.data as CommentResponse;
397 this.handleFinished(res.op, data);
398 } else if (res.op == UserOperation.EditComment) {
399 let data = res.data as CommentResponse;
400 this.handleFinished(res.op, data);