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,
40 import autosize from 'autosize';
41 import Tribute from 'tributejs/src/Tribute.js';
42 import emojiShortName from 'emoji-short-name';
43 import Selectr from 'mobius1-selectr';
44 import { i18n } from '../i18next';
46 const MAX_POST_TITLE_LENGTH = 200;
48 interface PostFormProps {
49 post?: Post; // If a post is given, that means this is an edit
50 params?: PostFormParams;
52 onCreate?(id: number): any;
53 onEdit?(post: Post): any;
55 enableDownvotes: boolean;
58 interface PostFormState {
60 communities: Array<Community>;
62 imageLoading: boolean;
64 suggestedTitle: string;
65 suggestedPosts: Array<Post>;
66 crossPosts: Array<Post>;
69 export class PostForm extends Component<PostFormProps, PostFormState> {
70 private id = `post-form-${randomStr()}`;
71 private tribute: Tribute;
72 private subscription: Subscription;
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();
98 this.setupEmojiPicker();
100 this.state = this.emptyState;
102 if (this.props.post) {
103 this.state.postForm = {
104 body: this.props.post.body,
105 // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
106 name: this.props.post.name,
107 community_id: this.props.post.community_id,
108 edit_id: this.props.post.id,
109 creator_id: this.props.post.creator_id,
110 url: this.props.post.url,
111 nsfw: this.props.post.nsfw,
116 if (this.props.params) {
117 this.state.postForm.name = this.props.params.name;
118 if (this.props.params.url) {
119 this.state.postForm.url = this.props.params.url;
121 if (this.props.params.body) {
122 this.state.postForm.body = this.props.params.body;
126 this.subscription = WebSocketService.Instance.subject
127 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
129 msg => this.parseMessage(msg),
130 err => console.error(err),
131 () => console.log('complete')
134 let listCommunitiesForm: ListCommunitiesForm = {
135 sort: SortType[SortType.TopAll],
139 WebSocketService.Instance.listCommunities(listCommunitiesForm);
142 componentDidMount() {
143 var textarea: any = document.getElementById(this.id);
145 this.tribute.attach(textarea);
146 textarea.addEventListener('tribute-replaced', () => {
147 this.state.postForm.body = textarea.value;
148 this.setState(this.state);
149 autosize.update(textarea);
154 componentDidUpdate() {
156 !this.state.loading &&
157 (this.state.postForm.name ||
158 this.state.postForm.url ||
159 this.state.postForm.body)
161 window.onbeforeunload = () => true;
163 window.onbeforeunload = undefined;
167 componentWillUnmount() {
168 this.subscription.unsubscribe();
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>
336 onClick={linkEvent(this, this.handleEmojiPickerClick)}
337 class="pointer unselectable d-inline-block mr-3 float-right text-muted font-weight-bold"
338 data-tippy-content={i18n.t('emoji_picker')}
340 <svg class="icon icon-inline">
341 <use xlinkHref="#icon-smile"></use>
346 {!this.props.post && (
347 <div class="form-group row">
348 <label class="col-sm-2 col-form-label" htmlFor="post-community">
349 {i18n.t('community')}
351 <div class="col-sm-10">
355 value={this.state.postForm.community_id}
356 onInput={linkEvent(this, this.handlePostCommunityChange)}
358 <option>{i18n.t('select_a_community')}</option>
359 {this.state.communities.map(community => (
360 <option value={community.id}>
363 : `${hostname(community.actor_id)}/${community.name}`}
370 {this.props.enableNsfw && (
371 <div class="form-group row">
372 <div class="col-sm-10">
373 <div class="form-check">
375 class="form-check-input"
378 checked={this.state.postForm.nsfw}
379 onChange={linkEvent(this, this.handlePostNsfwChange)}
381 <label class="form-check-label" htmlFor="post-nsfw">
388 <div class="form-group row">
389 <div class="col-sm-10">
392 !this.state.postForm.community_id || this.state.loading
395 class="btn btn-secondary mr-2"
397 {this.state.loading ? (
398 <svg class="icon icon-spinner spin">
399 <use xlinkHref="#icon-spinner"></use>
401 ) : this.props.post ? (
402 capitalizeFirstLetter(i18n.t('save'))
404 capitalizeFirstLetter(i18n.t('create'))
407 {this.props.post && (
410 class="btn btn-secondary"
411 onClick={linkEvent(this, this.handleCancel)}
424 emojiPicker.on('emoji', twemojiHtmlStr => {
425 if (this.state.postForm.body == null) {
426 this.state.postForm.body = '';
428 var el = document.createElement('div');
429 el.innerHTML = twemojiHtmlStr;
430 let nativeUnicode = (el.childNodes[0] as HTMLElement).getAttribute('alt');
431 let shortName = `:${emojiShortName[nativeUnicode]}:`;
432 this.state.postForm.body += shortName;
433 this.setState(this.state);
437 handlePostSubmit(i: PostForm, event: any) {
438 event.preventDefault();
440 // Coerce empty url string to undefined
441 if (i.state.postForm.url && i.state.postForm.url === '') {
442 i.state.postForm.url = undefined;
446 WebSocketService.Instance.editPost(i.state.postForm);
448 WebSocketService.Instance.createPost(i.state.postForm);
450 i.state.loading = true;
454 copySuggestedTitle(i: PostForm) {
455 i.state.postForm.name = i.state.suggestedTitle.substring(
457 MAX_POST_TITLE_LENGTH
459 i.state.suggestedTitle = undefined;
463 handlePostUrlChange(i: PostForm, event: any) {
464 i.state.postForm.url = event.target.value;
470 if (validURL(this.state.postForm.url)) {
471 let form: SearchForm = {
472 q: this.state.postForm.url,
473 type_: SearchType[SearchType.Url],
474 sort: SortType[SortType.TopAll],
479 WebSocketService.Instance.search(form);
481 // Fetch the page title
482 getPageTitle(this.state.postForm.url).then(d => {
483 this.state.suggestedTitle = d;
484 this.setState(this.state);
487 this.state.suggestedTitle = undefined;
488 this.state.crossPosts = [];
492 handlePostNameChange(i: PostForm, event: any) {
493 i.state.postForm.name = event.target.value;
495 i.fetchSimilarPosts();
498 fetchSimilarPosts() {
499 let form: SearchForm = {
500 q: this.state.postForm.name,
501 type_: SearchType[SearchType.Posts],
502 sort: SortType[SortType.TopAll],
503 community_id: this.state.postForm.community_id,
508 if (this.state.postForm.name !== '') {
509 WebSocketService.Instance.search(form);
511 this.state.suggestedPosts = [];
514 this.setState(this.state);
517 handlePostBodyChange(i: PostForm, event: any) {
518 i.state.postForm.body = event.target.value;
522 handlePostCommunityChange(i: PostForm, event: any) {
523 i.state.postForm.community_id = Number(event.target.value);
527 handlePostNsfwChange(i: PostForm, event: any) {
528 i.state.postForm.nsfw = event.target.checked;
532 handleCancel(i: PostForm) {
536 handlePreviewToggle(i: PostForm, event: any) {
537 event.preventDefault();
538 i.state.previewMode = !i.state.previewMode;
542 handleImageUploadPaste(i: PostForm, event: any) {
543 let image = event.clipboardData.files[0];
545 i.handleImageUpload(i, image);
549 handleImageUpload(i: PostForm, event: any) {
552 event.preventDefault();
553 file = event.target.files[0];
558 const imageUploadUrl = `/pictrs/image`;
559 const formData = new FormData();
560 formData.append('images[]', file);
562 i.state.imageLoading = true;
565 fetch(imageUploadUrl, {
569 .then(res => res.json())
571 console.log('pictrs upload:');
573 if (res.msg == 'ok') {
574 let hash = res.files[0].file;
575 let url = `${window.location.origin}/pictrs/image/${hash}`;
576 let deleteToken = res.files[0].delete_token;
577 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
578 i.state.postForm.url = url;
579 i.state.imageLoading = false;
582 i18n.t('click_to_delete_picture'),
583 i18n.t('picture_deleted'),
587 i.state.imageLoading = false;
589 toast(JSON.stringify(res), 'danger');
593 i.state.imageLoading = false;
595 toast(error, 'danger');
599 handleEmojiPickerClick(_i: PostForm, event: any) {
600 emojiPicker.togglePicker(event.target);
603 parseMessage(msg: WebSocketJsonResponse) {
604 let res = wsJsonToRes(msg);
606 toast(i18n.t(msg.error), 'danger');
607 this.state.loading = false;
608 this.setState(this.state);
610 } else if (res.op == UserOperation.ListCommunities) {
611 let data = res.data as ListCommunitiesResponse;
612 this.state.communities = data.communities;
613 if (this.props.post) {
614 this.state.postForm.community_id = this.props.post.community_id;
615 } else if (this.props.params && this.props.params.community) {
616 let foundCommunityId = data.communities.find(
617 r => r.name == this.props.params.community
619 this.state.postForm.community_id = foundCommunityId;
621 // By default, the null valued 'Select a Community'
623 this.setState(this.state);
625 // Set up select searching
626 let selectId: any = document.getElementById('post-community');
628 let selector = new Selectr(selectId, { nativeDropdown: false });
629 selector.on('selectr.select', option => {
630 this.state.postForm.community_id = Number(option.value);
631 this.setState(this.state);
634 } else if (res.op == UserOperation.CreatePost) {
635 let data = res.data as PostResponse;
636 if (data.post.creator_id == UserService.Instance.user.id) {
637 this.state.loading = false;
638 this.props.onCreate(data.post.id);
640 } else if (res.op == UserOperation.EditPost) {
641 let data = res.data as PostResponse;
642 if (data.post.creator_id == UserService.Instance.user.id) {
643 this.state.loading = false;
644 this.props.onEdit(data.post);
646 } else if (res.op == UserOperation.Search) {
647 let data = res.data as SearchResponse;
649 if (data.type_ == SearchType[SearchType.Posts]) {
650 this.state.suggestedPosts = data.posts;
651 } else if (data.type_ == SearchType[SearchType.Url]) {
652 this.state.crossPosts = data.posts;
654 this.setState(this.state);