]> Untitled Git - lemmy-ui.git/blobdiff - src/shared/components/post/post-form.tsx
reset, merge issues
[lemmy-ui.git] / src / shared / components / post / post-form.tsx
index 133af94521032d11db98e107af9e0a88ad90a452..c21a6e2b8e7c189e654f232fa3b4662f8f6cdb26 100644 (file)
 import autosize from "autosize";
-import { Component, linkEvent } from "inferno";
-import { Prompt } from "inferno-router";
+import { Component, InfernoNode, linkEvent } from "inferno";
 import {
   CommunityView,
   CreatePost,
   EditPost,
-  ListingType,
-  PostResponse,
+  GetSiteMetadataResponse,
+  Language,
   PostView,
-  Search,
   SearchResponse,
-  SearchType,
-  SortType,
-  UserOperation,
 } from "lemmy-js-client";
-import { Subscription } from "rxjs";
-import { pictrsUri } from "../../env";
 import { i18n } from "../../i18next";
 import { PostFormParams } from "../../interfaces";
-import { UserService, WebSocketService } from "../../services";
+import { UserService } from "../../services";
+import { HttpService, RequestState } from "../../services/HttpService";
 import {
+  Choice,
   archiveTodayUrl,
-  authField,
   capitalizeFirstLetter,
-  choicesConfig,
-  communitySelectName,
   communityToChoice,
-  debounce,
   fetchCommunities,
-  getSiteMetadata,
+  getIdFromString,
   ghostArchiveUrl,
-  isBrowser,
   isImage,
-  pictrsDeleteToast,
+  myAuth,
+  myAuthRequired,
+  relTags,
   setupTippy,
   toast,
+  trendingFetchLimit,
   validTitle,
   validURL,
   webArchiveUrl,
-  wsClient,
-  wsJsonToRes,
-  wsSubscribe,
-  wsUserOp,
 } from "../../utils";
+import { debounce } from "../../utils/helpers/debounce";
 import { Icon, Spinner } from "../common/icon";
+import { LanguageSelect } from "../common/language-select";
 import { MarkdownTextArea } from "../common/markdown-textarea";
+import NavigationPrompt from "../common/navigation-prompt";
+import { SearchableSelect } from "../common/searchable-select";
 import { PostListings } from "./post-listings";
 
-var Choices: any;
-if (isBrowser()) {
-  Choices = require("choices.js");
-}
-
 const MAX_POST_TITLE_LENGTH = 200;
 
 interface PostFormProps {
   post_view?: PostView; // If a post is given, that means this is an edit
-  communities?: CommunityView[];
+  crossPosts?: PostView[];
+  allLanguages: Language[];
+  siteLanguages: number[];
   params?: PostFormParams;
-  onCancel?(): any;
-  onCreate?(post: PostView): any;
-  onEdit?(post: PostView): any;
-  enableNsfw: boolean;
-  enableDownvotes: boolean;
+  onCancel?(): void;
+  onCreate?(form: CreatePost): void;
+  onEdit?(form: EditPost): void;
+  enableNsfw?: boolean;
+  enableDownvotes?: boolean;
+  selectedCommunityChoice?: Choice;
+  onSelectCommunity?: (choice: Choice) => void;
+  initialCommunities?: CommunityView[];
 }
 
 interface PostFormState {
-  postForm: CreatePost;
+  form: {
+    name?: string;
+    url?: string;
+    body?: string;
+    nsfw?: boolean;
+    language_id?: number;
+    community_id?: number;
+    honeypot?: string;
+  };
   loading: boolean;
+  suggestedPostsRes: RequestState<SearchResponse>;
+  metadataRes: RequestState<GetSiteMetadataResponse>;
   imageLoading: boolean;
+  imageDeleteUrl: string;
+  communitySearchLoading: boolean;
+  communitySearchOptions: Choice[];
   previewMode: boolean;
-  suggestedTitle: string;
-  suggestedPosts: PostView[];
-  crossPosts: PostView[];
+  submitted: boolean;
 }
 
 export class PostForm extends Component<PostFormProps, PostFormState> {
-  private subscription: Subscription;
-  private choices: any;
-  private emptyState: PostFormState = {
-    postForm: {
-      community_id: null,
-      name: null,
-      nsfw: false,
-      auth: authField(false),
-    },
+  state: PostFormState = {
+    suggestedPostsRes: { state: "empty" },
+    metadataRes: { state: "empty" },
+    form: {},
     loading: false,
     imageLoading: false,
+    imageDeleteUrl: "",
+    communitySearchLoading: false,
     previewMode: false,
-    suggestedTitle: undefined,
-    suggestedPosts: [],
-    crossPosts: [],
+    communitySearchOptions: [],
+    submitted: false,
   };
 
-  constructor(props: any, context: any) {
+  constructor(props: PostFormProps, context: any) {
     super(props, context);
     this.fetchSimilarPosts = debounce(this.fetchSimilarPosts.bind(this));
     this.fetchPageTitle = debounce(this.fetchPageTitle.bind(this));
     this.handlePostBodyChange = this.handlePostBodyChange.bind(this);
+    this.handleLanguageChange = this.handleLanguageChange.bind(this);
+    this.handleCommunitySelect = this.handleCommunitySelect.bind(this);
 
-    this.state = this.emptyState;
+    const { post_view, selectedCommunityChoice, params } = this.props;
 
     // Means its an edit
-    if (this.props.post_view) {
-      this.state.postForm = {
-        body: this.props.post_view.post.body,
-        name: this.props.post_view.post.name,
-        community_id: this.props.post_view.community.id,
-        url: this.props.post_view.post.url,
-        nsfw: this.props.post_view.post.nsfw,
-        auth: authField(),
+    if (post_view) {
+      this.state = {
+        ...this.state,
+        form: {
+          body: post_view.post.body,
+          name: post_view.post.name,
+          community_id: post_view.community.id,
+          url: post_view.post.url,
+          nsfw: post_view.post.nsfw,
+          language_id: post_view.post.language_id,
+        },
+      };
+    } else if (selectedCommunityChoice) {
+      this.state = {
+        ...this.state,
+        form: {
+          ...this.state.form,
+          community_id: getIdFromString(selectedCommunityChoice.value),
+        },
+        communitySearchOptions: [selectedCommunityChoice]
+          .concat(
+            this.props.initialCommunities?.map(
+              ({ community: { id, title } }) => ({
+                label: title,
+                value: id.toString(),
+              })
+            ) ?? []
+          )
+          .filter(option => option.value !== selectedCommunityChoice.value),
+      };
+    } else {
+      this.state = {
+        ...this.state,
+        communitySearchOptions:
+          this.props.initialCommunities?.map(
+            ({ community: { id, title } }) => ({
+              label: title,
+              value: id.toString(),
+            })
+          ) ?? [],
       };
     }
 
-    if (this.props.params) {
-      this.state.postForm.name = this.props.params.name;
-      if (this.props.params.url) {
-        this.state.postForm.url = this.props.params.url;
-      }
-      if (this.props.params.body) {
-        this.state.postForm.body = this.props.params.body;
-      }
+    if (params) {
+      this.state = {
+        ...this.state,
+        form: {
+          ...this.state.form,
+          ...params,
+        },
+      };
     }
-
-    this.parseMessage = this.parseMessage.bind(this);
-    this.subscription = wsSubscribe(this.parseMessage);
   }
 
   componentDidMount() {
     setupTippy();
-    this.setupCommunities();
-    let textarea: any = document.getElementById("post-title");
+    const textarea: any = document.getElementById("post-title");
+
     if (textarea) {
       autosize(textarea);
     }
   }
 
-  componentDidUpdate() {
-    if (
-      !this.state.loading &&
-      (this.state.postForm.name ||
-        this.state.postForm.url ||
-        this.state.postForm.body)
-    ) {
-      window.onbeforeunload = () => true;
-    } else {
-      window.onbeforeunload = undefined;
+  componentWillReceiveProps(
+    nextProps: Readonly<{ children?: InfernoNode } & PostFormProps>
+  ): void {
+    if (this.props != nextProps) {
+      this.setState(
+        s => (
+          (s.form.community_id = getIdFromString(
+            nextProps.selectedCommunityChoice?.value
+          )),
+          s
+        )
+      );
     }
   }
 
-  componentWillUnmount() {
-    this.subscription.unsubscribe();
-    /* this.choices && this.choices.destroy(); */
-    window.onbeforeunload = null;
-  }
-
   render() {
+    const firstLang = this.state.form.language_id;
+    const selectedLangs = firstLang ? Array.of(firstLang) : undefined;
+
+    const url = this.state.form.url;
+
+    // TODO
+    // const promptCheck =
+    // !!this.state.form.name || !!this.state.form.url || !!this.state.form.body;
+    // <Prompt when={promptCheck} message={i18n.t("block_leaving")} />
     return (
-      <div>
-        <Prompt
+      <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
+        <NavigationPrompt
           when={
-            !this.state.loading &&
-            (this.state.postForm.name ||
-              this.state.postForm.url ||
-              this.state.postForm.body)
+            !!(
+              this.state.form.name ||
+              this.state.form.url ||
+              this.state.form.body
+            ) && !this.state.submitted
           }
-          message={i18n.t("block_leaving")}
         />
-        <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
-          <div class="form-group row">
-            <label class="col-sm-2 col-form-label" htmlFor="post-url">
-              {i18n.t("url")}
-            </label>
-            <div class="col-sm-10">
+        <div className="form-group row">
+          <label className="col-sm-2 col-form-label" htmlFor="post-url">
+            {i18n.t("url")}
+          </label>
+          <div className="col-sm-10">
+            <input
+              type="url"
+              id="post-url"
+              className="form-control"
+              value={this.state.form.url}
+              onInput={linkEvent(this, this.handlePostUrlChange)}
+              onPaste={linkEvent(this, this.handleImageUploadPaste)}
+            />
+            {this.renderSuggestedTitleCopy()}
+            <form>
+              <label
+                htmlFor="file-upload"
+                className={`${
+                  UserService.Instance.myUserInfo && "pointer"
+                } d-inline-block float-right text-muted font-weight-bold`}
+                data-tippy-content={i18n.t("upload_image")}
+              >
+                <Icon icon="image" classes="icon-inline" />
+              </label>
               <input
-                type="url"
-                id="post-url"
-                class="form-control"
-                value={this.state.postForm.url}
-                onInput={linkEvent(this, this.handlePostUrlChange)}
-                onPaste={linkEvent(this, this.handleImageUploadPaste)}
+                id="file-upload"
+                type="file"
+                accept="image/*,video/*"
+                name="file"
+                className="d-none"
+                disabled={!UserService.Instance.myUserInfo}
+                onChange={linkEvent(this, this.handleImageUpload)}
               />
-              {this.state.suggestedTitle && (
-                <div
-                  class="mt-1 text-muted small font-weight-bold pointer"
-                  role="button"
-                  onClick={linkEvent(this, this.copySuggestedTitle)}
-                >
-                  {i18n.t("copy_suggested_title", {
-                    title: this.state.suggestedTitle,
-                  })}
-                </div>
-              )}
-              <form>
-                <label
-                  htmlFor="file-upload"
-                  className={`${
-                    UserService.Instance.myUserInfo && "pointer"
-                  } d-inline-block float-right text-muted font-weight-bold`}
-                  data-tippy-content={i18n.t("upload_image")}
-                >
-                  <Icon icon="image" classes="icon-inline" />
-                </label>
-                <input
-                  id="file-upload"
-                  type="file"
-                  accept="image/*,video/*"
-                  name="file"
-                  class="d-none"
-                  disabled={!UserService.Instance.myUserInfo}
-                  onChange={linkEvent(this, this.handleImageUpload)}
-                />
-              </form>
-              {this.state.postForm.url && validURL(this.state.postForm.url) && (
-                <div>
+            </form>
+            {url && validURL(url) && (
+              <div>
                 <a
-                  href={`${webArchiveUrl}/save/${encodeURIComponent(
-                    this.state.postForm.url
-                  )}`}
-                  class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
-                  rel="noopener"
+                  href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
+                  className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
+                  rel={relTags}
                 >
                   archive.org {i18n.t("archive_link")}
                 </a>
                 <a
                   href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
-                    this.state.postForm.url
+                    url
                   )}`}
-                  class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
-                  rel="noopener"
+                  className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
+                  rel={relTags}
                 >
                   ghostarchive.org {i18n.t("archive_link")}
                 </a>
                 <a
                   href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
-                    this.state.postForm.url
+                    url
                   )}`}
-                  class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
-                  rel="noopener"
+                  className="mr-2 d-inline-block float-right text-muted small font-weight-bold"
+                  rel={relTags}
                 >
-                 archive.today {i18n.t("archive_link")}
+                  archive.today {i18n.t("archive_link")}
                 </a>
+              </div>
+            )}
+            {this.state.imageLoading && <Spinner />}
+            {url && isImage(url) && (
+              <img src={url} className="img-fluid" alt="" />
+            )}
+            {this.state.imageDeleteUrl && (
+              <button
+                className="btn btn-danger btn-sm mt-2"
+                onClick={linkEvent(this, this.handleImageDelete)}
+                aria-label={i18n.t("delete")}
+                data-tippy-content={i18n.t("delete")}
+              >
+                <Icon icon="x" classes="icon-inline mr-1" />
+                {capitalizeFirstLetter(i18n.t("delete"))}
+              </button>
+            )}
+            {this.props.crossPosts && this.props.crossPosts.length > 0 && (
+              <>
+                <div className="my-1 text-muted small font-weight-bold">
+                  {i18n.t("cross_posts")}
                 </div>
-              )}
-              {this.state.imageLoading && <Spinner />}
-              {isImage(this.state.postForm.url) && (
-                <img src={this.state.postForm.url} class="img-fluid" alt="" />
-              )}
-              {this.state.crossPosts.length > 0 && (
-                <>
-                  <div class="my-1 text-muted small font-weight-bold">
-                    {i18n.t("cross_posts")}
-                  </div>
-                  <PostListings
-                    showCommunity
-                    posts={this.state.crossPosts}
-                    enableDownvotes={this.props.enableDownvotes}
-                    enableNsfw={this.props.enableNsfw}
-                  />
-                </>
-              )}
-            </div>
+                <PostListings
+                  showCommunity
+                  posts={this.props.crossPosts}
+                  enableDownvotes={this.props.enableDownvotes}
+                  enableNsfw={this.props.enableNsfw}
+                  allLanguages={this.props.allLanguages}
+                  siteLanguages={this.props.siteLanguages}
+                  viewOnly
+                  // All of these are unused, since its view only
+                  onPostEdit={() => {}}
+                  onPostVote={() => {}}
+                  onPostReport={() => {}}
+                  onBlockPerson={() => {}}
+                  onLockPost={() => {}}
+                  onDeletePost={() => {}}
+                  onRemovePost={() => {}}
+                  onSavePost={() => {}}
+                  onFeaturePost={() => {}}
+                  onPurgePerson={() => {}}
+                  onPurgePost={() => {}}
+                  onBanPersonFromCommunity={() => {}}
+                  onBanPerson={() => {}}
+                  onAddModToCommunity={() => {}}
+                  onAddAdmin={() => {}}
+                  onTransferCommunity={() => {}}
+                />
+              </>
+            )}
           </div>
-          <div class="form-group row">
-            <label class="col-sm-2 col-form-label" htmlFor="post-title">
-              {i18n.t("title")}
-            </label>
-            <div class="col-sm-10">
-              <textarea
-                value={this.state.postForm.name}
-                id="post-title"
-                onInput={linkEvent(this, this.handlePostNameChange)}
-                class={`form-control ${
-                  !validTitle(this.state.postForm.name) && "is-invalid"
-                }`}
-                required
-                rows={1}
-                minLength={3}
-                maxLength={MAX_POST_TITLE_LENGTH}
-              />
-              {!validTitle(this.state.postForm.name) && (
-                <div class="invalid-feedback">
-                  {i18n.t("invalid_post_title")}
-                </div>
-              )}
-              {this.state.suggestedPosts.length > 0 && (
-                <>
-                  <div class="my-1 text-muted small font-weight-bold">
-                    {i18n.t("related_posts")}
-                  </div>
-                  <PostListings
-                    posts={this.state.suggestedPosts}
-                    enableDownvotes={this.props.enableDownvotes}
-                    enableNsfw={this.props.enableNsfw}
-                  />
-                </>
-              )}
-            </div>
+        </div>
+        <div className="form-group row">
+          <label className="col-sm-2 col-form-label" htmlFor="post-title">
+            {i18n.t("title")}
+          </label>
+          <div className="col-sm-10">
+            <textarea
+              value={this.state.form.name}
+              id="post-title"
+              onInput={linkEvent(this, this.handlePostNameChange)}
+              className={`form-control ${
+                !validTitle(this.state.form.name) && "is-invalid"
+              }`}
+              required
+              rows={1}
+              minLength={3}
+              maxLength={MAX_POST_TITLE_LENGTH}
+            />
+            {!validTitle(this.state.form.name) && (
+              <div className="invalid-feedback">
+                {i18n.t("invalid_post_title")}
+              </div>
+            )}
+            {this.renderSuggestedPosts()}
           </div>
-
-          <div class="form-group row">
-            <label class="col-sm-2 col-form-label">{i18n.t("body")}</label>
-            <div class="col-sm-10">
-              <MarkdownTextArea
-                initialContent={this.state.postForm.body}
-                onContentChange={this.handlePostBodyChange}
+        </div>
+
+        <div className="form-group row">
+          <label className="col-sm-2 col-form-label">{i18n.t("body")}</label>
+          <div className="col-sm-10">
+            <MarkdownTextArea
+              initialContent={this.state.form.body}
+              onContentChange={this.handlePostBodyChange}
+              allLanguages={this.props.allLanguages}
+              siteLanguages={this.props.siteLanguages}
+              hideNavigationWarnings
+            />
+          </div>
+        </div>
+        {!this.props.post_view && (
+          <div className="form-group row">
+            <label className="col-sm-2 col-form-label" htmlFor="post-community">
+              {i18n.t("community")}
+            </label>
+            <div className="col-sm-10">
+              <SearchableSelect
+                id="post-community"
+                value={this.state.form.community_id}
+                options={[
+                  {
+                    label: i18n.t("select_a_community"),
+                    value: "",
+                    disabled: true,
+                  } as Choice,
+                ].concat(this.state.communitySearchOptions)}
+                loading={this.state.communitySearchLoading}
+                onChange={this.handleCommunitySelect}
+                onSearch={this.handleCommunitySearch}
               />
             </div>
           </div>
-          {!this.props.post_view && (
-            <div class="form-group row">
-              <label class="col-sm-2 col-form-label" htmlFor="post-community">
-                {i18n.t("community")}
-              </label>
-              <div class="col-sm-10">
-                <select
-                  class="form-control"
-                  id="post-community"
-                  value={this.state.postForm.community_id}
-                  onInput={linkEvent(this, this.handlePostCommunityChange)}
-                >
-                  <option>{i18n.t("select_a_community")}</option>
-                  {this.props.communities.map(cv => (
-                    <option value={cv.community.id}>
-                      {communitySelectName(cv)}
-                    </option>
-                  ))}
-                </select>
-              </div>
-            </div>
-          )}
-          {this.props.enableNsfw && (
-            <div class="form-group row">
-              <legend class="col-form-label col-sm-2 pt-0">
-                {i18n.t("nsfw")}
-              </legend>
-              <div class="col-sm-10">
-                <div class="form-check">
-                  <input
-                    class="form-check-input position-static"
-                    id="post-nsfw"
-                    type="checkbox"
-                    checked={this.state.postForm.nsfw}
-                    onChange={linkEvent(this, this.handlePostNsfwChange)}
-                  />
-                </div>
+        )}
+        {this.props.enableNsfw && (
+          <div className="form-group row">
+            <legend className="col-form-label col-sm-2 pt-0">
+              {i18n.t("nsfw")}
+            </legend>
+            <div className="col-sm-10">
+              <div className="form-check">
+                <input
+                  className="form-check-input position-static"
+                  id="post-nsfw"
+                  type="checkbox"
+                  checked={this.state.form.nsfw}
+                  onChange={linkEvent(this, this.handlePostNsfwChange)}
+                />
               </div>
             </div>
-          )}
-          <input
-            tabIndex={-1}
-            autoComplete="false"
-            name="a_password"
-            type="text"
-            class="form-control honeypot"
-            id="register-honey"
-            value={this.state.postForm.honeypot}
-            onInput={linkEvent(this, this.handleHoneyPotChange)}
-          />
-          <div class="form-group row">
-            <div class="col-sm-10">
+          </div>
+        )}
+        <LanguageSelect
+          allLanguages={this.props.allLanguages}
+          siteLanguages={this.props.siteLanguages}
+          selectedLanguageIds={selectedLangs}
+          multiple={false}
+          onChange={this.handleLanguageChange}
+        />
+        <input
+          tabIndex={-1}
+          autoComplete="false"
+          name="a_password"
+          type="text"
+          className="form-control honeypot"
+          id="register-honey"
+          value={this.state.form.honeypot}
+          onInput={linkEvent(this, this.handleHoneyPotChange)}
+        />
+        <div className="form-group row">
+          <div className="col-sm-10">
+            <button
+              disabled={!this.state.form.community_id || this.state.loading}
+              type="submit"
+              className="btn btn-secondary mr-2"
+            >
+              {this.state.loading ? (
+                <Spinner />
+              ) : this.props.post_view ? (
+                capitalizeFirstLetter(i18n.t("save"))
+              ) : (
+                capitalizeFirstLetter(i18n.t("create"))
+              )}
+            </button>
+            {this.props.post_view && (
               <button
-                disabled={
-                  !this.state.postForm.community_id || this.state.loading
-                }
-                type="submit"
-                class="btn btn-secondary mr-2"
+                type="button"
+                className="btn btn-secondary"
+                onClick={linkEvent(this, this.handleCancel)}
               >
-                {this.state.loading ? (
-                  <Spinner />
-                ) : this.props.post_view ? (
-                  capitalizeFirstLetter(i18n.t("save"))
-                ) : (
-                  capitalizeFirstLetter(i18n.t("create"))
-                )}
+                {i18n.t("cancel")}
               </button>
-              {this.props.post_view && (
-                <button
-                  type="button"
-                  class="btn btn-secondary"
-                  onClick={linkEvent(this, this.handleCancel)}
-                >
-                  {i18n.t("cancel")}
-                </button>
-              )}
-            </div>
+            )}
           </div>
-        </form>
-      </div>
+        </div>
+      </form>
     );
   }
 
+  renderSuggestedTitleCopy() {
+    switch (this.state.metadataRes.state) {
+      case "loading":
+        return <Spinner />;
+      case "success": {
+        const suggestedTitle = this.state.metadataRes.data.metadata.title;
+
+        return (
+          suggestedTitle && (
+            <div
+              className="mt-1 text-muted small font-weight-bold pointer"
+              role="button"
+              onClick={linkEvent(
+                { i: this, suggestedTitle },
+                this.copySuggestedTitle
+              )}
+            >
+              {i18n.t("copy_suggested_title", { title: "" })} {suggestedTitle}
+            </div>
+          )
+        );
+      }
+    }
+  }
+
+  renderSuggestedPosts() {
+    switch (this.state.suggestedPostsRes.state) {
+      case "loading":
+        return <Spinner />;
+      case "success": {
+        const suggestedPosts = this.state.suggestedPostsRes.data.posts;
+
+        return (
+          suggestedPosts &&
+          suggestedPosts.length > 0 && (
+            <>
+              <div className="my-1 text-muted small font-weight-bold">
+                {i18n.t("related_posts")}
+              </div>
+              <PostListings
+                showCommunity
+                posts={suggestedPosts}
+                enableDownvotes={this.props.enableDownvotes}
+                enableNsfw={this.props.enableNsfw}
+                allLanguages={this.props.allLanguages}
+                siteLanguages={this.props.siteLanguages}
+                viewOnly
+                // All of these are unused, since its view only
+                onPostEdit={() => {}}
+                onPostVote={() => {}}
+                onPostReport={() => {}}
+                onBlockPerson={() => {}}
+                onLockPost={() => {}}
+                onDeletePost={() => {}}
+                onRemovePost={() => {}}
+                onSavePost={() => {}}
+                onFeaturePost={() => {}}
+                onPurgePerson={() => {}}
+                onPurgePost={() => {}}
+                onBanPersonFromCommunity={() => {}}
+                onBanPerson={() => {}}
+                onAddModToCommunity={() => {}}
+                onAddAdmin={() => {}}
+                onTransferCommunity={() => {}}
+              />
+            </>
+          )
+        );
+      }
+    }
+  }
+
   handlePostSubmit(i: PostForm, event: any) {
     event.preventDefault();
-
     // Coerce empty url string to undefined
-    if (i.state.postForm.url !== undefined && i.state.postForm.url === "") {
-      i.state.postForm.url = undefined;
+    if ((i.state.form.url ?? "") === "") {
+      i.setState(s => ((s.form.url = undefined), s));
     }
-
-    if (i.props.post_view) {
-      let form: EditPost = {
-        ...i.state.postForm,
-        post_id: i.props.post_view.post.id,
-      };
-      WebSocketService.Instance.send(wsClient.editPost(form));
-    } else {
-      WebSocketService.Instance.send(wsClient.createPost(i.state.postForm));
+    i.setState({ loading: true, submitted: true });
+    const auth = myAuthRequired();
+
+    const pForm = i.state.form;
+    const pv = i.props.post_view;
+
+    if (pv) {
+      i.props.onEdit?.({
+        name: pForm.name,
+        url: pForm.url,
+        body: pForm.body,
+        nsfw: pForm.nsfw,
+        post_id: pv.post.id,
+        language_id: pForm.language_id,
+        auth,
+      });
+    } else if (pForm.name && pForm.community_id) {
+      i.props.onCreate?.({
+        name: pForm.name,
+        community_id: pForm.community_id,
+        url: pForm.url,
+        body: pForm.body,
+        nsfw: pForm.nsfw,
+        language_id: pForm.language_id,
+        honeypot: pForm.honeypot,
+        auth,
+      });
     }
-    i.state.loading = true;
-    i.setState(i.state);
   }
 
-  copySuggestedTitle(i: PostForm) {
-    i.state.postForm.name = i.state.suggestedTitle.substring(
-      0,
-      MAX_POST_TITLE_LENGTH
-    );
-    i.state.suggestedTitle = undefined;
-    setTimeout(() => {
-      let textarea: any = document.getElementById("post-title");
-      autosize.update(textarea);
-    }, 10);
-    i.setState(i.state);
+  copySuggestedTitle(d: { i: PostForm; suggestedTitle?: string }) {
+    const sTitle = d.suggestedTitle;
+    if (sTitle) {
+      d.i.setState(
+        s => ((s.form.name = sTitle?.substring(0, MAX_POST_TITLE_LENGTH)), s)
+      );
+      d.i.setState({ suggestedPostsRes: { state: "empty" } });
+      setTimeout(() => {
+        const textarea: any = document.getElementById("post-title");
+        autosize.update(textarea);
+      }, 10);
+    }
   }
 
   handlePostUrlChange(i: PostForm, event: any) {
-    i.state.postForm.url = event.target.value;
-    i.setState(i.state);
-    i.fetchPageTitle();
-  }
+    const url = event.target.value;
 
-  fetchPageTitle() {
-    if (validURL(this.state.postForm.url)) {
-      let form: Search = {
-        q: this.state.postForm.url,
-        type_: SearchType.Url,
-        sort: SortType.TopAll,
-        listing_type: ListingType.All,
-        page: 1,
-        limit: 6,
-        auth: authField(false),
-      };
+    i.setState({
+      form: {
+        url,
+      },
+      imageDeleteUrl: "",
+    });
 
-      WebSocketService.Instance.send(wsClient.search(form));
+    i.fetchPageTitle();
+  }
 
-      // Fetch the page title
-      getSiteMetadata(this.state.postForm.url).then(d => {
-        this.state.suggestedTitle = d.metadata.title;
-        this.setState(this.state);
+  async fetchPageTitle() {
+    const url = this.state.form.url;
+    if (url && validURL(url)) {
+      this.setState({ metadataRes: { state: "loading" } });
+      this.setState({
+        metadataRes: await HttpService.client.getSiteMetadata({ url }),
       });
-    } else {
-      this.state.suggestedTitle = undefined;
-      this.state.crossPosts = [];
     }
   }
 
   handlePostNameChange(i: PostForm, event: any) {
-    i.state.postForm.name = event.target.value;
-    i.setState(i.state);
+    i.setState(s => ((s.form.name = event.target.value), s));
     i.fetchSimilarPosts();
   }
 
-  fetchSimilarPosts() {
-    let form: Search = {
-      q: this.state.postForm.name,
-      type_: SearchType.Posts,
-      sort: SortType.TopAll,
-      listing_type: ListingType.All,
-      community_id: this.state.postForm.community_id,
-      page: 1,
-      limit: 6,
-      auth: authField(false),
-    };
-
-    if (this.state.postForm.name !== "") {
-      WebSocketService.Instance.send(wsClient.search(form));
-    } else {
-      this.state.suggestedPosts = [];
+  async fetchSimilarPosts() {
+    const q = this.state.form.name;
+    if (q && q !== "") {
+      this.setState({ suggestedPostsRes: { state: "loading" } });
+      this.setState({
+        suggestedPostsRes: await HttpService.client.search({
+          q,
+          type_: "Posts",
+          sort: "TopAll",
+          listing_type: "All",
+          community_id: this.state.form.community_id,
+          page: 1,
+          limit: trendingFetchLimit,
+          auth: myAuth(),
+        }),
+      });
     }
-
-    this.setState(this.state);
   }
 
   handlePostBodyChange(val: string) {
-    this.state.postForm.body = val;
-    this.setState(this.state);
+    this.setState(s => ((s.form.body = val), s));
   }
 
   handlePostCommunityChange(i: PostForm, event: any) {
-    i.state.postForm.community_id = Number(event.target.value);
-    i.setState(i.state);
+    i.setState(s => ((s.form.community_id = Number(event.target.value)), s));
   }
 
   handlePostNsfwChange(i: PostForm, event: any) {
-    i.state.postForm.nsfw = event.target.checked;
-    i.setState(i.state);
+    i.setState(s => ((s.form.nsfw = event.target.checked), s));
+  }
+
+  handleLanguageChange(val: number[]) {
+    this.setState(s => ((s.form.language_id = val.at(0)), s));
   }
 
   handleHoneyPotChange(i: PostForm, event: any) {
-    i.state.postForm.honeypot = event.target.value;
-    i.setState(i.state);
+    i.setState(s => ((s.form.honeypot = event.target.value), s));
   }
 
   handleCancel(i: PostForm) {
-    i.props.onCancel();
+    i.props.onCancel?.();
   }
 
   handlePreviewToggle(i: PostForm, event: any) {
     event.preventDefault();
-    i.state.previewMode = !i.state.previewMode;
-    i.setState(i.state);
+    i.setState({ previewMode: !i.state.previewMode });
   }
 
   handleImageUploadPaste(i: PostForm, event: any) {
-    let image = event.clipboardData.files[0];
+    const image = event.clipboardData.files[0];
     if (image) {
       i.handleImageUpload(i, image);
     }
@@ -529,138 +656,69 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
       file = event;
     }
 
-    const formData = new FormData();
-    formData.append("images[]", file);
-
-    i.state.imageLoading = true;
-    i.setState(i.state);
-
-    fetch(pictrsUri, {
-      method: "POST",
-      body: formData,
-    })
-      .then(res => res.json())
-      .then(res => {
-        console.log("pictrs upload:");
-        console.log(res);
-        if (res.msg == "ok") {
-          let hash = res.files[0].file;
-          let url = `${pictrsUri}/${hash}`;
-          let deleteToken = res.files[0].delete_token;
-          let deleteUrl = `${pictrsUri}/delete/${deleteToken}/${hash}`;
-          i.state.postForm.url = url;
-          i.state.imageLoading = false;
-          i.setState(i.state);
-          pictrsDeleteToast(
-            i18n.t("click_to_delete_picture"),
-            i18n.t("picture_deleted"),
-            deleteUrl
-          );
+    i.setState({ imageLoading: true });
+
+    HttpService.client.uploadImage({ image: file }).then(res => {
+      console.log("pictrs upload:");
+      console.log(res);
+      if (res.state === "success") {
+        if (res.data.msg === "ok") {
+          i.state.form.url = res.data.url;
+          i.setState({
+            imageLoading: false,
+            imageDeleteUrl: res.data.delete_url as string,
+          });
         } else {
-          i.state.imageLoading = false;
-          i.setState(i.state);
           toast(JSON.stringify(res), "danger");
         }
-      })
-      .catch(error => {
-        i.state.imageLoading = false;
-        i.setState(i.state);
-        toast(error, "danger");
-      });
+      } else if (res.state === "failed") {
+        console.error(res.msg);
+        toast(res.msg, "danger");
+        i.setState({ imageLoading: false });
+      }
+    });
   }
 
-  setupCommunities() {
-    // Set up select searching
-    if (isBrowser()) {
-      let selectId: any = document.getElementById("post-community");
-      if (selectId) {
-        this.choices = new Choices(selectId, choicesConfig);
-        this.choices.passedElement.element.addEventListener(
-          "choice",
-          (e: any) => {
-            this.state.postForm.community_id = Number(e.detail.choice.value);
-            this.setState(this.state);
-          },
-          false
-        );
-        this.choices.passedElement.element.addEventListener(
-          "search",
-          debounce(async (e: any) => {
-            let communities = (await fetchCommunities(e.detail.value))
-              .communities;
-            this.choices.setChoices(
-              communities.map(cv => communityToChoice(cv)),
-              "value",
-              "label",
-              true
-            );
-          }, 400),
-          false
-        );
-      }
+  handleImageDelete(i: PostForm) {
+    const { imageDeleteUrl } = i.state;
+
+    fetch(imageDeleteUrl);
+
+    i.setState({
+      imageDeleteUrl: "",
+      imageLoading: false,
+      form: {
+        url: "",
+      },
+    });
+  }
+
+  handleCommunitySearch = debounce(async (text: string) => {
+    const { selectedCommunityChoice } = this.props;
+    this.setState({ communitySearchLoading: true });
+
+    const newOptions: Choice[] = [];
+
+    if (selectedCommunityChoice) {
+      newOptions.push(selectedCommunityChoice);
     }
 
-    if (this.props.post_view) {
-      this.state.postForm.community_id = this.props.post_view.community.id;
-    } else if (
-      this.props.params &&
-      (this.props.params.community_id || this.props.params.community_name)
-    ) {
-      if (this.props.params.community_name) {
-        let foundCommunityId = this.props.communities.find(
-          r => r.community.name == this.props.params.community_name
-        ).community.id;
-        this.state.postForm.community_id = foundCommunityId;
-      } else if (this.props.params.community_id) {
-        this.state.postForm.community_id = this.props.params.community_id;
-      }
+    if (text.length > 0) {
+      newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
 
-      if (isBrowser()) {
-        this.choices.setChoiceByValue(
-          this.state.postForm.community_id.toString()
-        );
-      }
-      this.setState(this.state);
-    } else {
-      // By default, the null valued 'Select a Community'
+      this.setState({
+        communitySearchOptions: newOptions,
+      });
     }
-  }
 
-  parseMessage(msg: any) {
-    let op = wsUserOp(msg);
-    console.log(msg);
-    if (msg.error) {
-      toast(i18n.t(msg.error), "danger");
-      this.state.loading = false;
-      this.setState(this.state);
-      return;
-    } else if (op == UserOperation.CreatePost) {
-      let data = wsJsonToRes<PostResponse>(msg).data;
-      if (
-        data.post_view.creator.id ==
-        UserService.Instance.myUserInfo.local_user_view.person.id
-      ) {
-        this.state.loading = false;
-        this.props.onCreate(data.post_view);
-      }
-    } else if (op == UserOperation.EditPost) {
-      let data = wsJsonToRes<PostResponse>(msg).data;
-      if (
-        data.post_view.creator.id ==
-        UserService.Instance.myUserInfo.local_user_view.person.id
-      ) {
-        this.state.loading = false;
-        this.props.onEdit(data.post_view);
-      }
-    } else if (op == UserOperation.Search) {
-      let data = wsJsonToRes<SearchResponse>(msg).data;
+    this.setState({
+      communitySearchLoading: false,
+    });
+  });
 
-      if (data.type_ == SearchType[SearchType.Posts]) {
-        this.state.suggestedPosts = data.posts;
-      } else if (data.type_ == SearchType[SearchType.Url]) {
-        this.state.crossPosts = data.posts;
-      }
-      this.setState(this.state);
+  handleCommunitySelect(choice: Choice) {
+    if (this.props.onSelectCommunity) {
+      this.props.onSelectCommunity(choice);
     }
   }
 }