29 lines
No EOL
42 KiB
JavaScript
29 lines
No EOL
42 KiB
JavaScript
import browser from"./../../browser.js";import itemShortcuts from"./../../shortcuts.js";import connectionManager from"./../../emby-apiclient/connectionmanager.js";import serverNotifications from"./../../common/input/api.js";import events from"./../../emby-apiclient/events.js";import globalize from"./../../common/globalize.js";import dom from"./../../dom.js";import layoutManager from"./../../layoutmanager.js";import datetime from"./../../common/datetime.js";import focusManager from"./../../focusmanager.js";import loading from"./../../loading/loading.js";import mouseManager from"./../../input/mouse.js";import userSettings from"./../../common/usersettings/usersettings.js";import gridRowRenderer from"./gridrowrenderer.js";import"./../emby-button/emby-button.js";import"./../emby-scroller/emby-scroller.js";import"./../emby-button/paper-icon-button-light.js";import MethodTimer from"./../../common/methodtimer.js";import EmbyItemsContainer from"./../emby-itemscontainer/emby-itemscontainer.js";import inputManager from"./../../common/inputmanager.js";import playbackManager from"./../../common/playback/playbackmanager.js";require(["css!modules/emby-elements/guide/guide.css","programStyles","material-icons","flexStyles"]);let virtualChunkSize=25,cellCurationMinutes=30,cellDurationMs=60*cellCurationMinutes*1e3,msPerMinute=6e4,msPerHour=36e5,msPerDay=864e5,msPerPage=8*msPerHour,startId=Date.now();function showActionSheet(options){return Emby.importModule("./modules/actionsheet/actionsheet.js").then(function(ActionSheet){return ActionSheet.show(options)})}function normalizeDateToTimeslot(value,roundUp){var delta=value%cellDurationMs;return roundUp&&delta&&(value+=cellDurationMs),value-=delta}function onSettingsButtonClick(e){let instance=this;Emby.importModule("./modules/emby-elements/guide/guide-settings.js").then(function(guideSettingsDialog){guideSettingsDialog.show({categoryOptions:instance.categoryOptions,positionTo:e.target,positionY:"bottom",positionX:"after"},connectionManager.getApiClient(instance.options.serverId)).then(function(){instance.refresh()})})}function getDateMenuOptions(instance){var items=[];let start=new Date(instance._startDateMs);for(var end=new Date(instance._endDateMs),today=new Date,nowHours=today.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.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}function onDateButtonClick(e){showActionSheet({items:getDateMenuOptions(this),positionTo:e.target,title:globalize.translate("Date"),positionY:"bottom",hasItemSelectionState:!0}).then(onSelectedDateValue.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}))}function onSelectedDateValue(value){scrollToTimeMs(this,value,!1,!0)}function onTimerCreated(e,apiClient,data){var programId=data.ProgramId,newTimerId=data.Id,cells=this.options.element.querySelectorAll('.programCell[data-id="'+programId+'"]');for(let i=0,length=cells.length;i<length;i++){var programCellInner,cell=cells[i];cell.querySelector(".timerIcon")||(programCellInner=cell.querySelector(".programCellInner"),data.SeriesTimerId?programCellInner.insertAdjacentHTML("beforeend",'<i class="timerIcon md-icon md-icon-fill programIcon"></i>'):programCellInner.insertAdjacentHTML("beforeend",'<i class="timerIcon md-icon md-icon-fill programIcon"></i>')),newTimerId&&cell.setAttribute("data-timerid",newTimerId)}}function onSeriesTimerCreated(e,apiClient,data){}function onTimerCancelled(e,apiClient,data){var options=this.options,data=data.Id,cells=options.element.querySelectorAll('.programCell[data-timerid="'+data+'"]');for(let 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")}}function onSeriesTimerCancelled(e,apiClient,data){var options=this.options,data=data.Id,cells=options.element.querySelectorAll('.programCell[data-seriestimerid="'+data+'"]');for(let 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")}}let 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 updateProgramCellOnScroll(cell,scrollPct,borderPct,hidden){let pctOffsetStart,showLeftCaret;if(!hidden){let left=cell.posLeft,width=(left||(left=parseFloat(cell.style[InsetInlineStartProp].replace("%","")),cell.posLeft=left),cell.posWidth);width||(width=parseFloat(cell.style.width.replace("%","")),cell.posWidth=width),left<scrollPct&&(hidden=scrollPct-left,pctOffsetStart=hidden/(width-borderPct)*100),showLeftCaret=pctOffsetStart&&pctOffsetStart<100&&.1<pctOffsetStart}let programCellInner=cell.programCellInner,caret=(!programCellInner&&pctOffsetStart&&(programCellInner=cell.firstChild,cell.programCellInner=programCellInner),cell.caret);if(!caret&&pctOffsetStart&&(caret=programCellInner.firstChild,cell.caret=caret),programCellInner){if(showLeftCaret)return setPaddingInlineStart(programCellInner,pctOffsetStart+"%"),caret&&!1!==caret._hidden&&(caret._hidden=!1,caret.classList.remove("hide")),!0;pctOffsetStart?setPaddingInlineStart(programCellInner,pctOffsetStart+"%"):setPaddingInlineStart(programCellInner,"0"),caret&&!1===caret._hidden&&(caret._hidden=!0,caret.classList.add("hide"))}return!1}function getChannelCellWidth(instance){let channelCellWidth=instance.channelCellWidth;var scroller,focusScrollOffsetLeft;return channelCellWidth||(channelCellWidth=instance.firstChannelCell.offsetWidth,instance.channelCellWidth=channelCellWidth,(scroller=instance.scroller).setFocusScrollOffsetLeft&&(focusScrollOffsetLeft=(0-channelCellWidth)*scroller.getScrollLeftMultiplier(),scroller.setFocusScrollOffsetLeft(focusScrollOffsetLeft),focusScrollOffsetLeft=instance.headerScroller.querySelector(".timeslotHeader"))&&(scroller.scroller.options.scrollSnapSizeX=focusScrollOffsetLeft.getBoundingClientRect().width)),channelCellWidth}function getTimeBlockStart(instance,scrollLeft,scrollWidth){var startDate=instance._startDateMs,scrollLeft=scrollWidth?scrollLeft/scrollWidth*(instance._endDateMs-startDate):0;return(scrollLeft=Math.floor(scrollLeft))-scrollLeft%msPerPage+startDate}function getProgramFieldsProperty(){var programFields=[];return"true"===userSettings.get("false"!==userSettings.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 apiClient=connectionManager.getApiClient(instance.options.serverId);let cacheKey=[apiClient.getCurrentUserId(),timeBlockStart.toString(),channelIds.join(",")].join("|"),promise;instance.programCache||(instance.programCache={});var cachedResult=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(),EnableImages:!1},promise=apiClient.getLiveTvPrograms(timeBlockStart)),promise.then(function(result){return instance.programCache||(instance.programCache={}),instance.programCache[cacheKey]=result,insertLazyLoadedPrograms(instance,epgRowMap,result.Items)})}function getInsertIndex(programs,programStartTime){var numPrograms=programs.length;let insertAtIndex=numPrograms;for(let i=0,length=numPrograms;i<length;i++)if(programStartTime<=programs[i].StartDateLocalMs){insertAtIndex=i;break}return insertAtIndex}let ChannelProgramsChildIndex=1;function addProgramToList(instance,epgItem,program){gridRowRenderer.parseDates(program);let programs=epgItem.Programs,programMap=epgItem.ProgramMap;var programId=program.Id;let insertAtIndex;programMap[programId]||(programMap[programId]=program,insertAtIndex=getInsertIndex(programs,program.StartDateLocalMs),programs.splice(insertAtIndex,0,program));var channelProgramsElement,epgItem=epgItem.RowElement;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),epgItem=(programId=instance.itemsContainer.currentListOptions.options).endMs-programId.startMs,instance=gridRowRenderer.getProgramHtml(program,programId,epgItem),(program=channelProgramsElement.children[insertAtIndex])?program.insertAdjacentHTML("beforebegin",instance):channelProgramsElement.insertAdjacentHTML("beforeend",instance))}function insertLazyLoadedPrograms(instance,epgRowMap,programs){for(let i=0,length=programs.length;i<length;i++){var program=programs[i],epgItem=epgRowMap[program.ChannelId];epgItem&&addProgramToList(instance,epgItem,program)}updateCellTexts(instance)}function loadProgramsIfNeeded(){this._dataLoadSection=null;var itemsContainer=this.itemsContainer,activeItems=itemsContainer.virtualScroller.getActiveItems(),channelIdsNeedingData=[],epgRowMap={};for(let i=activeItems.firstIndex,last=activeItems.lastIndex;i<=last;i++){var channelId,itemIndex=i,itemIndex=itemsContainer.getItem(itemIndex);itemIndex&&(epgRowMap[channelId=itemIndex.Channel.Id]=itemIndex,channelIdsNeedingData.push(channelId))}if(channelIdsNeedingData.length){let loadDataInfo=this._loadDataInfo;var timeBlockStart,activeItems=loadDataInfo.scrollLeft,channelCellWidth=getChannelCellWidth(this),scrollWidth=this.scroller.getScrollWidth(),channelCellWidth=(scrollWidth-=channelCellWidth,this.scroller.getScrollContainerBoundingClientRect().width),originalScrollLeft=activeItems,timeblocks=[],promises=[];activeItems=Math.min(originalScrollLeft,scrollWidth),timeBlockStart=getTimeBlockStart(this,Math.max(activeItems,0),scrollWidth),-1===timeblocks.indexOf(timeBlockStart)&&(promises.push(loadPrograms(this,epgRowMap,channelIdsNeedingData,timeBlockStart)),timeblocks.push(timeBlockStart)),activeItems=originalScrollLeft,activeItems-=channelCellWidth,activeItems=Math.min(activeItems,scrollWidth),timeBlockStart=getTimeBlockStart(this,Math.max(activeItems,0),scrollWidth),-1===timeblocks.indexOf(timeBlockStart)&&(promises.push(loadPrograms(this,epgRowMap,channelIdsNeedingData,timeBlockStart)),timeblocks.push(timeBlockStart)),activeItems=originalScrollLeft,activeItems+=channelCellWidth,activeItems=Math.min(activeItems,scrollWidth),timeBlockStart=getTimeBlockStart(this,Math.max(activeItems,0),scrollWidth),-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.focus(row,{ignoreFocusedProgram:loadDataInfo.ignoreFocusedProgram})})}}function onScroll(e){var channelCellWidth,scrollWidth,absScrollLeft,scrollPct,scrollLeft=(e.currentTarget||e.target).getScrollLeft(),scrollXChanged=this.lastScrollLeft!==scrollLeft||browser.firefox;scrollXChanged&&this.headerScroller.scrollToPosition({left:scrollLeft,behavior:"instant"}),this._startDateMs&&this._endDateMs&&(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())&&(scrollWidth-=channelCellWidth,absScrollLeft=scrollLeft?Math.abs(scrollLeft):0,this.lastHorizontalScrollPct=scrollPct=scrollLeft?absScrollLeft/scrollWidth*100:0,this.startDataLoadTimer(absScrollLeft,scrollWidth,e.autoFocus,e.autoFocus),this.lastScrollLeft=scrollLeft,updateCellTexts(this,scrollPct,e.updateProgramTextRow,channelCellWidth,scrollWidth),scrollXChanged)&&this.updateDateButtonText(null,absScrollLeft,scrollWidth)}function onHeaderScroll(e){}function updateCellTexts(instance,scrollPct,rowToUpdate,channelCellWidth,scrollWidth){null==channelCellWidth&&(channelCellWidth=getChannelCellWidth(instance)),null==scrollWidth&&(scrollWidth=instance.scroller.getScrollWidth(),scrollWidth-=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{var activeItemElements=instance.itemsContainer.virtualScroller.getActiveItems().elements;for(let i=0,length=activeItemElements.length;i<length;i++)updateProgramCellTextsForRow(instance,activeItemElements[i],scrollPct,pixelPct)}}function onChannelCellResize(entries){entries[0]&&(this.channelCellWidth=null,this.programBorderInlineStartWidth=null)}function updateProgramCellTextsForRow(instance,row,scrollPct,pixelPct){row=row.children[ChannelProgramsChildIndex];if(row){var style,programCells=row.children;let borderPct=0,caretFound;for(let i=0,length=programCells.length;i<length;i++){if(0===i){let borderWidth=instance.programBorderInlineStartWidth;null==borderWidth&&(style=getComputedStyle(programCells[i]),borderWidth=parseFloat(style[BorderInlineStartWidthProp].replace("px","")),instance.programBorderInlineStartWidth=borderWidth),borderPct=borderWidth*pixelPct}updateProgramCellOnScroll(programCells[i],scrollPct,borderPct,caretFound)&&(caretFound=!0)}}}function getFocusableElementsInRow(newRowToFocus,activeElement,direction,focusOptions){var isRTL="rtl"===document.dir,scrollToChannelId=this.scrollToChannelId,scrollToChannelId=(scrollToChannelId&&(-1!==(scrollToChannelId=this.itemsContainer.indexOfItemId(scrollToChannelId))&&(scrollToChannelId=this.itemsContainer.getElement(scrollToChannelId))&&(newRowToFocus=scrollToChannelId),this.scrollToChannelId=null),activeElement.closest(".channelCell")),isGoingBackHorizontally=isRTL?1===direction:0===direction;if(scrollToChannelId){if(newRowToFocus){let elems=newRowToFocus.querySelectorAll(".channelCell");return elems.length?elems:null}if(isGoingBackHorizontally)return null}newRowToFocus=newRowToFocus||activeElement.closest(".epgRow");let elems;var focusedProgramCell=activeElement.closest(".programCell");if(isGoingBackHorizontally||focusedProgramCell&&null!=direction&&direction<2){let elems=newRowToFocus.querySelectorAll(".programCell,.channelCell");isGoingBackHorizontally=Array.prototype.indexOf.call(elems,activeElement);if(-1!==isGoingBackHorizontally){let offset=0===direction||2===direction?-1:1;direction<2&&isRTL&&(offset*=-1);activeElement=isGoingBackHorizontally+offset,activeElement=Math.min(Math.max(0,activeElement),elems.length-1);if((elems=Array.prototype.slice.call(elems,activeElement,activeElement+1)).length)return elems}return null}if(elems=newRowToFocus.querySelectorAll(".programCell"),null==direction||2<=direction||scrollToChannelId&&(isRTL?0===direction:1===direction)){isGoingBackHorizontally=this.currentPositionMs+msPerMinute;let currentPositionMs;currentPositionMs=focusedProgramCell&&(null==direction||2<=direction)&&!focusOptions?.ignoreFocusedProgram?(currentPositionMs=getProgramFromProgramCell(focusedProgramCell).StartDateLocalMs,Math.max(currentPositionMs,isGoingBackHorizontally)):isGoingBackHorizontally;var activeElement=Date.now(),programs=(activeElement>=currentPositionMs&¤tPositionMs+cellDurationMs>activeElement&&(currentPositionMs=activeElement),newRowToFocus.Programs||[]);let startIndex=0;for(let i=0,length=programs.length;i<length;i++){if(!(programs[i].EndDateLocalMs<=currentPositionMs))break;(startIndex=i)<length-1&&startIndex++}(elems=0<startIndex?Array.prototype.slice.call(elems,startIndex):elems).length&&(elems=Array.prototype.slice.call(elems,0,1))}return elems.length||null==direction&&(elems=newRowToFocus.querySelectorAll(".channelCell")).length?elems:null}function updateVirtualElement(row,item,index){let focusedId;var activeElement;row&&(activeElement=document.activeElement,row.contains(activeElement))&&(activeElement=activeElement.closest("button"))&&(focusedId=activeElement.getAttribute("data-id")),EmbyItemsContainer.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.focus(activeElement):focusManager.autoFocus(row))}function onRecycleElement(row,index){row.ProgramMap=null,row.Programs=null;row=this.itemsContainer.getItem(index);row&&(row.RowElement=null)}function fillTagsHtml(instance,items){let html="",selectedTagIds=userSettings.get("guide-tagids")||null;selectedTagIds=selectedTagIds?selectedTagIds.split(","):[];for(let i=0,length=items.length;i<length;i++){var item=items[i];html+='<button type="button" is="emby-button" class="raised raised-mini raised-outline guide-filter-button btnGuideTag" data-id="'+item.Id+'">'+item.Name+"</button>"}var parent=instance.options.element.querySelector(".tagFilters");parent.innerHTML=html;for(let i=0,length=selectedTagIds.length;i<length;i++){var id=selectedTagIds[i],id=parent.querySelector('button[data-id="'+id+'"]');id&&addSelectedClass(id)}}function refreshTagFilters(instance){layoutManager.tv||instance.options.condensed?(instance.filterScroller.classList.add("hide"),instance.settingsButtons[1].classList.remove("hide")):(instance.filterScroller.classList.remove("hide"),instance.settingsButtons[1].classList.add("hide")),connectionManager.getApiClient(instance.options.serverId).getLiveTvChannelTags({SortBy:"SortName",SortOrder:"Ascending",EnableImages:!1,EnableUserData:!1}).then(function(result){fillTagsHtml(instance,result.Items),selectAllButtonIfNeeded(instance)})}function afterRefresh(){var firstChannelCell=this.firstChannelCell,settingsChannelCell=this.settingsChannelCell,listOptions=this.itemsContainer.currentListOptions?.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")),listOptions=listOptions.channelCellClass||"";listOptions.includes("channelCell-wide2")?(firstChannelCell.classList.add("channelCell-wide2"),firstChannelCell.classList.remove("channelCell-wide"),settingsChannelCell.classList.add("channelCell-wide2"),settingsChannelCell.classList.remove("channelCell-wide"),elem.classList.add("guideEpg-currentTimeIndicatorDot-wide2"),elem.classList.remove("guideEpg-currentTimeIndicatorDot-wide")):listOptions.includes("channelCell-wide")?(firstChannelCell.classList.add("channelCell-wide"),firstChannelCell.classList.remove("channelCell-wide2"),settingsChannelCell.classList.add("channelCell-wide"),settingsChannelCell.classList.remove("channelCell-wide2"),elem.classList.add("guideEpg-currentTimeIndicatorDot-wide"),elem.classList.remove("guideEpg-currentTimeIndicatorDot-wide2")):(firstChannelCell.classList.remove("channelCell-wide","channelCell-wide2"),settingsChannelCell.classList.remove("channelCell-wide","channelCell-wide2"),elem.classList.remove("guideEpg-currentTimeIndicatorDot-wide","guideEpg-currentTimeIndicatorDot-wide2")),this.startCurrentTimeUpdateInterval()}function onLiveButtonClick(e){this.scrollToNow()}function removeSelectedClass(elems){for(let i=0,length=elems.length;i<length;i++){var elem=elems[i];elem.classList.remove("emby-tab-button-active"),elem.querySelector("i")?.remove()}}function removeItemOnce(arr,value){value=arr.indexOf(value);return-1<value&&arr.splice(value,1),arr}function addSelectedClass(elem){elem.classList.add("emby-tab-button-active"),elem.querySelector("i")||elem.insertAdjacentHTML("afterbegin",'<i class="md-icon button-icon button-icon-left md-icon-fill guide-filters-active-icon">check_circle</i>')}function selectAllButtonIfNeeded(instance){instance.options.element.querySelectorAll(".emby-tab-button-active:not(.btnGuideCategory-all)").length||addSelectedClass(instance.options.element.querySelector(".btnGuideCategory-all"))}function onFilterScrollerClick(e){let needsRefresh;var btnGuideCategory=e.target.closest(".btnGuideCategory"),type=(btnGuideCategory&&((type=btnGuideCategory.getAttribute("data-type"))?btnGuideCategory.classList.contains("emby-tab-button-active")?(removeSelectedClass([btnGuideCategory]),removeItemOnce(this.categoryOptions.categories,type),selectAllButtonIfNeeded(this)):(removeSelectedClass(this.options.element.querySelectorAll(".btnGuideCategory-all")),addSelectedClass(btnGuideCategory),this.categoryOptions.categories.push(type)):(this.categoryOptions.categories=[],userSettings.set("guide-tagids",""),removeSelectedClass(this.options.element.querySelectorAll(".emby-tab-button-active:not(.btnGuideCategory-all)")),addSelectedClass(btnGuideCategory)),needsRefresh=!0),e.target.closest(".btnGuideTag"));if(type){let selectedTagIds=userSettings.get("guide-tagids")||null;selectedTagIds=selectedTagIds?selectedTagIds.split(","):[];btnGuideCategory=type.getAttribute("data-id");type.classList.contains("emby-tab-button-active")?(removeSelectedClass([type]),removeItemOnce(selectedTagIds,btnGuideCategory),selectAllButtonIfNeeded(this)):(removeSelectedClass(this.options.element.querySelectorAll(".btnGuideCategory-all")),addSelectedClass(type),selectedTagIds.push(btnGuideCategory)),userSettings.set("guide-tagids",selectedTagIds.join(",")),needsRefresh=!0}needsRefresh&&this.refresh()}function onFocusInScroller(e){var item,e=e.target;e.classList.contains("programCell")&&(item=getProgramFromProgramCell(e=e))&&events.trigger(this,"focus",[{item:item,element:e}])}function bindScrollEventOnUpgrade(instance){instance.scroller.waitForCustomElementUpgrade().then(function(){instance.scroller.addScrollEventListener(onScroll.bind(instance),{passive:!0})}),instance.headerScroller.waitForCustomElementUpgrade().then(function(){instance.headerScroller.addScrollEventListener(onHeaderScroll.bind(instance),{passive:!0})})}function getContextMenuElementFromChildNode(child){return itemShortcuts.getItemElementFromChildNode(child,!1,this)}function getScrollButtonPageSize(scrollContainerSize,scrollType){return scrollContainerSize=scrollContainerSize-getChannelCellWidth(this)-20,Math.max(scrollContainerSize,0)}function initialRender(instance){return instance.rendered?Promise.resolve():(instance.rendered=!0,require(["text!modules/emby-elements/guide/tvguide.template.html"]).then(function(responses){var context=instance.options.element,responses=(context.classList.add("tvguide"),context.insertAdjacentHTML("beforeend",globalize.translateDocument(responses[0],"sharedcomponents")),instance.firstChannelCell=context.querySelector(".firstChannelCell"),instance.settingsChannelCell=context.querySelector(".settingsChannelCell"),instance.onTimerCreatedFn=onTimerCreated.bind(instance),events.on(serverNotifications,"TimerCreated",instance.onTimerCreatedFn),instance.onSeriesTimerCreatedFn=onSeriesTimerCreated.bind(instance),events.on(serverNotifications,"SeriesTimerCreated",instance.onSeriesTimerCreatedFn),instance.onTimerCancelledFn=onTimerCancelled.bind(instance),events.on(serverNotifications,"TimerCancelled",instance.onTimerCancelledFn),instance.onSeriesTimerCancelledFn=onSeriesTimerCancelled.bind(instance),events.on(serverNotifications,"SeriesTimerCancelled",instance.onSeriesTimerCancelledFn),instance.scroller=instance.options.element.querySelector(".virtualScrollerScrollContainer"),instance.scroller.getScrollButtonPageSize=getScrollButtonPageSize.bind(instance),instance.headerScroller=instance.options.element.querySelector(".headerScroller"),instance.uniqueId=startId,instance.scrollSliderUniqueClass="epgScrollSlider"+startId,instance.scroller.classList.add("epgVirtualScrollerScrollContainer-both"),bindScrollEventOnUpgrade(instance),context.querySelector(".itemsContainer"));responses.fetchData=instance.getItems.bind(instance),responses.afterRefresh=afterRefresh.bind(instance),responses.virtualChunkSize=virtualChunkSize,responses.getListOptions=instance.getListOptions.bind(instance),instance.itemsContainer=responses,instance.boundFocusableElements=getFocusableElementsInRow.bind(instance),responses.updateVirtualElement=updateVirtualElement.bind(instance),responses.onRecycleElement=onRecycleElement.bind(instance),responses.getContextMenuElementFromChildNode=getContextMenuElementFromChildNode.bind(responses),instance.channelCellResizeObserver=new ResizeObserver(onChannelCellResize.bind(instance),{}),instance.channelCellResizeObserver.observe(instance.firstChannelCell),instance.channelCellResizeObserver.observe(instance.scroller);let i,length;var settingsButtons=context.querySelectorAll(".btnGuideViewSettings");for(instance.settingsButtons=settingsButtons,i=0,length=settingsButtons.length;i<length;i++)settingsButtons[i].addEventListener("click",onSettingsButtonClick.bind(instance));for(instance.dateButtons=context.querySelectorAll(".btnSelectDate"),i=0,length=instance.dateButtons.length;i<length;i++)instance.dateButtons[i].addEventListener("click",onDateButtonClick.bind(instance));dom.addEventListener(instance.scroller,"focus",onFocusInScroller.bind(instance),{capture:!0,passive:!0}),instance.btnLiveGuide=instance.options.element.querySelector(".btnLiveGuide"),dom.addEventListener(instance.btnLiveGuide,"click",onLiveButtonClick.bind(instance),{capture:!0,passive:!0}),instance.filterScroller=context.querySelector(".filterScroller"),dom.addEventListener(instance.filterScroller,"click",onFilterScrollerClick.bind(instance),{}),instance.styleElementUniqueClass="guideStyle"+startId;responses=context.querySelectorAll(".epgScrollSlider");responses[0].classList.add(instance.scrollSliderUniqueClass),responses[1].classList.add(instance.scrollSliderUniqueClass),layoutManager.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=rowElement||programCell.parentNode.parentNode).ProgramMap;if(programCell){programCell=programCell[programId];if(programCell)return programCell}var programs=rowElement.Programs||[];for(let i=0,length=programs.length;i<length;i++){var program=programs[i];if(program.Id===programId)return program}}function handleBack(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()?void 0:(e.preventDefault(),e.stopPropagation(),void instance.scrollToNow())}instance.itemsContainer.scrollToIndex(0,{},!0),e.preventDefault(),e.stopPropagation()}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.isPlayingMediaType(["Audio","Video"])||(e.target.closest(".channelCell")?this.moveChannelPages(1):this.moveDays(1),e.preventDefault());break;case"rewind":playbackManager.isPlayingMediaType(["Audio","Video"])||(e.target.closest(".channelCell")?this.moveChannelPages(-1):this.moveDays(-1),e.preventDefault());break;case"nexttrack":case"nextchapter":case"next":playbackManager.isPlayingMediaType(["Audio","Video"])||(this.moveDays(1),e.preventDefault());break;case"previoustrack":case"previouschapter":case"previous":playbackManager.isPlayingMediaType(["Audio","Video"])||(this.moveDays(-1),e.preventDefault());break;case"back":handleBack(e,this)}}function Guide(options){(this.options=options).showEpisodeTitle=!options.condensed,this.categoryOptions={categories:[]},this.boundLoadPrograms=loadProgramsIfNeeded.bind(this),this.lastScrollTop=0,this.lastScrollLeft=0,inputManager.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.getDisplayTime(date)}function getTimeslotHeadersHtml(originalStartDateMs,endDateTimeMs){let startDate=new Date(originalStartDateMs),numSlots=0;for(;startDate.getTime()<endDateTimeMs;)numSlots++,startDate.setTime(startDate.getTime()+cellDurationMs);var width=100/numSlots;startDate=new Date(originalStartDateMs);let 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}function renderWidthCss(instance){var numCells=Math.ceil((instance._endDateMs-instance._startDateMs)/cellDurationMs);let html=`
|
|
.epgScrollSlider {
|
|
width: `+32*numCells+`ch;
|
|
}
|
|
|
|
@media all and (min-width: 80em) {
|
|
|
|
.epgScrollSlider {
|
|
width: `+40*numCells+`ch;
|
|
}
|
|
}
|
|
|
|
@media all and (min-width: 120em) {
|
|
|
|
.epgScrollSlider {
|
|
width: `+50*numCells+`ch;
|
|
}
|
|
}
|
|
|
|
@media all and (orientation: portrait) {
|
|
|
|
.epgScrollSlider {
|
|
width: calc(`+numCells+` * min(50ch, 34vw));
|
|
}
|
|
}
|
|
.epgScrollSlider-tv {
|
|
width: `+19*numCells+`vw;
|
|
}
|
|
`,elem=(console.log("rendering guide width css"),html=html.replaceAll("epgScrollSlider",instance.scrollSliderUniqueClass),document.querySelector("."+instance.styleElementUniqueClass));elem?elem.innerHTML=html:((elem=document.createElement("style")).innerHTML=html,document.head.appendChild(elem))}function onGetGuideInfo(guideInfo){var guideInfo=Date.parse(guideInfo.EndDate),startDate=(loading.show(),this._startDateMs=normalizeDateToTimeslot(Date.now())),guideInfo=this._endDateMs=normalizeDateToTimeslot(guideInfo,!0),guideInfo=(renderWidthCss(this),this.scroller.notifyResized(),this.options.element.querySelector(".timeslotHeaders").innerHTML=getTimeslotHeadersHtml(startDate,guideInfo),this.currentPositionMs?null:startDate);return this.updateDateButtonText(guideInfo,Math.abs(this.scroller.getScrollLeft())),refreshTagFilters(this),this.itemsContainer.virtualScroller?.resetAll(),this.itemsContainer.resume({refresh:!0}).then(function(){loading.hide()})}let 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 isInCurrentFocusScope(instance){return!focusManager.hasExclusiveFocusScope()}Guide.prototype.updateCurrentPositionIfNeeded=function(){var now,currentPositionMs=this.currentPositionMs;currentPositionMs&&(console.log("currentPositionMs: "+currentPositionMs),currentPositionMs=normalizeDateToTimeslot(currentPositionMs),console.log("currentPositionMs normalized: "+currentPositionMs),now=Date.now(),console.log("now: "+now),currentPositionMs<=now&&now<currentPositionMs+cellDurationMs?console.log("scrollToNow not needed"):isInCurrentFocusScope(this)&&this.scrollToNow())},Guide.prototype.scrollToNow=function(){var autoFocus=layoutManager.tv&&isInCurrentFocusScope(this);scrollToTimeMs(this,Date.now(),!0,autoFocus)},Guide.prototype.updateDateButtonText=function(currentPositionMs,scrollLeft,scrollWidth){if(!currentPositionMs){var startDate=this._startDateMs,endDate=this._endDateMs;if(!startDate||!endDate)return;if(0===scrollWidth)return;if(null==scrollWidth){var channelCellWidth=getChannelCellWidth(this);if(!channelCellWidth)return;if(!(scrollWidth=this.scroller.getScrollWidth()))return;scrollWidth-=channelCellWidth}if(scrollWidth<=0)return;currentPositionMs=scrollLeft/scrollWidth*(endDate-startDate),currentPositionMs=Math.floor(currentPositionMs),currentPositionMs+=startDate}this.currentPositionMs=currentPositionMs;channelCellWidth=new Date(currentPositionMs),scrollLeft=this.btnDateText||(this.btnDateText=this.options.element.querySelector(".btnDateText")),layoutManager.tv?scrollLeft.classList.remove("btnDateText-autosize"):scrollLeft.classList.add("btnDateText-autosize"),scrollLeft.innerHTML=datetime.toLocaleDateString(channelCellWidth,dateLocalOptions),scrollWidth=this.btnLiveGuide,!layoutManager.tv&&Math.abs(currentPositionMs-Date.now())>cellDurationMs?hideOrShow(scrollWidth,!1):hideOrShow(scrollWidth,!0),userSettings.guideChannelStyle();userSettings.showChannelNumberInGuide(),!1===this.options.dateButton?this.dateButtons[0].classList.add("hide"):this.dateButtons[0].classList.remove("hide")};let minIdleTime=6e4;function onCurrentTimeUpdate(){var dots=this.currentTimeIndicatorDots,startDateMs=this._startDateMs,endDate=this._endDateMs;let pct;var now=Date.now(),showIndicator=0<=(pct=startDateMs&&endDate?(now-startDateMs)/(endDate-startDateMs)*100:-100)&&pct<=100,displayTime=(pct=pct.toFixed(2)+"%",getDisplayTime(new Date(now)));for(let 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")}inputManager.idleTime()<minIdleTime||now-mouseManager.lastMouseInputTime()<minIdleTime||this.updateCurrentPositionIfNeeded()}function scrollToIndex(instance,index,focus,scrollBehavior){focus&&instance.scroller.setFocusScroll("start"),instance.itemsContainer.scrollToIndex(index,{behavior:scrollBehavior},focus),focus&&instance.scroller.setFocusScroll(null)}function scrollToChannel(instance,itemId,focus,scrollBehavior){focus||(instance.scrollToChannelId=itemId);var index=instance.itemsContainer.indexOfItemId(itemId);-1!==index?scrollToIndex(instance,index,focus,scrollBehavior):instance.itemsContainer.fetchData({Limit:0}).then(function(totalResult){totalResult.TotalRecordCount<=1?scrollToIndex(instance,0,focus,scrollBehavior):instance.itemsContainer.fetchData({StartItemId:itemId,Limit:0}).then(function(result){result=result.TotalRecordCount?Math.max(totalResult.TotalRecordCount-result.TotalRecordCount,0):0;scrollToIndex(instance,result,focus,scrollBehavior)})})}function getAfterRefreshFn(instance,options){return function(){options&&(options.autoFocus||options.scrollToChannelId)&&setTimeout(function(){options.scrollToChannelId?scrollToChannel(instance,options.scrollToChannelId,options.focusOnScroll,options.scrollBehavior):focusManager.autoFocus(instance.itemsContainer)},layoutManager.tv?200:100)}}function getProgramMap(epgItem){var programMap={},items=epgItem.Programs;for(let i=0,length=items.length;i<length;i++){var item=items[i];programMap[item.Id]=item}return programMap}function normalizeEpgResult(result){var items=result.Items;for(let i=0,length=items.length;i<length;i++){var item=items[i];item.ChannelId=item.Channel.Id,item.ProgramMap=getProgramMap(item)}return result}Guide.prototype.stopCurrentTimeUpdateInterval=function(){var interval=this.currentTimeUpdateInterval;interval&&(interval.destroy(),this.currentTimeUpdateInterval=null)},Guide.prototype.startCurrentTimeUpdateInterval=function(){var interval=this.currentTimeUpdateInterval,fn=onCurrentTimeUpdate.bind(this);interval||(this.currentTimeUpdateInterval=new MethodTimer({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){let instance=this;return initialRender(instance).then(function(){var itemsContainer;return options?.refresh?instance.refresh().then(getAfterRefreshFn(instance,options)):(itemsContainer=instance.itemsContainer)?itemsContainer.resume(options).then(function(){options&&options.scrollToChannelId&&scrollToChannel(instance,options.scrollToChannelId,options.focusOnScroll,options.scrollBehavior),instance.startCurrentTimeUpdateInterval(),options?.resetScroll&&instance.updateCurrentPositionIfNeeded()}):Promise.resolve()})},Guide.prototype.refresh=function(){this.cancelDataLoadTimer();var apiClient=connectionManager.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.getApiClient(options.serverId),endDate=this._startDateMs+msPerPage,maxEndDate=this._endDateMs-2e3,endDate=Math.min(endDate,maxEndDate),maxEndDate=Object.assign({Fields:"PrimaryImageAspectRatio",Limit:virtualChunkSize,MaxStartDate:new Date(endDate).toISOString(),MinEndDate:new Date(this._startDateMs+1e3).toISOString(),ProgramFields:getProgramFieldsProperty(),TagIds:userSettings.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.addLiveTvChannelSortingToQuery(maxEndDate,globalize),options.getEpg(maxEndDate).then(normalizeEpgResult.bind(this))},Guide.prototype.moveChannelPages=function(offset){var rowsPerPage=layoutManager.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+msPerDay*offset,!1,!0)},Guide.prototype.startDataLoadTimer=function(scrollLeft,scrollWidth,autoFocus,ignoreFocusedProgram){autoFocus={scrollLeft:scrollLeft,autoFocus:autoFocus,ignoreFocusedProgram:ignoreFocusedProgram},this._loadDataInfo=autoFocus,ignoreFocusedProgram=getTimeBlockStart(this,scrollLeft,scrollWidth),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({}),options:{categories:this.categoryOptions.categories,startDateMs:this._startDateMs,endDateMs:this._endDateMs,channelAction:this.options.channelAction||"linkdialog",showEpisodeTitle:this.options.showEpisodeTitle},virtualScrollLayout:"vertical-grid"}},Guide.prototype.destroy=function(){this.cancelDataLoadTimer();var options=this.options;this.stopCurrentTimeUpdateInterval(),options&&((options=this.onTimerCreatedFn)&&(events.off(serverNotifications,"TimerCreated",options),this.onTimerCreatedFn=null),(options=this.onSeriesTimerCreatedFn)&&(events.off(serverNotifications,"SeriesTimerCreated",options),this.onSeriesTimerCreatedFn=null),(options=this.onTimerCancelledFn)&&(events.off(serverNotifications,"TimerCancelled",options),this.onTimerCancelledFn=null),(options=this.onSeriesTimerCancelledFn)&&(events.off(serverNotifications,"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.settingsChannelCell=null,this.options=null,this._endDateMs=null,this._startDateMs=null,this.channelCellWidth=null,this.programCache=null,this.btnDateText=null,this.btnLiveGuide=null,this.programBorderInlineStartWidth=null,this.dateButtons=null,this.settingsButtons=null,this.filterScroller=null)};export default Guide; |