13 } from "@utils/helpers";
14 import { isImage } from "@utils/media";
15 import { Choice } from "@utils/types";
16 import autosize from "autosize";
17 import { Component, InfernoNode, linkEvent } from "inferno";
22 GetSiteMetadataResponse,
26 } from "lemmy-js-client";
33 } from "../../config";
34 import { PostFormParams } from "../../interfaces";
35 import { I18NextService, UserService } from "../../services";
36 import { HttpService, RequestState } from "../../services/HttpService";
37 import { setupTippy } from "../../tippy";
38 import { toast } from "../../toast";
39 import { Icon, Spinner } from "../common/icon";
40 import { LanguageSelect } from "../common/language-select";
41 import { MarkdownTextArea } from "../common/markdown-textarea";
42 import NavigationPrompt from "../common/navigation-prompt";
43 import { SearchableSelect } from "../common/searchable-select";
44 import { PostListings } from "./post-listings";
46 const MAX_POST_TITLE_LENGTH = 200;
48 interface PostFormProps {
49 post_view?: PostView; // If a post is given, that means this is an edit
50 crossPosts?: PostView[];
51 allLanguages: Language[];
52 siteLanguages: number[];
53 params?: PostFormParams;
55 onCreate?(form: CreatePost): void;
56 onEdit?(form: EditPost): void;
58 enableDownvotes?: boolean;
59 selectedCommunityChoice?: Choice;
60 onSelectCommunity?: (choice: Choice) => void;
61 initialCommunities?: CommunityView[];
64 interface PostFormState {
71 community_id?: number;
75 suggestedPostsRes: RequestState<SearchResponse>;
76 metadataRes: RequestState<GetSiteMetadataResponse>;
77 imageLoading: boolean;
78 imageDeleteUrl: string;
79 communitySearchLoading: boolean;
80 communitySearchOptions: Choice[];
85 function handlePostSubmit(i: PostForm, event: any) {
86 event.preventDefault();
87 // Coerce empty url string to undefined
88 if ((i.state.form.url ?? "") === "") {
89 i.setState(s => ((s.form.url = undefined), s));
91 i.setState({ loading: true, submitted: true });
92 const auth = myAuthRequired();
94 const pForm = i.state.form;
95 const pv = i.props.post_view;
104 language_id: pForm.language_id,
107 } else if (pForm.name && pForm.community_id) {
110 community_id: pForm.community_id,
114 language_id: pForm.language_id,
115 honeypot: pForm.honeypot,
121 function copySuggestedTitle(d: { i: PostForm; suggestedTitle?: string }) {
122 const sTitle = d.suggestedTitle;
125 s => ((s.form.name = sTitle?.substring(0, MAX_POST_TITLE_LENGTH)), s)
127 d.i.setState({ suggestedPostsRes: { state: "empty" } });
129 const textarea: any = document.getElementById("post-title");
130 autosize.update(textarea);
135 function handlePostUrlChange(i: PostForm, event: any) {
136 const url = event.target.value;
138 i.setState(prev => ({
150 function handlePostNsfwChange(i: PostForm, event: any) {
151 i.setState(s => ((s.form.nsfw = event.target.checked), s));
154 function handleHoneyPotChange(i: PostForm, event: any) {
155 i.setState(s => ((s.form.honeypot = event.target.value), s));
158 function handleCancel(i: PostForm) {
159 i.props.onCancel?.();
162 function handleImageUploadPaste(i: PostForm, event: any) {
163 const image = event.clipboardData.files[0];
165 handleImageUpload(i, image);
169 function handleImageUpload(i: PostForm, event: any) {
172 event.preventDefault();
173 file = event.target.files[0];
178 i.setState({ imageLoading: true });
180 HttpService.client.uploadImage({ image: file }).then(res => {
181 console.log("pictrs upload:");
183 if (res.state === "success") {
184 if (res.data.msg === "ok") {
185 i.state.form.url = res.data.url;
188 imageDeleteUrl: res.data.delete_url as string,
190 } else if (res.data.msg === "too_large") {
191 toast(I18NextService.i18n.t("upload_too_large"), "danger");
193 toast(JSON.stringify(res), "danger");
195 } else if (res.state === "failed") {
196 console.error(res.msg);
197 toast(res.msg, "danger");
198 i.setState({ imageLoading: false });
203 function handlePostNameChange(i: PostForm, event: any) {
204 i.setState(s => ((s.form.name = event.target.value), s));
205 i.fetchSimilarPosts();
208 function handleImageDelete(i: PostForm) {
209 const { imageDeleteUrl } = i.state;
211 fetch(imageDeleteUrl);
213 i.setState(prev => ({
224 export class PostForm extends Component<PostFormProps, PostFormState> {
225 state: PostFormState = {
226 suggestedPostsRes: { state: "empty" },
227 metadataRes: { state: "empty" },
232 communitySearchLoading: false,
234 communitySearchOptions: [],
238 constructor(props: PostFormProps, context: any) {
239 super(props, context);
240 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts.bind(this));
241 this.fetchPageTitle = debounce(this.fetchPageTitle.bind(this));
242 this.handlePostBodyChange = this.handlePostBodyChange.bind(this);
243 this.handleLanguageChange = this.handleLanguageChange.bind(this);
244 this.handleCommunitySelect = this.handleCommunitySelect.bind(this);
246 const { post_view, selectedCommunityChoice, params } = this.props;
253 body: post_view.post.body,
254 name: post_view.post.name,
255 community_id: post_view.community.id,
256 url: post_view.post.url,
257 nsfw: post_view.post.nsfw,
258 language_id: post_view.post.language_id,
261 } else if (selectedCommunityChoice) {
266 community_id: getIdFromString(selectedCommunityChoice.value),
268 communitySearchOptions: [selectedCommunityChoice].concat(
270 this.props.initialCommunities?.map(
271 ({ community: { id, title } }) => ({
273 value: id.toString(),
276 ).filter(option => option.value !== selectedCommunityChoice.value)
282 communitySearchOptions:
283 this.props.initialCommunities?.map(
284 ({ community: { id, title } }) => ({
286 value: id.toString(),
303 componentDidMount() {
305 const textarea: any = document.getElementById("post-title");
312 componentWillReceiveProps(
313 nextProps: Readonly<{ children?: InfernoNode } & PostFormProps>
315 if (this.props != nextProps) {
318 (s.form.community_id = getIdFromString(
319 nextProps.selectedCommunityChoice?.value
328 const firstLang = this.state.form.language_id;
329 const selectedLangs = firstLang ? Array.of(firstLang) : undefined;
331 const url = this.state.form.url;
334 <form className="post-form" onSubmit={linkEvent(this, handlePostSubmit)}>
338 this.state.form.name ||
339 this.state.form.url ||
341 ) && !this.state.submitted
344 <div className="mb-3 row">
345 <label className="col-sm-2 col-form-label" htmlFor="post-url">
346 {I18NextService.i18n.t("url")}
348 <div className="col-sm-10">
352 className="form-control mb-3"
354 onInput={linkEvent(this, handlePostUrlChange)}
355 onPaste={linkEvent(this, handleImageUploadPaste)}
357 {this.renderSuggestedTitleCopy()}
358 {url && validURL(url) && (
361 href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
362 className="me-2 d-inline-block float-right text-muted small fw-bold"
365 archive.org {I18NextService.i18n.t("archive_link")}
368 href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
371 className="me-2 d-inline-block float-right text-muted small fw-bold"
374 ghostarchive.org {I18NextService.i18n.t("archive_link")}
377 href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
380 className="me-2 d-inline-block float-right text-muted small fw-bold"
383 archive.today {I18NextService.i18n.t("archive_link")}
390 <div className="mb-3 row">
391 <label htmlFor="file-upload" className={"col-sm-2 col-form-label"}>
392 {capitalizeFirstLetter(I18NextService.i18n.t("image"))}
393 <Icon icon="image" classes="icon-inline ms-1" />
395 <div className="col-sm-10">
399 accept="image/*,video/*"
401 className="small col-sm-10 form-control"
402 disabled={!UserService.Instance.myUserInfo}
403 onChange={linkEvent(this, handleImageUpload)}
405 {this.state.imageLoading && <Spinner />}
406 {url && isImage(url) && (
407 <img src={url} className="img-fluid mt-2" alt="" />
409 {this.state.imageDeleteUrl && (
411 className="btn btn-danger btn-sm mt-2"
412 onClick={linkEvent(this, handleImageDelete)}
414 <Icon icon="x" classes="icon-inline me-1" />
415 {capitalizeFirstLetter(I18NextService.i18n.t("delete"))}
419 {this.props.crossPosts && this.props.crossPosts.length > 0 && (
421 <div className="my-1 text-muted small fw-bold">
422 {I18NextService.i18n.t("cross_posts")}
426 posts={this.props.crossPosts}
427 enableDownvotes={this.props.enableDownvotes}
428 enableNsfw={this.props.enableNsfw}
429 allLanguages={this.props.allLanguages}
430 siteLanguages={this.props.siteLanguages}
432 // All of these are unused, since its view only
433 onPostEdit={() => {}}
434 onPostVote={() => {}}
435 onPostReport={() => {}}
436 onBlockPerson={() => {}}
437 onLockPost={() => {}}
438 onDeletePost={() => {}}
439 onRemovePost={() => {}}
440 onSavePost={() => {}}
441 onFeaturePost={() => {}}
442 onPurgePerson={() => {}}
443 onPurgePost={() => {}}
444 onBanPersonFromCommunity={() => {}}
445 onBanPerson={() => {}}
446 onAddModToCommunity={() => {}}
447 onAddAdmin={() => {}}
448 onTransferCommunity={() => {}}
454 <div className="mb-3 row">
455 <label className="col-sm-2 col-form-label" htmlFor="post-title">
456 {I18NextService.i18n.t("title")}
458 <div className="col-sm-10">
460 value={this.state.form.name}
462 onInput={linkEvent(this, handlePostNameChange)}
463 className={`form-control ${
464 !validTitle(this.state.form.name) && "is-invalid"
469 maxLength={MAX_POST_TITLE_LENGTH}
471 {!validTitle(this.state.form.name) && (
472 <div className="invalid-feedback">
473 {I18NextService.i18n.t("invalid_post_title")}
476 {this.renderSuggestedPosts()}
480 <div className="mb-3 row">
481 <label className="col-sm-2 col-form-label">
482 {I18NextService.i18n.t("body")}
484 <div className="col-sm-10">
486 initialContent={this.state.form.body}
487 onContentChange={this.handlePostBodyChange}
488 allLanguages={this.props.allLanguages}
489 siteLanguages={this.props.siteLanguages}
490 hideNavigationWarnings
495 allLanguages={this.props.allLanguages}
496 siteLanguages={this.props.siteLanguages}
497 selectedLanguageIds={selectedLangs}
499 onChange={this.handleLanguageChange}
501 {!this.props.post_view && (
502 <div className="mb-3 row">
503 <label className="col-sm-2 col-form-label" htmlFor="post-community">
504 {I18NextService.i18n.t("community")}
506 <div className="col-sm-10">
509 value={this.state.form.community_id}
512 label: I18NextService.i18n.t("select_a_community"),
516 ].concat(this.state.communitySearchOptions)}
517 loading={this.state.communitySearchLoading}
518 onChange={this.handleCommunitySelect}
519 onSearch={this.handleCommunitySearch}
524 {this.props.enableNsfw && (
525 <div className="form-check mb-3">
527 className="form-check-input"
530 checked={this.state.form.nsfw}
531 onChange={linkEvent(this, handlePostNsfwChange)}
533 <label className="form-check-label" htmlFor="post-nsfw">
534 {I18NextService.i18n.t("nsfw")}
543 className="form-control honeypot"
545 value={this.state.form.honeypot}
546 onInput={linkEvent(this, handleHoneyPotChange)}
548 <div className="mb-3 row">
549 <div className="col-sm-10">
551 disabled={!this.state.form.community_id || this.state.loading}
553 className="btn btn-secondary me-2"
555 {this.state.loading ? (
557 ) : this.props.post_view ? (
558 capitalizeFirstLetter(I18NextService.i18n.t("save"))
560 capitalizeFirstLetter(I18NextService.i18n.t("create"))
563 {this.props.post_view && (
566 className="btn btn-secondary"
567 onClick={linkEvent(this, handleCancel)}
569 {I18NextService.i18n.t("cancel")}
578 renderSuggestedTitleCopy() {
579 switch (this.state.metadataRes.state) {
583 const suggestedTitle = this.state.metadataRes.data.metadata.title;
589 className="mt-1 small border-0 bg-transparent p-0 d-block text-muted fw-bold pointer"
591 { i: this, suggestedTitle },
595 {I18NextService.i18n.t("copy_suggested_title", { title: "" })}{" "}
604 renderSuggestedPosts() {
605 switch (this.state.suggestedPostsRes.state) {
609 const suggestedPosts = this.state.suggestedPostsRes.data.posts;
613 suggestedPosts.length > 0 && (
615 <div className="my-1 text-muted small fw-bold">
616 {I18NextService.i18n.t("related_posts")}
620 posts={suggestedPosts}
621 enableDownvotes={this.props.enableDownvotes}
622 enableNsfw={this.props.enableNsfw}
623 allLanguages={this.props.allLanguages}
624 siteLanguages={this.props.siteLanguages}
626 // All of these are unused, since its view only
627 onPostEdit={() => {}}
628 onPostVote={() => {}}
629 onPostReport={() => {}}
630 onBlockPerson={() => {}}
631 onLockPost={() => {}}
632 onDeletePost={() => {}}
633 onRemovePost={() => {}}
634 onSavePost={() => {}}
635 onFeaturePost={() => {}}
636 onPurgePerson={() => {}}
637 onPurgePost={() => {}}
638 onBanPersonFromCommunity={() => {}}
639 onBanPerson={() => {}}
640 onAddModToCommunity={() => {}}
641 onAddAdmin={() => {}}
642 onTransferCommunity={() => {}}
651 async fetchPageTitle() {
652 const url = this.state.form.url;
653 if (url && validURL(url)) {
654 this.setState({ metadataRes: { state: "loading" } });
656 metadataRes: await HttpService.client.getSiteMetadata({ url }),
661 async fetchSimilarPosts() {
662 const q = this.state.form.name;
664 this.setState({ suggestedPostsRes: { state: "loading" } });
666 suggestedPostsRes: await HttpService.client.search({
671 community_id: this.state.form.community_id,
673 limit: trendingFetchLimit,
680 handlePostBodyChange(val: string) {
681 this.setState(s => ((s.form.body = val), s));
684 handleLanguageChange(val: number[]) {
685 this.setState(s => ((s.form.language_id = val.at(0)), s));
688 handleCommunitySearch = debounce(async (text: string) => {
689 const { selectedCommunityChoice } = this.props;
690 this.setState({ communitySearchLoading: true });
692 const newOptions: Choice[] = [];
694 if (selectedCommunityChoice) {
695 newOptions.push(selectedCommunityChoice);
698 if (text.length > 0) {
699 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
702 communitySearchOptions: newOptions,
707 communitySearchLoading: false,
711 handleCommunitySelect(choice: Choice) {
712 if (this.props.onSelectCommunity) {
713 this.props.onSelectCommunity(choice);