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 +16 -0
- package/README.md +247 -104
- package/README.ru.md +70 -0
- package/dist/index.d.ts +126 -0
- package/dist/nanoplayer.css +1 -1
- package/dist/nanoplayer.es.js +478 -103
- package/dist/nanoplayer.umd.cjs +2 -0
- package/dist/nanoplayer.umd.js +2 -8
- package/dist/react.cjs +1 -0
- package/dist/react.d.ts +29 -0
- package/dist/react.js +48 -0
- package/package.json +76 -10
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(u,l){typeof exports=="object"&&typeof module<"u"?module.exports=l():typeof define=="function"&&define.amd?define(l):(u=typeof globalThis<"u"?globalThis:u||self,u.NanoPlayer=l())})(this,(function(){"use strict";const u=(o,t,e)=>Math.min(e,Math.max(t,Number(o)||0));function l(o){const t=Math.max(0,Math.floor(o||0));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")}`}function d(o){if(!o)return"";const t=new URL(o,document.baseURI);if(!["http:","https:","blob:","file:"].includes(t.protocol))throw new TypeError("Unsupported media URL protocol");return t.href}function n(o,t,e){const i=document.createElement(o);return t&&(i.className=t),e!==void 0&&(i.textContent=e),i}function y(o,t){const e=i=>i.split(":").reduce((s,r)=>s*60+Number(r),0);return o.replace(/\r/g,"").split(/\n\s*\n/).flatMap(i=>{const s=i.split(`
|
|
2
|
+
`),r=s.findIndex(h=>h.includes(" --> "));if(r<0||!s[r+1])return[];const[c,a]=s[r].split(" --> ").map(h=>e(h.trim().split(/\s/)[0])),[p,v]=s[r+1].trim().split("#xywh=");return Number.isFinite(c+a)?[{start:c,end:a,src:new URL(p,t).href,xywh:v?.split(",").map(Number)}]:[]})}const f={play:"M9 5 20 12 9 19Z",pause:"M8 5v14M16 5v14",volume:"M11 5 6 9H3v6h3l5 4ZM15 8q5 4 0 8M18 5q8 7 0 14",mute:"M11 5 6 9H3v6h3l5 4ZM16 9l6 6m0-6-6 6",settings:"M4 7h16M4 17h16M9 4v6M15 14v6",fullscreen:"M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5",pip:"M3 4h18v16H3ZM12 11h7v7h-7Z",theater:"M3 6h18v12H3Z",restart:"M4 10a8 8 0 1 1 1 8M4 4v6h6",back:"M11 6 3 12l8 6ZM21 6l-8 6 8 6Z",next:"m3 6 8 6-8 6Zm10 0 8 6-8 6Z",captions:"M3 5h18v14H3ZM10 9H7v6h3m8-6h-3v6h3"};function m(o){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true");const e=document.createElementNS(t.namespaceURI,"path");return e.setAttribute("d",f[o]||f.play),t.append(e),t}const g={src:"",name:"",theme:"dark",controls:!0,volume:1,playbackRate:1,seekStep:5,frameRate:30,autoHide:2500,playbackRates:[.25,.5,.75,1,1.25,1.5,2,3,4]};class w{constructor(t,e={}){if(this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("NanoPlayer: container not found");this.options={...g,...e},this.listeners=[],this.events=new Map,this.plugins=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();try{this.updateOptions(this.options),(e.plugins||[]).forEach(i=>this.use(i))}catch(i){throw this.destroy(),i}}listen(t,e,i,s){t.addEventListener(e,i,s),this.listeners.push(()=>t.removeEventListener(e,i,s))}button(t,e,i){const s=n("button","nano-icon");return s.type="button",s.title=t,s.setAttribute("aria-label",t),s.append(m(e)),this.listen(s,"click",()=>{Promise.resolve().then(i).catch(r=>this.showError(r))}),s}buildUI(){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(this.errorText,this.button("Retry playback","restart",()=>this.retry())),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);const t=n("div","nano-row"),e=n("div","nano-left"),i=n("div","nano-right");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(this.playBtn,this.button("Back 10 seconds","back",()=>this.skip(-10)),this.muteBtn,this.volumeSlider,this.timeDisplay),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=>{this.options.seekStep=Number(r)}),this.fillSelect(this.skipSelect,[5,10,30].map(r=>[r,`${r} seconds`])),this.loopInput=n("input"),this.loopInput.type="checkbox";const s=n("label","","Repeat video");s.append(this.loopInput),this.settings.append(s),this.listen(this.loopInput,"change",()=>{this.video.loop=this.loopInput.checked}),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(this.captionBtn,this.settingsBtn,this.button("Theater mode","theater",()=>this.toggleTheater()),this.pipBtn,this.fullscreenBtn),t.append(e,i),this.controls.append(this.timeline,t,this.settings),this.wrapper.append(this.title,this.bigPlay,this.spinner,this.feedback,this.errorBox,this.controls),this.pipBtn.hidden=!document.pictureInPictureEnabled||!this.video.requestPictureInPicture,this.fullscreenBtn.hidden=!(this.wrapper.requestFullscreen&&document.fullscreenEnabled!==!1)&&!this.video.webkitEnterFullscreen}select(t,e){const i=n("label","",t),s=n("select");return s.setAttribute("aria-label",t),i.append(s),this.settings.append(i),this.listen(s,"change",()=>{try{e(s.value)}catch(r){this.showError(r)}}),s}fillSelect(t,e){t.replaceChildren(...e.map(([i,s])=>{const r=n("option","",s);return r.value=String(i),r}))}bindEvents(){const t=this.video;for(const e of["play","pause","ended","timeupdate","volumechange","ratechange","loadedmetadata","durationchange","progress","waiting","playing","canplay","seeking","seeked"])this.listen(t,e,()=>{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)try{localStorage.setItem("nanoplayer-volume",String(t.volume))}catch{}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(e,e==="timeupdate"?t.currentTime:e==="volumechange"?t.volume:e==="ratechange"?t.playbackRate:void 0),e==="ended"&&(this.announce("Playback complete"),t.loop||this.next())});this.listen(t,"error",()=>this.showError(new Error(t.error?.message||"This video could not be played. Check the source or try again."))),this.listen(this.progress,"input",()=>this.seek(Number(this.progress.value)/1e3*(t.duration||0))),this.listen(this.volumeSlider,"input",()=>{t.muted=!1,this.setVolume(this.volumeSlider.value)}),this.listen(this.timeline,"pointermove",e=>this.showPreview(e)),this.listen(this.timeline,"pointerleave",()=>{this.preview.hidden=!0}),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=>{this.touchUntil>Date.now()||(this.wrapper.focus(),e.detail===1&&(clearTimeout(this.clickTimer),this.clickTimer=setTimeout(()=>this.togglePlay().catch(i=>this.showError(i)),230)))}),this.listen(t,"dblclick",()=>{clearTimeout(this.clickTimer),this.toggleFullscreen().catch(e=>this.showError(e))}),this.listen(t,"pointerup",e=>{if(e.pointerType!=="touch")return;this.touchUntil=Date.now()+500;const i=t.getBoundingClientRect(),s=e.clientX-i.left<i.width/2?-1:1;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())}),this.listen(document,"pointerdown",e=>{!this.settings.contains(e.target)&&!this.settingsBtn.contains(e.target)&&this.closeSettings()}),this.listen(document,"fullscreenchange",()=>this.wrapper.classList.toggle("nano-fullscreen",document.fullscreenElement===this.wrapper))}handleKey(t){if(t.altKey||t.ctrlKey||t.metaKey||t.target.closest('input,textarea,select,[contenteditable="true"]')||t.target.closest("button")&&[" ","Enter"].includes(t.key))return;const e={" ":()=>this.togglePlay(),k:()=>this.togglePlay(),ArrowLeft:()=>this.skip(-this.options.seekStep),ArrowRight:()=>this.skip(this.options.seekStep),ArrowUp:()=>this.setVolume(this.video.volume+.05),ArrowDown:()=>this.setVolume(this.video.volume-.05),m:()=>this.toggleMute(),f:()=>this.toggleFullscreen(),p:()=>this.togglePiP(),t:()=>this.toggleTheater(),j:()=>this.skip(-10),l:()=>this.skip(10),c:()=>this.toggleSubtitles(),",":()=>this.frame(-1),".":()=>this.frame(1),Escape:()=>{this.closeSettings(),this.settingsBtn.focus()}},i=/^\d$/.test(t.key)?()=>this.seek(this.video.duration*Number(t.key)/10):e[t.key]||e[t.key.toLowerCase()];i&&(t.preventDefault(),Promise.resolve().then(i).catch(s=>this.showError(s)),this.wake())}wake(){this.wrapper.classList.remove("is-idle"),clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{!this.video.paused&&this.settings.hidden&&!this.controls.contains(document.activeElement)&&this.wrapper.classList.add("is-idle")},this.options.autoHide)}animateProgress(){cancelAnimationFrame(this.animationFrame);const t=()=>{if(this.destroyed||this.video.paused)return;const e=this.video.duration;Number.isFinite(e)&&e>0&&this.progress.style.setProperty("--progress",`${this.video.currentTime/e*100}%`),this.animationFrame=requestAnimationFrame(t)};this.animationFrame=requestAnimationFrame(t)}announce(t){clearTimeout(this.feedbackTimer),this.feedback.textContent=t,this.feedback.classList.add("visible"),this.feedbackTimer=setTimeout(()=>this.feedback.classList.remove("visible"),900)}toggleSettings(){this.settings.hidden=!this.settings.hidden,this.settingsBtn.setAttribute("aria-expanded",String(!this.settings.hidden)),this.wake()}closeSettings(){this.settings.hidden=!0,this.settingsBtn.setAttribute("aria-expanded","false")}updateTime(){const t=Number.isFinite(this.video.duration)?this.video.duration:0,e=this.video.currentTime||0;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",`${l(e)} of ${l(t)}`),this.timeDisplay.textContent=`${l(e)} / ${t?l(t):"–:––"}`,this.buffered.replaceChildren();for(let i=0;t&&i<this.video.buffered.length;i++){const s=n("span");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)}this.markers.replaceChildren(...(this.options.chapters||[]).map(i=>{const s=n("span");return s.style.left=`${t?i.time/t*100:0}%`,s.title=i.title,s}))}showPreview(t){if(!Number.isFinite(this.video.duration))return;const e=this.timeline.getBoundingClientRect(),i=u((t.clientX-e.left)/e.width,0,1),s=i*this.video.duration;this.preview.hidden=!1,this.preview.style.left=`${u(i*100,15,85)}%`;const r=[...this.options.chapters||[]].reverse().find(a=>a.time<=s);this.previewTime.textContent=`${l(s)}${r?` · ${r.title}`:""}`;const c=this.thumbnails?.find(a=>a.start<=s&&a.end>s);if(this.previewImage.hidden=!c,c){this.previewImage.style.backgroundImage=`url(${JSON.stringify(d(c.src))})`;const a=c.xywh;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"}}async loadThumbnails(t){if(this.thumbnailAbort?.abort(),this.thumbnails=[],Array.isArray(t)){this.thumbnails=t;return}if(!t)return;const e=new AbortController;this.thumbnailAbort=e;try{const i=d(t),s=await fetch(i,{signal:e.signal});if(!s.ok)throw new Error("Thumbnail VTT could not be loaded");const r=await s.text();e.signal.aborted||(this.thumbnails=y(r,i))}catch(i){i.name!=="AbortError"&&this.emit("warning",i)}}updateOptions(t={}){t=Object.fromEntries(Object.entries(t).map(([s,r])=>[s,r===void 0?g[s]:r]));const e=this.options;this.options={...e,...t};const i=this.options;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=d(i.poster||""),"muted"in t&&(this.video.muted=!!i.muted),"volume"in t){let s=i.volume;if(i.persistVolume&&!this.initialized)try{const r=localStorage.getItem("nanoplayer-volume");r!==null&&(s=Number(r))}catch{}this.setVolume(s)}if("playbackRate"in t&&this.setPlaybackRate(i.playbackRate),this.fillSelect(this.speedSelect,i.playbackRates.map(s=>[s,`${s}×`])),this.speedSelect.value=String(this.video.playbackRate),this.fillSelect(this.qualitySelect,(i.sources||[]).map((s,r)=>[r,s.label||`${r+1}`])),this.qualitySelect.parentElement.hidden=!i.sources?.length,this.fillSelect(this.chapterSelect,(i.chapters||[]).map(s=>[s.time,s.title])),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){const s=i.src||i.sources?.[0]||i.playlist?.[0];s&&this.setSource(s)}if("plugins"in t&&this.initialized){for(const s of this.plugins.keys())(i.plugins||[]).includes(s)||this.removePlugin(s);for(const s of i.plugins||[])this.use(s)}this.initialized=!0,this.updateTime()}setTracks(t){this.video.querySelectorAll("track").forEach(e=>e.remove()),t.forEach(e=>{const i=n("track");Object.assign(i,{kind:"subtitles",label:e.label,srclang:e.srclang,src:d(e.src),default:!!e.default}),this.video.append(i)}),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}setSubtitle(t){Array.from(this.video.textTracks).forEach((e,i)=>{e.mode=i===t?"showing":"disabled"}),this.captionSelect.value=String(t),this.emit("subtitlechange",t)}toggleSubtitles(){this.setSubtitle(Array.from(this.video.textTracks).some(t=>t.mode==="showing")?-1:0)}refreshAudio(){const t=this.hls?.audioTracks||Array.from(this.video.audioTracks||[]);this.fillSelect(this.audioSelect,t.map((e,i)=>[i,e.name||e.label||e.language||`Track ${i+1}`])),this.audioSelect.parentElement.hidden=t.length<2}setAudioTrack(t){this.hls?this.hls.audioTrack=t:Array.from(this.video.audioTracks||[]).forEach((e,i)=>{e.enabled=i===t}),this.audioSelect.value=String(t)}setSource(t,{preserveTime:e=!1}={}){const i=typeof t=="string"?{src:t}:t,s=d(i.src),r=!this.video.paused,c=e?this.video.currentTime:0,a=++this.sourceId;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=d(i.poster)),i.tracks&&this.setTracks(i.tracks);const p=()=>{a===this.sourceId&&(c&&this.seek(c),(r||this.options.autoplay)&&this.play().catch(h=>{h.name!=="NotAllowedError"&&a===this.sourceId&&this.showError(h)}))};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")){const h=this.options.hls;if(!h?.isSupported()){this.showError(new Error("HLS is unavailable. Supply hls.js through the hls option."));return}this.video.removeAttribute("src"),this.video.load(),this.hls=new h,this.hls.attachMedia(this.video),this.hls.loadSource(s),this.hls.on(h.Events.ERROR,(k,b)=>{b.fatal&&a===this.sourceId&&this.showError(new Error(b.details||"HLS playback failed"))}),this.hls.on(h.Events.MANIFEST_PARSED,()=>{a===this.sourceId&&this.refreshAudio()})}else this.video.src=s,this.video.load();this.emit("sourcechange",i)}setQuality(t){const e=this.options.sources?.[t];e&&(this.setSource(e,{preserveTime:!0}),this.qualitySelect.value=String(t),this.emit("qualitychange",e))}async play(){this.destroyed||await this.video.play()}pause(){this.destroyed||this.video.pause()}async togglePlay(){this.video.paused?await this.play():this.pause()}seek(t){Number.isFinite(Number(t))&&(this.video.currentTime=u(t,0,Number.isFinite(this.video.duration)?this.video.duration:Number.MAX_SAFE_INTEGER))}skip(t){this.seek(this.video.currentTime+t),this.announce(`${t>0?"+":""}${t}s`)}frame(t=1){this.video.paused&&this.seek(this.video.currentTime+t/(this.options.frameRate||30))}setVolume(t){this.video.volume=u(t,0,1)}setPlaybackRate(t){this.video.defaultPlaybackRate=u(t,.25,4),this.video.playbackRate=this.video.defaultPlaybackRate}toggleMute(){this.video.muted=!this.video.muted}async restart(){this.seek(0),await this.play()}async retry(){this.setSource(this.source),await this.play()}next(){const t=this.options.playlist?.[this.playlistIndex+1];return t?(this.playlistIndex++,this.setSource(t),this.play().catch(e=>this.showError(e)),!0):!1}async enterFullscreen(){this.wrapper.requestFullscreen?await this.wrapper.requestFullscreen():this.video.webkitEnterFullscreen?.()}async exitFullscreen(){document.fullscreenElement===this.wrapper?await document.exitFullscreen():this.video.webkitExitFullscreen?.()}async toggleFullscreen(){document.fullscreenElement===this.wrapper||this.video.webkitDisplayingFullscreen?await this.exitFullscreen():await this.enterFullscreen()}async togglePiP(){document.pictureInPictureElement===this.video?await document.exitPictureInPicture():this.pipBtn.hidden||await this.video.requestPictureInPicture()}toggleTheater(){const t=this.wrapper.classList.toggle("nano-theater");return this.emit("theaterchange",t),t}formatTime(t){return l(t)}on(t,e){return this.events.has(t)||this.events.set(t,new Set),this.events.get(t).add(e),this}off(t,e){return this.events.get(t)?.delete(e),this}emit(t,e){for(const i of this.events.get(t)||[])i(e)}showError(t){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))}use(t){if(!this.plugins.has(t)){const e=typeof t=="function"?t(this):t.setup(this);this.plugins.set(t,e)}return this}removePlugin(t){const e=this.plugins.get(t);return this.plugins.delete(t),typeof e=="function"&&e(),this}destroy(){if(!this.destroyed){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());for(const t of this.plugins.keys())try{this.removePlugin(t)}catch{}this.hls?.destroy(),this.hls=null,document.pictureInPictureElement===this.video&&document.exitPictureInPicture().catch(()=>{}),document.fullscreenElement===this.wrapper&&document.exitFullscreen().catch(()=>{}),this.video.pause(),this.video.removeAttribute("src"),this.video.querySelectorAll("track").forEach(t=>t.remove()),this.video.load(),this.wrapper.remove(),this.events.clear()}}}return w}));
|
package/dist/nanoplayer.umd.js
CHANGED
|
@@ -1,8 +1,2 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
<strong>NanoPlayer</strong><br>
|
|
3
|
-
${e}
|
|
4
|
-
Version 0.1.7<br>
|
|
5
|
-
Apache-2.0 License
|
|
6
|
-
swiftmessage.org
|
|
7
|
-
github.com/swiftmessage/NanoPlayer
|
|
8
|
-
`,this.fullscreenBtn=document.createElement("button"),this.fullscreenBtn.className="nano-icon",this.fullscreenBtn.textContent="⛶",this.fullscreenBtn.onclick=()=>this.toggleFullscreen(),this.right.append(this.volumeMenu.root,this.settingsMenu.root,this.infoMenu.root,this.fullscreenBtn),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=t=>{if(!Number.isFinite(this.video.duration)||this.video.duration<=0)return;const i=this.progress.getBoundingClientRect();this.video.currentTime=(t.clientX-i.left)/i.width*this.video.duration},this.volumeSlider.oninput=()=>this.video.volume=this.volumeSlider.value}createMenu(e){const t=document.createElement("div");t.className="nano-menu-wrap";const i=document.createElement("button");i.className="nano-icon",i.textContent=e;const n=document.createElement("div");return n.className="nano-menu",i.onclick=r=>{r.stopPropagation(),document.querySelectorAll(".nano-menu-wrap.open").forEach(a=>a.classList.remove("open")),t.classList.toggle("open")},document.addEventListener("click",()=>{t.classList.remove("open")}),t.append(i,n),{root:t,menu:n,close:()=>t.classList.remove("open")}}bindEvents(){this.wrapper.addEventListener("click",()=>{this.wrapper.focus()}),this.video.addEventListener("loadedmetadata",()=>{this.options.poster||(this.video.currentTime=.1,this.video.pause()),this.updateTime()}),this.video.addEventListener("play",()=>{this.playBtn.textContent="❚❚",this.overlay.classList.add("hidden")}),this.video.addEventListener("pause",()=>{this.playBtn.textContent="▶"}),this.video.addEventListener("timeupdate",()=>{this.updateTime()}),this.wrapper.addEventListener("keydown",e=>{if(e.code!=="Space")return;const t=e.target.tagName;["INPUT","TEXTAREA","SELECT"].includes(t)||(e.preventDefault(),this.video.paused?this.video.play():this.video.pause())}),document.addEventListener("fullscreenchange",()=>{this.wrapper.classList.toggle("nano-fullscreen",!!document.fullscreenElement)})}updateTime(){const e=Number.isFinite(this.video.duration)?this.video.duration:0,t=Number.isFinite(this.video.currentTime)?this.video.currentTime:0,i=e>0?t/e*100:0;this.progressFill.style.width=`${i}%`,this.timeDisplay.textContent=`${this.formatTime(t)} / ${this.formatTime(e)}`}formatTime(e){const t=Math.max(0,Math.floor(e||0)),i=Math.floor(t/3600),n=Math.floor(t%3600/60),r=t%60,a=String(r).padStart(2,"0");if(i>0){const l=String(n).padStart(2,"0");return`${i}:${l}:${a}`}return`${n}:${a}`}toggleFullscreen(){const e=this.wrapper;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()}}return typeof window<"u"&&(window.NanoPlayer=s),s}));
|
|
1
|
+
(function(u,l){typeof exports=="object"&&typeof module<"u"?module.exports=l():typeof define=="function"&&define.amd?define(l):(u=typeof globalThis<"u"?globalThis:u||self,u.NanoPlayer=l())})(this,(function(){"use strict";const u=(o,t,e)=>Math.min(e,Math.max(t,Number(o)||0));function l(o){const t=Math.max(0,Math.floor(o||0));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")}`}function d(o){if(!o)return"";const t=new URL(o,document.baseURI);if(!["http:","https:","blob:","file:"].includes(t.protocol))throw new TypeError("Unsupported media URL protocol");return t.href}function n(o,t,e){const i=document.createElement(o);return t&&(i.className=t),e!==void 0&&(i.textContent=e),i}function y(o,t){const e=i=>i.split(":").reduce((s,r)=>s*60+Number(r),0);return o.replace(/\r/g,"").split(/\n\s*\n/).flatMap(i=>{const s=i.split(`
|
|
2
|
+
`),r=s.findIndex(h=>h.includes(" --> "));if(r<0||!s[r+1])return[];const[c,a]=s[r].split(" --> ").map(h=>e(h.trim().split(/\s/)[0])),[p,v]=s[r+1].trim().split("#xywh=");return Number.isFinite(c+a)?[{start:c,end:a,src:new URL(p,t).href,xywh:v?.split(",").map(Number)}]:[]})}const f={play:"M9 5 20 12 9 19Z",pause:"M8 5v14M16 5v14",volume:"M11 5 6 9H3v6h3l5 4ZM15 8q5 4 0 8M18 5q8 7 0 14",mute:"M11 5 6 9H3v6h3l5 4ZM16 9l6 6m0-6-6 6",settings:"M4 7h16M4 17h16M9 4v6M15 14v6",fullscreen:"M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5",pip:"M3 4h18v16H3ZM12 11h7v7h-7Z",theater:"M3 6h18v12H3Z",restart:"M4 10a8 8 0 1 1 1 8M4 4v6h6",back:"M11 6 3 12l8 6ZM21 6l-8 6 8 6Z",next:"m3 6 8 6-8 6Zm10 0 8 6-8 6Z",captions:"M3 5h18v14H3ZM10 9H7v6h3m8-6h-3v6h3"};function m(o){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true");const e=document.createElementNS(t.namespaceURI,"path");return e.setAttribute("d",f[o]||f.play),t.append(e),t}const g={src:"",name:"",theme:"dark",controls:!0,volume:1,playbackRate:1,seekStep:5,frameRate:30,autoHide:2500,playbackRates:[.25,.5,.75,1,1.25,1.5,2,3,4]};class w{constructor(t,e={}){if(this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("NanoPlayer: container not found");this.options={...g,...e},this.listeners=[],this.events=new Map,this.plugins=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();try{this.updateOptions(this.options),(e.plugins||[]).forEach(i=>this.use(i))}catch(i){throw this.destroy(),i}}listen(t,e,i,s){t.addEventListener(e,i,s),this.listeners.push(()=>t.removeEventListener(e,i,s))}button(t,e,i){const s=n("button","nano-icon");return s.type="button",s.title=t,s.setAttribute("aria-label",t),s.append(m(e)),this.listen(s,"click",()=>{Promise.resolve().then(i).catch(r=>this.showError(r))}),s}buildUI(){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(this.errorText,this.button("Retry playback","restart",()=>this.retry())),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);const t=n("div","nano-row"),e=n("div","nano-left"),i=n("div","nano-right");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(this.playBtn,this.button("Back 10 seconds","back",()=>this.skip(-10)),this.muteBtn,this.volumeSlider,this.timeDisplay),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=>{this.options.seekStep=Number(r)}),this.fillSelect(this.skipSelect,[5,10,30].map(r=>[r,`${r} seconds`])),this.loopInput=n("input"),this.loopInput.type="checkbox";const s=n("label","","Repeat video");s.append(this.loopInput),this.settings.append(s),this.listen(this.loopInput,"change",()=>{this.video.loop=this.loopInput.checked}),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(this.captionBtn,this.settingsBtn,this.button("Theater mode","theater",()=>this.toggleTheater()),this.pipBtn,this.fullscreenBtn),t.append(e,i),this.controls.append(this.timeline,t,this.settings),this.wrapper.append(this.title,this.bigPlay,this.spinner,this.feedback,this.errorBox,this.controls),this.pipBtn.hidden=!document.pictureInPictureEnabled||!this.video.requestPictureInPicture,this.fullscreenBtn.hidden=!(this.wrapper.requestFullscreen&&document.fullscreenEnabled!==!1)&&!this.video.webkitEnterFullscreen}select(t,e){const i=n("label","",t),s=n("select");return s.setAttribute("aria-label",t),i.append(s),this.settings.append(i),this.listen(s,"change",()=>{try{e(s.value)}catch(r){this.showError(r)}}),s}fillSelect(t,e){t.replaceChildren(...e.map(([i,s])=>{const r=n("option","",s);return r.value=String(i),r}))}bindEvents(){const t=this.video;for(const e of["play","pause","ended","timeupdate","volumechange","ratechange","loadedmetadata","durationchange","progress","waiting","playing","canplay","seeking","seeked"])this.listen(t,e,()=>{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)try{localStorage.setItem("nanoplayer-volume",String(t.volume))}catch{}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(e,e==="timeupdate"?t.currentTime:e==="volumechange"?t.volume:e==="ratechange"?t.playbackRate:void 0),e==="ended"&&(this.announce("Playback complete"),t.loop||this.next())});this.listen(t,"error",()=>this.showError(new Error(t.error?.message||"This video could not be played. Check the source or try again."))),this.listen(this.progress,"input",()=>this.seek(Number(this.progress.value)/1e3*(t.duration||0))),this.listen(this.volumeSlider,"input",()=>{t.muted=!1,this.setVolume(this.volumeSlider.value)}),this.listen(this.timeline,"pointermove",e=>this.showPreview(e)),this.listen(this.timeline,"pointerleave",()=>{this.preview.hidden=!0}),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=>{this.touchUntil>Date.now()||(this.wrapper.focus(),e.detail===1&&(clearTimeout(this.clickTimer),this.clickTimer=setTimeout(()=>this.togglePlay().catch(i=>this.showError(i)),230)))}),this.listen(t,"dblclick",()=>{clearTimeout(this.clickTimer),this.toggleFullscreen().catch(e=>this.showError(e))}),this.listen(t,"pointerup",e=>{if(e.pointerType!=="touch")return;this.touchUntil=Date.now()+500;const i=t.getBoundingClientRect(),s=e.clientX-i.left<i.width/2?-1:1;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())}),this.listen(document,"pointerdown",e=>{!this.settings.contains(e.target)&&!this.settingsBtn.contains(e.target)&&this.closeSettings()}),this.listen(document,"fullscreenchange",()=>this.wrapper.classList.toggle("nano-fullscreen",document.fullscreenElement===this.wrapper))}handleKey(t){if(t.altKey||t.ctrlKey||t.metaKey||t.target.closest('input,textarea,select,[contenteditable="true"]')||t.target.closest("button")&&[" ","Enter"].includes(t.key))return;const e={" ":()=>this.togglePlay(),k:()=>this.togglePlay(),ArrowLeft:()=>this.skip(-this.options.seekStep),ArrowRight:()=>this.skip(this.options.seekStep),ArrowUp:()=>this.setVolume(this.video.volume+.05),ArrowDown:()=>this.setVolume(this.video.volume-.05),m:()=>this.toggleMute(),f:()=>this.toggleFullscreen(),p:()=>this.togglePiP(),t:()=>this.toggleTheater(),j:()=>this.skip(-10),l:()=>this.skip(10),c:()=>this.toggleSubtitles(),",":()=>this.frame(-1),".":()=>this.frame(1),Escape:()=>{this.closeSettings(),this.settingsBtn.focus()}},i=/^\d$/.test(t.key)?()=>this.seek(this.video.duration*Number(t.key)/10):e[t.key]||e[t.key.toLowerCase()];i&&(t.preventDefault(),Promise.resolve().then(i).catch(s=>this.showError(s)),this.wake())}wake(){this.wrapper.classList.remove("is-idle"),clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{!this.video.paused&&this.settings.hidden&&!this.controls.contains(document.activeElement)&&this.wrapper.classList.add("is-idle")},this.options.autoHide)}animateProgress(){cancelAnimationFrame(this.animationFrame);const t=()=>{if(this.destroyed||this.video.paused)return;const e=this.video.duration;Number.isFinite(e)&&e>0&&this.progress.style.setProperty("--progress",`${this.video.currentTime/e*100}%`),this.animationFrame=requestAnimationFrame(t)};this.animationFrame=requestAnimationFrame(t)}announce(t){clearTimeout(this.feedbackTimer),this.feedback.textContent=t,this.feedback.classList.add("visible"),this.feedbackTimer=setTimeout(()=>this.feedback.classList.remove("visible"),900)}toggleSettings(){this.settings.hidden=!this.settings.hidden,this.settingsBtn.setAttribute("aria-expanded",String(!this.settings.hidden)),this.wake()}closeSettings(){this.settings.hidden=!0,this.settingsBtn.setAttribute("aria-expanded","false")}updateTime(){const t=Number.isFinite(this.video.duration)?this.video.duration:0,e=this.video.currentTime||0;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",`${l(e)} of ${l(t)}`),this.timeDisplay.textContent=`${l(e)} / ${t?l(t):"–:––"}`,this.buffered.replaceChildren();for(let i=0;t&&i<this.video.buffered.length;i++){const s=n("span");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)}this.markers.replaceChildren(...(this.options.chapters||[]).map(i=>{const s=n("span");return s.style.left=`${t?i.time/t*100:0}%`,s.title=i.title,s}))}showPreview(t){if(!Number.isFinite(this.video.duration))return;const e=this.timeline.getBoundingClientRect(),i=u((t.clientX-e.left)/e.width,0,1),s=i*this.video.duration;this.preview.hidden=!1,this.preview.style.left=`${u(i*100,15,85)}%`;const r=[...this.options.chapters||[]].reverse().find(a=>a.time<=s);this.previewTime.textContent=`${l(s)}${r?` · ${r.title}`:""}`;const c=this.thumbnails?.find(a=>a.start<=s&&a.end>s);if(this.previewImage.hidden=!c,c){this.previewImage.style.backgroundImage=`url(${JSON.stringify(d(c.src))})`;const a=c.xywh;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"}}async loadThumbnails(t){if(this.thumbnailAbort?.abort(),this.thumbnails=[],Array.isArray(t)){this.thumbnails=t;return}if(!t)return;const e=new AbortController;this.thumbnailAbort=e;try{const i=d(t),s=await fetch(i,{signal:e.signal});if(!s.ok)throw new Error("Thumbnail VTT could not be loaded");const r=await s.text();e.signal.aborted||(this.thumbnails=y(r,i))}catch(i){i.name!=="AbortError"&&this.emit("warning",i)}}updateOptions(t={}){t=Object.fromEntries(Object.entries(t).map(([s,r])=>[s,r===void 0?g[s]:r]));const e=this.options;this.options={...e,...t};const i=this.options;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=d(i.poster||""),"muted"in t&&(this.video.muted=!!i.muted),"volume"in t){let s=i.volume;if(i.persistVolume&&!this.initialized)try{const r=localStorage.getItem("nanoplayer-volume");r!==null&&(s=Number(r))}catch{}this.setVolume(s)}if("playbackRate"in t&&this.setPlaybackRate(i.playbackRate),this.fillSelect(this.speedSelect,i.playbackRates.map(s=>[s,`${s}×`])),this.speedSelect.value=String(this.video.playbackRate),this.fillSelect(this.qualitySelect,(i.sources||[]).map((s,r)=>[r,s.label||`${r+1}`])),this.qualitySelect.parentElement.hidden=!i.sources?.length,this.fillSelect(this.chapterSelect,(i.chapters||[]).map(s=>[s.time,s.title])),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){const s=i.src||i.sources?.[0]||i.playlist?.[0];s&&this.setSource(s)}if("plugins"in t&&this.initialized){for(const s of this.plugins.keys())(i.plugins||[]).includes(s)||this.removePlugin(s);for(const s of i.plugins||[])this.use(s)}this.initialized=!0,this.updateTime()}setTracks(t){this.video.querySelectorAll("track").forEach(e=>e.remove()),t.forEach(e=>{const i=n("track");Object.assign(i,{kind:"subtitles",label:e.label,srclang:e.srclang,src:d(e.src),default:!!e.default}),this.video.append(i)}),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}setSubtitle(t){Array.from(this.video.textTracks).forEach((e,i)=>{e.mode=i===t?"showing":"disabled"}),this.captionSelect.value=String(t),this.emit("subtitlechange",t)}toggleSubtitles(){this.setSubtitle(Array.from(this.video.textTracks).some(t=>t.mode==="showing")?-1:0)}refreshAudio(){const t=this.hls?.audioTracks||Array.from(this.video.audioTracks||[]);this.fillSelect(this.audioSelect,t.map((e,i)=>[i,e.name||e.label||e.language||`Track ${i+1}`])),this.audioSelect.parentElement.hidden=t.length<2}setAudioTrack(t){this.hls?this.hls.audioTrack=t:Array.from(this.video.audioTracks||[]).forEach((e,i)=>{e.enabled=i===t}),this.audioSelect.value=String(t)}setSource(t,{preserveTime:e=!1}={}){const i=typeof t=="string"?{src:t}:t,s=d(i.src),r=!this.video.paused,c=e?this.video.currentTime:0,a=++this.sourceId;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=d(i.poster)),i.tracks&&this.setTracks(i.tracks);const p=()=>{a===this.sourceId&&(c&&this.seek(c),(r||this.options.autoplay)&&this.play().catch(h=>{h.name!=="NotAllowedError"&&a===this.sourceId&&this.showError(h)}))};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")){const h=this.options.hls;if(!h?.isSupported()){this.showError(new Error("HLS is unavailable. Supply hls.js through the hls option."));return}this.video.removeAttribute("src"),this.video.load(),this.hls=new h,this.hls.attachMedia(this.video),this.hls.loadSource(s),this.hls.on(h.Events.ERROR,(k,b)=>{b.fatal&&a===this.sourceId&&this.showError(new Error(b.details||"HLS playback failed"))}),this.hls.on(h.Events.MANIFEST_PARSED,()=>{a===this.sourceId&&this.refreshAudio()})}else this.video.src=s,this.video.load();this.emit("sourcechange",i)}setQuality(t){const e=this.options.sources?.[t];e&&(this.setSource(e,{preserveTime:!0}),this.qualitySelect.value=String(t),this.emit("qualitychange",e))}async play(){this.destroyed||await this.video.play()}pause(){this.destroyed||this.video.pause()}async togglePlay(){this.video.paused?await this.play():this.pause()}seek(t){Number.isFinite(Number(t))&&(this.video.currentTime=u(t,0,Number.isFinite(this.video.duration)?this.video.duration:Number.MAX_SAFE_INTEGER))}skip(t){this.seek(this.video.currentTime+t),this.announce(`${t>0?"+":""}${t}s`)}frame(t=1){this.video.paused&&this.seek(this.video.currentTime+t/(this.options.frameRate||30))}setVolume(t){this.video.volume=u(t,0,1)}setPlaybackRate(t){this.video.defaultPlaybackRate=u(t,.25,4),this.video.playbackRate=this.video.defaultPlaybackRate}toggleMute(){this.video.muted=!this.video.muted}async restart(){this.seek(0),await this.play()}async retry(){this.setSource(this.source),await this.play()}next(){const t=this.options.playlist?.[this.playlistIndex+1];return t?(this.playlistIndex++,this.setSource(t),this.play().catch(e=>this.showError(e)),!0):!1}async enterFullscreen(){this.wrapper.requestFullscreen?await this.wrapper.requestFullscreen():this.video.webkitEnterFullscreen?.()}async exitFullscreen(){document.fullscreenElement===this.wrapper?await document.exitFullscreen():this.video.webkitExitFullscreen?.()}async toggleFullscreen(){document.fullscreenElement===this.wrapper||this.video.webkitDisplayingFullscreen?await this.exitFullscreen():await this.enterFullscreen()}async togglePiP(){document.pictureInPictureElement===this.video?await document.exitPictureInPicture():this.pipBtn.hidden||await this.video.requestPictureInPicture()}toggleTheater(){const t=this.wrapper.classList.toggle("nano-theater");return this.emit("theaterchange",t),t}formatTime(t){return l(t)}on(t,e){return this.events.has(t)||this.events.set(t,new Set),this.events.get(t).add(e),this}off(t,e){return this.events.get(t)?.delete(e),this}emit(t,e){for(const i of this.events.get(t)||[])i(e)}showError(t){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))}use(t){if(!this.plugins.has(t)){const e=typeof t=="function"?t(this):t.setup(this);this.plugins.set(t,e)}return this}removePlugin(t){const e=this.plugins.get(t);return this.plugins.delete(t),typeof e=="function"&&e(),this}destroy(){if(!this.destroyed){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());for(const t of this.plugins.keys())try{this.removePlugin(t)}catch{}this.hls?.destroy(),this.hls=null,document.pictureInPictureElement===this.video&&document.exitPictureInPicture().catch(()=>{}),document.fullscreenElement===this.wrapper&&document.exitFullscreen().catch(()=>{}),this.video.pause(),this.video.removeAttribute("src"),this.video.querySelectorAll("track").forEach(t=>t.remove()),this.video.load(),this.wrapper.remove(),this.events.clear()}}}return w}));
|
package/dist/react.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const n=require("react"),h=require("nanoplayer"),l={onPlay:"play",onPause:"pause",onEnded:"ended",onTimeUpdate:"timeupdate",onError:"error",onVolumeChange:"volumechange",onRateChange:"ratechange",onSourceChange:"sourcechange",onTheaterChange:"theaterchange"};function i(t={},e){const a=n.useRef(null),c=n.useRef(null),s=n.useRef(t);s.current=t,n.useEffect(()=>{const u=new h(a.current,s.current);c.current=u;for(const[r,f]of Object.entries(l))u.on(f,g=>s.current[r]?.(g));return s.current.onReady?.(u),()=>{u.destroy(),c.current=null}},[]),n.useEffect(()=>(typeof e=="function"?e(c.current):e&&(e.current=c.current),()=>{typeof e=="function"?e(null):e&&(e.current=null)}),[e]);const o=n.useRef(t);return n.useEffect(()=>{const u={};for(const r of new Set([...Object.keys(o.current),...Object.keys(t)]))t[r]!==o.current[r]&&!(r in l)&&!["onReady","className","style","id"].includes(r)&&(u[r]=t[r]);Object.keys(u).length&&c.current?.updateOptions(u),o.current=t}),{containerRef:a,playerRef:c}}const y=n.forwardRef(function(e,a){const{containerRef:c}=i(e,a);return n.createElement("div",{ref:c,className:e.className,style:e.style,id:e.id})});exports.NanoPlayer=y;exports.default=y;exports.useNanoPlayer=i;
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CSSProperties,
|
|
3
|
+
ForwardRefExoticComponent,
|
|
4
|
+
RefAttributes,
|
|
5
|
+
RefObject,
|
|
6
|
+
Ref,
|
|
7
|
+
} from 'react';
|
|
8
|
+
import Player, { Options, Source } from './index.js';
|
|
9
|
+
export interface NanoPlayerProps extends Options {
|
|
10
|
+
id?: string;
|
|
11
|
+
className?: string;
|
|
12
|
+
style?: CSSProperties;
|
|
13
|
+
onReady?: (player: Player) => void;
|
|
14
|
+
onPlay?: () => void;
|
|
15
|
+
onPause?: () => void;
|
|
16
|
+
onEnded?: () => void;
|
|
17
|
+
onTimeUpdate?: (time: number) => void;
|
|
18
|
+
onError?: (error: Error) => void;
|
|
19
|
+
onVolumeChange?: (volume: number) => void;
|
|
20
|
+
onRateChange?: (rate: number) => void;
|
|
21
|
+
onSourceChange?: (source: Source) => void;
|
|
22
|
+
onTheaterChange?: (theater: boolean) => void;
|
|
23
|
+
}
|
|
24
|
+
export declare const NanoPlayer: ForwardRefExoticComponent<NanoPlayerProps & RefAttributes<Player>>;
|
|
25
|
+
export declare function useNanoPlayer(
|
|
26
|
+
props?: NanoPlayerProps,
|
|
27
|
+
ref?: Ref<Player | null>,
|
|
28
|
+
): { containerRef: RefObject<HTMLDivElement | null>; playerRef: RefObject<Player | null> };
|
|
29
|
+
export default NanoPlayer;
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { forwardRef as f, createElement as h, useRef as o, useEffect as s } from "react";
|
|
2
|
+
import g from "nanoplayer";
|
|
3
|
+
const i = {
|
|
4
|
+
onPlay: "play",
|
|
5
|
+
onPause: "pause",
|
|
6
|
+
onEnded: "ended",
|
|
7
|
+
onTimeUpdate: "timeupdate",
|
|
8
|
+
onError: "error",
|
|
9
|
+
onVolumeChange: "volumechange",
|
|
10
|
+
onRateChange: "ratechange",
|
|
11
|
+
onSourceChange: "sourcechange",
|
|
12
|
+
onTheaterChange: "theaterchange"
|
|
13
|
+
};
|
|
14
|
+
function N(n = {}, e) {
|
|
15
|
+
const u = o(null), t = o(null), a = o(n);
|
|
16
|
+
a.current = n, s(() => {
|
|
17
|
+
const c = new g(u.current, a.current);
|
|
18
|
+
t.current = c;
|
|
19
|
+
for (const [r, y] of Object.entries(i))
|
|
20
|
+
c.on(y, (m) => a.current[r]?.(m));
|
|
21
|
+
return a.current.onReady?.(c), () => {
|
|
22
|
+
c.destroy(), t.current = null;
|
|
23
|
+
};
|
|
24
|
+
}, []), s(() => (typeof e == "function" ? e(t.current) : e && (e.current = t.current), () => {
|
|
25
|
+
typeof e == "function" ? e(null) : e && (e.current = null);
|
|
26
|
+
}), [e]);
|
|
27
|
+
const l = o(n);
|
|
28
|
+
return s(() => {
|
|
29
|
+
const c = {};
|
|
30
|
+
for (const r of /* @__PURE__ */ new Set([...Object.keys(l.current), ...Object.keys(n)]))
|
|
31
|
+
n[r] !== l.current[r] && !(r in i) && !["onReady", "className", "style", "id"].includes(r) && (c[r] = n[r]);
|
|
32
|
+
Object.keys(c).length && t.current?.updateOptions(c), l.current = n;
|
|
33
|
+
}), { containerRef: u, playerRef: t };
|
|
34
|
+
}
|
|
35
|
+
const O = f(function(e, u) {
|
|
36
|
+
const { containerRef: t } = N(e, u);
|
|
37
|
+
return h("div", {
|
|
38
|
+
ref: t,
|
|
39
|
+
className: e.className,
|
|
40
|
+
style: e.style,
|
|
41
|
+
id: e.id
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
export {
|
|
45
|
+
O as NanoPlayer,
|
|
46
|
+
O as default,
|
|
47
|
+
N as useNanoPlayer
|
|
48
|
+
};
|
package/package.json
CHANGED
|
@@ -1,25 +1,91 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nanoplayer",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
"
|
|
3
|
+
"version": "2.0.1",
|
|
4
|
+
"description": "Accessible, themeable HTML5 video player with an optional React adapter",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/nanoplayer.umd.cjs",
|
|
7
|
+
"module": "./dist/nanoplayer.es.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/nanoplayer.es.js",
|
|
13
|
+
"require": "./dist/nanoplayer.umd.cjs"
|
|
14
|
+
},
|
|
15
|
+
"./react": {
|
|
16
|
+
"types": "./dist/react.d.ts",
|
|
17
|
+
"import": "./dist/react.js",
|
|
18
|
+
"require": "./dist/react.cjs"
|
|
19
|
+
},
|
|
20
|
+
"./dist/nanoplayer.css": "./dist/nanoplayer.css",
|
|
21
|
+
"./dist/nanoplayer.es.js": "./dist/nanoplayer.es.js",
|
|
22
|
+
"./dist/nanoplayer.umd.js": "./dist/nanoplayer.umd.js",
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
7
25
|
"files": [
|
|
8
|
-
"dist"
|
|
26
|
+
"dist",
|
|
27
|
+
"README.ru.md",
|
|
28
|
+
"CHANGELOG.md"
|
|
29
|
+
],
|
|
30
|
+
"sideEffects": [
|
|
31
|
+
"**/*.css"
|
|
9
32
|
],
|
|
10
33
|
"scripts": {
|
|
11
|
-
"
|
|
34
|
+
"dev": "vite --host 127.0.0.1",
|
|
35
|
+
"build": "node scripts/build.mjs",
|
|
36
|
+
"build:demo": "vite build --config vite.demo.config.js",
|
|
37
|
+
"test": "vitest run",
|
|
38
|
+
"test:types": "tsc -p test/tsconfig.json",
|
|
39
|
+
"test:package": "node test/package.mjs",
|
|
40
|
+
"test:e2e": "playwright test",
|
|
41
|
+
"prepack": "npm run build",
|
|
42
|
+
"prepublishOnly": "npm test && npm run test:types && npm run test:package"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"react": ">=18",
|
|
46
|
+
"react-dom": ">=18"
|
|
12
47
|
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"react": {
|
|
50
|
+
"optional": true
|
|
51
|
+
},
|
|
52
|
+
"react-dom": {
|
|
53
|
+
"optional": true
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@playwright/test": "^1.56.0",
|
|
58
|
+
"@types/react": "^19.1.0",
|
|
59
|
+
"@types/react-dom": "^19.1.0",
|
|
60
|
+
"jsdom": "^26.1.0",
|
|
61
|
+
"prettier": "^3.10.1",
|
|
62
|
+
"react": "^19.1.0",
|
|
63
|
+
"react-dom": "^19.1.0",
|
|
64
|
+
"typescript": "^5.8.3",
|
|
65
|
+
"vite": "^7.3.1",
|
|
66
|
+
"vitest": "^5.1.2"
|
|
67
|
+
},
|
|
68
|
+
"engines": {
|
|
69
|
+
"node": ">=22.12"
|
|
70
|
+
},
|
|
71
|
+
"repository": {
|
|
72
|
+
"type": "git",
|
|
73
|
+
"url": "git+https://github.com/swiftmessage/NanoPlayer.git"
|
|
74
|
+
},
|
|
75
|
+
"homepage": "https://github.com/swiftmessage/NanoPlayer#readme",
|
|
76
|
+
"bugs": "https://github.com/swiftmessage/NanoPlayer/issues",
|
|
13
77
|
"keywords": [
|
|
14
78
|
"video",
|
|
15
79
|
"player",
|
|
16
80
|
"html5",
|
|
17
|
-
"
|
|
18
|
-
"
|
|
81
|
+
"react",
|
|
82
|
+
"typescript",
|
|
83
|
+
"hls",
|
|
84
|
+
"nanoplayer"
|
|
19
85
|
],
|
|
20
86
|
"author": "SWIFTMESSAGE",
|
|
21
87
|
"license": "Apache-2.0",
|
|
22
|
-
"
|
|
23
|
-
"
|
|
88
|
+
"dependencies": {
|
|
89
|
+
"nanoplayer": "file:nanoplayer-2.0.0.tgz"
|
|
24
90
|
}
|
|
25
91
|
}
|