]> Untitled Git - lemmy-ui.git/blob - src/shared/components/post/post-form.tsx
f14eac739372092650d088ad11ab0e7c18218e06
[lemmy-ui.git] / src / shared / components / post / post-form.tsx
1 import {
2   communityToChoice,
3   fetchCommunities,
4   myAuth,
5   myAuthRequired,
6 } from "@utils/app";
7 import getUserInterfaceLangId from "@utils/app/user-interface-language";
8 import {
9   capitalizeFirstLetter,
10   debounce,
11   getIdFromString,
12   validTitle,
13   validURL,
14 } from "@utils/helpers";
15 import { isImage } from "@utils/media";
16 import { Choice } from "@utils/types";
17 import autosize from "autosize";
18 import { Component, InfernoNode, linkEvent } from "inferno";
19 import {
20   CommunityView,
21   CreatePost,
22   EditPost,
23   GetSiteMetadataResponse,
24   Language,
25   PostView,
26   SearchResponse,
27 } from "lemmy-js-client";
28 import {
29   archiveTodayUrl,
30   ghostArchiveUrl,
31   relTags,
32   trendingFetchLimit,
33   webArchiveUrl,
34 } from "../../config";
35 import { PostFormParams } from "../../interfaces";
36 import { I18NextService, UserService } from "../../services";
37 import { HttpService, RequestState } from "../../services/HttpService";
38 import { setupTippy } from "../../tippy";
39 import { toast } from "../../toast";
40 import { Icon, Spinner } from "../common/icon";
41 import { LanguageSelect } from "../common/language-select";
42 import { MarkdownTextArea } from "../common/markdown-textarea";
43 import NavigationPrompt from "../common/navigation-prompt";
44 import { SearchableSelect } from "../common/searchable-select";
45 import { PostListings } from "./post-listings";
46
47 const MAX_POST_TITLE_LENGTH = 200;
48
49 interface PostFormProps {
50   post_view?: PostView; // If a post is given, that means this is an edit
51   crossPosts?: PostView[];
52   allLanguages: Language[];
53   siteLanguages: number[];
54   params?: PostFormParams;
55   onCancel?(): void;
56   onCreate?(form: CreatePost): void;
57   onEdit?(form: EditPost): void;
58   enableNsfw?: boolean;
59   enableDownvotes?: boolean;
60   selectedCommunityChoice?: Choice;
61   onSelectCommunity?: (choice: Choice) => void;
62   initialCommunities?: CommunityView[];
63 }
64
65 interface PostFormState {
66   form: {
67     name?: string;
68     url?: string;
69     body?: string;
70     nsfw?: boolean;
71     language_id?: number;
72     community_id?: number;
73     honeypot?: string;
74   };
75   loading: boolean;
76   suggestedPostsRes: RequestState<SearchResponse>;
77   metadataRes: RequestState<GetSiteMetadataResponse>;
78   imageLoading: boolean;
79   imageDeleteUrl: string;
80   communitySearchLoading: boolean;
81   communitySearchOptions: Choice[];
82   previewMode: boolean;
83   submitted: boolean;
84 }
85
86 function handlePostSubmit(i: PostForm, event: any) {
87   event.preventDefault();
88   // Coerce empty url string to undefined
89   if ((i.state.form.url ?? "") === "") {
90     i.setState(s => ((s.form.url = undefined), s));
91   }
92   i.setState({ loading: true, submitted: true });
93   const auth = myAuthRequired();
94
95   const pForm = i.state.form;
96   const pv = i.props.post_view;
97
98   if (pv) {
99     i.props.onEdit?.({
100       name: pForm.name,
101       url: pForm.url,
102       body: pForm.body,
103       nsfw: pForm.nsfw,
104       post_id: pv.post.id,
105       language_id: pForm.language_id,
106       auth,
107     });
108   } else if (pForm.name && pForm.community_id) {
109     i.props.onCreate?.({
110       name: pForm.name,
111       community_id: pForm.community_id,
112       url: pForm.url,
113       body: pForm.body,
114       nsfw: pForm.nsfw,
115       language_id: pForm.language_id,
116       honeypot: pForm.honeypot,
117       auth,
118     });
119   }
120 }
121
122 function copySuggestedTitle(d: { i: PostForm; suggestedTitle?: string }) {
123   const sTitle = d.suggestedTitle;
124   if (sTitle) {
125     d.i.setState(
126       s => ((s.form.name = sTitle?.substring(0, MAX_POST_TITLE_LENGTH)), s)
127     );
128     d.i.setState({ suggestedPostsRes: { state: "empty" } });
129     setTimeout(() => {
130       const textarea: any = document.getElementById("post-title");
131       autosize.update(textarea);
132     }, 10);
133   }
134 }
135
136 function handlePostUrlChange(i: PostForm, event: any) {
137   const url = event.target.value;
138
139   i.setState(prev => ({
140     ...prev,
141     form: {
142       ...prev.form,
143       url,
144     },
145     imageDeleteUrl: "",
146   }));
147
148   i.fetchPageTitle();
149 }
150
151 function handlePostNsfwChange(i: PostForm, event: any) {
152   i.setState(s => ((s.form.nsfw = event.target.checked), s));
153 }
154
155 function handleHoneyPotChange(i: PostForm, event: any) {
156   i.setState(s => ((s.form.honeypot = event.target.value), s));
157 }
158
159 function handleCancel(i: PostForm) {
160   i.props.onCancel?.();
161 }
162
163 function handleImageUploadPaste(i: PostForm, event: any) {
164   const image = event.clipboardData.files[0];
165   if (image) {
166     handleImageUpload(i, image);
167   }
168 }
169
170 function handleImageUpload(i: PostForm, event: any) {
171   let file: any;
172   if (event.target) {
173     event.preventDefault();
174     file = event.target.files[0];
175   } else {
176     file = event;
177   }
178
179   i.setState({ imageLoading: true });
180
181   HttpService.client.uploadImage({ image: file }).then(res => {
182     console.log("pictrs upload:");
183     console.log(res);
184     if (res.state === "success") {
185       if (res.data.msg === "ok") {
186         i.state.form.url = res.data.url;
187         i.setState({
188           imageLoading: false,
189           imageDeleteUrl: res.data.delete_url as string,
190         });
191       } else {
192         toast(JSON.stringify(res), "danger");
193       }
194     } else if (res.state === "failed") {
195       console.error(res.msg);
196       toast(res.msg, "danger");
197       i.setState({ imageLoading: false });
198     }
199   });
200 }
201
202 function handlePostNameChange(i: PostForm, event: any) {
203   i.setState(s => ((s.form.name = event.target.value), s));
204   i.fetchSimilarPosts();
205 }
206
207 function handleImageDelete(i: PostForm) {
208   const { imageDeleteUrl } = i.state;
209
210   fetch(imageDeleteUrl);
211
212   i.setState(prev => ({
213     ...prev,
214     imageDeleteUrl: "",
215     imageLoading: false,
216     form: {
217       ...prev.form,
218       url: "",
219     },
220   }));
221 }
222
223 export class PostForm extends Component<PostFormProps, PostFormState> {
224   state: PostFormState = {
225     suggestedPostsRes: { state: "empty" },
226     metadataRes: { state: "empty" },
227     form: {},
228     loading: false,
229     imageLoading: false,
230     imageDeleteUrl: "",
231     communitySearchLoading: false,
232     previewMode: false,
233     communitySearchOptions: [],
234     submitted: false,
235   };
236
237   constructor(props: PostFormProps, context: any) {
238     super(props, context);
239     this.fetchSimilarPosts = debounce(this.fetchSimilarPosts.bind(this));
240     this.fetchPageTitle = debounce(this.fetchPageTitle.bind(this));
241     this.handlePostBodyChange = this.handlePostBodyChange.bind(this);
242     this.handleLanguageChange = this.handleLanguageChange.bind(this);
243     this.handleCommunitySelect = this.handleCommunitySelect.bind(this);
244
245     const { post_view, selectedCommunityChoice, params } = this.props;
246
247     // Means its an edit
248     if (post_view) {
249       this.state = {
250         ...this.state,
251         form: {
252           body: post_view.post.body,
253           name: post_view.post.name,
254           community_id: post_view.community.id,
255           url: post_view.post.url,
256           nsfw: post_view.post.nsfw,
257           language_id: post_view.post.language_id,
258         },
259       };
260     } else if (selectedCommunityChoice) {
261       this.state = {
262         ...this.state,
263         form: {
264           ...this.state.form,
265           community_id: getIdFromString(selectedCommunityChoice.value),
266         },
267         communitySearchOptions: [selectedCommunityChoice].concat(
268           (
269             this.props.initialCommunities?.map(
270               ({ community: { id, title } }) => ({
271                 label: title,
272                 value: id.toString(),
273               })
274             ) ?? []
275           ).filter(option => option.value !== selectedCommunityChoice.value)
276         ),
277       };
278     } else {
279       this.state = {
280         ...this.state,
281         communitySearchOptions:
282           this.props.initialCommunities?.map(
283             ({ community: { id, title } }) => ({
284               label: title,
285               value: id.toString(),
286             })
287           ) ?? [],
288       };
289     }
290
291     if (params) {
292       this.state = {
293         ...this.state,
294         form: {
295           ...this.state.form,
296           ...params,
297         },
298       };
299     }
300   }
301
302   componentDidMount() {
303     setupTippy();
304     const textarea: any = document.getElementById("post-title");
305
306     if (textarea) {
307       autosize(textarea);
308     }
309   }
310
311   componentWillReceiveProps(
312     nextProps: Readonly<{ children?: InfernoNode } & PostFormProps>
313   ): void {
314     if (this.props != nextProps) {
315       this.setState(
316         s => (
317           (s.form.community_id = getIdFromString(
318             nextProps.selectedCommunityChoice?.value
319           )),
320           s
321         )
322       );
323     }
324   }
325
326   render() {
327     const url = this.state.form.url;
328
329     const userInterfaceLangId = getUserInterfaceLangId({
330       myUserInfo: UserService.Instance.myUserInfo,
331       allLanguages: this.props.allLanguages,
332     });
333
334     return (
335       <form className="post-form" onSubmit={linkEvent(this, handlePostSubmit)}>
336         <NavigationPrompt
337           when={
338             !!(
339               this.state.form.name ||
340               this.state.form.url ||
341               this.state.form.body
342             ) && !this.state.submitted
343           }
344         />
345         <div className="mb-3 row">
346           <label className="col-sm-2 col-form-label" htmlFor="post-url">
347             {I18NextService.i18n.t("url")}
348           </label>
349           <div className="col-sm-10">
350             <input
351               type="url"
352               id="post-url"
353               className="form-control"
354               value={url}
355               onInput={linkEvent(this, handlePostUrlChange)}
356               onPaste={linkEvent(this, handleImageUploadPaste)}
357             />
358             {this.renderSuggestedTitleCopy()}
359             <form>
360               <label
361                 htmlFor="file-upload"
362                 className={`${
363                   UserService.Instance.myUserInfo && "pointer"
364                 } d-inline-block float-right text-muted font-weight-bold`}
365                 data-tippy-content={I18NextService.i18n.t("upload_image")}
366               >
367                 <Icon icon="image" classes="icon-inline" />
368               </label>
369               <input
370                 id="file-upload"
371                 type="file"
372                 accept="image/*,video/*"
373                 name="file"
374                 className="d-none"
375                 disabled={!UserService.Instance.myUserInfo}
376                 onChange={linkEvent(this, handleImageUpload)}
377               />
378             </form>
379             {url && validURL(url) && (
380               <div>
381                 <a
382                   href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
383                   className="me-2 d-inline-block float-right text-muted small font-weight-bold"
384                   rel={relTags}
385                 >
386                   archive.org {I18NextService.i18n.t("archive_link")}
387                 </a>
388                 <a
389                   href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
390                     url
391                   )}`}
392                   className="me-2 d-inline-block float-right text-muted small font-weight-bold"
393                   rel={relTags}
394                 >
395                   ghostarchive.org {I18NextService.i18n.t("archive_link")}
396                 </a>
397                 <a
398                   href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
399                     url
400                   )}`}
401                   className="me-2 d-inline-block float-right text-muted small font-weight-bold"
402                   rel={relTags}
403                 >
404                   archive.today {I18NextService.i18n.t("archive_link")}
405                 </a>
406               </div>
407             )}
408             {this.state.imageLoading && <Spinner />}
409             {url && isImage(url) && (
410               <img src={url} className="img-fluid" alt="" />
411             )}
412             {this.state.imageDeleteUrl && (
413               <button
414                 className="btn btn-danger btn-sm mt-2"
415                 onClick={linkEvent(this, handleImageDelete)}
416                 aria-label={I18NextService.i18n.t("delete")}
417                 data-tippy-content={I18NextService.i18n.t("delete")}
418               >
419                 <Icon icon="x" classes="icon-inline me-1" />
420                 {capitalizeFirstLetter(I18NextService.i18n.t("delete"))}
421               </button>
422             )}
423             {this.props.crossPosts && this.props.crossPosts.length > 0 && (
424               <>
425                 <div className="my-1 text-muted small font-weight-bold">
426                   {I18NextService.i18n.t("cross_posts")}
427                 </div>
428                 <PostListings
429                   showCommunity
430                   posts={this.props.crossPosts}
431                   enableDownvotes={this.props.enableDownvotes}
432                   enableNsfw={this.props.enableNsfw}
433                   allLanguages={this.props.allLanguages}
434                   siteLanguages={this.props.siteLanguages}
435                   viewOnly
436                   // All of these are unused, since its view only
437                   onPostEdit={() => {}}
438                   onPostVote={() => {}}
439                   onPostReport={() => {}}
440                   onBlockPerson={() => {}}
441                   onLockPost={() => {}}
442                   onDeletePost={() => {}}
443                   onRemovePost={() => {}}
444                   onSavePost={() => {}}
445                   onFeaturePost={() => {}}
446                   onPurgePerson={() => {}}
447                   onPurgePost={() => {}}
448                   onBanPersonFromCommunity={() => {}}
449                   onBanPerson={() => {}}
450                   onAddModToCommunity={() => {}}
451                   onAddAdmin={() => {}}
452                   onTransferCommunity={() => {}}
453                 />
454               </>
455             )}
456           </div>
457         </div>
458         <div className="mb-3 row">
459           <label className="col-sm-2 col-form-label" htmlFor="post-title">
460             {I18NextService.i18n.t("title")}
461           </label>
462           <div className="col-sm-10">
463             <textarea
464               value={this.state.form.name}
465               id="post-title"
466               onInput={linkEvent(this, handlePostNameChange)}
467               className={`form-control ${
468                 !validTitle(this.state.form.name) && "is-invalid"
469               }`}
470               required
471               rows={1}
472               minLength={3}
473               maxLength={MAX_POST_TITLE_LENGTH}
474             />
475             {!validTitle(this.state.form.name) && (
476               <div className="invalid-feedback">
477                 {I18NextService.i18n.t("invalid_post_title")}
478               </div>
479             )}
480             {this.renderSuggestedPosts()}
481           </div>
482         </div>
483
484         <div className="mb-3 row">
485           <label className="col-sm-2 col-form-label">
486             {I18NextService.i18n.t("body")}
487           </label>
488           <div className="col-sm-10">
489             <MarkdownTextArea
490               initialContent={this.state.form.body}
491               onContentChange={this.handlePostBodyChange}
492               allLanguages={this.props.allLanguages}
493               siteLanguages={this.props.siteLanguages}
494               hideNavigationWarnings
495             />
496           </div>
497         </div>
498         <LanguageSelect
499           allLanguages={this.props.allLanguages}
500           selectedLanguageIds={[userInterfaceLangId]}
501           siteLanguages={this.props.siteLanguages}
502           multiple={false}
503           onChange={this.handleLanguageChange}
504         />
505         {!this.props.post_view && (
506           <div className="mb-3 row">
507             <label className="col-sm-2 col-form-label" htmlFor="post-community">
508               {I18NextService.i18n.t("community")}
509             </label>
510             <div className="col-sm-10">
511               <SearchableSelect
512                 id="post-community"
513                 value={this.state.form.community_id}
514                 options={[
515                   {
516                     label: I18NextService.i18n.t("select_a_community"),
517                     value: "",
518                     disabled: true,
519                   } as Choice,
520                 ].concat(this.state.communitySearchOptions)}
521                 loading={this.state.communitySearchLoading}
522                 onChange={this.handleCommunitySelect}
523                 onSearch={this.handleCommunitySearch}
524               />
525             </div>
526           </div>
527         )}
528         {this.props.enableNsfw && (
529           <div className="form-check mb-3">
530             <input
531               className="form-check-input"
532               id="post-nsfw"
533               type="checkbox"
534               checked={this.state.form.nsfw}
535               onChange={linkEvent(this, handlePostNsfwChange)}
536             />
537             <label className="form-check-label">
538               {I18NextService.i18n.t("nsfw")}
539             </label>
540           </div>
541         )}
542         <input
543           tabIndex={-1}
544           autoComplete="false"
545           name="a_password"
546           type="text"
547           className="form-control honeypot"
548           id="register-honey"
549           value={this.state.form.honeypot}
550           onInput={linkEvent(this, handleHoneyPotChange)}
551         />
552         <div className="mb-3 row">
553           <div className="col-sm-10">
554             <button
555               disabled={!this.state.form.community_id || this.state.loading}
556               type="submit"
557               className="btn btn-secondary me-2"
558             >
559               {this.state.loading ? (
560                 <Spinner />
561               ) : this.props.post_view ? (
562                 capitalizeFirstLetter(I18NextService.i18n.t("save"))
563               ) : (
564                 capitalizeFirstLetter(I18NextService.i18n.t("create"))
565               )}
566             </button>
567             {this.props.post_view && (
568               <button
569                 type="button"
570                 className="btn btn-secondary"
571                 onClick={linkEvent(this, handleCancel)}
572               >
573                 {I18NextService.i18n.t("cancel")}
574               </button>
575             )}
576           </div>
577         </div>
578       </form>
579     );
580   }
581
582   renderSuggestedTitleCopy() {
583     switch (this.state.metadataRes.state) {
584       case "loading":
585         return <Spinner />;
586       case "success": {
587         const suggestedTitle = this.state.metadataRes.data.metadata.title;
588
589         return (
590           suggestedTitle && (
591             <div
592               className="mt-1 text-muted small font-weight-bold pointer"
593               role="button"
594               onClick={linkEvent(
595                 { i: this, suggestedTitle },
596                 copySuggestedTitle
597               )}
598             >
599               {I18NextService.i18n.t("copy_suggested_title", { title: "" })}{" "}
600               {suggestedTitle}
601             </div>
602           )
603         );
604       }
605     }
606   }
607
608   renderSuggestedPosts() {
609     switch (this.state.suggestedPostsRes.state) {
610       case "loading":
611         return <Spinner />;
612       case "success": {
613         const suggestedPosts = this.state.suggestedPostsRes.data.posts;
614
615         return (
616           suggestedPosts &&
617           suggestedPosts.length > 0 && (
618             <>
619               <div className="my-1 text-muted small font-weight-bold">
620                 {I18NextService.i18n.t("related_posts")}
621               </div>
622               <PostListings
623                 showCommunity
624                 posts={suggestedPosts}
625                 enableDownvotes={this.props.enableDownvotes}
626                 enableNsfw={this.props.enableNsfw}
627                 allLanguages={this.props.allLanguages}
628                 siteLanguages={this.props.siteLanguages}
629                 viewOnly
630                 // All of these are unused, since its view only
631                 onPostEdit={() => {}}
632                 onPostVote={() => {}}
633                 onPostReport={() => {}}
634                 onBlockPerson={() => {}}
635                 onLockPost={() => {}}
636                 onDeletePost={() => {}}
637                 onRemovePost={() => {}}
638                 onSavePost={() => {}}
639                 onFeaturePost={() => {}}
640                 onPurgePerson={() => {}}
641                 onPurgePost={() => {}}
642                 onBanPersonFromCommunity={() => {}}
643                 onBanPerson={() => {}}
644                 onAddModToCommunity={() => {}}
645                 onAddAdmin={() => {}}
646                 onTransferCommunity={() => {}}
647               />
648             </>
649           )
650         );
651       }
652     }
653   }
654
655   async fetchPageTitle() {
656     const url = this.state.form.url;
657     if (url && validURL(url)) {
658       this.setState({ metadataRes: { state: "loading" } });
659       this.setState({
660         metadataRes: await HttpService.client.getSiteMetadata({ url }),
661       });
662     }
663   }
664
665   async fetchSimilarPosts() {
666     const q = this.state.form.name;
667     if (q && q !== "") {
668       this.setState({ suggestedPostsRes: { state: "loading" } });
669       this.setState({
670         suggestedPostsRes: await HttpService.client.search({
671           q,
672           type_: "Posts",
673           sort: "TopAll",
674           listing_type: "All",
675           community_id: this.state.form.community_id,
676           page: 1,
677           limit: trendingFetchLimit,
678           auth: myAuth(),
679         }),
680       });
681     }
682   }
683
684   handlePostBodyChange(val: string) {
685     this.setState(s => ((s.form.body = val), s));
686   }
687
688   handleLanguageChange(val: number[]) {
689     this.setState(s => ((s.form.language_id = val.at(0)), s));
690   }
691
692   handleCommunitySearch = debounce(async (text: string) => {
693     const { selectedCommunityChoice } = this.props;
694     this.setState({ communitySearchLoading: true });
695
696     const newOptions: Choice[] = [];
697
698     if (selectedCommunityChoice) {
699       newOptions.push(selectedCommunityChoice);
700     }
701
702     if (text.length > 0) {
703       newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
704
705       this.setState({
706         communitySearchOptions: newOptions,
707       });
708     }
709
710     this.setState({
711       communitySearchLoading: false,
712     });
713   });
714
715   handleCommunitySelect(choice: Choice) {
716     if (this.props.onSelectCommunity) {
717       this.props.onSelectCommunity(choice);
718     }
719   }
720 }