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