feat: Phase 6+9 real-time уведомления, CSS Modules, UI-правки
This commit is contained in:
@@ -1,84 +1,88 @@
|
||||
# News Editor
|
||||
|
||||
Full-stack application for creating, editing, and publishing news articles.
|
||||
Full-stack приложение для создания, редактирования и публикации новостей. Markdown-редактор, real-time уведомления, отложенная публикация.
|
||||
|
||||
## Architecture
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
┌──────────────────────────────────┐
|
||||
┌──────────────────────────────────────────┐
|
||||
│ Nginx (client) │
|
||||
│ React SPA + reverse proxy │
|
||||
│ /api → server, /socket.io → ws │
|
||||
└────────────────┬─────────────────┘
|
||||
│ /api → server, /socket.io → ws, │
|
||||
│ /uploads → server │
|
||||
└────────────────────┬─────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────┐
|
||||
┌──────────────────────────────────────────┐
|
||||
│ Express Backend │
|
||||
│ Auth (JWT), News CRUD, │
|
||||
│ Upload (multer), Scheduler, │
|
||||
│ Socket.IO (Phase 6) │
|
||||
└────────────────┬─────────────────┘
|
||||
│ Auth (JWT), News CRUD, Upload (multer), │
|
||||
│ Scheduler, Socket.IO, Notifications │
|
||||
└────────────────────┬─────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────┐
|
||||
┌──────────────────────────────────────────┐
|
||||
│ MongoDB │
|
||||
│ users, news, notifications │
|
||||
└──────────────────────────────────┘
|
||||
└──────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Tech Stack
|
||||
## Стек технологий
|
||||
|
||||
| Layer | Technology |
|
||||
|-----------|---------------------------------------------|
|
||||
| Backend | Node.js 22, Express, TypeScript, Mongoose |
|
||||
| Auth | JWT (jsonwebtoken), bcrypt (cost 12) |
|
||||
| Real-time | Socket.IO (Phase 6) |
|
||||
| Upload | multer (disk storage, UUID filenames) |
|
||||
| Frontend | React 18, TypeScript, Vite, react-router-dom |
|
||||
| Editor | Markdown (react-markdown, remark-gfm) |
|
||||
| Tests | Vitest, Supertest, mongodb-memory-server |
|
||||
| Deploy | Docker Compose (nginx + node + mongo) |
|
||||
| Слой | Технология |
|
||||
|-------------|-----------------------------------------------------|
|
||||
| Бэкенд | Node.js 22, Express, TypeScript (strict) |
|
||||
| Авторизация | JWT (jsonwebtoken), bcrypt (cost 12) |
|
||||
| Real-time | Socket.IO (JWT auth, user rooms) |
|
||||
| Файлы | multer (disk storage, UUID filenames, MIME whitelist) |
|
||||
| Фронтенд | React 18, TypeScript, Vite, react-router-dom |
|
||||
| Стили | SCSS Modules (per-component) + global base |
|
||||
| Редактор | Markdown (react-markdown, remark-gfm, rehype-sanitize) |
|
||||
| Тесты | Vitest, Supertest, mongodb-memory-server |
|
||||
| Деплой | Docker Compose (nginx + node + mongo) |
|
||||
|
||||
## Project Structure
|
||||
## Структура проекта
|
||||
|
||||
```
|
||||
news-editor/
|
||||
├── package.json ← root scripts (dev, test, lint, build)
|
||||
├── docker-compose.yml ← production stack
|
||||
├── .env ← docker env vars (JWT_SECRET, PORT)
|
||||
├── docker-compose.yml ← production-стек
|
||||
├── .env ← env для docker (JWT_SECRET, PORT)
|
||||
├── server/
|
||||
│ ├── Dockerfile ← multi-stage: tsc → node:22-alpine
|
||||
│ ├── src/
|
||||
│ │ ├── app.ts ← Express app factory
|
||||
│ │ ├── server.ts ← entry point (HTTP + scheduler)
|
||||
│ │ ├── app.ts ← фабрика Express-приложения
|
||||
│ │ ├── server.ts ← точка входа (HTTP + Socket.IO + scheduler)
|
||||
│ │ ├── config/ ← env, database
|
||||
│ │ ├── middleware/ ← auth (JWT), error, notFound, upload (multer)
|
||||
│ │ ├── models/ ← User, News (Mongoose)
|
||||
│ │ ├── routes/ ← auth, news, upload, health
|
||||
│ │ ├── services/ ← publicationScheduler
|
||||
│ │ ├── models/ ← User, News, Notification (Mongoose)
|
||||
│ │ ├── routes/ ← auth, news, notification, upload, health
|
||||
│ │ ├── services/ ← publicationScheduler, notification
|
||||
│ │ ├── socket/ ← Socket.IO server + типизация
|
||||
│ │ └── utils/ ← ApiError, asyncHandler, jwt
|
||||
│ └── tests/ ← integration tests (Vitest + Supertest)
|
||||
│ └── tests/ ← интеграционные тесты (Vitest + Supertest)
|
||||
└── client/
|
||||
├── Dockerfile ← multi-stage: vite build → nginx:alpine
|
||||
├── nginx.conf ← SPA + proxy
|
||||
└── src/
|
||||
├── api/ ← fetch client (apiFetch, apiUpload)
|
||||
├── api/ ← fetch клиент (apiFetch, apiUpload), типы
|
||||
├── auth/ ← AuthContext (login, register, logout)
|
||||
├── components/ ← ProtectedRoute
|
||||
├── pages/ ← Login, Register, Home
|
||||
├── components/ ← ProtectedRoute, NotificationBell, MarkdownToolbar
|
||||
├── hooks/ ← useNewsEditor, useNotifications, useSocket
|
||||
├── pages/ ← Login, Register, Home, NewsList, NewsEditor
|
||||
├── styles/ ← global.scss (base reset + shared)
|
||||
└── App.tsx ← BrowserRouter + Routes
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
## Требования
|
||||
|
||||
- Node.js >= 20
|
||||
- npm >= 10
|
||||
- MongoDB (local, Atlas, or Docker)
|
||||
- Docker + Docker Compose (for production deploy)
|
||||
- MongoDB (локальная, Atlas, или Docker)
|
||||
- Docker + Docker Compose (для production-деплоя)
|
||||
|
||||
## Development Setup
|
||||
## Разработка
|
||||
|
||||
### 1. Install dependencies
|
||||
### 1. Установка зависимостей
|
||||
|
||||
```bash
|
||||
npm install
|
||||
@@ -86,13 +90,13 @@ npm --prefix server install
|
||||
npm --prefix client install
|
||||
```
|
||||
|
||||
### 2. Configure environment
|
||||
### 2. Конфигурация окружения
|
||||
|
||||
```bash
|
||||
cp server/.env.example server/.env
|
||||
```
|
||||
|
||||
Edit `server/.env`:
|
||||
Редактируем `server/.env`:
|
||||
|
||||
```env
|
||||
NODE_ENV=development
|
||||
@@ -105,40 +109,40 @@ MAX_UPLOAD_SIZE=20971520
|
||||
SCHEDULER_INTERVAL_MS=20000
|
||||
```
|
||||
|
||||
### 3. Run MongoDB (if not already running)
|
||||
### 3. Запуск MongoDB (если не запущена)
|
||||
|
||||
```bash
|
||||
# Option A: Docker
|
||||
# Вариант A: Docker
|
||||
docker run -d --name mongo -p 27017:27017 mongo:7
|
||||
|
||||
# Option B: Local install
|
||||
# Вариант B: Локальная установка
|
||||
mongod --dbpath ~/mongodb-data
|
||||
```
|
||||
|
||||
### 4. Run
|
||||
### 4. Запуск
|
||||
|
||||
```bash
|
||||
# Both server + client (uses concurrently)
|
||||
# Сервер + клиент одновременно (concurrently)
|
||||
npm run dev
|
||||
|
||||
# Or separately
|
||||
# Или по отдельности
|
||||
npm --prefix server run dev # http://localhost:3000
|
||||
npm --prefix client run dev # http://localhost:5173
|
||||
```
|
||||
|
||||
- Backend: http://localhost:3000
|
||||
- Frontend: http://localhost:5173
|
||||
- Бэкенд: http://localhost:3000
|
||||
- Фронтенд: http://localhost:5173
|
||||
- LAN: http://192.168.50.7:5173
|
||||
- Health: http://localhost:3000/api/health
|
||||
|
||||
## Production (Docker Compose)
|
||||
|
||||
Полный production-стек одним `docker compose up`.
|
||||
Полный production-стек одной командой `docker compose up`.
|
||||
|
||||
### Архитектура
|
||||
|
||||
| Сервис | Образ | Описание |
|
||||
|--------|-------|----------|
|
||||
|----------|--------------------------------|-----------------------------------|
|
||||
| `mongo` | mongo:7 | MongoDB с healthcheck |
|
||||
| `server` | multi-stage (node:22-alpine) | Express API + Socket.IO |
|
||||
| `client` | multi-stage (nginx:alpine) | React SPA + reverse proxy |
|
||||
@@ -163,7 +167,7 @@ curl http://localhost:8080/api/health
|
||||
### Переменные окружения (.env)
|
||||
|
||||
| Переменная | По умолчанию | Описание |
|
||||
|------------|-------------|----------|
|
||||
|-----------------|----------------------|---------------------------------------------|
|
||||
| `JWT_SECRET` | — (обязательна) | Секрет подписи JWT |
|
||||
| `PORT` | `8080` | Внешний порт nginx |
|
||||
| `CLIENT_ORIGIN` | `http://localhost:8080` | CORS origin (через запятую — несколько) |
|
||||
@@ -181,67 +185,127 @@ docker compose down -v
|
||||
### Файлы
|
||||
|
||||
| Файл | Назначение |
|
||||
|------|------------|
|
||||
|-----------------------|-----------------------------------------------|
|
||||
| `docker-compose.yml` | Оркестрация: mongo + server + client |
|
||||
| `server/Dockerfile` | Multi-stage: tsc build → node:22-alpine |
|
||||
| `client/Dockerfile` | Multi-stage: vite build → nginx:alpine |
|
||||
| `client/nginx.conf` | SPA fallback + proxy /api, /uploads, /socket.io |
|
||||
| `.dockerignore` | Исключения из build context |
|
||||
|
||||
## API Endpoints
|
||||
## API
|
||||
|
||||
### Auth
|
||||
### Авторизация
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|----------------------|------|--------------------------------|
|
||||
| POST | `/api/auth/register` | – | Register, returns `{token, user}` |
|
||||
| POST | `/api/auth/login` | – | Login, returns `{token, user}` |
|
||||
| GET | `/api/auth/me` | ✓ | Current user info |
|
||||
| Method | Path | Auth | Описание |
|
||||
|--------|----------------------|------|---------------------------------------|
|
||||
| POST | `/api/auth/register` | – | Регистрация, возвращает `{token, user}` |
|
||||
| POST | `/api/auth/login` | – | Логин, возвращает `{token, user}` |
|
||||
| GET | `/api/auth/me` | ✓ | Текущий пользователь |
|
||||
|
||||
### News (authenticated)
|
||||
### Новости (авторизовано)
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------------------------|------------------------------------|
|
||||
| GET | `/api/news` | List own news |
|
||||
| GET | `/api/news/:id` | Get one news article |
|
||||
| POST | `/api/news` | Create draft |
|
||||
| PATCH | `/api/news/:id` | Update own article |
|
||||
| DELETE | `/api/news/:id` | Delete own article |
|
||||
| POST | `/api/news/:id/publish`| Publish immediately |
|
||||
| POST | `/api/news/:id/schedule`| Schedule publication (`{scheduledAt}`) |
|
||||
| Method | Path | Описание |
|
||||
|--------|-------------------------|---------------------------------------|
|
||||
| GET | `/api/news` | Список своих новостей |
|
||||
| GET | `/api/news/:id` | Одна новость |
|
||||
| POST | `/api/news` | Создать черновик |
|
||||
| PATCH | `/api/news/:id` | Обновить свою новость |
|
||||
| DELETE扭头 | `/api/news/:id` | Удалить свою новость |
|
||||
| POST | `/api/news/:id/publish` | Опубликовать немедленно |
|
||||
| POST | `/api/news/:id/schedule`| Отложенная публикация (`{scheduledAt}`) |
|
||||
|
||||
### Upload
|
||||
### Уведомления (авторизовано)
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|---------------|------|------------------------------------------|
|
||||
| POST | `/api/uploads`| ✓ | Upload file (multipart), returns `{file}` |
|
||||
| GET | `/uploads/:filename` | – | Serve uploaded file (static) |
|
||||
| Method | Path | Описание |
|
||||
|--------|-----------------------------------|-----------------------------|
|
||||
| GET | `/api/notifications` | Список (последние 50) |
|
||||
| GET | `/api/notifications/unread-count` | Счётчик непрочитанных |
|
||||
| PATCH | `/api/notifications/:id/read` | Прочитать одно |
|
||||
| POST | `/api/notifications/read-all` | Прочитать все |
|
||||
|
||||
### Загрузка файлов
|
||||
|
||||
| Method | Path | Auth | Описание |
|
||||
|--------|----------------------|------|-------------------------------------------|
|
||||
| POST | `/api/uploads` | ✓ | Загрузить файл (multipart) |
|
||||
| GET | `/uploads/:filename` | – | Статическая раздача загруженного файла |
|
||||
|
||||
**MIME whitelist**: image/jpeg, image/png, image/gif, image/webp, application/pdf, application/msword, .docx
|
||||
|
||||
### Health
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|----------------|-------------------|
|
||||
| Method | Path | Описание |
|
||||
|--------|---------------|-------------------|
|
||||
| GET | `/api/health` | `{"status":"ok"}` |
|
||||
|
||||
## Scheduled Publication
|
||||
## Real-time уведомления (Socket.IO)
|
||||
|
||||
The backend runs a poller every 20 seconds (configurable via `SCHEDULER_INTERVAL_MS`) that finds articles with:
|
||||
Socket.IO подключён к тому же HTTP-серверу, что и Express.
|
||||
|
||||
### Подключение клиента
|
||||
|
||||
```js
|
||||
import { io } from 'socket.io-client';
|
||||
|
||||
const socket = io('http://localhost:8080', {
|
||||
auth: { token: jwtToken },
|
||||
transports: ['websocket', 'polling'],
|
||||
});
|
||||
|
||||
// Real-time уведомления
|
||||
socket.on('notification', (data) => {
|
||||
console.log(data.title, data.message);
|
||||
});
|
||||
```
|
||||
|
||||
### Аутентификация
|
||||
|
||||
JWT передаётся через `handshake.auth.token`. Сервер верифицирует токен в `io.use()` middleware и при неудаче отклоняет подключение.
|
||||
|
||||
### События
|
||||
|
||||
| Event | Payload | Когда |
|
||||
|----------------|--------------------------------------------------|--------------------------------|
|
||||
| `notification` | `{id, type, title, message, isRead, createdAt}` | news.deleted, published, scheduled |
|
||||
|
||||
### Rooms
|
||||
|
||||
Каждый подключённый socket добавляется в room `user:{userId}`. Уведомления отправляются через `io.to('user:{id}').emit(...)`.
|
||||
|
||||
## Отложенная публикация
|
||||
|
||||
Бэкенд запускает poller каждые 20 секунд (настраивается через `SCHEDULER_INTERVAL_MS`), который находит статьи:
|
||||
|
||||
```js
|
||||
{ status: 'scheduled', scheduledAt: { $lte: now } }
|
||||
```
|
||||
|
||||
and atomically transitions them to `published` via `findOneAndUpdate`. Survives process restarts — no in-memory `setTimeout` per article.
|
||||
и атомарно переводит их в `published` через `findOneAndUpdate`. Выживает после перезапуска процесса — без in-memory `setTimeout` на статью.
|
||||
|
||||
## Upload
|
||||
## Загрузка файлов
|
||||
|
||||
Files are stored on the filesystem (`UPLOAD_DIR`, default `server/uploads/`). Filenames are UUID-based to prevent collisions. Max size: 20 MB (configurable via `MAX_UPLOAD_SIZE`).
|
||||
Файлы хранятся на файловой системе (`UPLOAD_DIR`, по умолчанию `server/uploads/`). Имена файлов — UUID (защита от коллизий). Максимальный размер: 20 МБ (настраивается через `MAX_UPLOAD_SIZE`).
|
||||
|
||||
## Error Format
|
||||
## Фронтенд: Markdown-редактор
|
||||
|
||||
All errors follow a consistent shape:
|
||||
- **Toolbar**: Bold, Italic, Heading, Quote, Code, Link, Image, File
|
||||
- **Preview**: react-markdown + remark-gfm + rehype-sanitize
|
||||
- **Upload**: изображение/файл → вставка markdown-ссылки в textarea
|
||||
- **UI зависит от статуса**:
|
||||
- Draft/scheduled: Сохранить + Опубликовать + Удалить + Schedule + toggle Редактор/Предпросмотр
|
||||
- Published: Сохранить + Удалить (по умолчанию preview, нет publish/schedule)
|
||||
|
||||
## Фронтенд: Колокольчик уведомлений
|
||||
|
||||
- 🔔 иконка с badge (счётчик непрочитанных)
|
||||
- Клик → панель со списком уведомлений
|
||||
- Клик по уведомлению → пометить прочитанным
|
||||
- "Прочитать все" → пометить все
|
||||
- Real-time: новые уведомления появляются без перезагрузки (Socket.IO)
|
||||
|
||||
## Формат ошибок
|
||||
|
||||
Все ошибки имеют единый формат:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -252,32 +316,33 @@ All errors follow a consistent shape:
|
||||
}
|
||||
```
|
||||
|
||||
## Testing
|
||||
## Тесты
|
||||
|
||||
```bash
|
||||
npm --prefix server test # Vitest + Supertest + mongodb-memory-server (46 tests)
|
||||
npm test # all tests
|
||||
npm --prefix server test # Vitest + Supertest + mongodb-memory-server (46 тестов)
|
||||
npm test # все тесты
|
||||
```
|
||||
|
||||
## Lint
|
||||
## Линт
|
||||
|
||||
```bash
|
||||
npm run lint # ESLint (strictTypeChecked + sonarjs) for server + client
|
||||
npm run lint # ESLint (strictTypeChecked + sonarjs) для server + client
|
||||
```
|
||||
|
||||
## Production Build
|
||||
## Production-сборка
|
||||
|
||||
```bash
|
||||
npm --prefix client run build
|
||||
# Output: client/dist/ (static files, deployable to any static host)
|
||||
# Результат: client/dist/ (статические файлы, можно деплоить на любой хостинг)
|
||||
```
|
||||
|
||||
## Demo Flow
|
||||
## Демонстрационный сценарий
|
||||
|
||||
1. Register → Login → see JWT with user `id`
|
||||
2. Create a draft → add markdown content
|
||||
3. Upload an image → get URL → insert into article
|
||||
4. Save draft → see in list
|
||||
5. Schedule publication for 1–2 min ahead → watch it auto-publish
|
||||
6. Publish immediately → article is live
|
||||
7. Delete article
|
||||
1. Регистрация → Логин → JWT с `id` пользователя
|
||||
2. Создать черновик → добавить markdown через toolbar
|
||||
3. Загрузить изображение → получить URL → вставить в статью
|
||||
4. Сохранить черновик → виден в списке (с preview контента)
|
||||
5. Запланировать публикацию на 1–2 мин вперёд → наблюдать авто-публикацию
|
||||
6. Опубликовать немедленно → статья live (UI переключается в read-only preview)
|
||||
7. Колокольчик показывает real-time события
|
||||
8. Удалить статью
|
||||
|
||||
Generated
+1
-4
@@ -14,7 +14,7 @@
|
||||
"react-router-dom": "^7.2.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-gfm": "^4.0.0",
|
||||
"socket.io-client": "^4.8.1"
|
||||
"socket.io-client": "^4.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
|
||||
@@ -1986,14 +1986,12 @@
|
||||
"version": "15.7.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
|
||||
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "18.3.31",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
|
||||
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
@@ -3293,7 +3291,6 @@
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/damerau-levenshtein": {
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
"react-router-dom": "^7.2.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-gfm": "^4.0.0",
|
||||
"socket.io-client": "^4.8.1"
|
||||
"socket.io-client": "^4.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
|
||||
|
||||
@@ -28,3 +28,18 @@ export interface NewsItem {
|
||||
export interface UploadResponse {
|
||||
file: { url: string; filename: string; size: number };
|
||||
}
|
||||
|
||||
/** Тип уведомления. */
|
||||
export type NotificationType = 'news.created' | 'news.updated' | 'news.deleted' | 'news.scheduled' | 'news.published';
|
||||
|
||||
/** Уведомление (сериализованное от backend). */
|
||||
export interface NotificationItem {
|
||||
id: string;
|
||||
actor: string | null;
|
||||
type: NotificationType;
|
||||
news: string | null;
|
||||
title: string;
|
||||
message: string;
|
||||
isRead: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ interface MarkdownToolbarProps {
|
||||
*/
|
||||
export function MarkdownToolbar({ onAction, onImageUpload, onFileUpload }: MarkdownToolbarProps) {
|
||||
return (
|
||||
<div className="markdown-toolbar" role="toolbar" aria-label="Форматирование">
|
||||
<div role="toolbar" aria-label="Форматирование">
|
||||
<button type="button" title="Полужирный" onClick={() => { onAction('bold'); }}>
|
||||
<strong>B</strong>
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
.wrapper {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.trigger {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-radius: 6px;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: #f3f4f6;
|
||||
}
|
||||
}
|
||||
|
||||
.bell {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.badge {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -10px;
|
||||
background: #ef4444;
|
||||
color: #fff;
|
||||
font-size: 0.65rem;
|
||||
font-weight: 700;
|
||||
border-radius: 10px;
|
||||
padding: 1px 5px;
|
||||
min-width: 16px;
|
||||
text-align: center;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.panel {
|
||||
position: absolute;
|
||||
top: calc(100% + 0.625rem);
|
||||
right: 0;
|
||||
width: 340px;
|
||||
max-height: 420px;
|
||||
overflow-y: auto;
|
||||
background: #fff;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.875rem 1.25rem;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.markAll {
|
||||
background: none;
|
||||
border: none;
|
||||
color: #3b82f6;
|
||||
cursor: pointer;
|
||||
font-size: 0.8rem;
|
||||
padding: 0;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
.item {
|
||||
border-bottom: 1px solid #f9fafb;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&.unread {
|
||||
background: #f0f7ff;
|
||||
}
|
||||
|
||||
&.read {
|
||||
opacity: 0.65;
|
||||
}
|
||||
}
|
||||
|
||||
.itemBtn {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.75rem 1.25rem;
|
||||
border: none;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background 0.1s;
|
||||
|
||||
&:hover {
|
||||
background: #f9fafb;
|
||||
}
|
||||
}
|
||||
|
||||
.itemTitle {
|
||||
display: block;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
.itemMessage {
|
||||
display: block;
|
||||
font-size: 0.82rem;
|
||||
color: #4b5563;
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
|
||||
.itemTime {
|
||||
display: block;
|
||||
font-size: 0.72rem;
|
||||
color: #9ca3af;
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 2rem 1.25rem;
|
||||
text-align: center;
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useNotifications } from '../hooks/useNotifications.js';
|
||||
|
||||
import styles from './NotificationBell.module.scss';
|
||||
|
||||
import type { NotificationItem } from '../api/types.js';
|
||||
|
||||
|
||||
/**
|
||||
* Форматирует дату в коротком формате.
|
||||
*
|
||||
* @param iso — ISO-дата
|
||||
* @returns строка вида "16.08 12:30"
|
||||
*/
|
||||
function formatDateTime(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const hours = String(d.getHours()).padStart(2, '0');
|
||||
const minutes = String(d.getMinutes()).padStart(2, '0');
|
||||
return `${day}.${month} ${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Одиночное уведомление в списке.
|
||||
*/
|
||||
function NotificationItemRow({
|
||||
notification, onRead,
|
||||
}: {
|
||||
readonly notification: NotificationItem;
|
||||
readonly onRead: (id: string) => void;
|
||||
}) {
|
||||
const cls = notification.isRead ? styles.read : styles.unread;
|
||||
return (
|
||||
<li className={`${styles.item} ${cls}`}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.itemBtn}
|
||||
onClick={() => { if (!notification.isRead) { onRead(notification.id); } }}
|
||||
>
|
||||
<span className={styles.itemTitle}>{notification.title}</span>
|
||||
<span className={styles.itemMessage}>{notification.message}</span>
|
||||
<span className={styles.itemTime}>{formatDateTime(notification.createdAt)}</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Компонент колокольчика уведомлений.
|
||||
*
|
||||
* Отображает иконку с badge, по клику раскрывает список уведомлений.
|
||||
* Подключается к Socket.IO для real-time обновлений.
|
||||
*/
|
||||
export function NotificationBell({ token }: { readonly token: string | null }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const {
|
||||
notifications, unreadCount, markAsRead, markAllAsRead,
|
||||
} = useNotifications(token);
|
||||
|
||||
const handleMarkAsRead = (id: string): void => {
|
||||
markAsRead(id).catch(() => { /* ignore */ });
|
||||
};
|
||||
|
||||
const handleMarkAll = (): void => {
|
||||
markAllAsRead().catch(() => { /* ignore */ });
|
||||
};
|
||||
|
||||
if (token === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.trigger}
|
||||
onClick={() => { setOpen((v) => !v); }}
|
||||
aria-label="Уведомления"
|
||||
>
|
||||
<span className={styles.bell}>
|
||||
🔔
|
||||
{unreadCount > 0 && <span className={styles.badge}>{unreadCount > 99 ? '99+' : String(unreadCount)}</span>}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{open ? <div className={styles.panel}>
|
||||
<div className={styles.header}>
|
||||
<h3>Уведомления</h3>
|
||||
{unreadCount > 0
|
||||
? (
|
||||
<button type="button" className={styles.markAll} onClick={handleMarkAll}>
|
||||
Прочитать все
|
||||
</button>
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
|
||||
{notifications.length === 0
|
||||
? <p className={styles.empty}>Нет уведомлений</p>
|
||||
: (
|
||||
<ul className={styles.list}>
|
||||
{notifications.map((n) => (
|
||||
<NotificationItemRow key={n.id} notification={n} onRead={handleMarkAsRead} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
|
||||
import { apiFetch, apiUpload } from '../api/client.js';
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { UploadResponse } from '../api/types.js';
|
||||
function useLoadNews(newsId: string | undefined, isNew: boolean) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [newsStatus, setNewsStatus] = useState<'draft' | 'scheduled' | 'published'>('draft');
|
||||
const [loading, setLoading] = useState(!isNew);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -20,9 +21,13 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
|
||||
void (async () => {
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- newsId гарантированно string (проверено isNew)
|
||||
const data = await apiFetch<{ news: { title: string; content: string } }>(`/news/${newsId}`);
|
||||
const data = await apiFetch<{ news: { title: string; content: string; status: string } }>(`/news/${newsId}`);
|
||||
setTitle(data.news.title);
|
||||
setContent(data.news.content);
|
||||
const s = data.news.status;
|
||||
if (s === 'draft' || s === 'scheduled' || s === 'published') {
|
||||
setNewsStatus(s);
|
||||
}
|
||||
} catch {
|
||||
// Ошибка загрузки — остаёмся с пустым состоянием
|
||||
} finally {
|
||||
@@ -31,7 +36,7 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
|
||||
})();
|
||||
}, [newsId, isNew]);
|
||||
|
||||
return { title, setTitle, content, setContent, loading };
|
||||
return { title, setTitle, content, setContent, newsStatus, loading };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,7 +48,7 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
|
||||
/* eslint-disable max-lines-per-function -- хук-оркестратор */
|
||||
export function useNewsEditor(newsId: string | undefined) {
|
||||
const isNew = newsId === undefined;
|
||||
const { title, setTitle, content, setContent, loading } = useLoadNews(newsId, isNew);
|
||||
const { title, setTitle, content, setContent, newsStatus, loading } = useLoadNews(newsId, isNew);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [scheduleDate, setScheduleDate] = useState('');
|
||||
@@ -203,14 +208,34 @@ export function useNewsEditor(newsId: string | undefined) {
|
||||
if (action === 'link') { insertMarkdown('[', '](https://)'); }
|
||||
}, [insertMarkdown]);
|
||||
|
||||
/** Обработчик file input для изображений. */
|
||||
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file !== undefined) {
|
||||
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
|
||||
}
|
||||
// eslint-disable-next-line no-param-reassign -- сброс file input
|
||||
e.target.value = '';
|
||||
}, [handleFileUpload]);
|
||||
|
||||
/** Обработчик file input для файлов. */
|
||||
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file !== undefined) {
|
||||
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
|
||||
}
|
||||
// eslint-disable-next-line no-param-reassign -- сброс file input
|
||||
e.target.value = '';
|
||||
}, [handleFileUpload]);
|
||||
|
||||
return {
|
||||
isNew, title, setTitle,
|
||||
content, setContent,
|
||||
content, setContent, newsStatus,
|
||||
loading, saving, error,
|
||||
scheduleDate, setScheduleDate,
|
||||
textareaRef,
|
||||
insertMarkdown, handleToolbarAction,
|
||||
handleFileUpload,
|
||||
handleFileUpload, onImageChange, onFileChange,
|
||||
onSave, onPublish, onDelete, onSchedule,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
import { apiFetch } from '../api/client.js';
|
||||
|
||||
import { useSocket } from './useSocket.js';
|
||||
|
||||
import type { NotificationItem } from '../api/types.js';
|
||||
|
||||
/**
|
||||
* Хук для управления уведомлениями.
|
||||
*
|
||||
* Подписывается на Socket.IO события, загружает список уведомлений,
|
||||
* предоставляет счётчик непрочитанных и методы отметки.
|
||||
*
|
||||
* @param token — JWT токен (null если не авторизован)
|
||||
* @returns состояние и методы для NotificationBell
|
||||
*/
|
||||
export function useNotifications(token: string | null) {
|
||||
const socket = useSocket(token);
|
||||
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
||||
const [unreadCount, setUnreadCount] = useState(0);
|
||||
|
||||
/** Загружает список уведомлений и счётчик непрочитанных. */
|
||||
const fetchNotifications = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
const [listRes, countRes] = await Promise.all([
|
||||
apiFetch<{ notifications: NotificationItem[] }>('/notifications'),
|
||||
apiFetch<{ count: number }>('/notifications/unread-count'),
|
||||
]);
|
||||
setNotifications(listRes.notifications);
|
||||
setUnreadCount(countRes.count);
|
||||
} catch {
|
||||
// Ошибка загрузки — игнорируем (user может быть offline)
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** Отмечает одно уведомление как прочитанное. */
|
||||
const markAsRead = useCallback(async (id: string): Promise<void> => {
|
||||
try {
|
||||
await apiFetch(`/notifications/${id}/read`, { method: 'PATCH' });
|
||||
setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, isRead: true } : n));
|
||||
setUnreadCount((prev) => Math.max(0, prev - 1));
|
||||
} catch {
|
||||
// Игнорируем ошибку
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** Отмечает все уведомления как прочитанные. */
|
||||
const markAllAsRead = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
await apiFetch('/notifications/read-all', { method: 'POST' });
|
||||
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
|
||||
setUnreadCount(0);
|
||||
} catch {
|
||||
// Игнорируем ошибку
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Загружаем уведомления при монтировании (если авторизован)
|
||||
useEffect(() => {
|
||||
if (token !== null) {
|
||||
fetchNotifications().catch(() => { /* ignore */ });
|
||||
}
|
||||
}, [token, fetchNotifications]);
|
||||
|
||||
// Подписываемся на real-time уведомления
|
||||
useEffect(() => {
|
||||
const onNotification = (data: NotificationItem): void => {
|
||||
setNotifications((prev) => [data, ...prev]);
|
||||
setUnreadCount((prev) => prev + 1);
|
||||
};
|
||||
|
||||
if (socket !== null) {
|
||||
socket.on('notification', onNotification);
|
||||
return () => {
|
||||
socket.off('notification', onNotification);
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}, [socket]);
|
||||
|
||||
return {
|
||||
notifications,
|
||||
unreadCount,
|
||||
fetchNotifications,
|
||||
markAsRead,
|
||||
markAllAsRead,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
|
||||
/**
|
||||
* Подключается к Socket.IO серверу с JWT-аутентификацией.
|
||||
*
|
||||
* @param token — JWT токен пользователя
|
||||
* @param url — URL Socket.IO сервера (по умолчанию — текущий origin)
|
||||
* @returns socket или null (если не подключено)
|
||||
*/
|
||||
export function useSocket(token: string | null, url?: string): Socket | null {
|
||||
const [socket, setSocket] = useState<Socket | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (token === null || token === '') {
|
||||
setSocket(null);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const socketUrl = url ?? window.location.origin;
|
||||
const newSocket = io(socketUrl, {
|
||||
auth: { token },
|
||||
transports: ['websocket', 'polling'],
|
||||
});
|
||||
|
||||
setSocket(newSocket);
|
||||
|
||||
return () => {
|
||||
newSocket.disconnect();
|
||||
setSocket(null);
|
||||
};
|
||||
}, [token, url]);
|
||||
|
||||
return socket;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
.page {
|
||||
max-width: 640px;
|
||||
margin: 3rem auto;
|
||||
padding: 3rem 2.5rem;
|
||||
text-align: center;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
|
||||
|
||||
p {
|
||||
margin-bottom: 1.5rem;
|
||||
color: #4b5563;
|
||||
}
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.875rem 2rem;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
|
||||
|
||||
a {
|
||||
margin-right: 1.25rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.navRight {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
|
||||
button {
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
import { useAuth } from '../auth/AuthContext.js';
|
||||
import { NotificationBell } from '../components/NotificationBell.js';
|
||||
|
||||
import styles from './HomePage.module.scss';
|
||||
|
||||
/**
|
||||
* Главная страница (защищена ProtectedRoute).
|
||||
* Показывает email пользователя, навигацию и кнопку logout.
|
||||
*/
|
||||
export function HomePage() {
|
||||
const { userEmail, logout } = useAuth();
|
||||
const { userEmail, token, logout } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="home-page">
|
||||
<nav className="top-nav">
|
||||
<>
|
||||
<nav className={styles.nav}>
|
||||
<span>News Editor — {userEmail}</span>
|
||||
<div>
|
||||
<div className={styles.navRight}>
|
||||
<NotificationBell token={token} />
|
||||
<Link to="/news">Мои новости</Link>
|
||||
<button type="button" onClick={logout}>
|
||||
Выйти
|
||||
@@ -21,11 +25,13 @@ export function HomePage() {
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div className={styles.page}>
|
||||
<h1>News Editor</h1>
|
||||
<p>Добро пожаловать, {userEmail}!</p>
|
||||
<Link to="/news" className="btn btn-primary">
|
||||
Перейти к новостям
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { useAuth } from '../auth/AuthContext.js';
|
||||
|
||||
import styles from './auth.module.scss';
|
||||
|
||||
/**
|
||||
* Страница логина.
|
||||
*/
|
||||
@@ -29,10 +31,10 @@ export function LoginPage() {
|
||||
/* eslint-enable @typescript-eslint/no-floating-promises */
|
||||
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<h1>Вход</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<div className={styles.page}>
|
||||
<h1 className={styles.title}>Вход</h1>
|
||||
<form className={styles.form} onSubmit={handleSubmit}>
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="email">Email</label>
|
||||
<input
|
||||
id="email"
|
||||
@@ -43,7 +45,7 @@ export function LoginPage() {
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="password">Пароль</label>
|
||||
<input
|
||||
id="password"
|
||||
@@ -55,13 +57,13 @@ export function LoginPage() {
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" disabled={loading}>
|
||||
<button type="submit" className={`btn btn-primary ${styles.submit}`} disabled={loading}>
|
||||
{loading ? 'Вход...' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
<p>
|
||||
<p className={styles.switch}>
|
||||
Нет аккаунта?{' '}
|
||||
<a href="/register">Зарегистрироваться</a>
|
||||
<Link to="/register">Зарегистрироваться</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
.page {
|
||||
max-width: 820px;
|
||||
margin: 2rem auto;
|
||||
padding: 2rem 2.5rem;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 2rem;
|
||||
padding-bottom: 1.25rem;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem 1rem;
|
||||
|
||||
h1 {
|
||||
margin-bottom: 0;
|
||||
font-size: 1.4rem;
|
||||
margin-right: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 0.625rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.titleInput {
|
||||
font-size: 1.3rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1.5rem;
|
||||
border: none;
|
||||
border-bottom: 2px solid #e5e7eb;
|
||||
border-radius: 0;
|
||||
padding: 0.625rem 0;
|
||||
|
||||
&:focus {
|
||||
border-bottom-color: #2563eb;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.scheduleRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.25rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: #fffbeb;
|
||||
border: 1px solid #fde68a;
|
||||
border-radius: 8px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
label {
|
||||
font-size: 0.9rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
input {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: #f9fafb;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-bottom: none;
|
||||
border-radius: 6px 6px 0 0;
|
||||
flex-wrap: wrap;
|
||||
|
||||
button {
|
||||
padding: 0.4rem 0.65rem;
|
||||
font-size: 0.88rem;
|
||||
background: transparent;
|
||||
color: #374151;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
|
||||
&:hover {
|
||||
background: #e5e7eb;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.textarea {
|
||||
min-height: 320px;
|
||||
resize: vertical;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.7;
|
||||
border-radius: 0 0 6px 6px;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.preview {
|
||||
padding: 1.5rem 2rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
background: #fafafa;
|
||||
min-height: 320px;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useRef, useState, type ChangeEvent, type RefObject } from 'react';
|
||||
import { useRef, useState, type ChangeEvent, type RefObject } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import rehypeSanitize from 'rehype-sanitize';
|
||||
@@ -7,33 +7,38 @@ import remarkGfm from 'remark-gfm';
|
||||
import { MarkdownToolbar } from '../components/MarkdownToolbar.js';
|
||||
import { useNewsEditor } from '../hooks/useNewsEditor.js';
|
||||
|
||||
import styles from './NewsEditorPage.module.scss';
|
||||
|
||||
/**
|
||||
* Панель действий редактора (кнопки).
|
||||
*/
|
||||
function EditorActions({
|
||||
isNew, saving, onSave, onPublish, onDelete,
|
||||
isNew, isPublished, saving, onSave, onPublish, onDelete,
|
||||
}: {
|
||||
readonly isNew: boolean;
|
||||
readonly isPublished: boolean;
|
||||
readonly saving: boolean;
|
||||
readonly onSave: () => void;
|
||||
readonly onPublish: () => void;
|
||||
readonly onDelete: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="editor-actions">
|
||||
<div className={styles.actions}>
|
||||
<button type="button" className="btn btn-primary" onClick={onSave} disabled={saving}>
|
||||
Сохранить
|
||||
</button>
|
||||
{!isNew
|
||||
{!isNew && !isPublished
|
||||
? (
|
||||
<>
|
||||
<button type="button" className="btn btn-publish" onClick={onPublish} disabled={saving}>
|
||||
Опубликовать
|
||||
</button>
|
||||
)
|
||||
: null}
|
||||
{!isNew
|
||||
? (
|
||||
<button type="button" className="btn btn-delete" onClick={onDelete} disabled={saving}>
|
||||
Удалить
|
||||
</button>
|
||||
</>
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
@@ -52,7 +57,7 @@ function ScheduleRow({
|
||||
readonly onSchedule: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="schedule-row">
|
||||
<div className={styles.scheduleRow}>
|
||||
<label>
|
||||
Отложенная публикация:{' '}
|
||||
<input
|
||||
@@ -93,11 +98,13 @@ function EditorForm({
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div className={styles.toolbar}>
|
||||
<MarkdownToolbar onAction={onAction} onImageUpload={onImageUpload} onFileUpload={onFileUpload} />
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="editor-textarea"
|
||||
className={styles.textarea}
|
||||
value={content}
|
||||
onChange={(e) => { setContent(e.target.value); }}
|
||||
placeholder="Напишите текст в Markdown..."
|
||||
@@ -127,10 +134,10 @@ function EditorForm({
|
||||
*/
|
||||
function EditorPreview({ content }: { readonly content: string }) {
|
||||
if (content === '') {
|
||||
return <div className="editor-preview markdown-body"><p className="empty">Нет контента для предпросмотра</p></div>;
|
||||
return <div className={styles.preview}><p className="empty">Нет контента для предпросмотра</p></div>;
|
||||
}
|
||||
return (
|
||||
<div className="editor-preview markdown-body">
|
||||
<div className={`${styles.preview} markdown-body`}>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSanitize]}>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
@@ -143,64 +150,57 @@ function EditorPreview({ content }: { readonly content: string }) {
|
||||
*/
|
||||
export function NewsEditorPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [showPreview, setShowPreview] = useState(false);
|
||||
const [showPreview, setShowPreview] = useState(id !== undefined);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const imageInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const editor = useNewsEditor(id);
|
||||
|
||||
const {
|
||||
isNew, title, setTitle, content, setContent,
|
||||
isNew, title, setTitle, content, setContent, newsStatus,
|
||||
loading, saving, error,
|
||||
scheduleDate, setScheduleDate, textareaRef,
|
||||
handleToolbarAction, handleFileUpload,
|
||||
handleToolbarAction, onImageChange, onFileChange,
|
||||
onSave, onPublish, onDelete, onSchedule,
|
||||
} = editor;
|
||||
|
||||
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file !== undefined) {
|
||||
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
|
||||
}
|
||||
// eslint-disable-next-line no-param-reassign -- сброс file input для повторной загрузки
|
||||
e.target.value = '';
|
||||
}, [handleFileUpload]);
|
||||
|
||||
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file !== undefined) {
|
||||
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
|
||||
}
|
||||
// eslint-disable-next-line no-param-reassign -- сброс file input для повторной загрузки
|
||||
e.target.value = '';
|
||||
}, [handleFileUpload]);
|
||||
|
||||
if (loading) {
|
||||
return <p className="loading">Загрузка...</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="news-editor">
|
||||
<div className="editor-header">
|
||||
<div className={styles.page}>
|
||||
<div className={styles.header}>
|
||||
<Link to="/news" className="btn btn-back">← Назад</Link>
|
||||
<h1>{isNew ? 'Новая новость' : 'Редактирование'}</h1>
|
||||
<EditorActions isNew={isNew} saving={saving} onSave={onSave} onPublish={onPublish} onDelete={onDelete} />
|
||||
<EditorActions
|
||||
isNew={isNew}
|
||||
isPublished={newsStatus === 'published'}
|
||||
saving={saving}
|
||||
onSave={onSave}
|
||||
onPublish={onPublish}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
{newsStatus !== 'published'
|
||||
? (
|
||||
<button type="button" className="btn" onClick={() => { setShowPreview((v) => !v); }}>
|
||||
{showPreview ? 'Редактор' : 'Предпросмотр'}
|
||||
</button>
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
|
||||
{error !== '' && <p className="error">{error}</p>}
|
||||
|
||||
<input
|
||||
type="text"
|
||||
className="title-input"
|
||||
className={styles.titleInput}
|
||||
placeholder="Заголовок..."
|
||||
value={title}
|
||||
onChange={(e) => { setTitle(e.target.value); }}
|
||||
/>
|
||||
|
||||
{!isNew
|
||||
{!isNew && newsStatus !== 'published'
|
||||
? (
|
||||
<ScheduleRow
|
||||
scheduleDate={scheduleDate}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
.page {
|
||||
max-width: 720px;
|
||||
margin: 2rem auto;
|
||||
padding: 2rem 2.5rem;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 1.5rem;
|
||||
padding-bottom: 1rem;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
|
||||
h1 {
|
||||
font-size: 1.4rem;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
padding: 1rem 1.25rem;
|
||||
background: #fafbfc;
|
||||
border: 1px solid #f3f4f6;
|
||||
border-radius: 8px;
|
||||
transition: box-shadow 0.15s, border-color 0.15s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
|
||||
border-color: #e5e7eb;
|
||||
}
|
||||
}
|
||||
|
||||
.cardBody {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cardTitle {
|
||||
font-weight: 600;
|
||||
display: block;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.cardPreview {
|
||||
font-size: 0.85rem;
|
||||
color: #6b7280;
|
||||
line-height: 1.4;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.cardMeta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 0.35rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cardDate {
|
||||
font-size: 0.78rem;
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 0.72rem;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
|
||||
&.draft {
|
||||
background: #f3f4f6;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
&.scheduled {
|
||||
background: #fef3c7;
|
||||
color: #92400e;
|
||||
}
|
||||
|
||||
&.published {
|
||||
background: #d1fae5;
|
||||
color: #065f46;
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,11 @@ import { Link } from 'react-router-dom';
|
||||
|
||||
import { apiFetch } from '../api/client.js';
|
||||
|
||||
import styles from './NewsListPage.module.scss';
|
||||
|
||||
import type { NewsItem } from '../api/types.js';
|
||||
|
||||
|
||||
/**
|
||||
* Страница со списком новостей текущего пользователя.
|
||||
*/
|
||||
@@ -32,8 +35,8 @@ export function NewsListPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="news-list">
|
||||
<div className="news-list-header">
|
||||
<div className={styles.page}>
|
||||
<div className={styles.header}>
|
||||
<h1>Мои новости</h1>
|
||||
<Link to="/news/new" className="btn btn-primary">
|
||||
+ Создать
|
||||
@@ -45,16 +48,25 @@ export function NewsListPage() {
|
||||
{news.length === 0
|
||||
? <p className="empty">Нет новостей. Создайте первую!</p>
|
||||
: (
|
||||
<ul className="news-cards">
|
||||
<ul className={styles.list}>
|
||||
{news.map((item) => (
|
||||
<li key={item.id} className="news-card">
|
||||
<Link to={`/news/${item.id}`} className="news-card-title">
|
||||
<li key={item.id} className={styles.card}>
|
||||
<div className={styles.cardBody}>
|
||||
<Link to={`/news/${item.id}`} className={styles.cardTitle}>
|
||||
{item.title !== '' ? item.title : '(без названия)'}
|
||||
</Link>
|
||||
<span className={`badge badge-${item.status}`}>{item.status}</span>
|
||||
<span className="news-card-date">
|
||||
{item.content !== '' && (
|
||||
<p className={styles.cardPreview}>
|
||||
{item.content.replace(/[#*`[\]!\n]/g, '').slice(0, 120)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.cardMeta}>
|
||||
<span className={`${styles.badge} ${styles[item.status]}`}>{item.status}</span>
|
||||
<span className={styles.cardDate}>
|
||||
{new Date(item.updatedAt).toLocaleString('ru-RU')}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { useAuth } from '../auth/AuthContext.js';
|
||||
|
||||
import styles from './auth.module.scss';
|
||||
|
||||
/**
|
||||
* Страница регистрации.
|
||||
*/
|
||||
@@ -34,10 +36,10 @@ export function RegisterPage() {
|
||||
/* eslint-enable @typescript-eslint/no-floating-promises */
|
||||
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<h1>Регистрация</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<div className={styles.page}>
|
||||
<h1 className={styles.title}>Регистрация</h1>
|
||||
<form className={styles.form} onSubmit={handleSubmit}>
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="email">Email</label>
|
||||
<input
|
||||
id="email"
|
||||
@@ -48,7 +50,7 @@ export function RegisterPage() {
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="password">Пароль</label>
|
||||
<input
|
||||
id="password"
|
||||
@@ -60,7 +62,7 @@ export function RegisterPage() {
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="confirmPassword">Повторите пароль</label>
|
||||
<input
|
||||
id="confirmPassword"
|
||||
@@ -72,13 +74,13 @@ export function RegisterPage() {
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" disabled={loading}>
|
||||
<button type="submit" className={`btn btn-primary ${styles.submit}`} disabled={loading}>
|
||||
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
<p>
|
||||
<p className={styles.switch}>
|
||||
Уже есть аккаунт?{' '}
|
||||
<a href="/login">Войти</a>
|
||||
<Link to="/login">Войти</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
.page {
|
||||
max-width: 400px;
|
||||
margin: 3rem auto;
|
||||
padding: 2rem 2.5rem;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 1.4rem;
|
||||
margin-bottom: 1.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
|
||||
label {
|
||||
font-weight: 500;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.submit {
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.switch {
|
||||
margin-top: 1.5rem;
|
||||
text-align: center;
|
||||
font-size: 0.9rem;
|
||||
color: #6b7280;
|
||||
|
||||
a {
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
}
|
||||
+34
-249
@@ -1,4 +1,4 @@
|
||||
// Глобальные стили News Editor
|
||||
// Глобальные стили News Editor (base + shared utilities)
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
@@ -10,7 +10,7 @@ body {
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #1a1a2e;
|
||||
background: #f5f5f5;
|
||||
background: #f0f2f5;
|
||||
}
|
||||
|
||||
a {
|
||||
@@ -27,25 +27,6 @@ h1 {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 0.5rem 1.2rem;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
background: #2563eb;
|
||||
color: #fff;
|
||||
font-size: 0.95rem;
|
||||
cursor: pointer;
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
}
|
||||
|
||||
input,
|
||||
textarea {
|
||||
width: 100%;
|
||||
@@ -62,7 +43,7 @@ textarea {
|
||||
}
|
||||
}
|
||||
|
||||
// Кнопки
|
||||
// === Shared: Кнопки ===
|
||||
.btn {
|
||||
display: inline-block;
|
||||
padding: 0.5rem 1.2rem;
|
||||
@@ -73,17 +54,23 @@ textarea {
|
||||
text-decoration: none;
|
||||
background: #e5e7eb;
|
||||
color: #1a1a2e;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: #d1d5db;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
&-primary {
|
||||
background: #2563eb;
|
||||
color: #fff;
|
||||
|
||||
&:hover {
|
||||
&:hover:not(:disabled) {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
}
|
||||
@@ -92,7 +79,7 @@ textarea {
|
||||
background: #16a34a;
|
||||
color: #fff;
|
||||
|
||||
&:hover {
|
||||
&:hover:not(:disabled) {
|
||||
background: #15803d;
|
||||
}
|
||||
}
|
||||
@@ -101,7 +88,7 @@ textarea {
|
||||
background: #f59e0b;
|
||||
color: #fff;
|
||||
|
||||
&:hover {
|
||||
&:hover:not(:disabled) {
|
||||
background: #d97706;
|
||||
}
|
||||
}
|
||||
@@ -110,7 +97,7 @@ textarea {
|
||||
background: #dc2626;
|
||||
color: #fff;
|
||||
|
||||
&:hover {
|
||||
&:hover:not(:disabled) {
|
||||
background: #b91c1c;
|
||||
}
|
||||
}
|
||||
@@ -119,37 +106,21 @@ textarea {
|
||||
background: transparent;
|
||||
color: #2563eb;
|
||||
|
||||
&:hover {
|
||||
&:hover:not(:disabled) {
|
||||
background: #eff6ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Страница авторизации
|
||||
.auth-page {
|
||||
max-width: 400px;
|
||||
margin: 4rem auto;
|
||||
padding: 2rem;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1rem;
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 0.25rem;
|
||||
font-weight: 500;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
// === Shared: Error / Loading / Empty ===
|
||||
.error {
|
||||
color: #dc2626;
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: #fef2f2;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #fecaca;
|
||||
}
|
||||
|
||||
.loading,
|
||||
@@ -158,219 +129,32 @@ textarea {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
// Навигация
|
||||
.top-nav {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.75rem 1.5rem;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
|
||||
a {
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Главная страница
|
||||
.home-page {
|
||||
max-width: 600px;
|
||||
margin: 2rem auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
|
||||
p {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Список новостей
|
||||
.news-list {
|
||||
max-width: 700px;
|
||||
margin: 2rem auto;
|
||||
padding: 1.5rem;
|
||||
|
||||
&-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.news-cards {
|
||||
list-style: none;
|
||||
|
||||
.news-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 0.5rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||
|
||||
&-title {
|
||||
flex: 1;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&-date {
|
||||
font-size: 0.8rem;
|
||||
color: #6b7280;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
font-weight: 500;
|
||||
|
||||
&-draft {
|
||||
background: #f3f4f6;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
&-scheduled {
|
||||
background: #fef3c7;
|
||||
color: #92400e;
|
||||
}
|
||||
|
||||
&-published {
|
||||
background: #d1fae5;
|
||||
color: #065f46;
|
||||
}
|
||||
}
|
||||
|
||||
// Редактор
|
||||
.news-editor {
|
||||
max-width: 800px;
|
||||
margin: 1.5rem auto;
|
||||
padding: 1.5rem;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
|
||||
|
||||
&-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
|
||||
h1 {
|
||||
margin-bottom: 0;
|
||||
font-size: 1.4rem;
|
||||
}
|
||||
}
|
||||
|
||||
&-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
|
||||
.title-input {
|
||||
font-size: 1.3rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1rem;
|
||||
border: none;
|
||||
border-bottom: 2px solid #e5e7eb;
|
||||
border-radius: 0;
|
||||
padding: 0.5rem 0;
|
||||
|
||||
&:focus {
|
||||
border-bottom-color: #2563eb;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.schedule-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
label {
|
||||
font-size: 0.9rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
input {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Markdown toolbar
|
||||
.markdown-toolbar {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
padding: 0.5rem;
|
||||
background: #f9fafb;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-bottom: none;
|
||||
border-radius: 6px 6px 0 0;
|
||||
|
||||
button {
|
||||
padding: 0.35rem 0.6rem;
|
||||
font-size: 0.9rem;
|
||||
background: transparent;
|
||||
color: #374151;
|
||||
border-radius: 4px;
|
||||
|
||||
&:hover {
|
||||
background: #e5e7eb;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.editor-textarea {
|
||||
min-height: 300px;
|
||||
resize: vertical;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||
font-size: 0.9rem;
|
||||
border-radius: 0 0 6px 6px;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
// Markdown preview
|
||||
// === Markdown body (используется в preview) ===
|
||||
.markdown-body {
|
||||
padding: 1.5rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 6px;
|
||||
background: #fafafa;
|
||||
min-height: 300px;
|
||||
|
||||
h1, h2, h3 {
|
||||
margin: 1rem 0 0.5rem;
|
||||
margin: 1.25rem 0 0.5rem;
|
||||
|
||||
&:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
p {
|
||||
margin-bottom: 0.75rem;
|
||||
margin-bottom: 0.875rem;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 4px solid #2563eb;
|
||||
padding-left: 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
margin: 1rem 0;
|
||||
color: #4b5563;
|
||||
background: #f8faff;
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
|
||||
code {
|
||||
background: #f3f4f6;
|
||||
padding: 0.15rem 0.35rem;
|
||||
padding: 0.15rem 0.4rem;
|
||||
border-radius: 3px;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
@@ -378,7 +162,7 @@ textarea {
|
||||
pre {
|
||||
background: #1f2937;
|
||||
color: #e5e7eb;
|
||||
padding: 1rem;
|
||||
padding: 1.25rem 1.5rem;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
margin: 1rem 0;
|
||||
@@ -402,12 +186,13 @@ textarea {
|
||||
|
||||
th, td {
|
||||
border: 1px solid #e5e7eb;
|
||||
padding: 0.5rem;
|
||||
padding: 0.6rem 0.75rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
th {
|
||||
background: #f9fafb;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+27
-10
@@ -7,27 +7,43 @@ import { errorHandler } from './middleware/error.middleware.js';
|
||||
import { notFoundHandler } from './middleware/notFound.middleware.js';
|
||||
import authRouter from './routes/auth.routes.js';
|
||||
import healthRouter from './routes/health.routes.js';
|
||||
import newsRouter from './routes/news.routes.js';
|
||||
import { createNewsRouter } from './routes/news.routes.js';
|
||||
import notificationRouter from './routes/notification.routes.js';
|
||||
import uploadRouter from './routes/upload.routes.js';
|
||||
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/**
|
||||
* Параметры для создания приложения.
|
||||
*/
|
||||
interface CreateAppOptions {
|
||||
/** Экземпляр Socket.IO server (передаётся в news routes для emit). */
|
||||
readonly io?: SocketIOServer;
|
||||
/** Дополнительные middleware (тесты). */
|
||||
readonly extraMiddleware?: express.RequestHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Создаёт и настраивает Express-приложение.
|
||||
*
|
||||
* Функция (а не готовый экземпляр) позволяет тестам создавать
|
||||
* независимые приложения без побочных эффектов.
|
||||
*
|
||||
* @param extraMiddleware — дополнительные middleware, подключаемые
|
||||
* после роутеров и до терминальных обработчиков (используется в тестах
|
||||
* для проверки error middleware на контролируемых путях)
|
||||
* @param options — параметры (io, extraMiddleware)
|
||||
* @returns настроенное Express-приложение
|
||||
*/
|
||||
export function createApp(extraMiddleware?: express.RequestHandler): express.Express {
|
||||
export function createApp(options?: CreateAppOptions): express.Express {
|
||||
const app = express();
|
||||
const { io, extraMiddleware } = options ?? {};
|
||||
|
||||
// /socket.io — Socket.IO (engine.io) обрабатывает на уровне HTTP server.
|
||||
// Express НЕ отвечает на эти запросы (не вызывает res.send/next).
|
||||
// Socket.IO handler (второй listener) получает те же req/res и отвечает.
|
||||
app.use('/socket.io', () => {
|
||||
// Intentionally empty — не отвечаем, Socket.IO обработает
|
||||
});
|
||||
|
||||
// Security headers
|
||||
app.use(helmet());
|
||||
|
||||
// CORS — whitelist из CLIENT_ORIGIN (поддерживается несколько через запятую)
|
||||
// CORS — whitelist из CLIENT_ORIGIN
|
||||
app.use(cors({ origin: env.clientOrigins }));
|
||||
|
||||
// Парсинг тела запроса
|
||||
@@ -41,7 +57,8 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
|
||||
// API-маршруты
|
||||
app.use('/api', healthRouter);
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/news', newsRouter);
|
||||
app.use('/api/news', createNewsRouter(io));
|
||||
app.use('/api/notifications', notificationRouter);
|
||||
app.use('/api/uploads', uploadRouter);
|
||||
|
||||
// Дополнительные middleware (тестовые маршруты, заглушки)
|
||||
|
||||
@@ -25,6 +25,11 @@ function errorMessageOf(err: unknown): string {
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- сигнатура Express требует 4 аргумента
|
||||
export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
// Если ответ уже отправлен (Socket.IO) — не дублируем
|
||||
if (res.headersSent) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ожидаемая ошибка — возвращаем её статус и код
|
||||
if (err instanceof ApiError) {
|
||||
res.status(err.status).json({ error: { code: err.code, message: err.message } });
|
||||
|
||||
@@ -8,6 +8,10 @@ import type { NextFunction, Request, Response } from 'express';
|
||||
* Вызывается после всех маршрутизаторов и передаёт ошибку 404
|
||||
* в централизованный error middleware.
|
||||
*/
|
||||
export function notFoundHandler(req: Request, _res: Response, next: NextFunction): void {
|
||||
export function notFoundHandler(req: Request, res: Response, next: NextFunction): void {
|
||||
// Если ответ уже отправлен (Socket.IO) — не дублируем
|
||||
if (res.headersSent) {
|
||||
return;
|
||||
}
|
||||
next(new ApiError(404, 'NOT_FOUND', `Маршрут не найден: ${req.method} ${req.originalUrl}`));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Schema, model, type HydratedDocument, type Types } from 'mongoose';
|
||||
|
||||
/** Тип уведомления о действиях с новостью. */
|
||||
export type NotificationType = 'news.created' | 'news.updated' | 'news.deleted' | 'news.scheduled' | 'news.published';
|
||||
|
||||
export interface INotification {
|
||||
/** Получатель уведомления. */
|
||||
user: Types.ObjectId;
|
||||
/** Кто совершил действие (может совпадать с user). */
|
||||
actor: Types.ObjectId | null;
|
||||
/** Тип события. */
|
||||
type: NotificationType;
|
||||
/** Ссылка на новость (если применимо). */
|
||||
news: Types.ObjectId | null;
|
||||
/** Заголовок уведомления. */
|
||||
title: string;
|
||||
/** Тело сообщения. */
|
||||
message: string;
|
||||
/** Прочитано ли. */
|
||||
isRead: boolean;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export type NotificationDocument = HydratedDocument<INotification>;
|
||||
|
||||
const notificationSchema = new Schema<INotification>(
|
||||
{
|
||||
user: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
required: [true, 'Получатель уведомления обязателен'],
|
||||
},
|
||||
actor: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
default: null,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['news.created', 'news.updated', 'news.deleted', 'news.scheduled', 'news.published'],
|
||||
required: [true, 'Тип уведомления обязателен'],
|
||||
},
|
||||
news: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'News',
|
||||
default: null,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
required: [true, 'Заголовок уведомления обязателен'],
|
||||
trim: true,
|
||||
},
|
||||
message: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
isRead: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: { createdAt: true, updatedAt: false },
|
||||
},
|
||||
);
|
||||
|
||||
// Индекс для быстрого поиска непрочитанных
|
||||
notificationSchema.index({ user: 1, isRead: 1, createdAt: -1 });
|
||||
|
||||
const Notification = model<INotification>('Notification', notificationSchema);
|
||||
|
||||
export default Notification;
|
||||
@@ -2,25 +2,16 @@ import { Router, type Request, type Response } from 'express';
|
||||
|
||||
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
||||
import News from '../models/news.model.js';
|
||||
import { createNotification } from '../services/notification.service.js';
|
||||
import { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
const newsRouter = Router();
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
// Сообщение об авторизации
|
||||
const AUTH_MSG = 'Требуется авторизация';
|
||||
// Сообщение о не найденной новости
|
||||
const NOT_FOUND_MSG = 'Новость не найдена';
|
||||
|
||||
// Все маршруты требуют авторизацию
|
||||
newsRouter.use(requireAuth);
|
||||
|
||||
/**
|
||||
* Возвращает id авторизованного пользователя или бросает 401.
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @returns id пользователя (string)
|
||||
*/
|
||||
/** Возвращает id авторизованного пользователя. */
|
||||
function getUserId(req: Request): string {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
@@ -30,25 +21,14 @@ function getUserId(req: Request): string {
|
||||
return authedReq.user.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Безопасно извлекает поле из req.body (any → unknown).
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @param key — имя поля
|
||||
* @returns значение поля (unknown)
|
||||
*/
|
||||
/** Безопасно извлекает поле из req.body. */
|
||||
function bodyField(req: Request, key: string): unknown {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- req.body из express
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- req.body из express typed as any
|
||||
const raw = (req.body ?? {}) as Record<string, unknown>;
|
||||
return raw[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирует Mongoose-документ новости для JSON-ответа.
|
||||
*
|
||||
* @param n — документ Mongoose
|
||||
* @returns объект с публичными полями
|
||||
*/
|
||||
/** Форматирует документ новости для JSON. */
|
||||
function serializeNews(n: InstanceType<typeof News>) {
|
||||
return {
|
||||
id: n._id,
|
||||
@@ -63,89 +43,58 @@ function serializeNews(n: InstanceType<typeof News>) {
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/news
|
||||
* Список новостей пользователя (все статусы).
|
||||
* Создаёт news router с привязкой к Socket.IO серверу.
|
||||
*
|
||||
* @returns 200 { news: [...] }
|
||||
* @param io — Socket.IO server для отправки real-time событий
|
||||
* @returns настроенный Router
|
||||
*/
|
||||
newsRouter.get(
|
||||
'/',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
/* eslint-disable max-lines-per-function -- factory-функция с 6 inline handlers (стандартный Express-паттерн) */
|
||||
export function createNewsRouter(io?: SocketIOServer): Router {
|
||||
const router = Router();
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const items = await News.find({ author: userId }).sort({ createdAt: -1 });
|
||||
|
||||
res.json({ news: items.map(serializeNews) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* GET /api/news/:id
|
||||
* Одна новость. Ownership: только свои статьи.
|
||||
*
|
||||
* @returns 200 { news: { id, title, content, status, ... } }
|
||||
*/
|
||||
newsRouter.get(
|
||||
'/:id',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.get('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
res.json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* POST /api/news
|
||||
* Создаёт новость (draft).
|
||||
*
|
||||
* @returns 201 { news: { id, title, content, status, ... } }
|
||||
*/
|
||||
newsRouter.post(
|
||||
'/',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.post('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const title = bodyField(req, 'title');
|
||||
const content = bodyField(req, 'content');
|
||||
|
||||
if (typeof title !== 'string' || title.trim().length === 0) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
|
||||
}
|
||||
if (title.trim().length > 200) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название не должно превышать 200 символов');
|
||||
}
|
||||
|
||||
const news = await News.create({
|
||||
title: title.trim(),
|
||||
content: typeof content === 'string' ? content : '',
|
||||
status: 'draft',
|
||||
author: userId,
|
||||
});
|
||||
|
||||
res.status(201).json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* PATCH /api/news/:id
|
||||
* Обновляет title и/или content. Ownership: только свои статьи.
|
||||
*
|
||||
* @returns 200 { news: { id, title, content, status, ... } }
|
||||
*/
|
||||
newsRouter.patch(
|
||||
'/:id',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
const title = bodyField(req, 'title');
|
||||
const content = bodyField(req, 'content');
|
||||
|
||||
if (title !== undefined) {
|
||||
if (typeof title !== 'string' || title.trim().length === 0) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
|
||||
@@ -155,93 +104,72 @@ newsRouter.patch(
|
||||
}
|
||||
news.title = title.trim();
|
||||
}
|
||||
|
||||
if (content !== undefined) {
|
||||
if (typeof content !== 'string') {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Контент должен быть строкой');
|
||||
}
|
||||
news.content = content;
|
||||
}
|
||||
|
||||
await news.save();
|
||||
|
||||
res.json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* DELETE /api/news/:id
|
||||
* Удаляет новость. Ownership: только свои статьи.
|
||||
*
|
||||
* @returns 204
|
||||
*/
|
||||
newsRouter.delete(
|
||||
'/:id',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
const title = news.title;
|
||||
await news.deleteOne();
|
||||
if (io) {
|
||||
await createNotification(io, {
|
||||
user: userId, actor: userId, type: 'news.deleted',
|
||||
newsId: String(req.params.id),
|
||||
title: 'Новость удалена',
|
||||
message: `«${title}» была удалена`,
|
||||
});
|
||||
}
|
||||
res.status(204).send();
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* POST /api/news/:id/publish
|
||||
* Немедленная публикация новости.
|
||||
*
|
||||
* @returns 200 { news: { id, title, content, status: 'published', ... } }
|
||||
*/
|
||||
newsRouter.post(
|
||||
'/:id/publish',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.post('/:id/publish', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
if (news.status === 'published') {
|
||||
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
|
||||
}
|
||||
|
||||
news.status = 'published';
|
||||
news.publishedAt = new Date();
|
||||
news.scheduledAt = null;
|
||||
await news.save();
|
||||
|
||||
if (io) {
|
||||
await createNotification(io, {
|
||||
user: userId, actor: userId, type: 'news.published',
|
||||
newsId: String(news._id),
|
||||
title: 'Новость опубликована',
|
||||
message: `«${news.title}» была опубликована`,
|
||||
});
|
||||
}
|
||||
res.json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* POST /api/news/:id/schedule
|
||||
* Отложенная публикация: устанавливает scheduledAt.
|
||||
*
|
||||
* @param req.body.scheduledAt — ISO-дата будущего времени
|
||||
* @returns 200 { news: { id, ..., status: 'scheduled', scheduledAt } }
|
||||
*/
|
||||
newsRouter.post(
|
||||
'/:id/schedule',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.post('/:id/schedule', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
if (news.status === 'published') {
|
||||
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
|
||||
}
|
||||
|
||||
const scheduledAtRaw = bodyField(req, 'scheduledAt');
|
||||
if (typeof scheduledAtRaw !== 'string') {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть строкой (ISO-дата)');
|
||||
}
|
||||
|
||||
const scheduledAt = new Date(scheduledAtRaw);
|
||||
if (Number.isNaN(scheduledAt.getTime())) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt не является валидной датой');
|
||||
@@ -249,14 +177,25 @@ newsRouter.post(
|
||||
if (scheduledAt.getTime() <= Date.now()) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть в будущем');
|
||||
}
|
||||
|
||||
news.status = 'scheduled';
|
||||
news.scheduledAt = scheduledAt;
|
||||
news.publishedAt = null;
|
||||
await news.save();
|
||||
|
||||
if (io) {
|
||||
await createNotification(io, {
|
||||
user: userId, actor: userId, type: 'news.scheduled',
|
||||
newsId: String(news._id),
|
||||
title: 'Публикация запланирована',
|
||||
message: `«${news.title}» запланирована на ${scheduledAt.toISOString()}`,
|
||||
});
|
||||
}
|
||||
res.json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
return router;
|
||||
}
|
||||
/* eslint-enable max-lines-per-function */
|
||||
|
||||
/** Дефолтный экспорт (без Socket.IO). */
|
||||
const newsRouter = createNewsRouter();
|
||||
export default newsRouter;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Router, type Request, type Response } from 'express';
|
||||
|
||||
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
||||
import Notification from '../models/notification.model.js';
|
||||
import { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
const notificationRouter = Router();
|
||||
|
||||
// Все маршруты требуют авторизацию
|
||||
notificationRouter.use(requireAuth);
|
||||
|
||||
/**
|
||||
* Извлекает id пользователя из авторизованного запроса.
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @returns id пользователя
|
||||
*/
|
||||
function getUserId(req: Request): string {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
if (!authedReq.user) {
|
||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
||||
}
|
||||
return authedReq.user.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирует документ уведомления для JSON.
|
||||
*
|
||||
* @param n — документ Mongoose
|
||||
* @returns объект с публичными полями
|
||||
*/
|
||||
function serializeNotification(n: InstanceType<typeof Notification>) {
|
||||
return {
|
||||
id: n._id,
|
||||
actor: n.actor,
|
||||
type: n.type,
|
||||
news: n.news,
|
||||
title: n.title,
|
||||
message: n.message,
|
||||
isRead: n.isRead,
|
||||
createdAt: n.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/notifications
|
||||
* Список уведомлений текущего пользователя (последние 50).
|
||||
*
|
||||
* @returns 200 { notifications: [...] }
|
||||
*/
|
||||
notificationRouter.get(
|
||||
'/',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const items = await Notification.find({ user: userId })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(50);
|
||||
|
||||
res.json({ notifications: items.map(serializeNotification) });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/notifications/unread-count
|
||||
* Количество непрочитанных уведомлений.
|
||||
*
|
||||
* @returns 200 { count: number }
|
||||
*/
|
||||
notificationRouter.get(
|
||||
'/unread-count',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const count = await Notification.countDocuments({ user: userId, isRead: false });
|
||||
|
||||
res.json({ count });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* PATCH /api/notifications/:id/read
|
||||
* Помечает одно уведомление как прочитанное.
|
||||
*
|
||||
* @returns 200 { notification: { ... } }
|
||||
*/
|
||||
notificationRouter.patch(
|
||||
'/:id/read',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const notification = await Notification.findOne({ _id: req.params.id, user: userId });
|
||||
if (!notification) {
|
||||
throw new ApiError(404, 'NOTIFICATION_NOT_FOUND', 'Уведомление не найдено');
|
||||
}
|
||||
|
||||
notification.isRead = true;
|
||||
await notification.save();
|
||||
|
||||
res.json({ notification: serializeNotification(notification) });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/notifications/read-all
|
||||
* Помечает все уведомления как прочитанные.
|
||||
*
|
||||
* @returns 200 { count: number } — количество помеченных
|
||||
*/
|
||||
notificationRouter.post(
|
||||
'/read-all',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const result = await Notification.updateMany(
|
||||
{ user: userId, isRead: false },
|
||||
{ $set: { isRead: true } },
|
||||
);
|
||||
|
||||
res.json({ count: result.modifiedCount });
|
||||
}),
|
||||
);
|
||||
|
||||
export default notificationRouter;
|
||||
+15
-3
@@ -4,6 +4,7 @@ import { createApp } from './app.js';
|
||||
import { connectDatabase } from './config/database.js';
|
||||
import { env } from './config/env.js';
|
||||
import { startPublicationScheduler, stopPublicationScheduler } from './services/publicationScheduler.service.js';
|
||||
import { createSocketServer } from './socket/socketServer.js';
|
||||
|
||||
/**
|
||||
* Завершает работу процесса после закрытия сервера.
|
||||
@@ -22,13 +23,24 @@ function shutdown(signal: string, server: http.Server): void {
|
||||
/**
|
||||
* Точка входа приложения.
|
||||
*
|
||||
* Подключает MongoDB и запускает HTTP-сервер на порту из env.
|
||||
* Подключает MongoDB, создаёт HTTP-сервер, Socket.IO и Express, запускает scheduler.
|
||||
*
|
||||
* Socket.IO подключается к HTTP-серверу через engine.io (перехватывает /socket.io).
|
||||
* Express не отвечает на /socket.io (middleware в app.ts) — Socket.IO обрабатывает.
|
||||
*/
|
||||
async function main(): Promise<void> {
|
||||
await connectDatabase();
|
||||
|
||||
const app = createApp();
|
||||
const server = http.createServer(app);
|
||||
// Создаём HTTP-сервер (без handler — добавим через server.on)
|
||||
const server = http.createServer();
|
||||
|
||||
// Socket.IO подключается к HTTP-серверу (engine.io перехватывает /socket.io)
|
||||
const io = createSocketServer(server);
|
||||
|
||||
// Express-приложение (с io для news routes)
|
||||
// Express НЕ отвечает на /socket.io — middleware в app.ts
|
||||
const app = createApp({ io });
|
||||
server.on('request', app);
|
||||
|
||||
// Запускаем планировщик отложенной публикации
|
||||
startPublicationScheduler(env.schedulerIntervalMs);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import Notification from '../models/notification.model.js';
|
||||
|
||||
import type { NotificationType } from '../models/notification.model.js';
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/** Параметры для создания уведомления. */
|
||||
interface CreateNotificationParams {
|
||||
/** Пользователь-получатель. */
|
||||
user: string;
|
||||
/** Пользователь-инициатор действия. */
|
||||
actor: string;
|
||||
/** Тип события. */
|
||||
type: NotificationType;
|
||||
/** Id новости (если применимо). */
|
||||
newsId?: string;
|
||||
/** Заголовок. */
|
||||
title: string;
|
||||
/** Сообщение. */
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохраняет уведомление в БД и отправляет real-time событие через Socket.IO.
|
||||
*
|
||||
* @param io — экземпляр Socket.IO server
|
||||
* @param params — данные уведомления
|
||||
* @returns сохранённое уведомление (или null, если получатель = автор — не уведомляем себя)
|
||||
*/
|
||||
export async function createNotification(
|
||||
io: SocketIOServer,
|
||||
params: CreateNotificationParams,
|
||||
): Promise<void> {
|
||||
// Не уведомляем пользователя о собственных действиях
|
||||
if (params.user === params.actor) {
|
||||
return;
|
||||
}
|
||||
|
||||
const notification = await Notification.create({
|
||||
user: params.user,
|
||||
actor: params.actor,
|
||||
type: params.type,
|
||||
news: params.newsId ?? null,
|
||||
title: params.title,
|
||||
message: params.message,
|
||||
isRead: false,
|
||||
});
|
||||
|
||||
// Отправляем real-time событие в room получателя
|
||||
io.to(`user:${params.user}`).emit('notification', {
|
||||
id: notification._id,
|
||||
type: notification.type,
|
||||
news: notification.news,
|
||||
title: notification.title,
|
||||
message: notification.message,
|
||||
isRead: false,
|
||||
createdAt: notification.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Публикует событие в room пользователя (без сохранения в БД).
|
||||
*
|
||||
* Используется для событий, которые не являются "уведомлениями"
|
||||
* в классическом смысле (например, обновление списка в реальном времени).
|
||||
*
|
||||
* @param io — экземпляр Socket.IO server
|
||||
* @param userId — получатель
|
||||
* @param event — название события
|
||||
* @param data — payload
|
||||
*/
|
||||
export function emitToUser(
|
||||
io: SocketIOServer,
|
||||
userId: string,
|
||||
event: string,
|
||||
data: unknown,
|
||||
): void {
|
||||
io.to(`user:${userId}`).emit(event, data);
|
||||
}
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Расширение типов Socket.IO для хранения userId в socket.data.
|
||||
*/
|
||||
import type { Socket } from 'socket.io';
|
||||
|
||||
declare module 'socket.io' {
|
||||
interface Socket {
|
||||
/** Id авторизованного пользователя (устанавливается middleware). */
|
||||
userId: string;
|
||||
}
|
||||
}
|
||||
|
||||
export type { Socket };
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Server } from 'socket.io';
|
||||
|
||||
import { env } from '../config/env.js';
|
||||
import { verifyUserToken } from '../utils/jwt.js';
|
||||
|
||||
import type { Server as HttpServer } from 'node:http';
|
||||
import type { Server as IOServer } from 'socket.io';
|
||||
|
||||
/**
|
||||
* Создаёт и настраивает Socket.IO сервер.
|
||||
*
|
||||
* @param httpServer — HTTP-сервер Express
|
||||
* @returns настроенный Socket.IO server
|
||||
*/
|
||||
export function createSocketServer(httpServer: HttpServer): IOServer {
|
||||
const io = new Server(httpServer, {
|
||||
cors: { origin: env.clientOrigins },
|
||||
});
|
||||
|
||||
// Middleware аутентификации: проверяем JWT из handshake.auth.token
|
||||
io.use((socket, next) => {
|
||||
// handshake.auth — any в типах socket.io, извлекаем token
|
||||
const token: unknown = socket.handshake.auth.token;
|
||||
|
||||
if (typeof token !== 'string' || token.length === 0) {
|
||||
next(new Error('UNAUTHORIZED: отсутствует токен'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const payload = verifyUserToken(token);
|
||||
// eslint-disable-next-line no-param-reassign -- socket.userId — стандартный паттерн Socket.IO
|
||||
socket.userId = payload.id;
|
||||
next();
|
||||
} catch {
|
||||
next(new Error('UNAUTHORIZED: недействительный токен'));
|
||||
}
|
||||
});
|
||||
|
||||
// При подключении — добавляем socket в room пользователя
|
||||
io.on('connection', (socket) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- socket.join fire-and-forget
|
||||
void socket.join(`user:${socket.userId}`);
|
||||
});
|
||||
|
||||
return io;
|
||||
}
|
||||
@@ -68,7 +68,7 @@ describe('API skeleton', () => {
|
||||
|
||||
describe('error middleware', () => {
|
||||
it('обрабатывает ApiError с её статусом и кодом', async () => {
|
||||
const errorApp = createApp(throwingMiddleware('/api/test-conflict', new ApiError(409, 'CONFLICT', 'Тестовый конфликт')));
|
||||
const errorApp = createApp({ extraMiddleware: throwingMiddleware('/api/test-conflict', new ApiError(409, 'CONFLICT', 'Тестовый конфликт')) });
|
||||
const res = await request(errorApp).get('/api/test-conflict');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
@@ -76,7 +76,7 @@ describe('API skeleton', () => {
|
||||
});
|
||||
|
||||
it('возвращает 500 для непредвиденных ошибок', async () => {
|
||||
const errorApp = createApp(throwingMiddleware('/api/test-unexpected', new Error('Внутренний сбой')));
|
||||
const errorApp = createApp({ extraMiddleware: throwingMiddleware('/api/test-unexpected', new Error('Внутренний сбой')) });
|
||||
const res = await request(errorApp).get('/api/test-unexpected');
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
|
||||
Reference in New Issue
Block a user