1 import autosize from "autosize";
2 import { Component, linkEvent } from "inferno";
3 import { Prompt } from "inferno-router";
15 } from "lemmy-js-client";
16 import { Subscription } from "rxjs";
17 import { i18n } from "../../i18next";
18 import { PostFormParams } from "../../interfaces";
19 import { UserService, WebSocketService } from "../../services";
23 capitalizeFirstLetter,
32 myFirstDiscussionLanguageId,
45 import { Icon, Spinner } from "../common/icon";
46 import { LanguageSelect } from "../common/language-select";
47 import { MarkdownTextArea } from "../common/markdown-textarea";
48 import { SearchableSelect } from "../common/searchable-select";
49 import { PostListings } from "./post-listings";
51 const MAX_POST_TITLE_LENGTH = 200;
53 interface PostFormProps {
54 post_view?: PostView; // If a post is given, that means this is an edit
55 allLanguages: Language[];
56 siteLanguages: number[];
57 params?: PostFormParams;
59 onCreate?(post: PostView): any;
60 onEdit?(post: PostView): any;
62 enableDownvotes?: boolean;
63 selectedCommunityChoice?: Choice;
64 onSelectCommunity?: (choice: Choice) => void;
67 interface PostFormState {
74 community_id?: number;
77 suggestedTitle?: string;
78 suggestedPosts?: PostView[];
79 crossPosts?: PostView[];
81 imageLoading: boolean;
82 communitySearchLoading: boolean;
83 communitySearchOptions: Choice[];
87 export class PostForm extends Component<PostFormProps, PostFormState> {
88 private subscription?: Subscription;
89 state: PostFormState = {
93 communitySearchLoading: false,
95 communitySearchOptions: [],
98 constructor(props: PostFormProps, context: any) {
99 super(props, context);
100 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts.bind(this));
101 this.fetchPageTitle = debounce(this.fetchPageTitle.bind(this));
102 this.handlePostBodyChange = this.handlePostBodyChange.bind(this);
103 this.handleLanguageChange = this.handleLanguageChange.bind(this);
104 this.handleCommunitySelect = this.handleCommunitySelect.bind(this);
106 this.parseMessage = this.parseMessage.bind(this);
107 this.subscription = wsSubscribe(this.parseMessage);
110 const pv = this.props.post_view;
117 community_id: pv.community.id,
120 language_id: pv.post.language_id,
125 const selectedCommunityChoice = this.props.selectedCommunityChoice;
127 if (selectedCommunityChoice) {
132 community_id: getIdFromString(selectedCommunityChoice.value),
134 communitySearchOptions: [selectedCommunityChoice],
138 const params = this.props.params;
150 componentDidMount() {
152 const textarea: any = document.getElementById("post-title");
159 componentDidUpdate() {
161 !this.state.loading &&
162 (this.state.form.name || this.state.form.url || this.state.form.body)
164 window.onbeforeunload = () => true;
166 window.onbeforeunload = null;
170 componentWillUnmount() {
171 this.subscription?.unsubscribe();
172 /* this.choices && this.choices.destroy(); */
173 window.onbeforeunload = null;
176 static getDerivedStateFromProps(
177 { selectedCommunityChoice }: PostFormProps,
178 { form, ...restState }: PostFormState
184 community_id: getIdFromString(selectedCommunityChoice?.value),
191 this.state.form.language_id ??
192 myFirstDiscussionLanguageId(
193 this.props.allLanguages,
194 this.props.siteLanguages,
195 UserService.Instance.myUserInfo
197 let selectedLangs = firstLang ? Array.of(firstLang) : undefined;
199 let url = this.state.form.url;
204 !this.state.loading &&
205 (this.state.form.name ||
206 this.state.form.url ||
207 this.state.form.body)
209 message={i18n.t("block_leaving")}
211 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
212 <div className="form-group row">
213 <label className="col-sm-2 col-form-label" htmlFor="post-url">
216 <div className="col-sm-10">
220 className="form-control"
221 value={this.state.form.url}
222 onInput={linkEvent(this, this.handlePostUrlChange)}
223 onPaste={linkEvent(this, this.handleImageUploadPaste)}
225 {this.state.suggestedTitle && (
227 className="mt-1 text-muted small font-weight-bold pointer"
229 onClick={linkEvent(this, this.copySuggestedTitle)}
231 {i18n.t("copy_suggested_title", { title: "" })}{" "}
232 {this.state.suggestedTitle}
237 htmlFor="file-upload"
239 UserService.Instance.myUserInfo && "pointer"
240 } d-inline-block float-right text-muted font-weight-bold`}
241 data-tippy-content={i18n.t("upload_image")}
243 <Icon icon="image" classes="icon-inline" />
248 accept="image/*,video/*"
251 disabled={!UserService.Instance.myUserInfo}
252 onChange={linkEvent(this, this.handleImageUpload)}
255 {url && validURL(url) && (
258 href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
259 className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
262 archive.org {i18n.t("archive_link")}
265 href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
268 className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
271 ghostarchive.org {i18n.t("archive_link")}
274 href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
277 className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
280 archive.today {i18n.t("archive_link")}
284 {this.state.imageLoading && <Spinner />}
285 {url && isImage(url) && (
286 <img src={url} className="img-fluid" alt="" />
288 {this.state.crossPosts && this.state.crossPosts.length > 0 && (
290 <div className="my-1 text-muted small font-weight-bold">
291 {i18n.t("cross_posts")}
295 posts={this.state.crossPosts}
296 enableDownvotes={this.props.enableDownvotes}
297 enableNsfw={this.props.enableNsfw}
298 allLanguages={this.props.allLanguages}
299 siteLanguages={this.props.siteLanguages}
305 <div className="form-group row">
306 <label className="col-sm-2 col-form-label" htmlFor="post-title">
309 <div className="col-sm-10">
311 value={this.state.form.name}
313 onInput={linkEvent(this, this.handlePostNameChange)}
314 className={`form-control ${
315 !validTitle(this.state.form.name) && "is-invalid"
320 maxLength={MAX_POST_TITLE_LENGTH}
322 {!validTitle(this.state.form.name) && (
323 <div className="invalid-feedback">
324 {i18n.t("invalid_post_title")}
327 {this.state.suggestedPosts &&
328 this.state.suggestedPosts.length > 0 && (
330 <div className="my-1 text-muted small font-weight-bold">
331 {i18n.t("related_posts")}
335 posts={this.state.suggestedPosts}
336 enableDownvotes={this.props.enableDownvotes}
337 enableNsfw={this.props.enableNsfw}
338 allLanguages={this.props.allLanguages}
339 siteLanguages={this.props.siteLanguages}
346 <div className="form-group row">
347 <label className="col-sm-2 col-form-label">{i18n.t("body")}</label>
348 <div className="col-sm-10">
350 initialContent={this.state.form.body}
351 onContentChange={this.handlePostBodyChange}
352 allLanguages={this.props.allLanguages}
353 siteLanguages={this.props.siteLanguages}
357 {!this.props.post_view && (
358 <div className="form-group row">
360 className="col-sm-2 col-form-label"
361 htmlFor="post-community"
363 {i18n.t("community")}
365 <div className="col-sm-10">
368 value={this.state.form.community_id}
371 label: i18n.t("select_a_community"),
375 ].concat(this.state.communitySearchOptions)}
376 loading={this.state.communitySearchLoading}
377 onChange={this.handleCommunitySelect}
378 onSearch={this.handleCommunitySearch}
383 {this.props.enableNsfw && (
384 <div className="form-group row">
385 <legend className="col-form-label col-sm-2 pt-0">
388 <div className="col-sm-10">
389 <div className="form-check">
391 className="form-check-input position-static"
394 checked={this.state.form.nsfw}
395 onChange={linkEvent(this, this.handlePostNsfwChange)}
402 allLanguages={this.props.allLanguages}
403 siteLanguages={this.props.siteLanguages}
404 selectedLanguageIds={selectedLangs}
406 onChange={this.handleLanguageChange}
413 className="form-control honeypot"
415 value={this.state.form.honeypot}
416 onInput={linkEvent(this, this.handleHoneyPotChange)}
418 <div className="form-group row">
419 <div className="col-sm-10">
421 disabled={!this.state.form.community_id || this.state.loading}
423 className="btn btn-secondary mr-2"
425 {this.state.loading ? (
427 ) : this.props.post_view ? (
428 capitalizeFirstLetter(i18n.t("save"))
430 capitalizeFirstLetter(i18n.t("create"))
433 {this.props.post_view && (
436 className="btn btn-secondary"
437 onClick={linkEvent(this, this.handleCancel)}
449 handlePostSubmit(i: PostForm, event: any) {
450 event.preventDefault();
452 i.setState({ loading: true });
454 // Coerce empty url string to undefined
455 if ((i.state.form.url ?? "blank") === "") {
456 i.setState(s => ((s.form.url = undefined), s));
459 let pForm = i.state.form;
460 let pv = i.props.post_view;
464 let form: EditPost = {
470 language_id: pv.post.language_id,
473 WebSocketService.Instance.send(wsClient.editPost(form));
475 if (pForm.name && pForm.community_id) {
476 let form: CreatePost = {
478 community_id: pForm.community_id,
482 language_id: pForm.language_id,
483 honeypot: pForm.honeypot,
486 WebSocketService.Instance.send(wsClient.createPost(form));
492 copySuggestedTitle(i: PostForm) {
493 let sTitle = i.state.suggestedTitle;
496 s => ((s.form.name = sTitle?.substring(0, MAX_POST_TITLE_LENGTH)), s)
498 i.setState({ suggestedTitle: undefined });
500 let textarea: any = document.getElementById("post-title");
501 autosize.update(textarea);
506 handlePostUrlChange(i: PostForm, event: any) {
507 i.setState(s => ((s.form.url = event.target.value), s));
512 let url = this.state.form.url;
513 if (url && validURL(url)) {
520 limit: trendingFetchLimit,
524 WebSocketService.Instance.send(wsClient.search(form));
526 // Fetch the page title
527 getSiteMetadata(url).then(d => {
528 this.setState({ suggestedTitle: d.metadata.title });
531 this.setState({ suggestedTitle: undefined, crossPosts: undefined });
535 handlePostNameChange(i: PostForm, event: any) {
536 i.setState(s => ((s.form.name = event.target.value), s));
537 i.fetchSimilarPosts();
540 fetchSimilarPosts() {
541 let q = this.state.form.name;
548 community_id: this.state.form.community_id,
550 limit: trendingFetchLimit,
554 WebSocketService.Instance.send(wsClient.search(form));
556 this.setState({ suggestedPosts: undefined });
560 handlePostBodyChange(val: string) {
561 this.setState(s => ((s.form.body = val), s));
564 handlePostCommunityChange(i: PostForm, event: any) {
565 i.setState(s => ((s.form.community_id = Number(event.target.value)), s));
568 handlePostNsfwChange(i: PostForm, event: any) {
569 i.setState(s => ((s.form.nsfw = event.target.checked), s));
572 handleLanguageChange(val: number[]) {
573 this.setState(s => ((s.form.language_id = val.at(0)), s));
576 handleHoneyPotChange(i: PostForm, event: any) {
577 i.setState(s => ((s.form.honeypot = event.target.value), s));
580 handleCancel(i: PostForm) {
581 i.props.onCancel?.();
584 handlePreviewToggle(i: PostForm, event: any) {
585 event.preventDefault();
586 i.setState({ previewMode: !i.state.previewMode });
589 handleImageUploadPaste(i: PostForm, event: any) {
590 let image = event.clipboardData.files[0];
592 i.handleImageUpload(i, image);
596 handleImageUpload(i: PostForm, event: any) {
599 event.preventDefault();
600 file = event.target.files[0];
605 i.setState({ imageLoading: true });
609 console.log("pictrs upload:");
611 if (res.msg === "ok") {
612 i.state.form.url = res.url;
613 i.setState({ imageLoading: false });
614 pictrsDeleteToast(file.name, res.delete_url as string);
616 i.setState({ imageLoading: false });
617 toast(JSON.stringify(res), "danger");
621 i.setState({ imageLoading: false });
622 console.error(error);
623 toast(error, "danger");
627 handleCommunitySearch = debounce(async (text: string) => {
628 const { selectedCommunityChoice } = this.props;
629 this.setState({ communitySearchLoading: true });
631 const newOptions: Choice[] = [];
633 if (selectedCommunityChoice) {
634 newOptions.push(selectedCommunityChoice);
637 if (text.length > 0) {
639 ...(await fetchCommunities(text)).communities.map(communityToChoice)
643 communitySearchOptions: newOptions,
648 communitySearchLoading: false,
652 handleCommunitySelect(choice: Choice) {
653 if (this.props.onSelectCommunity) {
658 this.props.onSelectCommunity(choice);
660 this.setState({ loading: false });
664 parseMessage(msg: any) {
665 let mui = UserService.Instance.myUserInfo;
666 let op = wsUserOp(msg);
669 // Errors handled by top level pages
670 // toast(i18n.t(msg.error), "danger");
671 this.setState({ loading: false });
673 } else if (op == UserOperation.CreatePost) {
674 let data = wsJsonToRes<PostResponse>(msg);
675 if (data.post_view.creator.id == mui?.local_user_view.person.id) {
676 this.props.onCreate?.(data.post_view);
678 } else if (op == UserOperation.EditPost) {
679 let data = wsJsonToRes<PostResponse>(msg);
680 if (data.post_view.creator.id == mui?.local_user_view.person.id) {
681 this.setState({ loading: false });
682 this.props.onEdit?.(data.post_view);
684 } else if (op == UserOperation.Search) {
685 let data = wsJsonToRes<SearchResponse>(msg);
687 if (data.type_ == "Posts") {
688 this.setState({ suggestedPosts: data.posts });
689 } else if (data.type_ == "Url") {
690 this.setState({ crossPosts: data.posts });