itube-modern-player 0.8.8 → 0.8.10

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/README.md CHANGED
@@ -1052,6 +1052,14 @@ npm publish # prepublishOnly прогонит typecheck + build
1052
1052
 
1053
1053
  Версионирование по [SemVer](https://semver.org/lang/ru/): `major.minor.patch`.
1054
1054
 
1055
+ ### 0.8.10
1056
+
1057
+ - Фикс зазоров центр-кластера: между кольцами и play было 40px (`gap: 16px` контейнера суммировался с `margin: 0 24px` у play) — теперь ровно макетные 24px, отступ задаёт только `gap` контейнера.
1058
+
1059
+ ### 0.8.9
1060
+
1061
+ - **Одна иконка перемотки на обе стороны**: дефолтные `seekBack`/`seekForward` — теперь один forward-глиф, кнопку «назад» плеер зеркалит сам (`scaleX(-1)` на svg/img внутри `.imp-*--seek-back`; число шага — соседний элемент, не зеркалится). ⚠️ Кастомные иконки: передавайте в `icons.seekBack`/`seekForward` один и тот же «вперёд»-глиф — заранее отзеркаленная `seekBack` теперь перевернётся обратно.
1062
+
1055
1063
  ### 0.8.8
1056
1064
 
1057
1065
  - **Превью следующего видео 1:1 с макетом**: карточка в стиле меню (`rgba(24,24,27,.95)` + blur, радиус 12, ring `white/10`, глубокая тень, без паддинга); миниатюра 16:9 на всю ширину с кикером «СЛЕДУЮЩЕЕ ВИДЕО» (11px/600, разрядка 0.1em) поверх верхнего затемнения 48px и бейджем длительности на кадре (11px/500, `black/80`); ниже инфо-блок 12px — тайтл 14px/600 (2 строки) и мета 12px `#a1a1aa` с разделителем `|` и 16px-иконками; зазор над кнопкой 4px. Без миниатюры кикер открывает инфо-блок.
package/dist/core.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var me=Object.create;var J=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var be=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ve(e))!ge.call(a,s)&&s!==t&&J(a,s,{get:()=>e[s],enumerable:!(i=fe(e,s))||i.enumerable});return a};var ke=(a,e,t)=>(t=a!=null?me(ye(a)):{},be(e||!a||!a.__esModule?J(t,"default",{value:a,enumerable:!0}):t,a));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("./placeholder-DeE6vGqL.cjs"),$=require("./labels-BOrrLImF.cjs");function o(a,e,t){const i=document.createElement(a);if(e&&(i.className=e),t)for(const[s,n]of Object.entries(t))i.setAttribute(s,n);return i}function S(a,e){if(a.textContent="",typeof e=="object"){"url"in e?a.append(o("img","imp-icon-img",{src:e.url,alt:""})):a.innerHTML=e.svg;return}/^\s*</.test(e)?a.innerHTML=e:a.append(o("img","imp-icon-img",{src:e,alt:""}))}function L(a,e=""){const t=o("img","imp-cover-img",{alt:e,decoding:"async"});return t.src=a,t}function g(a,e,t){const i=o("button",`imp-btn ${a}`,{type:"button","aria-label":e,title:e});return S(i,t),i}function te(a,e){const t=o("div",`${e}__meta`);return a.forEach((i,s)=>{s>0&&t.append(document.createTextNode(" "));const n=typeof i=="string"?i:i.text,r=typeof i=="string"?void 0:i.icon,l=o("span",`${e}__meta-chunk`);if(r){const c=o("span",`${e}__meta-icon`);S(c,r),l.append(c)}l.append(document.createTextNode(n)),t.append(l)}),t}function I(a,e,t){S(a,e),t!==void 0&&(a.setAttribute("aria-label",t),a.setAttribute("title",t))}function x(a,e,t){return Math.min(t,Math.max(e,a))}function b(a){if(!Number.isFinite(a)||a<0)return"0:00";const e=Math.floor(a%60),t=Math.floor(a/60%60),i=Math.floor(a/3600),s=i>0?String(t).padStart(2,"0"):String(t),n=String(e).padStart(2,"0");return i>0?`${i}:${s}:${n}`:`${s}:${n}`}function H(a){const e=a.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:[.,](\d{1,3}))?$/);if(!e)return null;const t=e[1]?Number(e[1]):0,i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4].padEnd(3,"0")):0;return t*3600+i*60+s+n/1e3}function ie(a){const e=[],t=a.replace(/\r\n?/g,`
1
+ "use strict";var me=Object.create;var J=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var be=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ve(e))!ge.call(a,s)&&s!==t&&J(a,s,{get:()=>e[s],enumerable:!(i=fe(e,s))||i.enumerable});return a};var ke=(a,e,t)=>(t=a!=null?me(ye(a)):{},be(e||!a||!a.__esModule?J(t,"default",{value:a,enumerable:!0}):t,a));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("./placeholder-DPxcQX8a.cjs"),$=require("./labels-BOrrLImF.cjs");function o(a,e,t){const i=document.createElement(a);if(e&&(i.className=e),t)for(const[s,n]of Object.entries(t))i.setAttribute(s,n);return i}function S(a,e){if(a.textContent="",typeof e=="object"){"url"in e?a.append(o("img","imp-icon-img",{src:e.url,alt:""})):a.innerHTML=e.svg;return}/^\s*</.test(e)?a.innerHTML=e:a.append(o("img","imp-icon-img",{src:e,alt:""}))}function L(a,e=""){const t=o("img","imp-cover-img",{alt:e,decoding:"async"});return t.src=a,t}function g(a,e,t){const i=o("button",`imp-btn ${a}`,{type:"button","aria-label":e,title:e});return S(i,t),i}function te(a,e){const t=o("div",`${e}__meta`);return a.forEach((i,s)=>{s>0&&t.append(document.createTextNode(" "));const n=typeof i=="string"?i:i.text,r=typeof i=="string"?void 0:i.icon,l=o("span",`${e}__meta-chunk`);if(r){const c=o("span",`${e}__meta-icon`);S(c,r),l.append(c)}l.append(document.createTextNode(n)),t.append(l)}),t}function I(a,e,t){S(a,e),t!==void 0&&(a.setAttribute("aria-label",t),a.setAttribute("title",t))}function x(a,e,t){return Math.min(t,Math.max(e,a))}function b(a){if(!Number.isFinite(a)||a<0)return"0:00";const e=Math.floor(a%60),t=Math.floor(a/60%60),i=Math.floor(a/3600),s=i>0?String(t).padStart(2,"0"):String(t),n=String(e).padStart(2,"0");return i>0?`${i}:${s}:${n}`:`${s}:${n}`}function H(a){const e=a.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:[.,](\d{1,3}))?$/);if(!e)return null;const t=e[1]?Number(e[1]):0,i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4].padEnd(3,"0")):0;return t*3600+i*60+s+n/1e3}function ie(a){const e=[],t=a.replace(/\r\n?/g,`
2
2
  `).split(/\n\n+/);for(const i of t){const s=i.split(`
3
3
  `).filter(m=>m.trim()!=="");if(s.length===0)continue;let n=s.findIndex(m=>m.includes("-->"));if(n===-1)continue;const[r,l]=s[n].split("-->"),c=H(r),h=H((l??"").split(" ")[1]??l??"")??H(l??"");if(c===null||h===null)continue;const d=s.slice(n+1).join(`
4
4
  `).trim();d&&e.push({start:c,end:h,text:d})}return e}function we(a,e){try{return new URL(a,new URL(e,window.location.href)).toString()}catch{return a}}class se{constructor(){this.listeners=new Map}on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>this.off(e,t)}once(e,t){const i=this.on(e,s=>{i(),t(s)});return i}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const i=this.listeners.get(e);if(i)for(const s of[...i])try{s(t)}catch(n){console.error("[itube-player] listener error",n)}}removeAll(){this.listeners.clear()}}const F={en:$.defaultLabels};function xe(a,e){F[a]=e}function _e(a){for(const[e,t]of Object.entries(a))t&&(F[e]=t)}function ne(a){return a&&F[a]||$.defaultLabels}function Se(){return Object.keys(F)}function Le(a){const e=[.06,.24,.4,.24,.06],t=a.length;return a.map((i,s)=>e.reduce((n,r,l)=>{const c=Math.min(t-1,Math.max(0,s+l-2));return n+r*a[c]},0))}function Te(a,e){if(a.length===0)return 0;const t=Math.min(a.length-1,Math.max(0,Math.round((a.length-1)*e)));return a[t]}function re(a,e){if(a.length===0||a.every(n=>n<=0))return[];const t=Le(a),i=e==="retention"?Te([...t].sort((n,r)=>n-r),.95):Math.max(...t);if(i<=0)return[];const s=.35;return t.map(n=>s+(1-s)*Math.min(1,Math.max(0,n/i)))}function oe(a,e,t=100){if(a.length===0||!Number.isFinite(e)||e<=0)return[];const i=new Array(t).fill(0);let s=!1;for(const n of a){if(!Number.isFinite(n.time)||n.time<0||n.time>e)continue;const r=Math.max(0,n.value);r!==0&&(i[Math.min(t-1,Math.floor(n.time/e*t))]+=r,s=!0)}return s?re(i,"peaks"):[]}function Ee(a,e="peaks",t=200){let i=a.map(s=>Number.isFinite(s)?Math.max(0,s):0);if(i.length>t){const s=new Array(t).fill(0),n=new Array(t).fill(0);for(let r=0;r<i.length;r++){const l=Math.min(t-1,Math.floor(r/i.length*t));s[l]+=i[r],n[l]++}i=s.map((r,l)=>n[l]>0?r/n[l]:0)}return re(i,e)}function ae(a,e=1,t=1e3,i=100){const s=a.length;if(s===0)return"";const n=t/(s-1||1),r=Math.max(0,e)/6,l=d=>{const m=Math.min(s-1,Math.max(0,d));return[m*n,i-a[m]*i]},[,c]=l(0);let h=`M 0 ${i} L 0 ${c.toFixed(1)}`;for(let d=0;d<s-1;d++){const[m,p]=l(d-1),[f,v]=l(d),[y,u]=l(d+1),[k,P]=l(d+2),A=f+(y-m)*r,D=Math.min(i,Math.max(0,v+(u-p)*r)),M=y-(k-f)*r,R=Math.min(i,Math.max(0,u-(P-v)*r));h+=` C ${A.toFixed(1)} ${D.toFixed(1)} ${M.toFixed(1)} ${R.toFixed(1)} ${y.toFixed(1)} ${u.toFixed(1)}`}return h+=` L ${t} ${i} Z`,h}async function le(a,e){if(a.src)return{roll:a.roll,mediaUrl:a.src,clickThrough:a.clickUrl,impressions:[],tracking:{}};if(!a.vastTag)throw new Error('Ad roll has neither "vastTag" nor "src"');return he(a,a.vastTag,e,0,{impressions:[],tracking:{}})}async function he(a,e,t,i,s){if(i>t.maxWrapperDepth)throw new Error("VAST wrapper depth limit exceeded");const n=new AbortController,r=setTimeout(()=>n.abort(),t.requestTimeout);let l;try{const v=await fetch(e,{signal:n.signal,credentials:"omit"});if(!v.ok)throw new Error(`VAST request failed (${v.status})`);l=await v.text()}finally{clearTimeout(r)}const c=new DOMParser().parseFromString(l,"text/xml");if(c.querySelector("parsererror"))throw new Error("VAST response is not valid XML");const h=c.querySelector("VAST > Ad");if(!h)throw new Error("VAST response contains no ads");Be(h,s);const d=h.querySelector(":scope > Wrapper");if(d){const v=_(d.querySelector("VASTAdTagURI"));if(!v)throw new Error("VAST wrapper without VASTAdTagURI");return he(a,v,t,i+1,s)}const m=h.querySelector(":scope > InLine");if(!m)throw new Error("VAST ad has neither InLine nor Wrapper");const p=m.querySelector("Creatives > Creative > Linear");if(!p)throw new Error("VAST ad has no Linear creative");const f=Ce(p);if(!f)throw new Error("VAST ad has no playable MediaFile");return{roll:a.roll,mediaUrl:f.url,mediaType:f.type,clickThrough:_(p.querySelector("VideoClicks > ClickThrough"))??a.clickUrl,duration:z(_(p.querySelector(":scope > Duration"))),skipOffset:Pe(p.getAttribute("skipoffset"),z(_(p.querySelector(":scope > Duration")))),impressions:s.impressions,tracking:s.tracking,adTitle:_(m.querySelector(":scope > AdTitle"))??void 0}}function Be(a,e){var t,i;for(const s of a.querySelectorAll("Impression")){const n=_(s);n&&e.impressions.push(n)}for(const s of a.querySelectorAll("Linear > TrackingEvents > Tracking")){const n=s.getAttribute("event"),r=_(s);!n||!r||["start","firstQuartile","midpoint","thirdQuartile","complete","skip","pause","resume"].includes(n)&&((t=e.tracking)[n]??(t[n]=[])).push(r)}for(const s of a.querySelectorAll("Linear > VideoClicks > ClickTracking")){const n=_(s);n&&((i=e.tracking).click??(i.click=[])).push(n)}}function Ce(a){const t=[...a.querySelectorAll("MediaFiles > MediaFile")].map(r=>({url:_(r)??"",type:r.getAttribute("type")??void 0,delivery:r.getAttribute("delivery")??"",bitrate:Number(r.getAttribute("bitrate")??0),apiFramework:r.getAttribute("apiFramework")??""})).filter(r=>r.url&&r.apiFramework.toUpperCase()!=="VPAID").filter(r=>!r.type||/(video\/(mp4|webm|ogg)|application\/(x-mpegurl|vnd\.apple\.mpegurl))/i.test(r.type));if(t.length===0)return null;t.sort((r,l)=>r.bitrate-l.bitrate);const i=t.filter(r=>r.delivery!=="streaming"),s=i.length>0?i:t,n=s[Math.floor(s.length/2)];return{url:n.url,type:n.type}}function z(a){if(!a)return;const e=a.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/);if(e)return(e[1]?Number(e[1])*3600:0)+Number(e[2])*60+Number(e[3])+(e[4]?Number(e[4].padEnd(3,"0"))/1e3:0)}function Pe(a,e){if(!a)return;const t=a.trim().match(/^(\d+(?:\.\d+)?)%$/);return t?e!==void 0?Number(t[1])/100*e:void 0:z(a)}function q(a){if(a)for(const e of a)try{new Image().src=e}catch{}}function _(a){return a?.textContent?.trim().replace(/^<!\[CDATA\[|\]\]>$/g,"").trim()||null}class Me{constructor(e,t){this.host=e,this.playedRolls=new Set,this.sourcesSeen=0,this.activeBreak=null,this.layer=null,this.adVideo=null,this.destroyed=!1,this.opts={skipDelay:5,maxWrapperDepth:3,requestTimeout:8e3,mediaTimeout:1e4,playOn:"every",...t}}ensureAdVideo(){if(!this.adVideo){this.adVideo=o("video","imp-ad__video",{playsinline:""});try{this.adVideo.load()}catch{}}return this.adVideo}get adPlaying(){return this.activeBreak!==null}get hasPendingPreRoll(){return this.pending("preRoll").length>0}resetForNewSource(){if(this.sourcesSeen++,this.opts.playOn==="first"&&this.sourcesSeen>1){for(const e of this.opts.adList)this.playedRolls.add(e);return}this.playedRolls.clear()}async playPreRoll(){await this.playRolls(this.pending("preRoll"))}async playPostRoll(){await this.playRolls(this.pending("postRoll"))}checkMidRolls(e){if(this.adPlaying)return;const t=this.pending("midRoll").filter(i=>i.timer!==void 0&&e>=i.timer);t.length>0&&this.playRolls(t)}pending(e){return this.opts.adList.filter(t=>t.roll===e&&!this.playedRolls.has(t))}async playRolls(e){if(e.length===0||this.destroyed)return;if(this.activeBreak)return this.activeBreak;this.ensureAdVideo();const t=(async()=>{const i=this.host.contentVideo,s=!i.paused&&!i.ended;i.pause();for(const n of e){this.playedRolls.add(n);try{const r=await le(n,this.opts);await this.playAd(r)}catch(r){const l=r instanceof Error?r:new Error(String(r));this.host.emitter.emit("aderror",{roll:n,error:l})}if(this.destroyed)return}(s||e[0].roll==="preRoll")&&i.play().catch(()=>{})})();return this.activeBreak=t.finally(()=>{this.activeBreak=null}),this.activeBreak}playAd(e){return new Promise(t=>{const{labels:i}=this.host,s=o("div","imp-ad"),n=this.ensureAdVideo(),r=new AbortController,l=r.signal;n.src=e.mediaUrl,n.muted=this.host.contentVideo.muted,n.volume=this.host.contentVideo.volume;const c=o("div","imp-spinner imp-ad__spinner"),h=o("div","imp-ad__hud"),d=o("span","imp-ad__badge");d.textContent=e.adTitle?`${i.adLabel} · ${e.adTitle}`:i.adLabel;const m=o("span","imp-ad__countdown");h.append(d,m);const p=o("div","imp-ad__actions");let f=null;e.clickThrough&&(f=o("button","imp-ad__visit",{type:"button"}),f.textContent=i.visitAdvertiser,p.append(f));const v=o("button","imp-ad__skip",{type:"button"});v.hidden=!0,p.append(v),s.append(n,c,h,p),this.host.container.append(s),this.layer=s;const y=e.skipOffset??this.opts.skipDelay,u=new Set,k=w=>{u.has(w)||(u.add(w),q(e.tracking[w]))};let P=Date.now(),A=-1;const D=setInterval(()=>{if(n.paused){P=Date.now();return}if(n.currentTime!==A){A=n.currentTime,P=Date.now();return}Date.now()-P>=this.opts.mediaTimeout&&(this.host.emitter.emit("aderror",{roll:{roll:e.roll},error:new Error(`Ad media stalled for ${this.opts.mediaTimeout} ms — skipping`)}),M())},500),M=()=>{clearInterval(D),r.abort(),n.pause(),n.removeAttribute("src"),n.load(),s.remove(),this.layer=null,t()},R=w=>{w?(k("skip"),this.host.emitter.emit("adskip",{ad:e})):k("complete"),this.host.emitter.emit("adend",{ad:e}),M()};n.addEventListener("playing",()=>{q(e.impressions),k("start"),this.host.emitter.emit("adstart",{ad:e})},{once:!0,signal:l}),n.addEventListener("playing",()=>{c.hidden=!0},{signal:l}),n.addEventListener("waiting",()=>{c.hidden=!1},{signal:l}),n.addEventListener("timeupdate",()=>{const w=n.currentTime,T=n.duration;if(Number.isFinite(T)&&T>0&&(m.textContent=b(Math.max(0,T-w)),w/T>=.25&&k("firstQuartile"),w/T>=.5&&k("midpoint"),w/T>=.75&&k("thirdQuartile")),y>=0){const X=Math.ceil(y-w);X>0?(v.hidden=!1,v.disabled=!0,v.textContent=`${i.skipAdIn} ${X}`):(v.hidden=!1,v.disabled=!1,v.textContent=i.skipAd)}},{signal:l}),n.addEventListener("ended",()=>R(!1),{signal:l}),n.addEventListener("error",()=>{this.host.emitter.emit("aderror",{roll:{roll:e.roll},error:new Error("Ad media failed to play")}),M()},{signal:l}),v.addEventListener("click",()=>R(!0));const U=()=>{e.clickThrough&&(k("click"),this.host.emitter.emit("adclick",{ad:e}),window.open(e.clickThrough,"_blank","noopener"),n.pause())};n.addEventListener("click",U,{signal:l}),f?.addEventListener("click",U);let K=!1,N=!1;n.addEventListener("playing",()=>{K=!0},{once:!0,signal:l}),n.addEventListener("pause",()=>{n.ended||!s.isConnected||(s.classList.add("imp-ad--paused"),K&&!N&&(N=!0,q(e.tracking.pause),this.host.emitter.emit("adpause",{ad:e})))},{signal:l}),n.addEventListener("play",()=>{s.classList.remove("imp-ad--paused"),N&&(N=!1,q(e.tracking.resume),this.host.emitter.emit("adresume",{ad:e}))},{signal:l}),s.addEventListener("click",w=>{(w.target===s||s.classList.contains("imp-ad--paused"))&&n.paused&&n.play().catch(()=>{})}),n.play().catch(()=>{s.classList.add("imp-ad--paused")})})}get closeIcon(){return this.host.closeIcon}destroy(){this.destroyed=!0,this.adVideo?.pause(),this.layer?.remove(),this.layer=null,this.adVideo=null}}function j(a,e){const t=[...a].sort((s,n)=>s.start-n.start),i=[];for(let s=0;s<t.length;s++){const n=Math.max(0,t[s].start);if(Number.isFinite(e)&&n>=e)continue;let r=t[s].end??t[s+1]?.start??e;Number.isFinite(e)&&(r=Math.min(r,e)),!(!Number.isFinite(r)||r<=n)&&i.push({start:n,end:r,title:t[s].title})}return i}async function ce(a){const e=await fetch(a);if(!e.ok)throw new Error(`Failed to load chapters VTT (${e.status})`);const t=await e.text();return ie(t).map(i=>({start:i.start,end:i.end,title:i.text}))}function Q(a,e){for(const t of a)if(e>=t.start&&e<t.end)return t;return null}function de(a,e){return e?/application\/(x-mpegurl|vnd\.apple\.mpegurl)/i.test(e):/\.m3u8(\?|#|$)/i.test(a)}let E;async function Ae(){if(E!==void 0)return E;const a=globalThis.Hls;if(a)return E=a,E;try{return E=(await import("hls.js/light")).default,E}catch{return null}}async function Re(a,e,t,i){if(de(e,t)){const s=a.canPlayType("application/vnd.apple.mpegurl"),n=s?null:await Ae();return n&&n.isSupported()?Ne(n,a,e,i):s?(a.src=e,G(a)):(i.onError("HLS is not supported in this browser and hls.js could not be loaded."),G(a))}return a.src=e,G(a)}function G(a){return{kind:"native",levels:[],selected:-1,setLevel(){},destroy(){a.removeAttribute("src"),a.load()}}}function Ne(a,e,t,i){const s=new a({enableWorker:!0}),n={kind:"hls",levels:[],selected:-1,setLevel(h){n.selected=h,s.currentLevel=h},destroy(){s.destroy(),e.removeAttribute("src"),e.load()}};s.on(a.Events.MANIFEST_PARSED,()=>{n.levels=s.levels.map((h,d)=>({index:d,label:h.height?`${h.height}p`:`${Math.round(h.bitrate/1e3)} kbps`})).reverse(),i.onLevels(n.levels)}),s.on(a.Events.LEVEL_SWITCHED,(h,d)=>{const m=s.levels[d.level];m&&i.onLevelSwitch(m.height?`${m.height}p`:`${Math.round(m.bitrate/1e3)} kbps`)});let r=0,l=0,c=!1;return s.on(a.Events.FRAG_BUFFERED,()=>{l=0}),s.on(a.Events.ERROR,(h,d)=>{if(d.fatal)switch(d.type){case a.ErrorTypes.NETWORK_ERROR:l<3?(l++,s.startLoad()):(i.onError(`HLS network error: ${d.details}`,d),s.destroy());break;case a.ErrorTypes.MEDIA_ERROR:r<3?(r++,s.recoverMediaError()):(i.onError(`HLS media error: ${d.details}`,d),s.destroy());break;default:if(c)i.onError(`HLS fatal error: ${d.details}`,d),s.destroy();else{c=!0;try{s.loadSource(t),s.startLoad()}catch{i.onError(`HLS fatal error: ${d.details}`,d),s.destroy()}}}}),s.loadSource(t),s.attachMedia(e),n}class V{constructor(e){this.cues=e}static async load(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to load thumbnails VTT (${t.status})`);const i=await t.text(),s=[];for(const n of ie(i)){const[r,l]=n.text.trim().split("#");if(!r)continue;const c={start:n.start,end:n.end,src:we(r,e)},h=l?.match(/xywh=(\d+),(\d+),(\d+),(\d+)/);h&&(c.xywh={x:Number(h[1]),y:Number(h[2]),w:Number(h[3]),h:Number(h[4])}),s.push(c)}return s.sort((n,r)=>n.start-r.start),new V(s)}cueAt(e){let t=0,i=this.cues.length-1;for(;t<=i;){const s=t+i>>1,n=this.cues[s];if(e<n.start)i=s-1;else if(e>=n.end)t=s+1;else return n}return null}}const Ie='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>',Z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 6-6 6 6 6"/></svg>',qe='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>',Oe='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',$e="(max-width: 767px)",Fe=["--imp-accent","--imp-control-bg","--imp-text","--imp-radius","--imp-transition"];let Y=0;class B{constructor(e){this.anchor=e,this.outsideListener=null,this.escListener=null,this.portal=null,this.homeParent=null,this.homeNext=null,this.fsListener=null,this.root=o("div","imp-menu"),this.root.hidden=!0,this.backdrop=o("div","imp-menu__backdrop"),this.backdrop.hidden=!0,this.backdrop.addEventListener("pointerdown",t=>t.preventDefault()),this.backdrop.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.close()})}get open(){return!this.root.hidden}buildSheetHead(e,t){const i=o("div","imp-menu__sheet-head");if(t){const r=o("button","imp-menu__sheet-back",{type:"button"});r.innerHTML=Z,r.addEventListener("click",t),i.append(r)}else i.append(o("span","imp-menu__sheet-spacer"));const s=o("div","imp-menu__sheet-title");s.textContent=e??this.sheetTitle??this.anchor.getAttribute("aria-label")??this.anchor.textContent??"";const n=o("button","imp-menu__sheet-close",{type:"button"});return n.innerHTML=Oe,n.addEventListener("click",()=>this.close()),i.append(s,n),i}toggle(e){this.open?this.close():this.show(e)}show(e){this.root.textContent="",this.root.append(this.buildSheetHead());for(const t of e)t.items.length!==0&&this.root.append(this.renderSection(t));this.reveal()}toggleSettings(e,t){this.open?this.close():this.showSettings(e,t)}toggleAccordion(e,t,i){this.open?this.close():this.showAccordion(e,t,i)}showAccordion(e,t,i){this.accOpenId=void 0,this.renderAccordion(e,t,i),this.reveal()}renderAccordion(e,t,i){this.root.textContent="",this.root.classList.add("imp-menu--accordion"),this.root.append(this.buildSheetHead());for(const s of e()){const n=this.accOpenId===void 0?s.expanded:s.id===this.accOpenId,r=o("button","imp-menu__acc-head",{type:"button","aria-expanded":String(n)});if(s.icon){const h=o("span","imp-menu__icon");S(h,s.icon),r.append(h)}const l=o("span","imp-menu__acc-title");l.textContent=s.title;const c=o("span","imp-menu__chevron imp-menu__acc-chevron");if(c.innerHTML=qe,r.append(l,c),n&&r.classList.add("imp-menu__acc-head--open"),r.addEventListener("click",()=>{n?this.accOpenId=null:(this.accOpenId=s.id,s.expanded||t(s.id)),this.renderAccordion(e,t,i)}),this.root.append(r),n){const h=o("div","imp-menu__acc-body");for(const d of s.items){const m=o("button","imp-menu__acc-item",{type:"button"});d.active&&m.classList.add("imp-menu__acc-item--active");const p=o("span","imp-menu__acc-label");if(p.textContent=d.label,m.append(p),d.note){const f=o("span","imp-menu__acc-note");f.textContent=d.note,m.append(f)}m.addEventListener("click",()=>{i(s.id,d.value),this.close()}),h.append(m)}this.root.append(h)}}}showSettings(e,t){this.root.classList.add("imp-menu--wide"),this.renderSettingsRoot(t),this.reveal()}renderSettingsRoot(e){this.root.textContent="",this.root.append(this.buildSheetHead());const t=o("div","imp-menu__section");for(const i of e){if(i.toggle){t.append(this.buildToggleRow(i,i.toggle));continue}const s=o("button","imp-menu__item imp-menu__row",{type:"button"}),n=o("span","imp-menu__label");n.textContent=i.label;const r=o("span","imp-menu__value");r.textContent=i.value??"";const l=o("span","imp-menu__chevron");l.innerHTML=Ie,s.append(n,r,l),s.addEventListener("click",()=>this.renderSettingsDetail(e,i)),t.append(s)}this.root.append(t)}buildToggleRow(e,t){const i=o("button","imp-menu__item imp-menu__row imp-menu__toggle",{type:"button",role:"switch","aria-checked":String(t.value)}),s=o("span","imp-menu__label");s.textContent=e.label;const n=o("span","imp-switch");return n.append(o("span","imp-switch__knob")),i.classList.toggle("imp-menu__toggle--on",t.value),i.append(s,n),i.addEventListener("click",()=>{const r=i.getAttribute("aria-checked")!=="true";i.setAttribute("aria-checked",String(r)),i.classList.toggle("imp-menu__toggle--on",r),t.onChange(r)}),i}renderSettingsDetail(e,t){if(!t.section)return;this.root.textContent="",this.root.append(this.buildSheetHead(t.label,()=>this.renderSettingsRoot(e)));const i=o("button","imp-menu__item imp-menu__back",{type:"button"}),s=o("span","imp-menu__chevron");s.innerHTML=Z;const n=o("span","imp-menu__label");n.textContent=t.label,i.append(s,n),i.addEventListener("click",()=>this.renderSettingsRoot(e)),this.root.append(i),this.root.append(this.renderSection(t.section())),this.root.scrollTop=0}renderSection(e){const t=o("div","imp-menu__section");if(e.title){const i=o("div","imp-menu__title");i.textContent=e.title,t.append(i)}for(const i of e.items){const s=o("button","imp-menu__item",{type:"button",role:"menuitemradio"});if(s.setAttribute("aria-checked",String(i.active)),i.active&&s.classList.add("imp-menu__item--active"),i.icon){const r=o("span","imp-menu__icon");S(r,i.icon),s.append(r)}const n=o("span","imp-menu__label");n.textContent=i.label,s.append(n),s.addEventListener("click",()=>{e.onSelect(i.value),this.close()}),t.append(s)}return t}portalize(){if(this.portal)return;this.homeParent=this.root.parentElement,this.homeNext=this.root.nextSibling;const e=o("div","imp-portal"),t=this.anchor.closest(".imp-player");if(t){const i=getComputedStyle(t);for(const s of Fe){const n=i.getPropertyValue(s);n&&e.style.setProperty(s,n)}e.style.fontFamily=i.fontFamily,e.style.color=i.color}e.append(this.backdrop,this.root),(document.fullscreenElement??document.body).append(e),this.portal=e,++Y===1&&document.documentElement.classList.add("imp-scroll-lock"),this.fsListener=()=>this.close(),document.addEventListener("fullscreenchange",this.fsListener)}unportalize(){this.portal&&(this.homeParent&&this.homeParent.isConnected&&(this.homeParent.insertBefore(this.backdrop,this.homeNext),this.homeParent.insertBefore(this.root,this.homeNext)),this.portal.remove(),this.portal=null,--Y===0&&document.documentElement.classList.remove("imp-scroll-lock"),this.fsListener&&(document.removeEventListener("fullscreenchange",this.fsListener),this.fsListener=null))}reveal(){if(typeof window<"u"&&window.matchMedia($e).matches)this.portalize();else{const e=this.root.parentElement;e&&this.backdrop.parentElement!==e&&e.insertBefore(this.backdrop,this.root)}this.root.hidden=!1,this.backdrop.hidden=!1,this.anchor.setAttribute("aria-expanded","true"),this.outsideListener=e=>{const t=e.target;this.backdrop.contains(t)||!this.root.contains(t)&&!this.anchor.contains(t)&&this.close()},this.escListener=e=>{e.key==="Escape"&&this.close()},document.addEventListener("keydown",this.escListener),setTimeout(()=>{this.outsideListener&&document.addEventListener("pointerdown",this.outsideListener)},0)}close(){this.root.hidden=!0,this.root.classList.remove("imp-menu--wide"),this.root.classList.remove("imp-menu--accordion"),this.accOpenId=void 0,this.anchor.setAttribute("aria-expanded","false"),this.unportalize(),this.backdrop.hidden=!0,this.outsideListener&&(document.removeEventListener("pointerdown",this.outsideListener),this.outsideListener=null),this.escListener&&(document.removeEventListener("keydown",this.escListener),this.escListener=null)}destroy(){this.close(),this.backdrop.remove(),this.root.remove()}}let Ve=0;const W=.85;class De{constructor(e,t="Seek"){this.cb=e,this.segments=[],this.duration=0,this.chapters=[],this.thumbnails=null,this.scrubbing=!1,this.heatmapClipRect=null,this.lastRatio=0,this.root=o("div","imp-progress",{role:"slider","aria-label":t,tabindex:"-1"}),this.buffered=o("div","imp-progress__buffered"),this.track=o("div","imp-progress__track"),this.handle=o("div","imp-progress__handle"),this.tooltipThumb=o("div","imp-progress__thumb"),this.tooltipThumbBox=o("div","imp-progress__thumb-box"),this.tooltipThumbBox.append(this.tooltipThumb),this.tooltipChapter=o("div","imp-progress__tooltip-chapter"),this.tooltipTime=o("div","imp-progress__tooltip-time"),this.tooltipCaption=o("div","imp-progress__caption"),this.tooltipCaption.append(this.tooltipChapter,this.tooltipTime),this.tooltip=o("div","imp-progress__tooltip"),this.tooltip.append(this.tooltipThumbBox,this.tooltipCaption),this.heatmap=o("div","imp-progress__heatmap"),this.heatmap.hidden=!0,this.root.append(this.heatmap,this.buffered,this.track,this.handle,this.tooltip),this.setChapters([]),this.bindPointer()}setHeatmap(e,t=1){if(e.length===0){this.heatmap.hidden=!0,this.heatmap.textContent="",this.heatmapClipRect=null;return}const i=ae(e,t),s=`imp-hm-clip-${++Ve}`;this.heatmap.innerHTML=`<svg viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><defs><clipPath id="${s}"><rect x="0" y="0" width="0" height="100"/></clipPath></defs><path d="${i}"/><path class="imp-progress__heatmap-played" d="${i}" clip-path="url(#${s})"/></svg>`,this.heatmapClipRect=this.heatmap.querySelector("clipPath rect"),this.heatmapClipRect?.setAttribute("width",String(this.lastRatio*1e3)),this.heatmap.hidden=!1}setDuration(e){this.duration=Number.isFinite(e)?e:0,this.root.classList.toggle("imp-progress--live",!Number.isFinite(e)),this.chapters.length===0&&this.setChapters([])}setChapters(e){this.chapters=e,this.track.textContent="",this.segments=[];const t=e.length>0?e:[{start:0,end:this.duration||1,title:""}],i=[];let s=0;for(const n of t)n.start>s&&i.push({start:s,end:n.start,title:""}),i.push(n),s=n.end;this.duration>0&&s<this.duration&&i.push({start:s,end:this.duration,title:""});for(const n of i){const r=o("div","imp-progress__segment");r.style.flexGrow=String(Math.max(n.end-n.start,.01));const l=o("div","imp-progress__fill");r.append(l),this.track.append(r),this.segments.push({chapter:n,root:r,fill:l})}}setThumbnails(e){this.thumbnails=e}update(e,t,i){if(t!==this.duration&&Number.isFinite(t)&&this.setDuration(t),this.scrubbing)return;this.render(e);const s=this.duration>0?x(i/this.duration,0,1):0;this.buffered.style.width=`${s*100}%`,this.root.setAttribute("aria-valuemin","0"),this.root.setAttribute("aria-valuemax",String(Math.round(this.duration))),this.root.setAttribute("aria-valuenow",String(Math.round(e))),this.root.setAttribute("aria-valuetext",`${b(e)} / ${b(this.duration)}`)}render(e){for(const{chapter:i,fill:s}of this.segments){const n=i.end-i.start,r=n>0?x((e-i.start)/n,0,1):0;s.style.transform=`scaleX(${r})`}const t=this.duration>0?x(e/this.duration,0,1):0;this.lastRatio=t,this.heatmapClipRect?.setAttribute("width",String(t*1e3))}timeFromEvent(e){const t=this.root.getBoundingClientRect();return(t.width>0?x((e.clientX-t.left)/t.width,0,1):0)*this.duration}bindPointer(){this.root.addEventListener("pointerdown",e=>{this.duration<=0||(e.preventDefault(),this.scrubbing=!0,this.root.classList.add("imp-progress--scrubbing"),this.root.setPointerCapture(e.pointerId),this.cb.onScrubStart(),this.render(this.timeFromEvent(e)),this.showTooltip(e))}),this.root.addEventListener("pointermove",e=>{this.duration<=0||(this.showTooltip(e),this.scrubbing&&this.render(this.timeFromEvent(e)))}),this.root.addEventListener("pointerup",e=>{this.scrubbing&&(this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onSeek(this.timeFromEvent(e)),this.cb.onScrubEnd())}),this.root.addEventListener("pointercancel",()=>{this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onScrubEnd()}),this.root.addEventListener("pointerleave",()=>this.hideTooltip())}showTooltip(e){const t=this.timeFromEvent(e);this.tooltipTime.textContent=b(t);const i=Q(this.chapters,t),s=!!i?.title;this.tooltipChapter.textContent=i?.title??"",this.tooltipChapter.hidden=!s,this.tooltipCaption.classList.toggle("imp-progress__caption--time-only",!s);const n=this.thumbnails?.cueAt(t)??null;if(this.tooltip.classList.toggle("imp-progress__tooltip--thumb",!!n),n){const h=n.xywh?.w??160,d=n.xywh?.h??90;this.tooltipThumbBox.hidden=!1,this.tooltipThumbBox.style.width=`${Math.round(h*W)}px`,this.tooltipThumbBox.style.height=`${Math.round(d*W)}px`,this.tooltipThumb.style.width=`${h}px`,this.tooltipThumb.style.height=`${d}px`,this.tooltipThumb.style.transform=`scale(${W})`,this.tooltipThumb.style.backgroundImage=`url("${n.src}")`,n.xywh?(this.tooltipThumb.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,this.tooltipThumb.style.backgroundSize="auto"):(this.tooltipThumb.style.backgroundPosition="center",this.tooltipThumb.style.backgroundSize="cover")}else this.tooltipThumbBox.hidden=!0;this.tooltip.classList.add("imp-progress__tooltip--visible");const r=this.root.getBoundingClientRect(),l=x(e.clientX-r.left,0,r.width);this.handle.style.left=`${l}px`;const c=this.tooltip.offsetWidth/2;this.tooltip.style.left=`${x(l,c,Math.max(c,r.width-c))}px`}hideTooltip(){this.tooltip.classList.remove("imp-progress__tooltip--visible")}}class He{constructor(e){this.player=e,this.rightItems=new Map,this.subtitlesBtn=null,this.settingsBtn=null,this.settingsMenu=null,this.subtitlesMenu=null,this.moreMenu=null,this.moreWrap=null,this.qualityBtn=null,this.qualityMenu=null,this.gearBtn=null,this.gearMenu=null,this.gear={speed:!1,quality:!1,subtitles:!1},this.nextPreviewEl=null,this.nextPreviewOpts=null,this.scenesBtn=null,this.sceneTypeBtn=null,this.sceneTypeMenu=null,this.likeBtn=null,this.dislikeBtn=null,this.likeCountEl=null,this.dislikeCountEl=null,this.prevBtn=null,this.nextBtn=null,this.seekBackBtn=null,this.seekFwdBtn=null,this.centerPlayBtn=null,this.centerPrevBtn=null,this.centerNextBtn=null,this.collapsibles=[],this.overflowed=new Set,this.resizeObserver=null,this.reflowScheduled=!1,this.actionItems=[],this.wasPlayingBeforeScrub=!1,this.disposers=[],this.onWindowResize=null;const{labels:t,icons:i}=e,s=e.controlsOptions;this.root=o("div","imp-controls"),s.heatmap==="always"&&e.container.classList.add("imp-player--heatmap-always"),s.volume==="always"&&e.container.classList.add("imp-player--volume-always"),this.progress=new De({onSeek:u=>e.seek(u),onScrubStart:()=>{e.scrubbing=!0,this.wasPlayingBeforeScrub=!e.paused,e.pause()},onScrubEnd:()=>{e.scrubbing=!1,this.wasPlayingBeforeScrub?e.play(!0):e.started||e.play()}},e.labels.seek),s.progress&&this.root.append(this.progress.root);const n=o("div","imp-controls__row");this.row=n,this.root.append(n);const r=o("div","imp-controls__group"),l=o("div","imp-controls__group");this.rightGroup=l;const c=o("div","imp-controls__spacer");this.chapterLabel=o("div","imp-controls__chapter"),n.append(r,c,l),c.append(this.chapterLabel);const h=typeof s.seekButtons=="object"?s.seekButtons:{},d=h.back??e.seekStep,m=h.forward??e.seekStep;if(this.seekLabelFn=h.label,s.playlist&&e.hasPlaylist&&!s.hidePrev&&(this.prevBtn=g("imp-btn--prev",t.previous,i.previous),this.prevBtn.addEventListener("click",()=>e.previous()),r.append(this.prevBtn)),s.seekButtons&&(this.seekBackBtn=g("imp-btn--seek-back",`${t.seekBack} ${d}s`,i.seekBack),this.addStepBadge(this.seekBackBtn,d,"back"),this.seekBackBtn.addEventListener("click",()=>e.skip(-d)),r.append(this.seekBackBtn)),s.play&&(this.playBtn=g("imp-btn--play",t.play,i.play),this.playBtn.addEventListener("click",()=>e.togglePlay()),r.append(this.playBtn)),s.seekButtons&&(this.seekFwdBtn=g("imp-btn--seek-forward",`${t.seekForward} ${m}s`,i.seekForward),this.addStepBadge(this.seekFwdBtn,m,"forward"),this.seekFwdBtn.addEventListener("click",()=>e.skip(m)),r.append(this.seekFwdBtn)),s.playlist&&e.hasPlaylist&&!s.hideNext&&(this.nextBtn=g("imp-btn--next",t.next,i.next),this.nextBtn.addEventListener("click",()=>e.next()),r.append(this.nextBtn)),s.volume){const u=o("div","imp-volume");this.muteBtn=g("imp-btn--mute",t.mute,i.volumeHigh),this.muteBtn.addEventListener("click",()=>e.toggleMute()),this.volumeSlider=o("input","imp-volume__slider",{type:"range",min:"0",max:"1",step:"0.05","aria-label":t.volume}),this.volumeSlider.addEventListener("input",()=>{e.setVolume(Number(this.volumeSlider.value))}),u.append(this.muteBtn,this.volumeSlider),r.append(u)}s.time&&(this.timeLabel=o("div","imp-controls__time"),this.timeCurrent=o("span","imp-controls__time-current"),this.timeTotal=o("span","imp-controls__time-total"),this.timeLabel.append(this.timeCurrent,this.timeTotal),this.liveBadge=o("span","imp-controls__live"),this.liveBadge.textContent=t.live,this.liveBadge.hidden=!0,r.append(this.timeLabel,this.liveBadge)),this.buildLikeDislike();for(const u of(e.actionsOptions.custom??[]).filter(k=>k.placement==="bar")){const k=g(`imp-btn--custom imp-btn--custom-${u.id}`,u.title,u.icon??i.more);k.addEventListener("click",()=>e.emit("customaction",{id:u.id})),this.rightItems.set(`custom:${u.id}`,k),this.registerCollapsible({key:`custom:${u.id}`,el:k,priority:55,available:()=>!0,section:()=>this.simpleSection(`custom:${u.id}`,u.title,u.icon??i.more,()=>e.emit("customaction",{id:u.id}))})}const p=u=>u===!1?"off":u==="bar"?"bar":"gear",f=p(s.subtitles),v=p(s.quality),y=p(s.speed);if(this.gear={speed:y==="gear",quality:v==="gear",subtitles:f==="gear"},f==="bar"){this.subtitlesBtn=g("imp-btn--subtitles",t.subtitles,i.subtitles),this.subtitlesMenu=new B(this.subtitlesBtn);const u=o("div","imp-controls__menu-anchor");u.append(this.subtitlesBtn,this.subtitlesMenu.root),this.subtitlesBtn.addEventListener("click",()=>this.toggleSubtitlesMenu()),this.rightItems.set("subtitles",u),this.registerCollapsible({key:"subtitles",el:u,priority:30,available:()=>e.subtitleTracks.length>0,section:()=>this.subtitlesSection()})}if(v==="bar"){this.qualityBtn=g("imp-btn--quality",t.quality,i.settings),this.qualityMenu=new B(this.qualityBtn);const u=o("div","imp-controls__menu-anchor");u.append(this.qualityBtn,this.qualityMenu.root),this.qualityBtn.addEventListener("click",()=>this.toggleQualityMenu()),this.rightItems.set("quality",u),this.registerCollapsible({key:"quality",el:u,priority:10,available:()=>e.qualityLevels.length>0,section:()=>this.qualitySection()})}if(y==="bar"){this.settingsBtn=g("imp-btn--speed",t.speed,i.speed),this.settingsMenu=new B(this.settingsBtn);const u=o("div","imp-controls__menu-anchor");u.append(this.settingsBtn,this.settingsMenu.root),this.settingsBtn.addEventListener("click",()=>this.toggleSettingsMenu()),this.rightItems.set("speed",u),this.registerCollapsible({key:"speed",el:u,priority:40,available:()=>!0,section:()=>this.speedSection()})}if(s.scenes&&(this.scenesBtn=g("imp-btn--scenes",t.scenes,i.scenes),this.scenesBtn.addEventListener("click",()=>e.toggleScenesPanel()),this.rightItems.set("scenes",this.scenesBtn),this.registerCollapsible({key:"scenes",el:this.scenesBtn,priority:25,available:()=>e.chapterList.length>0,section:()=>this.simpleSection("scenes",t.scenes,i.scenes,()=>e.toggleScenesPanel())})),s.sceneTypes!==!1){this.sceneTypeBtn=o("button","imp-btn imp-btn--scene-types",{type:"button"}),this.sceneTypeMenu=new B(this.sceneTypeBtn),this.sceneTypeMenu.sheetTitle=e.labels.sceneTypes;const u=o("div","imp-controls__menu-anchor");u.append(this.sceneTypeBtn,this.sceneTypeMenu.root),this.sceneTypeBtn.addEventListener("click",()=>this.toggleSceneTypeMenu()),this.rightItems.set("sceneTypes",u),this.refreshSceneTypeButton(),this.registerCollapsible({key:"sceneTypes",el:u,priority:68,available:()=>e.sceneTypes.length>0,section:()=>this.sceneTypeSection()})}if(s.playlist&&e.hasPlaylist&&s.playlistButton!==!1){const u=g("imp-btn--list",t.playlist,i.list);u.addEventListener("click",()=>e.togglePlaylistPanel()),this.rightItems.set("playlist",u),this.registerCollapsible({key:"list",el:u,priority:50,available:()=>!0,section:()=>this.simpleSection("list",t.playlist,i.list,()=>e.togglePlaylistPanel())})}if(s.pip&&"requestPictureInPicture"in HTMLVideoElement.prototype){const u=g("imp-btn--pip",t.pip,i.pip);u.addEventListener("click",()=>void e.togglePip()),this.rightItems.set("pip",u),this.registerCollapsible({key:"pip",el:u,priority:20,available:()=>!0,section:()=>this.simpleSection("pip",t.pip,i.pip,()=>void e.togglePip())})}if(s.fullscreen&&(this.fullscreenBtn=g("imp-btn--fullscreen",t.fullscreen,i.fullscreen),this.fullscreenBtn.addEventListener("click",()=>void e.toggleFullscreen()),this.rightItems.set("fullscreen",this.fullscreenBtn)),this.prevBtn&&this.registerCollapsible({key:"prev",el:this.prevBtn,priority:70,available:()=>!0,section:()=>e.hasPrevious?this.simpleSection("prev",t.previous,i.previous,()=>e.previous()):null}),this.nextBtn&&this.registerCollapsible({key:"next",el:this.nextBtn,priority:72,available:()=>!0,section:()=>e.hasNext?this.simpleSection("next",t.next,i.next,()=>e.next()):null}),this.seekBackBtn){const u=this.seekBackBtn;this.registerCollapsible({key:"seekBack",el:u,priority:80,available:()=>Number.isFinite(e.duration)&&e.duration>0,section:()=>this.simpleSection("seekBack",`${t.seekBack} ${d}s`,i.seekBack,()=>e.skip(-d))})}if(this.seekFwdBtn){const u=this.seekFwdBtn;this.registerCollapsible({key:"seekFwd",el:u,priority:82,available:()=>Number.isFinite(e.duration)&&e.duration>0,section:()=>this.simpleSection("seekFwd",`${t.seekForward} ${m}s`,i.seekForward,()=>e.skip(m))})}if(this.center=o("div","imp-center-controls"),s.playlist&&e.hasPlaylist&&(this.centerPrevBtn=this.makeCenterButton("prev",t.previous,i.previous),this.centerPrevBtn.addEventListener("click",()=>e.previous()),this.center.append(this.centerPrevBtn)),s.seekButtons){const u=this.makeCenterButton("seek-back",`${t.seekBack} ${d}s`,i.seekBack);this.addStepBadge(u,d,"back",!0),u.addEventListener("click",()=>e.skip(-d)),this.center.append(u)}if(s.play&&(this.centerPlayBtn=this.makeCenterButton("play",t.play,i.play),this.centerPlayBtn.addEventListener("click",()=>e.togglePlay()),this.center.append(this.centerPlayBtn)),s.seekButtons){const u=this.makeCenterButton("seek-forward",`${t.seekForward} ${m}s`,i.seekForward);this.addStepBadge(u,m,"forward",!0),u.addEventListener("click",()=>e.skip(m)),this.center.append(u)}if(s.playlist&&e.hasPlaylist&&(this.centerNextBtn=this.makeCenterButton("next",t.next,i.next),this.centerNextBtn.addEventListener("click",()=>e.next()),this.center.append(this.centerNextBtn)),this.center.style.display="none",this.setupNextPreview(),this.gear.speed||this.gear.quality||this.gear.subtitles){this.gearBtn=g("imp-btn--settings",t.settings,i.settings),this.gearMenu=new B(this.gearBtn);const u=o("div","imp-controls__menu-anchor imp-controls__gear");u.append(this.gearBtn,this.gearMenu.root),this.gearBtn.addEventListener("click",()=>this.toggleGearMenu()),this.rightItems.set("gear",u),this.registerCollapsible({key:"gear",el:u,priority:40,available:()=>this.gearSections().length>0,section:()=>this.gearSections()})}this.layoutRightCluster(l),this.buildMoreDropdown(l),this.bind(),this.syncVolume(),this.syncPlayState(),this.setLikeState(e.actionsOptions.likeState??null),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.scheduleReflow()),this.resizeObserver.observe(e.container)),this.onWindowResize=()=>this.scheduleReflow(),window.addEventListener("resize",this.onWindowResize)}registerCollapsible(e){this.collapsibles.push(e)}layoutRightCluster(e){const t=[...this.rightItems.keys()],i=this.player.controlsOptions.order;let s=t;if(i.length>0){const n=new Set;s=[];for(const r of i)this.rightItems.has(r)&&!n.has(r)&&(s.push(r),n.add(r));for(const r of t)n.has(r)||s.push(r)}for(const n of s){const r=this.rightItems.get(n);r&&e.append(r)}}makeCenterButton(e,t,i){const s=o("button",`imp-center-btn imp-center-btn--${e}`,{type:"button","aria-label":t,title:t});return S(s,i),s}addStepBadge(e,t,i,s=!1){const n=o("span","imp-seek-num");n.textContent=this.seekLabelFn?this.seekLabelFn(t,i):s?String(t):`${i==="back"?"−":"+"}${t}${this.player.labels.secondsShort}`,e.append(n)}gearSections(){const e=this.player,t=[];return this.gear.quality&&e.qualityLevels.length>0&&t.push(this.qualitySection()),this.gear.speed&&t.push(this.speedSection()),this.gear.subtitles&&e.subtitleTracks.length>0&&t.push(this.subtitlesSection()),t}gearEntries(){const e=this.player,t=[];if(e.hasPlaylist&&t.push({key:"autoplay",label:e.labels.autoplay,toggle:{value:e.autoAdvance,onChange:i=>e.setAutoAdvance(i)}}),this.gear.quality&&e.qualityLevels.length>0){const i=e.currentQuality===-1?e.labels.qualityAuto:e.qualityLevels.find(s=>s.index===e.currentQuality)?.label??e.labels.qualityAuto;t.push({key:"quality",label:e.labels.quality,value:i,section:()=>this.qualitySection()})}if(this.gear.speed){const i=e.playbackRate;t.push({key:"speed",label:e.labels.speed,value:i===1?e.labels.speedNormal:`${i}×`,section:()=>this.speedSection()})}if(this.gear.subtitles&&e.subtitleTracks.length>0){const i=e.activeSubtitle===-1?e.labels.subtitlesOff:e.subtitleTracks[e.activeSubtitle]?.label??e.labels.subtitlesOff;t.push({key:"subtitles",label:e.labels.subtitles,value:i,section:()=>this.subtitlesSection()})}return t}refreshSceneTypeButton(){const e=this.sceneTypeBtn;if(!e)return;const t=this.player.activeSceneType;if(e.textContent="",!t)return;if(t.icon){const s=o("span","imp-scene-type__icon");S(s,t.icon),e.append(s)}const i=o("span","imp-scene-type__label");i.textContent=t.title,e.append(i),e.setAttribute("aria-label",`${this.player.labels.sceneTypes}: ${t.title}`),e.title=t.title}sceneTypeSection(){const e=this.player;return{title:e.labels.sceneTypes,items:e.sceneTypes.map(t=>({label:t.title,value:t.id,icon:t.icon,active:t.id===(e.activeSceneType?.id??"")})),onSelect:t=>{e.setSceneGroup(t),this.refreshSceneTypeButton()}}}sceneAccordionGroups(){const e=this.player,t=e.activeSceneType?.id??"",i=e.video.currentTime,s=n=>{let r;for(const l of n)l.start<=i&&(r===void 0||l.start>r)&&(r=l.start);return r};return e.sceneTypes.map(n=>{const r=n.id===t?e.chapterList:n.scenes,l=s(r);return{id:n.id,title:n.title,icon:n.icon,expanded:n.id===t,items:r.map(c=>({label:c.title||b(c.start),note:b(c.start),value:String(c.start),active:l!==void 0&&c.start===l}))}})}toggleSceneTypeMenu(){if(!(!this.sceneTypeMenu||this.player.sceneTypes.length===0)){if(this.externalMenus()){const e=this.player;e.emit("menurequest",{kind:"sceneTypes",title:e.labels.sceneTypes,groups:this.sceneAccordionGroups().map(t=>({id:t.id,title:t.title,icon:t.icon,active:t.expanded,scenes:t.items.map(i=>({label:i.label,time:i.note??"",start:Number(i.value),current:i.active}))})),activate:t=>{e.setSceneGroup(t),this.refreshSceneTypeButton()},select:(t,i)=>{t!==(e.activeSceneType?.id??"")&&(e.setSceneGroup(t),this.refreshSceneTypeButton()),e.seek(i),e.play(!0)}});return}this.closeMenus(this.sceneTypeMenu),this.sceneTypeMenu.toggleAccordion(()=>this.sceneAccordionGroups(),e=>{this.player.setSceneGroup(e),this.refreshSceneTypeButton()},(e,t)=>{e!==(this.player.activeSceneType?.id??"")&&(this.player.setSceneGroup(e),this.refreshSceneTypeButton()),this.player.seek(Number(t)),this.player.play(!0)})}}toggleGearMenu(){if(!this.gearMenu)return;const e=this.gearEntries();if(e.length!==0){if(this.externalMenus()){this.player.emit("menurequest",{kind:"settings",title:this.player.labels.settings,entries:e.map(t=>({key:t.key,label:t.label,value:t.value,toggle:t.toggle?{value:t.toggle.value,set:t.toggle.onChange}:void 0,options:t.section?t.section().items.map(({label:i,value:s,active:n})=>({label:i,value:s,active:n})):void 0,select:t.section?i=>t.section().onSelect(i):void 0}))});return}this.closeMenus(this.gearMenu),this.gearMenu.toggleSettings(this.player.labels.settings,e)}}externalMenus(){const e=this.player.menusMode;return e==="external"?!0:e==="external-mobile"?typeof window<"u"&&window.matchMedia("(max-width: 767px)").matches:!1}toExternalSection(e){return{title:e.title,items:e.items.map(({label:t,value:i,active:s})=>({label:t,value:i,active:s})),select:t=>e.onSelect(t)}}requestExternalMenu(e,t){return this.externalMenus()?(this.player.emit("menurequest",{kind:"menu",title:e,sections:t.map(i=>this.toExternalSection(i))}),!0):!1}setupNextPreview(){const e=this.player,t=e.controlsOptions;if(t.nextPreview===!1||!t.playlist||!e.hasPlaylist)return;const i=typeof t.nextPreview=="object"?t.nextPreview:{};this.nextPreviewOpts={thumbnail:i.thumbnail??!0,title:i.title??!0,duration:i.duration??!0,meta:i.meta??!0},this.nextPreviewEl=o("div","imp-next-preview"),this.nextPreviewEl.hidden=!0,e.container.append(this.nextPreviewEl),this.nextBtn&&this.bindNextPreview(this.nextBtn),this.centerNextBtn&&this.bindNextPreview(this.centerNextBtn)}bindNextPreview(e){e.addEventListener("pointerenter",t=>{t.pointerType==="mouse"&&this.showNextPreview(e)}),e.addEventListener("pointerleave",()=>this.hideNextPreview()),e.addEventListener("click",()=>this.hideNextPreview())}showNextPreview(e){const t=this.nextPreviewEl,i=this.nextPreviewOpts;if(!t||!i)return;const s=this.player.nextSource;if(!s){this.hideNextPreview();return}t.textContent="";const n=o("div","imp-next-preview__kicker");n.textContent=this.player.labels.nextVideo;const r=C.posterSrc(s.poster);let l=null;if(i.thumbnail&&r){l=o("div","imp-next-preview__thumb");const y=L(r);if(y.addEventListener("error",()=>{this.player.markSourceDead(s),this.nextPreviewEl&&!this.nextPreviewEl.hidden&&this.showNextPreview(e)},{once:!0}),l.append(y,n),i.duration&&s.duration){const u=o("span","imp-next-preview__duration");u.textContent=b(s.duration),l.append(u)}t.append(l)}const c=o("div","imp-next-preview__info");if(l||c.append(n),i.title&&s.title){const y=o("div","imp-next-preview__title");y.textContent=s.title,c.append(y)}i.meta&&s.previewMeta?.length&&c.append(te(s.previewMeta,"imp-next-preview")),c.childElementCount>0&&t.append(c),t.hidden=!1;const h=this.player.container.getBoundingClientRect(),d=e.getBoundingClientRect(),m=8,p=t.offsetWidth,f=d.left-h.left+d.width/2-p/2,v=Math.max(m,Math.min(f,h.width-p-m));t.style.left=`${v}px`,t.style.bottom=`${h.height-(d.top-h.top)+4}px`}hideNextPreview(){this.nextPreviewEl&&(this.nextPreviewEl.hidden=!0)}buildLikeDislike(){const e=this.player,t=e.actionsOptions,{labels:i,icons:s}=e;if(t.like){this.likeBtn=g("imp-btn--like",i.like,s.like),this.likeBtn.addEventListener("click",()=>e.emit("action",{id:"like"})),this.likeCountEl=this.attachCountTooltip(this.likeBtn,t.likeCount);const n=this.wrapWithTooltip(this.likeBtn,this.likeCountEl);this.rightItems.set("like",n),this.registerCollapsible({key:"like",el:n,priority:62,available:()=>!0,section:()=>this.simpleSection("like",i.like,s.like,()=>e.emit("action",{id:"like"}))})}if(t.dislike){this.dislikeBtn=g("imp-btn--dislike",i.dislike,s.dislike),this.dislikeBtn.addEventListener("click",()=>e.emit("action",{id:"dislike"})),this.dislikeCountEl=this.attachCountTooltip(this.dislikeBtn,t.dislikeCount);const n=this.wrapWithTooltip(this.dislikeBtn,this.dislikeCountEl);this.rightItems.set("dislike",n),this.registerCollapsible({key:"dislike",el:n,priority:60,available:()=>!0,section:()=>this.simpleSection("dislike",i.dislike,s.dislike,()=>e.emit("action",{id:"dislike"}))})}}attachCountTooltip(e,t){const i=o("span","imp-count-tooltip");return this.setCountText(i,t),i}wrapWithTooltip(e,t){const i=o("div","imp-action");return i.append(e,t),i}setCountText(e,t){const i=t==null||t===""?"":String(t);e.textContent=i,e.hidden=i===""}setLikeCounts(e,t){this.likeCountEl&&e!==void 0&&this.setCountText(this.likeCountEl,e),this.dislikeCountEl&&t!==void 0&&this.setCountText(this.dislikeCountEl,t)}setLikeState(e){this.likeBtn?.classList.toggle("imp-btn--active",e==="like"),this.dislikeBtn?.classList.toggle("imp-btn--active",e==="dislike")}buildMoreDropdown(e){const t=this.player,i=t.actionsOptions,{labels:s,icons:n}=t;if(t.controlsOptions.more===!1)return;i.addTo&&this.actionItems.push({value:"addTo",label:s.addTo,icon:n.addTo,run:()=>t.emit("action",{id:"addTo"})}),i.share&&this.actionItems.push({value:"share",label:s.share,icon:n.share,run:()=>void t.share()}),i.report&&this.actionItems.push({value:"report",label:s.report,icon:n.report,run:()=>t.emit("action",{id:"report"})});for(const c of(i.custom??[]).filter(h=>h.placement!=="bar"))this.actionItems.push({value:`custom:${c.id}`,label:c.title,icon:c.icon,run:()=>t.emit("customaction",{id:c.id})});const r=g("imp-btn--more",s.more,n.more);this.moreMenu=new B(r),this.moreMenu.sheetTitle=t.labels.more;const l=o("div","imp-controls__menu-anchor imp-controls__more");l.append(r,this.moreMenu.root),r.addEventListener("click",()=>{this.requestExternalMenu(t.labels.more,this.buildMoreSections())||(this.closeMenus(this.moreMenu),this.moreMenu?.toggle(this.buildMoreSections()))}),e.append(l),this.moreWrap=l}buildMoreSections(){const e=[],t=new Map,i=[],s=["prev","next","seekBack","seekFwd","like","dislike","scenes","sceneTypes","pip","list","subtitles","speed","quality","gear"],n=l=>{const c=s.indexOf(l);return c===-1?s.length:c},r=this.collapsibles.filter(l=>this.overflowed.has(l.key)&&l.available()).sort((l,c)=>n(l.key)-n(c.key));for(const l of r){const c=l.section();if(c)for(const h of Array.isArray(c)?c:[c])if(!h.title&&h.items.length===1){const d=h.items[0];i.push(d),t.set(d.value,()=>h.onSelect(d.value))}else e.push(h)}if(i.length>0&&e.unshift({title:"",items:i,onSelect:l=>t.get(l)?.()}),this.actionItems.length>0){const l=new Map(this.actionItems.map(c=>[c.value,c.run]));e.push({title:"",items:this.actionItems.map(({value:c,label:h,icon:d})=>({value:c,label:h,icon:d,active:!1})),onSelect:c=>l.get(c)?.()})}return e}simpleSection(e,t,i,s){return{title:"",items:[{value:e,label:t,icon:i,active:!1}],onSelect:()=>s()}}speedSection(){const e=this.player;return{title:e.labels.speed,items:e.playbackRates.map(t=>({label:t===1?e.labels.speedNormal:`${t}×`,value:String(t),active:e.playbackRate===t})),onSelect:t=>e.setPlaybackRate(Number(t))}}qualitySection(){const e=this.player;return{title:e.labels.quality,items:[...e.qualityAutoAvailable?[{label:e.labels.qualityAuto,value:"-1",active:e.currentQuality===-1}]:[],...e.qualityLevels.map(t=>({label:t.label,value:String(t.index),active:e.currentQuality===t.index}))],onSelect:t=>e.setQuality(Number(t))}}subtitlesSection(){const e=this.player;return{title:e.labels.subtitles,items:[{label:e.labels.subtitlesOff,value:"-1",active:e.activeSubtitle===-1},...e.subtitleTracks.map((t,i)=>({label:t.label,value:String(i),active:e.activeSubtitle===i}))],onSelect:t=>e.setSubtitle(Number(t))}}scheduleReflow(){this.reflowScheduled||(this.reflowScheduled=!0,requestAnimationFrame(()=>{this.reflowScheduled=!1,this.reflow()}))}reflow(){const e=window.innerWidth<=767,t=e&&this.player.controlsOptions.mobileLayout==="center",s=this.player.controlsOptions.seekPlacement!=="bar"||e;this.center.style.display=s?"flex":"none",this.centerPrevBtn&&(this.centerPrevBtn.style.display=t?"":"none"),this.centerNextBtn&&(this.centerNextBtn.style.display=t?"":"none"),this.playBtn&&(this.playBtn.style.display=t?"none":"");const n=h=>h==="seekBack"||h==="seekFwd"?s:h==="prev"||h==="next"?t:!1;this.overflowed.clear(),this.moreWrap&&(this.moreWrap.style.display=this.actionItems.length>0?"":"none");for(const h of this.collapsibles){if(n(h.key)){h.el.style.display="none";continue}const d=h.available();h.el.style.display=d?"":"none",h.el.classList.remove("imp-collapsed")}const r=typeof window<"u"&&window.matchMedia("(max-width: 767px)").matches,l=this.player.controlsOptions.more===!1?[]:this.collapsibles.filter(h=>h.available()&&!n(h.key)&&!(r&&h.key==="gear")).sort((h,d)=>h.priority-d.priority);let c=l.length;for(;c-- >0&&this.overflowsRow();){const h=l.find(d=>!this.overflowed.has(d.key));if(!h)break;h.el.style.display="none",h.el.classList.add("imp-collapsed"),this.overflowed.add(h.key)}if(this.moreWrap){const h=this.actionItems.length>0||this.overflowed.size>0;this.moreWrap.style.display=h?"":"none"}}overflowsRow(){const e=this.row.getBoundingClientRect().right;return this.rightGroup.getBoundingClientRect().right>e+1}seedPrestart(e,t){const i=this.player;this.progress.update(e,t,i.bufferedEnd),this.timeLabel&&!i.live&&(this.timeLabel.hidden=!1,this.liveBadge.hidden=!0,this.timeCurrent.textContent=b(e),this.timeTotal.textContent=` / ${b(t)}`);let s=null;for(const n of i.chapterList)n.start<=e&&(s=n);this.chapterLabel.textContent=s?.title??""}bind(){const e=this.player;this.disposers.push(e.on("timeupdate",({currentTime:t,duration:i})=>{this.progress.update(t,i,e.bufferedEnd),this.timeLabel&&(e.live?(this.timeLabel.hidden=!0,this.liveBadge.hidden=!1):(this.timeLabel.hidden=!1,this.liveBadge.hidden=!0,this.timeCurrent.textContent=b(t),this.timeTotal.textContent=` / ${b(i)}`))}),e.on("play",()=>this.syncPlayState()),e.on("pause",()=>this.syncPlayState()),e.on("ended",()=>this.syncPlayState()),e.on("volumechange",()=>this.syncVolume()),e.on("chapterchange",({chapter:t})=>{this.chapterLabel.textContent=t?.title??""}),e.on("fullscreenchange",({active:t})=>{this.fullscreenBtn&&I(this.fullscreenBtn,t?e.icons.fullscreenExit:e.icons.fullscreen,t?e.labels.exitFullscreen:e.labels.fullscreen),this.scheduleReflow()}),e.on("playlistitemchange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()}),e.on("sourcechange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()})),this.syncPlaylistButtons(),this.reflow()}syncPlayState(){const e=this.player,[t,i]=e.ended?[e.icons.replay,e.labels.replay]:e.paused?[e.icons.play,e.labels.play]:[e.icons.pause,e.labels.pause];this.playBtn&&I(this.playBtn,t,i),this.centerPlayBtn&&I(this.centerPlayBtn,t,i)}syncVolume(){if(!this.muteBtn)return;const e=this.player,t=e.muted?0:e.volume,i=t===0?e.icons.volumeMute:t<.5?e.icons.volumeLow:e.icons.volumeHigh;I(this.muteBtn,i,e.muted?e.labels.unmute:e.labels.mute),this.volumeSlider.value=String(t),this.volumeSlider.style.setProperty("--imp-volume-fill",`${t*100}%`)}syncFeatureButtons(){this.refreshSceneTypeButton(),this.syncPlaylistButtons(),this.scheduleReflow()}syncPlaylistButtons(){const e=this.player;this.prevBtn&&(this.prevBtn.disabled=!e.hasPrevious),this.nextBtn&&(this.nextBtn.disabled=!e.hasNext),this.centerPrevBtn&&(this.centerPrevBtn.disabled=!e.hasPrevious),this.centerNextBtn&&(this.centerNextBtn.disabled=!e.hasNext)}closeMenus(e){for(const t of[this.gearMenu,this.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.sceneTypeMenu,this.moreMenu])t&&t!==e&&t.close()}anyMenuOpen(){return[this.gearMenu,this.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.sceneTypeMenu,this.moreMenu].some(e=>e?.open)}toggleSettingsMenu(){this.settingsMenu&&(this.requestExternalMenu(this.player.labels.speed,[this.speedSection()])||(this.closeMenus(this.settingsMenu),this.settingsMenu.toggle([this.speedSection()])))}toggleQualityMenu(){!this.qualityMenu||this.player.qualityLevels.length===0||this.requestExternalMenu(this.player.labels.quality,[this.qualitySection()])||(this.closeMenus(this.qualityMenu),this.qualityMenu.toggle([this.qualitySection()]))}toggleSubtitlesMenu(){!this.subtitlesMenu||this.player.subtitleTracks.length===0||this.requestExternalMenu(this.player.labels.subtitles,[this.subtitlesSection()])||(this.closeMenus(this.subtitlesMenu),this.subtitlesMenu.toggle([this.subtitlesSection()]))}destroy(){for(const e of this.disposers)e();this.disposers=[],this.resizeObserver?.disconnect(),this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize),this.gearMenu?.destroy(),this.sceneTypeMenu?.destroy(),this.settingsMenu?.destroy(),this.subtitlesMenu?.destroy(),this.qualityMenu?.destroy(),this.moreMenu?.destroy(),this.nextPreviewEl?.remove(),this.root.remove()}}class Ge{constructor(e){this.root=o("div","imp-poster"),this.image=o("div","imp-poster__image"),this.image.hidden=!0,this.img=L(""),this.image.append(this.img);const t=g("imp-poster__play",e.labels.play,e.icons.bigPlay);t.addEventListener("click",()=>void e.play()),this.root.append(this.image,t),this.root.addEventListener("pointerup",i=>{i.target!==this.root&&i.target!==this.image&&i.target!==this.img||i.pointerType==="touch"&&e.posterTapReveal()||e.play()})}setSource(e){const t=e?.poster;if(t){const i=typeof t=="string"?{src:t}:t;this.img.src=i.src,i.srcset?this.img.srcset=i.srcset:this.img.removeAttribute("srcset"),i.sizes?this.img.sizes=i.sizes:this.img.removeAttribute("sizes"),i.width?this.img.width=i.width:this.img.removeAttribute("width"),i.height?this.img.height=i.height:this.img.removeAttribute("height"),this.img.alt=i.alt??"",this.img.fetchPriority="high",this.image.hidden=!1}else this.img.removeAttribute("src"),this.image.hidden=!0}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class We{constructor(e){this.labels=e,this.channelUrl=null,this.custom=null,this.visible={title:!0,description:!0,sponsor:!0},this.root=o("div","imp-pause-screen"),this.root.hidden=!0,this.defaultContent=o("div","imp-pause-screen__default"),this.channel=o("button","imp-channel",{type:"button"}),this.channel.hidden=!0,this.channelAvatar=o("div","imp-channel__avatar"),this.channelName=o("div","imp-channel__name"),this.channel.append(this.channelName,this.channelAvatar),this.channel.addEventListener("click",()=>{this.channelUrl&&window.open(this.channelUrl,"_blank","noopener")});const t=o("div","imp-pause-screen__heading");this.title=o("div","imp-pause-screen__title"),this.description=o("div","imp-pause-screen__description"),this.sponsor=o("a","imp-sponsor",{target:"_blank",rel:"nofollow noopener"}),this.sponsor.hidden=!0,this.sponsorLabel=o("span","imp-sponsor__label"),this.sponsorText=o("span","imp-sponsor__text"),this.sponsor.append(this.sponsorLabel,this.sponsorText),this.sponsor.addEventListener("click",i=>i.stopPropagation()),t.append(this.sponsor,this.title,this.description),this.defaultContent.append(t,this.channel),this.root.append(this.defaultContent)}setCustomContent(e){this.custom?.remove(),this.custom=e,e&&(e.classList.add("imp-pause-screen__custom"),this.root.append(e)),this.defaultContent.hidden=e!==null,this.root.classList.toggle("imp-pause-screen--custom",e!==null)}get hasCustom(){return this.custom!==null}setVisibility(e){this.visible={title:e.title??this.visible.title,description:e.description??this.visible.description,sponsor:e.sponsor??this.visible.sponsor}}setSource(e){this.title.textContent=e?.title??"",this.description.textContent=e?.description??"",this.title.hidden=!this.visible.title||!e?.title,this.description.hidden=!this.visible.description||!e?.description;const t=this.visible.sponsor?e?.sponsor:void 0;this.sponsor.hidden=!t,t&&(this.sponsor.href=t.url,this.sponsorText.textContent=t.text,this.sponsorLabel.textContent=t.label??this.labels.sponsored);const i=e?.channel;this.channel.hidden=!i,this.channelUrl=i?.url??null,this.channel.classList.toggle("imp-channel--link",!!i?.url),i&&(this.channelName.textContent=i.name,this.channelAvatar.className=`imp-channel__avatar imp-channel__avatar--${i.avatarShape??"circle"}`,i.avatar?(this.channelAvatar.textContent="",this.channelAvatar.append(L(i.avatar,i.name))):this.channelAvatar.textContent=(i.name.trim()[0]??"?").toUpperCase())}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class ze{constructor(e){this.player=e,this.clickBehavior="player",this.root=o("div","imp-related"),this.root.hidden=!0,this.heading=o("div","imp-related__title"),this.grid=o("div","imp-related__grid");const t=g("imp-related__close",e.labels.close,e.icons.close);t.addEventListener("click",()=>this.hide()),this.root.append(t,this.heading,this.grid)}setOptions(e){if(this.grid.textContent="",!!e){this.clickBehavior=e.clickBehavior??"player",this.heading.textContent=e.title??this.player.labels.related;for(const t of e.items)this.grid.append(this.buildCard(t))}}buildCard(e){const t=o("button","imp-related__card",{type:"button"}),i=o("div","imp-related__thumb");if(e.poster&&i.append(L(e.poster)),e.duration){const n=o("span","imp-related__duration");n.textContent=e.duration,i.append(n)}const s=o("div","imp-related__card-title");return s.textContent=e.title,t.append(i,s),t.addEventListener("click",()=>{this.player.emit("relatedclick",{item:e}),this.hide(),this.activate(e)}),t}activate(e){const t=e.url??e.source?.src;switch(this.clickBehavior){case"newWindow":t&&window.open(t,"_blank","noopener");break;case"currentTab":t&&(window.location.href=t);break;case"player":default:e.source?(this.player.load(e.source),this.player.play()):e.url&&window.open(e.url,"_blank","noopener")}}get visible(){return!this.root.hidden}show(){this.grid.childElementCount!==0&&(this.root.hidden=!1,this.player.emit("relatedshow",void 0))}hide(){this.root.hidden=!0}}class je{constructor(e){this.player=e,this.root=o("div","imp-upnext"),this.root.hidden=!0}get visible(){return!this.root.hidden}show(){const e=this.player.nextSource;if(!e){this.hide();return}const{labels:t}=this.player;this.root.textContent="";const i=o("div","imp-upnext__card"),s=o("div","imp-upnext__kicker");s.textContent=t.nextVideo,i.append(s);const n=C.posterSrc(e.poster);if(n){const l=o("button","imp-upnext__thumb",{type:"button","aria-label":t.playNext}),c=L(n);if(c.addEventListener("error",()=>{this.player.markSourceDead(e),this.root.hidden||this.show()},{once:!0}),l.append(c),e.duration){const d=o("span","imp-upnext__duration");d.textContent=b(e.duration),l.append(d)}const h=o("span","imp-upnext__thumb-play");S(h,this.player.icons.bigPlay),l.append(h),l.addEventListener("click",()=>this.player.next()),i.append(l)}if(e.title){const l=o("div","imp-upnext__title");l.textContent=e.title,i.append(l)}e.previewMeta?.length&&i.append(te(e.previewMeta,"imp-upnext"));const r=o("button","imp-upnext__btn",{type:"button"});r.textContent=t.playNext,r.addEventListener("click",()=>this.player.next()),i.append(r),this.root.append(i),this.root.hidden=!1}hide(){this.root.hidden=!0}}class Qe{constructor(e,t="sidebar",i){this.player=e,this.root=o("div",`imp-playlist imp-playlist--${t}`),this.root.hidden=!0;const s=o("div","imp-playlist__header"),n=o("div","imp-playlist__heading");if(i){const c=o("div","imp-playlist__kicker");c.textContent=e.labels.playlist;const h=o("div","imp-playlist__name");h.textContent=i,n.append(c,h)}else n.textContent=e.labels.playlist;const r=o("div","imp-playlist__tools");this.shuffleBtn=g("imp-playlist__shuffle",e.labels.shuffle,e.icons.shuffle),this.shuffleBtn.addEventListener("click",()=>{e.setShuffle(!e.shuffle),this.syncModes()}),this.repeatBtn=g("imp-playlist__repeat",e.labels.repeat,e.icons.repeat),this.repeatBtn.addEventListener("click",()=>{e.setRepeat(!e.repeat),this.syncModes()});const l=g("imp-playlist__close",e.labels.close,e.icons.close);l.addEventListener("click",()=>this.hide()),r.append(this.shuffleBtn,this.repeatBtn,l),s.append(n,r),this.list=o("div","imp-playlist__list"),this.root.append(s,this.list),this.rebuild(),this.syncModes()}syncModes(){this.shuffleBtn.classList.toggle("imp-btn--active",this.player.shuffle),this.repeatBtn.classList.toggle("imp-btn--active",this.player.repeat)}rebuild(){this.list.textContent="",this.player.playlist.forEach((e,t)=>{const i=o("button","imp-playlist__item",{type:"button"});t===this.player.index&&i.classList.add("imp-playlist__item--active");const s=o("div","imp-playlist__thumb"),n=C.posterSrc(e.poster);n&&s.append(L(n));const r=o("div","imp-playlist__meta"),l=o("div","imp-playlist__title");if(l.textContent=e.title??`#${t+1}`,r.append(l),e.duration){const c=o("div","imp-playlist__duration");c.textContent=b(e.duration),r.append(c)}i.append(s,r),i.addEventListener("click",()=>{this.player.playItem(t),window.innerWidth<=767&&this.hide()}),this.list.append(i)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}class Ue{constructor(e,t="bottom"){this.player=e,this.items=[],this.root=o("div",`imp-playlist imp-scenes imp-playlist--${t}`),this.root.hidden=!0;const i=o("div","imp-playlist__header"),s=o("span");s.textContent=e.labels.scenes;const n=g("imp-playlist__close",e.labels.close,e.icons.close);n.addEventListener("click",()=>this.hide()),i.append(s,n),this.list=o("div","imp-playlist__list"),this.root.append(i,this.list),e.on("chapterchange",()=>this.syncActive())}rebuild(){this.list.textContent="",this.items=[];const e=this.player.thumbnails;for(const t of this.player.chapterList){const i=o("button","imp-playlist__item",{type:"button"}),s=o("div","imp-playlist__thumb"),n=e?.cueAt(t.start+.01)??null;if(n?.xywh){const h=o("div","imp-scenes__sprite");h.style.width=`${n.xywh.w}px`,h.style.height=`${n.xywh.h}px`,h.style.backgroundImage=`url("${n.src}")`,h.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,h.style.setProperty("--imp-sprite-w",String(n.xywh.w)),s.append(h)}else n&&s.append(L(n.src));const r=o("div","imp-playlist__meta"),l=o("div","imp-playlist__title");l.textContent=t.title||b(t.start);const c=o("div","imp-playlist__duration");c.textContent=b(t.start),r.append(l,c),i.append(s,r),i.addEventListener("click",()=>{this.player.seek(t.start),this.player.play(),window.innerWidth<=767&&this.hide()}),this.list.append(i),this.items.push(i)}this.syncActive()}syncActive(){const e=this.player.chapter,t=this.player.chapterList;this.items.forEach((i,s)=>{i.classList.toggle("imp-playlist__item--active",e!==null&&t[s]===e)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}let ue=0;function pe(a){const e=a.reason;e?.name==="AbortError"&&/interrupted by a (new load request|call to pause)/i.test(e.message??"")&&a.preventDefault()}function Ke(){typeof window<"u"&&++ue===1&&window.addEventListener("unhandledrejection",pe)}function Xe(){typeof window<"u"&&--ue===0&&window.removeEventListener("unhandledrejection",pe)}function O(a){console.debug("[itube-player] play() rejected:",a)}function ee(a){return a?typeof a=="string"?[{src:a,label:"Subtitles"}]:Array.isArray(a)?a:[a]:[]}const Je={play:!0,progress:!0,time:!0,volume:!0,more:!1,fullscreen:!0,pip:!1,speed:"gear",settings:"gear",quality:"gear",scenes:!1,sceneTypes:!0,heatmap:!0,subtitles:"gear",seekButtons:!0,seekPlacement:"overlay",mobileLayout:"bar",order:["sceneTypes","gear","fullscreen"],playlist:!0,hidePrev:!0,hideNext:!1,playlistButton:!1,nextPreview:!0,hideDelay:2500,revealBeforePlay:!0};class Ze{constructor(e,t={}){this.scrubbing=!1,this.emitter=new se,this.externalAdvance=!1,this.abort=new AbortController,this.sources=[],this.deadSources=new WeakSet,this.currentIndex=-1,this.sourceController=null,this.loadToken=0,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.thumbTrack=null,this.shuffleMode=!1,this.autoAdvanceEnabled=!0,this.persistKey=null,this.persistVolume=!1,this.persistAutoAdvance=!1,this.decodeRecoveries=0,this.adManager=null,this.playedOnce=!1,this.idleTimer=null,this.peekTimer=null,this.lastRetryAt=0,this.retryTimer=null,this.errorResumeTime=0,this.lastPlayheadTime=0,this.pendingSeek=null,this.destroyed=!1,this.persistTimer=null;const i=typeof e=="string"?document.querySelector(e):e;if(!i)throw new Error(`[itube-player] mount target not found: ${String(e)}`);this.mount=i,this.options=t,this.labels={...$.defaultLabels,...ne(t.language),...t.labels},this.icons={...C.defaultIcons,...t.icons};const s=t.controls??{},n=s.speed??s.settings??"gear";if(this.controlsOptions={...Je,...s,speed:n,settings:n},this.menusMode=t.menus??"native",this.actionsOptions=t.actions??{},this.playbackRates=t.playbackRates??[.5,1,1.5,2],this.seekStep=t.seekStep??15,this.playlistOptions={title:"",autoAdvance:!0,loop:!1,shuffle:!1,startIndex:0,layout:"sidebar",externalAdvance:!1,...t.playlist},this.shuffleMode=this.playlistOptions.shuffle,this.externalAdvance=this.playlistOptions.externalAdvance,t.persist){const y=t.persist===!0?{}:t.persist;this.persistKey=y.key??"itube-player",this.persistVolume=y.volume!==!1,this.persistAutoAdvance=y.autoAdvance!==!1}const r=this.readPersisted();this.autoAdvanceEnabled=this.persistAutoAdvance&&typeof r?.autoAdvance=="boolean"?r.autoAdvance:this.playlistOptions.autoAdvance,this.sources=t.source?Array.isArray(t.source)?[...t.source]:[t.source]:[],this.container=o("div","imp-player",{tabindex:"0"}),t.className&&this.container.classList.add(t.className);const l=t.styling;if(l?.themeColor&&this.container.style.setProperty("--imp-accent",l.themeColor),l?.likeColor&&this.container.style.setProperty("--imp-like",l.likeColor),l?.dislikeColor&&this.container.style.setProperty("--imp-dislike",l.dislikeColor),l?.fontFamily&&this.container.style.setProperty("--imp-font",l.fontFamily),l?.borderRadius!==void 0){const y=typeof l.borderRadius=="number"?`${l.borderRadius}px`:l.borderRadius;this.container.style.setProperty("--imp-radius",y)}if(l?.playButtonStyle==="inverted"&&this.container.classList.add("imp-player--play-inverted"),this.video=t.videoElement??o("video","imp-video"),this.video.classList.add("imp-video"),t.videoElement&&!t.videoElement.paused)try{t.videoElement.pause()}catch{}t.playsInline!==!1&&this.video.setAttribute("playsinline",""),t.crossOrigin!==void 0&&(this.video.crossOrigin=t.crossOrigin),this.video.preload="metadata",t.loop&&(this.video.loop=!0);const c=this.persistVolume?r:null;this.video.volume=x(c?.volume??t.volume??1,0,1),(c?.muted??t.muted)&&(this.video.muted=!0);const h=o("div","imp-layer");this.spinner=o("div","imp-spinner"),this.spinner.hidden=!0,this.errorBox=o("div","imp-error"),this.errorBox.hidden=!0,this.errorText=o("div","imp-error__text"),this.retryBtn=o("button","imp-error__retry",{type:"button"});const d=o("span","imp-error__retry-label");d.textContent=this.labels.tryAgain,this.retryBtn.append(d,o("span","imp-error__retry-spinner")),this.retryBtn.addEventListener("click",()=>this.retry()),this.errorNextBtn=o("button","imp-error__next",{type:"button"}),this.errorNextBtn.textContent=this.labels.nextVideo,this.errorNextBtn.addEventListener("click",()=>{this.clearError(),this.next()});const m=o("div","imp-error__actions");m.append(this.retryBtn,this.errorNextBtn),this.errorBox.append(this.errorText,m),this.pauseScreen=new We(this.labels),this.poster=new Ge(this),this.related=new ze(this),this.related.setOptions(t.related),this.upNext=new je(this),this.controls=new He(this),this.playlistPanel=new Qe(this,this.playlistOptions.layout,this.playlistOptions.title||void 0),this.scenesPanel=new Ue(this,t.scenes?.layout??"bottom");const p=o("div","imp-layer__middle");p.append(this.spinner,this.errorBox,this.controls.center);const f=o("div","imp-layer__bottom");f.append(this.controls.root),h.append(this.pauseScreen.root,this.related.root,this.upNext.root,p,f),this.container.append(this.video,h,this.poster.root,this.playlistPanel.root,this.scenesPanel.root),this.mount.append(this.container),t.pauseScreen instanceof HTMLElement?this.pauseScreen.setCustomContent(t.pauseScreen):typeof t.pauseScreen=="function"?this.pauseScreen.setCustomContent(t.pauseScreen(this)):t.pauseScreen&&typeof t.pauseScreen=="object"&&this.pauseScreen.setVisibility(t.pauseScreen);const v=t.adConfig??t.ads;v&&v.adList.length>0&&(this.adManager=new Me({container:this.container,contentVideo:this.video,emitter:this.emitter,labels:this.labels,closeIcon:this.icons.close},v)),this.emitter.on("error",({fatal:y})=>{if(!y)return;const u=this.lastPlayheadTime||this.video.currentTime;Number.isFinite(u)&&u>0&&(this.errorResumeTime=u),this.errorText.textContent=this.labels.videoNotFound,this.errorNextBtn.hidden=!this.hasNext,this.errorBox.hidden=!1,this.spinner.hidden=!0,this.poster.hide(),this.container.classList.add("imp-player--error")}),Ke(),this.bindVideoEvents(),this.bindIdleHide(),t.keyboard!==!1&&this.bindKeyboard(),this.video.addEventListener("pointerup",y=>{if(!(this.adPlaying||!this.playedOnce)){if(y.pointerType==="mouse"){this.togglePlay();return}this.container.classList.contains("imp-player--idle")?(this.showControlsNow(),this.scheduleIdle()):this.video.paused||this.container.classList.add("imp-player--idle")}},{signal:this.abort.signal}),this.pauseScreen.root.addEventListener("click",y=>{this.pauseScreen.hasCustom||y.target===this.pauseScreen.root&&this.togglePlay()},{signal:this.abort.signal}),this.sources.length>0&&this.loadItem(x(this.playlistOptions.startIndex,0,this.sources.length-1),!!(t.playOnInit??t.autoplay)),queueMicrotask(()=>{this.destroyed||this.emitter.emit("ready",{player:this})})}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,t){this.emitter.emit(e,t)}get paused(){return this.video.paused}get ended(){return this.video.ended}get currentTime(){return this.video.currentTime}get duration(){return this.video.duration||0}get live(){return this.video.duration===1/0}get bufferedEnd(){const e=this.video.buffered;return e.length>0?e.end(e.length-1):0}get adPlaying(){return this.adManager?.adPlaying??!1}async play(e=!1){if(!(this.destroyed||this.adPlaying)&&!(this.adManager&&!e&&(await this.adManager.playPreRoll(),this.destroyed||!this.video.paused)))try{await this.video.play()}catch(t){const i=t?.name;if(i==="NotSupportedError"&&this.video.readyState===0){const s=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{s===this.loadToken&&this.video.play().catch(O)},{once:!0,signal:this.abort.signal});return}i!=="AbortError"&&(O(t),this.playedOnce||this.poster.show())}}pause(){this.adPlaying||this.video.pause()}togglePlay(){this.video.paused||this.video.ended?this.play():this.pause()}retry(){const e=this.options.retryThrottle??5e3,t=Date.now();if(t-this.lastRetryAt<e)return;this.lastRetryAt=t,this.retryBtn.disabled=!0,this.retryBtn.classList.add("imp-error__retry--loading"),this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{this.destroyed||(this.retryBtn.disabled=!1,this.retryBtn.classList.remove("imp-error__retry--loading"))},e);const i=this.errorResumeTime;if(this.loadItem(this.currentIndex,!0,!0),this.errorResumeTime=i,i>0){const s=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{if(s===this.loadToken)try{this.video.currentTime=i}catch{}},{once:!0,signal:this.abort.signal})}}clearError(){this.errorBox.hidden=!0,this.container.classList.remove("imp-player--error")}get started(){return this.playedOnce}seek(e){if(Number.isFinite(this.video.duration)){this.video.currentTime=x(e,0,this.video.duration);return}const t=this.source?.duration;typeof t=="number"&&t>0&&(this.pendingSeek=x(e,0,t))}skip(e){this.seek(this.video.currentTime+e)}get volume(){return this.video.volume}get muted(){return this.video.muted}setVolume(e){this.video.volume=x(e,0,1),e>0&&(this.video.muted=!1)}setMuted(e){this.video.muted=e}toggleMute(){this.video.muted=!this.video.muted}readPersisted(){if(!this.persistKey)return null;try{const e=localStorage.getItem(this.persistKey),t=e?JSON.parse(e):null;return t&&typeof t=="object"?t:null}catch{return null}}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.destroyed||this.persistState()},300)}persistState(){if(this.persistKey)try{const e={};this.persistVolume&&(e.volume=this.video.volume,e.muted=this.video.muted),this.persistAutoAdvance&&(e.autoAdvance=this.autoAdvanceEnabled),localStorage.setItem(this.persistKey,JSON.stringify(e))}catch{}}get playbackRate(){return this.video.playbackRate}setPlaybackRate(e){this.video.playbackRate=e,this.emitter.emit("ratechange",{rate:e})}get qualityLevels(){if(this.sourceController?.kind==="hls")return this.sourceController.levels;const e=this.source?.qualities;return e?e.map((t,i)=>({index:i,label:t.label??String(t.quality??i)})):[]}get qualityAutoAvailable(){return this.sourceController?.kind==="hls"}get currentQuality(){return this.sourceController?.kind==="hls"?this.sourceController.selected:this.progressiveQuality}setQuality(e){if(this.sourceController?.kind==="hls"){this.sourceController.setLevel(e);const r=e===-1?this.labels.qualityAuto:this.sourceController.levels.find(l=>l.index===e)?.label??String(e);this.emitter.emit("qualitychange",{label:r});return}const t=this.source?.qualities;if(!t||!t[e]||e===this.progressiveQuality)return;const i=this.video.currentTime,s=!this.video.paused&&!this.video.ended;this.progressiveQuality=e,this.video.src=t[e].src;const n=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{if(n===this.loadToken){try{this.video.currentTime=i}catch{}s&&this.video.play().catch(O)}},{once:!0,signal:this.abort.signal}),this.emitter.emit("qualitychange",{label:t[e].label??String(t[e].quality??e)})}get subtitleTracks(){return ee(this.source?.subtitles)}get activeSubtitle(){const e=this.video.textTracks;for(let t=0;t<e.length;t++)if(e[t].mode==="showing")return t;return-1}setSubtitle(e){const t=this.video.textTracks;for(let i=0;i<t.length;i++)t[i].mode=i===e?"showing":"disabled";this.emitter.emit("subtitlechange",{track:this.subtitleTracks[e]??null})}get playlist(){return this.sources}get index(){return this.currentIndex}get source(){return this.sources[this.currentIndex]??null}markSourceDead(e){this.deadSources.add(e),this.controls.syncFeatureButtons()}nextAliveIndex(){const e=this.sources.length;if(e<2)return-1;for(let t=1;t<e;t++){const i=this.currentIndex+t;if(i>=e&&!this.playlistOptions.loop)return-1;const s=i%e;if(!this.deadSources.has(this.sources[s]))return s}return-1}get nextSource(){if(this.shuffleMode||this.sources.length<2)return null;const e=this.nextAliveIndex();return e===-1?null:this.sources[e]}get hasPlaylist(){return this.sources.length>1||this.externalAdvance}get hasNext(){return this.externalAdvance?!0:this.shuffleMode?this.sources.length>1:this.nextAliveIndex()!==-1}get hasPrevious(){return this.externalAdvance?!0:this.playlistOptions.loop?this.sources.length>1:this.currentIndex>0}get shuffle(){return this.shuffleMode}setShuffle(e){this.shuffleMode=e}get repeat(){return this.playlistOptions.loop}setRepeat(e){this.playlistOptions.loop=e}emitAdvanceRequest(e,t){if(!this.externalAdvance)return!1;const i=t!==null&&t>=0&&t<this.sources.length;return this.emitter.emit("advancerequest",{direction:e,index:i?t:null,source:i?this.sources[t]:null}),!0}next(){if(!this.hasNext||this.emitAdvanceRequest("next",this.sources.length>1?(this.currentIndex+1)%this.sources.length:null))return;if(this.shuffleMode&&this.sources.length>1){const t=this.sources.map((s,n)=>({s,i:n})).filter(({s,i:n})=>n!==this.currentIndex&&!this.deadSources.has(s)),i=t.length>0?t.map(({i:s})=>s):this.sources.map((s,n)=>n).filter(s=>s!==this.currentIndex);this.playItem(i[Math.floor(Math.random()*i.length)]);return}const e=this.nextAliveIndex();e!==-1&&this.playItem(e)}previous(){this.hasPrevious&&(this.emitAdvanceRequest("previous",this.sources.length>1?(this.currentIndex-1+this.sources.length)%this.sources.length:null)||this.playItem((this.currentIndex-1+this.sources.length)%this.sources.length))}playItem(e){e<0||e>=this.sources.length||e!==this.currentIndex&&this.emitAdvanceRequest("select",e)||this.loadItem(e,!0).then(()=>{this.emitter.emit("playlistitemchange",{source:this.sources[e],index:e})})}togglePlaylistPanel(){this.scenesPanel.hide(),this.playlistPanel.toggle()}toggleScenesPanel(){this.playlistPanel.hide(),this.scenesPanel.toggle()}get thumbnails(){return this.thumbTrack}load(e,t=0){this.sources=Array.isArray(e)?[...e]:[e],this.playlistPanel.rebuild(),this.loadItem(x(t,0,this.sources.length-1),!1)}get isFullscreen(){return document.fullscreenElement===this.container}async toggleFullscreen(){try{this.isFullscreen?await document.exitFullscreen():this.container.requestFullscreen?await this.container.requestFullscreen():this.video.webkitEnterFullscreen?.()}catch{}}async togglePip(){try{document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}catch{}}get chapterList(){return this.chapters}get chapter(){return this.currentChapter}get sceneTypes(){return this.sceneGroupList}get activeSceneType(){return this.sceneGroupList.find(e=>e.id===this.activeSceneGroupId)??null}setSceneGroup(e){e===this.activeSceneGroupId||!this.sceneGroupList.some(t=>t.id===e)||(this.activeSceneGroupId=e,this.applyActiveSceneGroup(),this.emitter.emit("scenetypechange",{group:this.activeSceneType}))}get knownDuration(){const e=this.video.duration;if(Number.isFinite(e)&&e>0)return e;const t=this.source?.duration;return typeof t=="number"&&t>0?t:NaN}applyActiveSceneGroup(){this.chapters=j(this.activeSceneType?.scenes??[],this.knownDuration),this.currentChapter=null,this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild()}async share(){const e={title:this.source?.title??document.title,url:window.location.href};if(typeof navigator.share=="function"){try{await navigator.share(e)}catch{}return}this.emitter.emit("action",{id:"share"})}setLikeState(e){this.controls.setLikeState(e)}setLikeCounts(e,t){this.controls.setLikeCounts(e,t)}setPauseScreenContent(e){this.pauseScreen.setCustomContent(e)}destroy(){this.destroyed||(this.destroyed=!0,this.loadToken++,this.adManager?.destroy(),this.controls.destroy(),this.sourceController?.destroy(),this.abort.abort(),this.idleTimer&&clearTimeout(this.idleTimer),this.peekTimer&&clearTimeout(this.peekTimer),this.retryTimer&&clearTimeout(this.retryTimer),this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null,this.persistState()),this.container.remove(),Xe(),this.emitter.emit("destroy",void 0),this.emitter.removeAll())}async loadItem(e,t,i=!1){const s=++this.loadToken,n=this.sources[e];if(!n)return;this.currentIndex=e,this.sourceController?.destroy(),this.sourceController=null,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.playedOnce=!1,this.lastPlayheadTime=0,this.errorResumeTime=0,this.pendingSeek=null,this.endPeek();for(const p of[...this.video.querySelectorAll("track")])p.remove();this.adManager?.resetForNewSource(),this.related.hide(),this.upNext.hide(),this.pauseScreen.hide(),this.scenesPanel.hide(),this.thumbTrack=null,this.decodeRecoveries=0,this.video.poster=C.posterSrc(n.poster)??"",this.poster.setSource(n),this.pauseScreen.setSource(n),this.controls.progress.setChapters([]),this.controls.progress.setThumbnails(null),this.controls.progress.setHeatmap([]),typeof n.duration=="number"&&n.duration>0&&this.controls.seedPrestart(0,n.duration),t?this.poster.hide():(this.poster.show(),this.isMobileViewport()&&this.revealPeek(!1)),this.playlistPanel.rebuild();for(const p of ee(n.subtitles)){const f=o("track","",{kind:"subtitles",src:p.src,label:p.label,...p.srclang?{srclang:p.srclang}:{}});p.default&&f.setAttribute("default",""),this.video.append(f)}let r=n.src,l=n.type;if(n.qualities&&n.qualities.length>0){const p=Math.max(0,n.qualities.findIndex(f=>f.src===n.src));this.progressiveQuality=p,r=n.qualities[p].src,l=n.qualities[p].type??l}this.video.preload=this.adManager?.hasPendingPreRoll?"auto":"metadata";const c=await Re(this.video,r,l,{onLevels:()=>{s===this.loadToken&&this.controls.syncFeatureButtons()},onLevelSwitch:p=>this.emitter.emit("qualitychange",{label:p}),onError:(p,f)=>this.emitter.emit("error",{message:p,cause:f,fatal:!0})});if(s!==this.loadToken){c.destroy();return}if(this.sourceController=c,this.emitter.emit("sourcechange",{source:n,index:e}),n.thumbnails&&V.load(n.thumbnails).then(p=>{s===this.loadToken&&(this.thumbTrack=p,this.controls.progress.setThumbnails(p),this.scenesPanel.visible&&this.scenesPanel.rebuild())}).catch(p=>this.emitter.emit("error",{message:"Failed to load thumbnails track",cause:p})),n.sceneGroups&&n.sceneGroups.length>0)this.sceneGroupList=n.sceneGroups,this.activeSceneGroupId=n.sceneGroups[0].id,this.applyActiveSceneGroup(),Number.isFinite(this.video.duration)&&this.video.duration>0||this.video.addEventListener("loadedmetadata",()=>{s===this.loadToken&&this.applyActiveSceneGroup()},{once:!0,signal:this.abort.signal});else if(n.chapters){const p=f=>{const v=()=>{s===this.loadToken&&(this.chapters=j(f,this.knownDuration),this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild())};Number.isFinite(this.video.duration)&&this.video.duration>0?v():this.video.addEventListener("loadedmetadata",v,{once:!0,signal:this.abort.signal})};typeof n.chapters=="string"?ce(n.chapters).then(f=>p(f)).catch(f=>this.emitter.emit("error",{message:"Failed to load chapters track",cause:f})):p(n.chapters)}const h=n.heatmap,d=h&&!Array.isArray(h),m=d?h.values.length>0:!!(h&&h.length>0);if(h&&m&&this.controlsOptions.heatmap){const p=()=>{if(s!==this.loadToken)return;const f=d?Ee(h.values,h.mode):oe(h,this.video.duration);this.controls.progress.setHeatmap(f,d?h.smoothing??1:1)};d||Number.isFinite(this.video.duration)&&this.video.duration>0?p():this.video.addEventListener("loadedmetadata",p,{once:!0,signal:this.abort.signal})}t&&this.play(i)}bindVideoEvents(){const{signal:e}=this.abort,t=this.video;t.addEventListener("play",()=>{this.playedOnce=!0,this.endPeek(),this.poster.hide(),this.pauseScreen.hide(),this.related.visible||this.related.hide(),this.related.hide(),this.upNext.hide(),t.readyState<3&&(this.spinner.hidden=!1),this.emitter.emit("play",void 0),this.scheduleIdle()},{signal:e}),t.addEventListener("pause",()=>{this.spinner.hidden=!0,this.emitter.emit("pause",void 0),this.showControlsNow(),!(this.video.ended||this.scrubbing||this.adPlaying||!this.playedOnce)&&(this.options.pauseScreen!==!1&&this.pauseScreen.show(),this.options.related?.showOn?.includes("pause")&&this.related.show())},{signal:e}),t.addEventListener("ended",()=>{this.handleEnded()},{signal:e}),t.addEventListener("timeupdate",()=>{!this.adPlaying&&t.currentTime>0&&(this.lastPlayheadTime=t.currentTime),this.emitter.emit("timeupdate",{currentTime:t.currentTime,duration:t.duration||0}),this.adManager?.checkMidRolls(t.currentTime);const i=Q(this.chapters,t.currentTime);i!==this.currentChapter&&(this.currentChapter=i,this.emitter.emit("chapterchange",{chapter:i}))},{signal:e}),t.addEventListener("progress",()=>{this.emitter.emit("progress",{buffered:this.bufferedEnd})},{signal:e}),t.addEventListener("volumechange",()=>{this.emitter.emit("volumechange",{volume:t.volume,muted:t.muted}),this.persistVolume&&this.schedulePersist()},{signal:e}),t.addEventListener("loadedmetadata",()=>{if(this.pendingSeek!==null){const i=x(this.pendingSeek,0,Number.isFinite(t.duration)?t.duration:this.pendingSeek);this.pendingSeek=null;try{t.currentTime=i}catch{}}!this.playedOnce&&Number.isFinite(t.duration)&&this.controls.seedPrestart(t.currentTime,t.duration)},{signal:e}),t.addEventListener("seeking",()=>this.emitter.emit("seeking",{currentTime:t.currentTime}),{signal:e}),t.addEventListener("seeked",()=>this.emitter.emit("seeked",{currentTime:t.currentTime}),{signal:e}),t.addEventListener("waiting",()=>{this.spinner.hidden=!1},{signal:e});for(const i of["playing","canplay","seeked"])t.addEventListener(i,()=>{this.spinner.hidden=!0,this.decodeRecoveries=0,i==="playing"&&this.clearError()},{signal:e});t.addEventListener("error",()=>{const i=t.error;if(!i||this.sourceController?.kind==="hls"||t.getAttribute("src")===null&&!t.currentSrc)return;if((i.code===MediaError.MEDIA_ERR_DECODE||/DEMUXER|PARSE|DECODE/i.test(i.message||""))&&this.decodeRecoveries<2&&Number.isFinite(t.duration)){this.decodeRecoveries++;const n=t.currentTime,r=!t.paused;t.load();const l=()=>{try{t.currentTime=n}catch{}r&&t.play().catch(O)};t.readyState>=1?l():t.addEventListener("loadedmetadata",l,{once:!0,signal:this.abort.signal});return}this.emitter.emit("error",{message:i.message||`Media error (code ${i.code})`,cause:i,fatal:!0})},{signal:e}),t.addEventListener("enterpictureinpicture",()=>this.emitter.emit("pipchange",{active:!0}),{signal:e}),t.addEventListener("leavepictureinpicture",()=>this.emitter.emit("pipchange",{active:!1}),{signal:e}),document.addEventListener("fullscreenchange",()=>{this.emitter.emit("fullscreenchange",{active:this.isFullscreen}),this.container.classList.toggle("imp-player--fullscreen",this.isFullscreen)},{signal:e}),t.addEventListener("webkitbeginfullscreen",()=>{this.emitter.emit("fullscreenchange",{active:!0}),this.container.classList.add("imp-player--fullscreen")},{signal:e}),t.addEventListener("webkitendfullscreen",()=>{this.emitter.emit("fullscreenchange",{active:!1}),this.container.classList.remove("imp-player--fullscreen")},{signal:e})}async handleEnded(){if(this.emitter.emit("ended",void 0),this.showControlsNow(),!(this.adManager&&(await this.adManager.playPostRoll(),this.destroyed))){if(this.autoAdvanceEnabled&&this.hasNext){if(this.emitAdvanceRequest("ended",this.sources.length>1?(this.currentIndex+1)%this.sources.length:null))return;this.next();return}if(!this.autoAdvanceEnabled&&this.hasNext){this.upNext.show();return}(this.options.related?.showOn?.includes("ended")??!!this.options.related)&&this.related.show()}}get autoAdvance(){return this.autoAdvanceEnabled}setAutoAdvance(e){this.autoAdvanceEnabled=e,e&&this.upNext.hide(),this.persistAutoAdvance&&this.persistState()}bindIdleHide(){const{signal:e}=this.abort,t=()=>{this.showControlsNow(),this.scheduleIdle()};this.container.addEventListener("pointermove",i=>{i.pointerType!=="touch"&&(t(),this.playedOnce||this.revealPeek(!1))},{signal:e}),this.container.addEventListener("pointerdown",i=>{i.pointerType!=="touch"&&t()},{signal:e}),this.container.addEventListener("keydown",t,{signal:e}),this.container.addEventListener("pointerleave",i=>{i.pointerType!=="touch"&&(this.controls.anyMenuOpen()||(this.playedOnce?this.video.paused||this.container.classList.add("imp-player--idle"):this.endPeek()))},{signal:e})}showControlsNow(){this.container.classList.remove("imp-player--idle")}isMobileViewport(){return typeof window<"u"&&window.matchMedia("(max-width: 767px)").matches}revealPeek(e){this.playedOnce||!this.controlsOptions.revealBeforePlay||(this.container.classList.add("imp-player--peek"),this.peekTimer&&clearTimeout(this.peekTimer),this.peekTimer=null,e&&!this.isMobileViewport()&&(this.peekTimer=setTimeout(()=>{!this.playedOnce&&!this.destroyed&&!this.controls.anyMenuOpen()&&this.container.classList.remove("imp-player--peek")},3e3)))}endPeek(){this.peekTimer&&clearTimeout(this.peekTimer),this.peekTimer=null,this.container.classList.remove("imp-player--peek")}posterTapReveal(){return this.playedOnce||!this.controlsOptions.revealBeforePlay?!1:(this.revealPeek(!0),!0)}scheduleIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{!this.video.paused&&!this.destroyed&&this.container.classList.add("imp-player--idle")},this.controlsOptions.hideDelay)}bindKeyboard(){this.container.addEventListener("keydown",e=>{const t=e.target;if(t.closest("input, select, textarea, [contenteditable]"))return;const s=t.closest("button")!==null;switch(e.key){case" ":case"k":if(e.key===" "&&s)return;e.preventDefault(),this.togglePlay();break;case"ArrowLeft":e.preventDefault(),this.skip(-this.seekStep);break;case"ArrowRight":e.preventDefault(),this.skip(this.seekStep);break;case"ArrowUp":e.preventDefault(),this.setVolume(this.volume+.1);break;case"ArrowDown":e.preventDefault(),this.setVolume(this.volume-.1);break;case"m":this.toggleMute();break;case"f":this.toggleFullscreen();break;case"Home":this.seek(0);break;case"End":this.seek(this.duration);break;default:/^[0-9]$/.test(e.key)&&Number.isFinite(this.video.duration)&&this.seek(Number(e.key)/10*this.video.duration)}},{signal:this.abort.signal})}}exports.defaultIcons=C.defaultIcons;exports.defaultLabels=$.defaultLabels;exports.Emitter=se;exports.Player=Ze;exports.ThumbnailTrack=V;exports.buildHeatmapValues=oe;exports.chapterAt=Q;exports.formatTime=b;exports.getLocale=ne;exports.heatmapPath=ae;exports.isHlsSource=de;exports.loadChaptersVtt=ce;exports.normalizeChapters=j;exports.registerLocale=xe;exports.registerLocales=_e;exports.registeredLanguages=Se;exports.resolveVast=le;
package/dist/core.js CHANGED
@@ -1,4 +1,4 @@
1
- import { p as $, d as oe } from "./placeholder-CdTvMpu6.js";
1
+ import { p as $, d as oe } from "./placeholder-B64YAdwx.js";
2
2
  import { d as W } from "./labels-CCjOCBKU.js";
3
3
  function o(a, e, t) {
4
4
  const i = document.createElement(a);
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./core.cjs"),t=require("./placeholder-DeE6vGqL.cjs"),r=require("./labels-BOrrLImF.cjs"),a=require("./locales.cjs");e.registerLocales(a.locales);exports.Emitter=e.Emitter;exports.Player=e.Player;exports.ThumbnailTrack=e.ThumbnailTrack;exports.buildHeatmapValues=e.buildHeatmapValues;exports.chapterAt=e.chapterAt;exports.formatTime=e.formatTime;exports.getLocale=e.getLocale;exports.heatmapPath=e.heatmapPath;exports.isHlsSource=e.isHlsSource;exports.loadChaptersVtt=e.loadChaptersVtt;exports.normalizeChapters=e.normalizeChapters;exports.registerLocale=e.registerLocale;exports.registerLocales=e.registerLocales;exports.registeredLanguages=e.registeredLanguages;exports.resolveVast=e.resolveVast;exports.defaultIcons=t.defaultIcons;exports.defaultLabels=r.defaultLabels;exports.locales=a.locales;exports.supportedLanguages=a.supportedLanguages;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./core.cjs"),t=require("./placeholder-DPxcQX8a.cjs"),r=require("./labels-BOrrLImF.cjs"),a=require("./locales.cjs");e.registerLocales(a.locales);exports.Emitter=e.Emitter;exports.Player=e.Player;exports.ThumbnailTrack=e.ThumbnailTrack;exports.buildHeatmapValues=e.buildHeatmapValues;exports.chapterAt=e.chapterAt;exports.formatTime=e.formatTime;exports.getLocale=e.getLocale;exports.heatmapPath=e.heatmapPath;exports.isHlsSource=e.isHlsSource;exports.loadChaptersVtt=e.loadChaptersVtt;exports.normalizeChapters=e.normalizeChapters;exports.registerLocale=e.registerLocale;exports.registerLocales=e.registerLocales;exports.registeredLanguages=e.registeredLanguages;exports.resolveVast=e.resolveVast;exports.defaultIcons=t.defaultIcons;exports.defaultLabels=r.defaultLabels;exports.locales=a.locales;exports.supportedLanguages=a.supportedLanguages;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { registerLocales as e } from "./core.js";
2
2
  import { Emitter as l, Player as m, ThumbnailTrack as p, buildHeatmapValues as i, chapterAt as f, formatTime as u, getLocale as c, heatmapPath as d, isHlsSource as g, loadChaptersVtt as h, normalizeChapters as L, registerLocale as n, registeredLanguages as x, resolveVast as b } from "./core.js";
3
- import { d as V } from "./placeholder-CdTvMpu6.js";
3
+ import { d as V } from "./placeholder-B64YAdwx.js";
4
4
  import { d as H } from "./labels-CCjOCBKU.js";
5
5
  import { locales as r } from "./locales.js";
6
6
  import { supportedLanguages as k } from "./locales.js";