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(this.props.allLanguages);
332 <form className="post-form" onSubmit={linkEvent(this, handlePostSubmit)}>
336 this.state.form.name ||
337 this.state.form.url ||
339 ) && !this.state.submitted
342 <div className="mb-3 row">
343 <label className="col-sm-2 col-form-label" htmlFor="post-url">
344 {I18NextService.i18n.t("url")}
346 <div className="col-sm-10">
350 className="form-control"
352 onInput={linkEvent(this, handlePostUrlChange)}
353 onPaste={linkEvent(this, handleImageUploadPaste)}
355 {this.renderSuggestedTitleCopy()}
358 htmlFor="file-upload"
360 UserService.Instance.myUserInfo && "pointer"
361 } d-inline-block float-right text-muted fw-bold`}
362 data-tippy-content={I18NextService.i18n.t("upload_image")}
364 <Icon icon="image" classes="icon-inline" />
369 accept="image/*,video/*"
372 disabled={!UserService.Instance.myUserInfo}
373 onChange={linkEvent(this, handleImageUpload)}
376 {url && validURL(url) && (
379 href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
380 className="me-2 d-inline-block float-right text-muted small fw-bold"
383 archive.org {I18NextService.i18n.t("archive_link")}
386 href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
389 className="me-2 d-inline-block float-right text-muted small fw-bold"
392 ghostarchive.org {I18NextService.i18n.t("archive_link")}
395 href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
398 className="me-2 d-inline-block float-right text-muted small fw-bold"
401 archive.today {I18NextService.i18n.t("archive_link")}
405 {this.state.imageLoading && <Spinner />}
406 {url && isImage(url) && (
407 <img src={url} className="img-fluid" alt="" />
409 {this.state.imageDeleteUrl && (
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")}
416 <Icon icon="x" classes="icon-inline me-1" />
417 {capitalizeFirstLetter(I18NextService.i18n.t("delete"))}
420 {this.props.crossPosts && this.props.crossPosts.length > 0 && (
422 <div className="my-1 text-muted small fw-bold">
423 {I18NextService.i18n.t("cross_posts")}
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}
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={() => {}}
455 <div className="mb-3 row">
456 <label className="col-sm-2 col-form-label" htmlFor="post-title">
457 {I18NextService.i18n.t("title")}
459 <div className="col-sm-10">
461 value={this.state.form.name}
463 onInput={linkEvent(this, handlePostNameChange)}
464 className={`form-control ${
465 !validTitle(this.state.form.name) && "is-invalid"
470 maxLength={MAX_POST_TITLE_LENGTH}
472 {!validTitle(this.state.form.name) && (
473 <div className="invalid-feedback">
474 {I18NextService.i18n.t("invalid_post_title")}
477 {this.renderSuggestedPosts()}
481 <div className="mb-3 row">
482 <label className="col-sm-2 col-form-label">
483 {I18NextService.i18n.t("body")}
485 <div className="col-sm-10">
487 initialContent={this.state.form.body}
488 onContentChange={this.handlePostBodyChange}
489 allLanguages={this.props.allLanguages}
490 siteLanguages={this.props.siteLanguages}
491 hideNavigationWarnings
496 allLanguages={this.props.allLanguages}
497 selectedLanguageIds={[userInterfaceLangId]}
498 siteLanguages={this.props.siteLanguages}
500 onChange={this.handleLanguageChange}
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")}
507 <div className="col-sm-10">
510 value={this.state.form.community_id}
513 label: I18NextService.i18n.t("select_a_community"),
517 ].concat(this.state.communitySearchOptions)}
518 loading={this.state.communitySearchLoading}
519 onChange={this.handleCommunitySelect}
520 onSearch={this.handleCommunitySearch}
525 {this.props.enableNsfw && (
526 <div className="form-check mb-3">
528 className="form-check-input"
531 checked={this.state.form.nsfw}
532 onChange={linkEvent(this, handlePostNsfwChange)}
534 <label className="form-check-label">
535 {I18NextService.i18n.t("nsfw")}
544 className="form-control honeypot"
546 value={this.state.form.honeypot}
547 onInput={linkEvent(this, handleHoneyPotChange)}
549 <div className="mb-3 row">
550 <div className="col-sm-10">
552 disabled={!this.state.form.community_id || this.state.loading}
554 className="btn btn-secondary me-2"
556 {this.state.loading ? (
558 ) : this.props.post_view ? (
559 capitalizeFirstLetter(I18NextService.i18n.t("save"))
561 capitalizeFirstLetter(I18NextService.i18n.t("create"))
564 {this.props.post_view && (
567 className="btn btn-secondary"
568 onClick={linkEvent(this, handleCancel)}
570 {I18NextService.i18n.t("cancel")}
579 renderSuggestedTitleCopy() {
580 switch (this.state.metadataRes.state) {
584 const suggestedTitle = this.state.metadataRes.data.metadata.title;
590 className="mt-1 small border-0 bg-transparent p-0 d-block text-muted fw-bold pointer"
592 { i: this, suggestedTitle },
596 {I18NextService.i18n.t("copy_suggested_title", { title: "" })}{" "}
605 renderSuggestedPosts() {
606 switch (this.state.suggestedPostsRes.state) {
610 const suggestedPosts = this.state.suggestedPostsRes.data.posts;
614 suggestedPosts.length > 0 && (
616 <div className="my-1 text-muted small fw-bold">
617 {I18NextService.i18n.t("related_posts")}
621 posts={suggestedPosts}
622 enableDownvotes={this.props.enableDownvotes}
623 enableNsfw={this.props.enableNsfw}
624 allLanguages={this.props.allLanguages}
625 siteLanguages={this.props.siteLanguages}
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={() => {}}
652 async fetchPageTitle() {
653 const url = this.state.form.url;
654 if (url && validURL(url)) {
655 this.setState({ metadataRes: { state: "loading" } });
657 metadataRes: await HttpService.client.getSiteMetadata({ url }),
662 async fetchSimilarPosts() {
663 const q = this.state.form.name;
665 this.setState({ suggestedPostsRes: { state: "loading" } });
667 suggestedPostsRes: await HttpService.client.search({
672 community_id: this.state.form.community_id,
674 limit: trendingFetchLimit,
681 handlePostBodyChange(val: string) {
682 this.setState(s => ((s.form.body = val), s));
685 handleLanguageChange(val: number[]) {
686 this.setState(s => ((s.form.language_id = val.at(0)), s));
689 handleCommunitySearch = debounce(async (text: string) => {
690 const { selectedCommunityChoice } = this.props;
691 this.setState({ communitySearchLoading: true });
693 const newOptions: Choice[] = [];
695 if (selectedCommunityChoice) {
696 newOptions.push(selectedCommunityChoice);
699 if (text.length > 0) {
700 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
703 communitySearchOptions: newOptions,
708 communitySearchLoading: false,
712 handleCommunitySelect(choice: Choice) {
713 if (this.props.onSelectCommunity) {
714 this.props.onSelectCommunity(choice);