1 import { Component, linkEvent } from 'inferno';
2 import { PostListings } from './post-listings';
3 import { Subscription } from 'rxjs';
4 import { retryWhen, delay, take } from 'rxjs/operators';
12 ListCommunitiesResponse,
19 WebSocketJsonResponse,
20 } from '../interfaces';
21 import { WebSocketService, UserService } from '../services';
26 capitalizeFirstLetter,
37 import autosize from 'autosize';
38 import Tribute from 'tributejs/src/Tribute.js';
39 import Selectr from 'mobius1-selectr';
40 import { i18n } from '../i18next';
42 const MAX_POST_TITLE_LENGTH = 200;
44 interface PostFormProps {
45 post?: Post; // If a post is given, that means this is an edit
46 params?: PostFormParams;
48 onCreate?(id: number): any;
49 onEdit?(post: Post): any;
52 interface PostFormState {
54 communities: Array<Community>;
56 imageLoading: boolean;
58 suggestedTitle: string;
59 suggestedPosts: Array<Post>;
60 crossPosts: Array<Post>;
64 export class PostForm extends Component<PostFormProps, PostFormState> {
65 private id = `post-form-${randomStr()}`;
66 private tribute: Tribute;
67 private subscription: Subscription;
68 private emptyState: PostFormState = {
74 creator_id: UserService.Instance.user
75 ? UserService.Instance.user.id
82 suggestedTitle: undefined,
85 enable_nsfw: undefined,
88 constructor(props: any, context: any) {
89 super(props, context);
90 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts).bind(this);
91 this.fetchPageTitle = debounce(this.fetchPageTitle).bind(this);
93 this.tribute = setupTribute();
94 this.state = this.emptyState;
96 if (this.props.post) {
97 this.state.postForm = {
98 body: this.props.post.body,
99 // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
100 name: this.props.post.name,
101 community_id: this.props.post.community_id,
102 edit_id: this.props.post.id,
103 creator_id: this.props.post.creator_id,
104 url: this.props.post.url,
105 nsfw: this.props.post.nsfw,
110 if (this.props.params) {
111 this.state.postForm.name = this.props.params.name;
112 if (this.props.params.url) {
113 this.state.postForm.url = this.props.params.url;
115 if (this.props.params.body) {
116 this.state.postForm.body = this.props.params.body;
120 this.subscription = WebSocketService.Instance.subject
121 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
123 msg => this.parseMessage(msg),
124 err => console.error(err),
125 () => console.log('complete')
128 let listCommunitiesForm: ListCommunitiesForm = {
129 sort: SortType[SortType.TopAll],
133 WebSocketService.Instance.listCommunities(listCommunitiesForm);
134 WebSocketService.Instance.getSite();
137 componentDidMount() {
138 var textarea: any = document.getElementById(this.id);
140 this.tribute.attach(textarea);
141 textarea.addEventListener('tribute-replaced', () => {
142 this.state.postForm.body = textarea.value;
143 this.setState(this.state);
144 autosize.update(textarea);
149 componentWillUnmount() {
150 this.subscription.unsubscribe();
156 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
157 <div class="form-group row">
158 <label class="col-sm-2 col-form-label" htmlFor="post-url">
161 <div class="col-sm-10">
166 value={this.state.postForm.url}
167 onInput={linkEvent(this, this.handlePostUrlChange)}
168 onPaste={linkEvent(this, this.handleImageUploadPaste)}
170 {this.state.suggestedTitle && (
172 class="mt-1 text-muted small font-weight-bold pointer"
173 onClick={linkEvent(this, this.copySuggestedTitle)}
175 {i18n.t('copy_suggested_title', {
176 title: this.state.suggestedTitle,
182 htmlFor="file-upload"
183 className={`${UserService.Instance.user &&
184 'pointer'} d-inline-block float-right text-muted h6 font-weight-bold`}
185 data-tippy-content={i18n.t('upload_image')}
187 <svg class="icon icon-inline">
188 <use xlinkHref="#icon-image"></use>
194 accept="image/*,video/*"
197 disabled={!UserService.Instance.user}
198 onChange={linkEvent(this, this.handleImageUpload)}
201 {validURL(this.state.postForm.url) && (
203 href={`${archiveUrl}/?run=1&url=${encodeURIComponent(
204 this.state.postForm.url
207 class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
209 {i18n.t('archive_link')}
212 {this.state.imageLoading && (
213 <svg class="icon icon-spinner spin">
214 <use xlinkHref="#icon-spinner"></use>
217 {isImage(this.state.postForm.url) && (
218 <img src={this.state.postForm.url} class="img-fluid" />
220 {this.state.crossPosts.length > 0 && (
222 <div class="my-1 text-muted small font-weight-bold">
223 {i18n.t('cross_posts')}
225 <PostListings showCommunity posts={this.state.crossPosts} />
230 <div class="form-group row">
231 <label class="col-sm-2 col-form-label" htmlFor="post-title">
234 <div class="col-sm-10">
236 value={this.state.postForm.name}
238 onInput={linkEvent(this, this.handlePostNameChange)}
243 maxLength={MAX_POST_TITLE_LENGTH}
245 {this.state.suggestedPosts.length > 0 && (
247 <div class="my-1 text-muted small font-weight-bold">
248 {i18n.t('related_posts')}
250 <PostListings posts={this.state.suggestedPosts} />
256 <div class="form-group row">
257 <label class="col-sm-2 col-form-label" htmlFor={this.id}>
260 <div class="col-sm-10">
263 value={this.state.postForm.body}
264 onInput={linkEvent(this, this.handlePostBodyChange)}
265 className={`form-control ${this.state.previewMode && 'd-none'}`}
269 {this.state.previewMode && (
272 dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)}
275 {this.state.postForm.body && (
277 className={`mt-1 mr-2 btn btn-sm btn-secondary ${this.state
278 .previewMode && 'active'}`}
279 onClick={linkEvent(this, this.handlePreviewToggle)}
285 href={markdownHelpUrl}
287 class="d-inline-block float-right text-muted h6 font-weight-bold"
288 title={i18n.t('formatting_help')}
290 <svg class="icon icon-inline">
291 <use xlinkHref="#icon-help-circle"></use>
296 {!this.props.post && (
297 <div class="form-group row">
298 <label class="col-sm-2 col-form-label" htmlFor="post-community">
299 {i18n.t('community')}
301 <div class="col-sm-10">
305 value={this.state.postForm.community_id}
306 onInput={linkEvent(this, this.handlePostCommunityChange)}
308 {this.state.communities.map(community => (
309 <option value={community.id}>{community.name}</option>
315 {this.state.enable_nsfw && (
316 <div class="form-group row">
317 <div class="col-sm-10">
318 <div class="form-check">
320 class="form-check-input"
323 checked={this.state.postForm.nsfw}
324 onChange={linkEvent(this, this.handlePostNsfwChange)}
326 <label class="form-check-label" htmlFor="post-nsfw">
333 <div class="form-group row">
334 <div class="col-sm-10">
335 <button type="submit" class="btn btn-secondary mr-2">
336 {this.state.loading ? (
337 <svg class="icon icon-spinner spin">
338 <use xlinkHref="#icon-spinner"></use>
340 ) : this.props.post ? (
341 capitalizeFirstLetter(i18n.t('save'))
343 capitalizeFirstLetter(i18n.t('create'))
346 {this.props.post && (
349 class="btn btn-secondary"
350 onClick={linkEvent(this, this.handleCancel)}
362 handlePostSubmit(i: PostForm, event: any) {
363 event.preventDefault();
365 WebSocketService.Instance.editPost(i.state.postForm);
367 WebSocketService.Instance.createPost(i.state.postForm);
369 i.state.loading = true;
373 copySuggestedTitle(i: PostForm) {
374 i.state.postForm.name = i.state.suggestedTitle.substring(
376 MAX_POST_TITLE_LENGTH
378 i.state.suggestedTitle = undefined;
382 handlePostUrlChange(i: PostForm, event: any) {
383 i.state.postForm.url = event.target.value;
389 if (validURL(this.state.postForm.url)) {
390 let form: SearchForm = {
391 q: this.state.postForm.url,
392 type_: SearchType[SearchType.Url],
393 sort: SortType[SortType.TopAll],
398 WebSocketService.Instance.search(form);
400 // Fetch the page title
401 getPageTitle(this.state.postForm.url).then(d => {
402 this.state.suggestedTitle = d;
403 this.setState(this.state);
406 this.state.suggestedTitle = undefined;
407 this.state.crossPosts = [];
411 handlePostNameChange(i: PostForm, event: any) {
412 i.state.postForm.name = event.target.value;
414 i.fetchSimilarPosts();
417 fetchSimilarPosts() {
418 let form: SearchForm = {
419 q: this.state.postForm.name,
420 type_: SearchType[SearchType.Posts],
421 sort: SortType[SortType.TopAll],
422 community_id: this.state.postForm.community_id,
427 if (this.state.postForm.name !== '') {
428 WebSocketService.Instance.search(form);
430 this.state.suggestedPosts = [];
433 this.setState(this.state);
436 handlePostBodyChange(i: PostForm, event: any) {
437 i.state.postForm.body = event.target.value;
441 handlePostCommunityChange(i: PostForm, event: any) {
442 i.state.postForm.community_id = Number(event.target.value);
446 handlePostNsfwChange(i: PostForm, event: any) {
447 i.state.postForm.nsfw = event.target.checked;
451 handleCancel(i: PostForm) {
455 handlePreviewToggle(i: PostForm, event: any) {
456 event.preventDefault();
457 i.state.previewMode = !i.state.previewMode;
461 handleImageUploadPaste(i: PostForm, event: any) {
462 let image = event.clipboardData.files[0];
464 i.handleImageUpload(i, image);
468 handleImageUpload(i: PostForm, event: any) {
471 event.preventDefault();
472 file = event.target.files[0];
477 const imageUploadUrl = `/pictshare/api/upload.php`;
478 const formData = new FormData();
479 formData.append('file', file);
481 i.state.imageLoading = true;
484 fetch(imageUploadUrl, {
488 .then(res => res.json())
490 let url = `${window.location.origin}/pictshare/${res.url}`;
491 if (res.filetype == 'mp4') {
494 i.state.postForm.url = url;
495 i.state.imageLoading = false;
499 i.state.imageLoading = false;
501 toast(error, 'danger');
505 parseMessage(msg: WebSocketJsonResponse) {
506 let res = wsJsonToRes(msg);
508 toast(i18n.t(msg.error), 'danger');
509 this.state.loading = false;
510 this.setState(this.state);
512 } else if (res.op == UserOperation.ListCommunities) {
513 let data = res.data as ListCommunitiesResponse;
514 this.state.communities = data.communities;
515 if (this.props.post) {
516 this.state.postForm.community_id = this.props.post.community_id;
517 } else if (this.props.params && this.props.params.community) {
518 let foundCommunityId = data.communities.find(
519 r => r.name == this.props.params.community
521 this.state.postForm.community_id = foundCommunityId;
523 this.state.postForm.community_id = data.communities[0].id;
525 this.setState(this.state);
527 // Set up select searching
528 let selectId: any = document.getElementById('post-community');
530 let selector = new Selectr(selectId, { nativeDropdown: false });
531 selector.on('selectr.select', option => {
532 this.state.postForm.community_id = Number(option.value);
535 } else if (res.op == UserOperation.CreatePost) {
536 let data = res.data as PostResponse;
537 if (data.post.creator_id == UserService.Instance.user.id) {
538 this.state.loading = false;
539 this.props.onCreate(data.post.id);
541 } else if (res.op == UserOperation.EditPost) {
542 let data = res.data as PostResponse;
543 if (data.post.creator_id == UserService.Instance.user.id) {
544 this.state.loading = false;
545 this.props.onEdit(data.post);
547 } else if (res.op == UserOperation.Search) {
548 let data = res.data as SearchResponse;
550 if (data.type_ == SearchType[SearchType.Posts]) {
551 this.state.suggestedPosts = data.posts;
552 } else if (data.type_ == SearchType[SearchType.Url]) {
553 this.state.crossPosts = data.posts;
555 this.setState(this.state);
556 } else if (res.op == UserOperation.GetSite) {
557 let data = res.data as GetSiteResponse;
558 this.state.enable_nsfw = data.site.enable_nsfw;
559 this.setState(this.state);