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,
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';
29 interface CommentFormProps {
32 onReplyCancel?(): any;
37 interface CommentFormState {
38 commentForm: CommentFormI;
42 imageLoading: boolean;
45 export class CommentForm extends Component<CommentFormProps, CommentFormState> {
46 private id = `comment-textarea-${randomStr()}`;
47 private formId = `comment-form-${randomStr()}`;
48 private tribute: Tribute;
49 private subscription: Subscription;
50 private emptyState: CommentFormState = {
54 post_id: this.props.node
55 ? this.props.node.comment.post_id
57 creator_id: UserService.Instance.user
58 ? UserService.Instance.user.id
61 buttonTitle: !this.props.node
62 ? capitalizeFirstLetter(i18n.t('post'))
64 ? capitalizeFirstLetter(i18n.t('save'))
65 : capitalizeFirstLetter(i18n.t('reply')),
71 constructor(props: any, context: any) {
72 super(props, context);
74 this.tribute = setupTribute();
75 this.setupEmojiPicker();
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 var textarea: any = document.getElementById(this.id);
103 this.tribute.attach(textarea);
104 textarea.addEventListener('tribute-replaced', () => {
105 this.state.commentForm.content = textarea.value;
106 this.setState(this.state);
107 autosize.update(textarea);
111 componentDidUpdate() {
112 if (this.state.commentForm.content) {
113 window.onbeforeunload = () => true;
115 window.onbeforeunload = undefined;
119 componentWillUnmount() {
120 this.subscription.unsubscribe();
121 window.onbeforeunload = null;
128 when={this.state.commentForm.content}
129 message={i18n.t('block_leaving')}
133 onSubmit={linkEvent(this, this.handleCommentSubmit)}
135 <div class="form-group row">
136 <div className={`col-sm-12`}>
139 className={`form-control ${this.state.previewMode && 'd-none'}`}
140 value={this.state.commentForm.content}
141 onInput={linkEvent(this, this.handleCommentContentChange)}
142 onPaste={linkEvent(this, this.handleImageUploadPaste)}
144 disabled={this.props.disabled}
148 {this.state.previewMode && (
150 className="card card-body md-div"
151 dangerouslySetInnerHTML={mdToHtml(
152 this.state.commentForm.content
159 <div class="col-sm-12">
162 class="btn btn-sm btn-secondary mr-2"
163 disabled={this.props.disabled || this.state.loading}
165 {this.state.loading ? (
166 <svg class="icon icon-spinner spin">
167 <use xlinkHref="#icon-spinner"></use>
170 <span>{this.state.buttonTitle}</span>
173 {this.state.commentForm.content && (
175 className={`btn btn-sm mr-2 btn-secondary ${
176 this.state.previewMode && 'active'
178 onClick={linkEvent(this, this.handlePreviewToggle)}
183 {this.props.node && (
186 class="btn btn-sm btn-secondary mr-2"
187 onClick={linkEvent(this, this.handleReplyCancel)}
193 href={markdownHelpUrl}
195 class="d-inline-block float-right text-muted font-weight-bold"
196 title={i18n.t('formatting_help')}
199 <svg class="icon icon-inline">
200 <use xlinkHref="#icon-help-circle"></use>
203 <form class="d-inline-block mr-3 float-right text-muted font-weight-bold">
205 htmlFor={`file-upload-${this.id}`}
206 className={`${UserService.Instance.user && 'pointer'}`}
207 data-tippy-content={i18n.t('upload_image')}
209 <svg class="icon icon-inline">
210 <use xlinkHref="#icon-image"></use>
214 id={`file-upload-${this.id}`}
216 accept="image/*,video/*"
219 disabled={!UserService.Instance.user}
220 onChange={linkEvent(this, this.handleImageUpload)}
223 {this.state.imageLoading && (
224 <svg class="icon icon-spinner spin">
225 <use xlinkHref="#icon-spinner"></use>
229 onClick={linkEvent(this, this.handleEmojiPickerClick)}
230 class="pointer unselectable d-inline-block mr-3 float-right text-muted font-weight-bold"
231 data-tippy-content={i18n.t('emoji_picker')}
233 <svg class="icon icon-inline">
234 <use xlinkHref="#icon-smile"></use>
245 emojiPicker.on('emoji', twemojiHtmlStr => {
246 if (this.state.commentForm.content == null) {
247 this.state.commentForm.content = '';
249 var el = document.createElement('div');
250 el.innerHTML = twemojiHtmlStr;
251 let nativeUnicode = (el.childNodes[0] as HTMLElement).getAttribute('alt');
252 let shortName = `:${emojiShortName[nativeUnicode]}:`;
253 this.state.commentForm.content += shortName;
254 this.setState(this.state);
258 handleFinished(op: UserOperation, data: CommentResponse) {
260 this.props.node !== undefined && data.comment.parent_id !== null;
262 +!(data.comment.parent_id !== null) ^ +(this.props.node !== undefined);
265 (data.comment.creator_id == UserService.Instance.user.id &&
266 ((op == UserOperation.CreateComment &&
267 // If its a reply, make sure parent child match
269 data.comment.parent_id == this.props.node.comment.id) ||
270 // Otherwise, check the XOR of the two
271 (!isReply && xor))) ||
272 // If its a comment edit, only check that its from your user, and that its a
275 (data.comment.creator_id == UserService.Instance.user.id &&
276 op == UserOperation.EditComment &&
277 data.comment.content)
279 this.state.previewMode = false;
280 this.state.loading = false;
281 this.state.commentForm.content = '';
282 this.setState(this.state);
283 let form: any = document.getElementById(this.formId);
285 if (this.props.node) {
286 this.props.onReplyCancel();
288 autosize.update(form);
289 this.setState(this.state);
293 handleCommentSubmit(i: CommentForm, event: any) {
294 event.preventDefault();
296 WebSocketService.Instance.editComment(i.state.commentForm);
298 WebSocketService.Instance.createComment(i.state.commentForm);
301 i.state.loading = true;
305 handleEmojiPickerClick(_i: CommentForm, event: any) {
306 emojiPicker.togglePicker(event.target);
309 handleCommentContentChange(i: CommentForm, event: any) {
310 i.state.commentForm.content = event.target.value;
314 handlePreviewToggle(i: CommentForm, event: any) {
315 event.preventDefault();
316 i.state.previewMode = !i.state.previewMode;
320 handleReplyCancel(i: CommentForm) {
321 i.props.onReplyCancel();
324 handleImageUploadPaste(i: CommentForm, event: any) {
325 let image = event.clipboardData.files[0];
327 i.handleImageUpload(i, image);
331 handleImageUpload(i: CommentForm, event: any) {
334 event.preventDefault();
335 file = event.target.files[0];
340 const imageUploadUrl = `/pictrs/image`;
341 const formData = new FormData();
342 formData.append('images[]', file);
344 i.state.imageLoading = true;
347 fetch(imageUploadUrl, {
351 .then(res => res.json())
353 console.log('pictrs upload:');
355 if (res.msg == 'ok') {
356 let hash = res.files[0].file;
357 let url = `${window.location.origin}/pictrs/image/${hash}`;
358 let deleteToken = res.files[0].delete_token;
359 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
360 let imageMarkdown = `![](${url})`;
361 let content = i.state.commentForm.content;
362 content = content ? `${content}\n${imageMarkdown}` : imageMarkdown;
363 i.state.commentForm.content = content;
364 i.state.imageLoading = false;
366 let textarea: any = document.getElementById(i.id);
367 autosize.update(textarea);
369 i18n.t('click_to_delete_picture'),
370 i18n.t('picture_deleted'),
374 i.state.imageLoading = false;
376 toast(JSON.stringify(res), 'danger');
380 i.state.imageLoading = false;
382 toast(error, 'danger');
386 parseMessage(msg: WebSocketJsonResponse) {
387 let res = wsJsonToRes(msg);
389 // Only do the showing and hiding if logged in
390 if (UserService.Instance.user) {
391 if (res.op == UserOperation.CreateComment) {
392 let data = res.data as CommentResponse;
393 this.handleFinished(res.op, data);
394 } else if (res.op == UserOperation.EditComment) {
395 let data = res.data as CommentResponse;
396 this.handleFinished(res.op, data);