Adding create private message.

This commit is contained in:
Dessalines 2020-09-08 13:44:55 -05:00
parent 6562b6f4f0
commit bfce461a14
9 changed files with 151 additions and 108 deletions

View file

@ -344,7 +344,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
<button class="btn btn-link btn-animate"> <button class="btn btn-link btn-animate">
<Link <Link
class="text-muted" class="text-muted"
to={`/create_private_message?recipient_id=${node.comment.creator_id}`} to={`/create_private_message/recipient/${node.comment.creator_id}`}
title={i18n.t('message').toLowerCase()} title={i18n.t('message').toLowerCase()}
> >
<svg class="icon"> <svg class="icon">

View file

@ -21,6 +21,8 @@ import {
CommentResponse, CommentResponse,
WebSocketJsonResponse, WebSocketJsonResponse,
GetSiteResponse, GetSiteResponse,
Category,
ListCategoriesResponse,
} from 'lemmy-js-client'; } from 'lemmy-js-client';
import { UserService, WebSocketService } from '../services'; import { UserService, WebSocketService } from '../services';
import { PostListings } from './post-listings'; import { PostListings } from './post-listings';
@ -65,6 +67,7 @@ interface State {
dataType: DataType; dataType: DataType;
sort: SortType; sort: SortType;
page: number; page: number;
categories: Category[];
} }
interface CommunityProps { interface CommunityProps {
@ -93,6 +96,7 @@ export class Community extends Component<any, State> {
sort: getSortTypeFromProps(this.props), sort: getSortTypeFromProps(this.props),
page: getPageFromProps(this.props), page: getPageFromProps(this.props),
siteRes: this.isoData.site, siteRes: this.isoData.site,
categories: [],
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -113,10 +117,12 @@ export class Community extends Component<any, State> {
} else { } else {
this.state.comments = this.isoData.routeData[1].comments; this.state.comments = this.isoData.routeData[1].comments;
} }
this.state.categories = this.isoData.routeData[2].categories;
this.state.loading = false; this.state.loading = false;
} else { } else {
this.fetchCommunity(); this.fetchCommunity();
this.fetchData(); this.fetchData();
WebSocketService.Instance.listCategories();
} }
setupTippy(); setupTippy();
} }
@ -195,6 +201,8 @@ export class Community extends Component<any, State> {
promises.push(lemmyHttp.getComments(getCommentsForm)); promises.push(lemmyHttp.getComments(getCommentsForm));
} }
promises.push(lemmyHttp.listCategories());
return promises; return promises;
} }
@ -263,6 +271,7 @@ export class Community extends Component<any, State> {
admins={this.state.siteRes.admins} admins={this.state.siteRes.admins}
online={this.state.communityRes.online} online={this.state.communityRes.online}
enableNsfw={this.state.siteRes.site.enable_nsfw} enableNsfw={this.state.siteRes.site.enable_nsfw}
categories={this.state.categories}
/> />
</div> </div>
</div> </div>
@ -425,6 +434,9 @@ export class Community extends Component<any, State> {
} else if (res.op == UserOperation.GetCommunity) { } else if (res.op == UserOperation.GetCommunity) {
let data = res.data as GetCommunityResponse; let data = res.data as GetCommunityResponse;
this.state.communityRes = data; this.state.communityRes = data;
if (this.state.posts.length || this.state.comments.length) {
this.state.loading = false;
}
this.setState(this.state); this.setState(this.state);
} else if ( } else if (
res.op == UserOperation.EditCommunity || res.op == UserOperation.EditCommunity ||
@ -443,7 +455,10 @@ export class Community extends Component<any, State> {
} else if (res.op == UserOperation.GetPosts) { } else if (res.op == UserOperation.GetPosts) {
let data = res.data as GetPostsResponse; let data = res.data as GetPostsResponse;
this.state.posts = data.posts; this.state.posts = data.posts;
this.state.loading = false;
if (this.state.communityRes) {
this.state.loading = false;
}
this.setState(this.state); this.setState(this.state);
setupTippy(); setupTippy();
} else if ( } else if (
@ -480,7 +495,9 @@ export class Community extends Component<any, State> {
} else if (res.op == UserOperation.GetComments) { } else if (res.op == UserOperation.GetComments) {
let data = res.data as GetCommentsResponse; let data = res.data as GetCommentsResponse;
this.state.comments = data.comments; this.state.comments = data.comments;
this.state.loading = false; if (this.state.communityRes) {
this.state.loading = false;
}
this.setState(this.state); this.setState(this.state);
} else if ( } else if (
res.op == UserOperation.EditComment || res.op == UserOperation.EditComment ||
@ -506,6 +523,10 @@ export class Community extends Component<any, State> {
let data = res.data as CommentResponse; let data = res.data as CommentResponse;
createCommentLikeRes(data, this.state.comments); createCommentLikeRes(data, this.state.comments);
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.ListCategories) {
let data = res.data as ListCategoriesResponse;
this.state.categories = data.categories;
this.setState(this.state);
} }
} }
} }

View file

@ -3,6 +3,7 @@ import { Helmet } from 'inferno-helmet';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { PostForm } from './post-form'; import { PostForm } from './post-form';
import { import {
isBrowser,
lemmyHttp, lemmyHttp,
setAuth, setAuth,
setIsoData, setIsoData,
@ -69,7 +70,9 @@ export class CreatePost extends Component<any, CreatePostState> {
} }
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); if (isBrowser()) {
this.subscription.unsubscribe();
}
} }
get documentTitle(): string { get documentTitle(): string {

View file

@ -1,30 +1,49 @@
import { Component } from 'inferno'; import { Component } from 'inferno';
import { Helmet } from 'inferno-helmet'; import { Helmet } from 'inferno-helmet';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
import { PrivateMessageForm } from './private-message-form'; import { PrivateMessageForm } from './private-message-form';
import { WebSocketService, UserService } from '../services'; import { UserService, WebSocketService } from '../services';
import { import {
UserOperation,
WebSocketJsonResponse,
GetSiteResponse,
Site, Site,
PrivateMessageFormParams, WebSocketJsonResponse,
UserOperation,
UserDetailsResponse,
UserView,
SortType,
GetUserDetailsForm,
} from 'lemmy-js-client'; } from 'lemmy-js-client';
import { toast, wsJsonToRes } from '../utils'; import {
getRecipientIdFromProps,
isBrowser,
lemmyHttp,
setAuth,
setIsoData,
toast,
wsJsonToRes,
wsSubscribe,
} from '../utils';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
interface CreatePrivateMessageProps {}
interface CreatePrivateMessageState { interface CreatePrivateMessageState {
site: Site; site: Site;
recipient: UserView;
recipient_id: number;
loading: boolean;
} }
export class CreatePrivateMessage extends Component< export class CreatePrivateMessage extends Component<
any, CreatePrivateMessageProps,
CreatePrivateMessageState CreatePrivateMessageState
> { > {
private isoData = setIsoData(this.context);
private subscription: Subscription; private subscription: Subscription;
private emptyState: CreatePrivateMessageState = { private emptyState: CreatePrivateMessageState = {
site: undefined, site: this.isoData.site.site,
recipient: undefined,
recipient_id: getRecipientIdFromProps(this.props),
loading: true,
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
@ -33,31 +52,50 @@ export class CreatePrivateMessage extends Component<
this this
); );
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);
if (!UserService.Instance.user) { if (!UserService.Instance.user) {
toast(i18n.t('not_logged_in'), 'danger'); toast(i18n.t('not_logged_in'), 'danger');
this.context.router.history.push(`/login`); this.context.router.history.push(`/login`);
} }
this.subscription = WebSocketService.Instance.subject // Only fetch the data if coming from another route
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10)))) if (this.isoData.path == this.context.router.route.match.url) {
.subscribe( this.state.recipient = this.isoData.routeData[0].user;
msg => this.parseMessage(msg), this.state.loading = false;
err => console.error(err), } else {
() => console.log('complete') this.fetchUserDetails();
); }
WebSocketService.Instance.getSite();
} }
componentWillUnmount() { fetchUserDetails() {
this.subscription.unsubscribe(); let form: GetUserDetailsForm = {
user_id: this.state.recipient_id,
sort: SortType.New,
saved_only: false,
};
WebSocketService.Instance.getUserDetails(form);
}
static fetchInitialData(auth: string, path: string): Promise<any>[] {
let user_id = Number(path.split('/').pop());
let form: GetUserDetailsForm = {
user_id,
sort: SortType.New,
saved_only: false,
};
setAuth(form, auth);
return [lemmyHttp.getUserDetails(form)];
} }
get documentTitle(): string { get documentTitle(): string {
if (this.state.site) { return `${i18n.t('create_private_message')} - ${this.state.site.name}`;
return `${i18n.t('create_private_message')} - ${this.state.site.name}`; }
} else {
return 'Lemmy'; componentWillUnmount() {
if (isBrowser()) {
this.subscription.unsubscribe();
} }
} }
@ -65,44 +103,45 @@ export class CreatePrivateMessage extends Component<
return ( return (
<div class="container"> <div class="container">
<Helmet title={this.documentTitle} /> <Helmet title={this.documentTitle} />
<div class="row"> {this.state.loading ? (
<div class="col-12 col-lg-6 offset-lg-3 mb-4"> <h5>
<h5>{i18n.t('create_private_message')}</h5> <svg class="icon icon-spinner spin">
<PrivateMessageForm <use xlinkHref="#icon-spinner"></use>
onCreate={this.handlePrivateMessageCreate} </svg>
params={this.params} </h5>
/> ) : (
<div class="row">
<div class="col-12 col-lg-6 offset-lg-3 mb-4">
<h5>{i18n.t('create_private_message')}</h5>
<PrivateMessageForm
onCreate={this.handlePrivateMessageCreate}
recipient={this.state.recipient}
/>
</div>
</div> </div>
</div> )}
</div> </div>
); );
} }
get params(): PrivateMessageFormParams {
let urlParams = new URLSearchParams(this.props.location.search);
let params: PrivateMessageFormParams = {
recipient_id: Number(urlParams.get('recipient_id')),
};
return params;
}
handlePrivateMessageCreate() { handlePrivateMessageCreate() {
toast(i18n.t('message_sent')); toast(i18n.t('message_sent'));
// Navigate to the front // Navigate to the front
this.props.history.push(`/`); this.context.router.history.push(`/`);
} }
parseMessage(msg: WebSocketJsonResponse) { parseMessage(msg: WebSocketJsonResponse) {
console.log(msg);
let res = wsJsonToRes(msg); let res = wsJsonToRes(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), 'danger'); toast(i18n.t(msg.error), 'danger');
this.state.loading = false;
this.setState(this.state);
return; return;
} else if (res.op == UserOperation.GetSite) { } else if (res.op == UserOperation.GetUserDetails) {
let data = res.data as GetSiteResponse; let data = res.data as UserDetailsResponse;
this.state.site = data.site; this.state.recipient = data.user;
this.state.loading = false;
this.setState(this.state); this.setState(this.state);
} }
} }

View file

@ -1,18 +1,13 @@
import { Component, linkEvent } from 'inferno'; import { Component, linkEvent } from 'inferno';
import { Prompt } from 'inferno-router'; import { Prompt } from 'inferno-router';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
import { import {
PrivateMessageForm as PrivateMessageFormI, PrivateMessageForm as PrivateMessageFormI,
EditPrivateMessageForm, EditPrivateMessageForm,
PrivateMessageFormParams,
PrivateMessage, PrivateMessage,
PrivateMessageResponse, PrivateMessageResponse,
UserView, UserView,
UserOperation, UserOperation,
UserDetailsResponse,
GetUserDetailsForm,
SortType,
WebSocketJsonResponse, WebSocketJsonResponse,
} from 'lemmy-js-client'; } from 'lemmy-js-client';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
@ -21,6 +16,8 @@ import {
wsJsonToRes, wsJsonToRes,
toast, toast,
setupTippy, setupTippy,
wsSubscribe,
isBrowser,
} from '../utils'; } from '../utils';
import { UserListing } from './user-listing'; import { UserListing } from './user-listing';
import { MarkdownTextArea } from './markdown-textarea'; import { MarkdownTextArea } from './markdown-textarea';
@ -28,8 +25,8 @@ import { i18n } from '../i18next';
import { T } from 'inferno-i18next'; import { T } from 'inferno-i18next';
interface PrivateMessageFormProps { interface PrivateMessageFormProps {
recipient: UserView;
privateMessage?: PrivateMessage; // If a pm is given, that means this is an edit privateMessage?: PrivateMessage; // If a pm is given, that means this is an edit
params?: PrivateMessageFormParams;
onCancel?(): any; onCancel?(): any;
onCreate?(message: PrivateMessage): any; onCreate?(message: PrivateMessage): any;
onEdit?(message: PrivateMessage): any; onEdit?(message: PrivateMessage): any;
@ -37,7 +34,6 @@ interface PrivateMessageFormProps {
interface PrivateMessageFormState { interface PrivateMessageFormState {
privateMessageForm: PrivateMessageFormI; privateMessageForm: PrivateMessageFormI;
recipient: UserView;
loading: boolean; loading: boolean;
previewMode: boolean; previewMode: boolean;
showDisclaimer: boolean; showDisclaimer: boolean;
@ -51,9 +47,8 @@ export class PrivateMessageForm extends Component<
private emptyState: PrivateMessageFormState = { private emptyState: PrivateMessageFormState = {
privateMessageForm: { privateMessageForm: {
content: null, content: null,
recipient_id: null, recipient_id: this.props.recipient.id,
}, },
recipient: null,
loading: false, loading: false,
previewMode: false, previewMode: false,
showDisclaimer: false, showDisclaimer: false,
@ -66,30 +61,15 @@ export class PrivateMessageForm extends Component<
this.handleContentChange = this.handleContentChange.bind(this); this.handleContentChange = this.handleContentChange.bind(this);
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);
if (this.props.privateMessage) { if (this.props.privateMessage) {
this.state.privateMessageForm = { this.state.privateMessageForm = {
content: this.props.privateMessage.content, content: this.props.privateMessage.content,
recipient_id: this.props.privateMessage.recipient_id, recipient_id: this.props.privateMessage.recipient_id,
}; };
} }
if (this.props.params) {
this.state.privateMessageForm.recipient_id = this.props.params.recipient_id;
let form: GetUserDetailsForm = {
user_id: this.state.privateMessageForm.recipient_id,
sort: SortType.New,
saved_only: false,
};
WebSocketService.Instance.getUserDetails(form);
}
this.subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => this.parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
} }
componentDidMount() { componentDidMount() {
@ -105,8 +85,10 @@ export class PrivateMessageForm extends Component<
} }
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); if (isBrowser()) {
window.onbeforeunload = null; this.subscription.unsubscribe();
window.onbeforeunload = null;
}
} }
render() { render() {
@ -123,21 +105,18 @@ export class PrivateMessageForm extends Component<
{capitalizeFirstLetter(i18n.t('to'))} {capitalizeFirstLetter(i18n.t('to'))}
</label> </label>
{this.state.recipient && ( <div class="col-sm-10 form-control-plaintext">
<div class="col-sm-10 form-control-plaintext"> <UserListing
<UserListing user={{
user={{ name: this.props.recipient.name,
name: this.state.recipient.name, preferred_username: this.props.recipient.preferred_username,
preferred_username: this.state.recipient avatar: this.props.recipient.avatar,
.preferred_username, id: this.props.recipient.id,
avatar: this.state.recipient.avatar, local: this.props.recipient.local,
id: this.state.recipient.id, actor_id: this.props.recipient.actor_id,
local: this.state.recipient.local, }}
actor_id: this.state.recipient.actor_id, />
}} </div>
/>
</div>
)}
</div> </div>
)} )}
<div class="form-group row"> <div class="form-group row">
@ -233,11 +212,6 @@ export class PrivateMessageForm extends Component<
i.setState(i.state); i.setState(i.state);
} }
handleRecipientChange(i: PrivateMessageForm, event: any) {
i.state.recipient = event.target.value;
i.setState(i.state);
}
handleContentChange(val: string) { handleContentChange(val: string) {
this.state.privateMessageForm.content = val; this.state.privateMessageForm.content = val;
this.setState(this.state); this.setState(this.state);
@ -273,11 +247,6 @@ export class PrivateMessageForm extends Component<
let data = res.data as PrivateMessageResponse; let data = res.data as PrivateMessageResponse;
this.state.loading = false; this.state.loading = false;
this.props.onEdit(data.message); this.props.onEdit(data.message);
} else if (res.op == UserOperation.GetUserDetails) {
let data = res.data as UserDetailsResponse;
this.state.recipient = data.user;
this.state.privateMessageForm.recipient_id = data.user.id;
this.setState(this.state);
} else if (res.op == UserOperation.CreatePrivateMessage) { } else if (res.op == UserOperation.CreatePrivateMessage) {
let data = res.data as PrivateMessageResponse; let data = res.data as PrivateMessageResponse;
this.state.loading = false; this.state.loading = false;

View file

@ -8,6 +8,7 @@ import {
RemoveCommunityForm, RemoveCommunityForm,
UserView, UserView,
AddModToCommunityForm, AddModToCommunityForm,
Category,
} from 'lemmy-js-client'; } from 'lemmy-js-client';
import { WebSocketService, UserService } from '../services'; import { WebSocketService, UserService } from '../services';
import { mdToHtml, getUnixTime } from '../utils'; import { mdToHtml, getUnixTime } from '../utils';
@ -19,6 +20,7 @@ import { i18n } from '../i18next';
interface SidebarProps { interface SidebarProps {
community: Community; community: Community;
categories: Category[];
moderators: CommunityUser[]; moderators: CommunityUser[];
admins: UserView[]; admins: UserView[];
online: number; online: number;
@ -57,6 +59,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
this.sidebar() this.sidebar()
) : ( ) : (
<CommunityForm <CommunityForm
categories={this.props.categories}
community={this.props.community} community={this.props.community}
onEdit={this.handleEditCommunity} onEdit={this.handleEditCommunity}
onCancel={this.handleEditCancel} onCancel={this.handleEditCancel}
@ -193,7 +196,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
return ( return (
<div class="d-flex flex-wrap"> <div class="d-flex flex-wrap">
<Link <Link
class={`btn btn-secondary flex-fill mr-2 mb-2 ${ className={`btn btn-secondary flex-fill mr-2 mb-2 ${
community.deleted || community.removed ? 'no-click' : '' community.deleted || community.removed ? 'no-click' : ''
}`} }`}
to={`/create_post?community=${community.name}`} to={`/create_post?community=${community.name}`}

View file

@ -430,7 +430,7 @@ export class User extends Component<any, UserState> {
</a> </a>
<Link <Link
class="d-flex align-self-start btn btn-secondary ml-2" class="d-flex align-self-start btn btn-secondary ml-2"
to={`/create_private_message?recipient_id=${this.state.user.id}`} to={`/create_private_message/recipient/${this.state.user.id}`}
> >
{i18n.t('send_message')} {i18n.t('send_message')}
</Link> </Link>

View file

@ -23,8 +23,8 @@ interface IRoutePropsWithFetch extends IRouteProps {
export const routes: IRoutePropsWithFetch[] = [ export const routes: IRoutePropsWithFetch[] = [
{ {
exact: true,
path: `/`, path: `/`,
exact: true,
component: Main, component: Main,
fetchInitialData: (auth, path) => Main.fetchInitialData(auth, path), fetchInitialData: (auth, path) => Main.fetchInitialData(auth, path),
}, },
@ -46,8 +46,10 @@ export const routes: IRoutePropsWithFetch[] = [
CreateCommunity.fetchInitialData(auth, path), CreateCommunity.fetchInitialData(auth, path),
}, },
{ {
path: `/create_private_message`, path: `/create_private_message/recipient/:recipient_id`,
component: CreatePrivateMessage, component: CreatePrivateMessage,
fetchInitialData: (auth, path) =>
CreatePrivateMessage.fetchInitialData(auth, path),
}, },
{ {
path: `/communities/page/:page`, path: `/communities/page/:page`,

View file

@ -839,6 +839,12 @@ export function getPageFromProps(props: any): number {
return props.match.params.page ? Number(props.match.params.page) : 1; return props.match.params.page ? Number(props.match.params.page) : 1;
} }
export function getRecipientIdFromProps(props: any): number {
return props.match.params.recipient_id
? Number(props.match.params.recipient_id)
: 1;
}
export function editCommentRes(data: CommentResponse, comments: Comment[]) { export function editCommentRes(data: CommentResponse, comments: Comment[]) {
let found = comments.find(c => c.id == data.comment.id); let found = comments.find(c => c.id == data.comment.id);
if (found) { if (found) {