1 import autosize from "autosize";
2 import { Component, linkEvent } from "inferno";
14 } from "lemmy-js-client";
15 import { Subscription } from "rxjs";
16 import { i18n } from "../../i18next";
17 import { PostFormParams } from "../../interfaces";
18 import { UserService, WebSocketService } from "../../services";
22 capitalizeFirstLetter,
43 import { Icon, Spinner } from "../common/icon";
44 import { LanguageSelect } from "../common/language-select";
45 import { MarkdownTextArea } from "../common/markdown-textarea";
46 import NavigationPrompt from "../common/navigation-prompt";
47 import { SearchableSelect } from "../common/searchable-select";
48 import { PostListings } from "./post-listings";
50 const MAX_POST_TITLE_LENGTH = 200;
52 interface PostFormProps {
53 post_view?: PostView; // If a post is given, that means this is an edit
54 allLanguages: Language[];
55 siteLanguages: number[];
56 params?: PostFormParams;
58 onCreate?(post: PostView): any;
59 onEdit?(post: PostView): any;
61 enableDownvotes?: boolean;
62 selectedCommunityChoice?: Choice;
63 onSelectCommunity?: (choice: Choice) => void;
66 interface PostFormState {
73 community_id?: number;
76 suggestedTitle?: string;
77 suggestedPosts?: PostView[];
78 crossPosts?: PostView[];
80 imageLoading: boolean;
81 communitySearchLoading: boolean;
82 communitySearchOptions: Choice[];
86 export class PostForm extends Component<PostFormProps, PostFormState> {
87 private subscription?: Subscription;
88 state: PostFormState = {
92 communitySearchLoading: false,
94 communitySearchOptions: [],
97 constructor(props: PostFormProps, context: any) {
98 super(props, context);
99 this.fetchSimilarPosts = debounce(this.fetchSimilarPosts.bind(this));
100 this.fetchPageTitle = debounce(this.fetchPageTitle.bind(this));
101 this.handlePostBodyChange = this.handlePostBodyChange.bind(this);
102 this.handleLanguageChange = this.handleLanguageChange.bind(this);
103 this.handleCommunitySelect = this.handleCommunitySelect.bind(this);
105 this.parseMessage = this.parseMessage.bind(this);
106 this.subscription = wsSubscribe(this.parseMessage);
109 const pv = this.props.post_view;
116 community_id: pv.community.id,
119 language_id: pv.post.language_id,
124 const selectedCommunityChoice = this.props.selectedCommunityChoice;
126 if (selectedCommunityChoice) {
131 community_id: getIdFromString(selectedCommunityChoice.value),
133 communitySearchOptions: [selectedCommunityChoice],
137 const params = this.props.params;
149 componentDidMount() {
151 const textarea: any = document.getElementById("post-title");
158 componentDidUpdate() {
160 !this.state.loading &&
161 (this.state.form.name || this.state.form.url || this.state.form.body)
163 window.onbeforeunload = () => true;
165 window.onbeforeunload = null;
169 componentWillUnmount() {
170 this.subscription?.unsubscribe();
171 /* this.choices && this.choices.destroy(); */
172 window.onbeforeunload = null;
175 static getDerivedStateFromProps(
176 { selectedCommunityChoice }: PostFormProps,
177 { form, ...restState }: PostFormState
183 community_id: getIdFromString(selectedCommunityChoice?.value),
189 const firstLang = this.state.form.language_id;
190 const selectedLangs = firstLang ? Array.of(firstLang) : undefined;
192 const url = this.state.form.url;
197 !this.state.loading &&
199 this.state.form.name ||
200 this.state.form.url ||
205 <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
206 <div className="form-group row">
207 <label className="col-sm-2 col-form-label" htmlFor="post-url">
210 <div className="col-sm-10">
214 className="form-control"
215 value={this.state.form.url}
216 onInput={linkEvent(this, this.handlePostUrlChange)}
217 onPaste={linkEvent(this, this.handleImageUploadPaste)}
219 {this.state.suggestedTitle && (
221 className="mt-1 text-muted small font-weight-bold pointer"
223 onClick={linkEvent(this, this.copySuggestedTitle)}
225 {i18n.t("copy_suggested_title", { title: "" })}{" "}
226 {this.state.suggestedTitle}
231 htmlFor="file-upload"
233 UserService.Instance.myUserInfo && "pointer"
234 } d-inline-block float-right text-muted font-weight-bold`}
235 data-tippy-content={i18n.t("upload_image")}
237 <Icon icon="image" classes="icon-inline" />
242 accept="image/*,video/*"
245 disabled={!UserService.Instance.myUserInfo}
246 onChange={linkEvent(this, this.handleImageUpload)}
249 {url && validURL(url) && (
252 href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
253 className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
256 archive.org {i18n.t("archive_link")}
259 href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
262 className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
265 ghostarchive.org {i18n.t("archive_link")}
268 href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
271 className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
274 archive.today {i18n.t("archive_link")}
278 {this.state.imageLoading && <Spinner />}
279 {url && isImage(url) && (
280 <img src={url} className="img-fluid" alt="" />
282 {this.state.crossPosts && this.state.crossPosts.length > 0 && (
284 <div className="my-1 text-muted small font-weight-bold">
285 {i18n.t("cross_posts")}
289 posts={this.state.crossPosts}
290 enableDownvotes={this.props.enableDownvotes}
291 enableNsfw={this.props.enableNsfw}
292 allLanguages={this.props.allLanguages}
293 siteLanguages={this.props.siteLanguages}
299 <div className="form-group row">
300 <label className="col-sm-2 col-form-label" htmlFor="post-title">
303 <div className="col-sm-10">
305 value={this.state.form.name}
307 onInput={linkEvent(this, this.handlePostNameChange)}
308 className={`form-control ${
309 !validTitle(this.state.form.name) && "is-invalid"
314 maxLength={MAX_POST_TITLE_LENGTH}
316 {!validTitle(this.state.form.name) && (
317 <div className="invalid-feedback">
318 {i18n.t("invalid_post_title")}
321 {this.state.suggestedPosts &&
322 this.state.suggestedPosts.length > 0 && (
324 <div className="my-1 text-muted small font-weight-bold">
325 {i18n.t("related_posts")}
329 posts={this.state.suggestedPosts}
330 enableDownvotes={this.props.enableDownvotes}
331 enableNsfw={this.props.enableNsfw}
332 allLanguages={this.props.allLanguages}
333 siteLanguages={this.props.siteLanguages}
340 <div className="form-group row">
341 <label className="col-sm-2 col-form-label">{i18n.t("body")}</label>
342 <div className="col-sm-10">
344 initialContent={this.state.form.body}
345 onContentChange={this.handlePostBodyChange}
346 allLanguages={this.props.allLanguages}
347 siteLanguages={this.props.siteLanguages}
351 {!this.props.post_view && (
352 <div className="form-group row">
354 className="col-sm-2 col-form-label"
355 htmlFor="post-community"
357 {i18n.t("community")}
359 <div className="col-sm-10">
362 value={this.state.form.community_id}
365 label: i18n.t("select_a_community"),
369 ].concat(this.state.communitySearchOptions)}
370 loading={this.state.communitySearchLoading}
371 onChange={this.handleCommunitySelect}
372 onSearch={this.handleCommunitySearch}
377 {this.props.enableNsfw && (
378 <div className="form-group row">
379 <legend className="col-form-label col-sm-2 pt-0">
382 <div className="col-sm-10">
383 <div className="form-check">
385 className="form-check-input position-static"
388 checked={this.state.form.nsfw}
389 onChange={linkEvent(this, this.handlePostNsfwChange)}
396 allLanguages={this.props.allLanguages}
397 siteLanguages={this.props.siteLanguages}
398 selectedLanguageIds={selectedLangs}
400 onChange={this.handleLanguageChange}
407 className="form-control honeypot"
409 value={this.state.form.honeypot}
410 onInput={linkEvent(this, this.handleHoneyPotChange)}
412 <div className="form-group row">
413 <div className="col-sm-10">
415 disabled={!this.state.form.community_id || this.state.loading}
417 className="btn btn-secondary mr-2"
419 {this.state.loading ? (
421 ) : this.props.post_view ? (
422 capitalizeFirstLetter(i18n.t("save"))
424 capitalizeFirstLetter(i18n.t("create"))
427 {this.props.post_view && (
430 className="btn btn-secondary"
431 onClick={linkEvent(this, this.handleCancel)}
443 handlePostSubmit(i: PostForm, event: any) {
444 event.preventDefault();
446 i.setState({ loading: true });
448 // Coerce empty url string to undefined
449 if ((i.state.form.url ?? "blank") === "") {
450 i.setState(s => ((s.form.url = undefined), s));
453 const pForm = i.state.form;
454 const pv = i.props.post_view;
455 const auth = myAuth();
458 const form: EditPost = {
464 language_id: pForm.language_id,
467 WebSocketService.Instance.send(wsClient.editPost(form));
469 if (pForm.name && pForm.community_id) {
470 const form: CreatePost = {
472 community_id: pForm.community_id,
476 language_id: pForm.language_id,
477 honeypot: pForm.honeypot,
480 WebSocketService.Instance.send(wsClient.createPost(form));
486 copySuggestedTitle(i: PostForm) {
487 const sTitle = i.state.suggestedTitle;
490 s => ((s.form.name = sTitle?.substring(0, MAX_POST_TITLE_LENGTH)), s)
492 i.setState({ suggestedTitle: undefined });
494 const textarea: any = document.getElementById("post-title");
495 autosize.update(textarea);
500 handlePostUrlChange(i: PostForm, event: any) {
501 i.setState(s => ((s.form.url = event.target.value), s));
506 const url = this.state.form.url;
507 if (url && validURL(url)) {
508 const form: Search = {
514 limit: trendingFetchLimit,
518 WebSocketService.Instance.send(wsClient.search(form));
520 // Fetch the page title
521 getSiteMetadata(url).then(d => {
522 this.setState({ suggestedTitle: d.metadata.title });
525 this.setState({ suggestedTitle: undefined, crossPosts: undefined });
529 handlePostNameChange(i: PostForm, event: any) {
530 i.setState(s => ((s.form.name = event.target.value), s));
531 i.fetchSimilarPosts();
534 fetchSimilarPosts() {
535 const q = this.state.form.name;
537 const form: Search = {
542 community_id: this.state.form.community_id,
544 limit: trendingFetchLimit,
548 WebSocketService.Instance.send(wsClient.search(form));
550 this.setState({ suggestedPosts: undefined });
554 handlePostBodyChange(val: string) {
555 this.setState(s => ((s.form.body = val), s));
558 handlePostCommunityChange(i: PostForm, event: any) {
559 i.setState(s => ((s.form.community_id = Number(event.target.value)), s));
562 handlePostNsfwChange(i: PostForm, event: any) {
563 i.setState(s => ((s.form.nsfw = event.target.checked), s));
566 handleLanguageChange(val: number[]) {
567 this.setState(s => ((s.form.language_id = val.at(0)), s));
570 handleHoneyPotChange(i: PostForm, event: any) {
571 i.setState(s => ((s.form.honeypot = event.target.value), s));
574 handleCancel(i: PostForm) {
575 i.props.onCancel?.();
578 handlePreviewToggle(i: PostForm, event: any) {
579 event.preventDefault();
580 i.setState({ previewMode: !i.state.previewMode });
583 handleImageUploadPaste(i: PostForm, event: any) {
584 const image = event.clipboardData.files[0];
586 i.handleImageUpload(i, image);
590 handleImageUpload(i: PostForm, event: any) {
593 event.preventDefault();
594 file = event.target.files[0];
599 i.setState({ imageLoading: true });
603 console.log("pictrs upload:");
605 if (res.msg === "ok") {
606 i.state.form.url = res.url;
607 i.setState({ imageLoading: false });
608 pictrsDeleteToast(file.name, res.delete_url as string);
610 i.setState({ imageLoading: false });
611 toast(JSON.stringify(res), "danger");
615 i.setState({ imageLoading: false });
616 console.error(error);
617 toast(error, "danger");
621 handleCommunitySearch = debounce(async (text: string) => {
622 const { selectedCommunityChoice } = this.props;
623 this.setState({ communitySearchLoading: true });
625 const newOptions: Choice[] = [];
627 if (selectedCommunityChoice) {
628 newOptions.push(selectedCommunityChoice);
631 if (text.length > 0) {
633 ...(await fetchCommunities(text)).communities.map(communityToChoice)
637 communitySearchOptions: newOptions,
642 communitySearchLoading: false,
646 handleCommunitySelect(choice: Choice) {
647 if (this.props.onSelectCommunity) {
648 this.props.onSelectCommunity(choice);
652 parseMessage(msg: any) {
653 const mui = UserService.Instance.myUserInfo;
654 const op = wsUserOp(msg);
657 // Errors handled by top level pages
658 // toast(i18n.t(msg.error), "danger");
659 this.setState({ loading: false });
661 } else if (op == UserOperation.CreatePost) {
662 const data = wsJsonToRes<PostResponse>(msg);
663 if (data.post_view.creator.id == mui?.local_user_view.person.id) {
664 this.props.onCreate?.(data.post_view);
666 } else if (op == UserOperation.EditPost) {
667 const data = wsJsonToRes<PostResponse>(msg);
668 if (data.post_view.creator.id == mui?.local_user_view.person.id) {
669 this.setState({ loading: false });
670 this.props.onEdit?.(data.post_view);
672 } else if (op == UserOperation.Search) {
673 const data = wsJsonToRes<SearchResponse>(msg);
675 if (data.type_ == "Posts") {
676 this.setState({ suggestedPosts: data.posts });
677 } else if (data.type_ == "Url") {
678 this.setState({ crossPosts: data.posts });