]> Untitled Git - lemmy-ui.git/blob - src/shared/components/post/post-form.tsx
9385179836ba6e320556a303b663ca0601364bb6
[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 { i18n } from "../../i18next";
35 import { PostFormParams } from "../../interfaces";
36 import { 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 firstLang = this.state.form.language_id;
328     const selectedLangs = firstLang ? Array.of(firstLang) : undefined;
329
330     const url = this.state.form.url;
331
332     return (
333       <form className="post-form" onSubmit={linkEvent(this, handlePostSubmit)}>
334         <NavigationPrompt
335           when={
336             !!(
337               this.state.form.name ||
338               this.state.form.url ||
339               this.state.form.body
340             ) && !this.state.submitted
341           }
342         />
343         <div className="mb-3 row">
344           <label className="col-sm-2 col-form-label" htmlFor="post-url">
345             {i18n.t("url")}
346           </label>
347           <div className="col-sm-10">
348             <input
349               type="url"
350               id="post-url"
351               className="form-control"
352               value={url}
353               onInput={linkEvent(this, handlePostUrlChange)}
354               onPaste={linkEvent(this, handleImageUploadPaste)}
355             />
356             {this.renderSuggestedTitleCopy()}
357             <form>
358               <label
359                 htmlFor="file-upload"
360                 className={`${
361                   UserService.Instance.myUserInfo && "pointer"
362                 } d-inline-block float-right text-muted font-weight-bold`}
363                 data-tippy-content={i18n.t("upload_image")}
364               >
365                 <Icon icon="image" classes="icon-inline" />
366               </label>
367               <input
368                 id="file-upload"
369                 type="file"
370                 accept="image/*,video/*"
371                 name="file"
372                 className="d-none"
373                 disabled={!UserService.Instance.myUserInfo}
374                 onChange={linkEvent(this, handleImageUpload)}
375               />
376             </form>
377             {url && validURL(url) && (
378               <div>
379                 <a
380                   href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
381                   className="me-2 d-inline-block float-right text-muted small font-weight-bold"
382                   rel={relTags}
383                 >
384                   archive.org {i18n.t("archive_link")}
385                 </a>
386                 <a
387                   href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
388                     url
389                   )}`}
390                   className="me-2 d-inline-block float-right text-muted small font-weight-bold"
391                   rel={relTags}
392                 >
393                   ghostarchive.org {i18n.t("archive_link")}
394                 </a>
395                 <a
396                   href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
397                     url
398                   )}`}
399                   className="me-2 d-inline-block float-right text-muted small font-weight-bold"
400                   rel={relTags}
401                 >
402                   archive.today {i18n.t("archive_link")}
403                 </a>
404               </div>
405             )}
406             {this.state.imageLoading && <Spinner />}
407             {url && isImage(url) && (
408               <img src={url} className="img-fluid" alt="" />
409             )}
410             {this.state.imageDeleteUrl && (
411               <button
412                 className="btn btn-danger btn-sm mt-2"
413                 onClick={linkEvent(this, handleImageDelete)}
414                 aria-label={i18n.t("delete")}
415                 data-tippy-content={i18n.t("delete")}
416               >
417                 <Icon icon="x" classes="icon-inline me-1" />
418                 {capitalizeFirstLetter(i18n.t("delete"))}
419               </button>
420             )}
421             {this.props.crossPosts && this.props.crossPosts.length > 0 && (
422               <>
423                 <div className="my-1 text-muted small font-weight-bold">
424                   {i18n.t("cross_posts")}
425                 </div>
426                 <PostListings
427                   showCommunity
428                   posts={this.props.crossPosts}
429                   enableDownvotes={this.props.enableDownvotes}
430                   enableNsfw={this.props.enableNsfw}
431                   allLanguages={this.props.allLanguages}
432                   siteLanguages={this.props.siteLanguages}
433                   viewOnly
434                   // All of these are unused, since its view only
435                   onPostEdit={() => {}}
436                   onPostVote={() => {}}
437                   onPostReport={() => {}}
438                   onBlockPerson={() => {}}
439                   onLockPost={() => {}}
440                   onDeletePost={() => {}}
441                   onRemovePost={() => {}}
442                   onSavePost={() => {}}
443                   onFeaturePost={() => {}}
444                   onPurgePerson={() => {}}
445                   onPurgePost={() => {}}
446                   onBanPersonFromCommunity={() => {}}
447                   onBanPerson={() => {}}
448                   onAddModToCommunity={() => {}}
449                   onAddAdmin={() => {}}
450                   onTransferCommunity={() => {}}
451                 />
452               </>
453             )}
454           </div>
455         </div>
456         <div className="mb-3 row">
457           <label className="col-sm-2 col-form-label" htmlFor="post-title">
458             {i18n.t("title")}
459           </label>
460           <div className="col-sm-10">
461             <textarea
462               value={this.state.form.name}
463               id="post-title"
464               onInput={linkEvent(this, handlePostNameChange)}
465               className={`form-control ${
466                 !validTitle(this.state.form.name) && "is-invalid"
467               }`}
468               required
469               rows={1}
470               minLength={3}
471               maxLength={MAX_POST_TITLE_LENGTH}
472             />
473             {!validTitle(this.state.form.name) && (
474               <div className="invalid-feedback">
475                 {i18n.t("invalid_post_title")}
476               </div>
477             )}
478             {this.renderSuggestedPosts()}
479           </div>
480         </div>
481
482         <div className="mb-3 row">
483           <label className="col-sm-2 col-form-label">{i18n.t("body")}</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               {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: 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">{i18n.t("nsfw")}</label>
534           </div>
535         )}
536         <input
537           tabIndex={-1}
538           autoComplete="false"
539           name="a_password"
540           type="text"
541           className="form-control honeypot"
542           id="register-honey"
543           value={this.state.form.honeypot}
544           onInput={linkEvent(this, handleHoneyPotChange)}
545         />
546         <div className="mb-3 row">
547           <div className="col-sm-10">
548             <button
549               disabled={!this.state.form.community_id || this.state.loading}
550               type="submit"
551               className="btn btn-secondary me-2"
552             >
553               {this.state.loading ? (
554                 <Spinner />
555               ) : this.props.post_view ? (
556                 capitalizeFirstLetter(i18n.t("save"))
557               ) : (
558                 capitalizeFirstLetter(i18n.t("create"))
559               )}
560             </button>
561             {this.props.post_view && (
562               <button
563                 type="button"
564                 className="btn btn-secondary"
565                 onClick={linkEvent(this, handleCancel)}
566               >
567                 {i18n.t("cancel")}
568               </button>
569             )}
570           </div>
571         </div>
572       </form>
573     );
574   }
575
576   renderSuggestedTitleCopy() {
577     switch (this.state.metadataRes.state) {
578       case "loading":
579         return <Spinner />;
580       case "success": {
581         const suggestedTitle = this.state.metadataRes.data.metadata.title;
582
583         return (
584           suggestedTitle && (
585             <div
586               className="mt-1 text-muted small font-weight-bold pointer"
587               role="button"
588               onClick={linkEvent(
589                 { i: this, suggestedTitle },
590                 copySuggestedTitle
591               )}
592             >
593               {i18n.t("copy_suggested_title", { title: "" })} {suggestedTitle}
594             </div>
595           )
596         );
597       }
598     }
599   }
600
601   renderSuggestedPosts() {
602     switch (this.state.suggestedPostsRes.state) {
603       case "loading":
604         return <Spinner />;
605       case "success": {
606         const suggestedPosts = this.state.suggestedPostsRes.data.posts;
607
608         return (
609           suggestedPosts &&
610           suggestedPosts.length > 0 && (
611             <>
612               <div className="my-1 text-muted small font-weight-bold">
613                 {i18n.t("related_posts")}
614               </div>
615               <PostListings
616                 showCommunity
617                 posts={suggestedPosts}
618                 enableDownvotes={this.props.enableDownvotes}
619                 enableNsfw={this.props.enableNsfw}
620                 allLanguages={this.props.allLanguages}
621                 siteLanguages={this.props.siteLanguages}
622                 viewOnly
623                 // All of these are unused, since its view only
624                 onPostEdit={() => {}}
625                 onPostVote={() => {}}
626                 onPostReport={() => {}}
627                 onBlockPerson={() => {}}
628                 onLockPost={() => {}}
629                 onDeletePost={() => {}}
630                 onRemovePost={() => {}}
631                 onSavePost={() => {}}
632                 onFeaturePost={() => {}}
633                 onPurgePerson={() => {}}
634                 onPurgePost={() => {}}
635                 onBanPersonFromCommunity={() => {}}
636                 onBanPerson={() => {}}
637                 onAddModToCommunity={() => {}}
638                 onAddAdmin={() => {}}
639                 onTransferCommunity={() => {}}
640               />
641             </>
642           )
643         );
644       }
645     }
646   }
647
648   async fetchPageTitle() {
649     const url = this.state.form.url;
650     if (url && validURL(url)) {
651       this.setState({ metadataRes: { state: "loading" } });
652       this.setState({
653         metadataRes: await HttpService.client.getSiteMetadata({ url }),
654       });
655     }
656   }
657
658   async fetchSimilarPosts() {
659     const q = this.state.form.name;
660     if (q && q !== "") {
661       this.setState({ suggestedPostsRes: { state: "loading" } });
662       this.setState({
663         suggestedPostsRes: await HttpService.client.search({
664           q,
665           type_: "Posts",
666           sort: "TopAll",
667           listing_type: "All",
668           community_id: this.state.form.community_id,
669           page: 1,
670           limit: trendingFetchLimit,
671           auth: myAuth(),
672         }),
673       });
674     }
675   }
676
677   handlePostBodyChange(val: string) {
678     this.setState(s => ((s.form.body = val), s));
679   }
680
681   handleLanguageChange(val: number[]) {
682     this.setState(s => ((s.form.language_id = val.at(0)), s));
683   }
684
685   handleCommunitySearch = debounce(async (text: string) => {
686     const { selectedCommunityChoice } = this.props;
687     this.setState({ communitySearchLoading: true });
688
689     const newOptions: Choice[] = [];
690
691     if (selectedCommunityChoice) {
692       newOptions.push(selectedCommunityChoice);
693     }
694
695     if (text.length > 0) {
696       newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
697
698       this.setState({
699         communitySearchOptions: newOptions,
700       });
701     }
702
703     this.setState({
704       communitySearchLoading: false,
705     });
706   });
707
708   handleCommunitySelect(choice: Choice) {
709     if (this.props.onSelectCommunity) {
710       this.props.onSelectCommunity(choice);
711     }
712   }
713 }