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,
38 import autosize from 'autosize';
39 import Tribute from 'tributejs/src/Tribute.js';
40 import Selectr from 'mobius1-selectr';
41 import { i18n } from '../i18next';
43 const MAX_POST_TITLE_LENGTH = 200;
45 interface PostFormProps {
46 post?: Post; // If a post is given, that means this is an edit
47 params?: PostFormParams;
49 onCreate?(id: number): any;
50 onEdit?(post: Post): any;
53 interface PostFormState {
55 communities: Array<Community>;
57 imageLoading: boolean;
59 suggestedTitle: string;
60 suggestedPosts: Array<Post>;
61 crossPosts: Array<Post>;
65 export class PostForm extends Component<PostFormProps, PostFormState> {
66 private id = `post-form-${randomStr()}`;
67 private tribute: Tribute;
68 private subscription: Subscription;
69 private emptyState: PostFormState = {
75 creator_id: UserService.Instance.user
76 ? UserService.Instance.user.id
83 suggestedTitle: undefined,
86 enable_nsfw: undefined,
89 constructor(props: any, context: any) {
90 super(props, context);
91 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts).bind(this);
92 this.fetchPageTitle = debounce(this.fetchPageTitle).bind(this);
94 this.tribute = setupTribute();
95 this.state = this.emptyState;
97 if (this.props.post) {
98 this.state.postForm = {
99 body: this.props.post.body,
100 // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
101 name: this.props.post.name,
102 community_id: this.props.post.community_id,
103 edit_id: this.props.post.id,
104 creator_id: this.props.post.creator_id,
105 url: this.props.post.url,
106 nsfw: this.props.post.nsfw,
111 if (this.props.params) {
112 this.state.postForm.name = this.props.params.name;
113 if (this.props.params.url) {
114 this.state.postForm.url = this.props.params.url;
116 if (this.props.params.body) {
117 this.state.postForm.body = this.props.params.body;
121 this.subscription = WebSocketService.Instance.subject
122 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
124 msg => this.parseMessage(msg),
125 err => console.error(err),
126 () => console.log('complete')
129 let listCommunitiesForm: ListCommunitiesForm = {
130 sort: SortType[SortType.TopAll],
134 WebSocketService.Instance.listCommunities(listCommunitiesForm);
135 WebSocketService.Instance.getSite();
138 componentDidMount() {
139 var textarea: any = document.getElementById(this.id);
141 this.tribute.attach(textarea);
142 textarea.addEventListener('tribute-replaced', () => {
143 this.state.postForm.body = textarea.value;
144 this.setState(this.state);
145 autosize.update(textarea);
150 componentWillUnmount() {
151 this.subscription.unsubscribe();
159 !this.state.loading &&
160 (this.state.postForm.name ||
161 this.state.postForm.url ||
162 this.state.postForm.body)
164 message={i18n.t('block_leaving')}
166 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
167 <div class="form-group row">
168 <label class="col-sm-2 col-form-label" htmlFor="post-url">
171 <div class="col-sm-10">
176 value={this.state.postForm.url}
177 onInput={linkEvent(this, this.handlePostUrlChange)}
178 onPaste={linkEvent(this, this.handleImageUploadPaste)}
180 {this.state.suggestedTitle && (
182 class="mt-1 text-muted small font-weight-bold pointer"
183 onClick={linkEvent(this, this.copySuggestedTitle)}
185 {i18n.t('copy_suggested_title', {
186 title: this.state.suggestedTitle,
192 htmlFor="file-upload"
193 className={`${UserService.Instance.user &&
194 'pointer'} d-inline-block float-right text-muted h6 font-weight-bold`}
195 data-tippy-content={i18n.t('upload_image')}
197 <svg class="icon icon-inline">
198 <use xlinkHref="#icon-image"></use>
204 accept="image/*,video/*"
207 disabled={!UserService.Instance.user}
208 onChange={linkEvent(this, this.handleImageUpload)}
211 {validURL(this.state.postForm.url) && (
213 href={`${archiveUrl}/?run=1&url=${encodeURIComponent(
214 this.state.postForm.url
217 class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
219 {i18n.t('archive_link')}
222 {this.state.imageLoading && (
223 <svg class="icon icon-spinner spin">
224 <use xlinkHref="#icon-spinner"></use>
227 {isImage(this.state.postForm.url) && (
228 <img src={this.state.postForm.url} class="img-fluid" />
230 {this.state.crossPosts.length > 0 && (
232 <div class="my-1 text-muted small font-weight-bold">
233 {i18n.t('cross_posts')}
235 <PostListings showCommunity posts={this.state.crossPosts} />
240 <div class="form-group row">
241 <label class="col-sm-2 col-form-label" htmlFor="post-title">
244 <div class="col-sm-10">
246 value={this.state.postForm.name}
248 onInput={linkEvent(this, this.handlePostNameChange)}
253 maxLength={MAX_POST_TITLE_LENGTH}
255 {this.state.suggestedPosts.length > 0 && (
257 <div class="my-1 text-muted small font-weight-bold">
258 {i18n.t('related_posts')}
260 <PostListings posts={this.state.suggestedPosts} />
266 <div class="form-group row">
267 <label class="col-sm-2 col-form-label" htmlFor={this.id}>
270 <div class="col-sm-10">
273 value={this.state.postForm.body}
274 onInput={linkEvent(this, this.handlePostBodyChange)}
275 className={`form-control ${this.state.previewMode && 'd-none'}`}
279 {this.state.previewMode && (
282 dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)}
285 {this.state.postForm.body && (
287 className={`mt-1 mr-2 btn btn-sm btn-secondary ${this.state
288 .previewMode && 'active'}`}
289 onClick={linkEvent(this, this.handlePreviewToggle)}
295 href={markdownHelpUrl}
297 class="d-inline-block float-right text-muted h6 font-weight-bold"
298 title={i18n.t('formatting_help')}
300 <svg class="icon icon-inline">
301 <use xlinkHref="#icon-help-circle"></use>
306 {!this.props.post && (
307 <div class="form-group row">
308 <label class="col-sm-2 col-form-label" htmlFor="post-community">
309 {i18n.t('community')}
311 <div class="col-sm-10">
315 value={this.state.postForm.community_id}
316 onInput={linkEvent(this, this.handlePostCommunityChange)}
318 {this.state.communities.map(community => (
319 <option value={community.id}>{community.name}</option>
325 {this.state.enable_nsfw && (
326 <div class="form-group row">
327 <div class="col-sm-10">
328 <div class="form-check">
330 class="form-check-input"
333 checked={this.state.postForm.nsfw}
334 onChange={linkEvent(this, this.handlePostNsfwChange)}
336 <label class="form-check-label" htmlFor="post-nsfw">
343 <div class="form-group row">
344 <div class="col-sm-10">
345 <button type="submit" class="btn btn-secondary mr-2">
346 {this.state.loading ? (
347 <svg class="icon icon-spinner spin">
348 <use xlinkHref="#icon-spinner"></use>
350 ) : this.props.post ? (
351 capitalizeFirstLetter(i18n.t('save'))
353 capitalizeFirstLetter(i18n.t('create'))
356 {this.props.post && (
359 class="btn btn-secondary"
360 onClick={linkEvent(this, this.handleCancel)}
372 handlePostSubmit(i: PostForm, event: any) {
373 event.preventDefault();
375 WebSocketService.Instance.editPost(i.state.postForm);
377 WebSocketService.Instance.createPost(i.state.postForm);
379 i.state.loading = true;
383 copySuggestedTitle(i: PostForm) {
384 i.state.postForm.name = i.state.suggestedTitle.substring(
386 MAX_POST_TITLE_LENGTH
388 i.state.suggestedTitle = undefined;
392 handlePostUrlChange(i: PostForm, event: any) {
393 i.state.postForm.url = event.target.value;
399 if (validURL(this.state.postForm.url)) {
400 let form: SearchForm = {
401 q: this.state.postForm.url,
402 type_: SearchType[SearchType.Url],
403 sort: SortType[SortType.TopAll],
408 WebSocketService.Instance.search(form);
410 // Fetch the page title
411 getPageTitle(this.state.postForm.url).then(d => {
412 this.state.suggestedTitle = d;
413 this.setState(this.state);
416 this.state.suggestedTitle = undefined;
417 this.state.crossPosts = [];
421 handlePostNameChange(i: PostForm, event: any) {
422 i.state.postForm.name = event.target.value;
424 i.fetchSimilarPosts();
427 fetchSimilarPosts() {
428 let form: SearchForm = {
429 q: this.state.postForm.name,
430 type_: SearchType[SearchType.Posts],
431 sort: SortType[SortType.TopAll],
432 community_id: this.state.postForm.community_id,
437 if (this.state.postForm.name !== '') {
438 WebSocketService.Instance.search(form);
440 this.state.suggestedPosts = [];
443 this.setState(this.state);
446 handlePostBodyChange(i: PostForm, event: any) {
447 i.state.postForm.body = event.target.value;
451 handlePostCommunityChange(i: PostForm, event: any) {
452 i.state.postForm.community_id = Number(event.target.value);
456 handlePostNsfwChange(i: PostForm, event: any) {
457 i.state.postForm.nsfw = event.target.checked;
461 handleCancel(i: PostForm) {
465 handlePreviewToggle(i: PostForm, event: any) {
466 event.preventDefault();
467 i.state.previewMode = !i.state.previewMode;
471 handleImageUploadPaste(i: PostForm, event: any) {
472 let image = event.clipboardData.files[0];
474 i.handleImageUpload(i, image);
478 handleImageUpload(i: PostForm, event: any) {
481 event.preventDefault();
482 file = event.target.files[0];
487 const imageUploadUrl = `/pictshare/api/upload.php`;
488 const formData = new FormData();
489 formData.append('file', file);
491 i.state.imageLoading = true;
494 fetch(imageUploadUrl, {
498 .then(res => res.json())
500 let url = `${window.location.origin}/pictshare/${encodeURI(res.url)}`;
501 if (res.filetype == 'mp4') {
504 i.state.postForm.url = url;
505 i.state.imageLoading = false;
509 i.state.imageLoading = false;
511 toast(error, 'danger');
515 parseMessage(msg: WebSocketJsonResponse) {
516 let res = wsJsonToRes(msg);
518 toast(i18n.t(msg.error), 'danger');
519 this.state.loading = false;
520 this.setState(this.state);
522 } else if (res.op == UserOperation.ListCommunities) {
523 let data = res.data as ListCommunitiesResponse;
524 this.state.communities = data.communities;
525 if (this.props.post) {
526 this.state.postForm.community_id = this.props.post.community_id;
527 } else if (this.props.params && this.props.params.community) {
528 let foundCommunityId = data.communities.find(
529 r => r.name == this.props.params.community
531 this.state.postForm.community_id = foundCommunityId;
533 this.state.postForm.community_id = data.communities[0].id;
535 this.setState(this.state);
537 // Set up select searching
538 let selectId: any = document.getElementById('post-community');
540 let selector = new Selectr(selectId, { nativeDropdown: false });
541 selector.on('selectr.select', option => {
542 this.state.postForm.community_id = Number(option.value);
545 } else if (res.op == UserOperation.CreatePost) {
546 let data = res.data as PostResponse;
547 if (data.post.creator_id == UserService.Instance.user.id) {
548 this.state.loading = false;
549 this.props.onCreate(data.post.id);
551 } else if (res.op == UserOperation.EditPost) {
552 let data = res.data as PostResponse;
553 if (data.post.creator_id == UserService.Instance.user.id) {
554 this.state.loading = false;
555 this.props.onEdit(data.post);
557 } else if (res.op == UserOperation.Search) {
558 let data = res.data as SearchResponse;
560 if (data.type_ == SearchType[SearchType.Posts]) {
561 this.state.suggestedPosts = data.posts;
562 } else if (data.type_ == SearchType[SearchType.Url]) {
563 this.state.crossPosts = data.posts;
565 this.setState(this.state);
566 } else if (res.op == UserOperation.GetSite) {
567 let data = res.data as GetSiteResponse;
568 this.state.enable_nsfw = data.site.enable_nsfw;
569 this.setState(this.state);