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';
40 const MAX_POST_TITLE_LENGTH = 200;
42 interface PostFormProps {
43 post?: Post; // If a post is given, that means this is an edit
44 params?: PostFormParams;
46 onCreate?(id: number): any;
47 onEdit?(post: Post): any;
50 interface PostFormState {
52 communities: Array<Community>;
54 imageLoading: boolean;
56 suggestedTitle: string;
57 suggestedPosts: Array<Post>;
58 crossPosts: Array<Post>;
62 export class PostForm extends Component<PostFormProps, PostFormState> {
63 private id = `post-form-${randomStr()}`;
64 private tribute: Tribute;
65 private subscription: Subscription;
66 private emptyState: PostFormState = {
72 creator_id: UserService.Instance.user
73 ? UserService.Instance.user.id
80 suggestedTitle: undefined,
83 enable_nsfw: undefined,
86 constructor(props: any, context: any) {
87 super(props, context);
88 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts).bind(this);
89 this.fetchPageTitle = debounce(this.fetchPageTitle).bind(this);
91 this.tribute = setupTribute();
92 this.state = this.emptyState;
94 if (this.props.post) {
95 this.state.postForm = {
96 body: this.props.post.body,
97 // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
98 name: this.props.post.name,
99 community_id: this.props.post.community_id,
100 edit_id: this.props.post.id,
101 creator_id: this.props.post.creator_id,
102 url: this.props.post.url,
103 nsfw: this.props.post.nsfw,
108 if (this.props.params) {
109 this.state.postForm.name = this.props.params.name;
110 if (this.props.params.url) {
111 this.state.postForm.url = this.props.params.url;
113 if (this.props.params.body) {
114 this.state.postForm.body = this.props.params.body;
118 this.subscription = WebSocketService.Instance.subject
119 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
121 msg => this.parseMessage(msg),
122 err => console.error(err),
123 () => console.log('complete')
126 let listCommunitiesForm: ListCommunitiesForm = {
127 sort: SortType[SortType.TopAll],
131 WebSocketService.Instance.listCommunities(listCommunitiesForm);
132 WebSocketService.Instance.getSite();
135 componentDidMount() {
136 var textarea: any = document.getElementById(this.id);
138 this.tribute.attach(textarea);
139 textarea.addEventListener('tribute-replaced', () => {
140 this.state.postForm.body = textarea.value;
141 this.setState(this.state);
142 autosize.update(textarea);
146 componentWillUnmount() {
147 this.subscription.unsubscribe();
153 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
154 <div class="form-group row">
155 <label class="col-sm-2 col-form-label" htmlFor="post-url">
158 <div class="col-sm-10">
163 value={this.state.postForm.url}
164 onInput={linkEvent(this, this.handlePostUrlChange)}
165 onPaste={linkEvent(this, this.handleImageUploadPaste)}
167 {this.state.suggestedTitle && (
169 class="mt-1 text-muted small font-weight-bold pointer"
170 onClick={linkEvent(this, this.copySuggestedTitle)}
172 {i18n.t('copy_suggested_title', {
173 title: this.state.suggestedTitle,
179 htmlFor="file-upload"
180 className={`${UserService.Instance.user &&
181 'pointer'} d-inline-block mr-2 float-right text-muted small font-weight-bold`}
183 {i18n.t('upload_image')}
188 accept="image/*,video/*"
191 disabled={!UserService.Instance.user}
192 onChange={linkEvent(this, this.handleImageUpload)}
195 {validURL(this.state.postForm.url) && (
197 href={`${archiveUrl}/?run=1&url=${encodeURIComponent(
198 this.state.postForm.url
201 class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
203 {i18n.t('archive_link')}
206 {this.state.imageLoading && (
207 <svg class="icon icon-spinner spin">
208 <use xlinkHref="#icon-spinner"></use>
211 {isImage(this.state.postForm.url) && (
212 <img src={this.state.postForm.url} class="img-fluid" />
214 {this.state.crossPosts.length > 0 && (
216 <div class="my-1 text-muted small font-weight-bold">
217 {i18n.t('cross_posts')}
219 <PostListings showCommunity posts={this.state.crossPosts} />
224 <div class="form-group row">
225 <label class="col-sm-2 col-form-label" htmlFor="post-title">
228 <div class="col-sm-10">
230 value={this.state.postForm.name}
232 onInput={linkEvent(this, this.handlePostNameChange)}
237 maxLength={MAX_POST_TITLE_LENGTH}
239 {this.state.suggestedPosts.length > 0 && (
241 <div class="my-1 text-muted small font-weight-bold">
242 {i18n.t('related_posts')}
244 <PostListings posts={this.state.suggestedPosts} />
250 <div class="form-group row">
251 <label class="col-sm-2 col-form-label" htmlFor={this.id}>
254 <div class="col-sm-10">
257 value={this.state.postForm.body}
258 onInput={linkEvent(this, this.handlePostBodyChange)}
259 className={`form-control ${this.state.previewMode && 'd-none'}`}
263 {this.state.previewMode && (
266 dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)}
269 {this.state.postForm.body && (
271 className={`mt-1 mr-2 btn btn-sm btn-secondary ${this.state
272 .previewMode && 'active'}`}
273 onClick={linkEvent(this, this.handlePreviewToggle)}
279 href={markdownHelpUrl}
281 class="d-inline-block float-right text-muted small font-weight-bold"
283 {i18n.t('formatting_help')}
287 {!this.props.post && (
288 <div class="form-group row">
289 <label class="col-sm-2 col-form-label" htmlFor="post-community">
290 {i18n.t('community')}
292 <div class="col-sm-10">
296 value={this.state.postForm.community_id}
297 onInput={linkEvent(this, this.handlePostCommunityChange)}
299 {this.state.communities.map(community => (
300 <option value={community.id}>{community.name}</option>
306 {this.state.enable_nsfw && (
307 <div class="form-group row">
308 <div class="col-sm-10">
309 <div class="form-check">
311 class="form-check-input"
314 checked={this.state.postForm.nsfw}
315 onChange={linkEvent(this, this.handlePostNsfwChange)}
317 <label class="form-check-label" htmlFor="post-nsfw">
324 <div class="form-group row">
325 <div class="col-sm-10">
326 <button type="submit" class="btn btn-secondary mr-2">
327 {this.state.loading ? (
328 <svg class="icon icon-spinner spin">
329 <use xlinkHref="#icon-spinner"></use>
331 ) : this.props.post ? (
332 capitalizeFirstLetter(i18n.t('save'))
334 capitalizeFirstLetter(i18n.t('create'))
337 {this.props.post && (
340 class="btn btn-secondary"
341 onClick={linkEvent(this, this.handleCancel)}
353 handlePostSubmit(i: PostForm, event: any) {
354 event.preventDefault();
356 WebSocketService.Instance.editPost(i.state.postForm);
358 WebSocketService.Instance.createPost(i.state.postForm);
360 i.state.loading = true;
364 copySuggestedTitle(i: PostForm) {
365 i.state.postForm.name = i.state.suggestedTitle.substring(
367 MAX_POST_TITLE_LENGTH
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);