1 import { Component, linkEvent } from 'inferno';
2 import { Prompt } from 'inferno-router';
3 import { PostListings } from './post-listings';
4 import { Subscription } from 'rxjs';
5 import { retryWhen, delay, take } from 'rxjs/operators';
13 ListCommunitiesResponse,
19 WebSocketJsonResponse,
20 } from '../interfaces';
21 import { WebSocketService, UserService } from '../services';
26 capitalizeFirstLetter,
39 import autosize from 'autosize';
40 import Tribute from 'tributejs/src/Tribute.js';
41 import emojiShortName from 'emoji-short-name';
42 import Choices from 'choices.js';
43 import { i18n } from '../i18next';
45 const MAX_POST_TITLE_LENGTH = 200;
47 interface PostFormProps {
48 post?: Post; // If a post is given, that means this is an edit
49 params?: PostFormParams;
51 onCreate?(id: number): any;
52 onEdit?(post: Post): any;
54 enableDownvotes: boolean;
57 interface PostFormState {
59 communities: Array<Community>;
61 imageLoading: boolean;
63 suggestedTitle: string;
64 suggestedPosts: Array<Post>;
65 crossPosts: Array<Post>;
68 export class PostForm extends Component<PostFormProps, PostFormState> {
69 private id = `post-form-${randomStr()}`;
70 private tribute: Tribute;
71 private subscription: Subscription;
72 private choices: Choices;
73 private emptyState: PostFormState = {
79 creator_id: UserService.Instance.user
80 ? UserService.Instance.user.id
87 suggestedTitle: undefined,
92 constructor(props: any, context: any) {
93 super(props, context);
94 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts).bind(this);
95 this.fetchPageTitle = debounce(this.fetchPageTitle).bind(this);
97 this.tribute = setupTribute();
99 this.state = this.emptyState;
101 if (this.props.post) {
102 this.state.postForm = {
103 body: this.props.post.body,
104 // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
105 name: this.props.post.name,
106 community_id: this.props.post.community_id,
107 edit_id: this.props.post.id,
108 creator_id: this.props.post.creator_id,
109 url: this.props.post.url,
110 nsfw: this.props.post.nsfw,
115 if (this.props.params) {
116 this.state.postForm.name = this.props.params.name;
117 if (this.props.params.url) {
118 this.state.postForm.url = this.props.params.url;
120 if (this.props.params.body) {
121 this.state.postForm.body = this.props.params.body;
125 this.subscription = WebSocketService.Instance.subject
126 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
128 msg => this.parseMessage(msg),
129 err => console.error(err),
130 () => console.log('complete')
133 let listCommunitiesForm: ListCommunitiesForm = {
134 sort: SortType[SortType.TopAll],
138 WebSocketService.Instance.listCommunities(listCommunitiesForm);
141 componentDidMount() {
142 var textarea: any = document.getElementById(this.id);
144 this.tribute.attach(textarea);
145 textarea.addEventListener('tribute-replaced', () => {
146 this.state.postForm.body = textarea.value;
147 this.setState(this.state);
148 autosize.update(textarea);
153 componentDidUpdate() {
155 !this.state.loading &&
156 (this.state.postForm.name ||
157 this.state.postForm.url ||
158 this.state.postForm.body)
160 window.onbeforeunload = () => true;
162 window.onbeforeunload = undefined;
166 componentWillUnmount() {
167 this.subscription.unsubscribe();
168 this.choices.destroy();
169 window.onbeforeunload = null;
177 !this.state.loading &&
178 (this.state.postForm.name ||
179 this.state.postForm.url ||
180 this.state.postForm.body)
182 message={i18n.t('block_leaving')}
184 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
185 <div class="form-group row">
186 <label class="col-sm-2 col-form-label" htmlFor="post-url">
189 <div class="col-sm-10">
194 value={this.state.postForm.url}
195 onInput={linkEvent(this, this.handlePostUrlChange)}
196 onPaste={linkEvent(this, this.handleImageUploadPaste)}
198 {this.state.suggestedTitle && (
200 class="mt-1 text-muted small font-weight-bold pointer"
201 onClick={linkEvent(this, this.copySuggestedTitle)}
203 {i18n.t('copy_suggested_title', {
204 title: this.state.suggestedTitle,
210 htmlFor="file-upload"
212 UserService.Instance.user && 'pointer'
213 } d-inline-block float-right text-muted font-weight-bold`}
214 data-tippy-content={i18n.t('upload_image')}
216 <svg class="icon icon-inline">
217 <use xlinkHref="#icon-image"></use>
223 accept="image/*,video/*"
226 disabled={!UserService.Instance.user}
227 onChange={linkEvent(this, this.handleImageUpload)}
230 {validURL(this.state.postForm.url) && (
232 href={`${archiveUrl}/?run=1&url=${encodeURIComponent(
233 this.state.postForm.url
236 class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
239 {i18n.t('archive_link')}
242 {this.state.imageLoading && (
243 <svg class="icon icon-spinner spin">
244 <use xlinkHref="#icon-spinner"></use>
247 {isImage(this.state.postForm.url) && (
248 <img src={this.state.postForm.url} class="img-fluid" />
250 {this.state.crossPosts.length > 0 && (
252 <div class="my-1 text-muted small font-weight-bold">
253 {i18n.t('cross_posts')}
257 posts={this.state.crossPosts}
258 enableDownvotes={this.props.enableDownvotes}
259 enableNsfw={this.props.enableNsfw}
265 <div class="form-group row">
266 <label class="col-sm-2 col-form-label" htmlFor="post-title">
269 <div class="col-sm-10">
271 value={this.state.postForm.name}
273 onInput={linkEvent(this, this.handlePostNameChange)}
278 maxLength={MAX_POST_TITLE_LENGTH}
280 {this.state.suggestedPosts.length > 0 && (
282 <div class="my-1 text-muted small font-weight-bold">
283 {i18n.t('related_posts')}
286 posts={this.state.suggestedPosts}
287 enableDownvotes={this.props.enableDownvotes}
288 enableNsfw={this.props.enableNsfw}
295 <div class="form-group row">
296 <label class="col-sm-2 col-form-label" htmlFor={this.id}>
299 <div class="col-sm-10">
302 value={this.state.postForm.body}
303 onInput={linkEvent(this, this.handlePostBodyChange)}
304 className={`form-control ${this.state.previewMode && 'd-none'}`}
308 {this.state.previewMode && (
310 className="card card-body md-div"
311 dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)}
314 {this.state.postForm.body && (
316 className={`mt-1 mr-2 btn btn-sm btn-secondary ${
317 this.state.previewMode && 'active'
319 onClick={linkEvent(this, this.handlePreviewToggle)}
325 href={markdownHelpUrl}
328 class="d-inline-block float-right text-muted font-weight-bold"
329 title={i18n.t('formatting_help')}
331 <svg class="icon icon-inline">
332 <use xlinkHref="#icon-help-circle"></use>
337 {!this.props.post && (
338 <div class="form-group row">
339 <label class="col-sm-2 col-form-label" htmlFor="post-community">
340 {i18n.t('community')}
342 <div class="col-sm-10">
346 value={this.state.postForm.community_id}
347 onInput={linkEvent(this, this.handlePostCommunityChange)}
349 <option>{i18n.t('select_a_community')}</option>
350 {this.state.communities.map(community => (
351 <option value={community.id}>
354 : `${hostname(community.actor_id)}/${community.name}`}
361 {this.props.enableNsfw && (
362 <div class="form-group row">
363 <div class="col-sm-10">
364 <div class="form-check">
366 class="form-check-input"
369 checked={this.state.postForm.nsfw}
370 onChange={linkEvent(this, this.handlePostNsfwChange)}
372 <label class="form-check-label" htmlFor="post-nsfw">
379 <div class="form-group row">
380 <div class="col-sm-10">
383 !this.state.postForm.community_id || this.state.loading
386 class="btn btn-secondary mr-2"
388 {this.state.loading ? (
389 <svg class="icon icon-spinner spin">
390 <use xlinkHref="#icon-spinner"></use>
392 ) : this.props.post ? (
393 capitalizeFirstLetter(i18n.t('save'))
395 capitalizeFirstLetter(i18n.t('create'))
398 {this.props.post && (
401 class="btn btn-secondary"
402 onClick={linkEvent(this, this.handleCancel)}
414 handlePostSubmit(i: PostForm, event: any) {
415 event.preventDefault();
417 // Coerce empty url string to undefined
418 if (i.state.postForm.url && i.state.postForm.url === '') {
419 i.state.postForm.url = undefined;
423 WebSocketService.Instance.editPost(i.state.postForm);
425 WebSocketService.Instance.createPost(i.state.postForm);
427 i.state.loading = true;
431 copySuggestedTitle(i: PostForm) {
432 i.state.postForm.name = i.state.suggestedTitle.substring(
434 MAX_POST_TITLE_LENGTH
436 i.state.suggestedTitle = undefined;
440 handlePostUrlChange(i: PostForm, event: any) {
441 i.state.postForm.url = event.target.value;
447 if (validURL(this.state.postForm.url)) {
448 let form: SearchForm = {
449 q: this.state.postForm.url,
450 type_: SearchType[SearchType.Url],
451 sort: SortType[SortType.TopAll],
456 WebSocketService.Instance.search(form);
458 // Fetch the page title
459 getPageTitle(this.state.postForm.url).then(d => {
460 this.state.suggestedTitle = d;
461 this.setState(this.state);
464 this.state.suggestedTitle = undefined;
465 this.state.crossPosts = [];
469 handlePostNameChange(i: PostForm, event: any) {
470 i.state.postForm.name = event.target.value;
472 i.fetchSimilarPosts();
475 fetchSimilarPosts() {
476 let form: SearchForm = {
477 q: this.state.postForm.name,
478 type_: SearchType[SearchType.Posts],
479 sort: SortType[SortType.TopAll],
480 community_id: this.state.postForm.community_id,
485 if (this.state.postForm.name !== '') {
486 WebSocketService.Instance.search(form);
488 this.state.suggestedPosts = [];
491 this.setState(this.state);
494 handlePostBodyChange(i: PostForm, event: any) {
495 i.state.postForm.body = event.target.value;
499 handlePostCommunityChange(i: PostForm, event: any) {
500 i.state.postForm.community_id = Number(event.target.value);
504 handlePostNsfwChange(i: PostForm, event: any) {
505 i.state.postForm.nsfw = event.target.checked;
509 handleCancel(i: PostForm) {
513 handlePreviewToggle(i: PostForm, event: any) {
514 event.preventDefault();
515 i.state.previewMode = !i.state.previewMode;
519 handleImageUploadPaste(i: PostForm, event: any) {
520 let image = event.clipboardData.files[0];
522 i.handleImageUpload(i, image);
526 handleImageUpload(i: PostForm, event: any) {
529 event.preventDefault();
530 file = event.target.files[0];
535 const imageUploadUrl = `/pictrs/image`;
536 const formData = new FormData();
537 formData.append('images[]', file);
539 i.state.imageLoading = true;
542 fetch(imageUploadUrl, {
546 .then(res => res.json())
548 console.log('pictrs upload:');
550 if (res.msg == 'ok') {
551 let hash = res.files[0].file;
552 let url = `${window.location.origin}/pictrs/image/${hash}`;
553 let deleteToken = res.files[0].delete_token;
554 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
555 i.state.postForm.url = url;
556 i.state.imageLoading = false;
559 i18n.t('click_to_delete_picture'),
560 i18n.t('picture_deleted'),
564 i.state.imageLoading = false;
566 toast(JSON.stringify(res), 'danger');
570 i.state.imageLoading = false;
572 toast(error, 'danger');
576 parseMessage(msg: WebSocketJsonResponse) {
577 let res = wsJsonToRes(msg);
579 toast(i18n.t(msg.error), 'danger');
580 this.state.loading = false;
581 this.setState(this.state);
583 } else if (res.op == UserOperation.ListCommunities) {
584 let data = res.data as ListCommunitiesResponse;
585 this.state.communities = data.communities;
586 if (this.props.post) {
587 this.state.postForm.community_id = this.props.post.community_id;
588 } else if (this.props.params && this.props.params.community) {
589 let foundCommunityId = data.communities.find(
590 r => r.name == this.props.params.community
592 this.state.postForm.community_id = foundCommunityId;
594 // By default, the null valued 'Select a Community'
596 this.setState(this.state);
598 // Set up select searching
599 let selectId: any = document.getElementById('post-community');
601 this.choices = new Choices(selectId, {
604 containerOuter: 'choices',
605 containerInner: 'choices__inner bg-secondary border-0',
606 input: 'form-control',
607 inputCloned: 'choices__input--cloned',
608 list: 'choices__list',
609 listItems: 'choices__list--multiple',
610 listSingle: 'choices__list--single',
611 listDropdown: 'choices__list--dropdown',
612 item: 'choices__item bg-secondary',
613 itemSelectable: 'choices__item--selectable',
614 itemDisabled: 'choices__item--disabled',
615 itemChoice: 'choices__item--choice',
616 placeholder: 'choices__placeholder',
617 group: 'choices__group',
618 groupHeading: 'choices__heading',
619 button: 'choices__button',
620 activeState: 'is-active',
621 focusState: 'is-focused',
622 openState: 'is-open',
623 disabledState: 'is-disabled',
624 highlightedState: 'text-info',
625 selectedState: 'text-info',
626 flippedState: 'is-flipped',
627 loadingState: 'is-loading',
628 noResults: 'has-no-results',
629 noChoices: 'has-no-choices',
632 this.choices.passedElement.element.addEventListener(
635 this.state.postForm.community_id = Number(e.detail.choice.value);
636 this.setState(this.state);
641 } else if (res.op == UserOperation.CreatePost) {
642 let data = res.data as PostResponse;
643 if (data.post.creator_id == UserService.Instance.user.id) {
644 this.state.loading = false;
645 this.props.onCreate(data.post.id);
647 } else if (res.op == UserOperation.EditPost) {
648 let data = res.data as PostResponse;
649 if (data.post.creator_id == UserService.Instance.user.id) {
650 this.state.loading = false;
651 this.props.onEdit(data.post);
653 } else if (res.op == UserOperation.Search) {
654 let data = res.data as SearchResponse;
656 if (data.type_ == SearchType[SearchType.Posts]) {
657 this.state.suggestedPosts = data.posts;
658 } else if (data.type_ == SearchType[SearchType.Url]) {
659 this.state.crossPosts = data.posts;
661 this.setState(this.state);