dashboard-ui/modules/emby-elements/guide/guide.js
2023-08-31 15:30:17 +02:00

1 line
35 KiB
JavaScript

define(["exports","./../../browser.js","./../../shortcuts.js","./../../emby-apiclient/connectionmanager.js","./../../common/input/api.js","./../../emby-apiclient/events.js","./../../common/globalize.js","./../../dom.js","./../../layoutmanager.js","./../../common/datetime.js","./../../focusmanager.js","./../../loading/loading.js","./../../common/usersettings/usersettings.js","./gridrowrenderer.js","./../emby-button/emby-button.js","./../emby-scroller/emby-scroller.js","./../emby-button/paper-icon-button-light.js","./../../common/methodtimer.js","./../emby-itemscontainer/emby-itemscontainer.js","./../../common/inputmanager.js","./../../common/playback/playbackmanager.js"],function(_exports,_browser,_shortcuts,_connectionmanager,_api,_events,_globalize,_dom,_layoutmanager,_datetime,_focusmanager,_loading,_usersettings,_gridrowrenderer,_embyButton,_embyScroller,_paperIconButtonLight,_methodtimer,_embyItemscontainer,_inputmanager,_playbackmanager){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,require(["css!modules/emby-elements/guide/guide.css","programStyles","material-icons","flexStyles"]);var cellDurationMs=18e5,msPerMinute=6e4,msPerPage=288e5,startId=Date.now();function normalizeDateToTimeslot(value,roundUp){var delta=value%cellDurationMs;return roundUp&&delta&&(value+=cellDurationMs),value-=delta}function onSettingsButtonClick(e){var instance=this;require(["guide-settings-dialog"],function(guideSettingsDialog){guideSettingsDialog.show({categoryOptions:instance.categoryOptions,positionTo:e.target,positionY:"bottom",positionX:"right"},_connectionmanager.default.getApiClient(instance.options.serverId)).then(function(){instance.refresh()})})}function onDateButtonClick(e){!function(options){return Emby.importModule("./modules/actionsheet/actionsheet.js").then(function(ActionSheet){return ActionSheet.show(options)})}({items:function(instance){for(var items=[],start=new Date(instance._startDateMs),end=new Date(instance._endDateMs),nowHours=(today=new Date).getHours(),nowMinutes=30<=today.getMinutes()?30:0,nowHours=(start.setHours(nowHours,nowMinutes,0,0),end.setHours(0,0,0,0),start.getTime()>=end.getTime()&&end.setDate(start.getDate()+1),start=new Date(Math.max(today,start)),instance.scroller),nowMinutes=instance.scroller.getScrollWidth(),today=(nowMinutes-=getChannelCellWidth(instance),instance._startDateMs),instance=instance._endDateMs,nowHours=Math.abs(nowHours.getScrollLeft())/nowMinutes*(instance-today),date=(nowHours+=today,new Date(nowHours));start<=end;)items.push({name:_datetime.default.toLocaleDateString(start,{weekday:"long",month:"short",day:"numeric"}),value:start.getTime().toString(),selected:date.getDate()===start.getDate()&&date.getMonth()===start.getMonth()&&date.getFullYear()===start.getFullYear()}),start.setDate(start.getDate()+1),start.setHours(0,0,0,0);return items}(this),positionTo:e.target,title:_globalize.default.translate("HeaderSelectDate"),positionY:"bottom",hasItemSelectionState:!0}).then(function(value){scrollToTimeMs(this,value,!1,!0)}.bind(this))}function scrollToTimeMs(instance,value,exactTime,autoFocus){value=parseInt(value);var startDate,endDate,date=new Date,value=(date.setTime(value),instance.scroller),scrollWidth=instance.scroller.getScrollWidth();scrollWidth&&(scrollWidth-=getChannelCellWidth(instance),startDate=instance._startDateMs,endDate=instance._endDateMs,exactTime||(exactTime=Math.abs(value.getScrollLeft())/scrollWidth*(endDate-startDate),exactTime+=startDate,exactTime=new Date(exactTime),date.setHours(exactTime.getHours(),exactTime.getMinutes()+1,0,0)),date.setTime(normalizeDateToTimeslot(date.getTime())),exactTime=Math.max(date.getTime()-startDate,0)/(endDate-startDate),value.scrollToPosition({left:exactTime*scrollWidth*value.getScrollLeftMultiplier(),behavior:"instant"}),onScroll.call(instance,{currentTarget:instance.scroller,target:instance.scroller,autoFocus:autoFocus}))}var InsetInlineStartProp=CSS.supports("inset-inline-start","0")?"insetInlineStart":"left",BorderInlineStartWidthProp=CSS.supports("border-inline-start-width","0")?"borderInlineStartWidth":"borderLeftWidth";function setPaddingInlineStart(elem,value){(elem._paddingInlineStart||"0")!==value&&(elem._paddingInlineStart=value,elem.style[InsetInlineStartProp]=value)}function getChannelCellWidth(instance){var channelCellWidth=instance.channelCellWidth;return channelCellWidth||(channelCellWidth=instance.firstChannelCell.offsetWidth,instance.channelCellWidth=channelCellWidth),channelCellWidth}function getTimeBlockStart(instance,scrollLeft,scrollWidth){var startDate=instance._startDateMs,instance=instance._endDateMs,scrollLeft=scrollWidth?scrollLeft/scrollWidth*(instance-startDate):0;return(scrollLeft=Math.floor(scrollLeft))-scrollLeft%msPerPage+startDate}function getProgramFieldsProperty(){var programFields=[];return"true"===_usersettings.default.get("false"!==_usersettings.default.get("guide-indicator-4k")||"guide-indicator-hd")&&(programFields.push("IsHD"),programFields.push("Width")),programFields.length?programFields.join(","):null}function loadPrograms(instance,epgRowMap,channelIds,timeBlockStart){var promise,apiClient=_connectionmanager.default.getApiClient(instance.options.serverId),cacheKey=[apiClient.getCurrentUserId(),timeBlockStart.toString(),channelIds.join(",")].join("|"),cachedResult=(instance.programCache||(instance.programCache={}),instance.programCache[cacheKey]);return(promise=cachedResult?Promise.resolve(cachedResult):promise)||(cachedResult=timeBlockStart===getTimeBlockStart(instance,0,0)?1e3:0,timeBlockStart={UserId:apiClient.getCurrentUserId(),MaxStartDate:new Date(timeBlockStart+msPerPage).toISOString(),MinEndDate:new Date(timeBlockStart+cachedResult).toISOString(),channelIds:channelIds.join(","),ImageTypeLimit:1,SortBy:"StartDate",EnableTotalRecordCount:!1,EnableUserData:!1,Fields:getProgramFieldsProperty()},promise=apiClient.getLiveTvPrograms(timeBlockStart)),promise.then(function(result){return instance.programCache||(instance.programCache={}),instance.programCache[cacheKey]=result,function(instance,epgRowMap,programs){for(var i=0,length=programs.length;i<length;i++){var program=programs[i],epgItem=epgRowMap[program.ChannelId];epgItem&&!function(instance,epgItem,program){_gridrowrenderer.default.parseDates(program);var insertAtIndex,programs=epgItem.Programs,programMap=epgItem.ProgramMap,programId=program.Id;programMap[programId]||(programMap[programId]=program,insertAtIndex=getInsertIndex(programs,program.StartDateLocalMs),programs.splice(insertAtIndex,0,program));epgItem=epgItem.RowElement;{var channelProgramsElement;epgItem&&(channelProgramsElement=epgItem.children[ChannelProgramsChildIndex])&&(programMap=epgItem.ProgramMap)&&!programMap[programId]&&(programMap[programId]=program,programs=epgItem.Programs,insertAtIndex=getInsertIndex(programs,program.StartDateLocalMs),programs.splice(insertAtIndex,0,program),programMap=instance.itemsContainer.currentListOptions.options,programId=programMap.endMs-programMap.startMs,epgItem=_gridrowrenderer.default.getProgramHtml(program,programMap,programId),(programs=channelProgramsElement.children[insertAtIndex])?programs.insertAdjacentHTML("beforebegin",epgItem):channelProgramsElement.insertAdjacentHTML("beforeend",epgItem))}}(instance,epgItem,program)}updateCellTexts(instance)}(instance,epgRowMap,result.Items)})}function getInsertIndex(programs,programStartTime){for(var numPrograms=programs.length,insertAtIndex=numPrograms,i=0,length=numPrograms;i<length;i++)if(programStartTime<=programs[i].StartDateLocalMs){insertAtIndex=i;break}return insertAtIndex}var ChannelProgramsChildIndex=1;function onScroll(e){var channelCellWidth,scrollWidth,absScrollLeft,scrollPct,scrollLeft=(e.currentTarget||e.target).getScrollLeft(),scrollXChanged=this.lastScrollLeft!==scrollLeft||_browser.default.firefox;scrollXChanged&&this.headerScroller.scrollToPosition({left:scrollLeft,behavior:"instant"}),(scrollXChanged||e.forceHorizontalChange||e.autoFocus)&&(scrollLeft?this.firstChannelCell.classList.add("firstChannelCell-withscroll"):this.firstChannelCell.classList.remove("firstChannelCell-withscroll"),channelCellWidth=getChannelCellWidth(this),scrollWidth=this.scroller.getScrollWidth()-channelCellWidth,absScrollLeft=scrollLeft?Math.abs(scrollLeft):0,this.lastHorizontalScrollPct=scrollPct=scrollLeft?absScrollLeft/scrollWidth*100:0,this.startDataLoadTimer(absScrollLeft,e.autoFocus,e.autoFocus),this.lastScrollLeft=scrollLeft,updateCellTexts(this,scrollPct,e.updateProgramTextRow,channelCellWidth,scrollWidth),scrollXChanged)&&this.updateDateButtonText(absScrollLeft,scrollWidth)}function updateCellTexts(instance,scrollPct,rowToUpdate,channelCellWidth,scrollWidth){null==channelCellWidth&&(channelCellWidth=getChannelCellWidth(instance)),null==scrollWidth&&(scrollWidth=instance.scroller.getScrollWidth()-channelCellWidth),null==scrollPct&&(scrollPct=(channelCellWidth=Math.abs(instance.scroller.getScrollLeft()))?channelCellWidth/scrollWidth*100:0);var pixelPct=scrollWidth?1/scrollWidth*100:0;if(rowToUpdate)updateProgramCellTextsForRow(instance,rowToUpdate,scrollPct,pixelPct);else for(var activeItemElements=instance.itemsContainer.virtualScroller.getActiveItems().elements,i=0,length=activeItemElements.length;i<length;i++)updateProgramCellTextsForRow(instance,activeItemElements[i],scrollPct,pixelPct)}function updateProgramCellTextsForRow(instance,row,scrollPct,pixelPct){row=row.children[ChannelProgramsChildIndex];if(row)for(var caretFound,style,borderWidth,programCells=row.children,borderPct=0,i=0,length=programCells.length;i<length;i++)0===i&&(null==(borderWidth=instance.programBorderInlineStartWidth)&&(style=getComputedStyle(programCells[i]),borderWidth=parseFloat(style[BorderInlineStartWidthProp].replace("px","")),instance.programBorderInlineStartWidth=borderWidth),borderPct=borderWidth*pixelPct),!function(cell,scrollPct,borderPct,hidden){var width,pctOffsetStart;if(hidden||((hidden=cell.posLeft)||(hidden=parseFloat(cell.style[InsetInlineStartProp].replace("%","")),cell.posLeft=hidden),(width=cell.posWidth)||(width=parseFloat(cell.style.width.replace("%","")),cell.posWidth=width),width=(pctOffsetStart=hidden<scrollPct?(scrollPct-hidden)/(width-borderPct)*100:pctOffsetStart)&&pctOffsetStart<100),!(scrollPct=cell.programCellInner)&&pctOffsetStart&&(scrollPct=cell.firstChild,cell.programCellInner=scrollPct),!(hidden=cell.caret)&&pctOffsetStart&&(hidden=scrollPct.firstChild,cell.caret=hidden),scrollPct){if(width)return setPaddingInlineStart(scrollPct,pctOffsetStart+"%"),hidden&&!1!==hidden._hidden&&(hidden._hidden=!1,hidden.classList.remove("hide")),1;setPaddingInlineStart(scrollPct,pctOffsetStart?pctOffsetStart+"%":"0"),hidden&&!1===hidden._hidden&&(hidden._hidden=!0,hidden.classList.add("hide"))}}(programCells[i],scrollPct,borderPct,caretFound)||(caretFound=!0)}function onLiveButtonClick(e){scrollToTimeMs(this,Date.now(),!0,!!_layoutmanager.default.tv)}function onFocusInScroller(e){var customXOffset,elementRect,previousItem,lastFocusedItem=this.lastFocusedItem,target=e.target,focused=_focusmanager.default.focusableParent(target),e=(focused&&lastFocusedItem!==focused&&(lastFocusedItem=e.currentTarget,e=this,lastFocusedItem=lastFocusedItem,customXOffset=(focused=focused).closest(".programCell")?0-getChannelCellWidth(e):0,elementRect=focused.getBoundingClientRect(),customXOffset=lastFocusedItem.getElementPosition(focused,!0,{offset:customXOffset*lastFocusedItem.getScrollLeftMultiplier(),itemBoundingClientRect:elementRect}),elementRect=lastFocusedItem.getElementPosition(focused,!1,{offset:0*lastFocusedItem.getScrollTopMultiplier(),itemBoundingClientRect:elementRect}),previousItem=(null==(previousItem=e._previousFocusItem)?void 0:previousItem.closest(".epgRow"))===focused.closest(".epgRow")?"isVisible":"anyVisible",e._previousFocusItem=focused,customXOffset[previousItem]||elementRect.isVisible?customXOffset[previousItem]?elementRect.isVisible||lastFocusedItem.scrollToPosition({top:Math.round(elementRect.center)}):lastFocusedItem.scrollToPosition({left:Math.round(customXOffset.start)}):lastFocusedItem.scrollToPosition({left:Math.round(customXOffset.start),top:Math.round(elementRect.center)})),target.closest(".programCell"));e&&(focused=e.closest(".epgRow"),previousItem=getProgramFromProgramCell(e,focused))&&_events.default.trigger(this,"focus",[{item:previousItem}])}function bindScrollEventOnUpgrade(){this.scroller.addScrollEventListener?(this.scroller.addScrollEventListener(onScroll.bind(this),{passive:!0}),this.headerScroller.addScrollEventListener(function(e){}.bind(this),{passive:!0})):this.scroller.addEventListener("upgraded",bindScrollEventOnUpgrade.bind(this))}function initialRender(instance){return instance.rendered?Promise.resolve():(instance.rendered=!0,require(["text!modules/emby-elements/guide/tvguide.template.html"]).then(function(responses){for(var context=instance.options.element,responses=(context.classList.add("tvguide"),context.innerHTML=_globalize.default.translateDocument(responses[0],"sharedcomponents"),instance.firstChannelCell=context.querySelector(".firstChannelCell"),instance.onTimerCreatedFn=function(e,apiClient,data){for(var programId=data.ProgramId,newTimerId=data.Id,cells=this.options.element.querySelectorAll('.programCell[data-id="'+programId+'"]'),i=0,length=cells.length;i<length;i++){var cell=cells[i];cell.querySelector(".timerIcon")||cell.querySelector(".programCellInner").insertAdjacentHTML("beforeend",'<i class="timerIcon md-icon programIcon">&#xE061;</i>'),newTimerId&&cell.setAttribute("data-timerid",newTimerId)}}.bind(instance),_events.default.on(_api.default,"TimerCreated",instance.onTimerCreatedFn),instance.onSeriesTimerCreatedFn=function(e,apiClient,data){}.bind(instance),_events.default.on(_api.default,"SeriesTimerCreated",instance.onSeriesTimerCreatedFn),instance.onTimerCancelledFn=function(e,apiClient,data){for(var options=this.options,data=data.Id,cells=options.element.querySelectorAll('.programCell[data-timerid="'+data+'"]'),i=0,length=cells.length;i<length;i++){var cell=cells[i],icon=cell.querySelector(".timerIcon");icon&&icon.parentNode.removeChild(icon),cell.removeAttribute("data-timerid")}}.bind(instance),_events.default.on(_api.default,"TimerCancelled",instance.onTimerCancelledFn),instance.onSeriesTimerCancelledFn=function(e,apiClient,data){for(var options=this.options,data=data.Id,cells=options.element.querySelectorAll('.programCell[data-seriestimerid="'+data+'"]'),i=0,length=cells.length;i<length;i++){var cell=cells[i],icon=cell.querySelector(".seriesTimerIcon");icon&&icon.parentNode.removeChild(icon),cell.removeAttribute("data-seriestimerid")}}.bind(instance),_events.default.on(_api.default,"SeriesTimerCancelled",instance.onSeriesTimerCancelledFn),instance.scroller=instance.options.element.querySelector(".virtualScrollerScrollContainer"),instance.scroller.getScrollButtonPageSize=function(scrollContainerSize,scrollType){return scrollContainerSize=scrollContainerSize-getChannelCellWidth(this)-20,Math.max(scrollContainerSize,0)}.bind(instance),instance.headerScroller=instance.options.element.querySelector(".headerScroller"),instance.uniqueId=startId,instance.scrollSliderUniqueClass="epgScrollSlider"+startId,instance.scroller.classList.add("epgVirtualScrollerScrollContainer-both"),bindScrollEventOnUpgrade.call(instance),context.querySelector(".itemsContainer")),settingsButtons=(responses.fetchData=instance.getItems.bind(instance),responses.afterRefresh=function(){var firstChannelCell=this.firstChannelCell,_this$itemsContainer$=(null==(_this$itemsContainer$=this.itemsContainer.currentListOptions)?void 0:_this$itemsContainer$.options)||{},elem=(this.currentTimeIndicatorDots=this.options.element.querySelectorAll(".guide-currentTimeIndicatorDot"),this.currentTimeIndicatorDots.length<2&&(this.itemsContainer.virtualScroller.insertAdjacentHTML("afterbegin",'<div class="guide-currentTimeIndicatorDot guideEpg-currentTimeIndicatorDot hide"></div>'),this.currentTimeIndicatorDots=this.options.element.querySelectorAll(".guide-currentTimeIndicatorDot")),this.options.element.querySelector(".guideEpg-currentTimeIndicatorDot"));(_this$itemsContainer$=_this$itemsContainer$.channelCellClass||"").includes("channelCell-wide2")?(firstChannelCell.classList.add("channelCell-wide2"),firstChannelCell.classList.remove("channelCell-wide"),elem.classList.add("guideEpg-currentTimeIndicatorDot-wide2"),elem.classList.remove("guideEpg-currentTimeIndicatorDot-wide")):_this$itemsContainer$.includes("channelCell-wide")?(firstChannelCell.classList.add("channelCell-wide"),firstChannelCell.classList.remove("channelCell-wide2"),elem.classList.add("guideEpg-currentTimeIndicatorDot-wide"),elem.classList.remove("guideEpg-currentTimeIndicatorDot-wide2")):(firstChannelCell.classList.remove("channelCell-wide","channelCell-wide2"),elem.classList.remove("guideEpg-currentTimeIndicatorDot-wide","guideEpg-currentTimeIndicatorDot-wide2")),this.startCurrentTimeUpdateInterval()}.bind(instance),responses.virtualChunkSize=25,responses.getListOptions=instance.getListOptions.bind(instance),instance.itemsContainer=responses,instance.boundFocusableElements=function(newRowToFocus,activeElement,direction,focusOptions){var isRTL="rtl"===document.dir,focusedChannelCell=activeElement.closest(".channelCell"),isGoingBackHorizontally=isRTL?1===direction:0===direction;if(focusedChannelCell){if(newRowToFocus)return(_elems=newRowToFocus.querySelectorAll(".channelCell")).length?_elems:null;if(isGoingBackHorizontally)return null}newRowToFocus=newRowToFocus||activeElement.closest(".epgRow");var _elems=activeElement.closest(".programCell");if(isGoingBackHorizontally||_elems&&null!=direction&&direction<2){isGoingBackHorizontally=newRowToFocus.querySelectorAll(".programCell,.channelCell"),activeElement=Array.prototype.indexOf.call(isGoingBackHorizontally,activeElement);if(-1!==activeElement){var offset=0===direction||2===direction?-1:1,activeElement=(direction<2&&isRTL&&(offset*=-1),activeElement+offset),activeElement=Math.min(Math.max(0,activeElement),isGoingBackHorizontally.length-1);if((isGoingBackHorizontally=Array.prototype.slice.call(isGoingBackHorizontally,activeElement,activeElement+1)).length)return isGoingBackHorizontally}return null}if(offset=newRowToFocus.querySelectorAll(".programCell"),null==direction||2<=direction||focusedChannelCell&&(isRTL?0===direction:1===direction)){for(var currentPositionMs=!_elems||!(null==direction||2<=direction)||null!=focusOptions&&focusOptions.ignoreFocusedProgram?this.currentPositionMs+msPerMinute:getProgramFromProgramCell(_elems,_elems.closest(".epgRow")).StartDateLocalMs,programs=newRowToFocus.Programs||[],startIndex=0,i=0,length=programs.length;i<length;i++){if(!(programs[i].EndDateLocalMs<=currentPositionMs))break;startIndex=i+1}0<startIndex&&(offset=Array.prototype.slice.call(offset,startIndex))}return offset.length||null==direction&&(offset=newRowToFocus.querySelectorAll(".channelCell")).length?offset:null}.bind(instance),responses.updateVirtualElement=function(row,item,index){var focusedId,activeElement;row&&(activeElement=document.activeElement,row.contains(activeElement))&&(activeElement=activeElement.closest("button"))&&(focusedId=activeElement.getAttribute("data-id")),_embyItemscontainer.default.prototype.updateVirtualElement.apply(this.itemsContainer,arguments),(item.RowElement=row).Programs=item.Programs.slice(0),row.ProgramMap=getProgramMap(row),row.getFocusableElements=this.boundFocusableElements,this.itemsContainer.itemParts[index]=null,onScroll.call(this,{target:this.scroller,currentTarget:this.scroller,updateProgramTextRow:row,forceHorizontalChange:!0}),focusedId&&((activeElement=row.querySelector('button[data-id="'+focusedId+'"]'))?_focusmanager.default.focus(activeElement):_focusmanager.default.autoFocus(row))}.bind(instance),responses.onRecycleElement=function(row,index){row.ProgramMap=null,row.Programs=null,(row=this.itemsContainer.getItem(index))&&(row.RowElement=null)}.bind(instance),responses.getContextMenuElementFromChildNode=function(child){return _shortcuts.default.getItemElementFromChildNode(child,!1,this)}.bind(responses),instance.channelCellResizeObserver=new ResizeObserver(function(entries){entries[0]&&(this.channelCellWidth=null,this.programBorderInlineStartWidth=null)}.bind(instance),{}),instance.channelCellResizeObserver.observe(instance.firstChannelCell),instance.channelCellResizeObserver.observe(instance.scroller),context.querySelectorAll(".btnGuideViewSettings")),i=0,length=settingsButtons.length;i<length;i++)settingsButtons[i].addEventListener("click",onSettingsButtonClick.bind(instance));var dateButtons=context.querySelectorAll(".btnSelectDate");for(i=0,length=dateButtons.length;i<length;i++)dateButtons[i].addEventListener("click",onDateButtonClick.bind(instance));_dom.default.addEventListener(instance.scroller,window.PointerEvent?"pointerdown":"mousedown",function(e){e=e.target,this.lastFocusedItem=_focusmanager.default.focusableParent(e),this.focusSourceIsPointer=!0}.bind(instance),{capture:!0,passive:!0}),_dom.default.addEventListener(instance.scroller,"focus",onFocusInScroller.bind(instance),{capture:!0,passive:!0}),instance.btnLiveGuide=instance.options.element.querySelector(".btnLiveGuide"),_dom.default.addEventListener(instance.btnLiveGuide,"click",onLiveButtonClick.bind(instance),{capture:!0,passive:!0}),instance.styleElementUniqueClass="guideStyle"+startId;responses=context.querySelectorAll(".epgScrollSlider");responses[0].classList.add(instance.scrollSliderUniqueClass),responses[1].classList.add(instance.scrollSliderUniqueClass),_layoutmanager.default.tv?(responses[0].classList.add(instance.scrollSliderUniqueClass+"-tv"),responses[1].classList.add(instance.scrollSliderUniqueClass+"-tv")):(responses[0].classList.remove(instance.scrollSliderUniqueClass+"-tv"),responses[1].classList.remove(instance.scrollSliderUniqueClass+"-tv")),startId++}))}function getProgramFromProgramCell(programCell,rowElement){var programId=programCell.getAttribute("data-id"),programCell=rowElement.ProgramMap;if(programCell){programCell=programCell[programId];if(programCell)return programCell}for(var programs=rowElement.Programs||[],i=0,length=programs.length;i<length;i++){var program=programs[i];if(program.Id===programId)return program}}function onInputCommand(e){switch(e.detail.command){case"pageup":this.moveChannelPages(-1),e.preventDefault();break;case"pagedown":case"channelup":this.moveChannelPages(1),e.preventDefault();break;case"channeldown":this.moveChannelPages(-1),e.preventDefault();break;case"fastforward":_playbackmanager.default.isPlayingMediaType(["Audio","Video"])||(this.moveDays(1),e.preventDefault());break;case"rewind":_playbackmanager.default.isPlayingMediaType(["Audio","Video"])||(this.moveDays(-1),e.preventDefault());break;case"nexttrack":case"nextchapter":case"next":_playbackmanager.default.isPlayingMediaType(["Audio","Video"])||(this.moveDays(1),e.preventDefault());break;case"previoustrack":case"previouschapter":case"previous":_playbackmanager.default.isPlayingMediaType(["Audio","Video"])||(this.moveDays(-1),e.preventDefault());break;case"back":!function(e,instance){var firstRow=instance.itemsContainer.getElement(0),activeElement=document.activeElement;if(firstRow&&activeElement&&firstRow.contains(activeElement)){if(activeElement.closest(".channelCell"))return;activeElement=activeElement.closest(".programCell");if(!activeElement)return;activeElement=getProgramFromProgramCell(activeElement,firstRow);if(activeElement)return activeElement.StartDateLocalMs<=Date.now()||activeElement.EndDateLocalMs<=Date.now()||(e.preventDefault(),e.stopPropagation(),onLiveButtonClick.call(instance))}instance.itemsContainer.scrollToIndex(0,{},!0),e.preventDefault(),e.stopPropagation()}(e,this)}}function Guide(options){(this.options=options).showEpisodeTitle=!options.condensed,this.categoryOptions={categories:[]},this.boundLoadPrograms=function(){this._dataLoadSection=null;for(var loadDataInfo,channelCellWidth,offsetWidth,timeBlockStart,originalScrollLeft,timeblocks,promises,activeItems=this.itemsContainer.virtualScroller.getActiveItems(),elements=activeItems.elements,channelIdsNeedingData=[],epgRowMap={},numActiveRows=Math.min(elements.length,activeItems.lastIndex-activeItems.firstIndex+1),i=0;i<numActiveRows;i++){var channelId,itemIndex=activeItems.firstIndex+i,itemIndex=this.itemsContainer.getItem(itemIndex);itemIndex&&(epgRowMap[channelId=itemIndex.Channel.Id]=itemIndex,channelIdsNeedingData.push(channelId))}channelIdsNeedingData.length&&(elements=(loadDataInfo=this._loadDataInfo).scrollLeft,channelCellWidth=getChannelCellWidth(this),channelCellWidth=this.scroller.getScrollWidth()-channelCellWidth,offsetWidth=this.scroller.getScrollContainerBoundingClientRect().width,timeblocks=[],promises=[],elements=originalScrollLeft=elements,elements=Math.min(originalScrollLeft,channelCellWidth),elements=Math.max(elements,0),timeBlockStart=getTimeBlockStart(this,elements,channelCellWidth),-1===timeblocks.indexOf(timeBlockStart)&&(promises.push(loadPrograms(this,epgRowMap,channelIdsNeedingData,timeBlockStart)),timeblocks.push(timeBlockStart)),elements=originalScrollLeft,elements-=offsetWidth,elements=Math.min(elements,channelCellWidth),elements=Math.max(elements,0),timeBlockStart=getTimeBlockStart(this,elements,channelCellWidth),-1===timeblocks.indexOf(timeBlockStart)&&(promises.push(loadPrograms(this,epgRowMap,channelIdsNeedingData,timeBlockStart)),timeblocks.push(timeBlockStart)),elements=originalScrollLeft,elements+=offsetWidth,elements=Math.min(elements,channelCellWidth),elements=Math.max(elements,0),timeBlockStart=getTimeBlockStart(this,elements,channelCellWidth),-1===timeblocks.indexOf(timeBlockStart)&&(promises.push(loadPrograms(this,epgRowMap,channelIdsNeedingData,timeBlockStart)),timeblocks.push(timeBlockStart)),loadDataInfo.autoFocus)&&Promise.all(promises).then(function(){var row=document.activeElement.closest(".epgRow");row&&_focusmanager.default.focus(row,{ignoreFocusedProgram:loadDataInfo.ignoreFocusedProgram})})}.bind(this),this.lastScrollTop=0,this.lastScrollLeft=0,_inputmanager.default.on(options.element,onInputCommand.bind(this))}function getDisplayTime(date){if("string"===(typeof date).toString().toLowerCase())try{date=new Date(Date.parse(date))}catch(err){return date}return _datetime.default.getDisplayTime(date)}function onGetGuideInfo(guideInfo){var guideInfo=Date.parse(guideInfo.EndDate),today=new Date,nowHours=today.getHours(),today=30<=today.getMinutes()?30:0,date=new Date,nowHours=(date.setHours(nowHours,today,0,0),_loading.default.show(),this._startDateMs=normalizeDateToTimeslot(date.getTime())),today=this._endDateMs=normalizeDateToTimeslot(guideInfo,!0);return function(instance){var numCells="\n.epgScrollSlider {\n width: "+19.5*(numCells=Math.ceil((instance._endDateMs-instance._startDateMs)/cellDurationMs))+"vw;\n}\n\n .epgScrollSlider:not(.epgScrollSlider-tv) {\n width: "+20*numCells+"vw;\n }\n\n@media all and (min-width: 120em) {\n\n .epgScrollSlider:not(.epgScrollSlider-tv) {\n width: "+50*numCells+"ch;\n }\n}\n\n@media all and (orientation: portrait) {\n\n .epgScrollSlider:not(.epgScrollSlider-tv) {\n width: calc("+numCells+" * min(50ch, 34vw));\n }\n}\n .epgScrollSlider-tv {\n width: "+21*numCells+"vw;\n }\n";console.log("rendering guide width css"),numCells=numCells.replaceAll("epgScrollSlider",instance.scrollSliderUniqueClass),(instance=document.querySelector("."+instance.styleElementUniqueClass))?instance.innerHTML=numCells:((instance=document.createElement("style")).innerHTML=numCells,document.head.appendChild(instance))}(this),this.scroller.notifyResized(),this.options.element.querySelector(".timeslotHeaders").innerHTML=function(originalStartDateMs,endDateTimeMs){for(var startDate=new Date(originalStartDateMs),numSlots=0;startDate.getTime()<endDateTimeMs;)numSlots++,startDate.setTime(startDate.getTime()+cellDurationMs);var width=100/numSlots,startDate=new Date(originalStartDateMs),html="";for(html+='<div class="guide-currentTimeIndicatorDot guideHeader-currentTimeIndicatorDot"></div>';startDate.getTime()<endDateTimeMs;)html=(html+='<div class="timeslotHeader" style="width:'+width+'%;">')+getDisplayTime(startDate)+"</div>",startDate.setTime(startDate.getTime()+cellDurationMs);return html}(nowHours,today),this.updateDateButtonText(Math.abs(this.scroller.getScrollLeft())),this.itemsContainer.resume({refresh:!0}).then(function(){_loading.default.hide()})}var dateLocalOptions={weekday:"short",month:"short",day:"numeric"};function hideOrShow(elem,hide){!0===elem._showing?hide&&(elem.classList.add("hide"),elem._showing=!1):hide||(elem.classList.remove("hide"),elem._showing=!0)}function getProgramMap(epgItem){for(var programMap={},items=epgItem.Programs,i=0,length=items.length;i<length;i++){var item=items[i];programMap[item.Id]=item}return programMap}Guide.prototype.updateDateButtonText=function(scrollLeft,scrollWidth){null==scrollWidth&&(scrollWidth=this.scroller.getScrollWidth());var startDate=this._startDateMs,scrollLeft=scrollLeft/scrollWidth*(this._endDateMs-startDate),scrollWidth=(this.currentPositionMs=scrollLeft+=startDate,new Date(scrollLeft)),startDate=this.btnDateText||(this.btnDateText=this.options.element.querySelector(".btnDateText-side")),scrollWidth=(startDate.innerHTML=_datetime.default.toLocaleDateString(scrollWidth,dateLocalOptions),this.btnLiveGuide),scrollLeft=(!_layoutmanager.default.tv&&Math.abs(scrollLeft-Date.now())>cellDurationMs?hideOrShow(scrollWidth,!1):hideOrShow(scrollWidth,!0),_usersettings.default.guideChannelStyle()),scrollWidth={};scrollWidth.showChannelImage="name"!==scrollLeft,scrollWidth.showChannelName="image"!==scrollLeft,scrollWidth.showChannelNumber=_usersettings.default.showChannelNumberInGuide(),scrollWidth.showChannelImage&&(!scrollWidth.showChannelNumber||scrollWidth.showChannelImage&&scrollWidth.showChannelName)?startDate.classList.add("hide"):startDate.classList.remove("hide")},Guide.prototype.stopCurrentTimeUpdateInterval=function(){var interval=this.currentTimeUpdateInterval;interval&&(interval.destroy(),this.currentTimeUpdateInterval=null)},Guide.prototype.startCurrentTimeUpdateInterval=function(){var interval=this.currentTimeUpdateInterval,fn=function(){for(var dots=this.currentTimeIndicatorDots,startDateMs=this._startDateMs,endDate=this._endDateMs,now=Date.now(),pct=startDateMs&&endDate?(now-startDateMs)/(endDate-startDateMs)*100:-100,showIndicator=0<=pct&&pct<=100,displayTime=(pct=pct.toFixed(2)+"%",getDisplayTime(new Date(now))),i=0,length=dots.length;i<length;i++){var dot=dots[i];dot.style[InsetInlineStartProp]=pct,dot.setAttribute("aria-label",displayTime),dot.title=displayTime,showIndicator?dot.classList.remove("hide"):dot.classList.add("hide")}}.bind(this);interval||(this.currentTimeUpdateInterval=new _methodtimer.default({onInterval:fn,timeoutMs:4e4,type:"interval"})),setTimeout(fn,200)},Guide.prototype.pause=function(){this.stopCurrentTimeUpdateInterval();var itemsContainer=this.itemsContainer;itemsContainer&&itemsContainer.pause()},Guide.prototype.resume=function(options){var instance=this;return initialRender(instance).then(function(){var itemsContainer;return options&&options.refresh?instance.refresh().then(function(instance,options){return function(){options&&options.autoFocus&&setTimeout(function(){_focusmanager.default.autoFocus(instance.itemsContainer)},_layoutmanager.default.tv?500:100)}}(instance,options)):(itemsContainer=instance.itemsContainer)?itemsContainer.resume(options).then(function(){instance.startCurrentTimeUpdateInterval();var activeElement=document.activeElement;activeElement&&itemsContainer.contains(activeElement)||onLiveButtonClick.call(instance)}):Promise.resolve()})},Guide.prototype.refresh=function(){this.cancelDataLoadTimer();var apiClient=_connectionmanager.default.getApiClient(this.options.serverId);return this.programCache=null,apiClient.getLiveTvGuideInfo().then(onGetGuideInfo.bind(this))},Guide.prototype.getItems=function(query){var options=this.options,options=_connectionmanager.default.getApiClient(options.serverId),endDate=this._startDateMs+msPerPage,maxEndDate=this._endDateMs-2e3,endDate=Math.min(endDate,maxEndDate),maxEndDate=Object.assign({Fields:"PrimaryImageAspectRatio",Limit:25,MaxStartDate:new Date(endDate).toISOString(),MinEndDate:new Date(this._startDateMs+1e3).toISOString(),ProgramFields:getProgramFieldsProperty(),TagIds:_usersettings.default.get("guide-tagids")||null},query||{}),endDate=this.categoryOptions.categories||[],query=!endDate.length||-1!==endDate.indexOf("movies"),displaySportsContent=!endDate.length||-1!==endDate.indexOf("sports"),displayNewsContent=!endDate.length||-1!==endDate.indexOf("news"),displayKidsContent=!endDate.length||-1!==endDate.indexOf("kids"),endDate=!endDate.length||-1!==endDate.indexOf("series");return query&&displaySportsContent&&displayNewsContent&&displayKidsContent?(maxEndDate.IsMovie=null,maxEndDate.IsSports=null,maxEndDate.IsKids=null,maxEndDate.IsNews=null,maxEndDate.IsSeries=null):(displayNewsContent&&(maxEndDate.IsNews=!0),displaySportsContent&&(maxEndDate.IsSports=!0),displayKidsContent&&(maxEndDate.IsKids=!0),query&&(maxEndDate.IsMovie=!0),endDate&&(maxEndDate.IsSeries=!0)),_usersettings.default.addLiveTvChannelSortingToQuery(maxEndDate,_globalize.default),options.getEpg(maxEndDate).then(function(result){for(var items=result.Items,i=0,length=items.length;i<length;i++){var epgRow=items[i];epgRow.ChannelId=epgRow.Channel.Id,epgRow.ProgramMap=getProgramMap(epgRow)}return result}.bind(this))},Guide.prototype.moveChannelPages=function(offset){var rowsPerPage=_layoutmanager.default.tv?5:12;0<offset?this.itemsContainer.pageDown(document.activeElement,rowsPerPage):this.itemsContainer.pageUp(document.activeElement,rowsPerPage)},Guide.prototype.moveDays=function(offset){scrollToTimeMs(this,this.currentPositionMs+864e5*offset,!1,!0)},Guide.prototype.startDataLoadTimer=function(scrollLeft,autoFocus,ignoreFocusedProgram){autoFocus={scrollLeft:scrollLeft,autoFocus:autoFocus,ignoreFocusedProgram:ignoreFocusedProgram},this._loadDataInfo=autoFocus,ignoreFocusedProgram=this.scroller.getScrollWidth(),scrollLeft=getTimeBlockStart(this,scrollLeft,ignoreFocusedProgram);scrollLeft!==this._dataLoadSection&&(this.cancelDataLoadTimer(),this._loadDataInfo=autoFocus,this._dataLoadSection=scrollLeft,this.getProgramsTimeout=setTimeout(this.boundLoadPrograms,100))},Guide.prototype.cancelDataLoadTimer=function(){var timeout=this.getProgramsTimeout;timeout&&(clearTimeout(timeout),this.getProgramsTimeout=null,this._loadDataInfo=null,this._dataLoadSection=null)},Guide.prototype.getListOptions=function(items){return{renderer:new _gridrowrenderer.default({}),options:{categories:this.categoryOptions.categories,startDateMs:this._startDateMs,endDateMs:this._endDateMs,channelAction:this.options.channelAction||"link",showEpisodeTitle:this.options.showEpisodeTitle},virtualScrollLayout:"vertical-grid"}},Guide.prototype.destroy=function(){this.cancelDataLoadTimer();var options=this.options;this.stopCurrentTimeUpdateInterval(),options&&((options=this.onTimerCreatedFn)&&(_events.default.off(_api.default,"TimerCreated",options),this.onTimerCreatedFn=null),(options=this.onSeriesTimerCreatedFn)&&(_events.default.off(_api.default,"SeriesTimerCreated",options),this.onSeriesTimerCreatedFn=null),(options=this.onTimerCancelledFn)&&(_events.default.off(_api.default,"TimerCancelled",options),this.onTimerCancelledFn=null),(options=this.onSeriesTimerCancelledFn)&&(_events.default.off(_api.default,"SeriesTimerCancelled",options),this.onSeriesTimerCancelledFn=null),(options=this.channelCellResizeObserver)&&(options.disconnect(),this.channelCellResizeObserver=null),this.itemsContainer=null,this.currentTimeIndicatorDot=null,this.scroller=null,this.headerScroller=null,this.firstChannelCell=null,this.options=null,this._endDateMs=null,this._startDateMs=null,this.channelCellWidth=null,this.programCache=null,this.btnDateText=null,this.btnLiveGuide=null,this.focusSourceIsPointer=null,this._previousFocusItem=null,this.programBorderInlineStartWidth=null)},_exports.default=Guide});