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