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