Compare commits

..

3 Commits

13 changed files with 530 additions and 620 deletions
-18
View File
@@ -1,18 +0,0 @@
MIT License
Copyright (c) 2026 laktionov-as
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
+13 -9
View File
@@ -2,17 +2,11 @@ import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
export default [
{ ignores: ['dist'] },
{
files: ['**/*.{js,jsx}'],
extends: [
js.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
@@ -22,8 +16,18 @@ export default defineConfig([
sourceType: 'module',
},
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...js.configs.recommended.rules,
...reactHooks.configs.recommended.rules,
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
])
]
+11 -11
View File
@@ -1,13 +1,13 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+383 -434
View File
File diff suppressed because it is too large Load Diff
+11 -12
View File
@@ -1,28 +1,27 @@
{
"name": "router-middleware-practice",
"name": "store-client",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.7.1"
"react-dom": "^19.1.0"
},
"devDependencies": {
"@eslint/js": "^9.30.1",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.6.0",
"eslint": "^9.30.1",
"@eslint/js": "^9.25.0",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"@vitejs/plugin-react": "^4.4.1",
"eslint": "^9.25.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"vite": "^7.0.4"
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^16.0.0",
"vite": "^6.3.5"
}
}
+93 -30
View File
@@ -1,35 +1,98 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import React from 'react'
import styles from './App.module.scss'
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerId = setInterval( () => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerId)
}
tick() {
this.setState({ date: new Date() })
}
render() {
return <div>{this.state.date.toLocaleTimeString()}</div>
}
}
function Clock2() {
const [date, setDate] = React.useState(new Date());
React.useEffect(()=>{
const timerId = setInterval(()=> setDate(new Date()),1000);
return () => clearInterval(timerId);
},[])
return <div>{date.toLocaleTimeString()}</div>
}
function MouseTracker() {
const [x,setX] = React.useState(0);
const [y,setY] = React.useState(0);
const mouseMoveHandler = event => {
setX(event.clientX);
setY(event.clientY);
}
React.useEffect(()=>{
document.addEventListener('mousemove', mouseMoveHandler);
return () => {
document.removeEventListener('mousemove',mouseMoveHandler);
}
},[]);
return <div className={styles.container}>
<p>Координаты мыши:<br /> X:<b>{x}</b>, Y:<b>{y}</b></p>
</div>
}
function DataFetcher() {
const [posts,setPosts] = React.useState([]);
const [users,setUsers] = React.useState([]);
const getPosts = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
setUsers(data.reduce((acc, value) => {
if (!(value.userId in acc))
return [...acc,value.userId]
return acc
}))
console.log(users);
setPosts(data.slice(1,10));
}
React.useEffect(() => {
console.log("Компонент создан");
getPosts();
return () => {console.log("Компонент удален");setPosts([])};
},[])
return <div><ol>{posts.map(post => <li id={post.id}>{post.title}</li>)}</ol></div>
}
function App() {
const [count, setCount] = useState(0)
return (
<>
<div>
<a href="https://vite.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.jsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
)
const [tracker,setTracker] = React.useState(false);
const [dataFetcher,setDataFetcher] = React.useState(false);
return (
<>
<h1>Hello, React!</h1>
<Clock />
<Clock2 />
<button onClick={() => setTracker(!tracker)}>Показать/Скрыть трекер</button>
{ tracker && <MouseTracker /> }
<button onClick={() => setDataFetcher(!dataFetcher)}>Показать/Скрыть посты</button>
{ dataFetcher && <DataFetcher /> }
</>
)
}
export default App
+11
View File
@@ -0,0 +1,11 @@
.container {
width: 300px;
height: 200px;
border: 2px dashed grey;
margin: 10px;
text-align: center;
p {
margin-top: 20%;
}
}
-26
View File
@@ -1,26 +0,0 @@
import { redirect } from 'react-router-dom'
// Проверка авторизации
export function requireAuth() {
const isAuthenticated = localStorage.getItem('auth') === 'true'
if (!isAuthenticated) {
return redirect('/login')
}
return null
}
// Проверка авторизации и роли
export function requireAdmin() {
const isAuthenticated = localStorage.getItem('auth') === 'true'
const role = localStorage.getItem('role')
if (!isAuthenticated) {
return redirect('/login')
}
if (role !== 'admin') {
return redirect('/dashboard') // если авторизован, но не админ — на общую панель
}
return null
}
+8 -8
View File
@@ -1,10 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider } from 'react-router-dom'
import router from './routes'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
// удаляем import './index.css'
import App from './App.jsx'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
)
-10
View File
@@ -1,10 +0,0 @@
import React from 'react'
export default function Admin() {
return (
<div>
<h1>Админ-панель</h1>
<p>Доступ разрешён только администраторам.</p>
</div>
)
}
-10
View File
@@ -1,10 +0,0 @@
import React from 'react'
export default function Dashboard() {
return (
<div>
<h1>Панель пользователя</h1>
<p>Вы вошли как обычный пользователь или администратор.</p>
</div>
)
}
-28
View File
@@ -1,28 +0,0 @@
import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
export default function Login() {
const [role, setRole] = useState('user')
const navigate = useNavigate()
const handleLogin = () => {
localStorage.setItem('auth', 'true')
localStorage.setItem('role', role)
navigate('/dashboard')
}
return (
<div>
<h1>Вход</h1>
<label>
Роль:
<select value={role} onChange={e => setRole(e.target.value)}>
<option value='user'>Обычный пользователь</option>
<option value='admin'>Администратор</option>
</select>
</label>
<br />
<button onClick={handleLogin}>Войти</button>
</div>
)
}
-24
View File
@@ -1,24 +0,0 @@
import { createBrowserRouter } from 'react-router-dom'
import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
import Admin from './pages/Admin'
import { requireAuth, requireAdmin } from './auth'
const router = createBrowserRouter([
{
path: '/login',
element: <Login />,
},
{
path: '/dashboard',
element: <Dashboard />,
loader: requireAuth,
},
{
path: '/admin',
element: <Admin />,
loader: requireAdmin,
},
])
export default router