Compare commits

...

6 Commits

Author SHA1 Message Date
grinikita
90992b087f init keycloak 2024-12-14 13:08:54 +03:00
grinikita
0ad224f04d redux 2024-12-14 12:32:32 +03:00
grinikita
b997d670a0 fix eslint 2024-12-07 14:14:45 +03:00
grinikita
0fe463e33a Базовые сетевые запросы 2024-12-07 13:43:07 +03:00
grinikita
34e30fbaba Добавлен логотип 2024-12-07 12:30:07 +03:00
grinikita
5d2dc9f7c5 Добавлены стили emotion 2024-12-01 14:48:24 +03:00
27 changed files with 1401 additions and 94 deletions

5
@types/assets.d.ts vendored Normal file
View File

@@ -0,0 +1,5 @@
declare module '*.png' {
const imagePath: string;
export default imagePath;
}

View File

@@ -11,7 +11,7 @@ module.exports = {
/* use https://admin.bro-js.ru/ to create config, navigations and features */
navigations: {
'kfu-24-teacher.main': '/kfu-24-teacher',
'kfu-24-teacher.detail': '/kfu-24-teacher/detail'
'kfu-24-teacher.detail': '/kfu-24-teacher/:id'
},
features: {
'kfu-24-teacher': {

View File

@@ -29,5 +29,11 @@ export default [
...hooksPlugin.configs.recommended.rules
}
},
{
files: ['stubs/api/**/*'],
rules: {
'@typescript-eslint/no-require-imports': 'off'
}
},
pluginPrettier
];

1109
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -14,14 +14,24 @@
"license": "ISC",
"description": "",
"dependencies": {
"@brojs/cli": "^1.6.1",
"@brojs/cli": "^1.6.3",
"@emotion/react": "^11.13.5",
"@emotion/styled": "^11.13.5",
"@reduxjs/toolkit": "^2.5.0",
"axios": "^1.7.9",
"express": "^4.19.2",
"keycloak-connect": "^26.0.7",
"keycloak-js": "^26.0.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.2.0",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
"@eslint/js": "^9.14.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@types/webpack-env": "^1.18.5",
"eslint": "^9.14.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jsx-a11y": "^6.10.2",

View File

@@ -0,0 +1,35 @@
import styled from '@emotion/styled';
import { HeadingVariant } from './types';
import { css } from '@emotion/react';
export const HeadingStyled = styled.h1<{ variant?: HeadingVariant }>`
font-size: 32px;
font-weight: bold;
color: blue;
width: 100%;
@media (min-width: 768px) {
font-size: 38px;
width: 50%;
}
@media (min-width: 1024px) {
width: 100%;
}
${({ variant }) => {
switch (variant) {
case HeadingVariant.h2:
return css`
font-size: 24px;
`;
case HeadingVariant.h3:
return css`
font-size: 18px;
`;
case HeadingVariant.h4:
return css`
font-size: 14px;
`;
}
return css``;
}}
`;

View File

@@ -0,0 +1,13 @@
import React from 'react';
import { HeadingStyled } from './index.style';
import { HeadingProps, HeadingVariant } from './types';
const Heading = ({ children, variant = HeadingVariant.h1, className }: HeadingProps) => {
return (
<HeadingStyled className={className} as={variant} variant={variant}>
{children}
</HeadingStyled>
);
};
export default Heading;

View File

@@ -0,0 +1,14 @@
import { ReactNode } from 'react';
export enum HeadingVariant {
h1 = 'h1',
h2 = 'h2',
h3 = 'h3',
h4 = 'h4'
}
export interface HeadingProps {
children?: ReactNode;
variant?: HeadingVariant;
className?: string;
}

View File

@@ -1,7 +1,11 @@
import React from 'react';
import Heading from '../../components/heading';
import { HeadingVariant } from '../../components/heading/types';
import { useParams } from 'react-router-dom';
const DetailPage = (): React.ReactElement => {
return <h1>Detail Page</h1>;
const { id } = useParams();
return <Heading variant={HeadingVariant.h2}>Detail Page {id} </Heading>;
};
export default DetailPage;

View File

@@ -1,7 +1,24 @@
import React from 'react';
import Heading from '../../components/heading';
import { useGetListQuery } from '../../store/api';
const ListPage = (): React.ReactElement => {
return <h1>List Page New</h1>;
const { data, isLoading, error } = useGetListQuery(undefined);
return (
<>
<Heading>List Page New</Heading>
{isLoading && <div>Loading...</div>}
{error && <div>Произошла ошибка</div>}
{data?.map((item) => {
return (
<div key={item.id}>
{item.id}: {item.title} - {item.description}
</div>
);
})}
</>
);
};
export default ListPage;

View File

@@ -1,31 +1,35 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { getNavigationsValue } from '@brojs/cli';
import { getNavigationValue } from '@brojs/cli';
import { HeaderContainer, NavContainer, NavItem, NavLink } from './index.style';
import Logo from './logo/logo';
const navigations: Array<{ name: string; href: string }> = [
{
name: 'Главная',
href: getNavigationsValue('kfu-24-teacher.main')
href: getNavigationValue('kfu-24-teacher.main')
},
{
name: 'Детальная информация',
href: getNavigationsValue('kfu-24-teacher.detail')
href: getNavigationValue('kfu-24-teacher.detail')
}
];
const Header = (): React.ReactElement => {
return (
<header>
<ul>
<HeaderContainer>
<Logo />
<NavContainer>
{navigations.map((item) => {
return (
<li key={item.name}>
<Link to={item.href}>{item.name}</Link>
</li>
<NavItem key={item.name}>
<NavLink to={item.href} end>
{item.name}
</NavLink>
</NavItem>
);
})}
</ul>
</header>
</NavContainer>
</HeaderContainer>
);
};

View File

@@ -0,0 +1,25 @@
import styled from '@emotion/styled';
import { NavLink as NavLinkBase } from 'react-router-dom';
export const HeaderContainer = styled('header')`
display: flex;
align-items: center;
`;
export const NavContainer = styled.nav`
display: flex;
gap: 24px;
padding: 12px 0;
`;
export const NavItem = styled.div``;
export const NavLink = styled(NavLinkBase)`
text-decoration: none;
color: black;
font-weight: bold;
&.active {
border-bottom: 2px solid black;
}
`;

View File

@@ -0,0 +1,17 @@
import React from 'react';
import styled from '@emotion/styled';
import logoPng from './logo2.png';
const LogoStyled = styled.img`
width: 24px;
height: 24px;
padding: 8px;
`;
// ${__webpack_public_path__}/remote-assets/logo.png
const Logo = () => {
return <LogoStyled src={logoPng} alt={'logo'} />;
};
export default Logo;

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

View File

@@ -1,9 +1,22 @@
import React from 'react';
import { RouterProvider } from 'react-router-dom';
import { router } from './router';
import { store } from '../../store';
import { Provider } from 'react-redux';
import { useKeycloak } from './keycloak';
const Main = (): React.ReactElement => {
return <RouterProvider router={router} />;
const Main = (): React.ReactElement | string => {
const { isLoading } = useKeycloak();
if (isLoading) {
return 'Loading...';
}
return (
<Provider store={store}>
<RouterProvider router={router} />
</Provider>
);
};
export default Main;

View File

@@ -0,0 +1,53 @@
import Keycloak from 'keycloak-js';
import { useEffect, useState } from 'react';
import { setToken } from '../../service/network';
const keycloak = new Keycloak({
url: 'https://kc.bro-js.ru/',
realm: 'open',
clientId: 'kfu-m-24-1'
});
export interface User {
email: string;
email_verified: boolean;
family_name: string;
given_name: string;
name: string;
preferred_username: string;
id: string;
}
export const useKeycloak = () => {
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState();
useEffect(() => {
const handle = async () => {
setIsLoading(true);
try {
const authenticated = await keycloak.init({ onLoad: 'login-required' });
if (authenticated) {
setToken(keycloak.token);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { sub, ...user } = (await keycloak.loadUserInfo()) as any;
console.log(user);
setUser({ ...user, id: sub });
console.log('User is authenticated');
} else {
console.log('User is not authenticated');
}
} catch (error) {
console.error('Failed to initialize adapter:', error);
} finally {
setIsLoading(false);
}
};
handle();
}, []);
return {
isLoading,
user
};
};

View File

@@ -2,22 +2,23 @@ import React from 'react';
import { createBrowserRouter } from 'react-router-dom';
import ListPage from '../list';
import DetailPage from '../detail';
import { getNavigationsValue } from '@brojs/cli';
import { getNavigationValue } from '@brojs/cli';
import Layout from './components/layout';
export const router = createBrowserRouter([
{
path: getNavigationsValue('kfu-24-teacher.main'),
path: getNavigationValue('kfu-24-teacher.main'),
element: <Layout />,
children: [
{
path: getNavigationsValue('kfu-24-teacher.main'),
path: getNavigationValue('kfu-24-teacher.main'),
element: <ListPage />
},
{
path: getNavigationsValue('kfu-24-teacher.detail'),
path: getNavigationValue('kfu-24-teacher.detail'),
element: <DetailPage />
}
},
{ path: '*', element: <h1>404</h1> }
]
}
]);

11
src/service/list/index.ts Normal file
View File

@@ -0,0 +1,11 @@
import { network } from '../network';
import { GetListResponse } from './types';
class ListService {
async getList() {
const res = await network.get<GetListResponse>('/list');
return res.data;
}
}
export const listService = new ListService();

View File

@@ -0,0 +1,7 @@
export interface ListItem {
id: number;
title: string;
description: string;
}
export type GetListResponse = Array<ListItem>;

10
src/service/network.ts Normal file
View File

@@ -0,0 +1,10 @@
import axios from 'axios';
import { getConfigValue } from '@brojs/cli';
const baseUrl = getConfigValue('kfu-24-teacher.api');
export const network = axios.create({ baseURL: baseUrl });
export const setToken = (token: string) => {
network.defaults.headers.authorization = `Bearer ${token}`;
};

29
src/store/api.ts Normal file
View File

@@ -0,0 +1,29 @@
// Need to use the React-specific entry point to import createApi
import { createApi, fetchBaseQuery, QueryReturnValue } from '@reduxjs/toolkit/query/react';
import { GetListResponse } from '../service/list/types';
import { listService } from '../service/list';
const createQueryFromPromise =
<ARGS, RES>(fn: (...args: Array<ARGS>) => Promise<RES>) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async (...args): Promise<QueryReturnValue<RES, any, any>> => {
try {
const data = await fn(...args);
return { data };
} catch (e: unknown) {
return { error: e };
}
};
// Define a service using a base URL and expected endpoints
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '' }),
endpoints: (builder) => ({
getList: builder.query<GetListResponse, undefined>({
queryFn: createQueryFromPromise(() => listService.getList())
})
})
});
export const { useGetListQuery } = api;

20
src/store/index.ts Normal file
View File

@@ -0,0 +1,20 @@
import { configureStore } from '@reduxjs/toolkit';
import { api } from './api';
import { setupListeners } from '@reduxjs/toolkit/query';
export const store = configureStore({
reducer: {
// Add the generated reducer as a specific top-level slice
[api.reducerPath]: api.reducer
},
// Adding the api middleware enables caching, invalidation, polling,
// and other useful features of `rtk-query`.
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware)
});
setupListeners(store.dispatch);
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

View File

@@ -1,3 +1,14 @@
const router = require('express').Router();
const listRouter = require('./list');
const keycloak = require('./keycloak');
module.exports = router;
const delay =
(ms = 1000) =>
(req, res, next) => {
setTimeout(next, ms);
};
router.use(keycloak.middleware());
router.use(delay());
router.use('/list', listRouter);

12
stubs/api/keycloak.js Normal file
View File

@@ -0,0 +1,12 @@
const Keycloak = require('keycloak-connect');
const kcConfig = {
clientId: 'kfu-m-24-1',
bearerOnly: true,
serverUrl: 'https://kc.bro-js.ru/',
realm: 'open'
};
const keycloak = new Keycloak({}, kcConfig);
module.exports = keycloak;

View File

@@ -0,0 +1,7 @@
[
{ "id": 1, "title": "title", "description": "description" },
{ "id": 2, "title": "title", "description": "description" },
{ "id": 3, "title": "title", "description": "description" },
{ "id": 4, "title": "title", "description": "description" },
{ "id": 5, "title": "title", "description": "description" }
]

13
stubs/api/list/index.js Normal file
View File

@@ -0,0 +1,13 @@
const router = require('express').Router();
module.exports = router;
const data = require('./data/list.json');
const keycloak = require('../keycloak');
router.get('/', keycloak.protect(), (req, res) => {
res.send(data);
// res.status(500).send({
// message: 'Internal server error'
// });
});

View File

@@ -9,11 +9,10 @@
"esModuleInterop": true,
"noImplicitAny": false,
"module": "esnext",
"moduleResolution": "node",
"moduleResolution": "Bundler",
"target": "es6",
"jsx": "react",
"typeRoots": ["node_modules/@types", "src/typings"],
"types" : ["webpack-env", "node"],
"resolveJsonModule": true
},
"exclude": [