1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-25 04:46:40 +07:00

removed profile redux items

This commit is contained in:
Fedor Katurov 2022-01-08 18:01:38 +07:00
parent 5b28313afd
commit 3c0571816c
55 changed files with 488 additions and 710 deletions

View file

@ -46,10 +46,7 @@ const NotificationsUnconnected: FC<IProps> = ({
return; return;
} }
return authOpenProfile( return authOpenProfile((notification as IMessageNotification).content.from!.username);
(notification as IMessageNotification).content.from!.username,
'messages'
);
default: default:
return; return;
} }

View file

@ -16,12 +16,12 @@ interface IProps {
const UserButton: FC<IProps> = ({ user: { username, photo }, authOpenProfile, onLogout }) => { const UserButton: FC<IProps> = ({ user: { username, photo }, authOpenProfile, onLogout }) => {
const onProfileOpen = useCallback(() => { const onProfileOpen = useCallback(() => {
if (!username) return; if (!username) return;
authOpenProfile(username, 'profile'); authOpenProfile(username);
}, [authOpenProfile, username]); }, [authOpenProfile, username]);
const onSettingsOpen = useCallback(() => { const onSettingsOpen = useCallback(() => {
if (!username) return; if (!username) return;
authOpenProfile(username, 'settings'); authOpenProfile(username);
}, [authOpenProfile, username]); }, [authOpenProfile, username]);
return ( return (

View file

@ -0,0 +1,45 @@
import React, { ChangeEvent, FC, useCallback } from 'react';
import styles from './styles.module.scss';
import { getURL } from '~/utils/dom';
import { PRESETS } from '~/constants/urls';
import { Icon } from '~/components/input/Icon';
import { IFile } from '~/redux/types';
export interface ProfileAvatarProps {
canEdit: boolean;
photo?: IFile;
onChangePhoto: (file: File) => void;
}
const ProfileAvatar: FC<ProfileAvatarProps> = ({ photo, onChangePhoto, canEdit }) => {
const onInputChange = useCallback(
async (event: ChangeEvent<HTMLInputElement>) => {
if (!event.target.files?.length) {
return;
}
onChangePhoto(event.target.files[0]);
},
[onChangePhoto]
);
const backgroundImage = photo ? `url("${getURL(photo, PRESETS.avatar)}")` : undefined;
return (
<div
className={styles.avatar}
style={{
backgroundImage,
}}
>
{canEdit && <input type="file" onInput={onInputChange} />}
{canEdit && (
<div className={styles.can_edit}>
<Icon icon="photo_add" />
</div>
)}
</div>
);
};
export { ProfileAvatar };

View file

@ -1,39 +1,33 @@
import React, { FC } from 'react'; import React, { FC } from 'react';
import { formatText } from '~/utils/dom'; import { formatText } from '~/utils/dom';
import styles from './styles.module.scss'; import styles from './styles.module.scss';
import { connect } from 'react-redux';
import { selectAuthProfile } from '~/redux/auth/selectors';
import { ProfileLoader } from '~/containers/profile/ProfileLoader'; import { ProfileLoader } from '~/containers/profile/ProfileLoader';
import { Group } from '~/components/containers/Group'; import { Group } from '~/components/containers/Group';
import markdown from '~/styles/common/markdown.module.scss'; import markdown from '~/styles/common/markdown.module.scss';
import classNames from 'classnames'; import classNames from 'classnames';
import { useProfileContext } from '~/utils/providers/ProfileProvider';
const mapStateToProps = state => ({ const ProfileDescription: FC = () => {
profile: selectAuthProfile(state), const { profile, isLoading } = useProfileContext();
});
type IProps = ReturnType<typeof mapStateToProps> & {}; if (isLoading) return <ProfileLoader />;
const ProfileDescriptionUnconnected: FC<IProps> = ({ profile: { user, is_loading } }) => {
if (is_loading) return <ProfileLoader />;
return ( return (
<div className={styles.wrap}> <div className={styles.wrap}>
{!!user?.description && ( {!!profile?.description && (
<Group <Group
className={classNames(styles.content, markdown.wrapper)} className={classNames(styles.content, markdown.wrapper)}
dangerouslySetInnerHTML={{ __html: formatText(user.description) }} dangerouslySetInnerHTML={{ __html: formatText(profile.description) }}
/> />
)} )}
{!user?.description && (
{!profile?.description && (
<div className={styles.placeholder}> <div className={styles.placeholder}>
{user?.fullname || user?.username} пока ничего не рассказал о себе {profile?.fullname || profile?.username} пока ничего не рассказал о себе
</div> </div>
)} )}
</div> </div>
); );
}; };
const ProfileDescription = connect(mapStateToProps)(ProfileDescriptionUnconnected);
export { ProfileDescription }; export { ProfileDescription };

View file

@ -1,35 +1,25 @@
import React, { FC, useCallback, useEffect, useState } from 'react'; import React, { FC, useCallback, useEffect, useState } from 'react';
import styles from './styles.module.scss'; import styles from './styles.module.scss';
import { connect } from 'react-redux';
import { selectAuthProfile, selectAuthUser } from '~/redux/auth/selectors';
import { Textarea } from '~/components/input/Textarea'; import { Textarea } from '~/components/input/Textarea';
import { Button } from '~/components/input/Button'; import { Button } from '~/components/input/Button';
import { Group } from '~/components/containers/Group'; import { Group } from '~/components/containers/Group';
import { Filler } from '~/components/containers/Filler'; import { Filler } from '~/components/containers/Filler';
import { InputText } from '~/components/input/InputText'; import { InputText } from '~/components/input/InputText';
import * as AUTH_ACTIONS from '~/redux/auth/actions';
import { ERROR_LITERAL } from '~/constants/errors'; import { ERROR_LITERAL } from '~/constants/errors';
import { ProfileAccounts } from '~/components/profile/ProfileAccounts'; import { ProfileAccounts } from '~/components/profile/ProfileAccounts';
import classNames from 'classnames'; import classNames from 'classnames';
import { useUser } from '~/hooks/user/userUser';
import { useProfileContext } from '~/utils/providers/ProfileProvider';
import { showErrorToast } from '~/utils/errors/showToast';
import { getValidationErrors } from '~/utils/errors/getValidationErrors';
import { showToastSuccess } from '~/utils/toast';
import { getRandomPhrase } from '~/constants/phrases';
const mapStateToProps = state => ({ const ProfileSettings: FC = () => {
user: selectAuthUser(state), const [errors, setErrors] = useState<Record<string, any>>({});
profile: selectAuthProfile(state), const user = useUser();
}); const { updateProfile } = useProfileContext();
const mapDispatchToProps = {
authPatchUser: AUTH_ACTIONS.authPatchUser,
authSetProfile: AUTH_ACTIONS.authSetProfile,
};
type IProps = ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps & {};
const ProfileSettingsUnconnected: FC<IProps> = ({
user,
profile: { patch_errors, socials },
authPatchUser,
authSetProfile,
}) => {
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [new_password, setNewPassword] = useState(''); const [new_password, setNewPassword] = useState('');
@ -39,12 +29,14 @@ const ProfileSettingsUnconnected: FC<IProps> = ({
data, data,
setData, setData,
]); ]);
const setEmail = useCallback(email => setData({ ...data, email }), [data, setData]); const setEmail = useCallback(email => setData({ ...data, email }), [data, setData]);
const setUsername = useCallback(username => setData({ ...data, username }), [data, setData]); const setUsername = useCallback(username => setData({ ...data, username }), [data, setData]);
const setFullname = useCallback(fullname => setData({ ...data, fullname }), [data, setData]); const setFullname = useCallback(fullname => setData({ ...data, fullname }), [data, setData]);
const onSubmit = useCallback( const onSubmit = useCallback(
event => { async event => {
try {
event.preventDefault(); event.preventDefault();
const fields = { const fields = {
@ -53,14 +45,24 @@ const ProfileSettingsUnconnected: FC<IProps> = ({
new_password: new_password.length > 0 && new_password ? new_password : undefined, new_password: new_password.length > 0 && new_password ? new_password : undefined,
}; };
authPatchUser(fields); await updateProfile(fields);
showToastSuccess(getRandomPhrase('SUCCESS'));
} catch (error) {
showErrorToast(error);
const validationErrors = getValidationErrors(error);
if (validationErrors) {
setErrors(validationErrors);
}
}
}, },
[data, password, new_password, authPatchUser] [data, password, new_password, updateProfile]
); );
useEffect(() => { useEffect(() => {
authSetProfile({ patch_errors: {} }); setErrors({});
}, [password, new_password, data, authSetProfile]); }, [password, new_password, data]);
return ( return (
<form className={styles.wrap} onSubmit={onSubmit}> <form className={styles.wrap} onSubmit={onSubmit}>
@ -74,7 +76,7 @@ const ProfileSettingsUnconnected: FC<IProps> = ({
value={data.fullname} value={data.fullname}
handler={setFullname} handler={setFullname}
title="Полное имя" title="Полное имя"
error={patch_errors.fullname && ERROR_LITERAL[patch_errors.fullname]} error={errors.fullname && ERROR_LITERAL[errors.fullname]}
/> />
<Textarea value={data.description} handler={setDescription} title="Описание" /> <Textarea value={data.description} handler={setDescription} title="Описание" />
@ -96,14 +98,14 @@ const ProfileSettingsUnconnected: FC<IProps> = ({
value={data.username} value={data.username}
handler={setUsername} handler={setUsername}
title="Логин" title="Логин"
error={patch_errors.username && ERROR_LITERAL[patch_errors.username]} error={errors.username && ERROR_LITERAL[errors.username]}
/> />
<InputText <InputText
value={data.email} value={data.email}
handler={setEmail} handler={setEmail}
title="E-mail" title="E-mail"
error={patch_errors.email && ERROR_LITERAL[patch_errors.email]} error={errors.email && ERROR_LITERAL[errors.email]}
/> />
<InputText <InputText
@ -111,7 +113,7 @@ const ProfileSettingsUnconnected: FC<IProps> = ({
handler={setNewPassword} handler={setNewPassword}
title="Новый пароль" title="Новый пароль"
type="password" type="password"
error={patch_errors.new_password && ERROR_LITERAL[patch_errors.new_password]} error={errors.new_password && ERROR_LITERAL[errors.new_password]}
/> />
<InputText <InputText
@ -119,7 +121,7 @@ const ProfileSettingsUnconnected: FC<IProps> = ({
handler={setPassword} handler={setPassword}
title="Старый пароль" title="Старый пароль"
type="password" type="password"
error={patch_errors.password && ERROR_LITERAL[patch_errors.password]} error={errors.password && ERROR_LITERAL[errors.password]}
/> />
<div className={styles.small}> <div className={styles.small}>
@ -150,6 +152,4 @@ const ProfileSettingsUnconnected: FC<IProps> = ({
); );
}; };
const ProfileSettings = connect(mapStateToProps, mapDispatchToProps)(ProfileSettingsUnconnected);
export { ProfileSettings }; export { ProfileSettings };

View file

@ -1,31 +0,0 @@
import React, { FC } from "react";
import styles from "./styles.module.scss";
import { ProfileAvatar } from "~/containers/profile/ProfileAvatar";
import { Placeholder } from "~/components/placeholders/Placeholder";
import { getPrettyDate } from "~/utils/dom";
import { IUser } from "~/redux/auth/types";
interface IProps {
is_loading: boolean;
user: IUser;
}
const ProfileSidebarInfo: FC<IProps> = ({ is_loading, user }) => (
<div className={styles.wrap}>
<div className={styles.avatar}>
<ProfileAvatar />
</div>
<div className={styles.field}>
<div className={styles.name}>
{is_loading ? <Placeholder width="80%" /> : user.fullname || user.username}
</div>
<div className={styles.description}>
{is_loading ? <Placeholder /> : getPrettyDate(user.last_seen)}
</div>
</div>
</div>
);
export { ProfileSidebarInfo };

View file

@ -1,41 +0,0 @@
@import "src/styles/variables";
.wrap.wrap {
justify-content: center;
align-items: center;
box-sizing: border-box;
position: relative;
flex: 0 0 100px;
display: flex;
margin: $gap;
box-shadow: transparentize(white, 0.95) 0 0 0 1px;
border-radius: $radius;
background: transparentize(black, 0.8);
}
.avatar {
border-radius: $radius;
width: 100px;
height: 100px;
background-size: cover;
position: relative;
flex: 0 0 100px;
left: -$gap;
margin-right: 10px;
}
.field {
flex: 1;
padding: $gap;
}
.name {
font: $font_24_bold;
margin-bottom: 4px;
}
.description {
color: transparentize($color: white, $amount: 0.7);
font: $font_14_regular;
text-transform: lowercase;
}

View file

@ -1,6 +1,7 @@
import { useMemo } from 'react'; import { useMemo } from 'react';
export const PHRASES = { export const PHRASES = {
SUCCESS: ['Готово! Что-нибудь ещё?'],
WELCOME: ['Ого! Кто это тут у нас?'], WELCOME: ['Ого! Кто это тут у нас?'],
GOODBYE: ['Возвращайся, мы будем скучать'], GOODBYE: ['Возвращайся, мы будем скучать'],
SIMPLE: [ SIMPLE: [

View file

@ -1,13 +1,13 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { Group } from '~/components/containers/Group'; import { Group } from "~/components/containers/Group";
import { NodeCommentForm } from '~/components/node/NodeCommentForm'; import { NodeCommentForm } from "~/components/node/NodeCommentForm";
import { NodeNoComments } from '~/components/node/NodeNoComments'; import { NodeNoComments } from "~/components/node/NodeNoComments";
import { NodeComments } from '~/containers/node/NodeComments'; import { NodeComments } from "~/containers/node/NodeComments";
import { Footer } from '~/components/main/Footer'; import { Footer } from "~/components/main/Footer";
import { CommentContextProvider, useCommentContext } from '~/utils/context/CommentContextProvider'; import { CommentContextProvider, useCommentContext } from "~/utils/context/CommentContextProvider";
import { useUserContext } from '~/utils/context/UserContextProvider'; import { useUserContext } from "~/utils/context/UserContextProvider";
import { useNodeContext } from '~/utils/context/NodeContextProvider'; import { useNodeContext } from "~/utils/context/NodeContextProvider";
interface IProps {} interface IProps {}

View file

@ -1,8 +1,8 @@
import React, { FC, MouseEventHandler, useEffect, useRef } from 'react'; import React, { FC, MouseEventHandler, useEffect, useRef } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { clearAllBodyScrollLocks, disableBodyScroll } from 'body-scroll-lock'; import { clearAllBodyScrollLocks, disableBodyScroll } from "body-scroll-lock";
import { Icon } from '~/components/input/Icon'; import { Icon } from "~/components/input/Icon";
import { LoaderCircle } from '~/components/input/LoaderCircle'; import { LoaderCircle } from "~/components/input/LoaderCircle";
interface IProps { interface IProps {
children: React.ReactChild; children: React.ReactChild;

View file

@ -1,24 +1,24 @@
import React, { createElement, FC, useCallback, useMemo, useState } from 'react'; import React, { createElement, FC, useCallback, useMemo, useState } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { NODE_EDITORS } from '~/constants/node'; import { NODE_EDITORS } from "~/constants/node";
import { BetterScrollDialog } from '../BetterScrollDialog'; import { BetterScrollDialog } from "../BetterScrollDialog";
import { CoverBackdrop } from '~/components/containers/CoverBackdrop'; import { CoverBackdrop } from "~/components/containers/CoverBackdrop";
import { prop } from 'ramda'; import { prop } from "ramda";
import { useNodeFormFormik } from '~/hooks/node/useNodeFormFormik'; import { useNodeFormFormik } from "~/hooks/node/useNodeFormFormik";
import { EditorButtons } from '~/components/editors/EditorButtons'; import { EditorButtons } from "~/components/editors/EditorButtons";
import { UploadSubject, UploadTarget } from '~/constants/uploads'; import { UploadSubject, UploadTarget } from "~/constants/uploads";
import { FormikProvider } from 'formik'; import { FormikProvider } from "formik";
import { INode } from '~/redux/types'; import { INode } from "~/redux/types";
import { ModalWrapper } from '~/components/dialogs/ModalWrapper'; import { ModalWrapper } from "~/components/dialogs/ModalWrapper";
import { useTranslatedError } from '~/hooks/data/useTranslatedError'; import { useTranslatedError } from "~/hooks/data/useTranslatedError";
import { useCloseOnEscape } from '~/hooks'; import { useCloseOnEscape } from "~/hooks";
import { EditorConfirmClose } from '~/components/editors/EditorConfirmClose'; import { EditorConfirmClose } from "~/components/editors/EditorConfirmClose";
import { IDialogProps } from '~/types/modal'; import { DialogComponentProps } from "~/types/modal";
import { useUploader } from '~/hooks/data/useUploader'; import { useUploader } from "~/hooks/data/useUploader";
import { UploaderContextProvider } from '~/utils/context/UploaderContextProvider'; import { UploaderContextProvider } from "~/utils/context/UploaderContextProvider";
import { observer } from 'mobx-react-lite'; import { observer } from "mobx-react-lite";
interface Props extends IDialogProps { interface Props extends DialogComponentProps {
node: INode; node: INode;
onSubmit: (node: INode) => Promise<unknown>; onSubmit: (node: INode) => Promise<unknown>;
} }

View file

@ -17,7 +17,7 @@ import { LoginDialogButtons } from '~/containers/dialogs/LoginDialogButtons';
import { OAUTH_EVENT_TYPES } from '~/redux/types'; import { OAUTH_EVENT_TYPES } from '~/redux/types';
import { DialogTitle } from '~/components/dialogs/DialogTitle'; import { DialogTitle } from '~/components/dialogs/DialogTitle';
import { useTranslatedError } from '~/hooks/data/useTranslatedError'; import { useTranslatedError } from '~/hooks/data/useTranslatedError';
import { IDialogProps } from '~/types/modal'; import { DialogComponentProps } from '~/types/modal';
import { useShowModal } from '~/hooks/modal/useShowModal'; import { useShowModal } from '~/hooks/modal/useShowModal';
import { Dialog } from '~/constants/modal'; import { Dialog } from '~/constants/modal';
@ -32,7 +32,9 @@ const mapDispatchToProps = {
authGotOauthLoginEvent: ACTIONS.authGotOauthLoginEvent, authGotOauthLoginEvent: ACTIONS.authGotOauthLoginEvent,
}; };
type IProps = ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps & IDialogProps & {}; type IProps = ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps &
DialogComponentProps & {};
const LoginDialogUnconnected: FC<IProps> = ({ const LoginDialogUnconnected: FC<IProps> = ({
error, error,

View file

@ -1,9 +1,9 @@
import React, { FC, MouseEventHandler } from 'react'; import React, { FC, MouseEventHandler } from "react";
import { Button } from '~/components/input/Button'; import { Button } from "~/components/input/Button";
import { Grid } from '~/components/containers/Grid'; import { Grid } from "~/components/containers/Grid";
import { Group } from '~/components/containers/Group'; import { Group } from "~/components/containers/Group";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { ISocialProvider } from '~/redux/auth/types'; import { ISocialProvider } from "~/redux/auth/types";
interface IProps { interface IProps {
openOauthWindow: (provider: ISocialProvider) => MouseEventHandler; openOauthWindow: (provider: ISocialProvider) => MouseEventHandler;

View file

@ -1,6 +1,6 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import { Button } from '~/components/input/Button'; import { Button } from "~/components/input/Button";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
interface IProps {} interface IProps {}

View file

@ -11,7 +11,7 @@ import * as AUTH_ACTIONS from '~/redux/auth/actions';
import { useCloseOnEscape } from '~/hooks'; import { useCloseOnEscape } from '~/hooks';
import { LoginSocialRegisterButtons } from '~/containers/dialogs/LoginSocialRegisterButtons'; import { LoginSocialRegisterButtons } from '~/containers/dialogs/LoginSocialRegisterButtons';
import { Toggle } from '~/components/input/Toggle'; import { Toggle } from '~/components/input/Toggle';
import { IDialogProps } from '~/types/modal'; import { DialogComponentProps } from '~/types/modal';
const mapStateToProps = selectAuthRegisterSocial; const mapStateToProps = selectAuthRegisterSocial;
const mapDispatchToProps = { const mapDispatchToProps = {
@ -20,7 +20,9 @@ const mapDispatchToProps = {
authSendRegisterSocial: AUTH_ACTIONS.authSendRegisterSocial, authSendRegisterSocial: AUTH_ACTIONS.authSendRegisterSocial,
}; };
type Props = ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps & IDialogProps & {}; type Props = ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps &
DialogComponentProps & {};
const phrase = [ const phrase = [
'Сушёный кабачок особенно хорош в это время года, знаете ли.', 'Сушёный кабачок особенно хорош в это время года, знаете ли.',

View file

@ -1,9 +1,9 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import { ModalWrapper } from '~/components/dialogs/ModalWrapper'; import { ModalWrapper } from "~/components/dialogs/ModalWrapper";
import { DIALOG_CONTENT } from '~/constants/modal'; import { DIALOG_CONTENT } from "~/constants/modal";
import { useModalStore } from '~/store/modal/useModalStore'; import { useModalStore } from "~/store/modal/useModalStore";
import { has } from 'ramda'; import { has } from "ramda";
import { observer } from 'mobx-react-lite'; import { observer } from "mobx-react-lite";
type IProps = {}; type IProps = {};

View file

@ -10,9 +10,9 @@ import { useBlockBackButton } from '~/hooks/navigation/useBlockBackButton';
import { useModal } from '~/hooks/modal/useModal'; import { useModal } from '~/hooks/modal/useModal';
import { observer } from 'mobx-react'; import { observer } from 'mobx-react';
import { IFile } from '~/redux/types'; import { IFile } from '~/redux/types';
import { IDialogProps } from '~/types/modal'; import { DialogComponentProps } from '~/types/modal';
export interface PhotoSwipeProps extends IDialogProps { export interface PhotoSwipeProps extends DialogComponentProps {
items: IFile[]; items: IFile[];
index: number; index: number;
} }

View file

@ -1,60 +1,31 @@
import React, { FC, useCallback } from 'react'; import React, { FC } from 'react';
import { BetterScrollDialog } from '../BetterScrollDialog'; import { BetterScrollDialog } from '../BetterScrollDialog';
import { ProfileInfo } from '~/containers/profile/ProfileInfo'; import { ProfileInfo } from '~/containers/profile/ProfileInfo';
import { connect } from 'react-redux';
import { selectAuthProfile, selectAuthUser } from '~/redux/auth/selectors';
import * as AUTH_ACTIONS from '~/redux/auth/actions';
import { IAuthState } from '~/redux/auth/types';
import { pick } from 'ramda';
import { CoverBackdrop } from '~/components/containers/CoverBackdrop'; import { CoverBackdrop } from '~/components/containers/CoverBackdrop';
import { Tabs } from '~/components/dialogs/Tabs'; import { Tabs } from '~/components/dialogs/Tabs';
import { ProfileDescription } from '~/components/profile/ProfileDescription'; import { ProfileDescription } from '~/components/profile/ProfileDescription';
import { ProfileMessages } from '~/containers/profile/ProfileMessages'; import { ProfileMessages } from '~/containers/profile/ProfileMessages';
import { ProfileSettings } from '~/components/profile/ProfileSettings'; import { ProfileSettings } from '~/components/profile/ProfileSettings';
import { ProfileAccounts } from '~/components/profile/ProfileAccounts'; import { ProfileAccounts } from '~/components/profile/ProfileAccounts';
import { IDialogProps } from '~/types/modal'; import { DialogComponentProps } from '~/types/modal';
import { useUser } from '~/hooks/user/userUser';
import { useGetProfile } from '~/hooks/profile/useGetProfile';
import { ProfileProvider } from '~/utils/providers/ProfileProvider';
const mapStateToProps = state => ({ export interface ProfileDialogProps extends DialogComponentProps {
profile: selectAuthProfile(state), username: string;
user: pick(['id'], selectAuthUser(state)), }
});
const mapDispatchToProps = { const ProfileDialog: FC<ProfileDialogProps> = ({ username, onRequestClose }) => {
authSetProfile: AUTH_ACTIONS.authSetProfile, const { isLoading, profile } = useGetProfile(username);
}; const { id } = useUser();
type IProps = IDialogProps & ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps & {};
const PROFILE_HEADERS = {};
const PROFILE_FOOTERS = {};
const ProfileDialogUnconnected: FC<IProps> = ({
onRequestClose,
authSetProfile,
profile: { is_loading, user, tab },
user: { id },
}) => {
const setTab = useCallback((val: IAuthState['profile']['tab']) => authSetProfile({ tab: val }), [
authSetProfile,
]);
return ( return (
<ProfileProvider username={username}>
<Tabs> <Tabs>
<BetterScrollDialog <BetterScrollDialog
header={ header={<ProfileInfo isOwn={profile.id === id} isLoading={isLoading} />}
<ProfileInfo backdrop={<CoverBackdrop cover={profile.cover} />}
is_own={user && user.id === id}
is_loading={is_loading}
user={user}
tab={tab}
setTab={setTab}
content={PROFILE_HEADERS[tab]}
/>
}
footer={PROFILE_FOOTERS[tab]}
backdrop={<CoverBackdrop cover={user && user.cover} />}
onClose={onRequestClose} onClose={onRequestClose}
> >
<Tabs.Content> <Tabs.Content>
@ -65,9 +36,8 @@ const ProfileDialogUnconnected: FC<IProps> = ({
</Tabs.Content> </Tabs.Content>
</BetterScrollDialog> </BetterScrollDialog>
</Tabs> </Tabs>
</ProfileProvider>
); );
}; };
const ProfileDialog = connect(mapStateToProps, mapDispatchToProps)(ProfileDialogUnconnected);
export { ProfileDialog }; export { ProfileDialog };

View file

@ -12,7 +12,7 @@ import { selectAuthRestore } from '~/redux/auth/selectors';
import { ERROR_LITERAL, ERRORS } from '~/constants/errors'; import { ERROR_LITERAL, ERRORS } from '~/constants/errors';
import { Icon } from '~/components/input/Icon'; import { Icon } from '~/components/input/Icon';
import { useCloseOnEscape } from '~/hooks'; import { useCloseOnEscape } from '~/hooks';
import { IDialogProps } from '~/types/modal'; import { DialogComponentProps } from '~/types/modal';
const mapStateToProps = state => ({ const mapStateToProps = state => ({
restore: selectAuthRestore(state), restore: selectAuthRestore(state),
@ -20,7 +20,9 @@ const mapStateToProps = state => ({
const mapDispatchToProps = pick(['authRestorePassword', 'authSetRestore'], AUTH_ACTIONS); const mapDispatchToProps = pick(['authRestorePassword', 'authSetRestore'], AUTH_ACTIONS);
type IProps = IDialogProps & ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps & {}; type IProps = DialogComponentProps &
ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps & {};
const RestorePasswordDialogUnconnected: FC<IProps> = ({ const RestorePasswordDialogUnconnected: FC<IProps> = ({
restore: { error, is_loading, is_succesfull, user }, restore: { error, is_loading, is_succesfull, user },

View file

@ -1,21 +1,21 @@
import React, { useCallback, useEffect, useMemo, useState, VFC } from 'react'; import React, { useCallback, useEffect, useMemo, useState, VFC } from "react";
import { useDispatch } from 'react-redux'; import { useDispatch } from "react-redux";
import { BetterScrollDialog } from '../BetterScrollDialog'; import { BetterScrollDialog } from "../BetterScrollDialog";
import { Group } from '~/components/containers/Group'; import { Group } from "~/components/containers/Group";
import { InputText } from '~/components/input/InputText'; import { InputText } from "~/components/input/InputText";
import { Button } from '~/components/input/Button'; import { Button } from "~/components/input/Button";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import * as AUTH_ACTIONS from '~/redux/auth/actions'; import * as AUTH_ACTIONS from "~/redux/auth/actions";
import { selectAuthRestore } from '~/redux/auth/selectors'; import { selectAuthRestore } from "~/redux/auth/selectors";
import { ERROR_LITERAL } from '~/constants/errors'; import { ERROR_LITERAL } from "~/constants/errors";
import { Icon } from '~/components/input/Icon'; import { Icon } from "~/components/input/Icon";
import { useCloseOnEscape } from '~/hooks'; import { useCloseOnEscape } from "~/hooks";
import { IDialogProps } from '~/types/modal'; import { DialogComponentProps } from "~/types/modal";
import { useShallowSelect } from '~/hooks/data/useShallowSelect'; import { useShallowSelect } from "~/hooks/data/useShallowSelect";
import { IAuthState } from '~/redux/auth/types'; import { IAuthState } from "~/redux/auth/types";
interface RestoreRequestDialogProps extends IDialogProps {} interface RestoreRequestDialogProps extends DialogComponentProps {}
const RestoreRequestDialog: VFC<RestoreRequestDialogProps> = ({ onRequestClose }) => { const RestoreRequestDialog: VFC<RestoreRequestDialogProps> = ({ onRequestClose }) => {
const dispatch = useDispatch(); const dispatch = useDispatch();

View file

@ -1,6 +1,6 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import { BetterScrollDialog } from '../BetterScrollDialog'; import { BetterScrollDialog } from "../BetterScrollDialog";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
interface IProps {} interface IProps {}

View file

@ -1,17 +1,17 @@
import React, { FC, FormEvent, useCallback, useMemo } from 'react'; import React, { FC, FormEvent, useCallback, useMemo } from "react";
import { InputText } from '~/components/input/InputText'; import { InputText } from "~/components/input/InputText";
import { FlowRecent } from '~/components/flow/FlowRecent'; import { FlowRecent } from "~/components/flow/FlowRecent";
import styles from '~/containers/flow/FlowStamp/styles.module.scss'; import styles from "~/containers/flow/FlowStamp/styles.module.scss";
import { FlowSearchResults } from '~/components/flow/FlowSearchResults'; import { FlowSearchResults } from "~/components/flow/FlowSearchResults";
import { Icon } from '~/components/input/Icon'; import { Icon } from "~/components/input/Icon";
import { Group } from '~/components/containers/Group'; import { Group } from "~/components/containers/Group";
import { Toggle } from '~/components/input/Toggle'; import { Toggle } from "~/components/input/Toggle";
import classNames from 'classnames'; import classNames from "classnames";
import { Superpower } from '~/components/boris/Superpower'; import { Superpower } from "~/components/boris/Superpower";
import { experimentalFeatures } from '~/constants/features'; import { experimentalFeatures } from "~/constants/features";
import { useSearchContext } from '~/utils/providers/SearchProvider'; import { useSearchContext } from "~/utils/providers/SearchProvider";
import { useFlowContext } from '~/utils/context/FlowContextProvider'; import { useFlowContext } from "~/utils/context/FlowContextProvider";
interface IProps { interface IProps {
isFluid: boolean; isFluid: boolean;

View file

@ -1,12 +1,12 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { LabBanner } from '~/components/lab/LabBanner'; import { LabBanner } from "~/components/lab/LabBanner";
import { Group } from '~/components/containers/Group'; import { Group } from "~/components/containers/Group";
import { LabTags } from '~/components/lab/LabTags'; import { LabTags } from "~/components/lab/LabTags";
import { LabHeroes } from '~/components/lab/LabHeroes'; import { LabHeroes } from "~/components/lab/LabHeroes";
import { FlowRecentItem } from '~/components/flow/FlowRecentItem'; import { FlowRecentItem } from "~/components/flow/FlowRecentItem";
import { SubTitle } from '~/components/common/SubTitle'; import { SubTitle } from "~/components/common/SubTitle";
import { useLabContext } from '~/utils/context/LabContextProvider'; import { useLabContext } from "~/utils/context/LabContextProvider";
interface IProps {} interface IProps {}

View file

@ -1,6 +1,6 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { PlayerView } from '~/containers/player/PlayerView'; import { PlayerView } from "~/containers/player/PlayerView";
type IProps = {}; type IProps = {};

View file

@ -1,6 +1,6 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import classNames from 'classnames'; import classNames from "classnames";
interface IProps { interface IProps {
className?: string; className?: string;

View file

@ -1,14 +1,14 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import { URLS } from '~/constants/urls'; import { URLS } from "~/constants/urls";
import { ErrorNotFound } from '~/containers/pages/ErrorNotFound'; import { ErrorNotFound } from "~/containers/pages/ErrorNotFound";
import { Redirect, Route, Switch, useLocation } from 'react-router'; import { Redirect, Route, Switch, useLocation } from "react-router";
import { useShallowSelect } from '~/hooks/data/useShallowSelect'; import { useShallowSelect } from "~/hooks/data/useShallowSelect";
import { selectAuthUser } from '~/redux/auth/selectors'; import { selectAuthUser } from "~/redux/auth/selectors";
import { ProfileLayout } from '~/layouts/ProfileLayout'; import { ProfileLayout } from "~/layouts/ProfileLayout";
import FlowPage from '~/pages'; import FlowPage from "~/pages";
import BorisPage from '~/pages/boris'; import BorisPage from "~/pages/boris";
import NodePage from '~/pages/node/[id]'; import NodePage from "~/pages/node/[id]";
import LabPage from '~/pages/lab'; import LabPage from "~/pages/lab";
interface IProps {} interface IProps {}

View file

@ -1,11 +1,10 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import { createPortal } from 'react-dom'; import { createPortal } from "react-dom";
import { Route, Switch } from 'react-router'; import { Route, Switch } from "react-router";
import { TagSidebar } from '~/containers/sidebars/TagSidebar'; import { TagSidebar } from "~/containers/sidebars/TagSidebar";
import { ProfileSidebar } from '~/containers/sidebars/ProfileSidebar'; import { Authorized } from "~/components/containers/Authorized";
import { Authorized } from '~/components/containers/Authorized'; import { SubmitBar } from "~/components/bars/SubmitBar";
import { SubmitBar } from '~/components/bars/SubmitBar'; import { EditorCreateDialog } from "~/containers/dialogs/EditorCreateDialog";
import { EditorCreateDialog } from '~/containers/dialogs/EditorCreateDialog';
interface IProps { interface IProps {
prefix?: string; prefix?: string;
@ -18,7 +17,6 @@ const SidebarRouter: FC<IProps> = ({ prefix = '', isLab }) => {
<Switch> <Switch>
<Route path={`${prefix}/create/:type`} component={EditorCreateDialog} /> <Route path={`${prefix}/create/:type`} component={EditorCreateDialog} />
<Route path={`${prefix}/tag/:tag`} component={TagSidebar} /> <Route path={`${prefix}/tag/:tag`} component={TagSidebar} />
<Route path={`${prefix}/~:username`} component={ProfileSidebar} />
</Switch> </Switch>
<Authorized> <Authorized>

View file

@ -1,20 +1,20 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import { NodeDeletedBadge } from '~/components/node/NodeDeletedBadge'; import { NodeDeletedBadge } from "~/components/node/NodeDeletedBadge";
import { Group } from '~/components/containers/Group'; import { Group } from "~/components/containers/Group";
import { Padder } from '~/components/containers/Padder'; import { Padder } from "~/components/containers/Padder";
import { NodeCommentForm } from '~/components/node/NodeCommentForm'; import { NodeCommentForm } from "~/components/node/NodeCommentForm";
import { NodeRelatedBlock } from '~/components/node/NodeRelatedBlock'; import { NodeRelatedBlock } from "~/components/node/NodeRelatedBlock";
import { useNodeBlocks } from '~/hooks/node/useNodeBlocks'; import { useNodeBlocks } from "~/hooks/node/useNodeBlocks";
import { NodeTagsBlock } from '~/components/node/NodeTagsBlock'; import { NodeTagsBlock } from "~/components/node/NodeTagsBlock";
import StickyBox from 'react-sticky-box'; import StickyBox from "react-sticky-box";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { NodeAuthorBlock } from '~/components/node/NodeAuthorBlock'; import { NodeAuthorBlock } from "~/components/node/NodeAuthorBlock";
import { useNodeContext } from '~/utils/context/NodeContextProvider'; import { useNodeContext } from "~/utils/context/NodeContextProvider";
import { useCommentContext } from '~/utils/context/CommentContextProvider'; import { useCommentContext } from "~/utils/context/CommentContextProvider";
import { NodeNoComments } from '~/components/node/NodeNoComments'; import { NodeNoComments } from "~/components/node/NodeNoComments";
import { NodeComments } from '~/containers/node/NodeComments'; import { NodeComments } from "~/containers/node/NodeComments";
import { useUserContext } from '~/utils/context/UserContextProvider'; import { useUserContext } from "~/utils/context/UserContextProvider";
import { useNodeRelatedContext } from '~/utils/context/NodeRelatedContextProvider'; import { useNodeRelatedContext } from "~/utils/context/NodeRelatedContextProvider";
interface IProps { interface IProps {
commentsOrder: 'ASC' | 'DESC'; commentsOrder: 'ASC' | 'DESC';

View file

@ -1,13 +1,13 @@
import React, { FC, memo, useMemo } from 'react'; import React, { FC, memo, useMemo } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { ICommentGroup } from '~/redux/types'; import { ICommentGroup } from "~/redux/types";
import { canEditComment } from '~/utils/node'; import { canEditComment } from "~/utils/node";
import { useGrouppedComments } from '~/hooks/node/useGrouppedComments'; import { useGrouppedComments } from "~/hooks/node/useGrouppedComments";
import { useCommentContext } from '~/utils/context/CommentContextProvider'; import { useCommentContext } from "~/utils/context/CommentContextProvider";
import { Comment } from '~/components/comment/Comment'; import { Comment } from "~/components/comment/Comment";
import { useUserContext } from '~/utils/context/UserContextProvider'; import { useUserContext } from "~/utils/context/UserContextProvider";
import { useNodeContext } from '~/utils/context/NodeContextProvider'; import { useNodeContext } from "~/utils/context/NodeContextProvider";
interface IProps { interface IProps {
order: 'ASC' | 'DESC'; order: 'ASC' | 'DESC';

View file

@ -1,6 +1,6 @@
import React, { VFC } from 'react'; import React, { VFC } from "react";
import { PlayerBar } from '~/components/bars/PlayerBar'; import { PlayerBar } from "~/components/bars/PlayerBar";
import { useAudioPlayer } from '~/utils/providers/AudioPlayerProvider'; import { useAudioPlayer } from "~/utils/providers/AudioPlayerProvider";
interface PlayerViewProps {} interface PlayerViewProps {}

View file

@ -1,76 +0,0 @@
import React, { ChangeEvent, FC, useCallback } from 'react';
import styles from './styles.module.scss';
import { connect } from 'react-redux';
import { getURL } from '~/utils/dom';
import { pick } from 'ramda';
import { selectAuthProfile, selectAuthUser } from '~/redux/auth/selectors';
import { PRESETS } from '~/constants/urls';
import { UploadSubject, UploadTarget } from '~/constants/uploads';
import * as AUTH_ACTIONS from '~/redux/auth/actions';
import { Icon } from '~/components/input/Icon';
import { useUploader } from '~/hooks/data/useUploader';
import { observer } from 'mobx-react-lite';
import { showErrorToast } from '~/utils/errors/showToast';
const mapStateToProps = state => ({
user: pick(['id'], selectAuthUser(state)),
profile: pick(['is_loading', 'user'], selectAuthProfile(state)),
});
const mapDispatchToProps = {
authPatchUser: AUTH_ACTIONS.authPatchUser,
};
type IProps = ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps & {};
const ProfileAvatarUnconnected: FC<IProps> = observer(
({ user: { id }, profile: { is_loading, user }, authPatchUser }) => {
const uploader = useUploader(
UploadSubject.Avatar,
UploadTarget.Profiles,
user?.photo ? [] : []
);
const onInputChange = useCallback(
async (event: ChangeEvent<HTMLInputElement>) => {
try {
if (!event.target.files?.length) {
return;
}
const photo = await uploader.uploadFile(event.target.files[0]);
authPatchUser({ photo });
} catch (error) {
showErrorToast(error);
}
},
[uploader, authPatchUser]
);
const can_edit = !is_loading && id && id === user?.id;
const backgroundImage = is_loading
? undefined
: `url("${user && getURL(user.photo, PRESETS.avatar)}")`;
return (
<div
className={styles.avatar}
style={{
backgroundImage,
}}
>
{can_edit && <input type="file" onInput={onInputChange} />}
{can_edit && (
<div className={styles.can_edit}>
<Icon icon="photo_add" />
</div>
)}
</div>
);
}
);
const ProfileAvatar = connect(mapStateToProps, mapDispatchToProps)(ProfileAvatarUnconnected);
export { ProfileAvatar };

View file

@ -1,44 +1,39 @@
import React, { FC, ReactNode } from 'react'; import React, { FC } from "react";
import { IAuthState, IUser } from '~/redux/auth/types'; import styles from "./styles.module.scss";
import styles from './styles.module.scss'; import { Group } from "~/components/containers/Group";
import { Group } from '~/components/containers/Group'; import { Placeholder } from "~/components/placeholders/Placeholder";
import { Placeholder } from '~/components/placeholders/Placeholder'; import { getPrettyDate } from "~/utils/dom";
import { getPrettyDate } from '~/utils/dom'; import { ProfileTabs } from "../ProfileTabs";
import { ProfileTabs } from '../ProfileTabs'; import { ProfileAvatar } from "~/components/profile/ProfileAvatar";
import { ProfileAvatar } from '../ProfileAvatar'; import { useProfileContext } from "~/utils/providers/ProfileProvider";
interface IProps { interface IProps {
user?: IUser; isLoading?: boolean;
tab: string; isOwn: boolean;
is_loading?: boolean;
is_own?: boolean;
setTab?: (tab: IAuthState['profile']['tab']) => void;
content?: ReactNode;
} }
const ProfileInfo: FC<IProps> = ({ user, tab, is_loading, is_own, setTab, content = null }) => ( const ProfileInfo: FC<IProps> = ({ isOwn }) => {
const { updatePhoto, profile, isLoading } = useProfileContext();
return (
<div> <div>
<Group className={styles.wrap} horizontal> <Group className={styles.wrap} horizontal>
<ProfileAvatar /> <ProfileAvatar canEdit={isOwn} onChangePhoto={updatePhoto} photo={profile.photo} />
<div className={styles.field}> <div className={styles.field}>
<div className={styles.name}> <div className={styles.name}>
{is_loading ? <Placeholder width="80%" /> : user?.fullname || user?.username} {isLoading ? <Placeholder width="80%" /> : profile?.fullname || profile?.username}
</div> </div>
<div className={styles.description}> <div className={styles.description}>
{is_loading ? <Placeholder /> : getPrettyDate(user?.last_seen)} {isLoading ? <Placeholder /> : getPrettyDate(profile?.last_seen)}
</div> </div>
</div> </div>
</Group> </Group>
<ProfileTabs tab={tab} is_own={!!is_own} setTab={setTab} /> <ProfileTabs is_own={isOwn} />
{content}
</div> </div>
); );
};
export { ProfileInfo }; export { ProfileInfo };

View file

@ -1,6 +1,6 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { LoaderCircle } from '~/components/input/LoaderCircle'; import { LoaderCircle } from "~/components/input/LoaderCircle";
interface IProps {} interface IProps {}

View file

@ -2,18 +2,17 @@ import React, { FC } from 'react';
import styles from './styles.module.scss'; import styles from './styles.module.scss';
import { Message } from '~/components/profile/Message'; import { Message } from '~/components/profile/Message';
import { NodeNoComments } from '~/components/node/NodeNoComments'; import { NodeNoComments } from '~/components/node/NodeNoComments';
import { useShallowSelect } from '~/hooks/data/useShallowSelect';
import { selectAuthProfile } from '~/redux/auth/selectors';
import { useMessages } from '~/hooks/messages/useMessages'; import { useMessages } from '~/hooks/messages/useMessages';
import { useUser } from '~/hooks/user/userUser'; import { useUser } from '~/hooks/user/userUser';
import { useProfileContext } from '~/utils/providers/ProfileProvider';
const ProfileMessages: FC = () => { const ProfileMessages: FC = () => {
const profile = useShallowSelect(selectAuthProfile); const { profile, isLoading: isLoadingProfile } = useProfileContext();
const user = useUser(); const user = useUser();
const { messages, isLoading } = useMessages(profile.user?.username || ''); const { messages, isLoading: isLoadingMessages } = useMessages(profile?.username || '');
if (!messages.length || profile.is_loading) if (!messages.length || isLoadingProfile)
return <NodeNoComments is_loading={isLoading || profile.is_loading} />; return <NodeNoComments is_loading={isLoadingMessages || isLoadingProfile} />;
if (messages.length <= 0) { if (messages.length <= 0) {
return null; return null;
@ -42,7 +41,7 @@ const ProfileMessages: FC = () => {
<Message message={message} incoming={user.id !== message.from.id} key={message.id} /> <Message message={message} incoming={user.id !== message.from.id} key={message.id} />
))} ))}
{!isLoading && messages.length > 0 && ( {!isLoadingMessages && messages.length > 0 && (
<div className={styles.placeholder}>Когда-нибудь здесь будут еще сообщения</div> <div className={styles.placeholder}>Когда-нибудь здесь будут еще сообщения</div>
)} )}
</div> </div>

View file

@ -1,42 +1,40 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import { IAuthState } from '~/redux/auth/types'; import { IUser } from "~/redux/auth/types";
import { formatText } from '~/utils/dom'; import { formatText } from "~/utils/dom";
import { PRESETS } from '~/constants/urls'; import { PRESETS } from "~/constants/urls";
import { Placeholder } from '~/components/placeholders/Placeholder'; import { Placeholder } from "~/components/placeholders/Placeholder";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { Avatar } from '~/components/common/Avatar'; import { Avatar } from "~/components/common/Avatar";
import { Markdown } from '~/components/containers/Markdown'; import { Markdown } from "~/components/containers/Markdown";
interface IProps { interface IProps {
profile: IAuthState['profile']; profile: IUser;
isLoading: boolean;
username: string; username: string;
} }
const ProfilePageLeft: FC<IProps> = ({ username, profile }) => { const ProfilePageLeft: FC<IProps> = ({ username, profile, isLoading }) => {
return ( return (
<div className={styles.wrap}> <div className={styles.wrap}>
<Avatar <Avatar
username={username} username={username}
url={profile.user?.photo?.url} url={profile?.photo?.url}
className={styles.avatar} className={styles.avatar}
preset={PRESETS['600']} preset={PRESETS['600']}
/> />
<div className={styles.region}> <div className={styles.region}>
<div className={styles.name}> <div className={styles.name}>{isLoading ? <Placeholder /> : profile?.fullname}</div>`
{profile.is_loading ? <Placeholder /> : profile?.user?.fullname}
</div>
<div className={styles.username}> <div className={styles.username}>
{profile.is_loading ? <Placeholder /> : `~${profile?.user?.username}`} {isLoading ? <Placeholder /> : `~${profile?.username}`}
</div> </div>
</div> </div>
{profile && profile.user && profile.user.description && ( {!!profile?.description && (
<Markdown <Markdown
className={styles.description} className={styles.description}
dangerouslySetInnerHTML={{ __html: formatText(profile.user.description) }} dangerouslySetInnerHTML={{ __html: formatText(profile.description) }}
/> />
)} )}
</div> </div>

View file

@ -1,7 +1,7 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { StatsRow } from '~/components/common/StatsRow'; import { StatsRow } from "~/components/common/StatsRow";
import { SubTitle } from '~/components/common/SubTitle'; import { SubTitle } from "~/components/common/SubTitle";
interface Props {} interface Props {}

View file

@ -1,15 +1,12 @@
import React, { FC } from 'react'; import React, { FC } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { IAuthState } from '~/redux/auth/types'; import { Tabs } from "~/components/dialogs/Tabs";
import { Tabs } from '~/components/dialogs/Tabs';
interface IProps { interface IProps {
tab: string;
is_own: boolean; is_own: boolean;
setTab?: (tab: IAuthState['profile']['tab']) => void;
} }
const ProfileTabs: FC<IProps> = ({ tab, is_own, setTab }) => { const ProfileTabs: FC<IProps> = ({ is_own }) => {
const items = ['Профиль', 'Сообщения', ...(is_own ? ['Настройки'] : [])]; const items = ['Профиль', 'Сообщения', ...(is_own ? ['Настройки'] : [])];
return ( return (

View file

@ -1,69 +0,0 @@
import React, { FC, useCallback, useEffect } from 'react';
import styles from './styles.module.scss';
import { SidebarWrapper } from '~/containers/sidebars/SidebarWrapper';
import { connect } from 'react-redux';
import { selectAuthProfile, selectAuthUser } from '~/redux/auth/selectors';
import pick from 'ramda/es/pick';
import { ProfileSidebarInfo } from '~/components/profile/ProfileSidebarInfo';
import { Filler } from '~/components/containers/Filler';
import { Route, Switch, useHistory, useRouteMatch } from 'react-router';
import * as USER_ACTIONS from '~/redux/auth/actions';
import { ProfileSidebarMenu } from '~/components/profile/ProfileSidebarMenu';
import { useCloseOnEscape } from '~/hooks';
import { Icon } from '~/components/input/Icon';
import { ProfileSidebarSettings } from '~/components/profile/ProfileSidebarSettings';
import classNames from 'classnames';
const mapStateToProps = state => ({
profile: selectAuthProfile(state),
user: pick(['id'], selectAuthUser(state)),
});
const mapDispatchToProps = {
authLoadProfile: USER_ACTIONS.authLoadProfile,
};
type Props = ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps & {};
const ProfileSidebarUnconnected: FC<Props> = ({
profile: { is_loading, user },
user: { id },
authLoadProfile,
}) => {
const {
params: { username },
url,
} = useRouteMatch<{ username: string }>();
useEffect(() => {
authLoadProfile(username);
}, [authLoadProfile, username]);
const history = useHistory();
const basePath = url.replace(new RegExp(`\/~${username}$`), '');
const onClose = useCallback(() => history.push(basePath), [basePath, history]);
useCloseOnEscape(onClose);
return (
<SidebarWrapper>
<div className={styles.close} onClick={onClose}>
<Icon icon="close" size={32} />
</div>
<Switch>
<Route path={`${url}/settings`} component={ProfileSidebarSettings} />
</Switch>
<div className={classNames(styles.wrap, styles.secondary)}>
{!!user && <ProfileSidebarInfo is_loading={is_loading} user={user} />}
<ProfileSidebarMenu path={url} />
<Filler />
</div>
</SidebarWrapper>
);
};
const ProfileSidebar = connect(mapStateToProps, mapDispatchToProps)(ProfileSidebarUnconnected);
export { ProfileSidebar };

View file

@ -1,33 +0,0 @@
@import "src/styles/variables";
.wrap {
@include sidebar_content;
display: flex;
flex-direction: column;
position: relative;
z-index: 2;
&.secondary {
background: transparentize($content_bg, 0.2);
}
}
.close {
position: absolute;
right: 0;
top: 0;
padding: $gap / 2;
background: $content_bg;
z-index: 6;
border-radius: 0 0 0 $radius;
cursor: pointer;
transition: all 100ms;
display: flex;
align-items: center;
justify-content: center;
&:hover {
fill: $red;
}
}

View file

@ -1,8 +1,8 @@
import React, { FC, useEffect, useRef } from 'react'; import React, { FC, useEffect, useRef } from "react";
import styles from './styles.module.scss'; import styles from "./styles.module.scss";
import { createPortal } from 'react-dom'; import { createPortal } from "react-dom";
import { clearAllBodyScrollLocks, disableBodyScroll } from 'body-scroll-lock'; import { clearAllBodyScrollLocks, disableBodyScroll } from "body-scroll-lock";
import { useCloseOnEscape } from '~/hooks'; import { useCloseOnEscape } from "~/hooks";
interface IProps { interface IProps {
onClose?: () => void; onClose?: () => void;

View file

@ -1,10 +1,10 @@
import React, { FC, HTMLAttributes, useCallback, useMemo, useState } from 'react'; import React, { FC, HTMLAttributes, useCallback, useMemo, useState } from "react";
import { TagField } from '~/components/containers/TagField'; import { TagField } from "~/components/containers/TagField";
import { ITag } from '~/redux/types'; import { ITag } from "~/redux/types";
import { uniq } from 'ramda'; import { uniq } from "ramda";
import { Tag } from '~/components/tags/Tag'; import { Tag } from "~/components/tags/Tag";
import { TagInput } from '~/containers/tags/TagInput'; import { TagInput } from "~/containers/tags/TagInput";
import { separateTags } from '~/utils/tag'; import { separateTags } from "~/utils/tag";
type IProps = HTMLAttributes<HTMLDivElement> & { type IProps = HTMLAttributes<HTMLDivElement> & {
tags: Partial<ITag>[]; tags: Partial<ITag>[];

View file

@ -1,11 +1,11 @@
import { useModalStore } from '~/store/modal/useModalStore'; import { useModalStore } from '~/store/modal/useModalStore';
import { useCallback } from 'react'; import { useCallback } from 'react';
import { Dialog, DIALOG_CONTENT } from '~/constants/modal'; import { Dialog, DIALOG_CONTENT } from '~/constants/modal';
import { IDialogProps } from '~/types/modal'; import { DialogComponentProps } from '~/types/modal';
export type DialogContentProps = { export type DialogContentProps = {
[K in keyof typeof DIALOG_CONTENT]: typeof DIALOG_CONTENT[K] extends (props: infer U) => any [K in keyof typeof DIALOG_CONTENT]: typeof DIALOG_CONTENT[K] extends (props: infer U) => any
? U extends IDialogProps ? U extends DialogComponentProps
? keyof Omit<U, 'onRequestClose' | 'children'> extends never ? keyof Omit<U, 'onRequestClose' | 'children'> extends never
? {} ? {}
: Omit<U, 'onRequestClose' | 'children'> : Omit<U, 'onRequestClose' | 'children'>

View file

@ -0,0 +1,34 @@
import useSWR from 'swr';
import { API } from '~/constants/api';
import { apiAuthGetUserProfile } from '~/redux/auth/api';
import { EMPTY_USER } from '~/redux/auth/constants';
import { useCallback } from 'react';
import { IUser } from '~/redux/auth/types';
const getKey = (username?: string): string | null => {
return username ? `${API.USER.PROFILE}/${username}` : null;
};
export const useGetProfile = (username?: string) => {
const { data, isValidating, mutate } = useSWR(
getKey(username),
async () => {
const result = await apiAuthGetUserProfile({ username: username || '' });
return result.user;
},
{
refreshInterval: 60000,
}
);
const profile = data || EMPTY_USER;
const update = useCallback(
async (user: Partial<IUser>) => {
await mutate({ ...profile, ...user });
},
[mutate, profile]
);
return { profile, isLoading: !data && isValidating, update };
};

View file

@ -0,0 +1,30 @@
import { useUploader } from '~/hooks/data/useUploader';
import { UploadSubject, UploadTarget } from '~/constants/uploads';
import { useCallback } from 'react';
import { showErrorToast } from '~/utils/errors/showToast';
import { IUser } from '~/redux/auth/types';
import { apiUpdateUser } from '~/redux/auth/api';
export const usePatchProfile = (updateUserData: (user: Partial<IUser>) => void) => {
const { uploadFile } = useUploader(UploadSubject.Avatar, UploadTarget.Profiles);
const updateProfile = useCallback(async (user: Partial<IUser>) => {
const result = await apiUpdateUser({ user });
await updateUserData(result.user);
return result.user;
}, []);
const updatePhoto = useCallback(
async (file: File) => {
try {
const photo = await uploadFile(file);
await updateProfile({ photo });
} catch (error) {
showErrorToast(error);
}
},
[updateUserData, uploadFile, updateProfile]
);
return { updatePhoto, updateProfile };
};

View file

@ -1,10 +1,8 @@
import React, { FC, useEffect } from "react"; import React, { FC } from "react";
import styles from "./styles.module.scss"; import styles from "./styles.module.scss";
import { RouteComponentProps } from "react-router"; import { RouteComponentProps } from "react-router";
import { useDispatch } from "react-redux";
import { authLoadProfile } from "~/redux/auth/actions";
import { useShallowSelect } from "~/hooks/data/useShallowSelect"; import { useShallowSelect } from "~/hooks/data/useShallowSelect";
import { selectAuthProfile, selectUser } from "~/redux/auth/selectors"; import { selectUser } from "~/redux/auth/selectors";
import { ProfilePageLeft } from "~/containers/profile/ProfilePageLeft"; import { ProfilePageLeft } from "~/containers/profile/ProfilePageLeft";
import { Container } from "~/containers/main/Container"; import { Container } from "~/containers/main/Container";
import { FlowGrid } from "~/components/flow/FlowGrid"; import { FlowGrid } from "~/components/flow/FlowGrid";
@ -12,6 +10,7 @@ import { ProfilePageStats } from "~/containers/profile/ProfilePageStats";
import { Card } from "~/components/containers/Card"; import { Card } from "~/components/containers/Card";
import { useFlowStore } from "~/store/flow/useFlowStore"; import { useFlowStore } from "~/store/flow/useFlowStore";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import { useGetProfile } from "~/hooks/profile/useGetProfile";
type Props = RouteComponentProps<{ username: string }> & {}; type Props = RouteComponentProps<{ username: string }> & {};
@ -23,26 +22,19 @@ const ProfileLayout: FC<Props> = observer(
}) => { }) => {
const { nodes } = useFlowStore(); const { nodes } = useFlowStore();
const user = useShallowSelect(selectUser); const user = useShallowSelect(selectUser);
const { profile, isLoading } = useGetProfile(username);
const dispatch = useDispatch();
useEffect(() => {
dispatch(authLoadProfile(username));
}, [dispatch, username]);
const profile = useShallowSelect(selectAuthProfile);
return ( return (
<Container className={styles.wrap}> <Container className={styles.wrap}>
<div className={styles.grid}> <div className={styles.grid}>
<div className={styles.stamp}> <div className={styles.stamp}>
<div className={styles.row}> <div className={styles.row}>
<ProfilePageLeft profile={profile} username={username} /> <ProfilePageLeft profile={profile} username={username} isLoading={isLoading} />
</div> </div>
{!!profile.user?.description && ( {!!profile?.description && (
<div className={styles.row}> <div className={styles.row}>
<Card className={styles.description}>{profile.user.description}</Card> <Card className={styles.description}>{profile.description}</Card>
</div> </div>
)} )}

View file

@ -43,20 +43,9 @@ export const authLoggedIn = () => ({
type: AUTH_USER_ACTIONS.LOGGED_IN, type: AUTH_USER_ACTIONS.LOGGED_IN,
}); });
export const authOpenProfile = (username: string, tab?: IAuthState['profile']['tab']) => ({ export const authOpenProfile = (username: string) => ({
type: AUTH_USER_ACTIONS.OPEN_PROFILE, type: AUTH_USER_ACTIONS.OPEN_PROFILE,
username, username,
tab,
});
export const authLoadProfile = (username: string) => ({
type: AUTH_USER_ACTIONS.LOAD_PROFILE,
username,
});
export const authSetProfile = (profile: Partial<IAuthState['profile']>) => ({
type: AUTH_USER_ACTIONS.SET_PROFILE,
profile,
}); });
export const authSetUpdates = (updates: Partial<IAuthState['updates']>) => ({ export const authSetUpdates = (updates: Partial<IAuthState['updates']>) => ({
@ -71,11 +60,6 @@ export const authSetLastSeenMessages = (
last_seen_messages, last_seen_messages,
}); });
export const authPatchUser = (user: Partial<IUser>) => ({
type: AUTH_USER_ACTIONS.PATCH_USER,
user,
});
export const authRequestRestoreCode = (field: string) => ({ export const authRequestRestoreCode = (field: string) => ({
type: AUTH_USER_ACTIONS.REQUEST_RESTORE_CODE, type: AUTH_USER_ACTIONS.REQUEST_RESTORE_CODE,
field, field,

View file

@ -12,12 +12,9 @@ export const AUTH_USER_ACTIONS = {
GOT_AUTH_POST_MESSAGE: 'GOT_POST_MESSAGE', GOT_AUTH_POST_MESSAGE: 'GOT_POST_MESSAGE',
OPEN_PROFILE: 'OPEN_PROFILE', OPEN_PROFILE: 'OPEN_PROFILE',
LOAD_PROFILE: 'LOAD_PROFILE',
SET_PROFILE: 'SET_PROFILE',
SET_UPDATES: 'SET_UPDATES', SET_UPDATES: 'SET_UPDATES',
SET_LAST_SEEN_MESSAGES: 'SET_LAST_SEEN_MESSAGES', SET_LAST_SEEN_MESSAGES: 'SET_LAST_SEEN_MESSAGES',
PATCH_USER: 'PATCH_USER',
SET_RESTORE: 'SET_RESTORE', SET_RESTORE: 'SET_RESTORE',
REQUEST_RESTORE_CODE: 'REQUEST_RESTORE_CODE', REQUEST_RESTORE_CODE: 'REQUEST_RESTORE_CODE',

View file

@ -35,14 +35,6 @@ const setToken: ActionHandler<typeof ActionCreators.authSetToken> = (state, { to
token, token,
}); });
const setProfile: ActionHandler<typeof ActionCreators.authSetProfile> = (state, { profile }) => ({
...state,
profile: {
...state.profile,
...profile,
},
});
const setUpdates: ActionHandler<typeof ActionCreators.authSetUpdates> = (state, { updates }) => ({ const setUpdates: ActionHandler<typeof ActionCreators.authSetUpdates> = (state, { updates }) => ({
...state, ...state,
updates: { updates: {
@ -111,7 +103,6 @@ export const AUTH_USER_HANDLERS = {
[AUTH_USER_ACTIONS.SET_USER]: setUser, [AUTH_USER_ACTIONS.SET_USER]: setUser,
[AUTH_USER_ACTIONS.SET_STATE]: setState, [AUTH_USER_ACTIONS.SET_STATE]: setState,
[AUTH_USER_ACTIONS.SET_TOKEN]: setToken, [AUTH_USER_ACTIONS.SET_TOKEN]: setToken,
[AUTH_USER_ACTIONS.SET_PROFILE]: setProfile,
[AUTH_USER_ACTIONS.SET_UPDATES]: setUpdates, [AUTH_USER_ACTIONS.SET_UPDATES]: setUpdates,
[AUTH_USER_ACTIONS.SET_LAST_SEEN_MESSAGES]: setLastSeenMessages, [AUTH_USER_ACTIONS.SET_LAST_SEEN_MESSAGES]: setLastSeenMessages,
[AUTH_USER_ACTIONS.SET_RESTORE]: setRestore, [AUTH_USER_ACTIONS.SET_RESTORE]: setRestore,

View file

@ -25,7 +25,6 @@ const INITIAL_STATE: IAuthState = {
}, },
profile: { profile: {
tab: 'profile',
is_loading: true, is_loading: true,
user: undefined, user: undefined,

View file

@ -4,16 +4,13 @@ import {
authAttachSocial, authAttachSocial,
authDropSocial, authDropSocial,
authGotOauthLoginEvent, authGotOauthLoginEvent,
authLoadProfile,
authLoggedIn, authLoggedIn,
authLoginWithSocial, authLoginWithSocial,
authOpenProfile, authOpenProfile,
authPatchUser,
authRequestRestoreCode, authRequestRestoreCode,
authRestorePassword, authRestorePassword,
authSendRegisterSocial, authSendRegisterSocial,
authSetLastSeenMessages, authSetLastSeenMessages,
authSetProfile,
authSetRegisterSocial, authSetRegisterSocial,
authSetRegisterSocialErrors, authSetRegisterSocialErrors,
authSetRestore, authSetRestore,
@ -30,7 +27,6 @@ import {
apiAttachSocial, apiAttachSocial,
apiAuthGetUpdates, apiAuthGetUpdates,
apiAuthGetUser, apiAuthGetUser,
apiAuthGetUserProfile,
apiCheckRestoreCode, apiCheckRestoreCode,
apiDropSocial, apiDropSocial,
apiGetSocials, apiGetSocials,
@ -51,14 +47,12 @@ import {
import { OAUTH_EVENT_TYPES, Unwrap } from '../types'; import { OAUTH_EVENT_TYPES, Unwrap } from '../types';
import { REHYDRATE, RehydrateAction } from 'redux-persist'; import { REHYDRATE, RehydrateAction } from 'redux-persist';
import { ERRORS } from '~/constants/errors'; import { ERRORS } from '~/constants/errors';
import { SagaIterator } from 'redux-saga';
import { AxiosError } from 'axios'; import { AxiosError } from 'axios';
import { getMOBXStore } from '~/store'; import { getMOBXStore } from '~/store';
import { Dialog } from '~/constants/modal'; import { Dialog } from '~/constants/modal';
import { showErrorToast } from '~/utils/errors/showToast'; import { showErrorToast } from '~/utils/errors/showToast';
import { showToastInfo } from '~/utils/toast'; import { showToastInfo } from '~/utils/toast';
import { getRandomPhrase } from '~/constants/phrases'; import { getRandomPhrase } from '~/constants/phrases';
import { getValidationErrors } from '~/utils/errors/getValidationErrors';
import { getErrorMessage } from '~/utils/errors/getErrorMessage'; import { getErrorMessage } from '~/utils/errors/getErrorMessage';
const modalStore = getMOBXStore().modal; const modalStore = getMOBXStore().modal;
@ -134,30 +128,8 @@ function* logoutSaga() {
showToastInfo(getRandomPhrase('GOODBYE')); showToastInfo(getRandomPhrase('GOODBYE'));
} }
function* loadProfile({ username }: ReturnType<typeof authLoadProfile>): SagaIterator<boolean> { function openProfile({ username }: ReturnType<typeof authOpenProfile>) {
yield put(authSetProfile({ is_loading: true })); modalStore.setCurrent(Dialog.Profile, { username });
try {
const { user }: Unwrap<typeof apiAuthGetUserProfile> = yield call(apiAuthGetUserProfile, {
username,
});
yield put(authSetProfile({ is_loading: false, user }));
return true;
} catch (error) {
return false;
}
}
function* openProfile({ username, tab = 'profile' }: ReturnType<typeof authOpenProfile>) {
modalStore.setCurrent(Dialog.Profile, {});
yield put(authSetProfile({ tab }));
const success: Unwrap<typeof loadProfile> = yield call(loadProfile, authLoadProfile(username));
if (!success) {
modalStore.hide();
}
} }
function* getUpdates() { function* getUpdates() {
@ -213,27 +185,6 @@ function* setLastSeenMessages({ last_seen_messages }: ReturnType<typeof authSetL
yield call(apiUpdateUser, { user: { last_seen_messages } }); yield call(apiUpdateUser, { user: { last_seen_messages } });
} }
function* patchUser(payload: ReturnType<typeof authPatchUser>) {
const me: ReturnType<typeof selectAuthUser> = yield select(selectAuthUser);
try {
const { user }: Unwrap<typeof apiUpdateUser> = yield call(apiUpdateUser, {
user: payload.user,
});
yield put(authSetUser({ ...me, ...user }));
yield put(authSetProfile({ user: { ...me, ...user }, tab: 'profile' }));
} catch (error) {
showErrorToast(error);
const patch_errors = getValidationErrors(error);
if (!patch_errors) return;
yield put(authSetProfile({ patch_errors }));
}
}
function* requestRestoreCode({ field }: ReturnType<typeof authRequestRestoreCode>) { function* requestRestoreCode({ field }: ReturnType<typeof authRequestRestoreCode>) {
if (!field) return; if (!field) return;
@ -445,9 +396,7 @@ function* authSaga() {
yield takeLatest(AUTH_USER_ACTIONS.SEND_LOGIN_REQUEST, sendLoginRequestSaga); yield takeLatest(AUTH_USER_ACTIONS.SEND_LOGIN_REQUEST, sendLoginRequestSaga);
yield takeLatest(AUTH_USER_ACTIONS.GOT_AUTH_POST_MESSAGE, gotPostMessageSaga); yield takeLatest(AUTH_USER_ACTIONS.GOT_AUTH_POST_MESSAGE, gotPostMessageSaga);
yield takeLatest(AUTH_USER_ACTIONS.OPEN_PROFILE, openProfile); yield takeLatest(AUTH_USER_ACTIONS.OPEN_PROFILE, openProfile);
yield takeLatest(AUTH_USER_ACTIONS.LOAD_PROFILE, loadProfile);
yield takeLatest(AUTH_USER_ACTIONS.SET_LAST_SEEN_MESSAGES, setLastSeenMessages); yield takeLatest(AUTH_USER_ACTIONS.SET_LAST_SEEN_MESSAGES, setLastSeenMessages);
yield takeLatest(AUTH_USER_ACTIONS.PATCH_USER, patchUser);
yield takeLatest(AUTH_USER_ACTIONS.REQUEST_RESTORE_CODE, requestRestoreCode); yield takeLatest(AUTH_USER_ACTIONS.REQUEST_RESTORE_CODE, requestRestoreCode);
yield takeLatest(AUTH_USER_ACTIONS.SHOW_RESTORE_MODAL, showRestoreModal); yield takeLatest(AUTH_USER_ACTIONS.SHOW_RESTORE_MODAL, showRestoreModal);
yield takeLatest(AUTH_USER_ACTIONS.RESTORE_PASSWORD, restorePassword); yield takeLatest(AUTH_USER_ACTIONS.RESTORE_PASSWORD, restorePassword);

View file

@ -3,10 +3,8 @@ import { IState } from '~/redux/store';
export const selectAuth = (state: IState) => state.auth; export const selectAuth = (state: IState) => state.auth;
export const selectUser = (state: IState) => state.auth.user; export const selectUser = (state: IState) => state.auth.user;
export const selectAuthIsTester = (state: IState) => state.auth.is_tester; export const selectAuthIsTester = (state: IState) => state.auth.is_tester;
export const selectToken = (state: IState) => state.auth.token;
export const selectAuthLogin = (state: IState) => state.auth.login; export const selectAuthLogin = (state: IState) => state.auth.login;
export const selectAuthProfile = (state: IState) => state.auth.profile; export const selectAuthProfile = (state: IState) => state.auth.profile;
export const selectAuthProfileUsername = (state: IState) => state.auth.profile.user?.username;
export const selectAuthUser = (state: IState) => state.auth.user; export const selectAuthUser = (state: IState) => state.auth.user;
export const selectAuthUpdates = (state: IState) => state.auth.updates; export const selectAuthUpdates = (state: IState) => state.auth.updates;
export const selectAuthRestore = (state: IState) => state.auth.restore; export const selectAuthRestore = (state: IState) => state.auth.restore;

View file

@ -52,7 +52,6 @@ export type IAuthState = Readonly<{
}; };
profile: { profile: {
tab: 'profile' | 'messages' | 'settings';
is_loading: boolean; is_loading: boolean;
user?: IUser; user?: IUser;

View file

@ -1,3 +1,3 @@
export interface IDialogProps { export interface DialogComponentProps {
onRequestClose: () => void; onRequestClose: () => void;
} }

View file

@ -0,0 +1,55 @@
import { createContext, FC, useCallback, useContext } from "react";
import { IUser } from "~/redux/auth/types";
import { useGetProfile } from "~/hooks/profile/useGetProfile";
import { EMPTY_USER } from "~/redux/auth/constants";
import { usePatchProfile } from "~/hooks/profile/usePatchProfile";
import { useUser } from "~/hooks/user/userUser";
import { useDispatch } from "react-redux";
import { authSetUser } from "~/redux/auth/actions";
interface ProfileProviderProps {
username: string;
}
interface ProfileContextValue {
profile: IUser;
isLoading: boolean;
updatePhoto: (file: File) => Promise<unknown>;
updateProfile: (user: Partial<IUser>) => Promise<IUser>;
}
const ProfileContext = createContext<ProfileContextValue>({
profile: EMPTY_USER,
isLoading: false,
updatePhoto: async () => {},
updateProfile: async () => EMPTY_USER,
});
export const ProfileProvider: FC<ProfileProviderProps> = ({ children, username }) => {
const dispatch = useDispatch();
const user = useUser();
const { profile, isLoading, update: updateProfileData } = useGetProfile(username);
const update = useCallback(
async (data: Partial<IUser>) => {
if (profile.id === user.id) {
await updateProfileData(data);
}
// TODO: user updateUser from useGetUser or something
dispatch(authSetUser(data));
},
[updateProfileData, dispatch, profile, user]
);
const { updatePhoto, updateProfile } = usePatchProfile(update);
return (
<ProfileContext.Provider value={{ profile, isLoading, updatePhoto, updateProfile }}>
{children}
</ProfileContext.Provider>
);
};
export const useProfileContext = () => useContext(ProfileContext);