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