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 = !UserService.Instance.myUserInfo
331 : getUserInterfaceLangId({
332 myUserInfo: UserService.Instance.myUserInfo,
333 allLanguages: this.props.allLanguages,
337 <form className="post-form" onSubmit={linkEvent(this, handlePostSubmit)}>
341 this.state.form.name ||
342 this.state.form.url ||
344 ) && !this.state.submitted
347 <div className="mb-3 row">
348 <label className="col-sm-2 col-form-label" htmlFor="post-url">
349 {I18NextService.i18n.t("url")}
351 <div className="col-sm-10">
355 className="form-control"
357 onInput={linkEvent(this, handlePostUrlChange)}
358 onPaste={linkEvent(this, handleImageUploadPaste)}
360 {this.renderSuggestedTitleCopy()}
363 htmlFor="file-upload"
365 UserService.Instance.myUserInfo && "pointer"
366 } d-inline-block float-right text-muted font-weight-bold`}
367 data-tippy-content={I18NextService.i18n.t("upload_image")}
369 <Icon icon="image" classes="icon-inline" />
374 accept="image/*,video/*"
377 disabled={!UserService.Instance.myUserInfo}
378 onChange={linkEvent(this, handleImageUpload)}
381 {url && validURL(url) && (
384 href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
385 className="me-2 d-inline-block float-right text-muted small font-weight-bold"
388 archive.org {I18NextService.i18n.t("archive_link")}
391 href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
394 className="me-2 d-inline-block float-right text-muted small font-weight-bold"
397 ghostarchive.org {I18NextService.i18n.t("archive_link")}
400 href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
403 className="me-2 d-inline-block float-right text-muted small font-weight-bold"
406 archive.today {I18NextService.i18n.t("archive_link")}
410 {this.state.imageLoading && <Spinner />}
411 {url && isImage(url) && (
412 <img src={url} className="img-fluid" alt="" />
414 {this.state.imageDeleteUrl && (
416 className="btn btn-danger btn-sm mt-2"
417 onClick={linkEvent(this, handleImageDelete)}
418 aria-label={I18NextService.i18n.t("delete")}
419 data-tippy-content={I18NextService.i18n.t("delete")}
421 <Icon icon="x" classes="icon-inline me-1" />
422 {capitalizeFirstLetter(I18NextService.i18n.t("delete"))}
425 {this.props.crossPosts && this.props.crossPosts.length > 0 && (
427 <div className="my-1 text-muted small font-weight-bold">
428 {I18NextService.i18n.t("cross_posts")}
432 posts={this.props.crossPosts}
433 enableDownvotes={this.props.enableDownvotes}
434 enableNsfw={this.props.enableNsfw}
435 allLanguages={this.props.allLanguages}
436 siteLanguages={this.props.siteLanguages}
438 // All of these are unused, since its view only
439 onPostEdit={() => {}}
440 onPostVote={() => {}}
441 onPostReport={() => {}}
442 onBlockPerson={() => {}}
443 onLockPost={() => {}}
444 onDeletePost={() => {}}
445 onRemovePost={() => {}}
446 onSavePost={() => {}}
447 onFeaturePost={() => {}}
448 onPurgePerson={() => {}}
449 onPurgePost={() => {}}
450 onBanPersonFromCommunity={() => {}}
451 onBanPerson={() => {}}
452 onAddModToCommunity={() => {}}
453 onAddAdmin={() => {}}
454 onTransferCommunity={() => {}}
460 <div className="mb-3 row">
461 <label className="col-sm-2 col-form-label" htmlFor="post-title">
462 {I18NextService.i18n.t("title")}
464 <div className="col-sm-10">
466 value={this.state.form.name}
468 onInput={linkEvent(this, handlePostNameChange)}
469 className={`form-control ${
470 !validTitle(this.state.form.name) && "is-invalid"
475 maxLength={MAX_POST_TITLE_LENGTH}
477 {!validTitle(this.state.form.name) && (
478 <div className="invalid-feedback">
479 {I18NextService.i18n.t("invalid_post_title")}
482 {this.renderSuggestedPosts()}
486 <div className="mb-3 row">
487 <label className="col-sm-2 col-form-label">
488 {I18NextService.i18n.t("body")}
490 <div className="col-sm-10">
492 initialContent={this.state.form.body}
493 onContentChange={this.handlePostBodyChange}
494 allLanguages={this.props.allLanguages}
495 siteLanguages={this.props.siteLanguages}
496 hideNavigationWarnings
501 allLanguages={this.props.allLanguages}
502 selectedLanguageIds={[userInterfaceLangId]}
503 siteLanguages={this.props.siteLanguages}
505 onChange={this.handleLanguageChange}
507 {!this.props.post_view && (
508 <div className="mb-3 row">
509 <label className="col-sm-2 col-form-label" htmlFor="post-community">
510 {I18NextService.i18n.t("community")}
512 <div className="col-sm-10">
515 value={this.state.form.community_id}
518 label: I18NextService.i18n.t("select_a_community"),
522 ].concat(this.state.communitySearchOptions)}
523 loading={this.state.communitySearchLoading}
524 onChange={this.handleCommunitySelect}
525 onSearch={this.handleCommunitySearch}
530 {this.props.enableNsfw && (
531 <div className="form-check mb-3">
533 className="form-check-input"
536 checked={this.state.form.nsfw}
537 onChange={linkEvent(this, handlePostNsfwChange)}
539 <label className="form-check-label">
540 {I18NextService.i18n.t("nsfw")}
549 className="form-control honeypot"
551 value={this.state.form.honeypot}
552 onInput={linkEvent(this, handleHoneyPotChange)}
554 <div className="mb-3 row">
555 <div className="col-sm-10">
557 disabled={!this.state.form.community_id || this.state.loading}
559 className="btn btn-secondary me-2"
561 {this.state.loading ? (
563 ) : this.props.post_view ? (
564 capitalizeFirstLetter(I18NextService.i18n.t("save"))
566 capitalizeFirstLetter(I18NextService.i18n.t("create"))
569 {this.props.post_view && (
572 className="btn btn-secondary"
573 onClick={linkEvent(this, handleCancel)}
575 {I18NextService.i18n.t("cancel")}
584 renderSuggestedTitleCopy() {
585 switch (this.state.metadataRes.state) {
589 const suggestedTitle = this.state.metadataRes.data.metadata.title;
594 className="mt-1 text-muted small font-weight-bold pointer"
597 { i: this, suggestedTitle },
601 {I18NextService.i18n.t("copy_suggested_title", { title: "" })}{" "}
610 renderSuggestedPosts() {
611 switch (this.state.suggestedPostsRes.state) {
615 const suggestedPosts = this.state.suggestedPostsRes.data.posts;
619 suggestedPosts.length > 0 && (
621 <div className="my-1 text-muted small font-weight-bold">
622 {I18NextService.i18n.t("related_posts")}
626 posts={suggestedPosts}
627 enableDownvotes={this.props.enableDownvotes}
628 enableNsfw={this.props.enableNsfw}
629 allLanguages={this.props.allLanguages}
630 siteLanguages={this.props.siteLanguages}
632 // All of these are unused, since its view only
633 onPostEdit={() => {}}
634 onPostVote={() => {}}
635 onPostReport={() => {}}
636 onBlockPerson={() => {}}
637 onLockPost={() => {}}
638 onDeletePost={() => {}}
639 onRemovePost={() => {}}
640 onSavePost={() => {}}
641 onFeaturePost={() => {}}
642 onPurgePerson={() => {}}
643 onPurgePost={() => {}}
644 onBanPersonFromCommunity={() => {}}
645 onBanPerson={() => {}}
646 onAddModToCommunity={() => {}}
647 onAddAdmin={() => {}}
648 onTransferCommunity={() => {}}
657 async fetchPageTitle() {
658 const url = this.state.form.url;
659 if (url && validURL(url)) {
660 this.setState({ metadataRes: { state: "loading" } });
662 metadataRes: await HttpService.client.getSiteMetadata({ url }),
667 async fetchSimilarPosts() {
668 const q = this.state.form.name;
670 this.setState({ suggestedPostsRes: { state: "loading" } });
672 suggestedPostsRes: await HttpService.client.search({
677 community_id: this.state.form.community_id,
679 limit: trendingFetchLimit,
686 handlePostBodyChange(val: string) {
687 this.setState(s => ((s.form.body = val), s));
690 handleLanguageChange(val: number[]) {
691 this.setState(s => ((s.form.language_id = val.at(0)), s));
694 handleCommunitySearch = debounce(async (text: string) => {
695 const { selectedCommunityChoice } = this.props;
696 this.setState({ communitySearchLoading: true });
698 const newOptions: Choice[] = [];
700 if (selectedCommunityChoice) {
701 newOptions.push(selectedCommunityChoice);
704 if (text.length > 0) {
705 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
708 communitySearchOptions: newOptions,
713 communitySearchLoading: false,
717 handleCommunitySelect(choice: Choice) {
718 if (this.props.onSelectCommunity) {
719 this.props.onSelectCommunity(choice);