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,
20 WebSocketJsonResponse,
21 } from '../interfaces';
22 import { WebSocketService, UserService } from '../services';
27 capitalizeFirstLetter,
41 import autosize from 'autosize';
42 import Tribute from 'tributejs/src/Tribute.js';
43 import emojiShortName from 'emoji-short-name';
44 import Selectr from 'mobius1-selectr';
45 import { i18n } from '../i18next';
47 const MAX_POST_TITLE_LENGTH = 200;
49 interface PostFormProps {
50 post?: Post; // If a post is given, that means this is an edit
51 params?: PostFormParams;
53 onCreate?(id: number): any;
54 onEdit?(post: Post): any;
57 interface PostFormState {
59 communities: Array<Community>;
61 imageLoading: boolean;
63 suggestedTitle: string;
64 suggestedPosts: Array<Post>;
65 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,
90 enable_nsfw: undefined,
93 constructor(props: any, context: any) {
94 super(props, context);
95 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts).bind(this);
96 this.fetchPageTitle = debounce(this.fetchPageTitle).bind(this);
98 this.tribute = setupTribute();
99 this.setupEmojiPicker();
101 this.state = this.emptyState;
103 if (this.props.post) {
104 this.state.postForm = {
105 body: this.props.post.body,
106 // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
107 name: this.props.post.name,
108 community_id: this.props.post.community_id,
109 edit_id: this.props.post.id,
110 creator_id: this.props.post.creator_id,
111 url: this.props.post.url,
112 nsfw: this.props.post.nsfw,
117 if (this.props.params) {
118 this.state.postForm.name = this.props.params.name;
119 if (this.props.params.url) {
120 this.state.postForm.url = this.props.params.url;
122 if (this.props.params.body) {
123 this.state.postForm.body = this.props.params.body;
127 this.subscription = WebSocketService.Instance.subject
128 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
130 msg => this.parseMessage(msg),
131 err => console.error(err),
132 () => console.log('complete')
135 let listCommunitiesForm: ListCommunitiesForm = {
136 sort: SortType[SortType.TopAll],
140 WebSocketService.Instance.listCommunities(listCommunitiesForm);
141 WebSocketService.Instance.getSite();
144 componentDidMount() {
145 var textarea: any = document.getElementById(this.id);
147 this.tribute.attach(textarea);
148 textarea.addEventListener('tribute-replaced', () => {
149 this.state.postForm.body = textarea.value;
150 this.setState(this.state);
151 autosize.update(textarea);
156 componentWillUnmount() {
157 this.subscription.unsubscribe();
165 !this.state.loading &&
166 (this.state.postForm.name ||
167 this.state.postForm.url ||
168 this.state.postForm.body)
170 message={i18n.t('block_leaving')}
172 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
173 <div class="form-group row">
174 <label class="col-sm-2 col-form-label" htmlFor="post-url">
177 <div class="col-sm-10">
182 value={this.state.postForm.url}
183 onInput={linkEvent(this, this.handlePostUrlChange)}
184 onPaste={linkEvent(this, this.handleImageUploadPaste)}
186 {this.state.suggestedTitle && (
188 class="mt-1 text-muted small font-weight-bold pointer"
189 onClick={linkEvent(this, this.copySuggestedTitle)}
191 {i18n.t('copy_suggested_title', {
192 title: this.state.suggestedTitle,
198 htmlFor="file-upload"
200 UserService.Instance.user && 'pointer'
201 } d-inline-block float-right text-muted font-weight-bold`}
202 data-tippy-content={i18n.t('upload_image')}
204 <svg class="icon icon-inline">
205 <use xlinkHref="#icon-image"></use>
211 accept="image/*,video/*"
214 disabled={!UserService.Instance.user}
215 onChange={linkEvent(this, this.handleImageUpload)}
218 {validURL(this.state.postForm.url) && (
220 href={`${archiveUrl}/?run=1&url=${encodeURIComponent(
221 this.state.postForm.url
224 class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
227 {i18n.t('archive_link')}
230 {this.state.imageLoading && (
231 <svg class="icon icon-spinner spin">
232 <use xlinkHref="#icon-spinner"></use>
235 {isImage(this.state.postForm.url) && (
236 <img src={this.state.postForm.url} class="img-fluid" />
238 {this.state.crossPosts.length > 0 && (
240 <div class="my-1 text-muted small font-weight-bold">
241 {i18n.t('cross_posts')}
243 <PostListings showCommunity posts={this.state.crossPosts} />
248 <div class="form-group row">
249 <label class="col-sm-2 col-form-label" htmlFor="post-title">
252 <div class="col-sm-10">
254 value={this.state.postForm.name}
256 onInput={linkEvent(this, this.handlePostNameChange)}
261 maxLength={MAX_POST_TITLE_LENGTH}
263 {this.state.suggestedPosts.length > 0 && (
265 <div class="my-1 text-muted small font-weight-bold">
266 {i18n.t('related_posts')}
268 <PostListings posts={this.state.suggestedPosts} />
274 <div class="form-group row">
275 <label class="col-sm-2 col-form-label" htmlFor={this.id}>
278 <div class="col-sm-10">
281 value={this.state.postForm.body}
282 onInput={linkEvent(this, this.handlePostBodyChange)}
283 className={`form-control ${this.state.previewMode && 'd-none'}`}
287 {this.state.previewMode && (
289 className="card card-body md-div"
290 dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)}
293 {this.state.postForm.body && (
295 className={`mt-1 mr-2 btn btn-sm btn-secondary ${
296 this.state.previewMode && 'active'
298 onClick={linkEvent(this, this.handlePreviewToggle)}
304 href={markdownHelpUrl}
307 class="d-inline-block float-right text-muted font-weight-bold"
308 title={i18n.t('formatting_help')}
310 <svg class="icon icon-inline">
311 <use xlinkHref="#icon-help-circle"></use>
315 onClick={linkEvent(this, this.handleEmojiPickerClick)}
316 class="pointer unselectable d-inline-block mr-3 float-right text-muted font-weight-bold"
317 data-tippy-content={i18n.t('emoji_picker')}
319 <svg class="icon icon-inline">
320 <use xlinkHref="#icon-smile"></use>
325 {!this.props.post && (
326 <div class="form-group row">
327 <label class="col-sm-2 col-form-label" htmlFor="post-community">
328 {i18n.t('community')}
330 <div class="col-sm-10">
334 value={this.state.postForm.community_id}
335 onInput={linkEvent(this, this.handlePostCommunityChange)}
337 <option>{i18n.t('select_a_community')}</option>
338 {this.state.communities.map(community => (
339 <option value={community.id}>
342 : `${hostname(community.actor_id)}/${community.name}`}
349 {this.state.enable_nsfw && (
350 <div class="form-group row">
351 <div class="col-sm-10">
352 <div class="form-check">
354 class="form-check-input"
357 checked={this.state.postForm.nsfw}
358 onChange={linkEvent(this, this.handlePostNsfwChange)}
360 <label class="form-check-label" htmlFor="post-nsfw">
367 <div class="form-group row">
368 <div class="col-sm-10">
371 !this.state.postForm.community_id || this.state.loading
374 class="btn btn-secondary mr-2"
376 {this.state.loading ? (
377 <svg class="icon icon-spinner spin">
378 <use xlinkHref="#icon-spinner"></use>
380 ) : this.props.post ? (
381 capitalizeFirstLetter(i18n.t('save'))
383 capitalizeFirstLetter(i18n.t('create'))
386 {this.props.post && (
389 class="btn btn-secondary"
390 onClick={linkEvent(this, this.handleCancel)}
403 emojiPicker.on('emoji', twemojiHtmlStr => {
404 if (this.state.postForm.body == null) {
405 this.state.postForm.body = '';
407 var el = document.createElement('div');
408 el.innerHTML = twemojiHtmlStr;
409 let nativeUnicode = (el.childNodes[0] as HTMLElement).getAttribute('alt');
410 let shortName = `:${emojiShortName[nativeUnicode]}:`;
411 this.state.postForm.body += shortName;
412 this.setState(this.state);
416 handlePostSubmit(i: PostForm, event: any) {
417 event.preventDefault();
419 // Coerce empty url string to undefined
420 if (i.state.postForm.url && i.state.postForm.url === '') {
421 i.state.postForm.url = undefined;
425 WebSocketService.Instance.editPost(i.state.postForm);
427 WebSocketService.Instance.createPost(i.state.postForm);
429 i.state.loading = true;
433 copySuggestedTitle(i: PostForm) {
434 i.state.postForm.name = i.state.suggestedTitle.substring(
436 MAX_POST_TITLE_LENGTH
438 i.state.suggestedTitle = undefined;
442 handlePostUrlChange(i: PostForm, event: any) {
443 i.state.postForm.url = event.target.value;
449 if (validURL(this.state.postForm.url)) {
450 let form: SearchForm = {
451 q: this.state.postForm.url,
452 type_: SearchType[SearchType.Url],
453 sort: SortType[SortType.TopAll],
458 WebSocketService.Instance.search(form);
460 // Fetch the page title
461 getPageTitle(this.state.postForm.url).then(d => {
462 this.state.suggestedTitle = d;
463 this.setState(this.state);
466 this.state.suggestedTitle = undefined;
467 this.state.crossPosts = [];
471 handlePostNameChange(i: PostForm, event: any) {
472 i.state.postForm.name = event.target.value;
474 i.fetchSimilarPosts();
477 fetchSimilarPosts() {
478 let form: SearchForm = {
479 q: this.state.postForm.name,
480 type_: SearchType[SearchType.Posts],
481 sort: SortType[SortType.TopAll],
482 community_id: this.state.postForm.community_id,
487 if (this.state.postForm.name !== '') {
488 WebSocketService.Instance.search(form);
490 this.state.suggestedPosts = [];
493 this.setState(this.state);
496 handlePostBodyChange(i: PostForm, event: any) {
497 i.state.postForm.body = event.target.value;
501 handlePostCommunityChange(i: PostForm, event: any) {
502 i.state.postForm.community_id = Number(event.target.value);
506 handlePostNsfwChange(i: PostForm, event: any) {
507 i.state.postForm.nsfw = event.target.checked;
511 handleCancel(i: PostForm) {
515 handlePreviewToggle(i: PostForm, event: any) {
516 event.preventDefault();
517 i.state.previewMode = !i.state.previewMode;
521 handleImageUploadPaste(i: PostForm, event: any) {
522 let image = event.clipboardData.files[0];
524 i.handleImageUpload(i, image);
528 handleImageUpload(i: PostForm, event: any) {
531 event.preventDefault();
532 file = event.target.files[0];
537 const imageUploadUrl = `/pictrs/image`;
538 const formData = new FormData();
539 formData.append('images[]', file);
541 i.state.imageLoading = true;
544 fetch(imageUploadUrl, {
548 .then(res => res.json())
550 console.log('pictrs upload:');
552 if (res.msg == 'ok') {
553 let hash = res.files[0].file;
554 let url = `${window.location.origin}/pictrs/image/${hash}`;
555 let deleteToken = res.files[0].delete_token;
556 let deleteUrl = `${window.location.origin}/pictrs/image/delete/${deleteToken}/${hash}`;
557 i.state.postForm.url = url;
558 i.state.imageLoading = false;
561 i18n.t('click_to_delete_picture'),
562 i18n.t('picture_deleted'),
566 i.state.imageLoading = false;
568 toast(JSON.stringify(res), 'danger');
572 i.state.imageLoading = false;
574 toast(error, 'danger');
578 handleEmojiPickerClick(_i: PostForm, event: any) {
579 emojiPicker.togglePicker(event.target);
582 parseMessage(msg: WebSocketJsonResponse) {
583 let res = wsJsonToRes(msg);
585 toast(i18n.t(msg.error), 'danger');
586 this.state.loading = false;
587 this.setState(this.state);
589 } else if (res.op == UserOperation.ListCommunities) {
590 let data = res.data as ListCommunitiesResponse;
591 this.state.communities = data.communities;
592 if (this.props.post) {
593 this.state.postForm.community_id = this.props.post.community_id;
594 } else if (this.props.params && this.props.params.community) {
595 let foundCommunityId = data.communities.find(
596 r => r.name == this.props.params.community
598 this.state.postForm.community_id = foundCommunityId;
600 // By default, the null valued 'Select a Community'
602 this.setState(this.state);
604 // Set up select searching
605 let selectId: any = document.getElementById('post-community');
607 let selector = new Selectr(selectId, { nativeDropdown: false });
608 selector.on('selectr.select', option => {
609 this.state.postForm.community_id = Number(option.value);
610 this.setState(this.state);
613 } else if (res.op == UserOperation.CreatePost) {
614 let data = res.data as PostResponse;
615 if (data.post.creator_id == UserService.Instance.user.id) {
616 this.state.loading = false;
617 this.props.onCreate(data.post.id);
619 } else if (res.op == UserOperation.EditPost) {
620 let data = res.data as PostResponse;
621 if (data.post.creator_id == UserService.Instance.user.id) {
622 this.state.loading = false;
623 this.props.onEdit(data.post);
625 } else if (res.op == UserOperation.Search) {
626 let data = res.data as SearchResponse;
628 if (data.type_ == SearchType[SearchType.Posts]) {
629 this.state.suggestedPosts = data.posts;
630 } else if (data.type_ == SearchType[SearchType.Url]) {
631 this.state.crossPosts = data.posts;
633 this.setState(this.state);
634 } else if (res.op == UserOperation.GetSite) {
635 let data = res.data as GetSiteResponse;
636 this.state.enable_nsfw = data.site.enable_nsfw;
637 this.setState(this.state);