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 Selectr from 'mobius1-selectr';
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 emptyState: PostFormState = {
78 creator_id: UserService.Instance.user
79 ? UserService.Instance.user.id
86 suggestedTitle: undefined,
91 constructor(props: any, context: any) {
92 super(props, context);
93 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts).bind(this);
94 this.fetchPageTitle = debounce(this.fetchPageTitle).bind(this);
96 this.tribute = setupTribute();
98 this.state = this.emptyState;
100 if (this.props.post) {
101 this.state.postForm = {
102 body: this.props.post.body,
103 // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
104 name: this.props.post.name,
105 community_id: this.props.post.community_id,
106 edit_id: this.props.post.id,
107 creator_id: this.props.post.creator_id,
108 url: this.props.post.url,
109 nsfw: this.props.post.nsfw,
114 if (this.props.params) {
115 this.state.postForm.name = this.props.params.name;
116 if (this.props.params.url) {
117 this.state.postForm.url = this.props.params.url;
119 if (this.props.params.body) {
120 this.state.postForm.body = this.props.params.body;
124 this.subscription = WebSocketService.Instance.subject
125 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
127 msg => this.parseMessage(msg),
128 err => console.error(err),
129 () => console.log('complete')
132 let listCommunitiesForm: ListCommunitiesForm = {
133 sort: SortType[SortType.TopAll],
137 WebSocketService.Instance.listCommunities(listCommunitiesForm);
140 componentDidMount() {
141 var textarea: any = document.getElementById(this.id);
143 this.tribute.attach(textarea);
144 textarea.addEventListener('tribute-replaced', () => {
145 this.state.postForm.body = textarea.value;
146 this.setState(this.state);
147 autosize.update(textarea);
152 componentDidUpdate() {
154 !this.state.loading &&
155 (this.state.postForm.name ||
156 this.state.postForm.url ||
157 this.state.postForm.body)
159 window.onbeforeunload = () => true;
161 window.onbeforeunload = undefined;
165 componentWillUnmount() {
166 this.subscription.unsubscribe();
167 window.onbeforeunload = null;
175 !this.state.loading &&
176 (this.state.postForm.name ||
177 this.state.postForm.url ||
178 this.state.postForm.body)
180 message={i18n.t('block_leaving')}
182 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
183 <div class="form-group row">
184 <label class="col-sm-2 col-form-label" htmlFor="post-url">
187 <div class="col-sm-10">
192 value={this.state.postForm.url}
193 onInput={linkEvent(this, this.handlePostUrlChange)}
194 onPaste={linkEvent(this, this.handleImageUploadPaste)}
196 {this.state.suggestedTitle && (
198 class="mt-1 text-muted small font-weight-bold pointer"
199 onClick={linkEvent(this, this.copySuggestedTitle)}
201 {i18n.t('copy_suggested_title', {
202 title: this.state.suggestedTitle,
208 htmlFor="file-upload"
210 UserService.Instance.user && 'pointer'
211 } d-inline-block float-right text-muted font-weight-bold`}
212 data-tippy-content={i18n.t('upload_image')}
214 <svg class="icon icon-inline">
215 <use xlinkHref="#icon-image"></use>
221 accept="image/*,video/*"
224 disabled={!UserService.Instance.user}
225 onChange={linkEvent(this, this.handleImageUpload)}
228 {validURL(this.state.postForm.url) && (
230 href={`${archiveUrl}/?run=1&url=${encodeURIComponent(
231 this.state.postForm.url
234 class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
237 {i18n.t('archive_link')}
240 {this.state.imageLoading && (
241 <svg class="icon icon-spinner spin">
242 <use xlinkHref="#icon-spinner"></use>
245 {isImage(this.state.postForm.url) && (
246 <img src={this.state.postForm.url} class="img-fluid" />
248 {this.state.crossPosts.length > 0 && (
250 <div class="my-1 text-muted small font-weight-bold">
251 {i18n.t('cross_posts')}
255 posts={this.state.crossPosts}
256 enableDownvotes={this.props.enableDownvotes}
257 enableNsfw={this.props.enableNsfw}
263 <div class="form-group row">
264 <label class="col-sm-2 col-form-label" htmlFor="post-title">
267 <div class="col-sm-10">
269 value={this.state.postForm.name}
271 onInput={linkEvent(this, this.handlePostNameChange)}
276 maxLength={MAX_POST_TITLE_LENGTH}
278 {this.state.suggestedPosts.length > 0 && (
280 <div class="my-1 text-muted small font-weight-bold">
281 {i18n.t('related_posts')}
284 posts={this.state.suggestedPosts}
285 enableDownvotes={this.props.enableDownvotes}
286 enableNsfw={this.props.enableNsfw}
293 <div class="form-group row">
294 <label class="col-sm-2 col-form-label" htmlFor={this.id}>
297 <div class="col-sm-10">
300 value={this.state.postForm.body}
301 onInput={linkEvent(this, this.handlePostBodyChange)}
302 className={`form-control ${this.state.previewMode && 'd-none'}`}
306 {this.state.previewMode && (
308 className="card card-body md-div"
309 dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)}
312 {this.state.postForm.body && (
314 className={`mt-1 mr-2 btn btn-sm btn-secondary ${
315 this.state.previewMode && 'active'
317 onClick={linkEvent(this, this.handlePreviewToggle)}
323 href={markdownHelpUrl}
326 class="d-inline-block float-right text-muted font-weight-bold"
327 title={i18n.t('formatting_help')}
329 <svg class="icon icon-inline">
330 <use xlinkHref="#icon-help-circle"></use>
335 {!this.props.post && (
336 <div class="form-group row">
337 <label class="col-sm-2 col-form-label" htmlFor="post-community">
338 {i18n.t('community')}
340 <div class="col-sm-10">
344 value={this.state.postForm.community_id}
345 onInput={linkEvent(this, this.handlePostCommunityChange)}
347 <option>{i18n.t('select_a_community')}</option>
348 {this.state.communities.map(community => (
349 <option value={community.id}>
352 : `${hostname(community.actor_id)}/${community.name}`}
359 {this.props.enableNsfw && (
360 <div class="form-group row">
361 <div class="col-sm-10">
362 <div class="form-check">
364 class="form-check-input"
367 checked={this.state.postForm.nsfw}
368 onChange={linkEvent(this, this.handlePostNsfwChange)}
370 <label class="form-check-label" htmlFor="post-nsfw">
377 <div class="form-group row">
378 <div class="col-sm-10">
381 !this.state.postForm.community_id || this.state.loading
384 class="btn btn-secondary mr-2"
386 {this.state.loading ? (
387 <svg class="icon icon-spinner spin">
388 <use xlinkHref="#icon-spinner"></use>
390 ) : this.props.post ? (
391 capitalizeFirstLetter(i18n.t('save'))
393 capitalizeFirstLetter(i18n.t('create'))
396 {this.props.post && (
399 class="btn btn-secondary"
400 onClick={linkEvent(this, this.handleCancel)}
412 handlePostSubmit(i: PostForm, event: any) {
413 event.preventDefault();
415 // Coerce empty url string to undefined
416 if (i.state.postForm.url && i.state.postForm.url === '') {
417 i.state.postForm.url = undefined;
421 WebSocketService.Instance.editPost(i.state.postForm);
423 WebSocketService.Instance.createPost(i.state.postForm);
425 i.state.loading = true;
429 copySuggestedTitle(i: PostForm) {
430 i.state.postForm.name = i.state.suggestedTitle.substring(
432 MAX_POST_TITLE_LENGTH
434 i.state.suggestedTitle = undefined;
438 handlePostUrlChange(i: PostForm, event: any) {
439 i.state.postForm.url = event.target.value;
445 if (validURL(this.state.postForm.url)) {
446 let form: SearchForm = {
447 q: this.state.postForm.url,
448 type_: SearchType[SearchType.Url],
449 sort: SortType[SortType.TopAll],
454 WebSocketService.Instance.search(form);
456 // Fetch the page title
457 getPageTitle(this.state.postForm.url).then(d => {
458 this.state.suggestedTitle = d;
459 this.setState(this.state);
462 this.state.suggestedTitle = undefined;
463 this.state.crossPosts = [];
467 handlePostNameChange(i: PostForm, event: any) {
468 i.state.postForm.name = event.target.value;
470 i.fetchSimilarPosts();
473 fetchSimilarPosts() {
474 let form: SearchForm = {
475 q: this.state.postForm.name,
476 type_: SearchType[SearchType.Posts],
477 sort: SortType[SortType.TopAll],
478 community_id: this.state.postForm.community_id,
483 if (this.state.postForm.name !== '') {
484 WebSocketService.Instance.search(form);
486 this.state.suggestedPosts = [];
489 this.setState(this.state);
492 handlePostBodyChange(i: PostForm, event: any) {
493 i.state.postForm.body = event.target.value;
497 handlePostCommunityChange(i: PostForm, event: any) {
498 i.state.postForm.community_id = Number(event.target.value);
502 handlePostNsfwChange(i: PostForm, event: any) {
503 i.state.postForm.nsfw = event.target.checked;
507 handleCancel(i: PostForm) {
511 handlePreviewToggle(i: PostForm, event: any) {
512 event.preventDefault();
513 i.state.previewMode = !i.state.previewMode;
517 handleImageUploadPaste(i: PostForm, event: any) {
518 let image = event.clipboardData.files[0];
520 i.handleImageUpload(i, image);
524 handleImageUpload(i: PostForm, event: any) {
527 event.preventDefault();
528 file = event.target.files[0];
533 const imageUploadUrl = `/pictrs/image`;
534 const formData = new FormData();
535 formData.append('images[]', file);
537 i.state.imageLoading = true;
540 fetch(imageUploadUrl, {
544 .then(res => res.json())
546 console.log('pictrs upload:');
548 if (res.msg == 'ok') {
549 let hash = res.files[0].file;
550 let url = `${window.location.origin}/pictrs/image/${hash}`;
551 let deleteToken = res.files[0].delete_token;
552 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
553 i.state.postForm.url = url;
554 i.state.imageLoading = false;
557 i18n.t('click_to_delete_picture'),
558 i18n.t('picture_deleted'),
562 i.state.imageLoading = false;
564 toast(JSON.stringify(res), 'danger');
568 i.state.imageLoading = false;
570 toast(error, 'danger');
574 parseMessage(msg: WebSocketJsonResponse) {
575 let res = wsJsonToRes(msg);
577 toast(i18n.t(msg.error), 'danger');
578 this.state.loading = false;
579 this.setState(this.state);
581 } else if (res.op == UserOperation.ListCommunities) {
582 let data = res.data as ListCommunitiesResponse;
583 this.state.communities = data.communities;
584 if (this.props.post) {
585 this.state.postForm.community_id = this.props.post.community_id;
586 } else if (this.props.params && this.props.params.community) {
587 let foundCommunityId = data.communities.find(
588 r => r.name == this.props.params.community
590 this.state.postForm.community_id = foundCommunityId;
592 // By default, the null valued 'Select a Community'
594 this.setState(this.state);
596 // Set up select searching
597 let selectId: any = document.getElementById('post-community');
599 let selector = new Selectr(selectId, { nativeDropdown: false });
600 selector.on('selectr.select', option => {
601 this.state.postForm.community_id = Number(option.value);
602 this.setState(this.state);
605 } else if (res.op == UserOperation.CreatePost) {
606 let data = res.data as PostResponse;
607 if (data.post.creator_id == UserService.Instance.user.id) {
608 this.state.loading = false;
609 this.props.onCreate(data.post.id);
611 } else if (res.op == UserOperation.EditPost) {
612 let data = res.data as PostResponse;
613 if (data.post.creator_id == UserService.Instance.user.id) {
614 this.state.loading = false;
615 this.props.onEdit(data.post);
617 } else if (res.op == UserOperation.Search) {
618 let data = res.data as SearchResponse;
620 if (data.type_ == SearchType[SearchType.Posts]) {
621 this.state.suggestedPosts = data.posts;
622 } else if (data.type_ == SearchType[SearchType.Url]) {
623 this.state.crossPosts = data.posts;
625 this.setState(this.state);