]> Untitled Git - lemmy.git/blob - ui/src/components/post-form.tsx
View where a URL has been cross-posted to in the past
[lemmy.git] / ui / src / components / post-form.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { PostListings } from './post-listings';
3 import { Subscription } from "rxjs";
4 import { retryWhen, delay, take } from 'rxjs/operators';
5 import { PostForm as PostFormI, Post, PostResponse, UserOperation, Community, ListCommunitiesResponse, ListCommunitiesForm, SortType, SearchForm, SearchType, SearchResponse } from '../interfaces';
6 import { WebSocketService, UserService } from '../services';
7 import { msgOp, getPageTitle, debounce, validURL, capitalizeFirstLetter } from '../utils';
8 import * as autosize from 'autosize';
9 import { i18n } from '../i18next';
10 import { T } from 'inferno-i18next';
11
12 interface PostFormProps {
13   post?: Post; // If a post is given, that means this is an edit
14   prevCommunityName?: string;
15   onCancel?(): any;
16   onCreate?(id: number): any;
17   onEdit?(post: Post): any;
18 }
19
20 interface PostFormState {
21   postForm: PostFormI;
22   communities: Array<Community>;
23   loading: boolean;
24   suggestedTitle: string;
25   suggestedPosts: Array<Post>;
26   crossPosts: Array<Post>;
27 }
28
29 export class PostForm extends Component<PostFormProps, PostFormState> {
30
31   private subscription: Subscription;
32   private emptyState: PostFormState = {
33     postForm: {
34       name: null,
35       nsfw: false,
36       auth: null,
37       community_id: null,
38       creator_id: (UserService.Instance.user) ? UserService.Instance.user.id : null,
39     },
40     communities: [],
41     loading: false,
42     suggestedTitle: undefined,
43     suggestedPosts: [],
44     crossPosts: [],
45   }
46
47   constructor(props: any, context: any) {
48     super(props, context);
49
50     this.state = this.emptyState;
51
52     if (this.props.post) {
53       this.state.postForm = {
54         body: this.props.post.body,
55         name: this.props.post.name,
56         community_id: this.props.post.community_id,
57         edit_id: this.props.post.id,
58         creator_id: this.props.post.creator_id,
59         url: this.props.post.url,
60         nsfw: this.props.post.nsfw,
61         auth: null
62       }
63     }
64
65     this.subscription = WebSocketService.Instance.subject
66       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
67       .subscribe(
68         (msg) => this.parseMessage(msg),
69         (err) => console.error(err),
70         () => console.log('complete')
71       );
72
73       let listCommunitiesForm: ListCommunitiesForm = {
74         sort: SortType[SortType.TopAll],
75         limit: 9999,
76       }
77
78       WebSocketService.Instance.listCommunities(listCommunitiesForm);
79   }
80
81   componentDidMount() {
82     autosize(document.querySelectorAll('textarea'));
83   }
84
85   componentWillUnmount() {
86     this.subscription.unsubscribe();
87   }
88
89   render() {
90     return (
91       <div>
92         <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
93           <div class="form-group row">
94             <label class="col-sm-2 col-form-label"><T i18nKey="url">#</T></label>
95             <div class="col-sm-10">
96               <input type="url" class="form-control" value={this.state.postForm.url} onInput={linkEvent(this, this.handlePostUrlChange)} />
97               {this.state.suggestedTitle && 
98                 <div class="mt-1 text-muted small font-weight-bold pointer" onClick={linkEvent(this, this.copySuggestedTitle)}><T i18nKey="copy_suggested_title" interpolation={{title: this.state.suggestedTitle}}>#</T></div>
99               }
100               {this.state.crossPosts.length > 0 && 
101                 <>
102                   <div class="my-1 text-muted small font-weight-bold"><T i18nKey="cross_posts">#</T></div>
103                   <PostListings showCommunity posts={this.state.crossPosts} />
104                 </>
105               }
106             </div>
107           </div>
108           <div class="form-group row">
109             <label class="col-sm-2 col-form-label"><T i18nKey="title">#</T></label>
110             <div class="col-sm-10">
111               <textarea value={this.state.postForm.name} onInput={linkEvent(this, this.handlePostNameChange)} class="form-control" required rows={2} minLength={3} maxLength={100} />
112               {this.state.suggestedPosts.length > 0 && 
113                 <>
114                   <div class="my-1 text-muted small font-weight-bold"><T i18nKey="related_posts">#</T></div>
115                   <PostListings posts={this.state.suggestedPosts} />
116                 </>
117               }
118             </div>
119           </div>
120           <div class="form-group row">
121             <label class="col-sm-2 col-form-label"><T i18nKey="body">#</T></label>
122             <div class="col-sm-10">
123               <textarea value={this.state.postForm.body} onInput={linkEvent(this, this.handlePostBodyChange)} class="form-control" rows={4} maxLength={10000} />
124             </div>
125           </div>
126           {/* Cant change a community from an edit */}
127           {!this.props.post &&
128             <div class="form-group row">
129             <label class="col-sm-2 col-form-label"><T i18nKey="community">#</T></label>
130             <div class="col-sm-10">
131               <select class="form-control" value={this.state.postForm.community_id} onInput={linkEvent(this, this.handlePostCommunityChange)}>
132                 {this.state.communities.map(community =>
133                   <option value={community.id}>{community.name}</option>
134                 )}
135               </select>
136             </div>
137             </div>
138             }
139           <div class="form-group row">
140             <div class="col-sm-10">
141               <div class="form-check">
142                 <input class="form-check-input" type="checkbox" checked={this.state.postForm.nsfw} onChange={linkEvent(this, this.handlePostNsfwChange)}/>
143                 <label class="form-check-label"><T i18nKey="nsfw">#</T></label>
144               </div>
145             </div>
146           </div>
147           <div class="form-group row">
148             <div class="col-sm-10">
149               <button type="submit" class="btn btn-secondary mr-2">
150               {this.state.loading ? 
151               <svg class="icon icon-spinner spin"><use xlinkHref="#icon-spinner"></use></svg> : 
152               this.props.post ? capitalizeFirstLetter(i18n.t('save')) : capitalizeFirstLetter(i18n.t('create'))}</button>
153               {this.props.post && <button type="button" class="btn btn-secondary" onClick={linkEvent(this, this.handleCancel)}><T i18nKey="cancel">#</T></button>}
154             </div>
155           </div>
156         </form>
157       </div>
158     );
159   }
160
161   handlePostSubmit(i: PostForm, event: any) {
162     event.preventDefault();
163     if (i.props.post) {
164       WebSocketService.Instance.editPost(i.state.postForm);
165     } else {
166       WebSocketService.Instance.createPost(i.state.postForm);
167     }
168     i.state.loading = true;
169     i.setState(i.state);
170   }
171
172   copySuggestedTitle(i: PostForm) {
173     i.state.postForm.name = i.state.suggestedTitle;
174     i.state.suggestedTitle = undefined;
175     i.setState(i.state);
176   }
177
178   handlePostUrlChange(i: PostForm, event: any) {
179     i.state.postForm.url = event.target.value;
180     if (validURL(i.state.postForm.url)) {
181
182       let form: SearchForm = {
183         q: i.state.postForm.url,
184         type_: SearchType[SearchType.Url],
185         sort: SortType[SortType.TopAll],
186         page: 1,
187         limit: 6,
188       };
189
190       WebSocketService.Instance.search(form);
191
192       // Fetch the page title
193       getPageTitle(i.state.postForm.url).then(d => {
194         i.state.suggestedTitle = d;
195         i.setState(i.state);
196       });
197     } else {
198       i.state.suggestedTitle = undefined;
199       i.state.crossPosts = [];
200     }
201
202     i.setState(i.state);
203   }
204
205   handlePostNameChange(i: PostForm, event: any) {
206     i.state.postForm.name = event.target.value;
207     let form: SearchForm = {
208       q: i.state.postForm.name,
209       type_: SearchType[SearchType.Posts],
210       sort: SortType[SortType.TopAll],
211       community_id: i.state.postForm.community_id,
212       page: 1,
213       limit: 6,
214     };
215
216     if (i.state.postForm.name !== '') {
217       WebSocketService.Instance.search(form);
218     } else {
219       i.state.suggestedPosts = [];
220     }
221
222     i.setState(i.state);
223   }
224
225   handlePostBodyChange(i: PostForm, event: any) {
226     i.state.postForm.body = event.target.value;
227     i.setState(i.state);
228   }
229
230   handlePostCommunityChange(i: PostForm, event: any) {
231     i.state.postForm.community_id = Number(event.target.value);
232     i.setState(i.state);
233   }
234
235   handlePostNsfwChange(i: PostForm, event: any) {
236     i.state.postForm.nsfw = event.target.checked;
237     i.setState(i.state);
238   }
239
240   handleCancel(i: PostForm) {
241     i.props.onCancel();
242   }
243
244   parseMessage(msg: any) {
245     let op: UserOperation = msgOp(msg);
246     if (msg.error) {
247       alert(i18n.t(msg.error));
248       this.state.loading = false;
249       this.setState(this.state);
250       return;
251     } else if (op == UserOperation.ListCommunities) {
252       let res: ListCommunitiesResponse = msg;
253       this.state.communities = res.communities;
254       if (this.props.post) {
255         this.state.postForm.community_id = this.props.post.community_id;
256       } else if (this.props.prevCommunityName) {
257         let foundCommunityId = res.communities.find(r => r.name == this.props.prevCommunityName).id;
258         this.state.postForm.community_id = foundCommunityId;
259       } else {
260         this.state.postForm.community_id = res.communities[0].id;
261       }
262       this.setState(this.state);
263     } else if (op == UserOperation.CreatePost) {
264       this.state.loading = false;
265       let res: PostResponse = msg;
266       this.props.onCreate(res.post.id);
267     } else if (op == UserOperation.EditPost) {
268       this.state.loading = false;
269       let res: PostResponse = msg;
270       this.props.onEdit(res.post);
271     } else if (op == UserOperation.Search) {
272       let res: SearchResponse = msg;
273       
274       if (res.type_ == SearchType[SearchType.Posts]) {
275         this.state.suggestedPosts = res.posts;
276       } else if (res.type_ == SearchType[SearchType.Url]) {
277         this.state.crossPosts = res.posts;
278       }
279       this.setState(this.state);
280     }
281   }
282
283 }
284
285