diff --git a/README.md b/README.md index dac2f65..d1f5bab 100644 --- a/README.md +++ b/README.md @@ -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 │ -└────────────────┬─────────────────┘ - │ - ▼ -┌──────────────────────────────────┐ -│ Express Backend │ -│ Auth (JWT), News CRUD, │ -│ Upload (multer), Scheduler, │ -│ Socket.IO (Phase 6) │ -└────────────────┬─────────────────┘ - │ - ▼ -┌──────────────────────────────────┐ -│ MongoDB │ -│ users, news, notifications │ -└──────────────────────────────────┘ +┌──────────────────────────────────────────┐ +│ Nginx (client) │ +│ React SPA + reverse proxy │ +│ /api → server, /socket.io → ws, │ +│ /uploads → server │ +└────────────────────┬─────────────────────┘ + │ + ▼ +┌──────────────────────────────────────────┐ +│ Express Backend │ +│ 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,43 +109,43 @@ 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 | +| Сервис | Образ | Описание | +|----------|--------------------------------|-----------------------------------| +| `mongo` | mongo:7 | MongoDB с healthcheck | +| `server` | multi-stage (node:22-alpine) | Express API + Socket.IO | +| `client` | multi-stage (nginx:alpine) | React SPA + reverse proxy | ### Запуск @@ -162,10 +166,10 @@ curl http://localhost:8080/api/health ### Переменные окружения (.env) -| Переменная | По умолчанию | Описание | -|------------|-------------|----------| -| `JWT_SECRET` | — (обязательна) | Секрет подписи JWT | -| `PORT` | `8080` | Внешний порт nginx | +| Переменная | По умолчанию | Описание | +|-----------------|----------------------|---------------------------------------------| +| `JWT_SECRET` | — (обязательна) | Секрет подписи JWT | +| `PORT` | `8080` | Внешний порт nginx | | `CLIENT_ORIGIN` | `http://localhost:8080` | CORS origin (через запятую — несколько) | ### Остановка @@ -180,68 +184,128 @@ 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 | +| Файл | Назначение | +|-----------------------|-----------------------------------------------| +| `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 | -|--------|----------------|-------------------| -| GET | `/api/health` | `{"status":"ok"}` | +| 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. Удалить статью diff --git a/client/package-lock.json b/client/package-lock.json index 4252e53..2231199 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -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": { diff --git a/client/package.json b/client/package.json index c39f707..2a56fed 100644 --- a/client/package.json +++ b/client/package.json @@ -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", diff --git a/client/src/api/types.ts b/client/src/api/types.ts index 9e7469d..7140cc1 100644 --- a/client/src/api/types.ts +++ b/client/src/api/types.ts @@ -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; +} diff --git a/client/src/components/MarkdownToolbar.tsx b/client/src/components/MarkdownToolbar.tsx index 227ad73..a64617c 100644 --- a/client/src/components/MarkdownToolbar.tsx +++ b/client/src/components/MarkdownToolbar.tsx @@ -12,7 +12,7 @@ interface MarkdownToolbarProps { */ export function MarkdownToolbar({ onAction, onImageUpload, onFileUpload }: MarkdownToolbarProps) { return ( -
+
diff --git a/client/src/components/NotificationBell.module.scss b/client/src/components/NotificationBell.module.scss new file mode 100644 index 0000000..599f642 --- /dev/null +++ b/client/src/components/NotificationBell.module.scss @@ -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; +} diff --git a/client/src/components/NotificationBell.tsx b/client/src/components/NotificationBell.tsx new file mode 100644 index 0000000..1a3015f --- /dev/null +++ b/client/src/components/NotificationBell.tsx @@ -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 ( +
  • + +
  • + ); +} + +/** + * Компонент колокольчика уведомлений. + * + * Отображает иконку с 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 ( +
    + + + {open ?
    +
    +

    Уведомления

    + {unreadCount > 0 + ? ( + + ) + : null} +
    + + {notifications.length === 0 + ?

    Нет уведомлений

    + : ( +
      + {notifications.map((n) => ( + + ))} +
    + )} +
    : null} +
    + ); +} diff --git a/client/src/hooks/useNewsEditor.ts b/client/src/hooks/useNewsEditor.ts index 442feb2..3b6fa72 100644 --- a/client/src/hooks/useNewsEditor.ts +++ b/client/src/hooks/useNewsEditor.ts @@ -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): 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): 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, }; } diff --git a/client/src/hooks/useNotifications.ts b/client/src/hooks/useNotifications.ts new file mode 100644 index 0000000..f73873b --- /dev/null +++ b/client/src/hooks/useNotifications.ts @@ -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([]); + const [unreadCount, setUnreadCount] = useState(0); + + /** Загружает список уведомлений и счётчик непрочитанных. */ + const fetchNotifications = useCallback(async (): Promise => { + 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 => { + 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 => { + 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, + }; +} diff --git a/client/src/hooks/useSocket.ts b/client/src/hooks/useSocket.ts new file mode 100644 index 0000000..32c5060 --- /dev/null +++ b/client/src/hooks/useSocket.ts @@ -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(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; +} diff --git a/client/src/pages/HomePage.module.scss b/client/src/pages/HomePage.module.scss new file mode 100644 index 0000000..dcffbcf --- /dev/null +++ b/client/src/pages/HomePage.module.scss @@ -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; + } +} diff --git a/client/src/pages/HomePage.tsx b/client/src/pages/HomePage.tsx index d40f722..492c252 100644 --- a/client/src/pages/HomePage.tsx +++ b/client/src/pages/HomePage.tsx @@ -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 ( -
    -
    +
    +

    News Editor

    +

    Добро пожаловать, {userEmail}!

    + + Перейти к новостям + +
    + ); } diff --git a/client/src/pages/LoginPage.tsx b/client/src/pages/LoginPage.tsx index c2aeb8f..ba45bfe 100644 --- a/client/src/pages/LoginPage.tsx +++ b/client/src/pages/LoginPage.tsx @@ -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 ( -
    -

    Вход

    -
    -
    +
    +

    Вход

    + +
    -
    +
    {error ?

    {error}

    : null} - -

    +

    Нет аккаунта?{' '} - Зарегистрироваться + Зарегистрироваться

    ); diff --git a/client/src/pages/NewsEditorPage.module.scss b/client/src/pages/NewsEditorPage.module.scss new file mode 100644 index 0000000..b841ece --- /dev/null +++ b/client/src/pages/NewsEditorPage.module.scss @@ -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; +} diff --git a/client/src/pages/NewsEditorPage.tsx b/client/src/pages/NewsEditorPage.tsx index 0567eb5..914f47b 100644 --- a/client/src/pages/NewsEditorPage.tsx +++ b/client/src/pages/NewsEditorPage.tsx @@ -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 ( -
    +
    + {!isNew && !isPublished + ? ( + + ) + : null} {!isNew ? ( - <> - - - + ) : null}
    @@ -52,7 +57,7 @@ function ScheduleRow({ readonly onSchedule: () => void; }) { return ( -
    +