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,
36 import autosize from 'autosize';
37 import Tribute from 'tributejs/src/Tribute.js';
38 import { i18n } from '../i18next';
39 import { T } from 'inferno-i18next';
41 interface PostFormProps {
42 post?: Post; // If a post is given, that means this is an edit
43 params?: PostFormParams;
45 onCreate?(id: number): any;
46 onEdit?(post: Post): any;
49 interface PostFormState {
51 communities: Array<Community>;
53 imageLoading: boolean;
55 suggestedTitle: string;
56 suggestedPosts: Array<Post>;
57 crossPosts: Array<Post>;
61 export class PostForm extends Component<PostFormProps, PostFormState> {
62 private id = `post-form-${randomStr()}`;
63 private tribute: Tribute;
64 private subscription: Subscription;
65 private emptyState: PostFormState = {
71 creator_id: UserService.Instance.user
72 ? UserService.Instance.user.id
79 suggestedTitle: undefined,
82 enable_nsfw: undefined,
85 constructor(props: any, context: any) {
86 super(props, context);
87 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts).bind(this);
88 this.fetchPageTitle = debounce(this.fetchPageTitle).bind(this);
90 this.tribute = setupTribute();
91 this.state = this.emptyState;
93 if (this.props.post) {
94 this.state.postForm = {
95 body: this.props.post.body,
96 // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
97 name: this.props.post.name,
98 community_id: this.props.post.community_id,
99 edit_id: this.props.post.id,
100 creator_id: this.props.post.creator_id,
101 url: this.props.post.url,
102 nsfw: this.props.post.nsfw,
107 if (this.props.params) {
108 this.state.postForm.name = this.props.params.name;
109 if (this.props.params.url) {
110 this.state.postForm.url = this.props.params.url;
112 if (this.props.params.body) {
113 this.state.postForm.body = this.props.params.body;
117 this.subscription = WebSocketService.Instance.subject
118 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
120 msg => this.parseMessage(msg),
121 err => console.error(err),
122 () => console.log('complete')
125 let listCommunitiesForm: ListCommunitiesForm = {
126 sort: SortType[SortType.TopAll],
130 WebSocketService.Instance.listCommunities(listCommunitiesForm);
131 WebSocketService.Instance.getSite();
134 componentDidMount() {
135 var textarea: any = document.getElementById(this.id);
137 this.tribute.attach(textarea);
138 textarea.addEventListener('tribute-replaced', () => {
139 this.state.postForm.body = textarea.value;
140 this.setState(this.state);
141 autosize.update(textarea);
145 componentWillUnmount() {
146 this.subscription.unsubscribe();
152 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
153 <div class="form-group row">
154 <label class="col-sm-2 col-form-label" for="post-url">
157 <div class="col-sm-10">
162 value={this.state.postForm.url}
163 onInput={linkEvent(this, this.handlePostUrlChange)}
164 onPaste={linkEvent(this, this.handleImageUploadPaste)}
166 {this.state.suggestedTitle && (
168 class="mt-1 text-muted small font-weight-bold pointer"
169 onClick={linkEvent(this, this.copySuggestedTitle)}
172 i18nKey="copy_suggested_title"
173 interpolation={{ title: this.state.suggestedTitle }}
181 htmlFor="file-upload"
182 className={`${UserService.Instance.user &&
183 'pointer'} d-inline-block mr-2 float-right text-muted small font-weight-bold`}
185 { i18n.t('upload_image') }
190 accept="image/*,video/*"
193 disabled={!UserService.Instance.user}
194 onChange={linkEvent(this, this.handleImageUpload)}
197 {validURL(this.state.postForm.url) && (
199 href={`${archiveUrl}/?run=1&url=${encodeURIComponent(
200 this.state.postForm.url
203 class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
205 { i18n.t('archive_link') }
208 {this.state.imageLoading && (
209 <svg class="icon icon-spinner spin">
210 <use xlinkHref="#icon-spinner"></use>
213 {isImage(this.state.postForm.url) && (
214 <img src={this.state.postForm.url} class="img-fluid" />
216 {this.state.crossPosts.length > 0 && (
218 <div class="my-1 text-muted small font-weight-bold">
219 { i18n.t('cross_posts') }
221 <PostListings showCommunity posts={this.state.crossPosts} />
226 <div class="form-group row">
227 <label class="col-sm-2 col-form-label" for="post-title">
230 <div class="col-sm-10">
232 value={this.state.postForm.name}
234 onInput={linkEvent(this, this.handlePostNameChange)}
241 {this.state.suggestedPosts.length > 0 && (
243 <div class="my-1 text-muted small font-weight-bold">
244 { i18n.t('related_posts') }
246 <PostListings posts={this.state.suggestedPosts} />
252 <div class="form-group row">
253 <label class="col-sm-2 col-form-label" for="post-body">
256 <div class="col-sm-10">
259 value={this.state.postForm.body}
261 onInput={linkEvent(this, this.handlePostBodyChange)}
262 className={`form-control ${this.state.previewMode && 'd-none'}`}
266 {this.state.previewMode && (
269 dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)}
272 {this.state.postForm.body && (
274 className={`mt-1 mr-2 btn btn-sm btn-secondary ${this.state
275 .previewMode && 'active'}`}
276 onClick={linkEvent(this, this.handlePreviewToggle)}
278 { i18n.t('preview') }
282 href={markdownHelpUrl}
284 class="d-inline-block float-right text-muted small font-weight-bold"
286 { i18n.t('formatting_help') }
290 {!this.props.post && (
291 <div class="form-group row">
292 <label class="col-sm-2 col-form-label" for="post-community">
293 { i18n.t('community') }
295 <div class="col-sm-10">
299 value={this.state.postForm.community_id}
300 onInput={linkEvent(this, this.handlePostCommunityChange)}
302 {this.state.communities.map(community => (
303 <option value={community.id}>{community.name}</option>
309 {this.state.enable_nsfw && (
310 <div class="form-group row">
311 <div class="col-sm-10">
312 <div class="form-check">
314 class="form-check-input"
317 checked={this.state.postForm.nsfw}
318 onChange={linkEvent(this, this.handlePostNsfwChange)}
320 <label class="form-check-label" for="post-nsfw">
327 <div class="form-group row">
328 <div class="col-sm-10">
329 <button type="submit" class="btn btn-secondary mr-2">
330 {this.state.loading ? (
331 <svg class="icon icon-spinner spin">
332 <use xlinkHref="#icon-spinner"></use>
334 ) : this.props.post ? (
335 capitalizeFirstLetter(i18n.t('save'))
337 capitalizeFirstLetter(i18n.t('create'))
340 {this.props.post && (
343 class="btn btn-secondary"
344 onClick={linkEvent(this, this.handleCancel)}
356 handlePostSubmit(i: PostForm, event: any) {
357 event.preventDefault();
359 WebSocketService.Instance.editPost(i.state.postForm);
361 WebSocketService.Instance.createPost(i.state.postForm);
363 i.state.loading = true;
367 copySuggestedTitle(i: PostForm) {
368 i.state.postForm.name = i.state.suggestedTitle;
369 i.state.suggestedTitle = undefined;
373 handlePostUrlChange(i: PostForm, event: any) {
374 i.state.postForm.url = event.target.value;
380 if (validURL(this.state.postForm.url)) {
381 let form: SearchForm = {
382 q: this.state.postForm.url,
383 type_: SearchType[SearchType.Url],
384 sort: SortType[SortType.TopAll],
389 WebSocketService.Instance.search(form);
391 // Fetch the page title
392 getPageTitle(this.state.postForm.url).then(d => {
393 this.state.suggestedTitle = d;
394 this.setState(this.state);
397 this.state.suggestedTitle = undefined;
398 this.state.crossPosts = [];
402 handlePostNameChange(i: PostForm, event: any) {
403 i.state.postForm.name = event.target.value;
405 i.fetchSimilarPosts();
408 fetchSimilarPosts() {
409 let form: SearchForm = {
410 q: this.state.postForm.name,
411 type_: SearchType[SearchType.Posts],
412 sort: SortType[SortType.TopAll],
413 community_id: this.state.postForm.community_id,
418 if (this.state.postForm.name !== '') {
419 WebSocketService.Instance.search(form);
421 this.state.suggestedPosts = [];
424 this.setState(this.state);
427 handlePostBodyChange(i: PostForm, event: any) {
428 i.state.postForm.body = event.target.value;
432 handlePostCommunityChange(i: PostForm, event: any) {
433 i.state.postForm.community_id = Number(event.target.value);
437 handlePostNsfwChange(i: PostForm, event: any) {
438 i.state.postForm.nsfw = event.target.checked;
442 handleCancel(i: PostForm) {
446 handlePreviewToggle(i: PostForm, event: any) {
447 event.preventDefault();
448 i.state.previewMode = !i.state.previewMode;
452 handleImageUploadPaste(i: PostForm, event: any) {
453 let image = event.clipboardData.files[0];
455 i.handleImageUpload(i, image);
459 handleImageUpload(i: PostForm, event: any) {
462 event.preventDefault();
463 file = event.target.files[0];
468 const imageUploadUrl = `/pictshare/api/upload.php`;
469 const formData = new FormData();
470 formData.append('file', file);
472 i.state.imageLoading = true;
475 fetch(imageUploadUrl, {
479 .then(res => res.json())
481 let url = `${window.location.origin}/pictshare/${res.url}`;
482 if (res.filetype == 'mp4') {
485 i.state.postForm.url = url;
486 i.state.imageLoading = false;
490 i.state.imageLoading = false;
492 toast(error, 'danger');
496 parseMessage(msg: WebSocketJsonResponse) {
497 let res = wsJsonToRes(msg);
499 toast(i18n.t(msg.error), 'danger');
500 this.state.loading = false;
501 this.setState(this.state);
503 } else if (res.op == UserOperation.ListCommunities) {
504 let data = res.data as ListCommunitiesResponse;
505 this.state.communities = data.communities;
506 if (this.props.post) {
507 this.state.postForm.community_id = this.props.post.community_id;
508 } else if (this.props.params && this.props.params.community) {
509 let foundCommunityId = data.communities.find(
510 r => r.name == this.props.params.community
512 this.state.postForm.community_id = foundCommunityId;
514 this.state.postForm.community_id = data.communities[0].id;
516 this.setState(this.state);
517 } else if (res.op == UserOperation.CreatePost) {
518 let data = res.data as PostResponse;
519 this.state.loading = false;
520 this.props.onCreate(data.post.id);
521 } else if (res.op == UserOperation.EditPost) {
522 let data = res.data as PostResponse;
523 this.state.loading = false;
524 this.props.onEdit(data.post);
525 } else if (res.op == UserOperation.Search) {
526 let data = res.data as SearchResponse;
528 if (data.type_ == SearchType[SearchType.Posts]) {
529 this.state.suggestedPosts = data.posts;
530 } else if (data.type_ == SearchType[SearchType.Url]) {
531 this.state.crossPosts = data.posts;
533 this.setState(this.state);
534 } else if (res.op == UserOperation.GetSite) {
535 let data = res.data as GetSiteResponse;
536 this.state.enable_nsfw = data.site.enable_nsfw;
537 this.setState(this.state);