7 import getUserInterfaceLangId from "@utils/app/user-interface-language";
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";
23 GetSiteMetadataResponse,
27 } from "lemmy-js-client";
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";
47 const MAX_POST_TITLE_LENGTH = 200;
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;
56 onCreate?(form: CreatePost): void;
57 onEdit?(form: EditPost): void;
59 enableDownvotes?: boolean;
60 selectedCommunityChoice?: Choice;
61 onSelectCommunity?: (choice: Choice) => void;
62 initialCommunities?: CommunityView[];
65 interface PostFormState {
72 community_id?: number;
76 suggestedPostsRes: RequestState<SearchResponse>;
77 metadataRes: RequestState<GetSiteMetadataResponse>;
78 imageLoading: boolean;
79 imageDeleteUrl: string;
80 communitySearchLoading: boolean;
81 communitySearchOptions: Choice[];
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));
92 i.setState({ loading: true, submitted: true });
93 const auth = myAuthRequired();
95 const pForm = i.state.form;
96 const pv = i.props.post_view;
105 language_id: pForm.language_id,
108 } else if (pForm.name && pForm.community_id) {
111 community_id: pForm.community_id,
115 language_id: pForm.language_id,
116 honeypot: pForm.honeypot,
122 function copySuggestedTitle(d: { i: PostForm; suggestedTitle?: string }) {
123 const sTitle = d.suggestedTitle;
126 s => ((s.form.name = sTitle?.substring(0, MAX_POST_TITLE_LENGTH)), s)
128 d.i.setState({ suggestedPostsRes: { state: "empty" } });
130 const textarea: any = document.getElementById("post-title");
131 autosize.update(textarea);
136 function handlePostUrlChange(i: PostForm, event: any) {
137 const url = event.target.value;
139 i.setState(prev => ({
151 function handlePostNsfwChange(i: PostForm, event: any) {
152 i.setState(s => ((s.form.nsfw = event.target.checked), s));
155 function handleHoneyPotChange(i: PostForm, event: any) {
156 i.setState(s => ((s.form.honeypot = event.target.value), s));
159 function handleCancel(i: PostForm) {
160 i.props.onCancel?.();
163 function handleImageUploadPaste(i: PostForm, event: any) {
164 const image = event.clipboardData.files[0];
166 handleImageUpload(i, image);
170 function handleImageUpload(i: PostForm, event: any) {
173 event.preventDefault();
174 file = event.target.files[0];
179 i.setState({ imageLoading: true });
181 HttpService.client.uploadImage({ image: file }).then(res => {
182 console.log("pictrs upload:");
184 if (res.state === "success") {
185 if (res.data.msg === "ok") {
186 i.state.form.url = res.data.url;
189 imageDeleteUrl: res.data.delete_url as string,
192 toast(JSON.stringify(res), "danger");
194 } else if (res.state === "failed") {
195 console.error(res.msg);
196 toast(res.msg, "danger");
197 i.setState({ imageLoading: false });
202 function handlePostNameChange(i: PostForm, event: any) {
203 i.setState(s => ((s.form.name = event.target.value), s));
204 i.fetchSimilarPosts();
207 function handleImageDelete(i: PostForm) {
208 const { imageDeleteUrl } = i.state;
210 fetch(imageDeleteUrl);
212 i.setState(prev => ({
223 export class PostForm extends Component<PostFormProps, PostFormState> {
224 state: PostFormState = {
225 suggestedPostsRes: { state: "empty" },
226 metadataRes: { state: "empty" },
231 communitySearchLoading: false,
233 communitySearchOptions: [],
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);
245 const { post_view, selectedCommunityChoice, params } = this.props;
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,
260 } else if (selectedCommunityChoice) {
265 community_id: getIdFromString(selectedCommunityChoice.value),
267 communitySearchOptions: [selectedCommunityChoice].concat(
269 this.props.initialCommunities?.map(
270 ({ community: { id, title } }) => ({
272 value: id.toString(),
275 ).filter(option => option.value !== selectedCommunityChoice.value)
281 communitySearchOptions:
282 this.props.initialCommunities?.map(
283 ({ community: { id, title } }) => ({
285 value: id.toString(),
302 componentDidMount() {
304 const textarea: any = document.getElementById("post-title");
311 componentWillReceiveProps(
312 nextProps: Readonly<{ children?: InfernoNode } & PostFormProps>
314 if (this.props != nextProps) {
317 (s.form.community_id = getIdFromString(
318 nextProps.selectedCommunityChoice?.value
327 const url = this.state.form.url;
329 const userInterfaceLangId = getUserInterfaceLangId({
330 myUserInfo: UserService.Instance.myUserInfo,
331 allLanguages: this.props.allLanguages,
335 <form className="post-form" onSubmit={linkEvent(this, handlePostSubmit)}>
339 this.state.form.name ||
340 this.state.form.url ||
342 ) && !this.state.submitted
345 <div className="mb-3 row">
346 <label className="col-sm-2 col-form-label" htmlFor="post-url">
347 {I18NextService.i18n.t("url")}
349 <div className="col-sm-10">
353 className="form-control"
355 onInput={linkEvent(this, handlePostUrlChange)}
356 onPaste={linkEvent(this, handleImageUploadPaste)}
358 {this.renderSuggestedTitleCopy()}
361 htmlFor="file-upload"
363 UserService.Instance.myUserInfo && "pointer"
364 } d-inline-block float-right text-muted font-weight-bold`}
365 data-tippy-content={I18NextService.i18n.t("upload_image")}
367 <Icon icon="image" classes="icon-inline" />
372 accept="image/*,video/*"
375 disabled={!UserService.Instance.myUserInfo}
376 onChange={linkEvent(this, handleImageUpload)}
379 {url && validURL(url) && (
382 href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
383 className="me-2 d-inline-block float-right text-muted small font-weight-bold"
386 archive.org {I18NextService.i18n.t("archive_link")}
389 href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
392 className="me-2 d-inline-block float-right text-muted small font-weight-bold"
395 ghostarchive.org {I18NextService.i18n.t("archive_link")}
398 href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
401 className="me-2 d-inline-block float-right text-muted small font-weight-bold"
404 archive.today {I18NextService.i18n.t("archive_link")}
408 {this.state.imageLoading && <Spinner />}
409 {url && isImage(url) && (
410 <img src={url} className="img-fluid" alt="" />
412 {this.state.imageDeleteUrl && (
414 className="btn btn-danger btn-sm mt-2"
415 onClick={linkEvent(this, handleImageDelete)}
416 aria-label={I18NextService.i18n.t("delete")}
417 data-tippy-content={I18NextService.i18n.t("delete")}
419 <Icon icon="x" classes="icon-inline me-1" />
420 {capitalizeFirstLetter(I18NextService.i18n.t("delete"))}
423 {this.props.crossPosts && this.props.crossPosts.length > 0 && (
425 <div className="my-1 text-muted small font-weight-bold">
426 {I18NextService.i18n.t("cross_posts")}
430 posts={this.props.crossPosts}
431 enableDownvotes={this.props.enableDownvotes}
432 enableNsfw={this.props.enableNsfw}
433 allLanguages={this.props.allLanguages}
434 siteLanguages={this.props.siteLanguages}
436 // All of these are unused, since its view only
437 onPostEdit={() => {}}
438 onPostVote={() => {}}
439 onPostReport={() => {}}
440 onBlockPerson={() => {}}
441 onLockPost={() => {}}
442 onDeletePost={() => {}}
443 onRemovePost={() => {}}
444 onSavePost={() => {}}
445 onFeaturePost={() => {}}
446 onPurgePerson={() => {}}
447 onPurgePost={() => {}}
448 onBanPersonFromCommunity={() => {}}
449 onBanPerson={() => {}}
450 onAddModToCommunity={() => {}}
451 onAddAdmin={() => {}}
452 onTransferCommunity={() => {}}
458 <div className="mb-3 row">
459 <label className="col-sm-2 col-form-label" htmlFor="post-title">
460 {I18NextService.i18n.t("title")}
462 <div className="col-sm-10">
464 value={this.state.form.name}
466 onInput={linkEvent(this, handlePostNameChange)}
467 className={`form-control ${
468 !validTitle(this.state.form.name) && "is-invalid"
473 maxLength={MAX_POST_TITLE_LENGTH}
475 {!validTitle(this.state.form.name) && (
476 <div className="invalid-feedback">
477 {I18NextService.i18n.t("invalid_post_title")}
480 {this.renderSuggestedPosts()}
484 <div className="mb-3 row">
485 <label className="col-sm-2 col-form-label">
486 {I18NextService.i18n.t("body")}
488 <div className="col-sm-10">
490 initialContent={this.state.form.body}
491 onContentChange={this.handlePostBodyChange}
492 allLanguages={this.props.allLanguages}
493 siteLanguages={this.props.siteLanguages}
494 hideNavigationWarnings
499 allLanguages={this.props.allLanguages}
500 selectedLanguageIds={[userInterfaceLangId]}
501 siteLanguages={this.props.siteLanguages}
503 onChange={this.handleLanguageChange}
505 {!this.props.post_view && (
506 <div className="mb-3 row">
507 <label className="col-sm-2 col-form-label" htmlFor="post-community">
508 {I18NextService.i18n.t("community")}
510 <div className="col-sm-10">
513 value={this.state.form.community_id}
516 label: I18NextService.i18n.t("select_a_community"),
520 ].concat(this.state.communitySearchOptions)}
521 loading={this.state.communitySearchLoading}
522 onChange={this.handleCommunitySelect}
523 onSearch={this.handleCommunitySearch}
528 {this.props.enableNsfw && (
529 <div className="form-check mb-3">
531 className="form-check-input"
534 checked={this.state.form.nsfw}
535 onChange={linkEvent(this, handlePostNsfwChange)}
537 <label className="form-check-label">
538 {I18NextService.i18n.t("nsfw")}
547 className="form-control honeypot"
549 value={this.state.form.honeypot}
550 onInput={linkEvent(this, handleHoneyPotChange)}
552 <div className="mb-3 row">
553 <div className="col-sm-10">
555 disabled={!this.state.form.community_id || this.state.loading}
557 className="btn btn-secondary me-2"
559 {this.state.loading ? (
561 ) : this.props.post_view ? (
562 capitalizeFirstLetter(I18NextService.i18n.t("save"))
564 capitalizeFirstLetter(I18NextService.i18n.t("create"))
567 {this.props.post_view && (
570 className="btn btn-secondary"
571 onClick={linkEvent(this, handleCancel)}
573 {I18NextService.i18n.t("cancel")}
582 renderSuggestedTitleCopy() {
583 switch (this.state.metadataRes.state) {
587 const suggestedTitle = this.state.metadataRes.data.metadata.title;
592 className="mt-1 text-muted small font-weight-bold pointer"
595 { i: this, suggestedTitle },
599 {I18NextService.i18n.t("copy_suggested_title", { title: "" })}{" "}
608 renderSuggestedPosts() {
609 switch (this.state.suggestedPostsRes.state) {
613 const suggestedPosts = this.state.suggestedPostsRes.data.posts;
617 suggestedPosts.length > 0 && (
619 <div className="my-1 text-muted small font-weight-bold">
620 {I18NextService.i18n.t("related_posts")}
624 posts={suggestedPosts}
625 enableDownvotes={this.props.enableDownvotes}
626 enableNsfw={this.props.enableNsfw}
627 allLanguages={this.props.allLanguages}
628 siteLanguages={this.props.siteLanguages}
630 // All of these are unused, since its view only
631 onPostEdit={() => {}}
632 onPostVote={() => {}}
633 onPostReport={() => {}}
634 onBlockPerson={() => {}}
635 onLockPost={() => {}}
636 onDeletePost={() => {}}
637 onRemovePost={() => {}}
638 onSavePost={() => {}}
639 onFeaturePost={() => {}}
640 onPurgePerson={() => {}}
641 onPurgePost={() => {}}
642 onBanPersonFromCommunity={() => {}}
643 onBanPerson={() => {}}
644 onAddModToCommunity={() => {}}
645 onAddAdmin={() => {}}
646 onTransferCommunity={() => {}}
655 async fetchPageTitle() {
656 const url = this.state.form.url;
657 if (url && validURL(url)) {
658 this.setState({ metadataRes: { state: "loading" } });
660 metadataRes: await HttpService.client.getSiteMetadata({ url }),
665 async fetchSimilarPosts() {
666 const q = this.state.form.name;
668 this.setState({ suggestedPostsRes: { state: "loading" } });
670 suggestedPostsRes: await HttpService.client.search({
675 community_id: this.state.form.community_id,
677 limit: trendingFetchLimit,
684 handlePostBodyChange(val: string) {
685 this.setState(s => ((s.form.body = val), s));
688 handleLanguageChange(val: number[]) {
689 this.setState(s => ((s.form.language_id = val.at(0)), s));
692 handleCommunitySearch = debounce(async (text: string) => {
693 const { selectedCommunityChoice } = this.props;
694 this.setState({ communitySearchLoading: true });
696 const newOptions: Choice[] = [];
698 if (selectedCommunityChoice) {
699 newOptions.push(selectedCommunityChoice);
702 if (text.length > 0) {
703 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
706 communitySearchOptions: newOptions,
711 communitySearchLoading: false,
715 handleCommunitySelect(choice: Choice) {
716 if (this.props.onSelectCommunity) {
717 this.props.onSelectCommunity(choice);