nanoplayer 0.1.6 → 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.
@@ -1,95 +1,488 @@
1
- class l {
2
- constructor(e, t = {}) {
3
- if (this.container = document.querySelector(e), !this.container)
4
- throw new Error("NanoPlayer: container not found");
5
- this.options = {
6
- src: "",
7
- poster: null,
8
- autoplay: !1,
9
- volume: 1,
10
- playbackRates: [0.5, 1, 1.5, 2],
11
- ...t
12
- }, this.init();
13
- }
14
- /* ================= INIT ================= */
15
- init() {
16
- this.wrapper = document.createElement("div"), this.wrapper.className = "nano-player", this.wrapper.tabIndex = 0, this.video = document.createElement("video"), this.video.src = this.options.src, this.video.autoplay = this.options.autoplay, this.video.volume = this.options.volume, this.video.preload = "metadata", this.video.controls = !1, this.options.poster && (this.video.poster = this.options.poster), this.wrapper.appendChild(this.video), this.container.appendChild(this.wrapper), this.createOverlay(), this.createControls(), this.bindEvents();
17
- }
18
- /* ================= OVERLAY ================= */
19
- createOverlay() {
20
- this.overlay = document.createElement("div"), this.overlay.className = "nano-overlay", this.bigPlay = document.createElement("button"), this.bigPlay.className = "nano-big-play", this.bigPlay.textContent = "▶", this.infoOverlay = document.createElement("div"), this.infoOverlay.className = "nano-info-overlay", this.infoOverlay.textContent = "", this.overlay.append(this.bigPlay, this.infoOverlay), this.wrapper.appendChild(this.overlay), this.bigPlay.onclick = () => this.video.play();
21
- }
22
- /* ================= CONTROLS ================= */
23
- createControls() {
24
- this.controls = document.createElement("div"), this.controls.className = "nano-controls", this.left = document.createElement("div"), this.left.className = "nano-left", this.playBtn = document.createElement("button"), this.playBtn.className = "nano-icon", this.playBtn.textContent = "▶", this.left.appendChild(this.playBtn), this.center = document.createElement("div"), this.center.className = "nano-center", this.progress = document.createElement("div"), this.progress.className = "nano-progress", this.progressFill = document.createElement("div"), this.progressFill.className = "nano-progress-fill", this.progress.appendChild(this.progressFill), this.center.appendChild(this.progress), this.right = document.createElement("div"), this.right.className = "nano-right", this.volumeMenu = this.createMenu("🔊"), this.volumeSlider = document.createElement("input"), this.volumeSlider.type = "range", this.volumeSlider.min = 0, this.volumeSlider.max = 1, this.volumeSlider.step = 0.01, this.volumeSlider.value = this.video.volume, this.volumeMenu.menu.appendChild(this.volumeSlider), this.settingsMenu = this.createMenu("⚙️"), this.options.playbackRates.forEach((e) => {
25
- const t = document.createElement("button");
26
- t.textContent = `${e}x`, t.onclick = () => {
27
- this.video.playbackRate = e, this.settingsMenu.close();
28
- }, this.settingsMenu.menu.appendChild(t);
29
- }), this.infoMenu = this.createMenu("ℹ️"), this.infoMenu.menu.innerHTML = `
30
- <strong>NanoPlayer</strong><br>
31
- Version 0.1.4<br>
32
- MIT License
33
- swiftmessage.org
34
- github.com/swiftmessage/NanoPlayer
35
- `, this.fullscreenBtn = document.createElement("button"), this.fullscreenBtn.className = "nano-icon", this.fullscreenBtn.textContent = "⛶", this.fullscreenBtn.onclick = () => this.toggleFullscreen(), this.right.append(
36
- this.volumeMenu.root,
37
- this.settingsMenu.root,
38
- this.infoMenu.root,
1
+ const d = (h, t, e) => Math.min(e, Math.max(t, Number(h) || 0));
2
+ function c(h) {
3
+ const t = Math.max(0, Math.floor(h || 0));
4
+ return t >= 3600 ? `${Math.floor(t / 3600)}:${String(Math.floor(t / 60) % 60).padStart(2, "0")}:${String(t % 60).padStart(2, "0")}` : `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;
5
+ }
6
+ function u(h) {
7
+ if (!h) return "";
8
+ const t = new URL(h, document.baseURI);
9
+ if (!["http:", "https:", "blob:", "file:"].includes(t.protocol))
10
+ throw new TypeError("Unsupported media URL protocol");
11
+ return t.href;
12
+ }
13
+ function n(h, t, e) {
14
+ const i = document.createElement(h);
15
+ return t && (i.className = t), e !== void 0 && (i.textContent = e), i;
16
+ }
17
+ function y(h, t) {
18
+ const e = (i) => i.split(":").reduce((s, r) => s * 60 + Number(r), 0);
19
+ return h.replace(/\r/g, "").split(/\n\s*\n/).flatMap((i) => {
20
+ const s = i.split(`
21
+ `), r = s.findIndex((o) => o.includes(" --> "));
22
+ if (r < 0 || !s[r + 1]) return [];
23
+ const [l, a] = s[r].split(" --> ").map((o) => e(o.trim().split(/\s/)[0])), [p, g] = s[r + 1].trim().split("#xywh=");
24
+ return Number.isFinite(l + a) ? [{ start: l, end: a, src: new URL(p, t).href, xywh: g?.split(",").map(Number) }] : [];
25
+ });
26
+ }
27
+ const v = {
28
+ play: "M9 5 20 12 9 19Z",
29
+ pause: "M8 5v14M16 5v14",
30
+ volume: "M11 5 6 9H3v6h3l5 4ZM15 8q5 4 0 8M18 5q8 7 0 14",
31
+ mute: "M11 5 6 9H3v6h3l5 4ZM16 9l6 6m0-6-6 6",
32
+ settings: "M4 7h16M4 17h16M9 4v6M15 14v6",
33
+ fullscreen: "M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5",
34
+ pip: "M3 4h18v16H3ZM12 11h7v7h-7Z",
35
+ theater: "M3 6h18v12H3Z",
36
+ restart: "M4 10a8 8 0 1 1 1 8M4 4v6h6",
37
+ back: "M11 6 3 12l8 6ZM21 6l-8 6 8 6Z",
38
+ next: "m3 6 8 6-8 6Zm10 0 8 6-8 6Z",
39
+ captions: "M3 5h18v14H3ZM10 9H7v6h3m8-6h-3v6h3"
40
+ };
41
+ function m(h) {
42
+ const t = document.createElementNS("http://www.w3.org/2000/svg", "svg");
43
+ t.setAttribute("viewBox", "0 0 24 24"), t.setAttribute("aria-hidden", "true");
44
+ const e = document.createElementNS(t.namespaceURI, "path");
45
+ return e.setAttribute("d", v[h] || v.play), t.append(e), t;
46
+ }
47
+ const b = {
48
+ src: "",
49
+ name: "",
50
+ theme: "dark",
51
+ controls: !0,
52
+ volume: 1,
53
+ playbackRate: 1,
54
+ seekStep: 5,
55
+ frameRate: 30,
56
+ autoHide: 2500,
57
+ playbackRates: [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4]
58
+ };
59
+ class k {
60
+ constructor(t, e = {}) {
61
+ if (this.container = typeof t == "string" ? document.querySelector(t) : t, !this.container) throw new Error("NanoPlayer: container not found");
62
+ this.options = { ...b, ...e }, this.listeners = [], this.events = /* @__PURE__ */ new Map(), this.plugins = /* @__PURE__ */ new Map(), this.sourceId = 0, this.playlistIndex = 0, this.wrapper = n("div", "nano-player"), this.wrapper.tabIndex = 0, this.wrapper.setAttribute("role", "region"), this.wrapper.setAttribute("aria-label", e.name || "Video player"), this.video = n("video"), this.video.playsInline = !0, this.video.preload = "metadata", this.wrapper.append(this.video), this.container.append(this.wrapper), this.buildUI(), this.bindEvents();
63
+ try {
64
+ this.updateOptions(this.options), (e.plugins || []).forEach((i) => this.use(i));
65
+ } catch (i) {
66
+ throw this.destroy(), i;
67
+ }
68
+ }
69
+ listen(t, e, i, s) {
70
+ t.addEventListener(e, i, s), this.listeners.push(() => t.removeEventListener(e, i, s));
71
+ }
72
+ button(t, e, i) {
73
+ const s = n("button", "nano-icon");
74
+ return s.type = "button", s.title = t, s.setAttribute("aria-label", t), s.append(m(e)), this.listen(s, "click", () => {
75
+ Promise.resolve().then(i).catch((r) => this.showError(r));
76
+ }), s;
77
+ }
78
+ buildUI() {
79
+ this.title = n("div", "nano-title"), this.bigPlay = this.button("Play video", "play", () => this.play()), this.bigPlay.classList.add("nano-big-play"), this.spinner = n("div", "nano-spinner"), this.spinner.setAttribute("aria-label", "Buffering"), this.feedback = n("div", "nano-feedback"), this.feedback.setAttribute("aria-live", "polite"), this.errorBox = n("div", "nano-error"), this.errorBox.hidden = !0, this.errorBox.setAttribute("role", "alert"), this.errorText = n("p"), this.errorBox.append(
80
+ this.errorText,
81
+ this.button("Retry playback", "restart", () => this.retry())
82
+ ), this.controls = n("div", "nano-controls"), this.timeline = n("div", "nano-timeline"), this.buffered = n("div", "nano-buffered"), this.markers = n("div", "nano-chapters"), this.progress = n("input", "nano-progress"), Object.assign(this.progress, { type: "range", min: "0", max: "1000", step: "1", value: "0" }), this.progress.setAttribute("aria-label", "Seek"), this.preview = n("div", "nano-preview"), this.preview.hidden = !0, this.previewImage = n("div", "nano-preview-image"), this.previewTime = n("span"), this.preview.append(this.previewImage, this.previewTime), this.timeline.append(this.buffered, this.markers, this.progress, this.preview);
83
+ const t = n("div", "nano-row"), e = n("div", "nano-left"), i = n("div", "nano-right");
84
+ this.playBtn = this.button("Play", "play", () => this.togglePlay()), this.muteBtn = this.button("Mute", "volume", () => this.toggleMute()), this.volumeSlider = n("input", "nano-volume"), Object.assign(this.volumeSlider, { type: "range", min: "0", max: "1", step: ".01" }), this.volumeSlider.setAttribute("aria-label", "Volume"), this.timeDisplay = n("span", "nano-time", "0:00 / 0:00"), e.append(
85
+ this.playBtn,
86
+ this.button("Back 10 seconds", "back", () => this.skip(-10)),
87
+ this.muteBtn,
88
+ this.volumeSlider,
89
+ this.timeDisplay
90
+ ), this.settingsBtn = this.button("Settings", "settings", () => this.toggleSettings()), this.settingsBtn.setAttribute("aria-expanded", "false"), this.settings = n("div", "nano-settings"), this.settings.hidden = !0, this.speedSelect = this.select("Playback speed", (r) => this.setPlaybackRate(r)), this.qualitySelect = this.select("Quality", (r) => this.setQuality(Number(r))), this.captionSelect = this.select("Subtitles", (r) => this.setSubtitle(Number(r))), this.audioSelect = this.select("Audio track", (r) => this.setAudioTrack(Number(r))), this.chapterSelect = this.select("Chapter", (r) => this.seek(Number(r))), this.skipSelect = this.select("Seek interval", (r) => {
91
+ this.options.seekStep = Number(r);
92
+ }), this.fillSelect(
93
+ this.skipSelect,
94
+ [5, 10, 30].map((r) => [r, `${r} seconds`])
95
+ ), this.loopInput = n("input"), this.loopInput.type = "checkbox";
96
+ const s = n("label", "", "Repeat video");
97
+ s.append(this.loopInput), this.settings.append(s), this.listen(this.loopInput, "change", () => {
98
+ this.video.loop = this.loopInput.checked;
99
+ }), this.settings.append(this.button("Restart video", "restart", () => this.restart())), this.captionBtn = this.button("Toggle subtitles", "captions", () => this.toggleSubtitles()), this.pipBtn = this.button("Picture in picture", "pip", () => this.togglePiP()), this.fullscreenBtn = this.button("Fullscreen", "fullscreen", () => this.toggleFullscreen()), i.append(
100
+ this.captionBtn,
101
+ this.settingsBtn,
102
+ this.button("Theater mode", "theater", () => this.toggleTheater()),
103
+ this.pipBtn,
39
104
  this.fullscreenBtn
40
- ), this.controls.append(this.left, this.center, this.right), this.wrapper.appendChild(this.controls), this.playBtn.onclick = () => this.video.paused ? this.video.play() : this.video.pause(), this.progress.onclick = (e) => {
41
- const t = this.progress.getBoundingClientRect();
42
- this.video.currentTime = (e.clientX - t.left) / t.width * this.video.duration;
43
- }, this.volumeSlider.oninput = () => this.video.volume = this.volumeSlider.value;
44
- }
45
- /* ================= MENU HELPER ================= */
46
- createMenu(e) {
47
- const t = document.createElement("div");
48
- t.className = "nano-menu-wrap";
49
- const s = document.createElement("button");
50
- s.className = "nano-icon", s.textContent = e;
51
- const i = document.createElement("div");
52
- return i.className = "nano-menu", s.onclick = (n) => {
53
- n.stopPropagation(), document.querySelectorAll(".nano-menu-wrap.open").forEach((o) => o.classList.remove("open")), t.classList.toggle("open");
54
- }, document.addEventListener("click", () => {
55
- t.classList.remove("open");
56
- }), t.append(s, i), {
57
- root: t,
58
- menu: i,
59
- close: () => t.classList.remove("open")
60
- };
105
+ ), t.append(e, i), this.controls.append(this.timeline, t, this.settings), this.wrapper.append(
106
+ this.title,
107
+ this.bigPlay,
108
+ this.spinner,
109
+ this.feedback,
110
+ this.errorBox,
111
+ this.controls
112
+ ), this.pipBtn.hidden = !document.pictureInPictureEnabled || !this.video.requestPictureInPicture, this.fullscreenBtn.hidden = !(this.wrapper.requestFullscreen && document.fullscreenEnabled !== !1) && !this.video.webkitEnterFullscreen;
113
+ }
114
+ select(t, e) {
115
+ const i = n("label", "", t), s = n("select");
116
+ return s.setAttribute("aria-label", t), i.append(s), this.settings.append(i), this.listen(s, "change", () => {
117
+ try {
118
+ e(s.value);
119
+ } catch (r) {
120
+ this.showError(r);
121
+ }
122
+ }), s;
123
+ }
124
+ fillSelect(t, e) {
125
+ t.replaceChildren(
126
+ ...e.map(([i, s]) => {
127
+ const r = n("option", "", s);
128
+ return r.value = String(i), r;
129
+ })
130
+ );
61
131
  }
62
- /* ================= EVENTS ================= */
63
132
  bindEvents() {
64
- this.wrapper.addEventListener("click", () => {
65
- this.wrapper.focus();
66
- }), this.video.addEventListener("loadedmetadata", () => {
67
- this.options.poster || (this.video.currentTime = 0.1, this.video.pause());
68
- }), this.video.addEventListener("play", () => {
69
- this.playBtn.textContent = "❚❚", this.overlay.classList.add("hidden");
70
- }), this.video.addEventListener("pause", () => {
71
- this.playBtn.textContent = "▶";
72
- }), this.video.addEventListener("timeupdate", () => {
73
- const e = this.video.currentTime / this.video.duration * 100;
74
- this.progressFill.style.width = `${e}%`;
75
- }), this.wrapper.addEventListener("keydown", (e) => {
76
- if (e.code !== "Space") return;
77
- const t = e.target.tagName;
78
- ["INPUT", "TEXTAREA", "SELECT"].includes(t) || (e.preventDefault(), this.video.paused ? this.video.play() : this.video.pause());
79
- }), document.addEventListener("fullscreenchange", () => {
80
- this.wrapper.classList.toggle(
81
- "nano-fullscreen",
82
- !!document.fullscreenElement
83
- );
84
- });
85
- }
86
- /* ================= FULLSCREEN ================= */
87
- toggleFullscreen() {
88
- const e = this.wrapper;
89
- document.fullscreenElement ? document.exitFullscreen ? document.exitFullscreen() : document.webkitExitFullscreen ? document.webkitExitFullscreen() : document.msExitFullscreen && document.msExitFullscreen() : e.requestFullscreen ? e.requestFullscreen() : e.webkitRequestFullscreen ? e.webkitRequestFullscreen() : e.msRequestFullscreen && e.msRequestFullscreen();
133
+ const t = this.video;
134
+ for (const e of [
135
+ "play",
136
+ "pause",
137
+ "ended",
138
+ "timeupdate",
139
+ "volumechange",
140
+ "ratechange",
141
+ "loadedmetadata",
142
+ "durationchange",
143
+ "progress",
144
+ "waiting",
145
+ "playing",
146
+ "canplay",
147
+ "seeking",
148
+ "seeked"
149
+ ])
150
+ this.listen(t, e, () => {
151
+ if (this.wrapper.classList.toggle("is-playing", !t.paused && !t.ended), ["waiting", "seeking"].includes(e) && this.wrapper.classList.add("is-loading"), ["playing", "canplay", "seeked", "pause", "ended"].includes(e) && this.wrapper.classList.remove("is-loading"), this.playBtn.replaceChildren(m(t.paused ? "play" : "pause")), this.playBtn.setAttribute("aria-label", t.paused ? "Play" : "Pause"), this.bigPlay.tabIndex = t.paused ? 0 : -1, this.bigPlay.setAttribute("aria-hidden", String(!t.paused)), this.volumeSlider.value = String(t.muted ? 0 : t.volume), this.muteBtn.replaceChildren(m(t.muted || !t.volume ? "mute" : "volume")), this.muteBtn.setAttribute("aria-label", t.muted ? "Unmute" : "Mute"), this.speedSelect.value = String(t.playbackRate), this.updateTime(), e === "volumechange" && this.options.persistVolume)
152
+ try {
153
+ localStorage.setItem("nanoplayer-volume", String(t.volume));
154
+ } catch {
155
+ }
156
+ e === "play" && (this.wake(), this.animateProgress()), e === "playing" && (this.errorBox.hidden = !0, this.wrapper.classList.remove("has-error")), (e === "pause" || e === "ended") && cancelAnimationFrame(this.animationFrame), e === "loadedmetadata" && this.refreshAudio(), this.emit(
157
+ e,
158
+ e === "timeupdate" ? t.currentTime : e === "volumechange" ? t.volume : e === "ratechange" ? t.playbackRate : void 0
159
+ ), e === "ended" && (this.announce("Playback complete"), t.loop || this.next());
160
+ });
161
+ this.listen(
162
+ t,
163
+ "error",
164
+ () => this.showError(
165
+ new Error(
166
+ t.error?.message || "This video could not be played. Check the source or try again."
167
+ )
168
+ )
169
+ ), this.listen(
170
+ this.progress,
171
+ "input",
172
+ () => this.seek(Number(this.progress.value) / 1e3 * (t.duration || 0))
173
+ ), this.listen(this.volumeSlider, "input", () => {
174
+ t.muted = !1, this.setVolume(this.volumeSlider.value);
175
+ }), this.listen(this.timeline, "pointermove", (e) => this.showPreview(e)), this.listen(this.timeline, "pointerleave", () => {
176
+ this.preview.hidden = !0;
177
+ }), this.listen(this.wrapper, "pointermove", () => this.wake()), this.listen(this.wrapper, "focusin", () => this.wake()), this.listen(this.wrapper, "keydown", (e) => this.handleKey(e)), this.listen(t, "click", (e) => {
178
+ this.touchUntil > Date.now() || (this.wrapper.focus(), e.detail === 1 && (clearTimeout(this.clickTimer), this.clickTimer = setTimeout(
179
+ () => this.togglePlay().catch((i) => this.showError(i)),
180
+ 230
181
+ )));
182
+ }), this.listen(t, "dblclick", () => {
183
+ clearTimeout(this.clickTimer), this.toggleFullscreen().catch((e) => this.showError(e));
184
+ }), this.listen(t, "pointerup", (e) => {
185
+ if (e.pointerType !== "touch") return;
186
+ this.touchUntil = Date.now() + 500;
187
+ const i = t.getBoundingClientRect(), s = e.clientX - i.left < i.width / 2 ? -1 : 1;
188
+ this.lastTap && Date.now() - this.lastTap.time < 320 && this.lastTap.side === s ? (this.skip(s * 10), this.lastTap = null) : (this.lastTap = { time: Date.now(), side: s }, this.wake());
189
+ }), this.listen(document, "pointerdown", (e) => {
190
+ !this.settings.contains(e.target) && !this.settingsBtn.contains(e.target) && this.closeSettings();
191
+ }), this.listen(
192
+ document,
193
+ "fullscreenchange",
194
+ () => this.wrapper.classList.toggle("nano-fullscreen", document.fullscreenElement === this.wrapper)
195
+ );
196
+ }
197
+ handleKey(t) {
198
+ if (t.altKey || t.ctrlKey || t.metaKey || t.target.closest('input,textarea,select,[contenteditable="true"]') || t.target.closest("button") && [" ", "Enter"].includes(t.key)) return;
199
+ const e = {
200
+ " ": () => this.togglePlay(),
201
+ k: () => this.togglePlay(),
202
+ ArrowLeft: () => this.skip(-this.options.seekStep),
203
+ ArrowRight: () => this.skip(this.options.seekStep),
204
+ ArrowUp: () => this.setVolume(this.video.volume + 0.05),
205
+ ArrowDown: () => this.setVolume(this.video.volume - 0.05),
206
+ m: () => this.toggleMute(),
207
+ f: () => this.toggleFullscreen(),
208
+ p: () => this.togglePiP(),
209
+ t: () => this.toggleTheater(),
210
+ j: () => this.skip(-10),
211
+ l: () => this.skip(10),
212
+ c: () => this.toggleSubtitles(),
213
+ ",": () => this.frame(-1),
214
+ ".": () => this.frame(1),
215
+ Escape: () => {
216
+ this.closeSettings(), this.settingsBtn.focus();
217
+ }
218
+ }, i = /^\d$/.test(t.key) ? () => this.seek(this.video.duration * Number(t.key) / 10) : e[t.key] || e[t.key.toLowerCase()];
219
+ i && (t.preventDefault(), Promise.resolve().then(i).catch((s) => this.showError(s)), this.wake());
220
+ }
221
+ wake() {
222
+ this.wrapper.classList.remove("is-idle"), clearTimeout(this.hideTimer), this.hideTimer = setTimeout(() => {
223
+ !this.video.paused && this.settings.hidden && !this.controls.contains(document.activeElement) && this.wrapper.classList.add("is-idle");
224
+ }, this.options.autoHide);
225
+ }
226
+ animateProgress() {
227
+ cancelAnimationFrame(this.animationFrame);
228
+ const t = () => {
229
+ if (this.destroyed || this.video.paused) return;
230
+ const e = this.video.duration;
231
+ Number.isFinite(e) && e > 0 && this.progress.style.setProperty(
232
+ "--progress",
233
+ `${this.video.currentTime / e * 100}%`
234
+ ), this.animationFrame = requestAnimationFrame(t);
235
+ };
236
+ this.animationFrame = requestAnimationFrame(t);
237
+ }
238
+ announce(t) {
239
+ clearTimeout(this.feedbackTimer), this.feedback.textContent = t, this.feedback.classList.add("visible"), this.feedbackTimer = setTimeout(() => this.feedback.classList.remove("visible"), 900);
240
+ }
241
+ toggleSettings() {
242
+ this.settings.hidden = !this.settings.hidden, this.settingsBtn.setAttribute("aria-expanded", String(!this.settings.hidden)), this.wake();
243
+ }
244
+ closeSettings() {
245
+ this.settings.hidden = !0, this.settingsBtn.setAttribute("aria-expanded", "false");
246
+ }
247
+ updateTime() {
248
+ const t = Number.isFinite(this.video.duration) ? this.video.duration : 0, e = this.video.currentTime || 0;
249
+ this.progress.disabled = !t, this.progress.value = String(t ? e / t * 1e3 : 0), this.progress.style.setProperty("--progress", `${t ? e / t * 100 : 0}%`), this.progress.setAttribute("aria-valuetext", `${c(e)} of ${c(t)}`), this.timeDisplay.textContent = `${c(e)} / ${t ? c(t) : "–:––"}`, this.buffered.replaceChildren();
250
+ for (let i = 0; t && i < this.video.buffered.length; i++) {
251
+ const s = n("span");
252
+ s.style.left = `${this.video.buffered.start(i) / t * 100}%`, s.style.width = `${(this.video.buffered.end(i) - this.video.buffered.start(i)) / t * 100}%`, this.buffered.append(s);
253
+ }
254
+ this.markers.replaceChildren(
255
+ ...(this.options.chapters || []).map((i) => {
256
+ const s = n("span");
257
+ return s.style.left = `${t ? i.time / t * 100 : 0}%`, s.title = i.title, s;
258
+ })
259
+ );
260
+ }
261
+ showPreview(t) {
262
+ if (!Number.isFinite(this.video.duration)) return;
263
+ const e = this.timeline.getBoundingClientRect(), i = d((t.clientX - e.left) / e.width, 0, 1), s = i * this.video.duration;
264
+ this.preview.hidden = !1, this.preview.style.left = `${d(i * 100, 15, 85)}%`;
265
+ const r = [...this.options.chapters || []].reverse().find((a) => a.time <= s);
266
+ this.previewTime.textContent = `${c(s)}${r ? ` · ${r.title}` : ""}`;
267
+ const l = this.thumbnails?.find((a) => a.start <= s && a.end > s);
268
+ if (this.previewImage.hidden = !l, l) {
269
+ this.previewImage.style.backgroundImage = `url(${JSON.stringify(u(l.src))})`;
270
+ const a = l.xywh;
271
+ this.previewImage.style.width = `${a?.[2] || 160}px`, this.previewImage.style.height = `${a?.[3] || 90}px`, this.previewImage.style.backgroundPosition = a ? `-${a[0]}px -${a[1]}px` : "center", this.previewImage.style.backgroundSize = a ? "auto" : "cover";
272
+ }
273
+ }
274
+ async loadThumbnails(t) {
275
+ if (this.thumbnailAbort?.abort(), this.thumbnails = [], Array.isArray(t)) {
276
+ this.thumbnails = t;
277
+ return;
278
+ }
279
+ if (!t) return;
280
+ const e = new AbortController();
281
+ this.thumbnailAbort = e;
282
+ try {
283
+ const i = u(t), s = await fetch(i, { signal: e.signal });
284
+ if (!s.ok) throw new Error("Thumbnail VTT could not be loaded");
285
+ const r = await s.text();
286
+ e.signal.aborted || (this.thumbnails = y(r, i));
287
+ } catch (i) {
288
+ i.name !== "AbortError" && this.emit("warning", i);
289
+ }
290
+ }
291
+ updateOptions(t = {}) {
292
+ t = Object.fromEntries(
293
+ Object.entries(t).map(([s, r]) => [
294
+ s,
295
+ r === void 0 ? b[s] : r
296
+ ])
297
+ );
298
+ const e = this.options;
299
+ this.options = { ...e, ...t };
300
+ const i = this.options;
301
+ if (this.wrapper.dataset.theme = i.theme, this.title.textContent = i.name || "", this.controls.hidden = i.controls === !1, this.bigPlay.hidden = i.controls === !1, this.video.autoplay = !!i.autoplay, this.video.loop = !!i.loop, this.loopInput.checked = !!i.loop, this.video.poster = u(i.poster || ""), "muted" in t && (this.video.muted = !!i.muted), "volume" in t) {
302
+ let s = i.volume;
303
+ if (i.persistVolume && !this.initialized)
304
+ try {
305
+ const r = localStorage.getItem("nanoplayer-volume");
306
+ r !== null && (s = Number(r));
307
+ } catch {
308
+ }
309
+ this.setVolume(s);
310
+ }
311
+ if ("playbackRate" in t && this.setPlaybackRate(i.playbackRate), this.fillSelect(
312
+ this.speedSelect,
313
+ i.playbackRates.map((s) => [s, `${s}×`])
314
+ ), this.speedSelect.value = String(this.video.playbackRate), this.fillSelect(
315
+ this.qualitySelect,
316
+ (i.sources || []).map((s, r) => [r, s.label || `${r + 1}`])
317
+ ), this.qualitySelect.parentElement.hidden = !i.sources?.length, this.fillSelect(
318
+ this.chapterSelect,
319
+ (i.chapters || []).map((s) => [s.time, s.title])
320
+ ), this.chapterSelect.parentElement.hidden = !i.chapters?.length, this.skipSelect.value = String(i.seekStep), ("tracks" in t || !this.initialized) && this.setTracks(i.tracks || []), "thumbnails" in t && this.loadThumbnails(i.thumbnails), "src" in t && (t.src !== e.src || !this.initialized) || "sources" in t && t.sources !== e.sources || !this.initialized) {
321
+ const s = i.src || i.sources?.[0] || i.playlist?.[0];
322
+ s && this.setSource(s);
323
+ }
324
+ if ("plugins" in t && this.initialized) {
325
+ for (const s of this.plugins.keys()) (i.plugins || []).includes(s) || this.removePlugin(s);
326
+ for (const s of i.plugins || []) this.use(s);
327
+ }
328
+ this.initialized = !0, this.updateTime();
329
+ }
330
+ setTracks(t) {
331
+ this.video.querySelectorAll("track").forEach((e) => e.remove()), t.forEach((e) => {
332
+ const i = n("track");
333
+ Object.assign(i, {
334
+ kind: "subtitles",
335
+ label: e.label,
336
+ srclang: e.srclang,
337
+ src: u(e.src),
338
+ default: !!e.default
339
+ }), this.video.append(i);
340
+ }), this.fillSelect(this.captionSelect, [[-1, "Off"], ...t.map((e, i) => [i, e.label])]), this.captionSelect.value = String(t.findIndex((e) => e.default)), this.captionBtn.hidden = !t.length, this.captionSelect.parentElement.hidden = !t.length;
341
+ }
342
+ setSubtitle(t) {
343
+ Array.from(this.video.textTracks).forEach((e, i) => {
344
+ e.mode = i === t ? "showing" : "disabled";
345
+ }), this.captionSelect.value = String(t), this.emit("subtitlechange", t);
346
+ }
347
+ toggleSubtitles() {
348
+ this.setSubtitle(Array.from(this.video.textTracks).some((t) => t.mode === "showing") ? -1 : 0);
349
+ }
350
+ refreshAudio() {
351
+ const t = this.hls?.audioTracks || Array.from(this.video.audioTracks || []);
352
+ this.fillSelect(
353
+ this.audioSelect,
354
+ t.map((e, i) => [i, e.name || e.label || e.language || `Track ${i + 1}`])
355
+ ), this.audioSelect.parentElement.hidden = t.length < 2;
356
+ }
357
+ setAudioTrack(t) {
358
+ this.hls ? this.hls.audioTrack = t : Array.from(this.video.audioTracks || []).forEach((e, i) => {
359
+ e.enabled = i === t;
360
+ }), this.audioSelect.value = String(t);
361
+ }
362
+ setSource(t, { preserveTime: e = !1 } = {}) {
363
+ const i = typeof t == "string" ? { src: t } : t, s = u(i.src), r = !this.video.paused, l = e ? this.video.currentTime : 0, a = ++this.sourceId;
364
+ this.sourceCleanup?.(), this.hls?.destroy(), this.hls = null, this.source = i, this.errorBox.hidden = !0, this.wrapper.classList.remove("has-error", "is-loading"), i.poster !== void 0 && (this.video.poster = u(i.poster)), i.tracks && this.setTracks(i.tracks);
365
+ const p = () => {
366
+ a === this.sourceId && (l && this.seek(l), (r || this.options.autoplay) && this.play().catch((o) => {
367
+ o.name !== "NotAllowedError" && a === this.sourceId && this.showError(o);
368
+ }));
369
+ };
370
+ if (this.video.addEventListener("loadedmetadata", p, { once: !0 }), this.sourceCleanup = () => this.video.removeEventListener("loadedmetadata", p), (/\.m3u8(?:$|[?#])/i.test(s) || /mpegurl/i.test(i.type || "")) && !this.video.canPlayType("application/vnd.apple.mpegurl")) {
371
+ const o = this.options.hls;
372
+ if (!o?.isSupported()) {
373
+ this.showError(new Error("HLS is unavailable. Supply hls.js through the hls option."));
374
+ return;
375
+ }
376
+ this.video.removeAttribute("src"), this.video.load(), this.hls = new o(), this.hls.attachMedia(this.video), this.hls.loadSource(s), this.hls.on(o.Events.ERROR, (w, f) => {
377
+ f.fatal && a === this.sourceId && this.showError(new Error(f.details || "HLS playback failed"));
378
+ }), this.hls.on(o.Events.MANIFEST_PARSED, () => {
379
+ a === this.sourceId && this.refreshAudio();
380
+ });
381
+ } else
382
+ this.video.src = s, this.video.load();
383
+ this.emit("sourcechange", i);
384
+ }
385
+ setQuality(t) {
386
+ const e = this.options.sources?.[t];
387
+ e && (this.setSource(e, { preserveTime: !0 }), this.qualitySelect.value = String(t), this.emit("qualitychange", e));
388
+ }
389
+ async play() {
390
+ this.destroyed || await this.video.play();
391
+ }
392
+ pause() {
393
+ this.destroyed || this.video.pause();
394
+ }
395
+ async togglePlay() {
396
+ this.video.paused ? await this.play() : this.pause();
397
+ }
398
+ seek(t) {
399
+ Number.isFinite(Number(t)) && (this.video.currentTime = d(
400
+ t,
401
+ 0,
402
+ Number.isFinite(this.video.duration) ? this.video.duration : Number.MAX_SAFE_INTEGER
403
+ ));
404
+ }
405
+ skip(t) {
406
+ this.seek(this.video.currentTime + t), this.announce(`${t > 0 ? "+" : ""}${t}s`);
407
+ }
408
+ frame(t = 1) {
409
+ this.video.paused && this.seek(this.video.currentTime + t / (this.options.frameRate || 30));
410
+ }
411
+ setVolume(t) {
412
+ this.video.volume = d(t, 0, 1);
413
+ }
414
+ setPlaybackRate(t) {
415
+ this.video.defaultPlaybackRate = d(t, 0.25, 4), this.video.playbackRate = this.video.defaultPlaybackRate;
416
+ }
417
+ toggleMute() {
418
+ this.video.muted = !this.video.muted;
419
+ }
420
+ async restart() {
421
+ this.seek(0), await this.play();
422
+ }
423
+ async retry() {
424
+ this.setSource(this.source), await this.play();
425
+ }
426
+ next() {
427
+ const t = this.options.playlist?.[this.playlistIndex + 1];
428
+ return t ? (this.playlistIndex++, this.setSource(t), this.play().catch((e) => this.showError(e)), !0) : !1;
429
+ }
430
+ async enterFullscreen() {
431
+ this.wrapper.requestFullscreen ? await this.wrapper.requestFullscreen() : this.video.webkitEnterFullscreen?.();
432
+ }
433
+ async exitFullscreen() {
434
+ document.fullscreenElement === this.wrapper ? await document.exitFullscreen() : this.video.webkitExitFullscreen?.();
435
+ }
436
+ async toggleFullscreen() {
437
+ document.fullscreenElement === this.wrapper || this.video.webkitDisplayingFullscreen ? await this.exitFullscreen() : await this.enterFullscreen();
438
+ }
439
+ async togglePiP() {
440
+ document.pictureInPictureElement === this.video ? await document.exitPictureInPicture() : this.pipBtn.hidden || await this.video.requestPictureInPicture();
441
+ }
442
+ toggleTheater() {
443
+ const t = this.wrapper.classList.toggle("nano-theater");
444
+ return this.emit("theaterchange", t), t;
445
+ }
446
+ formatTime(t) {
447
+ return c(t);
448
+ }
449
+ on(t, e) {
450
+ return this.events.has(t) || this.events.set(t, /* @__PURE__ */ new Set()), this.events.get(t).add(e), this;
451
+ }
452
+ off(t, e) {
453
+ return this.events.get(t)?.delete(e), this;
454
+ }
455
+ emit(t, e) {
456
+ for (const i of this.events.get(t) || []) i(e);
457
+ }
458
+ showError(t) {
459
+ this.destroyed || (this.errorText.textContent = t.message || String(t), this.errorBox.hidden = !1, this.wrapper.classList.add("has-error"), this.wrapper.classList.remove("is-loading"), this.emit("error", t));
460
+ }
461
+ use(t) {
462
+ if (!this.plugins.has(t)) {
463
+ const e = typeof t == "function" ? t(this) : t.setup(this);
464
+ this.plugins.set(t, e);
465
+ }
466
+ return this;
467
+ }
468
+ removePlugin(t) {
469
+ const e = this.plugins.get(t);
470
+ return this.plugins.delete(t), typeof e == "function" && e(), this;
471
+ }
472
+ destroy() {
473
+ if (!this.destroyed) {
474
+ this.destroyed = !0, clearTimeout(this.hideTimer), clearTimeout(this.feedbackTimer), clearTimeout(this.clickTimer), cancelAnimationFrame(this.animationFrame), this.thumbnailAbort?.abort(), this.sourceCleanup?.(), this.listeners.splice(0).forEach((t) => t());
475
+ for (const t of this.plugins.keys())
476
+ try {
477
+ this.removePlugin(t);
478
+ } catch {
479
+ }
480
+ this.hls?.destroy(), this.hls = null, document.pictureInPictureElement === this.video && document.exitPictureInPicture().catch(() => {
481
+ }), document.fullscreenElement === this.wrapper && document.exitFullscreen().catch(() => {
482
+ }), this.video.pause(), this.video.removeAttribute("src"), this.video.querySelectorAll("track").forEach((t) => t.remove()), this.video.load(), this.wrapper.remove(), this.events.clear();
483
+ }
90
484
  }
91
485
  }
92
- typeof window < "u" && (window.NanoPlayer = l);
93
486
  export {
94
- l as default
487
+ k as default
95
488
  };