This commit is contained in:
Primakov Alexandr Alexandrovich 2025-11-17 13:31:58 +03:00
commit c3eab8bcac
20 changed files with 12781 additions and 0 deletions

132
.gitignore vendored Normal file
View File

@ -0,0 +1,132 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

7
.prettierignore Normal file
View File

@ -0,0 +1,7 @@
# Ignore artifacts:
build
dist
coverage
stubs
logs
d-scripts

7
.prettierrc.json Normal file
View File

@ -0,0 +1,7 @@
{
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"jsxSingleQuote": false
}

57
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,57 @@
pipeline {
agent {
docker {
image 'node:20'
}
}
stages {
stage('install') {
steps {
sh 'node -v'
sh 'npm -v'
script {
String tag = sh(returnStdout: true, script: 'git tag --contains').trim()
String branchName = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
String commit = sh(returnStdout: true, script: 'git log -1 --oneline').trim()
String commitMsg = commit.substring(commit.indexOf(' ')).trim()
if (tag) {
currentBuild.displayName = "#${BUILD_NUMBER}, tag ${tag}"
} else {
currentBuild.displayName = "#${BUILD_NUMBER}, branch ${branchName}"
}
String author = sh(returnStdout: true, script: "git log -1 --pretty=format:'%an'").trim()
currentBuild.description = "${author}<br />${commitMsg}"
echo 'starting installing'
sh 'npm ci'
}
}
}
stage('checks') {
parallel {
stage('eslint') {
steps {
sh 'npm run eslint'
}
}
stage('build') {
steps {
sh 'npm run build'
}
}
}
}
stage('clean-all') {
steps {
sh 'rm -rf .[!.]*'
sh 'rm -rf ./*'
sh 'ls -a'
}
}
}
}

23
bro.config.js Normal file
View File

@ -0,0 +1,23 @@
const pkg = require('./package')
module.exports = {
apiPath: 'stubs/api',
webpackConfig: {
output: {
publicPath: `/static/${pkg.name}/${process.env.VERSION || pkg.version}/`
}
},
/* use https://admin.bro-js.ru/ to create config, navigations and features */
navigations: {
'smoke-tracker.main': '/smoke-tracker',
'link.smoke-tracker.auth': '/auth'
},
features: {
'smoke-tracker': {
// add your features here in the format [featureName]: { value: string }
},
},
config: {
'smoke-tracker.api': '/api'
}
}

57
eslint.config.mjs Normal file
View File

@ -0,0 +1,57 @@
import globals from 'globals'
import pluginJs from '@eslint/js'
import tseslint from 'typescript-eslint'
import pluginReact from 'eslint-plugin-react'
import stylistic from '@stylistic/eslint-plugin'
export default [
{
settings: {
react: {
version: 'detect',
},
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
},
},
},
{ files: ['**/*.{js,mjs,cjs,ts,jsx,tsx}'] },
{ languageOptions: { globals: globals.browser } },
{
ignores: ['stubs/', 'bro.config.js'],
},
pluginJs.configs.recommended,
...tseslint.configs.recommended,
pluginReact.configs.flat.recommended,
{
plugins: {
'@stylistic': stylistic,
},
rules: {
'no-unused-vars': 'off',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': [
'warn', // or "error"
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
'sort-imports': [
'error',
{
ignoreCase: false,
ignoreDeclarationSort: true,
ignoreMemberSort: true,
memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
allowSeparatedGroups: true,
},
],
semi: ['error', 'never'],
'@stylistic/indent': ['error', 2],
},
},
]

626
memory-bank/API.md Normal file
View File

@ -0,0 +1,626 @@
# Smoke Tracker API — Документация для Frontend
## Базовый URL
```
http://localhost:8044/smoke-tracker
```
В production окружении замените на соответствующий домен.
---
## Оглавление
1. [Авторизация](#авторизация)
- [Регистрация](#post-authsignup)
- [Вход](#post-authsignin)
2. [Логирование сигарет](#логирование-сигарет)
- [Записать сигарету](#post-cigarettes)
- [Получить список сигарет](#get-cigarettes)
3. [Статистика](#статистика)
- [Дневная статистика](#get-statsdaily)
---
## Авторизация
Все эндпоинты, кроме `/auth/signup` и `/auth/signin`, требуют JWT-токен в заголовке:
```
Authorization: Bearer <token>
```
Токен возвращается при успешном входе (`/auth/signin`) и действителен **12 часов**.
---
### `POST /auth/signup`
**Описание**: Регистрация нового пользователя
**Требуется авторизация**: ❌ Нет
**Тело запроса** (JSON):
```json
{
"login": "string", // обязательно, уникальный логин
"password": "string" // обязательно
}
```
**Пример запроса**:
```bash
curl -X POST http://localhost:8044/smoke-tracker/auth/signup \
-H "Content-Type: application/json" \
-d '{
"login": "user123",
"password": "mySecurePassword"
}'
```
**Ответ при успехе** (200 OK):
```json
{
"success": true,
"body": {
"ok": true
}
}
```
**Возможные ошибки**:
- **400 Bad Request**: `"Не все поля заполнены: login, password"` — не указаны обязательные поля
- **500 Internal Server Error**: `"Пользователь с таким логином уже существует"` — логин занят
---
### `POST /auth/signin`
**Описание**: Вход в систему (получение JWT-токена)
**Требуется авторизация**: ❌ Нет
**Тело запроса** (JSON):
```json
{
"login": "string", // обязательно
"password": "string" // обязательно
}
```
**Пример запроса**:
```bash
curl -X POST http://localhost:8044/smoke-tracker/auth/signin \
-H "Content-Type: application/json" \
-d '{
"login": "user123",
"password": "mySecurePassword"
}'
```
**Ответ при успехе** (200 OK):
```json
{
"success": true,
"body": {
"user": {
"id": "507f1f77bcf86cd799439011",
"login": "user123",
"created": "2024-01-15T10:30:00.000Z"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
```
**Поля ответа**:
- `user.id` — уникальный идентификатор пользователя
- `user.login` — логин пользователя
- `user.created` — дата создания аккаунта (ISO 8601)
- `token` — JWT-токен для авторизации (действителен 12 часов)
**Возможные ошибки**:
- **400 Bad Request**: `"Не все поля заполнены: login, password"` — не указаны обязательные поля
- **500 Internal Server Error**: `"Неверный логин или пароль"` — неправильные учётные данные
**Использование токена**:
Сохраните токен в localStorage/sessionStorage/cookie и передавайте в заголовке всех последующих запросов:
```javascript
// Пример для fetch API
const token = localStorage.getItem('smokeToken');
fetch('http://localhost:8044/smoke-tracker/cigarettes', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
```
---
## Логирование сигарет
### `POST /cigarettes`
**Описание**: Записать факт выкуренной сигареты
**Требуется авторизация**: ✅ Да (Bearer token)
**Тело запроса** (JSON):
```json
{
"smokedAt": "string (ISO 8601)", // необязательно, по умолчанию — текущее время
"note": "string" // необязательно, заметка/комментарий
}
```
**Пример запроса**:
```bash
curl -X POST http://localhost:8044/smoke-tracker/cigarettes \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
-H "Content-Type: application/json" \
-d '{
"smokedAt": "2024-01-15T14:30:00.000Z",
"note": "После обеда"
}'
```
**Пример без указания времени** (будет текущее время):
```bash
curl -X POST http://localhost:8044/smoke-tracker/cigarettes \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
-H "Content-Type: application/json" \
-d '{}'
```
**Ответ при успехе** (200 OK):
```json
{
"success": true,
"body": {
"id": "507f1f77bcf86cd799439012",
"userId": "507f1f77bcf86cd799439011",
"smokedAt": "2024-01-15T14:30:00.000Z",
"note": "После обеда",
"created": "2024-01-15T14:30:05.123Z"
}
}
```
**Поля ответа**:
- `id` — уникальный идентификатор записи
- `userId` — ID пользователя
- `smokedAt` — дата и время курения (ISO 8601)
- `note` — заметка (если была указана)
- `created` — дата создания записи в БД
**Возможные ошибки**:
- **401 Unauthorized**: `"Требуется авторизация"` — не передан токен
- **401 Unauthorized**: `"Неверный или истекший токен авторизации"` — токен невалидный/просрочен
- **400 Bad Request**: `"Некорректный формат даты smokedAt"` — неверный формат даты
---
### `GET /cigarettes`
**Описание**: Получить список всех выкуренных сигарет текущего пользователя
**Требуется авторизация**: ✅ Да (Bearer token)
**Query-параметры** (все необязательные):
| Параметр | Тип | Описание | Пример |
|----------|-----|----------|--------|
| `from` | string (ISO 8601) | Начало периода (включительно) | `2024-01-01T00:00:00.000Z` |
| `to` | string (ISO 8601) | Конец периода (включительно) | `2024-01-31T23:59:59.999Z` |
**Пример запроса** (все сигареты):
```bash
curl -X GET http://localhost:8044/smoke-tracker/cigarettes \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
**Пример запроса** (с фильтрацией по датам):
```bash
curl -X GET "http://localhost:8044/smoke-tracker/cigarettes?from=2024-01-01T00:00:00.000Z&to=2024-01-31T23:59:59.999Z" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
**Ответ при успехе** (200 OK):
```json
{
"success": true,
"body": [
{
"id": "507f1f77bcf86cd799439012",
"userId": "507f1f77bcf86cd799439011",
"smokedAt": "2024-01-15T10:30:00.000Z",
"note": "Утренняя",
"created": "2024-01-15T10:30:05.123Z"
},
{
"id": "507f1f77bcf86cd799439013",
"userId": "507f1f77bcf86cd799439011",
"smokedAt": "2024-01-15T14:30:00.000Z",
"note": "После обеда",
"created": "2024-01-15T14:30:05.456Z"
}
]
}
```
**Особенности**:
- Записи отсортированы по `smokedAt` (от старых к новым)
- Если указаны `from` и/или `to`, будет применена фильтрация
- Пустой массив возвращается, если сигарет в периоде нет
**Возможные ошибки**:
- **401 Unauthorized**: `"Требуется авторизация"` — не передан токен
- **401 Unauthorized**: `"Неверный или истекший токен авторизации"` — токен невалидный/просрочен
---
## Статистика
### `GET /stats/daily`
**Описание**: Получить дневную статистику по количеству сигарет для построения графика
**Требуется авторизация**: ✅ Да (Bearer token)
**Query-параметры** (все необязательные):
| Параметр | Тип | Описание | Пример | По умолчанию |
|----------|-----|----------|--------|--------------|
| `from` | string (ISO 8601) | Начало периода | `2024-01-01T00:00:00.000Z` | 30 дней назад от текущей даты |
| `to` | string (ISO 8601) | Конец периода | `2024-01-31T23:59:59.999Z` | Текущая дата и время |
**Пример запроса** (последние 30 дней):
```bash
curl -X GET http://localhost:8044/smoke-tracker/stats/daily \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
**Пример запроса** (с указанием периода):
```bash
curl -X GET "http://localhost:8044/smoke-tracker/stats/daily?from=2024-01-01T00:00:00.000Z&to=2024-01-31T23:59:59.999Z" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
**Ответ при успехе** (200 OK):
```json
{
"success": true,
"body": [
{
"date": "2024-01-15",
"count": 8
},
{
"date": "2024-01-16",
"count": 12
},
{
"date": "2024-01-17",
"count": 5
}
]
}
```
**Поля ответа**:
- `date` — дата в формате `YYYY-MM-DD`
- `count` — количество сигарет, выкуренных в этот день
**Особенности**:
- Данные отсортированы по дате (от старых к новым)
- Дни без сигарет **не включаются** в ответ (фронтенду нужно самостоятельно заполнить пропуски нулями при построении графика)
- Агрегация происходит по дате из поля `smokedAt` (не `created`)
**Пример использования для графика** (Chart.js):
```javascript
const response = await fetch('http://localhost:8044/smoke-tracker/stats/daily', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const { body } = await response.json();
// Заполнение пропущенных дней нулями
const fillMissingDates = (data, from, to) => {
const result = [];
const current = new Date(from);
const end = new Date(to);
while (current <= end) {
const dateStr = current.toISOString().split('T')[0];
const existing = data.find(d => d.date === dateStr);
result.push({
date: dateStr,
count: existing ? existing.count : 0
});
current.setDate(current.getDate() + 1);
}
return result;
};
const filledData = fillMissingDates(body, '2024-01-01', '2024-01-31');
// Данные для графика
const chartData = {
labels: filledData.map(d => d.date),
datasets: [{
label: 'Количество сигарет',
data: filledData.map(d => d.count),
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
}]
};
```
**Возможные ошибки**:
- **401 Unauthorized**: `"Требуется авторизация"` — не передан токен
- **401 Unauthorized**: `"Неверный или истекший токен авторизации"` — токен невалидный/просрочен
---
## Общая структура ответов
Все эндпоинты возвращают JSON в следующем формате:
**Успешный ответ**:
```json
{
"success": true,
"body": { /* данные */ }
}
```
**Ответ с ошибкой**:
```json
{
"success": false,
"errors": "Описание ошибки"
}
```
или (при использовании глобального обработчика ошибок):
```json
{
"message": "Описание ошибки"
}
```
---
## Коды состояния HTTP
| Код | Описание |
|-----|----------|
| **200 OK** | Запрос выполнен успешно |
| **400 Bad Request** | Некорректные данные в запросе |
| **401 Unauthorized** | Требуется авторизация или токен невалидный |
| **500 Internal Server Error** | Внутренняя ошибка сервера |
---
## Примеры интеграции
### React + Axios
```javascript
import axios from 'axios';
const API_BASE_URL = 'http://localhost:8044/smoke-tracker';
// Создание экземпляра axios с базовыми настройками
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json'
}
});
// Интерцептор для добавления токена
api.interceptors.request.use(config => {
const token = localStorage.getItem('smokeToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Регистрация
export const signup = async (login, password) => {
const { data } = await api.post('/auth/signup', { login, password });
return data;
};
// Вход
export const signin = async (login, password) => {
const { data } = await api.post('/auth/signin', { login, password });
if (data.success) {
localStorage.setItem('smokeToken', data.body.token);
}
return data;
};
// Выход
export const signout = () => {
localStorage.removeItem('smokeToken');
};
// Записать сигарету
export const logCigarette = async (smokedAt = null, note = '') => {
const { data } = await api.post('/cigarettes', { smokedAt, note });
return data;
};
// Получить список сигарет
export const getCigarettes = async (from = null, to = null) => {
const params = {};
if (from) params.from = from;
if (to) params.to = to;
const { data } = await api.get('/cigarettes', { params });
return data;
};
// Получить дневную статистику
export const getDailyStats = async (from = null, to = null) => {
const params = {};
if (from) params.from = from;
if (to) params.to = to;
const { data } = await api.get('/stats/daily', { params });
return data;
};
```
### Vanilla JavaScript + Fetch
```javascript
const API_BASE_URL = 'http://localhost:8044/smoke-tracker';
// Получение токена
const getToken = () => localStorage.getItem('smokeToken');
// Базовый запрос
const apiRequest = async (endpoint, options = {}) => {
const token = getToken();
const headers = {
'Content-Type': 'application/json',
...options.headers
};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...options,
headers
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || error.errors || 'Ошибка запроса');
}
return response.json();
};
// Регистрация
async function signup(login, password) {
return apiRequest('/auth/signup', {
method: 'POST',
body: JSON.stringify({ login, password })
});
}
// Вход
async function signin(login, password) {
const data = await apiRequest('/auth/signin', {
method: 'POST',
body: JSON.stringify({ login, password })
});
if (data.success) {
localStorage.setItem('smokeToken', data.body.token);
}
return data;
}
// Записать сигарету
async function logCigarette(note = '') {
return apiRequest('/cigarettes', {
method: 'POST',
body: JSON.stringify({ note })
});
}
// Получить дневную статистику
async function getDailyStats() {
return apiRequest('/stats/daily');
}
```
---
## Рекомендации по безопасности
1. **Хранение токена**:
- Для веб-приложений: используйте `httpOnly` cookies или `sessionStorage`
- Избегайте `localStorage` при работе с чувствительными данными
- Для мобильных приложений: используйте безопасное хранилище (Keychain/Keystore)
2. **HTTPS**: В production всегда используйте HTTPS для защиты токена при передаче
3. **Обработка истечения токена**:
- Токен действителен 12 часов
- При получении ошибки 401 перенаправляйте пользователя на страницу входа
- Реализуйте механизм refresh token для бесшовного обновления
4. **Валидация на фронтенде**:
- Проверяйте корректность email/логина перед отправкой
- Требуйте минимальную длину пароля (8+ символов)
- Показывайте индикатор силы пароля
---
## Postman-коллекция
Готовая коллекция для тестирования доступна в файле:
```
server/routers/smoke-tracker/postman/smoke-tracker.postman_collection.json
```
Импортируйте её в Postman для быстрого тестирования всех эндпоинтов.
---
## Поддержка
При возникновении вопросов или обнаружении проблем обращайтесь к разработчикам backend-команды.

11642
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
package.json Normal file
View File

@ -0,0 +1,40 @@
{
"name": "smoke-tracker",
"version": "0.0.0",
"description": "",
"main": "./src/index.tsx",
"scripts": {
"test": "exit 0",
"start": "brojs server --port=8099 --with-open-browser",
"build": "npm run clean && brojs build --dev",
"build:prod": "npm run clean && brojs build",
"clean": "rimraf dist",
"eslint": "npx eslint ./src/**/*",
"eslint:fix": "npx eslint ./src/**/* --fix"
},
"repository": {
"type": "git",
"url": "ssh://git@85.143.175.152:222/primakov/smoke-tracker.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@brojs/cli": "^1.10.0",
"@chakra-ui/react": "^3.2.0",
"@emotion/react": "^11.13.5",
"@eslint/js": "^9.11.0",
"@stylistic/eslint-plugin": "^2.8.0",
"@types/node": "^22.19.1",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"eslint": "^9.11.0",
"eslint-plugin-react": "^7.36.1",
"express": "^4.19.2",
"globals": "^15.9.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.23.1",
"typescript-eslint": "^8.6.0"
}
}

15
src/__data__/urls.ts Normal file
View File

@ -0,0 +1,15 @@
import { getNavigation, getNavigationValue } from '@brojs/cli'
import pkg from '../../package.json'
const baseUrl = getNavigationValue(`${pkg.name}.main`)
const navs = getNavigation()
const makeUrl = (url) => baseUrl + url
export const URLs = {
baseUrl,
auth: {
url: makeUrl(navs[`link.${pkg.name}.auth`]),
isOn: Boolean(navs[`link.${pkg.name}.auth`])
},
}

17
src/app.tsx Normal file
View File

@ -0,0 +1,17 @@
import React from 'react'
import { BrowserRouter } from 'react-router-dom'
import { Dashboard } from './dashboard'
import { Provider } from './theme'
const App = () => {
return (
<BrowserRouter>
<Provider>
<Dashboard />
</Provider>
</BrowserRouter>
)
}
export default App

24
src/dashboard.tsx Normal file
View File

@ -0,0 +1,24 @@
import React, { Suspense } from 'react'
import { Route, Routes } from 'react-router-dom'
import { URLs } from './__data__/urls'
import { MainPage } from './pages'
const PageWrapper = ({ children }: React.PropsWithChildren) => (
<Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
)
export const Dashboard = () => {
return (
<Routes>
<Route
path={URLs.baseUrl}
element={
<PageWrapper>
<MainPage />
</PageWrapper>
}
/>
</Routes>
)
}

28
src/index.tsx Normal file
View File

@ -0,0 +1,28 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react/display-name */
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './app'
export default () => <App/>
let rootElement: ReactDOM.Root
export const mount = (Component, element = document.getElementById('app')) => {
rootElement = ReactDOM.createRoot(element)
rootElement.render(<Component/>)
// @ts-ignore
if(module.hot) {
// @ts-ignore
module.hot.accept('./app', ()=> {
rootElement.render(<Component/>)
})
}
}
export const unmount = () => {
rootElement.unmount()
}

3
src/pages/index.ts Normal file
View File

@ -0,0 +1,3 @@
import { lazy } from 'react'
export const MainPage = lazy(() => import(/* webpackChunkName: 'main' */'./main'))

3
src/pages/main/index.ts Normal file
View File

@ -0,0 +1,3 @@
import { MainPage } from './main'
export default MainPage

28
src/pages/main/main.tsx Normal file
View File

@ -0,0 +1,28 @@
import React from 'react'
import { Grid, GridItem } from '@chakra-ui/react'
export const MainPage = () => {
return (
<Grid
h="100%"
bgColor="gray.300"
templateAreas={{
md: `"header header"
"aside main"
"footer footer"`,
sm: `"header"
"main"
"aside"
"footer"`,
}}
gridTemplateRows={{ sm: '1fr', md: '50px 1fr 30px' }}
gridTemplateColumns={{ sm: '1fr', md: '150px 1fr' }}
gap={4}
>
<GridItem bgColor="green.100" gridArea="header">header</GridItem>
<GridItem bgColor="green.300" gridArea="aside">aside</GridItem>
<GridItem bgColor="green.600" gridArea="main" h="100vh">main</GridItem>
<GridItem bgColor="green.300" gridArea="footer">footer</GridItem>
</Grid>
)
}

33
src/theme.tsx Normal file
View File

@ -0,0 +1,33 @@
import React from 'react'
import { ChakraProvider as ChacraProv, createSystem, defaultConfig } from '@chakra-ui/react'
import type { PropsWithChildren } from 'react'
const ChacraProvider: React.ElementType = ChacraProv
const system = createSystem(defaultConfig, {
globalCss: {
body: {
colorPalette: 'teal',
},
},
theme: {
tokens: {
fonts: {
body: { value: 'var(--font-outfit)' },
},
},
semanticTokens: {
radii: {
l1: { value: '0.5rem' },
l2: { value: '0.75rem' },
l3: { value: '1rem' },
},
},
},
})
export const Provider = (props: PropsWithChildren) => (
<ChacraProvider value={system}>
{props.children}
</ChacraProvider>
)

8
stubs/api/index.js Normal file
View File

@ -0,0 +1,8 @@
const router = require('express').Router();
const timer = (time = 300) => (req, res, next) => setTimeout(next, time);
router.use(timer());
module.exports = router;

25
tsconfig.json Normal file
View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"lib": [
"dom",
"es2017"
],
"outDir": "./dist/",
"sourceMap": true,
"esModuleInterop": true,
"noImplicitAny": false,
"module": "esnext",
"moduleResolution": "node",
"target": "es6",
"jsx": "react",
"typeRoots": ["node_modules/@types", "src/typings"],
"types" : ["webpack-env", "node"],
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"**/*.test.ts",
"**/*.test.tsx",
"node_modules/@types/jest"
]
}

6
types.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
declare module '*.svg' {
const src: string
export default src
}
declare const __webpack_public_path__: string