nanoplayer 0.1.7 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 2.0.0 — Unreleased
4
+
5
+ - Replace the legacy UI with six scoped themes, SVG controls, responsive layout and reduced-motion support.
6
+ - Add public playback/source/quality/subtitle APIs, events, plugins and deterministic teardown.
7
+ - Add chapters, buffered timeline, optional VTT/image previews, playlist, repeat and keyboard/touch shortcuts.
8
+ - Add feature-detected fullscreen/PiP, theater mode and optional native/hls.js playback.
9
+ - Add React 18+ adapter, TypeScript declarations, ESM/UMD/CJS exports and CSS export.
10
+ - Add interactive product demo, CI, package/browser tests and publication documentation.
11
+ - Correct package license metadata to Apache-2.0, matching the unchanged LICENSE.
12
+ - Migration: legacy construction options remain supported; internal DOM/CSS is redesigned. No automatic global side effect from ESM; use UMD for window.NanoPlayer. Auto-frame poster seeking is removed to avoid interrupting playback; supply a poster.
13
+
14
+ ## 0.1.7
15
+
16
+ Original published baseline: basic HTML5 player, speed menu, volume, fullscreen and Vite ESM/UMD bundles.
package/README.md CHANGED
@@ -1,147 +1,290 @@
1
- # NanoPlayer 🎬
1
+ <div align="center">
2
+ <img src="https://capsule-render.vercel.app/api?type=waving&amp;color=0:161b33,55:6463ad,100:c1a0df&amp;height=160&amp;section=header&amp;text=NanoPlayer&amp;fontSize=46&amp;fontColor=ffffff" alt="NanoPlayer" />
2
3
 
3
- NanoPlayer — лёгкий, dependency-free HTML5 видеоплеер на чистом JavaScript
4
- с интерфейсом в стиле YouTube.
4
+ ### Small player. Big atmosphere.
5
5
 
6
- Проект создаётся как open-source и подходит как для личных,
7
- так и для коммерческих проектов.
6
+ A considered HTML5 video experience. Vanilla JavaScript at the core. React when you need it.
8
7
 
9
- ---
8
+ [![npm](https://img.shields.io/npm/v/nanoplayer?color=9699ef)](https://www.npmjs.com/package/nanoplayer)
9
+ [![License](https://img.shields.io/badge/license-Apache--2.0-b5a0df)](LICENSE)
10
+ [![Build tool](https://img.shields.io/badge/build-Vite-8c93ef)](https://vite.dev)
11
+ [![GitHub](https://img.shields.io/badge/GitHub-swiftmessage-30364e?logo=github)](https://github.com/swiftmessage/NanoPlayer)
10
12
 
11
- ## Возможности
13
+ **English** · [Русский](README.ru.md)
12
14
 
13
- - Play / Pause (кнопка и пробел)
14
- - Превью видео (poster или первый кадр автоматически)
15
- - Прогресс и перемотка
16
- - Громкость (выпадающее меню)
17
- - Скорость воспроизведения
18
- - Информация о плеере
19
- - Полноэкранный режим
20
- - Управление с клавиатуры
21
- - Кастомный UI (без native controls)
22
- - Без зависимостей
15
+ [Explore the local demo](#live-demo) · [API](#api) · [Publishing](PUBLISHING.md)
16
+ </div>
23
17
 
24
- ---
18
+ > **Release status:** this checkout is the unpublished **2.0.0** release candidate. The npm registry currently serves **0.1.7** (verified 2026-11-29). The React entry and new features below require this checkout or the eventual 2.0 release. No publication is performed automatically.
25
19
 
26
- ## Установка
20
+ ## Preview
27
21
 
28
- Через npm:
29
- ```
22
+ ![NanoPlayer playground, captured in Chromium](docs/demo-chromium.png)
23
+
24
+ ## Live demo
25
+
26
+ Run `npm install`, then `npm run dev`, and open the URL Vite prints. The product playground includes six themes, two videos, MP4/WebM source switching, captions, repeat, controls and copyable integration examples. `npm run build:demo` writes a portable site to `demo-dist/`. The manual Pages workflow deploys it after GitHub Pages is configured for Actions. No hosted demo URL is advertised until deployment succeeds.
27
+
28
+ Demo media: [MDN flower (CC0)](https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4), [Big Buck Bunny (Blender Foundation, CC BY 3.0)](https://peach.blender.org/). The landscape poster is an original SVG illustration included in `public/poster.svg`. MP4/WebM choices demonstrate source switching, not different resolutions; supply your own bitrate/resolution sources for a quality ladder.
29
+
30
+ ## Features
31
+
32
+ - Six complete themes: dark, light, midnight, ocean, purple and gold; scoped CSS variables.
33
+ - Play/pause, seek, restart, loop, playlist advance, 0.25–4× speed, configurable frame stepping.
34
+ - Buffered ranges, chapter marks and selection, time preview, optional image/VTT sprite thumbnails.
35
+ - Volume, mute and opt-in volume persistence. Native/HLS audio selection when available.
36
+ - Source quality selection, MP4/WebM, native HLS or explicitly supplied hls.js.
37
+ - WebVTT subtitles, fullscreen, Picture-in-Picture and theater mode with feature detection.
38
+ - Focus-scoped keyboard shortcuts, double click fullscreen, double tap seeking, retry UI.
39
+ - Independent instances, deterministic teardown and small cleanup-based plugins.
40
+ - ESM, CommonJS, browser UMD, TypeScript declarations and optional React 18+ adapter.
41
+
42
+ ## Installation
43
+
44
+ ```sh
45
+ # Existing public release (0.1.7, legacy API):
30
46
  npm install nanoplayer
31
- ```
32
47
 
33
- В html
34
- ```
35
- <link rel="stylesheet" href="https://unpkg.com/nanoplayer@latest/dist/nanoplayer.css">
36
- <script src="https://unpkg.com/nanoplayer@latest/dist/nanoplayer.umd.js"></script>
37
- ```
38
- Допольнительный cdn
39
- ```
40
- https://cdn.jsdelivr.net/npm/nanoplayer@latest/dist/nanoplayer.umd.js
41
- https://cdn.jsdelivr.net/npm/nanoplayer@latest/dist/nanoplayer.css
48
+ # Try this unpublished release from a local checkout:
49
+ npm install
50
+ npm pack
51
+ # In your consuming application:
52
+ npm install /absolute/path/to/nanoplayer-2.0.0.tgz
42
53
  ```
43
- ES модули
44
- ```
45
- https://cdn.jsdelivr.net/npm/nanoplayer@latest/dist/nanoplayer.es.js
46
- https://cdn.jsdelivr.net/npm/nanoplayer@latest/dist/nanoplayer.css
47
54
 
48
- https:/unpkg.com/nanoplayer@latest/dist/nanoplayer.es.js
49
- https:/unpkg.com/nanoplayer@latest/dist/nanoplayer.css
50
- ```
51
- ---
55
+ ## CDN / plain HTML
52
56
 
53
- ## Быстрый старт
57
+ The **currently published legacy** release has these pinned paths. It does not contain the 2.0 React adapter or themes:
54
58
 
55
- HTML (UMD):
59
+ ```html
60
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nanoplayer@0.1.7/dist/nanoplayer.css">
61
+ <div id="player"></div>
62
+ <script src="https://cdn.jsdelivr.net/npm/nanoplayer@0.1.7/dist/nanoplayer.umd.js"></script>
63
+ <script>new NanoPlayer('#player', { src: '/video.mp4' });</script>
56
64
  ```
57
- <link rel="stylesheet" href="dist/style.css">
58
65
 
59
- <div id="player"></div>
66
+ Legacy ESM: `https://cdn.jsdelivr.net/npm/nanoplayer@0.1.7/dist/nanoplayer.es.js`.
60
67
 
61
- <script src="dist/nanoplayer.umd.js"></script>
62
- <script>
63
- new NanoPlayer('#player', {
64
- src: 'video.mp4',
65
- poster: 'poster.jpg' // необязательно
66
- })
67
- </script>
68
+ For **this 2.0 build**, serve the output locally over HTTP:
69
+
70
+ ```html
71
+ <link rel="stylesheet" href="./dist/nanoplayer.css">
72
+ <div id="player"></div>
73
+ <script src="./dist/nanoplayer.umd.js"></script>
74
+ <script>const player = new NanoPlayer('#player', { src: '/video.mp4', theme: 'midnight' });</script>
68
75
  ```
69
- ---
70
76
 
71
- ES Modules:
77
+ Or use `<script type="module">` and `import NanoPlayer from './dist/nanoplayer.es.js'`. Both files are emitted by `npm run build`. After publishing, verify all three CDN paths before replacing the pinned legacy version; see [PUBLISHING.md](PUBLISHING.md).
78
+
79
+ ## Vanilla JavaScript
80
+
81
+ ```js
82
+ import NanoPlayer from 'nanoplayer';
83
+ import 'nanoplayer/dist/nanoplayer.css';
84
+
85
+ const player = new NanoPlayer('#player', {
86
+ src: '/video.mp4', poster: '/poster.jpg', theme: 'dark', autoplay: false
87
+ });
88
+ player.on('timeupdate', seconds => console.log(seconds));
89
+ // When the owning view is removed:
90
+ player.destroy();
72
91
  ```
73
- import NanoPlayer from 'nanoplayer'
74
- import 'nanoplayer/dist/style.css'
75
92
 
76
- new NanoPlayer('#player', {
77
- src: 'video.mp4'
78
- })
93
+ Pass a selector or an HTMLElement. Existing container children are preserved. The constructor attaches one wrapper; importing the package never touches the DOM.
94
+
95
+ ## React
96
+
97
+ React and React DOM are optional peers, never included in the core bundle. Install React in the consuming app. Import the CSS once:
98
+
99
+ ```tsx
100
+ 'use client'; // only needed at a Next.js client boundary
101
+ import { useRef } from 'react';
102
+ import { NanoPlayer } from 'nanoplayer/react';
103
+ import type Player from 'nanoplayer';
104
+ import 'nanoplayer/dist/nanoplayer.css';
105
+
106
+ export default function App() {
107
+ const ref = useRef<Player>(null);
108
+ return <NanoPlayer ref={ref} src="/video.mp4" theme="midnight"
109
+ controls autoplay={false} onPlay={() => console.log('Playing')}
110
+ onReady={player => console.log(player.video)} />;
111
+ }
79
112
  ```
80
- Важно: ES-модули должны запускаться через HTTP-сервер, не file://
81
113
 
82
- ---
114
+ The adapter updates changed options without replacing the player, reads the latest event callbacks, and cleans up on unmount and StrictMode remount. Keep arrays/objects stable with `useMemo` when possible. `useNanoPlayer(options, ref?)` returns `{ containerRef, playerRef }` for a custom host. Imports and server rendering are safe; construction occurs in an effect. `onReady` runs for every mount, including StrictMode's development remount. A ref is available after the mount effect.
83
115
 
84
- ## Параметры
116
+ ## TypeScript
85
117
 
86
- new NanoPlayer(selector, options)
118
+ ```ts
119
+ import NanoPlayer, { type Options, type Plugin } from 'nanoplayer';
120
+ const options: Options = { src: '/movie.webm', theme: 'ocean' };
121
+ const player = new NanoPlayer(document.getElementById('player')!, options);
122
+ player.on('timeupdate', seconds => seconds.toFixed(1));
123
+ ```
87
124
 
88
- options:
125
+ ## Configuration
126
+
127
+ | Option | Default | Purpose |
128
+ | --- | --- | --- |
129
+ | `src` | `''` | URL or `{ src, type?, label?, poster?, tracks? }` |
130
+ | `name`, `poster` | empty | Title (text only), poster URL |
131
+ | `theme` | `dark` | One of the six themes |
132
+ | `controls`, `autoplay`, `muted`, `loop` | true, false, false, false | Playback/UI behavior |
133
+ | `volume`, `persistVolume` | 1, false | 0–1; opt-in localStorage persistence |
134
+ | `playbackRate` | 1 | 0.25–4 |
135
+ | `playbackRates` | .25, .5, .75, 1, 1.25, 1.5, 2, 3, 4 | Speed menu |
136
+ | `seekStep`, `frameRate`, `autoHide` | 5, 30, 2500 | Seconds, estimated FPS, milliseconds |
137
+ | `sources` | [] | Labeled quality/source alternatives |
138
+ | `tracks` | [] | `{ src, label, srclang, default? }` WebVTT subtitles |
139
+ | `chapters` | [] | Ordered `{ time, title }` markers, time in seconds |
140
+ | `thumbnails` | none | VTT URL or `{ start, end, src, xywh? }[]` |
141
+ | `playlist` | [] | Sources in playback order; starts at first if `src` is empty |
142
+ | `hls` | none | Explicit hls.js constructor; never downloaded automatically |
143
+ | `plugins` | [] | Setup functions or `{ setup(player) }` objects |
144
+
145
+ `src` takes priority over `sources[0]`, then `playlist[0]`. Playlist auto-advance uses the ordered playlist and stops at the end; repeat loops the current video. Source changes preserve volume/speed; `setQuality()` also restores time and playing state after metadata. Use absolute or relative HTTP(S), blob or file media URLs; javascript/data URLs are rejected. Cross-origin subtitles, thumbnails and HLS need appropriate server CORS headers.
146
+
147
+ ### HLS, subtitles and previews
148
+
149
+ ```js
150
+ import Hls from 'hls.js'; // npm install hls.js, only if needed
151
+ new NanoPlayer('#player', {
152
+ src: '/stream.m3u8', hls: Hls,
153
+ sources: [{ src: '/720.mp4', label: '720p' }, { src: '/1080.mp4', label: '1080p' }],
154
+ tracks: [{ src: '/en.vtt', label: 'English', srclang: 'en' }],
155
+ chapters: [{ time: 0, title: 'Intro' }, { time: 60, title: 'Chapter two' }],
156
+ thumbnails: '/thumbnails.vtt'
157
+ });
158
+ ```
89
159
 
90
- - src (string) — путь к видео
91
- - poster (string | null) — превью (если не указано, берётся первый кадр)
92
- - autoplay (boolean) — автозапуск
93
- - volume (number) — громкость (0–1)
94
- - playbackRates (number[]) — доступные скорости
160
+ Thumbnail VTT cue text is an image URL, optionally followed by `#xywh=0,90,160,90`. Preview generation is never required. HLS uses native support first, then the supplied constructor. Adaptive HLS quality remains automatic; the quality menu switches explicit sources. Audio selection appears only for multiple exposed tracks.
161
+
162
+ ## API
163
+
164
+ | Method | Result / behavior |
165
+ | --- | --- |
166
+ | `play()`, `togglePlay()` | Promise; playback rejection is observable by the caller |
167
+ | `pause()` | Pause immediately |
168
+ | `seek(seconds)`, `skip(delta)` | Absolute/clamped or relative seek |
169
+ | `frame(direction = 1)` | Step by configured FPS while paused |
170
+ | `setVolume(value)`, `toggleMute()` | Volume and mute |
171
+ | `setPlaybackRate(rate)` | Clamp to 0.25–4 |
172
+ | `setSource(source, { preserveTime? })` | Replace source and dispose old HLS engine |
173
+ | `setQuality(index)` | Switch `sources[index]`, preserve position |
174
+ | `setSubtitle(index)` | Track index, or -1 for off |
175
+ | `setAudioTrack(index)` | Select exposed audio track |
176
+ | `restart()`, `retry()` | Promise; replay from start / reload current source |
177
+ | `next()` | Advance playlist; boolean indicates whether item exists |
178
+ | `enterFullscreen()`, `exitFullscreen()`, `toggleFullscreen()` | Promise; supported browser API |
179
+ | `togglePiP()` | Promise; no-op if unsupported |
180
+ | `toggleTheater()` | Toggle wide aspect ratio; return boolean |
181
+ | `updateOptions(options)` | Update options; changing source-related options reloads media |
182
+ | `on(event, fn)`, `off(event, fn)` | Subscribe/unsubscribe; chainable |
183
+ | `use(plugin)`, `removePlugin(plugin)` | Attach/cleanup; chainable |
184
+ | `destroy()` | Idempotent teardown of listeners, timers, requests, engine and wrapper |
185
+
186
+ `video`, `wrapper` and `container` expose the underlying elements. Only `destroy()` is guaranteed safe to call after destruction. `formatTime()` and `toggleFullscreen()` remain compatible with 0.1.7. Internal DOM/class structure has changed; custom legacy CSS needs migration.
187
+
188
+ ## Events
189
+
190
+ | Event | Callback argument |
191
+ | --- | --- |
192
+ | `play`, `pause`, `ended` | undefined |
193
+ | `timeupdate` | Current seconds (number) |
194
+ | `volumechange`, `ratechange` | Current volume / playback rate (number) |
195
+ | `sourcechange`, `qualitychange` | Source object |
196
+ | `subtitlechange` | Track index (-1 means off) |
197
+ | `theaterchange` | Boolean |
198
+ | `error`, `warning` | Error; thumbnail failures are nonblocking warnings |
199
+ | `loadedmetadata`, `durationchange`, `progress`, `waiting`, `playing`, `canplay`, `seeking`, `seeked` | undefined |
200
+
201
+ React supports `onPlay`, `onPause`, `onEnded`, `onTimeUpdate`, `onError`, `onVolumeChange`, `onRateChange`, `onSourceChange`, `onTheaterChange` and `onReady`. Use the instance for other events. `play()` rejection is not automatically emitted as an error for API calls; handle its Promise. Built-in buttons handle rejection in the UI.
202
+
203
+ ## Keyboard shortcuts
204
+
205
+ Shortcuts apply only inside the focused player. Text fields, selects, contenteditable and modifier-key combinations are ignored. Native button Space/Enter behavior is preserved.
206
+
207
+ | Key | Action |
208
+ | --- | --- |
209
+ | Space / K | Play/pause |
210
+ | Left / Right | Seek by configured interval (5/10/30 seconds) |
211
+ | Up / Down | Volume ±5% |
212
+ | J / L | Seek ±10 seconds |
213
+ | 0–9 | Seek to 0–90% |
214
+ | M / F / P / T / C | Mute / fullscreen / PiP / theater / subtitles |
215
+ | , / . | Previous / next approximate frame while paused |
216
+ | Escape | Close settings and return focus |
217
+
218
+ ## Themes and customization
219
+
220
+ ```css
221
+ /* Load after nanoplayer.css; custom variables override theme defaults. */
222
+ .my-player .nano-player {
223
+ --nano-primary: #a7b4ff;
224
+ --nano-secondary: #dcc298;
225
+ --nano-background: #09090f;
226
+ --nano-controls-bg: rgba(10, 10, 20, .9);
227
+ --nano-text: #f5f6ff;
228
+ --nano-muted: #b6bdd5;
229
+ --nano-border: rgba(170,180,230,.2);
230
+ --nano-radius: 16px;
231
+ }
232
+ ```
95
233
 
96
- ---
234
+ Each palette changes backgrounds, controls, text, borders and accents. Focus outlines, accessible labels, range inputs and reduced-motion styles are included. Theater mode changes the player aspect ratio; host layouts can respond to `theaterchange` to expand the container.
235
+
236
+ ## Plugins
237
+
238
+ ```js
239
+ function progressLogger() {
240
+ return player => {
241
+ const report = seconds => console.log('Watched to', seconds);
242
+ player.on('timeupdate', report);
243
+ return () => player.off('timeupdate', report);
244
+ };
245
+ }
246
+ const plugin = progressLogger();
247
+ const player = new NanoPlayer('#player', { src: '/video.mp4', plugins: [plugin] });
248
+ player.removePlugin(plugin);
249
+ ```
97
250
 
98
- ## Управление с клавиатуры
251
+ Cleanup is called on removal and destruction. Plugins own their resources; return a cleanup function. No plugin registry or global player state is required.
99
252
 
100
- - Space — Play / Pause
101
- - Esc — выход из fullscreen
253
+ ## Browser compatibility and limits
102
254
 
103
- Пробел не перехватывается, если фокус находится в input, textarea или select.
255
+ Target modern evergreen Chromium, Firefox and Safari. Actual codecs, PiP, fullscreen, audio track exposure and autoplay policy depend on the browser/device. Unsupported capability buttons are hidden. iOS uses its video fullscreen fallback where available; volume may be OS-controlled. Live streams without a finite duration disable absolute timeline seeking. Frame stepping is time-based, not decoder-frame-accurate. Native HLS and actual iOS/Safari behavior need device validation before a release. Remote demo media require network access.
104
256
 
105
- ---
257
+ ## Development / Build
106
258
 
107
- ## Стилизация
259
+ Node 22.12+ (Node 24 recommended).
108
260
 
109
- NanoPlayer не влияет на глобальные стили страницы.
110
- Все CSS-классы имеют префикс nano-.
261
+ ```sh
262
+ npm ci
263
+ npm run dev
264
+ npm run build
265
+ npm test
266
+ npm run test:types
267
+ npm run test:package
268
+ npx playwright install chromium
269
+ npm run test:e2e
270
+ npm run build:demo
271
+ npm pack --dry-run
272
+ ```
111
273
 
112
- Можно:
113
- - переопределять стили
114
- - писать собственные темы
115
- - полностью заменить style.css
274
+ Core: `src/NanoPlayer.js`; safe DOM/URL/time/VTT helpers: `src/utils.js`; icons: `src/icons.js`; scoped themes/styles: `src/style.css`; optional adapter: `src/react.js`; declarations: `types/`. Vite emits ESM/UMD/CSS and a separate React entry. `.cjs` copies preserve CommonJS use while browser UMD keeps its requested `.js` name.
116
275
 
117
- ---
276
+ ## Publishing
118
277
 
119
- ## Архитектура
278
+ Read [the Russian first-time publishing guide](PUBLISHING.md). `npm pack` builds first. `npm publish` runs validation; it is an explicit maintainer action. The optional release workflow is manual and requires an approved `npm` environment plus a configured npm trusted publisher. It never runs merely because a PR is opened.
120
279
 
121
- .nano-player
122
- ├── video
123
- ├── overlay (big play + info)
124
- ├── controls
125
- │ ├── left (play)
126
- │ ├── center (progress)
127
- │ └── right (menus)
128
- │ ├── volume
129
- │ ├── settings
130
- │ └── info
280
+ ## Contributing
131
281
 
132
- Каждое меню — отдельный popover, как в YouTube.
282
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Report browser/version, source type and reproduction steps. Do not add heavy runtime dependencies to the core.
133
283
 
134
- ---
284
+ ## License / Author
135
285
 
136
- ## Структура проекта
286
+ [Apache License 2.0](LICENSE), preserved from the original LICENSE file. The previous package.json MIT label was incorrect and has been corrected without changing the license text.
137
287
 
138
- nanoplayer/
139
- ├── src/
140
- │ ├── NanoPlayer.js
141
- │ └── index.js
142
- │ └── style.css
143
- ├── dist/
144
- │ ├── nanoplayer.umd.js
145
- │ └── nanoplayer.es.js
146
- │ └── nanoplayer.umd.js
288
+ Created by **[SWIFTMESSAGE](https://github.com/swiftmessage)** · [swiftmessage.org](https://www.swiftmessage.org)
147
289
 
290
+ <div align="center">Built for the moments worth watching.<br>✦ NanoPlayer · SwiftMessage</div>
package/README.ru.md ADDED
@@ -0,0 +1,70 @@
1
+ # NanoPlayer 2.0
2
+
3
+ [English](README.md) · **Русский**
4
+
5
+ Лёгкий HTML5-видеоплеер: шесть тем, клавиатура и сенсорное управление, WebVTT, главы, предпросмотр, качество, HLS, плагины и отдельный React-адаптер.
6
+
7
+ **Статус:** версия 2.0.0 подготовлена локально, но ещё не опубликована. В npm на 29 ноября 2026 доступна 0.1.7. Команда `npm install nanoplayer` до публикации установит старую версию без React-адаптера.
8
+
9
+ ![Демо NanoPlayer](docs/demo-chromium.png)
10
+
11
+ ## Запуск
12
+
13
+ ```sh
14
+ npm install
15
+ npm run dev
16
+ ```
17
+
18
+ ## Сборка и проверки
19
+
20
+ ```sh
21
+ npm run build
22
+ npm test
23
+ npm run test:types
24
+ npm run test:package
25
+ npx playwright install chromium
26
+ npm run test:e2e
27
+ npm run build:demo
28
+ npm pack --dry-run
29
+ ```
30
+
31
+ ## React
32
+
33
+ Сначала установите локальный архив, созданный `npm pack`, в своё приложение:
34
+
35
+ ```sh
36
+ npm install /путь/к/nanoplayer-2.0.0.tgz
37
+ ```
38
+
39
+ ```jsx
40
+ import { NanoPlayer } from 'nanoplayer/react';
41
+ import 'nanoplayer/dist/nanoplayer.css';
42
+ export default function App() {
43
+ return <NanoPlayer src="/video.mp4" theme="midnight" onPlay={() => console.log('Play')} />;
44
+ }
45
+ ```
46
+
47
+ Для Next.js используйте клиентский компонент с `'use client'`. Сам импорт SSR-safe. Доступ к экземпляру — через ref или onReady.
48
+
49
+ ## Обычный HTML
50
+
51
+ ```html
52
+ <link rel="stylesheet" href="./dist/nanoplayer.css">
53
+ <div id="player"></div>
54
+ <script src="./dist/nanoplayer.umd.js"></script>
55
+ <script>new NanoPlayer('#player', { src: '/video.mp4', theme: 'ocean' });</script>
56
+ ```
57
+
58
+ ## Управление
59
+
60
+ Space/K — воспроизведение; стрелки — время и громкость; J/L — ±10 секунд; M — звук; F — полный экран; P — PiP; T — театральный режим; C — субтитры; цифры — проценты видео; запятая/точка — приблизительный кадр. Клавиши работают только внутри выбранного плеера и не мешают вводу.
61
+
62
+ Методы: `play`, `pause`, `togglePlay`, `seek`, `skip`, `setVolume`, `setPlaybackRate`, `setSource`, `setQuality`, `setSubtitle`, `next`, `restart`, `destroy`. `destroy()` удаляет обработчики, таймеры, HLS и DOM плеера. Плагины возвращают функцию очистки.
63
+
64
+ Подробные таблицы параметров, событий, методов и примеры HLS/плагинов — в [английском README](README.md). Пошаговая публикация — [PUBLISHING.md](PUBLISHING.md).
65
+
66
+ ## Ограничения
67
+
68
+ HLS без нативной поддержки требует отдельно установленного hls.js. Для нескольких аудиодорожек браузер или HLS должен предоставлять API. Автовоспроизведение зависит от политики браузера. Покадровая перемотка рассчитывается по frameRate. Реальные Safari/iOS и HLS-потоки требуют дополнительной проверки на устройствах. Демо использует внешние видео. GitHub Pages включается вручную; несуществующую ссылку на опубликованное демо проект не обещает.
69
+
70
+ Лицензия: [Apache-2.0](LICENSE). Автор: [SWIFTMESSAGE](https://www.swiftmessage.org).
@@ -0,0 +1,126 @@
1
+ export type Theme = 'dark' | 'light' | 'midnight' | 'ocean' | 'purple' | 'gold';
2
+ export interface Track {
3
+ src: string;
4
+ label: string;
5
+ srclang: string;
6
+ default?: boolean;
7
+ }
8
+ export interface Source {
9
+ src: string;
10
+ type?: string;
11
+ label?: string;
12
+ poster?: string;
13
+ tracks?: Track[];
14
+ }
15
+ export interface Chapter {
16
+ time: number;
17
+ title: string;
18
+ }
19
+ export interface Thumbnail {
20
+ start: number;
21
+ end: number;
22
+ src: string;
23
+ xywh?: [number, number, number, number];
24
+ }
25
+ export interface HlsInstance {
26
+ attachMedia(video: HTMLVideoElement): void;
27
+ loadSource(url: string): void;
28
+ destroy(): void;
29
+ on(event: string, callback: (event: string, data: any) => void): void;
30
+ audioTracks: Array<{ name?: string; lang?: string }>;
31
+ audioTrack: number;
32
+ }
33
+ export interface HlsConstructor {
34
+ new (): HlsInstance;
35
+ isSupported(): boolean;
36
+ Events: { ERROR: string; MANIFEST_PARSED: string };
37
+ }
38
+ export type Plugin =
39
+ | ((player: NanoPlayer) => void | (() => void))
40
+ | { setup(player: NanoPlayer): void | (() => void) };
41
+ export interface Options {
42
+ src?: string | Source;
43
+ name?: string;
44
+ poster?: string | null;
45
+ theme?: Theme;
46
+ controls?: boolean;
47
+ autoplay?: boolean;
48
+ muted?: boolean;
49
+ loop?: boolean;
50
+ volume?: number;
51
+ persistVolume?: boolean;
52
+ playbackRate?: number;
53
+ playbackRates?: number[];
54
+ seekStep?: number;
55
+ frameRate?: number;
56
+ autoHide?: number;
57
+ sources?: Source[];
58
+ tracks?: Track[];
59
+ chapters?: Chapter[];
60
+ thumbnails?: Thumbnail[] | string;
61
+ playlist?: Array<Source | string>;
62
+ hls?: HlsConstructor;
63
+ plugins?: Plugin[];
64
+ }
65
+ export interface Events {
66
+ play: undefined;
67
+ pause: undefined;
68
+ ended: undefined;
69
+ timeupdate: number;
70
+ volumechange: number;
71
+ ratechange: number;
72
+ error: Error;
73
+ warning: Error;
74
+ sourcechange: Source;
75
+ qualitychange: Source;
76
+ subtitlechange: number;
77
+ theaterchange: boolean;
78
+ loadedmetadata: undefined;
79
+ durationchange: undefined;
80
+ progress: undefined;
81
+ waiting: undefined;
82
+ playing: undefined;
83
+ canplay: undefined;
84
+ seeking: undefined;
85
+ seeked: undefined;
86
+ }
87
+ export default class NanoPlayer {
88
+ constructor(target: string | HTMLElement, options?: Options);
89
+ readonly container: HTMLElement;
90
+ readonly wrapper: HTMLDivElement;
91
+ readonly video: HTMLVideoElement;
92
+ readonly options: Options;
93
+ readonly destroyed: boolean;
94
+ play(): Promise<void>;
95
+ pause(): void;
96
+ togglePlay(): Promise<void>;
97
+ seek(seconds: number): void;
98
+ skip(seconds: number): void;
99
+ frame(direction?: number): void;
100
+ setVolume(value: number): void;
101
+ setPlaybackRate(rate: number): void;
102
+ toggleMute(): void;
103
+ restart(): Promise<void>;
104
+ retry(): Promise<void>;
105
+ next(): boolean;
106
+ setSource(source: string | Source, options?: { preserveTime?: boolean }): void;
107
+ setQuality(index: number): void;
108
+ setSubtitle(index: number): void;
109
+ toggleSubtitles(): void;
110
+ setAudioTrack(index: number): void;
111
+ enterFullscreen(): Promise<void>;
112
+ exitFullscreen(): Promise<void>;
113
+ toggleFullscreen(): Promise<void>;
114
+ togglePiP(): Promise<void>;
115
+ toggleTheater(): boolean;
116
+ updateOptions(options: Partial<Options>): void;
117
+ formatTime(seconds: number): string;
118
+ on<K extends keyof Events>(event: K, callback: (payload: Events[K]) => void): this;
119
+ off<K extends keyof Events>(event: K, callback: (payload: Events[K]) => void): this;
120
+ on(event: string, callback: (payload: any) => void): this;
121
+ off(event: string, callback: (payload: any) => void): this;
122
+ emit(event: string, payload?: unknown): void;
123
+ use(plugin: Plugin): this;
124
+ removePlugin(plugin: Plugin): this;
125
+ destroy(): void;
126
+ }
@@ -1 +1 @@
1
- @import"https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&display=swap";:root{--nano-bg: #0b0d10;--nano-accent: #ffb703;--nano-accent-2: #219ebc;--nano-glow: rgba(255, 183, 3, .35);--nano-text: #f7f7f7;--nano-muted: rgba(255, 255, 255, .7);--nano-glass: rgba(12, 14, 18, .55);--nano-border: rgba(255, 255, 255, .12)}.nano-player{position:relative;max-width:720px;aspect-ratio:16 / 9;background:radial-gradient(1200px 500px at 10% 110%,rgba(33,158,188,.35),transparent 50%),radial-gradient(900px 400px at 110% -10%,rgba(255,183,3,.35),transparent 45%),var(--nano-bg);border-radius:18px;overflow:hidden;font-family:Space Grotesk,Segoe UI,Tahoma,sans-serif;box-shadow:0 10px 30px #0006,0 0 0 1px #ffffff14 inset;transform:translateZ(0)}.nano-player video{width:100%;height:100%;display:block;filter:saturate(1.05) contrast(1.02)}.nano-overlay{position:absolute;inset:0;background:radial-gradient(360px 360px at 50% 30%,rgba(255,255,255,.12),transparent 60%),#05070a99;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);transition:opacity .22s ease}.nano-overlay.hidden{display:none}.nano-big-play{width:86px;height:86px;border-radius:50%;border:1px solid rgba(255,255,255,.3);font-size:36px;cursor:pointer;color:#0b0d10;background:radial-gradient(circle at 30% 30%,#fff,#ffe8a3 60%,#ffb703);box-shadow:0 10px 24px #00000059,0 0 0 6px #ffb70326;transition:transform .16s ease,box-shadow .16s ease,filter .16s ease}.nano-big-play:hover{transform:scale(1.04);box-shadow:0 12px 30px #00000073,0 0 0 8px #ffb70333;filter:brightness(1.05)}.nano-info-overlay{color:var(--nano-text);font-size:13px;text-align:center;letter-spacing:.03em}.nano-controls{position:absolute;bottom:0;left:0;right:0;display:grid;grid-template-columns:auto 1fr auto;gap:12px;padding:10px 12px 12px;background:linear-gradient(to top,rgba(5,7,10,.95),rgba(5,7,10,.2) 65%,transparent),radial-gradient(500px 140px at 50% 120%,rgba(255,183,3,.18),transparent 60%)}.nano-left,.nano-center,.nano-right{display:flex;align-items:center;gap:6px}.nano-time{color:var(--nano-muted);font-size:12px;letter-spacing:.02em;min-width:84px}.nano-icon{background:none;border:none;color:var(--nano-text);font-size:16px;cursor:pointer;padding:6px;border-radius:8px;transition:background .16s ease,color .16s ease}.nano-icon:hover{color:var(--nano-accent);background:#ffffff14}.nano-icon:active{transform:translateY(1px)}.nano-progress{width:100%;height:7px;background:#ffffff26;cursor:pointer;border-radius:999px;overflow:hidden;position:relative}.nano-progress-fill{height:100%;background:linear-gradient(90deg,var(--nano-accent),#ffe169);width:0%;box-shadow:0 0 10px var(--nano-glow)}.nano-progress:after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,rgba(255,255,255,.25),transparent 45%,rgba(255,255,255,.2));opacity:.2}.nano-menu-wrap{position:relative}.nano-menu{position:absolute;bottom:36px;right:0;min-width:140px;background:#0a0c10e6;border-radius:10px;padding:10px;display:none;color:var(--nano-text);font-size:13px;box-shadow:0 10px 26px #00000073,0 0 0 1px #ffffff14 inset;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.nano-menu-wrap.open .nano-menu{display:block}.nano-menu button{width:100%;background:none;border:none;color:var(--nano-text);padding:6px;cursor:pointer;text-align:left;border-radius:6px;transition:background .16s ease,color .16s ease}.nano-menu button:hover{background:#ffffff14;color:var(--nano-accent)}.nano-menu input[type=range]{width:100%;accent-color:var(--nano-accent)}.nano-player.nano-fullscreen{width:100vw;height:100vh;max-width:none;border-radius:0}
1
+ .nano-player{--nano-primary: #8b9bff;--nano-secondary: #c7a4ff;--nano-background: #101321;--nano-text: #f5f6ff;--nano-muted: #b6bdd5;--nano-controls-bg: rgba(16, 19, 33, .88);--nano-border: rgba(170, 180, 230, .2);--nano-radius: 18px;position:relative;isolation:isolate;width:100%;aspect-ratio:16/9;background:var(--nano-background);color:var(--nano-text);border-radius:var(--nano-radius);overflow:hidden;font:14px/1.5 system-ui,sans-serif;box-shadow:0 24px 70px #0005,0 0 0 1px var(--nano-border)}.nano-player:where([data-theme=light]){--nano-primary: #4845bc;--nano-secondary: #78511e;--nano-background: #e9edf8;--nano-text: #171c35;--nano-muted: #3e4763;--nano-controls-bg: rgba(245, 247, 255, .95);--nano-border: #aeb8d4}.nano-player:where([data-theme=midnight]){--nano-primary: #9eacff;--nano-secondary: #72dbec;--nano-background: #060a18;--nano-controls-bg: rgba(7, 12, 31, .95);--nano-text: #e5eaff;--nano-muted: #9ba9d3;--nano-border: #293861}.nano-player:where([data-theme=ocean]){--nano-primary: #54e0e5;--nano-secondary: #8fbaff;--nano-background: #061e29;--nano-controls-bg: rgba(5, 34, 46, .92);--nano-text: #e2fcff;--nano-muted: #96cbd5;--nano-border: #245163}.nano-player:where([data-theme=purple]){--nano-primary: #d4acff;--nano-secondary: #ffb4df;--nano-background: #21102e;--nano-controls-bg: rgba(37, 16, 51, .92);--nano-text: #f8edff;--nano-muted: #cfb5e0;--nano-border: #623c73}.nano-player:where([data-theme=gold]){--nano-primary: #f3d68a;--nano-secondary: #f6b68b;--nano-background: #211c12;--nano-controls-bg: rgba(36, 29, 15, .94);--nano-text: #fff5df;--nano-muted: #d5c49c;--nano-border: #65542e}.nano-player *{box-sizing:border-box}.nano-player [hidden]{display:none!important}.nano-player video{width:100%;height:100%;display:block;object-fit:contain}.nano-player button,.nano-player select,.nano-player input{font:inherit}.nano-player button{cursor:pointer}.nano-player :focus-visible{outline:2px solid var(--nano-primary);outline-offset:3px}.nano-player svg{width:21px;height:21px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;pointer-events:none}.nano-title{position:absolute;top:0;left:0;right:0;padding:24px;background:linear-gradient(#0009,transparent);color:#fff;font-weight:600;letter-spacing:.02em;pointer-events:none;transition:opacity .25s}.nano-title:empty{display:none}.nano-big-play{position:absolute!important;left:50%;top:50%;width:80px!important;height:80px!important;transform:translate(-50%,-50%);border-radius:50%!important;color:var(--nano-primary)!important;background:var(--nano-controls-bg)!important;border:1px solid var(--nano-border)!important;box-shadow:0 0 0 10px #ffffff0a,0 12px 36px #0005;-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px);transition:opacity .25s,scale .25s!important}.nano-big-play svg{width:30px;height:30px;fill:currentColor;stroke-width:1}.nano-big-play:hover{scale:1.07}.is-playing .nano-big-play{opacity:0;pointer-events:none;scale:.85}.nano-controls{position:absolute;bottom:0;left:0;right:0;padding:35px 18px 12px;background:linear-gradient(transparent,var(--nano-controls-bg) 45%);transition:opacity .25s,transform .25s}.is-idle.is-playing .nano-controls{opacity:0;transform:translateY(12px);pointer-events:none}.is-idle.is-playing .nano-title{opacity:0}.nano-controls:focus-within{opacity:1!important;transform:none!important;pointer-events:auto!important}.nano-row,.nano-left,.nano-right{display:flex;align-items:center;gap:5px}.nano-row{justify-content:space-between;gap:8px}.nano-icon{display:inline-flex;flex-shrink:0;align-items:center;justify-content:center;width:40px;height:40px;border:0;border-radius:10px;background:transparent;color:var(--nano-text);transition:background .18s,color .18s,scale .18s}.nano-icon:hover{color:var(--nano-primary);background:var(--nano-border)}.nano-icon:active{scale:.94}.nano-time{font-variant-numeric:tabular-nums;font-size:12px;white-space:nowrap;color:var(--nano-muted);padding:0 8px}.nano-volume{width:65px;accent-color:var(--nano-primary);height:24px}.nano-timeline{position:relative;height:24px;margin-bottom:6px;display:flex;align-items:center}.nano-progress{appearance:none;width:100%;margin:0;height:5px;cursor:pointer;border-radius:8px;background:linear-gradient(to right,var(--nano-primary) 0%,var(--nano-secondary) var(--progress, 0%),transparent var(--progress, 0%));z-index:2;position:relative;touch-action:pan-y}.nano-progress::-webkit-slider-thumb{appearance:none;width:12px;height:12px;background:var(--nano-primary);border:2px solid var(--nano-text);border-radius:50%;box-shadow:0 0 12px #0005}.nano-progress::-moz-range-thumb{width:10px;height:10px;background:var(--nano-primary);border:2px solid var(--nano-text);border-radius:50%}.nano-buffered{position:absolute;height:5px;left:0;right:0;border-radius:8px;overflow:hidden;background:var(--nano-border)}.nano-buffered span{position:absolute;height:100%;background:#aab6cf66}.nano-chapters{position:absolute;inset:9px 0;pointer-events:none;z-index:3}.nano-chapters span{position:absolute;width:2px;height:6px;background:var(--nano-background)}.nano-preview{position:absolute;bottom:30px;transform:translate(-50%);padding:6px;border-radius:9px;background:var(--nano-controls-bg);border:1px solid var(--nano-border);box-shadow:0 5px 25px #0005;text-align:center;max-width:240px;pointer-events:none}.nano-preview span{display:block;font-size:12px;white-space:nowrap}.nano-preview-image{border-radius:5px;margin-bottom:5px;background-repeat:no-repeat;max-width:220px;max-height:140px}.nano-settings{position:absolute;right:16px;bottom:76px;width:260px;max-width:calc(100% - 32px);max-height:calc(100cqh - 100px);overflow:auto;padding:14px;border-radius:14px;border:1px solid var(--nano-border);background:var(--nano-controls-bg);-webkit-backdrop-filter:blur(24px);backdrop-filter:blur(24px);box-shadow:0 15px 50px #0006;z-index:5}.nano-player{container-type:size}.nano-settings label{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:8px 0;font-size:13px}.nano-settings select{max-width:140px;min-width:85px;color:var(--nano-text);background:var(--nano-background);border:1px solid var(--nano-border);padding:7px;border-radius:7px}.nano-settings input{accent-color:var(--nano-primary)}.nano-spinner{display:none;position:absolute;top:50%;left:50%;width:38px;height:38px;border:3px solid #ffffff40;border-top-color:var(--nano-primary);border-radius:50%;margin:-19px;animation:nano-spin .8s linear infinite;pointer-events:none}.is-loading .nano-spinner{display:block}.is-loading .nano-big-play,.has-error .nano-big-play{opacity:0;pointer-events:none}.nano-feedback{position:absolute;top:35%;left:50%;transform:translate(-50%);padding:10px 18px;background:var(--nano-controls-bg);border-radius:24px;opacity:0;transition:opacity .15s;pointer-events:none}.nano-feedback.visible{opacity:1}.nano-error{position:absolute;inset:0 0 90px;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:24px;text-align:center;background:var(--nano-background)}.nano-error p{max-width:400px}.nano-theater{aspect-ratio:21/9}.nano-player:fullscreen,.nano-fullscreen{width:100%;height:100%;aspect-ratio:auto;border-radius:0}.nano-player:fullscreen .nano-settings{max-height:70vh}@keyframes nano-spin{to{transform:rotate(360deg)}}@media(max-width:600px){.nano-controls{padding:24px 8px 6px}.nano-icon{width:34px;height:38px}.nano-left,.nano-right{gap:0}.nano-volume{display:none}.nano-time{font-size:11px;padding:0 4px}.nano-title{padding:14px;font-size:12px}.nano-big-play{width:62px!important;height:62px!important}.nano-settings{bottom:65px;padding:8px 12px}.nano-left>.nano-icon:nth-child(2){display:none}}@media(prefers-reduced-motion:reduce){.nano-player *{transition:none!important;animation:none!important}}.nano-controls{pointer-events:none}.nano-controls>.nano-row,.nano-controls>.nano-timeline,.nano-controls>.nano-settings{pointer-events:auto}.is-idle.is-playing .nano-controls:not(:focus-within)>*{pointer-events:none}