refactor keyboard and mouse code: SVG -> div components & logical refactoring. Add some new DEV-features
Some checks failed
CI / checks (push) Failing after 6m56s

This commit is contained in:
Микаэл Оганесян
2026-04-10 02:54:32 +03:00
parent d96c152ae3
commit 84586b5ce2
35 changed files with 1315 additions and 205 deletions

160
README.md
View File

@@ -1,59 +1,149 @@
# Sparkguardian
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 21.2.6.
Клиентское веб-приложение для просмотра записанных сессий, HLS-потоков и телеметрии (клавиатура, мышь и др.), работающее поверх REST API Sparkguardian.
## Development server
A single-page web client for reviewing recorded sessions, HLS streams, and telemetry (keyboard, mouse, and more), built on top of the Sparkguardian REST API.
To start a local development server, run:
---
```bash
ng serve
```
## О проекте
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
Приложение предназначено для операторов и разработчиков, которым нужно открыть список сессий, перейти к деталям конкретной записи и синхронно смотреть видео с разбором событий на временной шкале. Бэкенд отвечает за хранение чанков, плейлистов и событий; фронтенд подставляет базовый URL API, подгружает данные и отображает их в интерфейсе на базе Taiga UI.
## Code scaffolding
## Основные возможности
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
- **Список сессий** с пагинацией и созданием новой сессии по названию.
- **Карточка сессии** с вкладками: сводная информация, просмотр записи и телеметрии, интерактивный режим с визуализацией клавиатуры и курсора поверх видео.
- **HLS-воспроизведение** через hls.js, выбор потока (например, экран или веб-камера), если бэкенд отдаёт несколько `stream_type`.
- **Телеметрия**: загрузка разобранных событий с фильтрацией по типу и времени, привязка к окну записи (`started_at` / `ended_at`).
- **Уведомления об ошибках** HTTP с понятными сообщениями для пользователя.
```bash
ng generate component component-name
```
## Технологии
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
| Область | Выбор |
|--------|--------|
| Фреймворк | Angular 21, TypeScript |
| UI | Taiga UI, анимации через `@angular/animations` |
| HTTP | `HttpClient`, интерсептор базового URL API |
| Тесты | Vitest через `@angular/build:unit-test`, jsdom |
| Линт | ESLint (`angular-eslint`) |
| Видео | hls.js |
```bash
ng generate --help
```
Стили опираются на дизайн-токены (CSS-переменные); для компонентов по возможности используются примитивы Taiga UI.
## Building
## Как устроен код
To build the project run:
- **Маршруты**: главная страница — список сессий (`/`); детали — `/sessions/:id`. Остальные пути перенаправляются на список.
- **Слой API**: `SessionsApiService` ходит на эндпоинты вида `/sessions`, `/sessions/:id/events` и т.д.; префикс API задаётся через `API_BASE_URL` (см. ниже). Относительные URL плейлистов HLS разрешаются к origin через `API_ORIGIN`.
- **Окружение**: `src/environments/environment.ts` генерируется скриптом `npm run env:sync` из переменных в `.env` (значения по умолчанию совпадают с `.env.example`). Production-сборка подменяет файл на `environment.prod.ts`.
- **Прокси в разработке**: `ng serve` использует `proxy.conf.cjs`: запросы к `/api/**` уходят на хост из `SG_DEV_PROXY_TARGET` в `.env` (по умолчанию указан в примере).
```bash
ng build
```
Подробная схема REST описана в `docs/doc_v1.json` (OpenAPI).
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
## Требования
## Running unit tests
- Node.js версии, совместимой с Angular 21 (см. рекомендации в документации Angular CLI).
- npm (в проекте зафиксирован `packageManager` в `package.json`).
To execute unit tests with the [Vitest](https://vitest.dev/) test runner, use the following command:
## Локальная настройка
```bash
ng test
```
1. Скопируйте `.env.example` в `.env` и при необходимости измените переменные (`SG_API_BASE_PATH`, `SG_API_FALLBACK_ORIGIN`, `SG_INTERACTIVE_PREROLL_MS`, для dev — `SG_DEV_PROXY_TARGET`).
2. Установите зависимости: `npm install` или `make install`.
3. Сгенерируйте `environment.ts`: `npm run env:sync` или `make env-sync` (перед `start` и `build` это выполняется автоматически через npm-скрипты `prestart` / `prebuild`).
## Running end-to-end tests
## Запуск и сборка
For end-to-end (e2e) testing, run:
| Задача | Команда |
|--------|---------|
| Dev-сервер с прокси | `npm start` или `make start` |
| Production-сборка | `npm run build` или `make build` |
| Сборка development | `make build-dev` |
| Unit-тесты | `npm test` (в режиме разработки без CI обычно удобен интерактивный режим) |
| Линт | `npm run lint` |
| Очистка артефактов | `make clean` |
```bash
ng e2e
```
После `npm start` приложение доступно по адресу, который выводит Angular CLI (по умолчанию `http://localhost:4200/`).
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## CI
## Additional Resources
В репозитории описан workflow Gitea Actions: `.gitea/workflows/ci.yml` — линт, тесты с `--watch=false`, production build. На сервере должны быть включены Actions и настроен runner.
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
## Структура каталогов (кратко)
- `src/app/core` — API, HTTP, модели, уведомления, разбор телеметрии клавиатуры/мыши, подсветка SVG.
- `src/app/features/sessions` — список сессий, детальная страница и вкладки, плеер HLS, выбор потока, детали события.
- `src/environments` — конфигурация окружения.
- `public` — статические ассеты (иконки, SVG для визуализации и т.д.).
- `scripts` — вспомогательные скрипты (`sync-env.cjs`).
---
## About the project
The app is aimed at operators and developers who need a session list, a focused session view, and a way to watch video while inspecting timed telemetry. The backend owns chunks, playlists, and events; the frontend configures the API base URL, loads data, and presents it through Taiga UI.
## Features
- **Session list** with pagination and creating a session with a title.
- **Session detail** with tabs: summary, combined playback and telemetry, and an interactive view with keyboard and cursor overlays on top of the video.
- **HLS playback** via hls.js, with stream selection when multiple `stream_type` entries exist.
- **Telemetry**: parsed events with type and time filters, aligned with the recording window (`started_at` / `ended_at`).
- **HTTP error notifications** with user-facing messages.
## Tech stack
| Area | Choice |
|------|--------|
| Framework | Angular 21, TypeScript |
| UI | Taiga UI, `@angular/animations` for motion |
| HTTP | `HttpClient`, API base URL interceptor |
| Tests | Vitest via `@angular/build:unit-test`, jsdom |
| Lint | ESLint (`angular-eslint`) |
| Video | hls.js |
Styling relies on CSS variables (design tokens); Taiga UI components are preferred where they fit.
## Architecture
- **Routes**: home is the session list (`/`); details live at `/sessions/:id`. Unknown paths redirect to the list.
- **API layer**: `SessionsApiService` calls `/sessions`, `/sessions/:id/events`, etc. The API prefix comes from `API_BASE_URL`. Relative HLS playlist URLs are resolved with `API_ORIGIN`.
- **Environment**: `src/environments/environment.ts` is generated by `npm run env:sync` from `.env` (defaults match `.env.example`). Production builds use `environment.prod.ts`.
- **Dev proxy**: `ng serve` loads `proxy.conf.cjs`: `/api/**` is forwarded to `SG_DEV_PROXY_TARGET` from `.env`.
The REST contract is summarized in `docs/doc_v1.json` (OpenAPI).
## Prerequisites
- A Node.js version compatible with Angular 21 (see Angular CLI docs).
- npm (see `packageManager` in `package.json`).
## Local setup
1. Copy `.env.example` to `.env` and adjust variables (`SG_API_BASE_PATH`, `SG_API_FALLBACK_ORIGIN`, `SG_INTERACTIVE_PREROLL_MS`, and for local dev `SG_DEV_PROXY_TARGET`).
2. Install dependencies: `npm install` or `make install`.
3. Generate `environment.ts`: `npm run env:sync` or `make env-sync` (also runs automatically before `start` / `build` via npm `prestart` / `prebuild`).
## Running and building
| Task | Command |
|------|---------|
| Dev server with proxy | `npm start` or `make start` |
| Production build | `npm run build` or `make build` |
| Development build | `make build-dev` |
| Unit tests | `npm test` |
| Lint | `npm run lint` |
| Clean artifacts | `make clean` |
After `npm start`, open the URL printed by the CLI (typically `http://localhost:4200/`).
## CI
Gitea Actions workflow: `.gitea/workflows/ci.yml` — lint, tests with `--watch=false`, production build. Actions must be enabled and a runner must be available.
## Repository layout
- `src/app/core` — API client, HTTP, models, notifications, keyboard/mouse telemetry parsing and SVG highlighting.
- `src/app/features/sessions` — session list, detail page and tabs, HLS player, stream selector, telemetry event drill-down.
- `src/environments` — environment configuration.
- `public` — static assets (fonts, SVG overlays, favicon).
- `scripts` — helpers such as `sync-env.cjs`.