]> Untitled Git - lemmy-ui.git/blob - src/shared/components/post/create-post.tsx
Removing monads. Fixes #884 (#886)
[lemmy-ui.git] / src / shared / components / post / create-post.tsx
1 import { Component } from "inferno";
2 import {
3   GetCommunity,
4   GetCommunityResponse,
5   GetSiteResponse,
6   ListCommunities,
7   ListCommunitiesResponse,
8   ListingType,
9   PostView,
10   SortType,
11   UserOperation,
12   wsJsonToRes,
13   wsUserOp,
14 } from "lemmy-js-client";
15 import { Subscription } from "rxjs";
16 import { InitialFetchRequest, PostFormParams } from "shared/interfaces";
17 import { i18n } from "../../i18next";
18 import { UserService, WebSocketService } from "../../services";
19 import {
20   enableDownvotes,
21   enableNsfw,
22   fetchLimit,
23   isBrowser,
24   myAuth,
25   setIsoData,
26   toast,
27   wsClient,
28   wsSubscribe,
29 } from "../../utils";
30 import { HtmlTags } from "../common/html-tags";
31 import { Spinner } from "../common/icon";
32 import { PostForm } from "./post-form";
33
34 interface CreatePostState {
35   listCommunitiesResponse?: ListCommunitiesResponse;
36   siteRes: GetSiteResponse;
37   loading: boolean;
38 }
39
40 export class CreatePost extends Component<any, CreatePostState> {
41   private isoData = setIsoData(this.context);
42   private subscription?: Subscription;
43   state: CreatePostState = {
44     siteRes: this.isoData.site_res,
45     loading: true,
46   };
47
48   constructor(props: any, context: any) {
49     super(props, context);
50
51     this.handlePostCreate = this.handlePostCreate.bind(this);
52
53     this.parseMessage = this.parseMessage.bind(this);
54     this.subscription = wsSubscribe(this.parseMessage);
55
56     if (!UserService.Instance.myUserInfo && isBrowser()) {
57       toast(i18n.t("not_logged_in"), "danger");
58       this.context.router.history.push(`/login`);
59     }
60
61     // Only fetch the data if coming from another route
62     if (this.isoData.path == this.context.router.route.match.url) {
63       this.state = {
64         ...this.state,
65         listCommunitiesResponse: this.isoData
66           .routeData[0] as ListCommunitiesResponse,
67         loading: false,
68       };
69     } else {
70       this.refetch();
71     }
72   }
73
74   refetch() {
75     let nameOrId = this.params.nameOrId;
76     let auth = myAuth(false);
77     if (nameOrId) {
78       if (typeof nameOrId === "string") {
79         let form: GetCommunity = {
80           name: nameOrId,
81           auth,
82         };
83         WebSocketService.Instance.send(wsClient.getCommunity(form));
84       } else {
85         let form: GetCommunity = {
86           id: nameOrId,
87           auth,
88         };
89         WebSocketService.Instance.send(wsClient.getCommunity(form));
90       }
91     } else {
92       let listCommunitiesForm: ListCommunities = {
93         type_: ListingType.All,
94         sort: SortType.TopAll,
95         limit: fetchLimit,
96         auth,
97       };
98       WebSocketService.Instance.send(
99         wsClient.listCommunities(listCommunitiesForm)
100       );
101     }
102   }
103
104   componentWillUnmount() {
105     if (isBrowser()) {
106       this.subscription?.unsubscribe();
107     }
108   }
109
110   get documentTitle(): string {
111     return `${i18n.t("create_post")} - ${
112       this.state.siteRes.site_view.site.name
113     }`;
114   }
115
116   render() {
117     let res = this.state.listCommunitiesResponse;
118     return (
119       <div className="container-lg">
120         <HtmlTags
121           title={this.documentTitle}
122           path={this.context.router.route.match.url}
123         />
124         {this.state.loading ? (
125           <h5>
126             <Spinner large />
127           </h5>
128         ) : (
129           res && (
130             <div className="row">
131               <div className="col-12 col-lg-6 offset-lg-3 mb-4">
132                 <h5>{i18n.t("create_post")}</h5>
133                 <PostForm
134                   communities={res.communities}
135                   onCreate={this.handlePostCreate}
136                   params={this.params}
137                   enableDownvotes={enableDownvotes(this.state.siteRes)}
138                   enableNsfw={enableNsfw(this.state.siteRes)}
139                   allLanguages={this.state.siteRes.all_languages}
140                   siteLanguages={this.state.siteRes.discussion_languages}
141                 />
142               </div>
143             </div>
144           )
145         )}
146       </div>
147     );
148   }
149
150   get params(): PostFormParams {
151     let urlParams = new URLSearchParams(this.props.location.search);
152     let name = urlParams.get("community_name") ?? this.prevCommunityName;
153     let communityIdParam = urlParams.get("community_id");
154     let id = communityIdParam ? Number(communityIdParam) : this.prevCommunityId;
155     let nameOrId: string | number | undefined;
156     if (name) {
157       nameOrId = name;
158     } else if (id) {
159       nameOrId = id;
160     }
161
162     let params: PostFormParams = {
163       name: urlParams.get("title") ?? undefined,
164       nameOrId,
165       body: urlParams.get("body") ?? undefined,
166       url: urlParams.get("url") ?? undefined,
167     };
168
169     return params;
170   }
171
172   get prevCommunityName(): string | undefined {
173     if (this.props.match.params.name) {
174       return this.props.match.params.name;
175     } else if (this.props.location.state) {
176       let lastLocation = this.props.location.state.prevPath;
177       if (lastLocation.includes("/c/")) {
178         return lastLocation.split("/c/").at(1);
179       }
180     }
181     return undefined;
182   }
183
184   get prevCommunityId(): number | undefined {
185     // TODO is this actually a number? Whats the real return type
186     let id = this.props.match.params.id;
187     return id ?? undefined;
188   }
189
190   handlePostCreate(post_view: PostView) {
191     this.props.history.push(`/post/${post_view.post.id}`);
192   }
193
194   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
195     let listCommunitiesForm: ListCommunities = {
196       type_: ListingType.All,
197       sort: SortType.TopAll,
198       limit: fetchLimit,
199       auth: req.auth,
200     };
201     return [req.client.listCommunities(listCommunitiesForm)];
202   }
203
204   parseMessage(msg: any) {
205     let op = wsUserOp(msg);
206     console.log(msg);
207     if (msg.error) {
208       toast(i18n.t(msg.error), "danger");
209       return;
210     } else if (op == UserOperation.ListCommunities) {
211       let data = wsJsonToRes<ListCommunitiesResponse>(msg);
212       this.setState({ listCommunitiesResponse: data, loading: false });
213     } else if (op == UserOperation.GetCommunity) {
214       let data = wsJsonToRes<GetCommunityResponse>(msg);
215       this.setState({
216         listCommunitiesResponse: {
217           communities: [data.community_view],
218         },
219         loading: false,
220       });
221     }
222   }
223 }