Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/docs fetch #59

Merged
merged 5 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions src/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import localStorageKeys from '@/shared/constants/localStorageKeys';
import AppContextProvider from '@/shared/Context/AppContext';
import colorThemeSwitcher from '@/shared/helpers/colorThemeSwitcher';
import EditorProvider from '@components/Editor/context/EditorProvider';
import AuthProvider from '@shared/Context/AuthContext';
import LanguageProvider from '@shared/Context/LanguageContext';

const App = () => {
Expand All @@ -21,11 +20,9 @@ const App = () => {
return (
<EditorProvider>
<AppContextProvider>
<AuthProvider>
<LanguageProvider>
<RouterProvider router={router} />
</LanguageProvider>
</AuthProvider>
<LanguageProvider>
<RouterProvider router={router} />
</LanguageProvider>
</AppContextProvider>
</EditorProvider>
);
Expand Down
22 changes: 22 additions & 0 deletions src/components/DocsComp/lib/helpers/getEndpointSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { SetStateAction } from 'react';

import introspectionQuery from '@/shared/constants/introspectionQuery';
import { DocsSchemaType } from '@/shared/types';

export default async function getEndpointSchema(
endpoint: string,
setter: (value: SetStateAction<DocsSchemaType>) => void,
) {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(introspectionQuery),
});
if (response.ok && response.status === 200) {
const res = await response.json();
return setter(res.data.__schema);
}
return setter(null);
}
20 changes: 14 additions & 6 deletions src/components/DocsComp/ui/DocsModal.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
// AFTER LOGIC FOR SAVING AND FETCHING ENDPOINT SHEMA WILL BE ADDED - MUST REMOVE SCHEMA IMPORT AND REPLACE IT FOR DOWNLOADED SCHEMA IN FURTHER CODE
import { Dispatch, SetStateAction, useEffect } from 'react';

import { Dispatch, SetStateAction } from 'react';

import { swapiSchema } from '@/shared/constants/schemaData';
import { useAppContext } from '@/shared/Context/hooks';
import { DocsExplorerType, SchemaTypeObj } from '@/shared/types';
import CloseDocsBtn from '@components/DocsComp/ui/CloseDocsBtn';

import DocsRootComp from './DocsRootComp';
import DocsTypeComp from './DocsTypeComp';
import SchemaFallaback from './schemaFallback';
import getEndpointSchema from '../lib/helpers/getEndpointSchema';

type PropsType = {
setIsDocsShown: Dispatch<SetStateAction<boolean>>;
explorer: DocsExplorerType;
};

const DocsModal = ({ setIsDocsShown, explorer }: PropsType) => {
const { currEndpoint, setEndpointSchema, endpointSchema } = useAppContext();
useEffect(() => {
getEndpointSchema(currEndpoint, setEndpointSchema);
}, [currEndpoint, setEndpointSchema]);

if (!endpointSchema) return <SchemaFallaback closeModal={setIsDocsShown} />;

const content = explorer.isDocs() ? (
<DocsRootComp types={swapiSchema.data.__schema.types as SchemaTypeObj[]} explorer={explorer} />
<DocsRootComp types={endpointSchema.types as SchemaTypeObj[]} explorer={explorer} />
) : (
<DocsTypeComp
explorer={explorer}
currType={swapiSchema.data.__schema.types.find((elem) => elem.name === explorer.current()) as SchemaTypeObj}
currType={endpointSchema.types.find((elem) => elem.name === explorer.current()) as SchemaTypeObj}
/>
);

return (
<section className="relative z-20 h-[100dvh] w-[270px] cursor-auto rounded-r-[28px] bg-surface p-3 sm:w-[420px]">
<CloseDocsBtn
Expand Down
23 changes: 23 additions & 0 deletions src/components/DocsComp/ui/schemaFallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { FC, SetStateAction } from 'react';

import CloseDocsBtn from './CloseDocsBtn';

type PropsType = {
closeModal: (value: SetStateAction<boolean>) => void;
};

const SchemaFallaback: FC<PropsType> = ({ closeModal }) => {
return (
<div className="relative z-20 flex h-[100dvh] w-[270px] cursor-auto items-center rounded-r-[28px] bg-surface p-3 sm:w-[420px]">
<CloseDocsBtn
onClick={() => {
closeModal((prev) => !prev);
}}
className="absolute right-[20px] top-[20px] z-20"
/>
<p className="w-full p-6 text-center text-on-surface">There is no schema at provided endpoint :(</p>
</div>
);
};

export default SchemaFallaback;
5 changes: 5 additions & 0 deletions src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useState } from 'react';

import { Link, useLocation, useNavigate } from 'react-router-dom';

import useAuth from '@/shared/Context/authHook';
import { useLanguage } from '@/shared/Context/hooks';
import Icon from '@/shared/ui/Icon';
import IconButton from '@/shared/ui/IconButton';
Expand All @@ -17,6 +18,7 @@ const Header = () => {
const isSettings = pathname.slice(1) === ROUTES.SETTINGS;
const navigate = useNavigate();
const isMobile = useScreen() === 'mobile';
const { logOut } = useAuth();

const docsTooltip = translation.mainLayout.header.tooltips.docs;

Expand Down Expand Up @@ -46,6 +48,9 @@ const Header = () => {
<Link to={ROUTES.WELCOME_PAGE}>GraphiQL</Link>
</h1>
)}
<button type="button" onClick={() => logOut()}>
Log out
</button>
<IconButton
onClick={() => setIsDocsShown((prev) => !prev)}
data-tooltip={docsTooltip}
Expand Down
18 changes: 6 additions & 12 deletions src/components/SettingsPageComp/EndpointComp.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
import { FC } from 'react';

import { useLanguage } from '@/shared/Context/hooks';
import { useAppContext, useLanguage } from '@/shared/Context/hooks';
import FilledTextField from '@/shared/ui/FilledTextField';
import Icon from '@/shared/ui/Icon';
import IconButton from '@/shared/ui/IconButton';

type PropsType = {
endpoint: string;
saveEndpoint: (value: string) => void;
};

const EndpointComp: FC<PropsType> = ({ endpoint, saveEndpoint }) => {
const EndpointComp = () => {
const { translation } = useLanguage();
const { currEndpoint, setCurrEndpoint } = useAppContext();
return (
<div className="mt-6 flex flex-col items-center justify-between border-b-[1px] border-outline-variant pb-6 sm:flex-row">
<div className="flex w-full flex-col items-start justify-between">
Expand All @@ -21,11 +15,11 @@ const EndpointComp: FC<PropsType> = ({ endpoint, saveEndpoint }) => {
<FilledTextField
className="relative ml-auto mt-4 h-[68px] w-full max-w-[360px] text-base sm:mt-0"
label="API endpoint"
value={endpoint}
value={currEndpoint}
name="endpoint"
onChange={(e) => saveEndpoint((e?.target as HTMLInputElement).value)}
onChange={(e) => setCurrEndpoint((e?.target as HTMLInputElement).value)}
>
<IconButton className="absolute right-0 top-[10px]" slot="trailing-icon" onClick={() => saveEndpoint('')}>
<IconButton className="absolute right-0 top-[10px]" slot="trailing-icon" onClick={() => setCurrEndpoint('')}>
<Icon>cancel</Icon>
</IconButton>
</FilledTextField>
Expand Down
65 changes: 34 additions & 31 deletions src/layouts/MainLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Nav from '@components/Nav/Nav';
import Controls from '@components/RequestEditor/ui/Controls';
import ViewProvider from '@components/ViewList/context/ViewProvider';
import { SNACKBAR_AUTO_HIDE_DURATION } from '@shared/constants/const';
import AuthProvider from '@shared/Context/AuthContext';
import useScreen from '@shared/lib/hooks/useScreen';
import useScrollbar from '@shared/lib/hooks/useScrollbar';

Expand All @@ -20,39 +21,41 @@ const MainLayout = () => {
const navContainerRef = useScrollbar<HTMLDivElement>(screenType === 'desktop');

return (
<ViewProvider>
<main
data-testid="main-layout"
className="relative grid h-screen grid-rows-[64px_auto_80px] text-sm text-on-surface-text sm:grid-cols-[80px_1fr] sm:grid-rows-[80px_1fr] sm:pb-3 sm:pr-3 sm:text-base lg:min-h-[initial] lg:grid-cols-[384px_1fr_0fr] lg:gap-4 lg:px-4 lg:pb-4 lg:pr-0"
>
<Header />
<div
ref={navContainerRef}
className="row-start-3 row-end-4 sm:col-start-1 sm:row-start-auto sm:row-end-auto lg:overflow-auto"
<AuthProvider>
<ViewProvider>
<main
data-testid="main-layout"
className="relative grid h-screen grid-rows-[64px_auto_80px] text-sm text-on-surface-text sm:grid-cols-[80px_1fr] sm:grid-rows-[80px_1fr] sm:pb-3 sm:pr-3 sm:text-base lg:min-h-[initial] lg:grid-cols-[384px_1fr_0fr] lg:gap-4 lg:px-4 lg:pb-4 lg:pr-0"
>
<Nav />
</div>
<Outlet />
<div className="col-start-1 hidden lg:block">
<Footer />
</div>
<Controls className="absolute bottom-36 right-6 z-10 sm:hidden" />
</main>
<Header />
<div
ref={navContainerRef}
className="row-start-3 row-end-4 sm:col-start-1 sm:row-start-auto sm:row-end-auto lg:overflow-auto"
>
<Nav />
</div>
<Outlet />
<div className="col-start-1 hidden lg:block">
<Footer />
</div>
<Controls className="absolute bottom-36 right-6 z-10 sm:hidden" />
</main>

<ToastContainer
closeOnClick={false}
closeButton={false}
autoClose={SNACKBAR_AUTO_HIDE_DURATION}
hideProgressBar
pauseOnHover={false}
draggable={false}
limit={1}
transition={SnackBarTransition}
position="bottom-center"
toastClassName="!text-inverse-on-surface origin-bottom !bg-inverse-surface max-w-[337px] !pl-4 !min-h-[48px] text-left"
bodyClassName="text-sm font-normal relative !p-0 [&>div]:origin-bottom [&>div]:animate-fade-in-snackbar-body [&>div]:truncate w-full [&>div]:pe-16"
/>
</ViewProvider>
<ToastContainer
closeOnClick={false}
closeButton={false}
autoClose={SNACKBAR_AUTO_HIDE_DURATION}
hideProgressBar
pauseOnHover={false}
draggable={false}
limit={1}
transition={SnackBarTransition}
position="bottom-center"
toastClassName="!text-inverse-on-surface origin-bottom !bg-inverse-surface max-w-[337px] !pl-4 !min-h-[48px] text-left"
bodyClassName="text-sm font-normal relative !p-0 [&>div]:origin-bottom [&>div]:animate-fade-in-snackbar-body [&>div]:truncate w-full [&>div]:pe-16"
/>
</ViewProvider>
</AuthProvider>
);
};

Expand Down
21 changes: 9 additions & 12 deletions src/pages/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { useState } from 'react';

import { yupResolver } from '@hookform/resolvers/yup';
import { TextFieldType } from '@material/web/textfield/outlined-text-field';
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';
import { useForm } from 'react-hook-form';
import { Link, useNavigate } from 'react-router-dom';
import { Link } from 'react-router-dom';
import { toast } from 'react-toastify';

import PassVisibilityIcon from '@/components/loginReg/PassVisibilityIcon';
Expand All @@ -20,11 +19,10 @@ import OutlinedTextField from '@/shared/ui/OutlinedTextField';
import SubmitBtn from '@components/loginReg/SubmitBtn';

export default function LoginPage() {
const navigate = useNavigate();
const [passType, setPassType] = useState('password');
const { translation, language } = useLanguage();
const { title, subtitle, emailPlaceHold, passPlaceHold, btnTitle, linkClue, linkTitle } = translation.loginPage;
const { logInAuth } = useAuth();
const { logIn } = useAuth();

const {
register,
Expand All @@ -37,20 +35,19 @@ export default function LoginPage() {
});

async function onSubmit({ email, password }: { email: string; password: string }) {
const auth = getAuth();
try {
const { user } = await signInWithEmailAndPassword(auth, email, password);
if (user) {
logInAuth(user.email as string);
const isSuccess = await logIn(email, password);
if (isSuccess) {
reset();
navigate(`/${ROUTES.MAIN}`);
}
return null;
return undefined;
} catch (e) {
if ((e as ErrorType).code === AUTH_ERRORS.INVALID_EMAIL)
if ((e as ErrorType).code === AUTH_ERRORS.INVALID_EMAIL) {
return toast(<p className="text-center">{notationLocalizer(language, 'code8')}</p>);
if ((e as ErrorType).code === AUTH_ERRORS.INVALID_PASS)
}
if ((e as ErrorType).code === AUTH_ERRORS.INVALID_PASS) {
return toast(<p className="text-center">{notationLocalizer(language, 'code9')}</p>);
}
return toast(<p className="text-center">{notationLocalizer(language, 'code11')}</p>);
}
}
Expand Down
6 changes: 1 addition & 5 deletions src/pages/SettingsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import useScrollbar from '@shared/lib/hooks/useScrollbar';
const SettignsPage = () => {
const [settingsState, setSettingsState] = useState({
headers: true,
endpoint: 'goods',
});
const root = useScrollbar();

Expand All @@ -25,10 +24,7 @@ const SettignsPage = () => {
switcher={() => setSettingsState((prev) => ({ ...prev, headers: !prev.headers }))}
/>
<DarkModeComp />
<EndpointComp
endpoint={settingsState.endpoint}
saveEndpoint={(value: string) => setSettingsState((prev) => ({ ...prev, endpoint: value }))}
/>
<EndpointComp />
<LangSelectorComp />
<ClearStorageComp />
</div>
Expand Down
15 changes: 5 additions & 10 deletions src/pages/SignUpPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { useState } from 'react';

import { yupResolver } from '@hookform/resolvers/yup';
import { TextFieldType } from '@material/web/textfield/outlined-text-field';
import { createUserWithEmailAndPassword, getAuth } from 'firebase/auth';
import { useForm } from 'react-hook-form';
import { Link, useNavigate } from 'react-router-dom';
import { Link } from 'react-router-dom';
import { toast } from 'react-toastify';

import PassVisibilityIcon from '@/components/loginReg/PassVisibilityIcon';
Expand All @@ -22,8 +21,7 @@ import SubmitBtn from '@components/loginReg/SubmitBtn';
export default function SignUpPage() {
const [passType, setPassType] = useState('password');
const [confPassType, setConfPassType] = useState('password');
const navigate = useNavigate();
const { logInAuth } = useAuth();
const { createAccount } = useAuth();
const { translation, language } = useLanguage();
const { title, subtitle, emailPlaceHold, passPlaceHold, btnTitle, linkClue, linkTitle, confPassPlaceHold } =
translation.signUpPage;
Expand All @@ -38,15 +36,12 @@ export default function SignUpPage() {
});

async function onSubmit({ email, password }: { email: string; password: string }) {
const auth = getAuth();
try {
const { user } = await createUserWithEmailAndPassword(auth, email, password);
if (user) {
const isSuccess = await createAccount(email, password);
if (isSuccess) {
reset();
logInAuth(user.email as string);
navigate(`/${ROUTES.MAIN}`);
}
return null;
return undefined;
} catch (e) {
if ((e as ErrorType).code === AUTH_ERRORS.EMAIL_IN_USE)
return toast(<p className="text-center">{notationLocalizer(language, 'code10')}</p>);
Expand Down
Loading