Skip to content

Commit

Permalink
Merge pull request #99 from Chat-Your-Way/CHAT-236-Interface-for-non-…
Browse files Browse the repository at this point in the history
…authenticated-user

Chat 236 interface for non authenticated user
  • Loading branch information
PDigitator authored Jul 14, 2024
2 parents b0a8bfa + e9fc766 commit f695070
Show file tree
Hide file tree
Showing 14 changed files with 215 additions and 36 deletions.
31 changes: 23 additions & 8 deletions src/components/Chat/Chat.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ import {
} from '../../redux/messagesAPI/messagesAPI';
import { selectAccessToken } from '../../redux/authOperatonsToolkit/authOperationsThunkSelectors';
import localLogOutUtil from '../../utils/localLogOutUtil';
import UsersAvatar from './UsersAvatar/';
import { useMediaQuery } from 'react-responsive';

const Chat = ({ children }) => {
const { title: topicId } = useParams();
Expand All @@ -94,11 +96,14 @@ const Chat = ({ children }) => {
currentData: currentMessagesByTopic,
isFetching: isFetchingMessagesByTopic,
error: messagesByTopicError,
} = useGetMessagesByTopicQuery(topicId, {
refetchOnMountOrArgChange: 10,
refetchOnFocus: true,
refetchOnReconnect: true,
});
} = useGetMessagesByTopicQuery(
{ topicId, accessTokenInStore },
{
refetchOnMountOrArgChange: 10,
refetchOnFocus: true,
refetchOnReconnect: true,
},
);

const { email } = useSelector(getUserInfo);
const { isTopics } = useTopicsContext();
Expand All @@ -113,6 +118,11 @@ const Chat = ({ children }) => {
const subscribed = useSelector(selectSubscribed);
const isChatOpened = useSelector(selectChatOpened);

const useMobileMediaQuery = () =>
// useMediaQuery({ query: '(max-width: 769px)' });
useMediaQuery({ query: '(max-width: 767px)' });
const isMobile = useMobileMediaQuery();

const [sendMessageToTopic, { error: sendMessageError }] =
useSendMessageToTopicMutation();

Expand Down Expand Up @@ -310,14 +320,19 @@ const Chat = ({ children }) => {
<ChatWrap>
<ChatHeader>
<UserBox>
<Avatar>{getAvatar(isTopics, topicIdData)}</Avatar>
<Avatar size={isMobile ? 'sm' : 'md'}>
{topicIdData ? getAvatar(isTopics, topicIdData) : null}
</Avatar>
<InfoBox>
<ChatUserName variant="h5">
<ChatUserName variant={isMobile ? 'h6' : 'h5'}>
{topicIdData ? topicIdData.name : 'імя користувача'}
</ChatUserName>
<TypingIndicator variant="h5">Ти/Пишеш...</TypingIndicator>
<TypingIndicator variant={isMobile ? 'h6' : 'h5'}>
Ти/Пишеш...
</TypingIndicator>
</InfoBox>
</UserBox>
<UsersAvatar topicId={topicId} />
<InfoMoreBox>
{children}
<TopicSettingsMenu
Expand Down
21 changes: 13 additions & 8 deletions src/components/Chat/Chat.styled.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,11 @@ export const ChatWrap = styled(Box)`
`;

export const ChatHeader = styled(Box)`
display: flex;
justify-content: space-between;
/* display: flex;
justify-content: space-between; */
display: grid;
grid-template-columns: 2fr 2fr 50px;
margin-bottom: 16px;
`;

Expand All @@ -55,29 +58,31 @@ export const UserBox = styled(Box)`
export const InfoBox = styled(Box)`
display: flex;
flex-direction: column;
padding: 8px 8px 0px 8px;
padding: 8px;
@media screen and (min-width: calc(845px - 0.02px)) {
padding: 8px 12px 4px 12px;
/* padding: 8px 12px 4px 12px; */
}
`;

export const ChatUserName = styled(Typography)`
margin-bottom: 4px;
color: ${(p) => p.theme.palette.primary.dark};
/* font-size: ${(p) => p.fontSize}; */
`;

export const TypingIndicator = styled(Typography)`
${(p) => p.theme.typography.h6};
/* ${(p) => p.theme.typography.h6}; */
color: #48a87a;
@media screen and (min-width: calc(845px - 0.02px)) {
${(p) => p.theme.typography.h5};
}
/* @media screen and (min-width: calc(845px - 0.02px)) {
${(p) => p.theme.typography.h5};
} */
`;

export const InfoMoreBox = styled(Box)`
display: flex;
gap: 4px;
justify-self: right;
`;

export const ChatSectionWrap = styled(Box)`
Expand Down
94 changes: 94 additions & 0 deletions src/components/Chat/UsersAvatar/UsersAvatar.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/* eslint-disable no-unused-vars */
import { useSelector } from 'react-redux';
import { useGetSubscribersQuery } from '../../../redux/topics-operations';
// eslint-disable-next-line max-len
import { selectAccessToken } from '../../../redux/authOperatonsToolkit/authOperationsThunkSelectors';
import { Avatars } from '../../../ui-kit/images/avatars';
import Avatar from '../../../ui-kit/components/Avatar';

import { getUserInfo } from '../../../redux/userSlice';
import { useMediaQuery } from 'react-responsive';
import {
UsersAvatarStyledList,
UsersAvatarStyledWrapper,
UsersAvatarStyledLi,
} from './UsersAvatarStyled';
import { memo } from 'react';

const UsersAvatar = ({ topicId }) => {
const accessTokenInStore = useSelector(selectAccessToken);
const isTablet = useMediaQuery({ query: '(min-width: 768px' });
const isDesktop = useMediaQuery({ query: '(mint-width: 1200px)' });

const {
isLoading,
isError,
error,
data: usersSubscribers,
} = useGetSubscribersQuery({ topicId, accessTokenInStore });

return (
<UsersAvatarStyledWrapper>
<UsersAvatarStyledList>
{usersSubscribers
? // ? usersSubscribers.map(user => (
// <UsersAvatarStyledLi key={user.id}>
// {Object.values(Avatars).map(
// (Logo, index) =>
// user.avatarId - 1 === index && (
// <Avatar size={isTablet ? 'md' : 'sm'} key={index} isCurrent={'true'}>
// <Logo />
// </Avatar>
// )
// )}
// </UsersAvatarStyledLi>
// ))
usersSubscribers.reduce((acuum, user, index, array) => {
if (index === 4) {
return [
...acuum,
<UsersAvatarStyledLi
key={user.id}
$left={index === 0 ? 0 : index * (isTablet ? 30 : 10)}
$width={isTablet ? '180px' : isDesktop ? '220px' : '94px'}
>
<Avatar
size={isTablet ? 'md' : 'sm'}
key={index}
isCurrent={'true'}
>
{usersSubscribers.length}
</Avatar>
</UsersAvatarStyledLi>,
];
}

acuum.push(
<UsersAvatarStyledLi
key={user.id}
$left={index === 0 ? 0 : index * (isTablet ? 30 : 10)}
>
{Object.values(Avatars).map(
(Logo, index) =>
user.avatarId - 1 === index && (
<Avatar
size={isTablet ? 'md' : 'sm'}
key={index}
isCurrent={'true'}
>
<Logo />
</Avatar>
),
)}
</UsersAvatarStyledLi>,
);

return acuum;
}, [])
: null}
</UsersAvatarStyledList>
</UsersAvatarStyledWrapper>
);
};

export default memo(UsersAvatar);
29 changes: 29 additions & 0 deletions src/components/Chat/UsersAvatar/UsersAvatarStyled.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import styled from '@emotion/styled';

export const UsersAvatarStyledWrapper = styled.div`
justify-self: right;
/* display: flex; */
`;

export const UsersAvatarStyledList = styled.ul`
position: relative;
display: flex;
justify-content: right;
/* flex-direction: row-reverse; */
margin: 0;
padding: 0;
width: 94px;
list-style: none;
@media screen and (min-width: 768px) {
width: 180px;
}
@media screen and (min-width: 1200px) {
width: 220px;
}
`;

export const UsersAvatarStyledLi = styled.li`
position: relative;
position: absolute;
left: ${(p) => `${p.$left}px`};
`;
1 change: 1 addition & 0 deletions src/components/Chat/UsersAvatar/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './UsersAvatar';
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function RegistrationPageComponent() {
};

try {
const { error } = await registration(userData);
const { error, data: registrationData } = await registration(userData);

if (error) {
if (
Expand All @@ -58,7 +58,8 @@ function RegistrationPageComponent() {
}
return;
}

localStorage.setItem('accessToken', registrationData.accessToken);
localStorage.setItem('refreshToken', registrationData.refreshToken);
navigate(PATH.VERIFICATION_EMAIL);
} catch (error) {
console.error('Виникла помилка під час заповнення форми:', error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ export const RegistrationWrapper = styled(Box)`
}
@media screen and (min-width: 1200px) {
padding: 5px 80px 164px 80px;
position: absolute;
transform: translateY(-50%);
top: 58%;
/* position: absolute; */
/* transform: translateY(-50%);
top: 58%; */
}
`;

Expand Down
2 changes: 1 addition & 1 deletion src/components/Routes/Route.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const Router = () => {
path={PATH.RECOVERY_PASSWORD}
element={<RecoveryPasswordPage />}
/>
<Route path={PATH.SUCCESS_SIGNUP} element={<SuccessSignupPage />} />
<Route path={'activate'} element={<SuccessSignupPage />} />
<Route
path={PATH.VERIFICATION_EMAIL}
element={<VerificationEmailPage />}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useSearchParams } from 'react-router-dom';
import { PATH } from '../../constans/routes';
import WhiteLayout from '../../ui-kit/components/WhiteLayout/WhiteLayout';
import {
Expand All @@ -6,16 +7,35 @@ import {
SuccessSignupWrapper,
Logo,
} from './SuccessSignupPageComponent.styled';
import { useActivateMutation } from '../../redux/auth-operations';
import { useEffect } from 'react';

function SuccessSignupPageComponent() {
const [searchParams] = useSearchParams();
const activationToken = searchParams.get('token');

const [activateEmail, { isError, isFetching }] = useActivateMutation();

useEffect(() => {
activateEmail({ activationToken });
}, [activateEmail, activationToken]);

return (
<WhiteLayout>
<SuccessSignupWrapper>
<Logo />
<SuccessSignupTitle variant="h2">
Ви успішно зареєструвались у ChatYourWay
{isFetching
? 'Отримуємо інформацію...'
: isError
? 'Щось пішло не так під час активації email'
: 'Ви успішно зареєструвались у ChatYourWay'}
</SuccessSignupTitle>
<LoginAccountButton label="Увійти в акаунт" to={PATH.LOGIN} />
<LoginAccountButton
label="Увійти в акаунт"
to={PATH.LOGIN}
isDisabled={isError}
/>
</SuccessSignupWrapper>
</WhiteLayout>
);
Expand Down
2 changes: 1 addition & 1 deletion src/constans/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const PATH = {
REGISTER: 'register',
RECOVERY_PASSWORD: '/recovery-password',
SETTINGS: 'settings',
SUCCESS_SIGNUP: '/success-signup',
SUCCESS_SIGNUP: '/activate',
TOPICS: 'topics',
VERIFICATION_EMAIL: '/verification-email',
};
15 changes: 9 additions & 6 deletions src/redux/auth-operations.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { BASE_URL, Referer, ajwt, rjwt } from './apiParams';
import { BASE_URL, Referer, ajwt } from './apiParams';

const authenticationApi = createApi({
reducerPath: 'authenticationApi',
Expand All @@ -17,10 +17,10 @@ const authenticationApi = createApi({
}),
}),
refresh: builder.mutation({
query: () => ({
query: ({ accessTokenInStore }) => ({
url: '/auth/refresh',
method: 'POST',
headers: { Authorization: `Bearer ${rjwt}` },
headers: { Authorization: `Bearer ${accessTokenInStore}` },
}),
}),
login: builder.mutation({
Expand All @@ -30,11 +30,14 @@ const authenticationApi = createApi({
body: body,
}),
}),

activate: builder.mutation({
query: (activationCode) => ({
url: `/auth/activate?Email%20token=${activationCode}`,
query: ({ activationToken }) => ({
url: `/auth/activate?Email%20token=${activationToken}`,
method: 'POST',
headers: { Authorization: `Bearer ${ajwt}` },
headers: {
Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
},
}),
}),
logout: builder.mutation({
Expand Down
4 changes: 2 additions & 2 deletions src/redux/messagesAPI/messagesAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ export const messagesAPI = createApi({
tagTypes: ['messages'],
endpoints: (builder) => ({
getMessagesByTopic: builder.query({
query: (topicId) => ({
query: ({ topicId, accessTokenInStore }) => ({
url: `messages/topic/${topicId}`,
headers: {
Referer: Referer,
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
Authorization: `Bearer ${accessTokenInStore}`,
},
}),
providesTags: ['messages'],
Expand Down
Loading

0 comments on commit f695070

Please sign in to comment.