Version 5.0.13

This commit is contained in:
Neo committed 2025-12-19 19:04:57 -08:00
1 parent b89858b2ff
commit 5efe744c5f
1407 files changed
+69690 -30177

No files matched your search

+3 -3
View File
@@ -1,6 +1,6 @@
ips.templates.set("eventLoading",`
<li class='ipsData__item ipsData__item--loading'>
<div class="ipsData__image"></div>
<div class="ipsData__image" aria-hidden="true"></div>
<div class="ipsData__content">
<div class="ipsData__main">
<div class="ipsData__title"></div>
@@ -39,7 +39,7 @@ this.googleMap.panTo(mostMiddleMarker);}}).bind(this);window.setTimeout(cb,0);}}
markersGroup.addTo(this._map);this._map.fitBounds(markersGroup.getBounds(),{maxZoom:5});}},getDistance:function(lat1,lat2,lng1,lng2){lng1=lng1*Math.PI/180;lng2=lng2*Math.PI/180;lat1=lat1*Math.PI/180;lat2=lat2*Math.PI/180;let dlng=lng2-lng1;let dlat=lat2-lat1;let a=Math.pow(Math.sin(dlat/2),2)
+Math.cos(lat1)*Math.cos(lat2)*Math.pow(Math.sin(dlng/2),2);let c=Math.asin(Math.sqrt(a));return c;},_markerMouseOver:function(e){var eventId=e.target.options.eventId;this.scope.find('[data-eventid]').stop(false,true);this.scope.find('[data-eventid]:not([data-eventid="'+eventId+'"])').animate({opacity:0.4},'fast');},_markerMouseOut:function(e){this.scope.find('[data-eventid]').stop(false,true);this.scope.find('[data-eventid]').animate({opacity:1},'fast');},showPlaceholders:function(count){var events=[];for(var i=0;i<6;i++){events.push(ips.templates.render('eventLoading'));}
this.scope.find('[data-role="locationEvents"]').removeClass('ipsJS_hide').html(ips.templates.render('nearMe',{events:events.join('')}));}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('calendar.front.overview.search',{initialize(){this.on('click','[data-action="useMyLocation"]',this.useMyLocation);this.on('click','[data-action="cancelLocation"]',this.cancelLocation);this.on('submit',this.doSearch);this.on(document,'click','[data-action="backToOverview"]',this.backToOverview);this.on(document,'click','[data-action="loadMoreSearch"]',this.loadMore);this.on(document,'menuItemSelected','#elSortMenu',this.changeSort);this.on(document,'click','[data-action="moreNearMe"]',this.moreNearMe);this.on(document,'click','[data-action="moreExhibitions"]',this.moreExhibitions);this.on(window,'historychange:calendarSearch',this.stateChange);this.setup();},setup(){this._gotCoords=false;this._offset=0;this._limit=20;this._currentSort=$('body').find('#elSortMenu_menu .ipsMenu_itemChecked').attr('data-ipsMenuValue');this._baseURL=this.scope.attr('action');this._initialURL=window.location.href;this._cancelledLookup=false;this._searchBox=this.scope.find('input[name="location"]');this._previousValue=this._searchBox.val();this._originalPlaceholder=this.scope.attr('data-placeholder');this._locationLink=this.scope.find('[data-action="useMyLocation"]');this._cancelLocationLink=this.scope.find('[data-action="cancelLocation"]');this._page=this.scope.closest('[data-role="eventsPage"]');this._resultsContainer=$('body').find('[data-role="searchResults"]');this._noResults=$('body').find('[data-role="noSearchResults"]');this._loadMore=$('body').find('[data-action="loadMoreSearch"]');this._noMore=$('body').find('[data-role="noMoreSearchResults"]');this._map=null;this._mapContainer=$('body').find('[data-role="searchResultsMap"]');this._markers={};this.getInitialLocation();if(ips.getSetting('mapProvider')==='google'){this.setupGoogle();}else if(ips.getSetting('mapProvider')==='mapbox'){this.setupMapbox();}else{this._mapContainer.hide();}},setupGoogle(){this._mapReady=true;Debug.log(this._resultsContainer.find('[data-eventid]'));Debug.log(this._mapContainer.attr('data-markers'));if(this._resultsContainer.find('[data-eventid]').length&&this._mapContainer.attr('data-markers')){Debug.log('here');try{var markers=JSON.parse(this._mapContainer.attr('data-markers'));Debug.log(markers);this._updateGoogleMap(markers);}catch(err){Debug.log("Invalid marker JSON");Debug.log(err);}}},setupMapbox(){$('head').append`
;(function($,_,undefined){"use strict";ips.controller.register('calendar.front.overview.search',{initialize(){this.on('click','[data-action="useMyLocation"]',this.useMyLocation);this.on('click','[data-action="cancelLocation"]',this.cancelLocation);this.on('submit',this.doSearch);this.on(document,'click','[data-action="backToOverview"]',this.backToOverview);this.on(document,'click','[data-action="loadMoreSearch"]',this.loadMore);this.on(document,'menuItemSelected','#elSortMenu',this.changeSort);this.on(document,'click','[data-action="moreNearMe"]',this.moreNearMe);this.on(document,'click','[data-action="moreExhibitions"]',this.moreExhibitions);this.on(window,'historychange:calendarSearch',this.stateChange);this.setup();},setup(){this._gotCoords=false;this._offset=0;this._limit=20;this._currentSort=$('body').find('#elSortMenu_menu [aria-selected="true"]').attr('data-ipsMenuValue');this._baseURL=this.scope.attr('action');this._initialURL=window.location.href;this._cancelledLookup=false;this._searchBox=this.scope.find('input[name="location"]');this._previousValue=this._searchBox.val();this._originalPlaceholder=this.scope.attr('data-placeholder');this._locationLink=this.scope.find('[data-action="useMyLocation"]');this._cancelLocationLink=this.scope.find('[data-action="cancelLocation"]');this._page=this.scope.closest('[data-role="eventsPage"]');this._resultsContainer=$('body').find('[data-role="searchResults"]');this._noResults=$('body').find('[data-role="noSearchResults"]');this._loadMore=$('body').find('[data-action="loadMoreSearch"]');this._noMore=$('body').find('[data-role="noMoreSearchResults"]');this._map=null;this._mapContainer=$('body').find('[data-role="searchResultsMap"]');this._markers={};this.getInitialLocation();if(ips.getSetting('mapProvider')==='google'){this.setupGoogle();}else if(ips.getSetting('mapProvider')==='mapbox'){this.setupMapbox();}else{this._mapContainer.hide();}},setupGoogle(){this._mapReady=true;Debug.log(this._resultsContainer.find('[data-eventid]'));Debug.log(this._mapContainer.attr('data-markers'));if(this._resultsContainer.find('[data-eventid]').length&&this._mapContainer.attr('data-markers')){Debug.log('here');try{var markers=JSON.parse(this._mapContainer.attr('data-markers'));Debug.log(markers);this._updateGoogleMap(markers);}catch(err){Debug.log("Invalid marker JSON");Debug.log(err);}}},setupMapbox(){$('head').append`
<link rel='stylesheet' type='text/css' media='all' href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css'>
<link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/MarkerCluster.css' rel='stylesheet' />
<link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/MarkerCluster.Default.css' rel='stylesheet' />
@@ -48,7 +48,7 @@ this.setSearchToLocation();this._locationLink.attr('hidden',true);this._cancelLo
const url=this._getUrlFromData();ips.utils.history.replaceState({controller:'calendar.front.overview.search',url},'calendarSearch',url);},getPlaceholders(count){let events='';count=typeof count==='number'?10:count;for(let i=0;i<count;i++){events+=ips.templates.render('eventLoading');}
return events;},stateChange(){if(!('calendarSearch'in ips.utils.history.getState())&&this._initialURL!==window.location.href){return;}
const state=ips.utils.history.getState('calendarSearch')
if(this._initialURL===state?.url){this.hideResults();}else if(this._initialURL===window.location.href&&state?.url===undefined){this._loadResults(this._getUrlFromData(this._initialData));}else{this._loadResults(state?.url);}},changeSort(e,data){e.preventDefault();this._currentSort=data.selectedItemID;const title=data.menuElem.find('[data-ipsMenuValue="'+this._currentSort+'"]').text();$('body').find('[data-role="searchOrder"]').text(title);this.doSearch();},_getUrlFromData(){const formData=this.scope.serializeArray();const params=[];_.each(formData,function(item){if($.trim(item.value)!==''){params.push(item.name+"="+encodeURIComponent(item.value));}});params.push("sortBy="+this._currentSort);if(this._baseURL.match(/\?/)){if(!this._baseURL.endsWith('?')){this._baseURL+='&';}}else{this._baseURL+='?';}
if(this._initialURL===state?.url){this.hideResults();}else if(this._initialURL===window.location.href&&state?.url===undefined){this._loadResults(this._getUrlFromData(this._initialData));}else{this._loadResults(state?.url);}},changeSort(e,data=e.detail){e.preventDefault();this._currentSort=data.selectedItemID;const title=$(data.menuElem).find('[data-ipsMenuValue="'+this._currentSort+'"]').text();$('body').find('[data-role="searchOrder"]').text(title);this.doSearch();},_getUrlFromData(){const formData=this.scope.serializeArray();const params=[];_.each(formData,function(item){if($.trim(item.value)!==''){params.push(item.name+"="+encodeURIComponent(item.value));}});params.push("sortBy="+this._currentSort);if(this._baseURL.match(/\?/)){if(!this._baseURL.endsWith('?')){this._baseURL+='&';}}else{this._baseURL+='?';}
return this._baseURL+params.join('&');},async _loadResults(url){if(this._page.length){this._page.find('[data-role="eventsOverview"]').hide();this._page.find('[data-role="searchResultsWrapper"]').show();}
this._resultsContainer.removeClass('ipsHide').html(this.getPlaceholders(6));if(ips.getSetting('mapProvider')!=='none'){this._mapContainer.addClass('cEvents__searchMap--loading').show();}
this._currentUrl=url;const response=await ips.fetch(url);if(response.count){this._resultsContainer.html(response.content);this._noResults.addClass('ipsHide');this._updateMap(_.extend({},this._markers,response.markers));if(response.totalCount>(response.count+this._offset)){this._loadMore.show();this._noMore.hide();}else{this._loadMore.hide();this._noMore.hide();}}else{this._resultsContainer.html('').addClass('ipsHide');this._noResults.removeClass('ipsHide');this._loadMore.hide();this._noMore.hide();this._mapContainer.hide();}
+2 -4
View File
@@ -10,14 +10,12 @@ if((endDate.getMonth()-startDate.getMonth()+(12*(endDate.getFullYear()-startDate
if(dayDifference>365){$('#elSelect_event_repeats').find('option[value="yearly"]').prop('selected',false);this.disableRecurring();$('#elRepeatRow_hidden').hide();}
else
{$('#elRepeatRow_hidden').show();}
this._updateSummary();},finishRepeat:function(){this._updateSummary();$('#elRecurEdit_menu').trigger('closeMenu');},setup:function(){this._updateSummary();this.toggleFields();this.updateTimezone();},toggleEndtimeFields:function(e){if(this.scope.find('#check_no_end_time').is(':checked')){this.scope.find('#end_time').prop('disabled',true);}
this._updateSummary();},finishRepeat:function(){this._updateSummary();},setup:function(){this._updateSummary();this.toggleFields();this.updateTimezone();},toggleEndtimeFields:function(e){if(this.scope.find('#check_no_end_time').is(':checked')){this.scope.find('#end_time').prop('disabled',true);}
else
{this.scope.find('#end_time').prop('disabled',false);}},toggleFields:function(e){this.toggleEndtimeFields();var singleDay=this.scope.find('#check_single_day');var allDay=this.scope.find('#check_all_day');var self=this;var toggles={start_time_wrap:true,end_time_wrap:true,event_end_date_wrap:true,elDateGrid_arrow:true,elDateGrid_end:true,end_date_controls:true};if(singleDay.is(':checked')&&!allDay.is(':checked')){toggles.event_end_date_wrap=false;}else if(singleDay.is(':checked')&&allDay.is(':checked')){toggles.elDateGrid_arrow=false;toggles.elDateGrid_end=false;toggles.start_time_wrap=false;}else if(!singleDay.is(':checked')&&allDay.is(':checked')){toggles.start_time_wrap=false;toggles.end_time_wrap=false;toggles.end_date_controls=false;}
else
{toggles.end_date_controls=false;this.scope.find('#end_time').prop('disabled',false);}
_.each(toggles,function(val,key){self.scope.find('#'+key).toggle(val);});},checkForSummaryChange:function(e){if($(e.currentTarget).attr('name').startsWith('event_dates[')){this._updateSummary();}},updateTimezone:function(e){if(e){e.preventDefault();}
this.scope.find('[data-role="timezone_display"]').text($('#event_timezone option:selected').data('abbreviated')).trigger('closeMenu');},disableRecurring:function(e){if(e){e.preventDefault();}
this.scope.find('#elRepeatCb').prop('checked',false);this._updateSummary();},finishRepeatConfiguration:function(e,data){e.preventDefault();this.scope.find('[data-role="recur_summary_final"]').text(this.scope.find('[data-role="recur_summary"]').text());this.scope.find('#elRecurEdit').trigger('closeMenu');},_updateSummary:function(){var summary=this.scope.find('[data-role="recurringSummary"]');if(this.scope.find('#elRepeatCb').is(':checked')){summary.text(this._getSummary());this.scope.find('#elRepeatRow_hidden').hide();this.scope.find('#elRepeatRow_shown').show();}else{summary.html("<em class='i-color_soft'>"+ips.getString('doesnt_repeat')+"</em>");this.scope.find('#elRepeatRow_hidden').show();this.scope.find('#elRepeatRow_shown').hide();}
_.each(toggles,function(val,key){self.scope.find('#'+key).toggle(val);});},checkForSummaryChange:function(e){if($(e.currentTarget).attr('name').startsWith('event_dates[')){this._updateSummary();}},updateTimezone:function(e){this.scope.find('[data-role="timezone_display"]').text($('#event_timezone option:selected').data('abbreviated'));},disableRecurring:function(e){this._updateSummary();},_updateSummary:function(){var summary=this.scope.find('[data-role="recurringSummary"]');if(this.scope.find('#elRepeatCb').is(':checked')){summary.text(this._getSummary());this.scope.find('#elRepeatRow_hidden').hide();this.scope.find('#elRepeatRow_shown').show();}else{summary.html("<em class='i-color_soft'>"+ips.getString('doesnt_repeat')+"</em>");this.scope.find('#elRepeatRow_hidden').show();this.scope.find('#elRepeatRow_shown').hide();}
this.scope.find('[data-role="dateSummary"]').html(this._dateSummary());},_dateSummary:function(){var startDate=ips.utils.time.getDateFromInput(this.scope.find('input[name="event_dates[start_date]"]'));var singleDay=this.scope.find('#check_single_day');var allDay=this.scope.find('#check_all_day');if(!ips.utils.time.isValidDateObj(startDate)||startDate.getFullYear()<1900){return'';}
ips.utils.time.removeTimezone(startDate);var startDateString=ips.utils.time.localeDateString(startDate,{weekday:'short',month:'short',day:'numeric',year:'numeric',timeZone:'UTC'});var startTime=this._getTime(this.scope.find('input[name="event_dates[start_time]"]').val());var endTime=this._getTime(this.scope.find('input[name="event_dates[end_time]"]').val());var endDate=ips.utils.time.getDateFromInput(this.scope.find('input[name="event_dates[end_date]"]'));var endDateString='';if(!singleDay.is(':checked')&&ips.utils.time.isValidDateObj(endDate)){ips.utils.time.removeTimezone(endDate);endDateString=ips.utils.time.localeDateString(endDate,{weekday:'short',month:'short',day:'numeric',year:'numeric',timeZone:'UTC'});}
var finalString='';if(singleDay.is(':checked')&&!allDay.is(':checked')){if(this.scope.find('#check_no_end_time').is(':checked')){finalString=ips.getString('single_not_allday_noendtime',{startDate:startDateString,startTime:startTime});}
+7 -7
View File
@@ -5,14 +5,14 @@ ips.getAjax()($(e.currentTarget).attr('action'),{dataType:'json',data:$(e.curren
else if(span.hasClass('ipsButton--secondary')){radio.removeAttr('checked');span.removeClass('ipsButton--secondary').addClass('ipsButton--primary').find('strong').html(ips.getString('sc_use_this_version'));$('input[type=radio][name=conflict_'+id+']').closest('span.ipsButton[data-conflict-name='+(name=='new'?'old':'new')+']').removeClass('ipsButton--disabled');$('th span[data-conflict-id='+id+'][data-conflict-name='+name+']').removeClass('ipsBadge ipsBadge--positive');ips.utils.anim.go('blindDown',this.scope.find('div[data-conflict-id='+id+']'));}
else
{radio.attr('checked','checked');span.removeClass('ipsButton--primary').addClass('ipsButton--secondary').find('strong').html(ips.getString('sc_remove_selection'));$('input[type=radio][name=conflict_'+id+']').closest('span.ipsButton[data-conflict-name='+(name=='new'?'old':'new')+']').addClass('ipsButton--disabled');$('th span[data-conflict-id='+id+'][data-conflict-name='+name+']').addClass('ipsBadge ipsBadge--positive');ips.utils.anim.go('fadeOut',this.scope.find('div[data-conflict-id='+id+']'));}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('cms.admin.templates.fileEditor',{_tabBar:null,_tabContent:null,_fileStore:{},_ajaxURL:'',_cmInstances:{},_currentHeight:0,_editorPreferences:{wrap:true,lines:false},initialize:function(){this.on(document,'openFile.templates',this.openFile);this.on(document,'variablesUpdated.templates',this.updateVariables);this.on('tabChanged',this.changedTab);this.on('click','[data-action="closeTab"]',this.closeTab);this.on('click','[data-action="save"]',this.save);this.on('click','[data-action="revert"]:not( .ipsButton--disabled )',this.revert);this.on('savedFile.templates',this.updateFile);this.on('revertedFile.templates',this.updateFile);this.on('openDialog',this.openedDialog);this.on('menuItemSelected',this.menuSelected);var debounce=_.debounce(_.bind(this._recalculatePanelWrapper,this),100);this.on(window,'resize',debounce);this.setup();},setup:function(){var self=this;this._tabBar=this.scope.find('#elTemplateEditor_tabbar [role="tablist"]');this._tabContent=this.scope.find('#elTemplateEditor_panels');this._currentHeight=this._tabBar.outerHeight();this._ajaxURL=this.scope.closest('[data-ajaxURL]').attr('data-ajaxURL');this._normalURL=this.scope.closest('[data-normalURL]').attr('data-normalURL');this._editorPreferences['wrap']=ips.utils.db.get('templateEditor','wrap');this._editorPreferences['lines']=ips.utils.db.get('templateEditor','lines');if(this._editorPreferences['wrap']){$('#elTemplateEditor_preferences_menu').find('[data-ipsMenuValue="wrap"]').addClass('ipsMenu_itemChecked');}
if(this._editorPreferences['lines']){$('#elTemplateEditor_preferences_menu').find('[data-ipsMenuValue="lines"]').addClass('ipsMenu_itemChecked');}
;(function($,_,undefined){"use strict";ips.controller.register('cms.admin.templates.fileEditor',{_tabBar:null,_tabContent:null,_fileStore:{},_ajaxURL:'',_cmInstances:{},_currentHeight:0,_editorPreferences:{wrap:true,lines:false},initialize:function(){this.on(document,'openFile.templates',this.openFile);this.on(document,'variablesUpdated.templates',this.updateVariables);this.on('tabChanged',this.changedTab);this.on('click','[data-action="closeTab"]',this.closeTab);this.on('click','[data-action="save"]',this.save);this.on('click','[data-action="revert"]:not( .ipsButton--disabled )',this.revert);this.on('savedFile.templates',this.updateFile);this.on('revertedFile.templates',this.updateFile);this.on('openDialog',this.openedDialog);this.on('menuItemSelected',this.menuSelected);var debounce=_.debounce(_.bind(this._recalculatePanelWrapper,this),100);this.on(window,'resize',debounce);this.setup();},setup:function(){var self=this;this._tabBar=this.scope.find('#elTemplateEditor_tabbar [role="tablist"]');this._tabContent=this.scope.find('#elTemplateEditor_panels');this._currentHeight=this._tabBar.outerHeight();this._ajaxURL=this.scope.closest('[data-ajaxURL]').attr('data-ajaxURL');this._normalURL=this.scope.closest('[data-normalURL]').attr('data-normalURL');this._editorPreferences['wrap']=ips.utils.db.get('templateEditor','wrap');this._editorPreferences['lines']=ips.utils.db.get('templateEditor','lines');if(this._editorPreferences['wrap']){$('#elTemplateEditor_preferences_menu').find('[data-ipsMenuValue="wrap"]').attr("aria-selected","true");}
if(this._editorPreferences['lines']){$('#elTemplateEditor_preferences_menu').find('[data-ipsMenuValue="lines"]').attr("aria-selected","true");}
this._tabContent.find('[data-group]').each(function(i,item){var original=self._tabContent.find('[data-fileid="'+$(item).attr('data-fileid')+
'"] input[data-role="variables"]');if(original.length){original.after($('<input/>').attr('type','hidden').attr('name',original.attr('name')).attr('value',original.attr('value')).attr('data-role','variables'))
original.remove();}
ips.loader.getStatic(['applications/core/interface/static/codemirror/diff_match_patch.js','applications/core/interface/static/codemirror/codemirror.js']).then(function(){self._initCodeMirror($(item).attr('data-fileid'),$(item).attr('data-type'));});});},menuSelected:function(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
ips.loader.getStatic(['applications/core/interface/static/codemirror/diff_match_patch.js','applications/core/interface/static/codemirror/codemirror.js']).then(function(){self._initCodeMirror($(item).attr('data-fileid'),$(item).attr('data-type'));});});},menuSelected:function(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
if(data.triggerID=='elTemplateEditor_preferences'){if(data.selectedItemID=='diff'){this.toggleDiff();}
else if(data.selectedItemID=='wrap'){this._changeEditorPreference(!ips.utils.db.get('templateEditor','wrap'),'wrap','lineWrapping');}else{this._changeEditorPreference(!ips.utils.db.get('templateEditor','lines'),'lines','lineNumbers');}}},_changeEditorPreference:function(toValue,type,cmName){if(toValue){$('#elTemplateEditor_preferences_menu').find('[data-ipsMenuValue="'+type+'"]').addClass('ipsMenu_itemChecked');}else{$('#elTemplateEditor_preferences_menu').find('[data-ipsMenuValue="'+type+'"]').removeClass('ipsMenu_itemChecked');}
else if(data.selectedItemID=='wrap'){this._changeEditorPreference(!ips.utils.db.get('templateEditor','wrap'),'wrap','lineWrapping');}else{this._changeEditorPreference(!ips.utils.db.get('templateEditor','lines'),'lines','lineNumbers');}}},_changeEditorPreference:function(toValue,type,cmName){if(toValue){$('#elTemplateEditor_preferences_menu').find('[data-ipsMenuValue="'+type+'"]').attr("aria-selected","true");}else{$('#elTemplateEditor_preferences_menu').find('[data-ipsMenuValue="'+type+'"]').removeAttr("aria-selected");}
this._editorPreferences[type]=toValue;ips.utils.db.set('templateEditor',type,toValue);for(var i in this._cmInstances){if(this._cmInstances[i]instanceof CodeMirror.MergeView){this._cmInstances[i].edit.setOption(cmName,toValue);this._cmInstances[i].left.orig.setOption(cmName,toValue);}else{this._cmInstances[i].setOption(cmName,toValue);}}},openedDialog:function(e,data){if(data.elemID=='elTemplateEditor_variables'||data.elemID=='elTemplateEditor_attributes'){this._insertVariablesIntoDialog(data);}},_insertVariablesIntoDialog:function(data){var active=this._getActiveTab();if(!active.tabPanel){return;}
var variablesValue=active.tabPanel.find('[data-role="variables"]').val().trim();var descriptionValue=active.tabPanel.find('[data-role="description"]').val().trim();var titleValue=active.tabPanel.find('[data-role="title"]').val().trim();var groupValue=active.tabPanel.find('[data-role="group"]').val().trim();data.dialog.find('[data-role="variables"]').val(variablesValue).end().find('[data-role="description"]').val(descriptionValue).end().find('[name="_variables_fileid"]').val(active.tabPanel.attr('data-fileid')).end().find('[name="_variables_location"]').val(active.tabPanel.attr('data-location')).end().find('[data-role="title"]').val(titleValue);data.dialog.find('select[data-container-type]').addClass('ipsHide');data.dialog.find('select[data-container-type='+active.tabPanel.attr('data-location')+']').removeClass('ipsHide');data.dialog.find('select[data-container-type='+active.tabPanel.attr('data-location')+']').val(groupValue);data.dialog.find('#elTemplateEditor_container_title').show();data.dialog.find('[data-role="container"]').show();data.dialog.find('[data-role="variables"]').show();data.dialog.find('#elTemplateEditor_attributes_title').show();if(active.tabPanel.attr('data-type')!='template'){data.dialog.find('#elTemplateEditor_group_title').hide();data.dialog.find('[data-role="variables"]').hide();data.dialog.find('#elTemplateEditor_attributes_title').hide();}
else if(active.tabPanel.attr('data-location')=='block'){data.dialog.find('#elTemplateEditor_group_title').hide();data.dialog.find('[data-role="group"]').hide();}
@@ -30,7 +30,7 @@ if(newTab){newTab.click();}
ips.utils.anim.go('fadeOutDown fast',tabParent).done(function(){tabParent.remove();self._recalculatePanelWrapper();});this._tabContent.find('[data-fileid="'+key+'"]').remove();},changedTab:function(e,data){var tab=data.tab;if(!_.isUndefined(tab.closest('[data-fileid]').attr('data-fileid'))){this.trigger('fileSelected.templates',{fileID:tab.closest('[data-fileid]').attr('data-fileid')});}
this._updateToolbar(tab);},_updateToolbar:function(tab){var tabParent=tab.closest('[data-fileid]').attr('data-fileid');var tabPanel=this._tabContent.find('[data-fileid="'+tabParent+'"]');var status=tabPanel.attr('data-inherited-value');var type=tabPanel.attr('data-type');var revert=this.scope.find('[data-action="revert"]');var key=tabPanel.attr('data-fileid');switch(status){case'original':case'inherit':revert.addClass('ipsButton--disabled')
break;case'custom':revert.html(ips.getString('skin_delete')).removeClass('ipsButton--disabled').attr('data-actionType','delete').show();break;case'changed':revert.html(ips.getString('skin_delete')).removeClass('ipsButton--disabled').attr('data-actionType','delete').show();break;}
$('#elTemplateEditor_variables').show();$('#elTemplateEditor_attributes').hide();if(this._cmInstances[key]instanceof CodeMirror.MergeView){$('[data-ipsmenuvalue="diff"]').addClass('ipsMenu_itemChecked');}else{$('[data-ipsmenuvalue="diff"]').removeClass('ipsMenu_itemChecked');}},openFile:function(e,data){if(!this._tabBar.find('[data-fileid="'+data.meta.key+'"]').length){this._buildTab(data.meta);}else{this._tabBar.find('[data-fileid="'+data.meta.key+'"]').click();}},_buildTab:function(meta){var self=this;this._tabContent.attr('data-haseditor','true');this.scope.find('#elTemplateEditor_panels_empty').hide();this._tabBar.append(ips.templates.render('templates.editor.newTab',{title:meta.title,fileid:meta.key,location:meta.location,group:meta.group,container:meta.container,id:'tab_'+meta.key}));this._tabContent.append(ips.templates.render('templates.editor.tabPanel',{fileid:meta.key,name:meta.name,type:meta.type,location:meta.location,container:meta.container,group:meta.group,id:meta.id,inherited:meta.inherited}));this._recalculatePanelWrapper();this._tabBar.find('[data-fileid="'+meta.key+'"]').click();this._tabContent.addClass('ipsLoading ipsTabs_loadingContent');ips.getAjax()(this._ajaxURL+'&do=loadTemplate&show=json',{dataType:'json',data:{'t_container':meta.container,'t_group':meta.group,'t_name':meta.name,'t_key':meta.key,'t_location':meta.location,'t_type':meta.type}}).done(function(response){self._postProcessNewTab(response,meta);}).always(function(){self._tabContent.removeClass('ipsLoading ipsTabs_loadingContent');});},_updateTabLabel:function(key,title){var span=this._tabBar.find('[data-fileid="'+key+'"] span').clone();this._tabBar.find('[data-fileid="'+key+'"]').html(title).append(span);},_postProcessNewTab:function(response,meta){var content=ips.templates.render('templates.editor.tabContent',{fileid:meta.key,content:response.template_content,variables:response.template_params,description:response.template_desc,title:response.template_title,container:response.template_container,group:response.template_group});this._tabContent.find('[data-fileid="'+meta.key+'"]').html(content);this._initCodeMirror(meta.key,meta.type);},_initCodeMirror:function(key,type){var self=this;this._cmInstances[key]=CodeMirror.fromTextArea(document.getElementById('editor_'+key),{mode:(type=='template'?'htmlmixed':'css'),lineWrapping:this._editorPreferences['wrap'],lineNumbers:this._editorPreferences['lines']});this._cmInstances[key].on('change',function(doc,cm){self._setChanged(true,key);});},_setChanged:function(state,key){if(state==true){this._tabBar.find('[data-fileid="'+key+'"]').attr('data-state','unsaved').find('[data-action="closeTab"]').html(ips.templates.render('templates.editor.unsaved'));}else{this._tabBar.find('[data-fileid="'+key+'"]').attr('data-state','saved').find('[data-action="closeTab"]').html(ips.templates.render('templates.editor.saved'));}},_recalculatePanelWrapper:function(){},_getActiveTab:function(){var toReturn={tab:null,tabPanel:null};var tab=this._tabBar.find('[aria-selected="true"]').first();if(!tab.length){return toReturn;}
$('#elTemplateEditor_variables').show();$('#elTemplateEditor_attributes').hide();if(this._cmInstances[key]instanceof CodeMirror.MergeView){$('[data-ipsmenuvalue="diff"]').attr("aria-selected","true");}else{$('[data-ipsmenuvalue="diff"]').removeAttr("aria-selected");}},openFile:function(e,data){if(!this._tabBar.find('[data-fileid="'+data.meta.key+'"]').length){this._buildTab(data.meta);}else{this._tabBar.find('[data-fileid="'+data.meta.key+'"]').click();}},_buildTab:function(meta){var self=this;this._tabContent.attr('data-haseditor','true');this.scope.find('#elTemplateEditor_panels_empty').hide();this._tabBar.append(ips.templates.render('templates.editor.newTab',{title:meta.title,fileid:meta.key,location:meta.location,group:meta.group,container:meta.container,id:'tab_'+meta.key}));this._tabContent.append(ips.templates.render('templates.editor.tabPanel',{fileid:meta.key,name:meta.name,type:meta.type,location:meta.location,container:meta.container,group:meta.group,id:meta.id,inherited:meta.inherited}));this._recalculatePanelWrapper();this._tabBar.find('[data-fileid="'+meta.key+'"]').click();this._tabContent.addClass('ipsLoading ipsTabs_loadingContent');ips.getAjax()(this._ajaxURL+'&do=loadTemplate&show=json',{dataType:'json',data:{'t_container':meta.container,'t_group':meta.group,'t_name':meta.name,'t_key':meta.key,'t_location':meta.location,'t_type':meta.type}}).done(function(response){self._postProcessNewTab(response,meta);}).always(function(){self._tabContent.removeClass('ipsLoading ipsTabs_loadingContent');});},_updateTabLabel:function(key,title){var span=this._tabBar.find('[data-fileid="'+key+'"] span').clone();this._tabBar.find('[data-fileid="'+key+'"]').html(title).append(span);},_postProcessNewTab:function(response,meta){var content=ips.templates.render('templates.editor.tabContent',{fileid:meta.key,content:response.template_content,variables:response.template_params,description:response.template_desc,title:response.template_title,container:response.template_container,group:response.template_group});this._tabContent.find('[data-fileid="'+meta.key+'"]').html(content);this._initCodeMirror(meta.key,meta.type);},_initCodeMirror:function(key,type){var self=this;this._cmInstances[key]=CodeMirror.fromTextArea(document.getElementById('editor_'+key),{mode:(type=='template'?'htmlmixed':'css'),lineWrapping:this._editorPreferences['wrap'],lineNumbers:this._editorPreferences['lines']});this._cmInstances[key].on('change',function(doc,cm){self._setChanged(true,key);});},_setChanged:function(state,key){if(state==true){this._tabBar.find('[data-fileid="'+key+'"]').attr('data-state','unsaved').find('[data-action="closeTab"]').html(ips.templates.render('templates.editor.unsaved'));}else{this._tabBar.find('[data-fileid="'+key+'"]').attr('data-state','saved').find('[data-action="closeTab"]').html(ips.templates.render('templates.editor.saved'));}},_recalculatePanelWrapper:function(){},_getActiveTab:function(){var toReturn={tab:null,tabPanel:null};var tab=this._tabBar.find('[aria-selected="true"]').first();if(!tab.length){return toReturn;}
toReturn={tab:tab,tabPanel:this._tabContent.find('[data-fileid="'+tab.attr('data-fileid')+'"]')};return toReturn;},_getTabContentHeight:function(){var tabContentTop=this._tabContent.offset().top;var windowHeight=$(window).height();var infoHeight=$('#elTemplateEditor_info').outerHeight();this._panelHeight=windowHeight-tabContentTop-infoHeight;return this._panelHeight;}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('cms.admin.templates.fileList',{_tabBar:null,_tabContent:null,initialize:function(){this.on('click','[data-action="openFile"]',this.openFile);this.on('modifiedFile.templates',this.refreshFileList);this.on(document,'fileSelected.templates',this.selectFile);this.on(document,'savedFile.templates revertedFile.templates',this.updateItemMeta);this.on(document,'savedFile.templates revertedFile.templates',this.fileChangedStatus);this.on(document,'addedFile.templates',this.refreshFileList);this.on(document,'deletedFile.templates',this.refreshFileList);this.setup();},setup:function(){this._tabBar=this.scope.find('#elTemplateEditor_typeTabs');this._tabContent=this.scope.find('#elTemplateEditor_fileList');},refreshFileList:function(e,data){var self=this;var type=data.type;var panel=this._tabContent.find('.cTemplateList[data-type="'+type+'"]');var activeItem=panel.find('.cTemplateList_activeNode > a').attr('data-key');if(!panel.length){this._tabBar.find('[data-type="'+type+'"]').click();}else{var open=this._getOpenNodes(panel);var url=this._tabBar.find('[data-type]').attr('data-tabURL');ips.getAjax()(url).done(function(response){panel.html(response);self._openNodes(open,panel,activeItem);if(data.fileID){panel.find('[data-itemid="'+data.fileID+'"]').click();}
self.trigger('fileListRefreshed.templates');});}},_openNodes:function(toOpen,panel,activeItem){var selector=[];if(toOpen.locations.length){for(var i=0;i<toOpen.locations.length;i++){selector.push('[data-location="'+toOpen.locations[i]+'"]');}}
@@ -41,9 +41,9 @@ this.scope.find('[data-itemID="'+data.newID+'"]').attr('data-name',data.newTitle
if(this._tabBar.find('[data-type="js"]').attr('aria-selected')==="true"){return'js';}
return'css';}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('cms.admin.templates.main',{_timer:null,_textField:null,_lastValue:'',_ajax:null,initialize:function(){this._textField=$(this.scope).find('[data-role="templateSearch"]');this.on(document,'focus','[data-role="templateSearch"]',this.fieldFocus);this.on(document,'blur','[data-role="templateSearch"]',this.fieldBlur);this.on('menuItemSelected',this.menuSelected);this.on('savingFile.templates',this.showLoading);this.on('saveFileFinished.templates',this.hideLoading);},showLoading:function(e){ips.utils.anim.go('fadeIn',this.scope.find('[data-role="loading"]'));},hideLoading:function(e){ips.utils.anim.go('fadeOut',this.scope.find('[data-role="loading"]'));},fieldFocus:function(e){this._timer=setInterval(_.bind(this._timerFocus,this),700);},fieldBlur:function(e){clearInterval(this._timer);},_timerFocus:function(){var currentValue=this._textField.val();if(currentValue==this._lastValue){return;}
this._lastValue=currentValue;this._loadResults();},_swapTab:function(e,data){if(data.barID=='elTemplateEditor_typeTabs'){this._loadResults();}},menuSelected:function(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
this._lastValue=currentValue;this._loadResults();},_swapTab:function(e,data){if(data.barID=='elTemplateEditor_typeTabs'){this._loadResults();}},menuSelected:function(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
this._loadResults();},_loadResults:function(){if(this._ajax){this._ajax.abort();}
if(this._lastValue){this._textField.addClass('ipsField_loading');}
var type=$('#elTemplateEditor_typeTabs').find('[aria-selected="true"]').attr('data-type');var type=(type=='templates')?'template':type;$('#elTemplateEditor_fileList').find('li[data-type='+type+']').addClass('ipsHide');var filters=[];$('#elTemplateFilterMenu_menu .ipsMenu_itemChecked').each(function(){filters.push($(this).attr('data-ipsMenuValue'));});var self=this;this._ajax=ips.getAjax()($(this.scope).attr('data-ajaxURL')+'&do=searchtemplates&type='+type+'&term='+encodeURIComponent(this._lastValue)+'&filters='+filters.join(',')).done(function(response){var i;var j;for(j in response){$('#elTemplateEditor_fileList').find('[data-location="'+j+'"]').removeClass('ipsHide');var k;for(k in response[j]){$('#elTemplateEditor_fileList').find('[data-location="'+j+'"] [data-group="'+k+'"]').removeClass('ipsHide');var l;for(l in response[j][k]){if(k=='.'){$('#elTemplateEditor_fileList').find('[data-location="'+j+'"] [data-name="'+response[j][k][l]+'"]').parent().removeClass('ipsHide');}else{$('#elTemplateEditor_fileList').find('[data-location="'+j+'"] [data-group="'+k+'"] [data-name="'+response[j][k][l]+'"]').parent().removeClass('ipsHide');}}}}
var type=$('#elTemplateEditor_typeTabs').find('[aria-selected="true"]').attr('data-type');var type=(type=='templates')?'template':type;$('#elTemplateEditor_fileList').find('li[data-type='+type+']').addClass('ipsHide');var filters=[];$('#elTemplateFilterMenu_menu [aria-selected="true"]').each(function(){filters.push($(this).attr('data-ipsMenuValue'));});var self=this;this._ajax=ips.getAjax()($(this.scope).attr('data-ajaxURL')+'&do=searchtemplates&type='+type+'&term='+encodeURIComponent(this._lastValue)+'&filters='+filters.join(',')).done(function(response){var i;var j;for(j in response){$('#elTemplateEditor_fileList').find('[data-location="'+j+'"]').removeClass('ipsHide');var k;for(k in response[j]){$('#elTemplateEditor_fileList').find('[data-location="'+j+'"] [data-group="'+k+'"]').removeClass('ipsHide');var l;for(l in response[j][k]){if(k=='.'){$('#elTemplateEditor_fileList').find('[data-location="'+j+'"] [data-name="'+response[j][k][l]+'"]').parent().removeClass('ipsHide');}else{$('#elTemplateEditor_fileList').find('[data-location="'+j+'"] [data-group="'+k+'"] [data-name="'+response[j][k][l]+'"]').parent().removeClass('ipsHide');}}}}
self._textField.removeClass('ipsField_loading');});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('cms.admin.templates.variablesDialog',{initialize:function(){this.on('click','input[type="submit"]',this.submitChange);},submitChange:function(e){var key=this.scope.find('[name="_variables_fileid"]').val();$('[data-fileid="'+key+'"]').attr('data-state','unsaved').find('[data-action="closeTab"]').html(ips.templates.render('templates.editor.unsaved'));this.trigger('variablesUpdated.templates',{fileID:this.scope.find('[name="_variables_fileid"]').val(),value:this.scope.find('[data-role="variables"]').val(),title:this.scope.find('[data-role="title"]').val(),description:this.scope.find('[data-role="description"]').val(),container:this.scope.find('[data-role="container"]').val(),group:this.scope.find('[data-role="group"]:not(.ipsHide)').val()});this.trigger('closeDialog');}});}(jQuery,_));;
+1 -1
View File
@@ -1 +1 @@
;(function($,_,undefined){"use strict";ips.controller.register('convert.admin.forms.reactionmapper',{initialize:function(){var id=$(this.scope).data('reactionid');this.on(document,'click',"#elReactionMapper"+id+"_menu .ipsMenu_item",this.selectReaction);this.setup();},setup:function(){this.scope.find('a[data-default="true"]').click();},selectReaction:function(e){e.preventDefault();var menuItem=$(e.target);this.scope.find('.elMenuSelect_replace').html(menuItem.html());this.scope.find('input[type=hidden]').val(menuItem.data('id'));}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('convert.admin.forms.reactionmapper',{initialize:function(){var id=$(this.scope).data('reactionid');this.on(document,'click',"#elReactionMapper"+id+"_menu [data-action='selectReaction']",this.selectReaction);this.setup();},setup:function(){this.scope.find('[data-default="true"]').click();},selectReaction:function(e){e.preventDefault();var menuItem=$(e.target);this.scope.find('.elMenuSelect_replace').html(menuItem.html());this.scope.find('input[type=hidden]').val(menuItem.data('id'));}});}(jQuery,_));;
+8 -9
View File
@@ -1,19 +1,18 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.tags',{initialize:function(){this.on('submit',this.submitForm);},submitForm:function(e){if($(e.currentTarget).attr('data-bypassValidation')){return true;}
e.preventDefault();e.stopPropagation();ips.ui.alert.show({type:'confirm',subText:ips.getString('tag_delete_confirm_detail'),icon:'fa-solid fa-triangle-exclamation',callbacks:{ok:function(){$(e.currentTarget).attr('data-bypassValidation',true);$(e.currentTarget).submit();},cancel:function(){return false;}}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.notificationMenu',{initialize:function(){this.on(document,'menuOpened',this.menuOpened);$('body').on('updateNotificationCount',this.updateNotificationCount);this.setup();},setup:function(){var notificationCount=parseInt(this.scope.find('[data-role="notificationCount"]').text());if(isNaN(notificationCount)){notificationCount=0;}
var storedNotificationCount=parseInt(ips.utils.cookie.get('acpNotificationCount'));if(isNaN(storedNotificationCount)){storedNotificationCount=0;}
if(notificationCount>storedNotificationCount){setTimeout(function(){$(this.scope).find('[data-role="notificationIcon"]').addClass('cAcpNotifications_animate');}.bind(this),800);}
ips.utils.cookie.set('acpNotificationCount',notificationCount);},loaded:false,menuOpened:function(e,data){if(!this.loaded){var self=this;var ajaxObj=ips.getAjax();$('[data-role="notificationList"]').html('').css({height:'100px'}).addClass('ipsLoading');ajaxObj('?app=core&module=overview&controller=notifications',{dataType:'json'}).done(function(returnedData){$('[data-role="notificationList"]').css({height:'auto'}).removeClass('ipsLoading').html(returnedData.data);self.loaded=true;$(document).trigger('contentChange',[$('[data-role="notificationList"]')]);});}},updateNotificationCount:function(){ips.getAjax()('?app=core&module=overview&controller=notifications').done(function(response){var count=parseInt(response.count);if(count){$(this).find('[data-role="notificationCount"]').removeClass('ipsHide').text(count).closest('.cAcpNotifications').addClass('cAcpNotifications_active');}else{$(this).find('[data-role="notificationCount"]').addClass('ipsHide').closest('.cAcpNotifications').removeClass('cAcpNotifications_active');}}.bind(this));}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.acpSearchKeywords',{initialize:function(){this.on('click','[data-action="save"]',this.saveKeywords);},saveKeywords:function(e){e.preventDefault();var scope=this.scope;var data={url:scope.attr('data-url'),lang_key:scope.find("[data-role='lang_key']").val(),restriction:scope.find("[data-role='restriction']").val(),keywords:[]};scope.find("[data-role='keywords']").each(function(){if($(this).val()){data.keywords.push($(this).val());}});ips.getAjax()(scope.attr('data-action'),{data:data,type:'post',showLoading:true}).done(function(response){scope.trigger('closeMenu');ips.ui.flashMsg.show('Keywords saved');});},});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.changeTheme',{initialize:function(){$('#elAdminUser,#elThemeLangMenuMob').on('menuItemSelected',_.bind(this.themePreferenceSelected,this));this.setTheme();},setTheme:function(){if(_.isUndefined(ips.utils.cookie.get('acptheme'))||ips.utils.cookie.get('acptheme')=='undefined'){if(window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches){$('html').attr('data-ips-scheme','dark');ips.utils.cookie.set('acpthemedefault','dark');}
ips.utils.cookie.set('acpNotificationCount',notificationCount);},loaded:false,menuOpened:function(e,data=e.detail){if(!this.loaded){var self=this;var ajaxObj=ips.getAjax();$('[data-role="notificationList"]').html('').css({height:'100px'}).addClass('ipsLoading');ajaxObj('?app=core&module=overview&controller=notifications',{dataType:'json'}).done(function(returnedData){$('[data-role="notificationList"]').css({height:'auto'}).removeClass('ipsLoading').html(returnedData.data);self.loaded=true;$(document).trigger('contentChange',[$('[data-role="notificationList"]')]);});}},updateNotificationCount:function(){ips.getAjax()('?app=core&module=overview&controller=notifications').done(function(response){var count=parseInt(response.count);if(count){$(this).find('[data-role="notificationCount"]').removeClass('ipsHide').text(count).closest('.cAcpNotifications').addClass('cAcpNotifications_active');}else{$(this).find('[data-role="notificationCount"]').addClass('ipsHide').closest('.cAcpNotifications').removeClass('cAcpNotifications_active');}}.bind(this));}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.tags',{initialize:function(){this.on('submit',this.submitForm);},submitForm:function(e){if($(e.currentTarget).attr('data-bypassValidation')){return true;}
e.preventDefault();e.stopPropagation();ips.ui.alert.show({type:'confirm',subText:ips.getString('tag_delete_confirm_detail'),icon:'fa-solid fa-triangle-exclamation',callbacks:{ok:function(){$(e.currentTarget).attr('data-bypassValidation',true);$(e.currentTarget).submit();},cancel:function(){return false;}}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.acpSearchKeywords',{initialize:function(){this.on('click','[data-action="save"]',this.saveKeywords);},saveKeywords:function(e){e.preventDefault();var scope=this.scope;var data={url:scope.attr('data-url'),lang_key:scope.find("[data-role='lang_key']").val(),restriction:scope.find("[data-role='restriction']").val(),keywords:[]};scope.find("[data-role='keywords']").each(function(){if($(this).val()){data.keywords.push($(this).val());}});ips.getAjax()(scope.attr('data-action'),{data:data,type:'post',showLoading:true}).done(function(response){scope[0].closest("[popover]")?.hidePopover();ips.ui.flashMsg.show('Keywords saved');});},});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.changeTheme',{initialize:function(){this.on('menuItemSelected',_.bind(this.themePreferenceSelected,this));this.on('click','[data-role="mobileThemeMenu"] button',this.mobileThemePreferenceSelected);this.setTheme();},setTheme:function(){if(_.isUndefined(ips.utils.cookie.get('acptheme'))||ips.utils.cookie.get('acptheme')=='undefined'){if(window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches){$('html').attr('data-ips-scheme','dark');ips.utils.cookie.set('acpthemedefault','dark');}
else
{$('html').attr('data-ips-scheme','light');ips.utils.cookie.set('acpthemedefault','light');}}
else
{if(ips.utils.cookie.get('acptheme')==='dark'){$('html').attr('data-ips-scheme','dark');}else{$('html').attr('data-ips-scheme','light');}}},themePreferenceSelected:function(e,data){if(_.isUndefined(data.selectedItemID)){return;}
e.preventDefault();if(data.selectedItemID=='os'){ips.utils.cookie.unset('acptheme');}
{if(ips.utils.cookie.get('acptheme')==='dark'){$('html').attr('data-ips-scheme','dark');}else{$('html').attr('data-ips-scheme','light');}}},updatePreference:function(choice){if(choice=='os'){ips.utils.cookie.unset('acptheme');}
else
{var expires=new Date();expires.setFullYear(expires.getFullYear()+1);ips.utils.cookie.set('acptheme',data.selectedItemID,expires.toUTCString());}
$('#elThemeMenu_menu, #elNavThemeMob_menu').find('.ipsMenu_itemChecked').removeClass('ipsMenu_itemChecked');$('#elThemeMenu_menu, #elNavThemeMob_menu').find('[data-ipsMenuValue="'+data.selectedItemID+'"]').addClass('ipsMenu_itemChecked');this.setTheme();}});}(jQuery,_));;
{var expires=new Date();expires.setFullYear(expires.getFullYear()+1);ips.utils.cookie.set('acptheme',choice,expires.toUTCString());}},themePreferenceSelected:function(e,data=e.detail){if(_.isUndefined(data.selectedItemID)){return;}
this.updatePreference(data.selectedItemID);this.setTheme();},mobileThemePreferenceSelected:function(e){let choice=e.currentTarget.getAttribute("data-value");this.updatePreference(choice);this.setTheme();}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.editable',{_editTimeout:null,_editing:false,initialize:function(){this.on('mousedown',this.editMousedown);this.on('mouseup mouseleave',this.editMouseup);this.on('click',this.editMouseclick);this.on('click','[data-role="edit"]',this.clickEdit);this.setup();},setup:function(){var defaultFill=this.scope.attr('data-default');if(ips.utils.events.isTouchDevice()||(!_.isUndefined(defaultFill)&&defaultFill=='empty')){this.scope.removeClass('ipsType_editable').find('[data-role="edit"]').show();}},clickEdit:function(e){e.preventDefault();this._triggerEdit();},editMousedown:function(e){var self=this;if(e.which!==1){return;}
this._editTimeout=setTimeout(_.bind(this._triggerEdit,this),1000);},editMouseup:function(e){clearTimeout(this._editTimeout);},editMouseclick:function(e){if(this._editing){e.preventDefault();}},_triggerEdit:function(){var self=this;this._editing=true;clearTimeout(this._editTimeout);var span=this.scope;var url=span.attr('data-url');var textField=span.find('[data-role="text"]');var fieldName=span.find('[data-name]').attr('data-name');var defaultFill=span.attr('data-default');span.hide();var defaultText=(_.isUndefined(defaultFill)||defaultFill!='empty')?textField.text().trim():'';var inputNode=$('<input/>').attr({type:'text'}).attr('data-role','editField').val(defaultText);span.after(inputNode);inputNode.focus();inputNode.on('blur',function(){inputNode.addClass('ipsField_loading');if(inputNode.val()==''){inputNode.remove();span.show();self._editing=false;}else{var dataToSend={};dataToSend[fieldName]=inputNode.val();ips.getAjax()(url,{method:'post',data:dataToSend}).done(function(response){textField.text(inputNode.val());}).fail(function(response){ips.ui.alert.show({type:'alert',icon:'warn',message:response.responseJSON,});}).always(function(){inputNode.remove();span.show();self._editing=false;});}});inputNode.on('keypress',function(e){if(e.keyCode==ips.ui.key.ENTER){e.stopPropagation();e.preventDefault();inputNode.blur();return false;}});inputNode.on('keydown',function(e){if(e.keyCode==ips.ui.key.ESCAPE){inputNode.remove();span.show();self._editing=false;return false;}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.langString',{_url:null,_hideTimeout:null,_currentValue:'',initialize:function(){this.on('input','textarea',this.changeTextarea);this.on('focus','textarea',this.focusTextarea);this.on('blur','textarea',this.blurTextarea);this.on('click','[data-action="saveWords"]',this.saveWords);this.on('click','[data-action="revertWords"]',this.revertWords);this.setup();},setup:function(){this._url=this.scope.attr('data-saveURL');const contentRoot=this.elem.querySelector('[data-langcontent]');let contents;if(contentRoot){const getText=node=>(node instanceof Text?[node.wholeText]:(node.childNodes?.length?[...node.childNodes].map(getText):[])).flat();contents=getText(contentRoot).join('');}else{contents=this.elem.innerText;}
+2 -6
View File
@@ -17,14 +17,10 @@ ips.templates.set('dashboard.widget',`
</div>
</div>
</li>
`);ips.templates.set('dashboard.menuItem',`
<li class='ipsMenu_item' data-ipsMenuValue='{{key}}' data-widgetName='{{name}}' data-widgetBy='{{by}}'>
<a href='#'>{{name}}</a>
</li>
`);;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.dashboard.adminNotes',{initialize:function(){this.on('submit','form',this.saveNotes);},saveNotes:function(e){e.preventDefault();var url=$(e.currentTarget).attr('action');var self=this;this.scope.find('[data-role="notesInfo"]').hide();this.scope.find('[data-role="notesLoading"]').removeClass('ipsHide');ips.getAjax()(url,{type:'post',data:$('#admin_notes').serialize()}).done(function(response){self.scope.find('[data-role="notesInfo"]').html(response);}).fail(function(){}).always(function(){self.scope.find('[data-role="notesInfo"]').show();self.scope.find('[data-role="notesLoading"]').addClass('ipsHide');});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.dashboard.main',{_managing:false,initialize:function(){this.on('click','.acpWidget_close',this.closeWidget);this.on('click','[data-widgetCollapse]',this.collapseWidget);this.on(document,'menuItemSelected','#elAddWidgets:not( .ipsButton--disabled )',this.addWidget);this.on('refreshWidget','[data-widgetKey]',this.refreshWidget);this.setup();},setup:function(){this.mainColumn=this.scope.find('[data-role="mainColumn"]');this.sideColumn=this.scope.find('[data-role="sideColumn"]');this.scope.find('[data-role="sideColumn"]').sortable({handle:'.acpWidget_reorder',forcePlaceholderSize:true,placeholder:'acpWidget_emptyHover',connectWith:'[data-role="mainColumn"]',tolerance:'pointer',start:this.startDrag,stop:_.bind(this.stopDrag,this),update:_.bind(this.update,this)});this.scope.find('[data-role="mainColumn"]').sortable({handle:'.acpWidget_reorder',forcePlaceholderSize:true,placeholder:'acpWidget_emptyHover',connectWith:'[data-role="sideColumn"]',tolerance:'pointer',start:this.startDrag,stop:_.bind(this.stopDrag,this),update:_.bind(this.update,this)});this.scope.find('[data-widgetCollapsed="true"][data-widgetCollapse-content]').hide();},startDrag:function(e,ui){$('body').attr('data-dragging',true).css({overflow:'scroll'});ui.item.css({zIndex:ips.ui.zIndex()});},stopDrag:function(e,ui){$('body').removeAttr('data-dragging').css({overflow:'auto'});$(ui.item).trigger('sorted.dashboard',{ui:ui});this._loadWidget($(ui.item).attr('data-widgetkey'));$('#ipsTooltip').hide();},update:function(){this._savePositions();},closeWidget:function(e){e.preventDefault();var self=this;var widget=$(e.currentTarget).closest('[data-widgetKey]');var key=widget.attr('data-widgetKey');var name=widget.attr('data-widgetName');widget.animationComplete(function(){widget.remove();self.mainColumn.sortable('refresh');self.sideColumn.sortable('refresh');self._savePositions();});widget.animate({height:"0"});ips.utils.anim.go('zoomOut fast',widget);$('#elAddWidgets_menu').find('[data-ipsMenuValue="'+key+'"]').removeClass('ipsHide');this.scope.find('#elAddWidgets_button').removeClass('ipsButton--disabled').removeAttr('data-disabled');},collapseWidget:function(e){e.preventDefault();if($(e.target).is('.acpWidget_tools *')){return;}
var self=this;var widget=$(e.currentTarget).closest('[data-widgetKey]');var collapsed=widget.find('[data-role="widgetContent"]').attr('data-widgetCollapsed');widget.find('[data-role="widgetContent"]').attr('data-widgetCollapsed',(collapsed=='true')?'false':'true');widget.find('[data-widgetCollapse-content]').slideToggle();this._savePositions();},addWidget:function(e,data){data.originalEvent.preventDefault();var item=data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"]');var key=item.attr('data-ipsMenuValue');var name=item.attr('data-widgetName');var newWidget=ips.templates.render('dashboard.widget',{key:key,name:name});this.mainColumn.prepend(newWidget);var newWidgetElem=this.mainColumn.find('#elWidget_'+key);ips.utils.anim.go('fadeIn',newWidgetElem);this._loadWidget(key);this._savePositions();setTimeout(function(){item.addClass('ipsHide');},500);if(!data.menuElem.find('[data-ipsMenuValue]:not( .ipsHide ):not( [data-ipsMenuValue="'+data.selectedItemID+'"] )').length){this.scope.find('#elAddWidgets_button').addClass('ipsButton--disabled').attr('data-disabled',true);}},_loadWidget:function(key){var widget=this.scope.find('[data-widgetKey="'+key+'"]');if(!widget.length){return;}
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.dashboard.main',{_managing:false,initialize:function(){this.on('click','.acpWidget_close',this.closeWidget);this.on('click','[data-widgetCollapse]',this.collapseWidget);this.on(document,'menuItemSelected','#elAddWidgets:not( .ipsButton--disabled )',this.addWidget);this.on('refreshWidget','[data-widgetKey]',this.refreshWidget);this.setup();},setup:function(){this.mainColumn=this.scope.find('[data-role="mainColumn"]');this.sideColumn=this.scope.find('[data-role="sideColumn"]');this.scope.find('[data-role="sideColumn"]').sortable({handle:'.acpWidget_reorder',forcePlaceholderSize:true,placeholder:'acpWidget_emptyHover',connectWith:'[data-role="mainColumn"]',tolerance:'pointer',start:this.startDrag,stop:_.bind(this.stopDrag,this),update:_.bind(this.update,this)});this.scope.find('[data-role="mainColumn"]').sortable({handle:'.acpWidget_reorder',forcePlaceholderSize:true,placeholder:'acpWidget_emptyHover',connectWith:'[data-role="sideColumn"]',tolerance:'pointer',start:this.startDrag,stop:_.bind(this.stopDrag,this),update:_.bind(this.update,this)});this.scope.find('[data-widgetCollapsed="true"][data-widgetCollapse-content]').hide();},startDrag:function(e,ui){$('body').attr('data-dragging',true).css({overflow:'scroll'});ui.item.css({zIndex:ips.ui.zIndex()});},stopDrag:function(e,ui){$('body').removeAttr('data-dragging').css({overflow:'auto'});$(ui.item).trigger('sorted.dashboard',{ui:ui});this._loadWidget($(ui.item).attr('data-widgetkey'));$('#ipsTooltip')[0].hidePopover();},update:function(){this._savePositions();},closeWidget:function(e){e.preventDefault();var self=this;var widget=$(e.currentTarget).closest('[data-widgetKey]');var key=widget.attr('data-widgetKey');var name=widget.attr('data-widgetName');widget.animationComplete(function(){widget.remove();self.mainColumn.sortable('refresh');self.sideColumn.sortable('refresh');self._savePositions();});widget.animate({height:"0"});ips.utils.anim.go('zoomOut fast',widget);$('#elAddWidgets_menu').find('[data-ipsMenuValue="'+key+'"]').removeClass('ipsHide');this.scope.find('#elAddWidgets_button').removeClass('ipsButton--disabled').removeAttr('data-disabled');},collapseWidget:function(e){e.preventDefault();if($(e.target).is('.acpWidget_tools *')){return;}
var self=this;var widget=$(e.currentTarget).closest('[data-widgetKey]');var collapsed=widget.find('[data-role="widgetContent"]').attr('data-widgetCollapsed');widget.find('[data-role="widgetContent"]').attr('data-widgetCollapsed',(collapsed=='true')?'false':'true');widget.find('[data-widgetCollapse-content]').slideToggle();this._savePositions();},addWidget:function(e,data=e.detail){data.originalEvent.preventDefault();var item=$(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"]');var key=item.attr('data-ipsMenuValue');var name=item.attr('data-widgetName');var newWidget=ips.templates.render('dashboard.widget',{key:key,name:name});this.mainColumn.prepend(newWidget);var newWidgetElem=this.mainColumn.find('#elWidget_'+key);ips.utils.anim.go('fadeIn',newWidgetElem);this._loadWidget(key);this._savePositions();setTimeout(function(){item.addClass('ipsHide');},500);if(!$(data.menuElem).find('[data-ipsMenuValue]:not( .ipsHide ):not( [data-ipsMenuValue="'+data.selectedItemID+'"] )').length){this.scope.find('#elAddWidgets_button').addClass('ipsButton--disabled').attr('data-disabled',true);}},_loadWidget:function(key){var widget=this.scope.find('[data-widgetKey="'+key+'"]');if(!widget.length){return;}
widget.find('[data-role="widgetContent"]').css({height:widget.find('[data-role="widgetContent"]').outerHeight()+'px',}).html('').addClass('ipsLoading');ips.getAjax()('?app=core&module=overview&controller=dashboard&do=getBlock',{data:{appKey:key.substr(0,key.indexOf('_')),blockKey:key}}).done(function(response){widget.find('[data-role="widgetContent"]').css({height:'auto'}).html(response).removeClass('ipsLoading');$(document).trigger('contentChange',[widget]);});},refreshWidget:function(e){var key=$(e.currentTarget).attr('data-widgetKey');this._loadWidget(key);},_savePositions:function(){var main=this.mainColumn.sortable('toArray',{attribute:'data-widgetKey'});var side=this.sideColumn.sortable('toArray',{attribute:'data-widgetKey'});var collapsed=_.map(this.scope.find('[data-widgetCollapsed="true"]'),function(elem){return $(elem).closest('[data-widgetKey]').attr('data-widgetKey');});ips.getAjax()('?app=core&module=overview&controller=dashboard&do=update',{data:{blocks:{'main':main,'side':side,'collapsed':collapsed}}}).done(function(){}).fail(function(){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('dashboard_cant_save'),callbacks:{}});});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.dashboard.onboard',{initialize:function(){this.on('click','[data-role="sectionToggle"]',this.toggleSection);this.on('click','[data-action="nextStep"]',this.nextStep);this.on('click','[data-action="skipStep"]',this.skipStep);this.setup();},setup:function(){},toggleSection:function(e){e.preventDefault();this.scope.find('[data-role="sectionWrap"]').addClass('cOnboard__section--closed');$(e.currentTarget).closest('.cOnboard__section').toggleClass('cOnboard__section--closed');$(document).trigger('contentChange',[$(e.currentTarget).closest('.cOnboard__section')]);},nextStep:function(e){e.preventDefault();var wrap=$(e.currentTarget).closest('.cOnboard__section');var nextWrap=wrap.next('.cOnboard__section');if(nextWrap.length){$('html, body').animate({scrollTop:String(wrap.position().top-70)},function(){setTimeout(function(){wrap.addClass('cOnboard__section--closed cOnboard__section--done');nextWrap.removeClass('cOnboard__section--closed');$(document).trigger('contentChange',[nextWrap]);},200);});}else{wrap.addClass('cOnboard__section--closed cOnboard__section--done');}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.dashboard.validation',{initialize:function(){this.on('click','[data-action="approve"], [data-action="ban"]',this.validateUser);},validateUser:function(e){e.preventDefault();var self=this;var button=$(e.currentTarget);var url=button.attr('href');var type=button.attr('data-action');var row=button.closest('[data-role="validatingRow"]');var name=row.find('[data-role="userName"]').text();var toggles=button.closest('[data-role="validateToggles"]');ips.ui.alert.show({type:'confirm',callbacks:{'ok':function(){toggles.find('a').addClass('ipsButton--disabled');ips.getAjax()(url).done(function(response){ips.ui.flashMsg.show(ips.getString(type=='approve'?'userApproved':'userBanned',{name:name}));if(response){var newElement=$(response);$(self.scope).replaceWith(newElement);$(document).trigger('contentChange',[newElement]);}else{ips.utils.anim.go('fadeOut',$(self.scope).closest('.cNotification'));$('body').trigger('updateNotificationCount');}});}}});}});}(jQuery,_));;
+1 -1
View File
@@ -1,2 +1,2 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.developer.details',{initialize:function(){this.setup();},setup:function(){var self=this;_.each($(this.scope).find('[data-role="devCenterIssues"]'),function(elem){$(elem).find('[data-role="devCenterIssues_content"]').html('').addClass('ipsLoading');$(elem).find('[data-iconType]').hide();$(elem).removeClass('elCritical');self.loadDevCenterIssues();});},loadDevCenterIssues:function(){var self=this;ips.getAjax()('?app=core&module=developer&controller=details&appKey='+ips.getSetting('devAppKey')+'&do=scan').done(function(response){self.scope.find('[data-role="devCenterIssues_content"]').html(response.html).removeClass('ipsLoading');$(document).trigger('contentChange',[self.scope.find('[data-role="devCenterIssues"]')]);self.scope.find('[data-role="devCenterIssues"] [data-iconType]').hide();if(parseInt(response.criticalIssues)){ips.utils.anim.go('fadeIn slow',self.scope.find('[data-role="devCenterIssues"] [data-iconType="critical"]'));self.scope.find('[data-role="devCenterIssues"]').addClass('elCritical');}
else if(parseInt(response.recommendedIssues)){ips.utils.anim.go('fadeIn slow',self.scope.find('[data-role="devCenterIssues"] [data-iconType="recommended"]'));}}).fail(function(response){self.scope.find('[data-role="devCenterIssues_content"]').html(ips.getString("hookscanner_error")).removeClass("ipsLoading");self.scope.find('[data-role="devCenterIssues"]').addClass('elCritical');$(document).trigger('contentChange',[self.scope.find('[data-role="devCenterIssues"]')]);});}});}(jQuery,_));;
else if(parseInt(response.recommendedIssues)){ips.utils.anim.go('fadeIn slow',self.scope.find('[data-role="devCenterIssues"] [data-iconType="recommended"]'));}}).fail(function(response){self.scope.find('[data-role="devCenterIssues_content"]').removeClass("ipsLoading");self.scope.find('[data-role="devCenterIssues"]').addClass('elCritical');$(document).trigger('contentChange',[self.scope.find('[data-role="devCenterIssues"]')]);});}});}(jQuery,_));;
-3
View File
@@ -1,5 +1,2 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.files.form',{initialize:function(){if(this.scope.find('input[name=filestorage_move]')){$('#form_filestorage_move').hide();this.on('submit','form',this.submitForm);}},submitForm:function(e){var self=this;if($(e.currentTarget).attr('data-bypassValidation')){return true;}
e.preventDefault();$(e.currentTarget).attr('data-bypassValidation',true);ips.getAjax()($(e.currentTarget).attr('action').replace('do=configurationForm','do=checkMoveNeeded'),{data:$(e.currentTarget).serialize(),type:'post'}).done(function(response){if(response.needsMoving){ips.ui.alert.show({type:'confirm',message:ips.getString('files_overview_move_desc'),icon:'fa-solid fa-triangle-exclamation',buttons:{ok:ips.getString('files_overview_move'),cancel:ips.getString('files_overview_leave')},callbacks:{ok:function(){$('input[name=filestorage_move_checkbox]').prop('checked',true);$(e.currentTarget).submit();},cancel:function(){$('input[name=filestorage_move_checkbox]').prop('checked',false);$(e.currentTarget).submit();}}});}
else{$(e.currentTarget).submit();}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('ips.admin.files.multimod',{initialize:function(){this.on('submit','[data-role="moderationTools"]',this.moderationSubmit);this.on('menuItemSelected',this.itemSelected);},moderationSubmit:function(e){var action=this.scope.find('[data-role="moderationAction"]').val();switch(action){case'delete':this._modActionDelete(e);break;default:$(document).trigger('moderationSubmitted');break;}},_modActionDelete:function(e){var self=this;var form=this.scope.find('[data-role="moderationTools"]');if(self._bypassDeleteCheck){return;}
e.preventDefault();var count=parseInt(this.scope.find('[data-role="moderation"]:checked').length);ips.ui.alert.show({type:'confirm',icon:'warn',message:(count>1)?ips.pluralize(ips.getString('delete_confirm_many'),count):ips.getString('delete_confirm'),callbacks:{ok:function(){$(document).trigger('moderationSubmitted');self._bypassDeleteCheck=true;self.scope.find('[data-role="moderationTools"]').submit();}}});}});}(jQuery,_));;
+9 -8
View File
@@ -1,13 +1,15 @@
ips.templates.set('moderatorPermissions.checkUncheckAll'," <li class='ipsFieldRow'> <div class='ipsFieldRow__label'> </div> <div class='ipsFieldRow__content'> <ul class='ipsList ipsList--inline i-font-weight_500'> <li><button type='button' data-role='checkAll'>{{#lang}}check_all{{/lang}}</button></li> <li><button type='button' data-role='uncheckAll'>{{#lang}}uncheck_all{{/lang}}</button></li> </ul> </div> </li>");;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.restrictions',{initialize:function(){this.on('click','.acpRestrictions_subHeader h3',this.toggleSubHeader);this.on('change','.acpRestrictions_header input[type="checkbox"]',this.toggleHeader);this.on('change','.acpAppRestrictions_header input[type="checkbox"]',this.toggleAppHeader);this.on('click','[data-action="checkAll"]',this.checkAll);this.on('click','[data-action="checkNone"]',this.checkNone);this.on('click','[data-action="expandAll"], [data-action="collapseAll"]',this.toggleDisplay);this.setup();},toggleDisplay:function(e){e.preventDefault();var row=$(e.currentTarget).closest('.acpRestrictions_header');var subHeaders=row.next().find('.acpRestrictions_subHeader');var self=this;var action=($(e.currentTarget).attr('data-action')=='expandAll')?'expand':'collapse';subHeaders.each(function(){if(action=='expand'){self._expandSection($(this));}else{self._collapseSection($(this));}});},toggleAppHeader:function(e){var check=$(e.currentTarget);var row=check.closest('.acpAppRestrictions_header');if(!check.is(':checked')){row.siblings('.acpAppRestrictions_panel').find('.acpRestrictions_header input[type="checkbox"]').each(function(){$(this).prop('disabled',true).attr('data-originalState',$(this).is(':checked')).attr('checked',false).trigger('change');});}else{row.siblings('.acpAppRestrictions_panel').find('input[type="checkbox"]').each(function(){var thisCheck=$(this);thisCheck.prop('disabled',false);if(thisCheck.attr('data-originalState')=='true'){thisCheck.prop('checked',true).trigger('change');}});row.siblings('.acpAppRestrictions_panel').find('.acpRestrictions_panel input[type="checkbox"]').each(function(){var thisCheck=$(this);var checked=thisCheck.closest('.acpRestrictions_panel').siblings('.acpRestrictions_header').find('input[type="checkbox"]').is(':checked');if(!checked){thisCheck.prop('disabled',true);}else{thisCheck.prop('disabled',false);}
if(thisCheck.attr('data-originalState')=='true'){thisCheck.prop('checked',true).trigger('change');}});}},toggleHeader:function(e){var check=$(e.currentTarget);var row=check.closest('.acpRestrictions_header');var unChecked=!check.is(':checked');row.next().find('input[type="checkbox"]').each(function(){var thisCheck=$(this);if(unChecked){thisCheck.attr('data-originalState',thisCheck.is(':checked')).prop('checked',false);}else if((thisCheck.attr('data-originalState')=='true')){thisCheck.prop('checked',true);}
thisCheck.prop('disabled',unChecked).trigger('change');});},toggleSubHeader:function(e){var header=$(e.currentTarget).parent();if(header.hasClass('acpRestrictions_open')){this._collapseSection(header);}else{this._expandSection(header);}},_expandSection:function(section){var next=section.next('ul');section.addClass('acpRestrictions_open').removeClass('acpRestrictions_closed');ips.utils.anim.go('fadeInDown fast',next);},_collapseSection:function(section){section.removeClass('acpRestrictions_open').addClass('acpRestrictions_closed');},checkAll:function(e){e.preventDefault();var self=this;var header=$(e.currentTarget).parents('.acpRestrictions_subHeader');var next=header.next('ul');if(!next.is(':visible')){next.animationComplete(function(){self._togglePermissions(true,next);});this._expandSection(header);}else{this._togglePermissions(true,next);}},checkNone:function(e){e.preventDefault();var self=this;var header=$(e.currentTarget).parents('.acpRestrictions_subHeader');var next=header.next('ul');if(!next.is(':visible')){next.animationComplete(function(){self._togglePermissions(false,next);});this._expandSection(header);}else{this._togglePermissions(false,next);}},_togglePermissions:function(state,container){container.find('input[type="checkbox"]:not( [disabled] )').prop('checked',state).change();},setup:function(){this.scope.find('.acpRestrictions_open').removeClass('acpRestrictions_open').addClass('acpRestrictions_closed');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.moderatorPermissions',{initialize:function(){this.on('change','#ipsTabs_form_modperms__core_Content_panel input[type="checkbox"]',this.toggle);this.on('click','[data-role="checkAll"]',this.checkAll);this.on('click','[data-role="uncheckAll"]',this.checkAll);this.setup();},setup:function(){var mainPanel=this.scope.find('#ipsTabs_form_modperms__core_Content_panel');var self=this;mainPanel.find('input[type="checkbox"]').each(function(){self._toggleChanged($(this));});$(this.scope).find('.ipsTabs__panel').each(function(){var controls=$(ips.templates.render('moderatorPermissions.checkUncheckAll'));controls.find('button').attr('data-scope',$(this).attr('id'));$(this).children('ul').prepend(controls);});this._checkEachTab();},checkAll:function(e){e.preventDefault();var check=$(e.currentTarget).attr('data-role')=='checkAll';if($(e.currentTarget).attr('data-scope')){var scope=$('#'+$(e.currentTarget).attr('data-scope'));}else{var scope=$(this.scope);}
if(check&&!$(e.currentTarget).attr('data-scope')){$('input[name="mod_use_restrictions"][value="no"]').prop('checked',true).change();}
var self=this;scope.find('input[type="checkbox"]').each(function(){if(check&&!$(this).is(':checked')){$(this).prop('checked',true).change();}else if(!check&&$(this).is(':checked')){$(this).prop('checked',false).change();}});},toggle:function(e){this._toggleChanged($(e.currentTarget));this._checkEachTab();},_toggleChanged:function(thisToggle){var id=thisToggle.closest('.ipsFieldRow').attr('id').replace('_content','');var panels=this.scope.find('.ipsTabs__panel:not( #ipsTabs_form_modperms__core_Content_panel )');var otherToggles=panels.find('.ipsFieldRow[id^="'+id+'"]').not(thisToggle.closest('.ipsFieldRow'));if(thisToggle.is(':checked')){otherToggles.hide();otherToggles.find('input[type="checkbox"]').prop('disabled',true);}else{otherToggles.show();otherToggles.find('input[type="checkbox"]').prop('disabled',false);}},_checkEachTab:function(){var self=this;var panels=this.scope.find('.ipsTabs__panel:not( #ipsTabs_form_modperms__core_Content_panel )');panels.each(function(){var count=$(this).find('input[type="checkbox"]:enabled:not( [data-role="zeroVal"] )').length;var id=$(this).attr('id').replace('ipsTabs_tabs_form_','').replace('_panel','');if(!count){self.scope.find('#'+id).closest('li').hide();}else{self.scope.find('#'+id).closest('li').show();}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.listFlagSpammer',{initialize:function(){this.on('click',this.toggleFlagSpammer);},toggleFlagSpammer:function(e){e.preventDefault();var elem=$(e.currentTarget);var icon=elem.find('.fa-flag');ips.ui.alert.show({'type':'confirm','icon':'warn','message':icon.hasClass('ipsType_spammer')?ips.getString('confirmUnFlagAsSpammer'):ips.getString('confirmFlagAsSpammer'),'subText':icon.hasClass('ipsType_spammer')?ips.getString('confirmUnFlagAsSpammerDesc'):'',callbacks:{ok:function(){ips.getAjax()(elem.attr('href'),{dataType:'json'}).done(function(response){ips.ui.flashMsg.show(response);icon.toggleClass('ipsType_spammer');var newStatus=ips.utils.url.getParam('status',elem.attr('href'))==1?0:1;var newUrl=ips.utils.url.removeParam('status',elem.attr('href'));elem.attr('href',newUrl+'&status='+newStatus);elem.attr('_title',newStatus?ips.getString('flagAsSpammer'):ips.getString('unflagAsSpammer'));elem.attr('aria-label',newStatus?ips.getString('flagAsSpammer'):ips.getString('unflagAsSpammer'));}).fail(function(jqXHR){if(Debug.isEnabled()){Debug.error(jqXHR.responseText);}else{window.location=elem.attr('href');}});}}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.history',{initialize:function(){this.on('menuItemSelected',this.filterSelected);},filterSelected:function(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
if(data.triggerID=='memberHistoryFilters'){$(this.scope).find('[data-role="historyTitle"]').text(data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"]').text());$(this.scope).find('[data-role="historyDisplay"]').addClass('ipsLoading').html('');ips.getAjax()(data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"] a').attr('href')).done(function(response){$(this.scope).find('[data-role="historyDisplay"]').html(response).removeClass('ipsLoading');$(document).trigger('contentChange',[this.scope]);}.bind(this));}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.restrictions',{initialize:function(){this.on('click','.acpRestrictions_subHeader h3',this.toggleSubHeader);this.on('change','.acpRestrictions_header input[type="checkbox"]',this.toggleHeader);this.on('change','.acpAppRestrictions_header input[type="checkbox"]',this.toggleAppHeader);this.on('click','[data-action="checkAll"]',this.checkAll);this.on('click','[data-action="checkNone"]',this.checkNone);this.on('click','[data-action="expandAll"], [data-action="collapseAll"]',this.toggleDisplay);this.setup();},toggleDisplay:function(e){e.preventDefault();var row=$(e.currentTarget).closest('.acpRestrictions_header');var subHeaders=row.next().find('.acpRestrictions_subHeader');var self=this;var action=($(e.currentTarget).attr('data-action')=='expandAll')?'expand':'collapse';subHeaders.each(function(){if(action=='expand'){self._expandSection($(this));}else{self._collapseSection($(this));}});},toggleAppHeader:function(e){var check=$(e.currentTarget);var row=check.closest('.acpAppRestrictions_header');if(!check.is(':checked')){row.siblings('.acpAppRestrictions_panel').find('.acpRestrictions_header input[type="checkbox"]').each(function(){$(this).prop('disabled',true).attr('data-originalState',$(this).is(':checked')).attr('checked',false).trigger('change');});}else{row.siblings('.acpAppRestrictions_panel').find('input[type="checkbox"]').each(function(){var thisCheck=$(this);thisCheck.prop('disabled',false);if(thisCheck.attr('data-originalState')=='true'){thisCheck.prop('checked',true).trigger('change');}});row.siblings('.acpAppRestrictions_panel').find('.acpRestrictions_panel input[type="checkbox"]').each(function(){var thisCheck=$(this);var checked=thisCheck.closest('.acpRestrictions_panel').siblings('.acpRestrictions_header').find('input[type="checkbox"]').is(':checked');if(!checked){thisCheck.prop('disabled',true);}else{thisCheck.prop('disabled',false);}
if(thisCheck.attr('data-originalState')=='true'){thisCheck.prop('checked',true).trigger('change');}});}},toggleHeader:function(e){var check=$(e.currentTarget);var row=check.closest('.acpRestrictions_header');var unChecked=!check.is(':checked');row.next().find('input[type="checkbox"]').each(function(){var thisCheck=$(this);if(unChecked){thisCheck.attr('data-originalState',thisCheck.is(':checked')).prop('checked',false);}else if((thisCheck.attr('data-originalState')=='true')){thisCheck.prop('checked',true);}
thisCheck.prop('disabled',unChecked).trigger('change');});},toggleSubHeader:function(e){var header=$(e.currentTarget).parent();if(header.hasClass('acpRestrictions_open')){this._collapseSection(header);}else{this._expandSection(header);}},_expandSection:function(section){var next=section.next('ul');section.addClass('acpRestrictions_open').removeClass('acpRestrictions_closed');ips.utils.anim.go('fadeInDown fast',next);},_collapseSection:function(section){section.removeClass('acpRestrictions_open').addClass('acpRestrictions_closed');},checkAll:function(e){e.preventDefault();var self=this;var header=$(e.currentTarget).parents('.acpRestrictions_subHeader');var next=header.next('ul');if(!next.is(':visible')){next.animationComplete(function(){self._togglePermissions(true,next);});this._expandSection(header);}else{this._togglePermissions(true,next);}},checkNone:function(e){e.preventDefault();var self=this;var header=$(e.currentTarget).parents('.acpRestrictions_subHeader');var next=header.next('ul');if(!next.is(':visible')){next.animationComplete(function(){self._togglePermissions(false,next);});this._expandSection(header);}else{this._togglePermissions(false,next);}},_togglePermissions:function(state,container){container.find('input[type="checkbox"]:not( [disabled] )').prop('checked',state).change();},setup:function(){this.scope.find('.acpRestrictions_open').removeClass('acpRestrictions_open').addClass('acpRestrictions_closed');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.listFlagSpammer',{initialize:function(){this.on('click',this.toggleFlagSpammer);},toggleFlagSpammer:function(e){e.preventDefault();var elem=$(e.currentTarget);var icon=elem.find('.fa-flag');var textLabel=elem.find('span');ips.ui.alert.show({'type':'confirm','icon':'warn','message':icon.hasClass('i-color_warning')?ips.getString('confirmUnFlagAsSpammer'):ips.getString('confirmFlagAsSpammer'),'subText':icon.hasClass('i-color_warning')?ips.getString('confirmUnFlagAsSpammerDesc'):'',callbacks:{ok:function(){ips.getAjax()(elem.attr('href'),{dataType:'json'}).done(function(response){ips.ui.flashMsg.show(response);icon.toggleClass('i-color_warning');var newStatus=ips.utils.url.getParam('status',elem.attr('href'))==1?0:1;var newUrl=ips.utils.url.removeParam('status',elem.attr('href'));elem.attr('href',newUrl+'&status='+newStatus);elem.attr('_title',newStatus?ips.getString('flagAsSpammer'):ips.getString('unflagAsSpammer'));elem.attr('aria-label',newStatus?ips.getString('flagAsSpammer'):ips.getString('unflagAsSpammer'));textLabel.text(newStatus?ips.getString('flagAsSpammer'):ips.getString('unflagAsSpammer'));}).fail(function(jqXHR){if(Debug.isEnabled()){Debug.error(jqXHR.responseText);}else{window.location=elem.attr('href');}});}}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.lazyLoadingProfileBlock',{initialize:function(){var scope=$(this.scope);ips.getAjax()(scope.attr('data-url')).done(function(response){const doc=(new DOMParser()).parseFromString(response,'text/html');scope.html(doc.body.innerHTML);let headInserts="";doc.head.querySelectorAll('script').forEach(script=>{if(!script.hasAttribute('src')||!document.querySelector(`script[src="${script.getAttribute('src')}"]`)){headInserts+=script.outerHTML+'\n';}});doc.head.querySelectorAll('link[href]').forEach(link=>{if(!document.querySelector(`link[href="${link.getAttribute('href')}"]`)){headInserts+=link.outerHTML+'\n';}});if(headInserts){document.head.insertAdjacentHTML('beforeend',headInserts);}
$(document).trigger('contentChange',[scope]);});},});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.history',{initialize:function(){this.on('menuItemSelected',this.filterSelected);},filterSelected:function(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
if(data.triggerID=='memberHistoryFilters'){$(this.scope).find('[data-role="historyTitle"]').text($(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"]').text());$(this.scope).find('[data-role="historyDisplay"]').addClass('ipsLoading').html('');ips.getAjax()($(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"] a').attr('href')).done(function(response){$(this.scope).find('[data-role="historyDisplay"]').html(response).removeClass('ipsLoading');$(document).trigger('contentChange',[this.scope]);}.bind(this));}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.form',{initialize:function(){this.on('submit',this.submitForm);},submitForm:function(e){var self=this;if($(e.currentTarget).attr('data-bypassValidation')){return true;}
e.preventDefault();e.stopPropagation();var isInAdminGroup=false;var mainGroup=this.scope.find('select[name=group]').val();var secondaryGroups=_.map(this.scope.find('select[name="secondary_groups[]"]').val(),function(val){return parseInt(val);});var adminGroups=$.parseJSON(this.scope.attr('data-adminGroups'));if(adminGroups.length){for(var i=0;i<adminGroups.length;i++){var testId=adminGroups[i];if(secondaryGroups!=null&&secondaryGroups.length&&_.indexOf(secondaryGroups,testId)!=-1){isInAdminGroup=true;}
if(testId==mainGroup){isInAdminGroup=true;}
@@ -19,5 +21,4 @@ this.scope.find('[data-role="regex"]').show();this.scope.find('[data-role="easy"
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.achievementRuleForm',{initialize(){this.on('click','[data-action="filterReveal"]',this.showFilter);this.on('click','[data-action="filterCollapse"]',this.hideFilter);this.on('change keyup','input[type="number"]',this.changeNumber);},showFilter(e){const ruleWrap=e.currentTarget.closest('[data-role="ruleWrap"]');const toggleWrap=e.currentTarget.closest('[data-role="toggleFilter"]');const check=toggleWrap.querySelector('input[type="checkbox"]');const conditionButtons=toggleWrap.closest('[data-role="conditionButtons"]');check.checked=true;check.dispatchEvent(new Event('change',{bubbles:true}));toggleWrap.ipsHide();if(conditionButtons?.querySelector('[data-role="toggleFilter"] input[data-filter]:not(:checked)')){conditionButtons?.ipsShow();}else{conditionButtons?.ipsHide();}
const filterName=check.dataset.filter;if(filterName){ruleWrap.querySelectorAll(`#${filterName}`).ipsShow();}
ruleWrap.querySelectorAll('input[type="number"]').forEach(el=>this._pluralizeNumber(el));},hideFilter(e){e.preventDefault();const filter=e.currentTarget.closest('[data-role="filterField"]');const filterName=filter.id;const check=filter.closest('[data-role="ruleWrap"]').querySelector(`#${filterName}Checkbox`);const toggleWrap=check.closest('[data-role="toggleFilter"]');check.checked=false;check.dispatchEvent(new Event('change',{bubbles:true}));toggleWrap.ipsShow()
toggleWrap.closest('[data-role="conditionButtons"]')?.ipsShow();filter.ipsHide();},changeNumber(e){this._pluralizeNumber(e.currentTarget);},_pluralizeNumber(input){const span=input.nextElementSibling;if(span?.matches('[data-role="th"]')){span.innerText=ips.pluralize(ips.getString('numberSuffix'),input.value);}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.members.lazyLoadingProfileBlock',{initialize:function(){var scope=$(this.scope);ips.getAjax()(scope.attr('data-url')).done(function(response){scope.html(response);$(document).trigger('contentChange',[scope]);});},});}(jQuery,_));;
toggleWrap.closest('[data-role="conditionButtons"]')?.ipsShow();filter.ipsHide();},changeNumber(e){this._pluralizeNumber(e.currentTarget);},_pluralizeNumber(input){const span=input.nextElementSibling;if(span?.matches('[data-role="th"]')){span.innerText=ips.pluralize(ips.getString('numberSuffix'),input.value);}}});}(jQuery,_));;
+39 -11
View File
@@ -1,14 +1,42 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.stats.overview',{dateFilters:{'start':null,'end':null,'range':null},initialize:function(){this.on('submit','[data-role="dateFilter"]',this.updateDateFilter);this.on('change','[data-action="toggleApp"]',this.toggleApp);this.on('change','[name="predate"]',this.submitForm);this.on('click','[data-action="cancelDateRange"]',this.cancelDateRange);this.on('stats.ready',this.blockReady);$(document).on('reloadStatsDateFilters',_.bind(this.resendDateFilters,this));this.setup();},setup:function(){this.url=this.scope.attr('data-url');this.dateFilters.range=this.scope.find('[data-role="dateFilter"]').attr('data-defaultRange');},resendDateFilters:function(e){this.trigger('stats.setDateFilters',{dateFilters:this.dateFilters,url:this.url});},cancelDateRange:function(e){e.preventDefault();this.scope.find('select[name="predate"]').val(this.scope.find('.cStatsFilters').attr('data-defaultRange')).change();},submitForm:function(e){var select=$(e.currentTarget);if(select.val()==='-1'){this.scope.find('.cStatsFilters [data-role="formTitle"], select[name="predate"]').hide();this.scope.find('.cStatsFilters button').show();}else{this.scope.find('.cStatsFilters [data-role="formTitle"], select[name="predate"]').show();this.scope.find('.cStatsFilters button').hide();select.closest('form').submit();}},blockReady:function(e,data){$(e.target).trigger('stats.loadBlock',{dateFilters:this.dateFilters,url:this.url});},toggleApp:function(){var enabledApps=_.map(this.scope.find('[data-action="toggleApp"]:checked'),function(app){return $(app).attr('data-toggledApp')});var disabledApps=_.map(this.scope.find('[data-action="toggleApp"]:not( :checked )'),function(app){return $(app).attr('data-toggledApp');});this.scope.find('.cStatTile[data-app]').each(function(){var tile=$(this);if(tile.hasClass('ipsHide')&&enabledApps.indexOf($(this).attr('data-app'))!==-1){tile.css({transform:'scale(0.7)',opacity:"0"}).removeClass('ipsHide').animate({transform:'scale(1)',opacity:"1"});}else if(enabledApps.indexOf($(this).attr('data-app'))===-1){tile.addClass('ipsHide');}});ips.utils.cookie.set('overviewExcludedApps',JSON.stringify(disabledApps),true);},updateDateFilter:function(e){e.preventDefault();e.stopPropagation();this.dateFilters={'start':null,'end':null,'range':this.scope.find('[name="predate"]').val()};if(this.dateFilters.range=='-1'){this.dateFilters.start=this.scope.find('[name="date[start]"]').val();this.dateFilters.end=this.scope.find('[name="date[end]"]').val();}
this.triggerOn('core.admin.stats.overviewBlock','stats.loadBlock',{dateFilters:this.dateFilters,url:this.url});this.triggerOn('core.admin.stats.nodeFilters','stats.setDateFilters',{dateFilters:this.dateFilters,url:this.url});},});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.stats.nodeFilters',{url:null,dateFilters:{'start':null,'end':null,'range':null},initialize:function(){this.on('submit',this.reloadBlock);$(document).on('stats.setDateFilters',_.bind(this.statsReady,this));$(document).on('click.hovercard',_.bind(function(){this.trigger('reloadStatsDateFilters');},this));this.trigger('reloadStatsDateFilters');},statsReady:function(e,data){this.url=data.url;this.dateFilters=data.dateFilters;},reloadBlock:function(e){var blockKey=$(e.currentTarget).attr('data-block');var subblock=$(e.currentTarget).attr('data-subblock');var blockElement=$('[data-role="statsBlock"][data-block="'+blockKey+'"][data-subblock="'+subblock.replace(/\\/g,'\\\\')+'"]');blockElement.attr('data-nodeFilter',$(e.currentTarget).find('[data-role="nodeValue"]').val());e.preventDefault();e.stopPropagation();this.trigger('stats.nodeFilters',{blockToRefresh:blockKey,subblockToRefresh:subblock,url:this.url,dateFilters:this.dateFilters});$(document).trigger('click');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.stats.overview',{_dateFilters:undefined,_dateFilterQueue:new Set(),set dateFilters(dateFilters){this._dateFilters=dateFilters;this._dateFilterQueue.forEach(cb=>cb());this._dateFilterQueue.clear();},get dateFilters(){if(this._dateFilters){return this._dateFilters;}
return{start:null,end:null,range:null,}},initialize:function(){document.addEventListener('ips:stats.setDateFilters',e=>this.updateDateFilter(e));this.on('change','[data-action="toggleApp"]',this.toggleApp);this.elem.addEventListener('stats.ready',_.debounce((...args)=>this.blockReady(...args),100));this.url=this.scope.attr('data-url');},dateFiltersKnown(){return new Promise((resolve)=>{if(this._dateFilters){return resolve();}
this._dateFilterQueue.add(resolve);setTimeout(()=>{document.dispatchEvent(new CustomEvent('reloadStatsDateFilters'));})});},async blockReady(e,data){await this.dateFiltersKnown();$(e.target).trigger('stats.loadBlock',{dateFilters:this.dateFilters,url:this.url});},toggleApp:function(){var enabledApps=_.map(this.scope.find('[data-action="toggleApp"]:checked'),function(app){return $(app).attr('data-toggledApp')});var disabledApps=_.map(this.scope.find('[data-action="toggleApp"]:not( :checked )'),function(app){return $(app).attr('data-toggledApp');});function toggleTiles(){this.scope.find('.cStatTile[data-app]').each(function(){var tile=$(this);if(tile.is('[hidden]')&&enabledApps.indexOf($(this).attr('data-app'))!==-1){tile.prop('hidden',false);}else if(enabledApps.indexOf($(this).attr('data-app'))===-1){tile.prop('hidden',true);}});};if(document.startViewTransition){document.startViewTransition(()=>toggleTiles());}else{toggleTiles();}
ips.utils.cookie.set('overviewExcludedApps',JSON.stringify(disabledApps),true);},updateDateFilter:function(e){this.dateFilters={...e.detail.dateFilters};this.triggerOn('core.admin.stats.overviewBlock','stats.loadBlock',{dateFilters:e.detail.dateFilters,url:this.url});this.triggerOn('core.admin.stats.nodeFilters','stats.setDateFilters',{dateFilters:e.detail.dateFilters,url:this.url});},});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.stats.liveDateFilter',{dateFilters:{'start':null,'end':null,'range':null},initialize(){this.on('submit',this.updateDateFilter);this.on('change','[name="predate"]',this.changeDateField);this.on('click','[data-action="cancelDateRange"]',this.cancelDateRange);document.addEventListener('reloadStatsDateFilters',e=>this.resendDateFilters(e));this.dateFilters.range=this.elem.dataset.defaultrange;this.elem.querySelector('[name="predate"]')?.dispatchEvent(new CustomEvent('change',{bubbles:true,detail:{submit:false}}));},resendDateFilters(){const url=new URL(window.location.href);let days=parseInt(this.dateFilters.range?.toString?.()||'NaN');if(Number.isInteger(days)&&days>=0){url.updateSearchParams({param:'predate',value:days.toString()});}else{['start','end'].forEach(prop=>{let ts=null;if(typeof this.dateFilters[prop]==='string'){try{ts=Math.round((new Date(this.dateFilters[prop])).getTime()/1000);}catch(e){}}
url.updateSearchParams({param:'predate',value:null});url.updateSearchParams({param:`date[${prop}]`,value:ts});});}
if(url.toString()!==window.location.href){ips.utils.history.replaceState({},'stats.liveDateFilter',url.toString());}
this.elem.dispatchEvent(new CustomEvent('ips:stats.setDateFilters',{bubbles:true,detail:{dateFilters:this.dateFilters}}));},cancelDateRange(e){e.preventDefault();const select=this.elem.querySelector('select[name="predate"]');select.value=this.elem.dataset.defaultrange;select.dispatchEvent(new CustomEvent('change',{bubbles:true}));},changeDateField(e){const select=e.target;if(!(select instanceof HTMLSelectElement)||!select?.matches?.('select[name="predate"]')){return;}
const button=this.elem.querySelectorAll('.cStatsFilters button');if(Number(select.value)===-1){select.ipsHide();button.ipsShow();}else{this.elem.dataset.defaultrange=select.value;select.ipsShow();button.ipsHide();if(e?.detail?.submit!==false){select.closest('form')?.dispatchEvent(new CustomEvent('submit'));}}},updateDateFilter(e){e.preventDefault();e.stopPropagation();this.dateFilters={'start':null,'end':null,'range':this.elem.querySelector('[name="predate"]').value};if(Number(this.dateFilters.range)===-1){this.dateFilters.start=this.elem.querySelector('[name="date[start]"]').value;this.dateFilters.end=this.elem.querySelector('[name="date[end]"]').value;}
this.resendDateFilters();this.actuallySubmitForm();},async actuallySubmitForm(){const url=new URL(this.elem.getAttribute('action'),window.location.href);if(!url.searchParams.has('report_id')||url.searchParams.get('app')!=='core'||url.searchParams.get('module')!=='overview'||url.searchParams.get('controller')!=='mycharts'){return;}
const values=Object.fromEntries([...(new FormData(this.elem)).entries()]);const response=await ips.fetch(url.toString(),{method:'post',data:values,});console.log('got form submission response',response);return response;}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.stats.filtering',{initialize:function(){this.on('click','[data-role="toggleGroupFilter"]',this.toggleGroupFilter);if($('#elGroupFilter').attr('data-hasGroupFilters')=='true'){$('#elGroupFilter').show();}},toggleGroupFilter:function(e){e.preventDefault();if($('#elGroupFilter').is(':visible')){$('#elGroupFilter').find('input[type="checkbox"]').prop('checked',true);$('#elGroupFilter').slideUp();}
else
{$('#elGroupFilter').slideDown();}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.stats.overviewBlock',{initialize:function(){Debug.log('init bloc');this.on('stats.loadBlock',this.loadBlock);$(document).on('stats.nodeFilters',_.bind(this.loadBlock,this));this.setup();},setup:function(){this.refresh=null;this.loaded=false;this.currentCounts=[];this.url=null;this.block=this.scope.attr('data-block');this.subblock=this.scope.attr('data-subblock');this.refreshInterval=this.scope.attr('data-refresh')?parseInt(this.scope.attr('data-refresh')):false;this.trigger('stats.ready');},getCounts:function(elem){return _.map(elem.find('[data-number]'),function(thisElem){return parseInt($(thisElem).attr('data-number'))});},startInterval:function(){if(!this.refreshInterval||!this.url){return;}
clearInterval(this.refresh);this.refresh=setInterval(_.bind(this.fetchUpdate,this),this.refreshInterval*1000);},fetchUpdate:function(){var self=this;ips.getAjax()(this.url,{type:'get'}).done(function(response){var newContent=$("<div>"+response+"</div>");var counts=self.getCounts(newContent);var hasDifference=false;if(counts.length!==self.currentCounts.length){hasDifference=true;}else{for(var i=0;i<counts.length;i++){if(counts[i]!==self.currentCounts[i]){hasDifference=true;break;}}}
if(hasDifference){self.scope.addClass('cStatTile--updated').find('[data-role="statBlockContent"]').html(response);self.currentCounts=counts;setTimeout(function(){self.scope.removeClass('cStatTile--updated');},2200);$(document).trigger('contentChange',[self.scope]);}else{Debug.log("No change in values in "+self.block);}});},loadBlock:function(e,data){if(!_.isUndefined(data.blockToRefresh)&&(data.blockToRefresh!=this.block||data.subblockToRefresh!=this.subblock)){Debug.log("Skipping because "+data.blockToRefresh+" does not match "+this.block+" or "+data.subblockToRefresh+" does not match "+this.subblock);return;}
var self=this;this.url=data.url+'&blockKey='+this.block;clearInterval(this.refresh);if(this.loaded){this.loaded=false;this.scope.removeClass('cStatTile--loaded').find('.cStatTile__body').addClass('ipsLoading').end().find('[data-role="statBlockContent"]').hide().html('');}
if(!_.isUndefined(this.subblock)){this.url=this.url+'&subblock='+this.subblock;}
if(data.dateFilters.range!='-1'&&data.dateFilters.range!='0'){this.url=this.url+'&range='+data.dateFilters.range;}else if(data.dateFilters.range=='-1'&&!_.isNull(data.dateFilters.start)){this.url=this.url+'&start='+data.dateFilters.start+'&end='+data.dateFilters.end;}
if(this.scope.attr('data-nodeFilter')){this.url=this.url+'&nodes='+this.scope.attr('data-nodeFilter');}
ips.getAjax()(this.url,{type:'get'}).done(function(response){self.scope.addClass('cStatTile--loaded').find('.cStatTile__body').removeClass('ipsLoading').end().find('[data-role="statBlockContent"]').hide().html(response);self.scope.find('[data-role="statBlockContent"]').fadeIn('fast');self.loaded=true;self.currentCounts=self.getCounts(self.scope);self.startInterval();$(document).trigger('contentChange',[self.scope]);});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.stats.overviewBlock',{_lastURL:null,initialize(){this.on('stats.loadBlock',this.loadBlock);$(document).on('stats.nodeFilters',(...args)=>this.loadBlock(...args));this.refresh=null;this.loaded=false;this.currentCounts=[];this.url=null;this.block=this.elem.dataset.block;this.subblock=this.elem.dataset.subblock;this.savedstatid=this.elem.dataset.savedstatid;this.refreshInterval=this.elem.dataset.refresh?parseInt(this.elem.dataset.refresh):false;this.elem.dispatchEvent(new CustomEvent('stats.ready',{bubbles:true}));this.elem.addEventListener('submit',e=>this.handleSubmit(e),{capture:true});this.elem.querySelector('[data-role="removeBlock"]')?.addEventListener('click',e=>this.deleteBlock(e));},deleteBlock(e){e?.preventDefault();ips.ui.alert.show({message:ips.getString('statsreports_delete_confirm'),type:'confirm',callbacks:{ok:()=>{const url=new URL(window.location.protocol+ips.getSetting('baseURL'),window.location.origin);url.pathname+=url.pathname.endsWith('/')?"admin/":"/admin/";url.searchParams.set('app','core');url.searchParams.set('module','overview');url.searchParams.set('controller','mycharts');url.searchParams.set('do','deleteBlock');url.searchParams.set('saved_block_id',this.savedstatid);url.searchParams.set('csrfKey',ips.getSetting('csrfKey'));window.location.href=url.toString();}}});},async handleSubmit(e){e.preventDefault();e.stopPropagation();const form=e.target;const dropdown=form.closest('i-dropdown[data-dropdown-role]');if(dropdown){dropdown.createContentElement();}
if(dropdown?.dataset.dropdownRole==='saveReport'){const data=Object.fromEntries([...(new FormData(form)).entries()]);const url=(new URL(form.action,window.location.href)).toString();dropdown.contentElement.classList.add('ipsLoading','ipsLoading--small');try{const response=await ips.fetch(url,{method:"post",data});if(typeof response!=='object'||response.message!=='ok'){const err=new Error();err.jqxhr=jqxhr;throw err;}
if(this.savedstatid&&response.title&&this.elem.querySelector(`[data-role="stat_title"]`)){this.elem.querySelector('[data-role="stat_title"]').innerText=response.title;}}catch(e){if(e.jqxhr?.responseText&&dropdown.contentElement){dropdown.contentElement.innerHTML=e.jqxhr?.responseText;return;}
if(e.jqxhr?.responseText||e.jqxhr?.responseJSON){ips.ui.alert.show({message:e.jqxhr.responseText||e.jqxhr?.responseJSON});return;}
ips.ui.alert.show({message:ips.getString('unexpected_error')});return;}}else if(dropdown?.dataset.dropdownRole==='filterForm'){this.elem.dataset.nodefilter=form.querySelector('[data-role="nodeValue"]')?.value;this.currentCounts=null;}
if(this.url){this.url=this.rebuildURL();this._lastURL=this.url;await this.fetchUpdate();}else{this.elem.dispatchEvent(new CustomEvent('stats.ready',{bubbles:true}));}
dropdown?.hidePopover();if(dropdown?.dataset.dropdownRole==='saveReport'){ips.ui.flashMsg.show(ips.getString('saved'));await dropdown.resetRemoteContent();}},getCounts(elem){return[...$(elem).get(0).querySelectorAll('[data-number]')].map(el=>parseInt(el.dataset.number));},startInterval(){if(!this.refreshInterval||!this.url){return;}
clearInterval(this.refresh);this.refresh=setInterval(()=>this.fetchUpdate(),this.refreshInterval*1000);},async fetchUpdate(){const response=await ips.fetch(this.url,{type:'get'});let identifiedDifference=!this.currentCounts;const counts=this.getCounts((new DOMParser()).parseFromString(response,'text/html').body);if(!identifiedDifference){if(counts.length!==this.currentCounts.length){identifiedDifference=true;}else{for(let i=0;i<counts.length;i++){if(counts[i]!==this.currentCounts[i]){identifiedDifference=true;break;}}}}
if(identifiedDifference){this.elem.classList.add('cStatTile--updated');let contentContainer=this.elem.querySelector('[data-role="statBlockContent"]');if(contentContainer){contentContainer.innerHTML="<div>"+response+"</div>";}
this.currentCounts=counts;setTimeout(()=>this.elem.classList.remove('cStatTile--updated'),2200);$(document).trigger('contentChange',[this.scope]);}else{Debug.log("No change in values in "+this.block);}},rebuildURL(data){if(!data){const currentURL=new URL(this.url||"",location.href);data={url:this.url,dateFilters:{range:currentURL.searchParams.get('range'),start:currentURL.searchParams.get('start'),end:currentURL.searchParams.get('end'),}}}
let url=new URL(data.url,location.href);url.updateSearchParams('blockKey',this.block);url.updateSearchParams('subblock',this.subblock||null);const range=![0,-1,Number.NaN].includes(parseInt(data?.dateFilters?.range))?data.dateFilters.range.toString():null
url.updateSearchParams('range',range);url.updateSearchParams('start',(!range&&data?.dateFilters?.start?.toString())||null);url.updateSearchParams('end',(!range&&data?.dateFilters?.end?.toString())||null);url.updateSearchParams('nodes',this.elem.dataset.nodefilter||null);return url.toString();},async loadBlock(e,data){if(!_.isUndefined(data.blockToRefresh)&&(data.blockToRefresh!==this.block||data.subblockToRefresh!==this.subblock)){Debug.log("Skipping because "+data.blockToRefresh+" does not match "+this.block+" or "+data.subblockToRefresh+" does not match "+this.subblock);return;}
if(!data.url){throw new Error(`No URL provided to load this block`);}
this._lastURL=this.url;this.url=this.rebuildURL(data);if(this.url===this._lastURL){return;}
clearInterval(this.refresh);if(this.loaded){this.loaded=false;this.scope.removeClass('cStatTile--loaded').find('.cStatTile__body').addClass('ipsLoading').end().find('[data-role="statBlockContent"]').hide().html('');}
const response=await ips.fetch(this.url,{type:'get'})
this.scope.addClass('cStatTile--loaded').find('.cStatTile__body').removeClass('ipsLoading').end().find('[data-role="statBlockContent"]').hide().html(response);this.scope.find('[data-role="statBlockContent"]').fadeIn('fast');this.loaded=true;this.currentCounts=this.getCounts(this.scope);this.startInterval();$(document).trigger('contentChange',[this.scope]);}});}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register("core.admin.stats.downloadButton",{initialize(){const update=()=>{const url=new URL(this.scope.attr('href'),window.location.origin);const locationParams=new URLSearchParams(window.location.search);url.updateSearchParams('report_id',locationParams.get('report_id')||'0');url.updateSearchParams('tab',locationParams.get('tab')||'charts');const rangeVal=document.querySelector(`[data-controller*="core.admin.stats.overview"] .cStatsFilters select[name="predate"]`)?.value||'7';if(rangeVal&&parseInt(rangeVal)===-1){url.updateSearchParams({param:'range',value:null});let startInput=document.querySelector(`[data-controller*="core.admin.stats.overview"] .cStatsFilters #dateFilterInputs input[name="date[start]"]`);let endInput=document.querySelector(`[data-controller*="core.admin.stats.overview"] .cStatsFilters #dateFilterInputs input[name="date[end]"]`);if(startInput.valueAsNumber&&endInput.valueAsNumber){url.updateSearchParams('range[start]',Math.round(startInput.valueAsNumber/1000).toString());url.updateSearchParams('range[end]',Math.round((endInput.valueAsNumber||Date.now())/1000).toString());}}else{console.log('updating range; removing start and end')
url.updateSearchParams({params:{'range[start]':null,'range[end]':null,}});url.updateSearchParams("range",rangeVal);}
this.scope.attr('href',url.toString());const menuSelectorLink=this.scope.get(0).closest('[data-controller*="core.admin.core.pageActions"]')?.querySelector('[data-role="reportSelector"]');const menuSelector=menuSelectorLink?.getAttribute('id')&&document.querySelector(`.ipsMenu#${menuSelectorLink?.getAttribute("id")}_menu`);menuSelector?.querySelectorAll('.ipsMenu_item a').forEach(link=>{const linkUrl=new URL(link.getAttribute('href'),window.location.href);linkUrl.updateSearchParams({param:'tab',value:url.searchParams.get('tab')||null});link.setAttribute('href',linkUrl.toString());});};window.addEventListener("historychange",update);document.addEventListener('input',e=>{if(e.target.matches('[data-controller*="core.admin.stats.overview"] .cStatsFilters :not([data-role="dateFilterInputs"] *)')){if(e.target.matches(`select[name="predate"]`)&&parseInt(e.target.value)===-1){Debug.log(`Not updating because the date isn't updated`);return;}
setTimeout(()=>{update();})}},{capture:true});document.addEventListener('submit',e=>{if(e.target instanceof HTMLFormElement&&e.target.matches(`[data-role="dateFilter"]`)){setTimeout(()=>update());}},{capture:true});update();}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.mixin('core.dynamicChartReportFields','core.admin.core.dynamicChart',true,function(){this.after('initialize',()=>{return
this.scope.get(0).querySelectorAll('[data-role="filterSaveMenu"].ipsHide').forEach(hiddenMenu=>{const reportSelector=hiddenMenu.querySelector(`#statsreports_report_select`);const titleToggle=reportSelector?.querySelector('input[name="statsreports_report_unlimited"]')
const reportTitle=hiddenMenu.querySelector(`#statsreports_report_new_title`);if(!reportSelector&&!reportTitle){return;}
const usingReport=!hiddenMenu.querySelector(`[name="statsreports_include_in_report"]`)?.value;let creatingNewReport=false;if(usingReport){if(!reportSelector){reportTitle.style.display="";return;}
reportSelector.style.display="";if(titleToggle?.checked){creatingNewReport=true;}}else{if(!reportSelector){reportTitle.style.display="none";return;}
reportSelector.style.display="none";}
if(reportTitle&&creatingNewReport){reportTitle.style.display="";}else if(reportTitle){reportTitle.style.display="none";}});})});}(jQuery,_));;
+2 -2
View File
@@ -1,3 +1,4 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.support.md5',{initialize:function(){this.on('click','[data-action="downloadDelta"]',this.downloadDelta);},downloadDelta:function(e){e.preventDefault();$(this.scope).find('[data-role="initialScreen"]').hide();$(this.scope).find('[data-role="downloadForm"]').show();}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.support.contact',{initialize:function(){this.on('change','#elCheckbox_support_request_extra_admin',this.acpAccountCheckboxChange);this.on(document,'refreshSupportSummary',this.embedSummary);this.embedSummary();},acpAccountCheckboxChange:function(e){if(!$('#elCheckbox_support_request_extra_admin').is(':checked')){ips.ui.alert.show({type:'confirm',message:ips.getString('supportAcpAccountHead'),subText:ips.getString('supportAcpAccountDisableBlurb'),icon:'warn',buttons:{ok:ips.getString('supportAcpAccountDisableYes'),cancel:ips.getString('supportAcpAccountDisableNo')},callbacks:{ok:function(){$('#elCheckbox_support_request_extra_admin').prop('checked',true);}}});}},embedSummary:function(){var summary=$(document).find('[data-controller="core.admin.support.dashboard"] [data-role="summary"]');if(summary.length){var html=$('<div>').append(summary.clone());html.find('.i-float_end').remove();html.find('[data-role="summary"]').addClass('i-margin-bottom_3');html.find('[data-role="summaryText"]').append(ips.templates.render('support.ticket.supportSummary'));html=html.html();this.scope.find('ul.ipsForm').prepend('<li>'+html+'</li>');}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.support.dashboard',{blocksToLoad:0,blocksLoaded:0,criticalIssuesCount:0,recommendedIssuesCount:0,results:{},_ajax:{},_timers:{},_lastValue:'',_input:null,initialize:function(){this.on('click','[data-role="checkAgain"]',this.checkAgain);this.on('click','[data-role="disableCustomizations"]',this.disableCustomizations);this.on('click','[data-role="enableCustomizations"]',this.enableCustomizations);this.on('click','[data-action="enableThirdPartyPart"]',this.enableSingleCustomizations);this.on(document,'customizationsEnabled',this.setCustomizationsButton);this._input=$('#elInput_support_advice_search');this.on('focus','#elInput_support_advice_search',this.fieldFocus);this.on('blur','#elInput_support_advice_search',this.fieldBlur);this.on('submit','#guidesForm form',this.guideFormSubmit);this.initializeBlocks();},guideFormSubmit:function(e){e.preventDefault();},fieldFocus:function(e){this._timers.focus=setInterval(_.bind(this.guideSearch,this),700);},fieldBlur:function(e){clearInterval(this._timers);},guideSearch:function(e){var searchTerm=this._input.val().trim();if(searchTerm==this._lastValue){return;}
if(searchTerm.length<3){if(!$('#featuredGuides').is(':visible')&&searchTerm.length==0){ips.utils.anim.go('fadeIn fast',$('#featuredGuides'));ips.utils.anim.go('fadeOut fast',$('#guideSearchResults'));}
@@ -11,5 +12,4 @@ else
if(html){$('#guideSearchResults > ul').html(html);}else{}},initializeBlocks:function(){var self=this;self.blocksToLoad=0;self.blocksLoaded=0;self.criticalIssuesCount=0;self.recommendedIssuesCount=0;_.each($(this.scope).find('[data-role="patchworkItem"]'),function(elem){$(elem).find('[data-role="supportBlock"]').html('').addClass('ipsLoading');$(elem).find('[data-iconType]').hide();$(elem).removeClass('elCritical');self.loadBlock($(elem).attr('data-blockid'));self.blocksToLoad++;});},checkAgain:function(){this.blocksToLoad=0;this.blocksLoaded=0;this.scope.find('[data-role="summary"]').hide();this.initializeBlocks();},disableCustomizations:function(e){e.preventDefault();$(e.target).prop('disabled',true).attr('data-oldText',$(e.target).text()).text(ips.getString('supportDisablingCustomizations'));var self=this;ips.getAjax()($(e.target).attr('href')).done(function(response){self.scope.find('[data-role="customizationsWrapper"]').html(response);self.scope.find('[data-role="disableCustomizations"]').text($(e.target).attr('data-oldText')).prop('disabled',false).hide();self.scope.find('[data-role="enableCustomizations"]').show();$(document).trigger('contentChange',[self.scope]);});},enableCustomizations:function(e){e.preventDefault();$(e.target).prop('disabled',true).attr('data-oldText',$(e.target).text()).text(ips.getString('supportEnablingCustomizations'));var self=this;ips.getAjax()($(e.target).attr('href')).done(function(response){self.scope.find('[data-role="disableCustomizations"]').show();self.scope.find('[data-role="enableCustomizations"]').prop('disabled',false).text($(e.target).attr('data-oldText')).hide();var container=self.scope.find('[data-role="disabledInformation"]');container.find('.i-color_warning').removeClass('i-color_warning').addClass('i-color_soft');container.find('.fa-exclamation-triangle').removeClass('fa-exclamation-triangle').addClass('fa-info-circle');container.find('.ipsButton--negative').removeClass('ipsButton--negative').addClass('ipsButton--inherit');container.find('[data-role="disabledMessage"]').hide();container.find('[data-role="enabledMessage"]').show();container.find('[data-action="enableThirdPartyPart"]').remove();$(document).trigger('contentChange',[self.scope]);});},enableSingleCustomizations:function(e){e.preventDefault();$(e.target).prop('disabled',true).text(ips.getString('supportEnablingCustomizations'));var self=this;ips.getAjax()($(e.target).attr('href')+'&enable=1&type='+$(e.target).attr('data-type')).done(function(response){var container=$(e.target).closest('li');container.find('.i-color_warning').removeClass('i-color_warning').addClass('i-color_soft');container.find('.fa-exclamation-triangle').removeClass('fa-exclamation-triangle').addClass('fa-info-circle');container.find('.ipsButton--negative').removeClass('ipsButton--negative').addClass('ipsButton--inherit');container.find('[data-role="disabledMessage"]').hide();container.find('[data-role="enabledMessage"]').show();if(self.scope.find('.ipsButton--negative').length<1){self.scope.find('[data-role="disableCustomizations"]').show();self.scope.find('[data-role="enableCustomizations"]').hide();$(document).trigger('customizationsEnabled');}
$(e.target).remove();$(document).trigger('contentChange',[self.scope]);});},loadBlock:function(blockid){var loadBlockUrl='?app=core&module=support&controller=support&do=getBlock&block='+blockid;var self=this;ips.getAjax()(loadBlockUrl).done(function(response){self.scope.find('[data-blockid="'+blockid+'"] [data-role="supportBlock"]').html(response.html).removeClass('ipsLoading');$(document).trigger('contentChange',[self.scope.find('[data-blockid="'+blockid+'"]')]);self.blocksLoaded++;self.criticalIssuesCount=self.criticalIssuesCount+parseInt(response.criticalIssues);self.recommendedIssuesCount=self.recommendedIssuesCount+parseInt(response.recommendedIssues);self.scope.find('[data-blockid="'+blockid+'"] [data-iconType]').hide();if(parseInt(response.criticalIssues)){ips.utils.anim.go('fadeIn slow',self.scope.find('[data-blockid="'+blockid+'"] [data-iconType="critical"]'));self.scope.find('[data-blockid="'+blockid+'"]').addClass('elCritical');}
else if(parseInt(response.recommendedIssues)){ips.utils.anim.go('fadeIn slow',self.scope.find('[data-blockid="'+blockid+'"] [data-iconType="recommended"]'));}
if(self.blocksLoaded==self.blocksToLoad){self.finishSetup();}}).fail(function(response){self.scope.find('[data-blockid="'+blockid+'"] [data-role="supportBlock"]').html(ips.getString("hookscanner_error")).removeClass("ipsLoading");self.scope.find('[data-blockid="'+blockid+'"]').addClass('elCritical');$(document).trigger('contentChange',[self.scope.find('[data-blockid="'+blockid+'"]')]);self.blocksLoaded++;});},finishSetup:function(){this.scope.find('[data-role="summaryText"]').html(ips.pluralize(ips.getString('health_check_summary'),[this.criticalIssuesCount,this.recommendedIssuesCount]));ips.utils.anim.go('fadeIn slow',this.scope.find('[data-role="summary"]'));$(document).trigger('refreshSupportSummary');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.support.md5',{initialize:function(){this.on('click','[data-action="downloadDelta"]',this.downloadDelta);},downloadDelta:function(e){e.preventDefault();$(this.scope).find('[data-role="initialScreen"]').hide();$(this.scope).find('[data-role="downloadForm"]').show();}});}(jQuery,_));;
if(self.blocksLoaded==self.blocksToLoad){self.finishSetup();}}).fail(function(response){self.scope.find('[data-blockid="'+blockid+'"] [data-role="supportBlock"]').removeClass("ipsLoading");self.scope.find('[data-blockid="'+blockid+'"]').addClass('elCritical');$(document).trigger('contentChange',[self.scope.find('[data-blockid="'+blockid+'"]')]);self.blocksLoaded++;});},finishSetup:function(){this.scope.find('[data-role="summaryText"]').html(ips.pluralize(ips.getString('health_check_summary'),[this.criticalIssuesCount,this.recommendedIssuesCount]));ips.utils.anim.go('fadeIn slow',this.scope.find('[data-role="summary"]'));$(document).trigger('refreshSupportSummary');}});}(jQuery,_));;
+2 -2
View File
@@ -1,6 +1,6 @@
ips.templates.set('club.request.approve'," <span class='cClubRequestCover_icon i-background_positive'> <i class='fa-solid fa-check'></i> </span> <br> <span class='ipsBadge ipsBadge--large ipsBadge--positive'>{{#lang}}clubRequestApproved{{/lang}}</span>");ips.templates.set('club.request.decline'," <span class='cClubRequestCover_icon i-background_negative'> <i class='fa-solid fa-xmark'></i> </span> <br> <span class='ipsBadge ipsBadge--large ipsBadge--negative'>{{#lang}}clubRequestDenied{{/lang}}</span>");ips.templates.set('club.menu.dragHandle'," <span data-role='clubMenuDrag' style='display: none'><i class='fa-solid fa-bars'></i> &nbsp;</span>");;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.clubs.navbar',{_interval:null,_sortableElem:null,initialize:function(){this.on(document,'click','[data-action="reorderClubmenu"]',this.startReorder);this.on(document,'click','[data-action="saveClubmenu"]',this.saveOrder);this.setup();},setup:function(){this._sortableElem=this.scope.find('[data-club-menu]');},startReorder:function(e){e.preventDefault();$('[data-action="saveClubmenu"]').removeClass('ipsHide');$('[data-action="reorderClubmenu"]').parent().addClass('ipsHide');var self=this;this._sortableElem.find('a').addClass('i-cursor_move').prepend(ips.templates.render('club.menu.dragHandle'));ips.loader.get(['core/interface/jquery/jquery-ui.js']).then(function(){self._sortableElem.sortable({items:'> a',forcePlaceholderSize:true,update:function(){self._orderChanged=true;}});self._reordering=true;self._orderChanged=false;self._sortableElem.find('a [data-role="clubMenuDrag"]').fadeIn();});},_finishReorder:function(){this._sortableElem.find('a').removeClass('i-cursor_move').find('[data-role="clubMenuDrag"]').remove();$('[data-action="saveClubmenu"]').addClass('ipsHide');$('[data-action="reorderClubmenu"]').parent().removeClass('ipsHide');this._sortableElem.sortable('destroy');this._reordering=false;},saveOrder:function(e){e.preventDefault();var self=this;var tabOrder=this._sortableElem.sortable('toArray',{attribute:'data-tab'});if(this._orderChanged){ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=clubs&controller=view&do=saveMenu',{data:{tabOrder:tabOrder,id:this.scope.attr('data-clubID')},dataType:'json',type:'post'}).done(function(response){ips.ui.flashMsg.show(ips.getString('tab_order_saved'));}).fail(function(){ips.ui.alert.show({type:'alert',icon:'warning',message:ips.getString('tab_order_not_saved'),callbacks:{ok:function(){}}});}).always(function(){self._finishReorder();});}else{this._finishReorder();}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.clubs.requests',{_interval:null,initialize:function(){this.on('click','[data-action="requestApprove"], [data-action="requestDecline"]',this.handleRequest);this.on(document,'menuItemSelected',this.handleRequest);this.on(window,'resize',this.resizeCovers);this.setup();},setup:function(){},resizeCovers:function(e){var self=this;var cards=this.scope.find('[data-ips-js=memberCard][data-hasCover]');if(cards.length){$.each(cards,function(){var id=$(this).identify().attr('id');var cover=$('body').find('.cClubRequestCover[data-cardId="'+id+'"]');self._positionCover($(this),cover);});}},handleRequest:function(e,data){var self=this;if(e.type=='menuItemSelected'){if(data.menuElem.attr('data-role')!='acceptMenu'){return;}
;(function($,_,undefined){"use strict";ips.controller.register('core.front.clubs.navbar',{_interval:null,_sortableElem:null,initialize:function(){this.on(document,'click','[data-action="reorderClubmenu"]',this.startReorder);this.on(document,'click','[data-action="saveClubmenu"]',this.saveOrder);this.setup();},setup:function(){this._sortableElem=this.scope.find('[data-club-menu]');},startReorder:function(e){e.preventDefault();$('[data-action="saveClubmenu"]').removeClass('ipsHide');$('[data-action="reorderClubmenu"]').parent().addClass('ipsHide');var self=this;this._sortableElem.find('a').addClass('i-cursor_move').prepend(ips.templates.render('club.menu.dragHandle'));ips.loader.get(['core/interface/jquery/jquery-ui.js']).then(function(){self._sortableElem.sortable({items:'>',forcePlaceholderSize:true,update:function(){self._orderChanged=true;}});self._reordering=true;self._orderChanged=false;self._sortableElem.find('a [data-role="clubMenuDrag"]').fadeIn();});},_finishReorder:function(){this._sortableElem.find('a').removeClass('i-cursor_move').find('[data-role="clubMenuDrag"]').remove();$('[data-action="saveClubmenu"]').addClass('ipsHide');$('[data-action="reorderClubmenu"]').parent().removeClass('ipsHide');this._sortableElem.sortable('destroy');this._reordering=false;},saveOrder:function(e){e.preventDefault();var self=this;var tabOrder=this._sortableElem.sortable('toArray',{attribute:'data-tab'});if(this._orderChanged){ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=clubs&controller=view&do=saveMenu',{data:{tabOrder:tabOrder,id:this.scope.attr('data-clubID')},dataType:'json',type:'post'}).done(function(response){ips.ui.flashMsg.show(ips.getString('tab_order_saved'));}).fail(function(){ips.ui.alert.show({type:'alert',icon:'warning',message:ips.getString('tab_order_not_saved'),callbacks:{ok:function(){}}});}).always(function(){self._finishReorder();});}else{this._finishReorder();}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.clubs.requests',{_interval:null,initialize:function(){this.on('click','[data-action="requestApprove"], [data-action="requestDecline"]',this.handleRequest);this.on(document,'menuItemSelected',this.handleRequest);this.on(window,'resize',this.resizeCovers);this.setup();},setup:function(){},resizeCovers:function(e){var self=this;var cards=this.scope.find('[data-ips-js=memberCard][data-hasCover]');if(cards.length){$.each(cards,function(){var id=$(this).identify().attr('id');var cover=$('body').find('.cClubRequestCover[data-cardId="'+id+'"]');self._positionCover($(this),cover);});}},handleRequest:function(e,data=e.detail){var self=this;if(e.type=='menuItemSelected'){if($(data.menuElem).attr('data-role')!='acceptMenu'){return;}
data.originalEvent.preventDefault();var url=$(data.originalEvent.target).attr('href');var card=$(e.target).closest('[data-ips-js=memberCard]');}else{e.preventDefault();var url=$(e.currentTarget).attr('href');var card=$(e.currentTarget).closest('[data-ips-js=memberCard]');}
var id=card.identify().attr('id');card.find('[data-action]').addClass('ipsButton--disabled');ips.getAjax()(url,{showLoading:true}).done(function(response){card.attr('data-hasCover',true);card.animate({opacity:"0.2"});var cover=$('<div/>').addClass('cClubRequestCover').attr('data-cardId',id);$('body').append(cover);self._positionCover(card,cover);cover.append(ips.templates.render(response.status=='approved'?'club.request.approve':'club.request.decline')).fadeIn();ips.ui.flashMsg.show(response.status=='approved'?ips.getString('clubMemberApproved'):ips.getString('clubMemberDeclined'),{escape:false});if(!self._interval){self._interval=window.setInterval(_.bind(self._checkCardsExist,self),200);}}).fail(function(){window.location=url;});},_checkCardsExist:function(){var self=this;var covers=$('body').find('.cClubRequestCover');var cards=this.scope.find('[data-ips-js=memberCard][data-hasCover]');if(cards.length==covers.length){return;}
if(covers.length){$.each(covers,function(){var cardId=$(this).attr('data-cardId');var card=self.scope.find('#'+cardId);if(!card.length){$(this).remove();}});}},_positionCover:function(card,cover){var elemPosition=ips.utils.position.getElemPosition(card);var dims=ips.utils.position.getElemDims(card);cover.css({position:'absolute',top:elemPosition.absPos.top+'px',left:elemPosition.absPos.left+'px',width:dims.outerWidth+'px',height:dims.outerHeight+'px'});}});}(jQuery,_));;
+19 -15
View File
@@ -1,6 +1,7 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.notifications',{initialize:function(){this.on(document,'menuOpened',this.menuOpened);this.on(document,'permissionDenied.notifications',this.hideNotice);this.on(document,'subscribePending.notifications',this.subscribePending);this.on(document,'subscribeSuccess.notifications',this.subscribeSuccess);this.on(document,'subscribeFail.notifications',this.subscribeFail);this.on('click','[data-action=browserNotificationPrompt]',this.requestPermission);this.on('click','[data-role=dismissNotification]',this.dismissNotification);this.on('click','[data-action="rejectPush"]',this.rejectPush);if(ips.getSetting('memberID')&&ips.utils.notification.supported&&ips.utils.serviceWorker.supported){this.setup();}},setup:function(){this._timeout=null;this._buttonText='';this._missingSubscription=false;if(ips.utils.notification.needsPermission()&&_.isUndefined(ips.utils.cookie.get('browserNotificationDismiss'))){this.scope.html(ips.templates.render('core.browserNotification.prompt')).hide();}else if(ips.utils.notification.hasPermission()&&_.isUndefined(ips.utils.cookie.get('notificationPushRejected'))){ips.utils.notification.getSubscription().then(subscription=>{if(subscription){return;}
this._missingSubscription=true;this.scope.html(ips.templates.render('core.browserNotification.missingSubscription')).hide();}).catch(err=>{Debug.log("getSubscription failed - browser may not support pushManager");Debug.log(err);return;});}},destroy:function(){clearTimeout(this._timeout);},menuOpened:function(e,data){let date;const showPrompt=()=>{this._timeout=setTimeout(()=>{this.scope.slideDown('fast');ips.utils.cookie.unset('notificationMenuShown');},750);};if(data.elemID==='elFullNotifications'){if(this._missingSubscription){showPrompt();}else{if(ips.utils.cookie.get('notificationMenuShown')===undefined){date=parseInt(ips.utils.cookie.get('notificationMenuShown'));if(date&&Date.now()>=date){showPrompt();}}else{date=new Date();date.setDate(date.getDate()+2);ips.utils.cookie.set('notificationMenuShown',date.getTime(),true);}}}},subscribePending:function(e,data){const button=this.scope.find('[data-action="browserNotificationPrompt"]');this._buttonText=button.text();button.prop('disabled',true).text(ips.getString('notificationsEnabling'));},subscribeSuccess:function(e,data){const button=this.scope.find('[data-action="browserNotificationPrompt"]');button.prop('disabled',true).text(ips.getString('notificationsSubscribed'));},subscribeFail:function(e,data){this.scope.find('[data-action="browserNotificationPrompt"]').prop('disabled',false).text(this._buttonText);this.scope.find('[data-role="promptMessage"]').text(ips.getString('notificationsSubscribeFailed')).slideDown();},requestPermission:function(){this.scope.find('[data-role="promptMessage"]').text(ips.getString('notificationsAllowPrompt')).slideDown();$(document).trigger('requestPermission.notifications');},rejectPush:function(e){e.preventDefault();ips.utils.cookie.set('notificationPushRejected',true,true);this.hideNotice();},hideNotice:function(){this.scope.slideUp('fast');},dismissNotification:function(e){if(e){e.preventDefault();}
this._missingSubscription=true;this.scope.html(ips.templates.render('core.browserNotification.missingSubscription')).hide();}).catch(err=>{Debug.log("getSubscription failed - browser may not support pushManager");Debug.log(err);return;});}},destroy:function(){clearTimeout(this._timeout);},menuOpened:function(e,data=e.detail){let date;const showPrompt=()=>{this._timeout=setTimeout(()=>{this.scope.slideDown('fast');ips.utils.cookie.unset('notificationMenuShown');},750);};if(data.elemID==='elFullNotifications'){if(this._missingSubscription){showPrompt();}else{if(ips.utils.cookie.get('notificationMenuShown')===undefined){date=parseInt(ips.utils.cookie.get('notificationMenuShown'));if(date&&Date.now()>=date){showPrompt();}}else{date=new Date();date.setDate(date.getDate()+2);ips.utils.cookie.set('notificationMenuShown',date.getTime(),true);}}}},subscribePending:function(e,data){const button=this.scope.find('[data-action="browserNotificationPrompt"]');this._buttonText=button.text();button.prop('disabled',true).text(ips.getString('notificationsEnabling'));},subscribeSuccess:function(e,data){const button=this.scope.find('[data-action="browserNotificationPrompt"]');button.prop('disabled',true).text(ips.getString('notificationsSubscribed'));},subscribeFail:function(e,data){this.scope.find('[data-action="browserNotificationPrompt"]').prop('disabled',false).text(this._buttonText);this.scope.find('[data-role="promptMessage"]').text(ips.getString('notificationsSubscribeFailed')).slideDown();},requestPermission:function(){this.scope.find('[data-role="promptMessage"]').text(ips.getString('notificationsAllowPrompt')).slideDown();$(document).trigger('requestPermission.notifications');},rejectPush:function(e){e.preventDefault();ips.utils.cookie.set('notificationPushRejected',true,true);this.hideNotice();},hideNotice:function(){this.scope.slideUp('fast');},dismissNotification:function(e){if(e){e.preventDefault();}
var date=new Date();date.setDate(date.getDate()+100);ips.utils.cookie.set('browserNotificationDismiss',true,date.toUTCString());this.scope.slideUp({duration:400,complete:function(){$(this).remove();}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.notificationsMenu',{initialize:function(){this.on(document,'menuOpened',this.menuOpened);},menuOpened:function(e,data){ips.utils.notification.clearBadgeCount();}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.poll',{initialize:function(){this.on('submit','form',this.submitPoll);this.on('click','[data-action="viewResults"]',this.viewResults);},viewResults:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href')+'&fetchPoll=1&viewResults=1';if($(e.currentTarget).attr('data-viewResults-confirm')){var self=this;ips.ui.alert.show({type:'confirm',icon:'warn',message:ips.getString('generic_confirm'),subText:ips.getString('warn_allow_result_view'),callbacks:{ok:function(){self._viewResults(url+'&nullVote=1');}}});}else{this._viewResults(url);}},_viewResults:function(url){var self=this;self._setContentsLoading();ips.getAjax()(url).done(function(response){self.cleanContents();self.scope.html(response);$(document).trigger('contentChange',[self.scope]);});},_setContentsLoading:function(){var container=this.scope.find('[data-role="pollContents"]');var height=container.outerHeight();container.css({height:height+'px'}).html('').addClass('ipsLoading');},submitPoll:function(e){var form=$(e.currentTarget);if(form.attr('data-bypassAjax')){return}
e.preventDefault();var url=form.attr('action');var self=this;this.scope.find('button[type="submit"]').prop('disabled',true).text(ips.getString('votingNow'));if(url.match(/\?/)){url+='&';}else{url+='?';}
ips.getAjax()(url+'fetchPoll=1',{data:form.serialize(),type:'POST'}).done(function(response){self.cleanContents();self.scope.html(response);$(document).trigger('contentChange',[self.scope]);ips.ui.flashMsg.show(ips.getString('thanksForVoting'));}).fail(function(){form.attr('data-bypassAjax',true).submit();});}});}(jQuery,_));;
@@ -17,12 +18,12 @@ this.scope.find('[data-role="pollContainer"]').append(ips.templates.render('core
this.scope.find('.ipsTags__item:not(.ipsTags__item--edit)').remove();this.scope.prepend(data.tags);var editablePrefix=$('body').find('[data-editablePrefix]');if(editablePrefix.length){if(data.prefix){editablePrefix.html(data.prefix).removeClass('ipsHide');}else{editablePrefix.html('').addClass('ipsHide');}}else if(data.prefix.length){this.scope.prepend(data.prefix);}
this._setCount();this._checkMinMax();if(data.tagsChanged==1){ips.ui.flashMsg.show(ips.getString('tagsUpdated'));}},removeTag:function(e){e.preventDefault();var self=this;var remove=$(e.currentTarget);var url=remove.attr('href');var tagContainer=remove.closest('.ipsTags__item');var tag=tagContainer.find('.ipsTags__tag');tagContainer.fadeOut('fast');this._count--;this._checkMinMax();ips.getAjax()(url,{bypassRedirect:true}).done(function(){ips.ui.flashMsg.show(ips.getString('tagRemoved'));setTimeout(function(){tagContainer.remove();},200);}).fail(function(jqXHR,textStatus,errorThrown){tagContainer.stop().show().css({opacity:"1"});self._count++;if(jqXHR.responseJSON){ips.ui.alert.show({type:'alert',icon:'warn',message:jqXHR.responseJSON,callbacks:{}});}});},_checkMinMax:function(){var allowRemove=!(this._minTags&&this._count<=this._minTags);this.scope.find('[data-action="removeTag"]').toggle(allowRemove).end().find('.ipsTags__item--deletable').toggleClass('ipsTags__item--deletable',allowRemove);this.scope.find('.ipsTags__item--edit').toggle(!(this._maxTags&&this._count>=this._maxTags));},_setCount:function(){var prefix=this._getPrefix();var count=this.scope.find('.ipsTags__item').length;if(prefix.length&&prefix.is(':visible')){count++;}
this._count=count;},_getPrefix:function(){return $('body').find('[data-editablePrefix]');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.tagEditorForm',{_placeholder:null,_menuID:'',_tagEditID:'',initialize:function(){this.on(document,'menuOpened',this.menuOpened);this.on(document,'menuClosed',this.menuClosed);this.on('submit','form',this.submitForm);this.setup();},setup:function(){this._menuID=this.scope.closest('.ipsMenu').attr('id').replace('_menu','');this._tagEditID=this._menuID.replace('elTagEditor_','');},menuClosed:function(e,data){if(data.elemID!==this._menuID){return;}
ips.cleanContentsOf(this.elem);this.scope.html(ips.templates.render('core.edittags.default'));this._buildPlaceholder();},menuOpened:function(e,data){if(data.elemID!=this._menuID){return;}
var self=this;var url=$(data.originalEvent.currentTarget).attr('href');ips.getAjax()(url).done(function(response){self._setLoading(false);self.scope.html(response);$(document).trigger('contentChange',[self.scope]);}).fail(function(){window.location=url;});},submitForm:function(e){e.preventDefault();var self=this;var form=$(e.currentTarget);var autoComplete=this.scope.find('[data-ipsAutocomplete]');autoComplete.trigger('blur');setTimeout(function(){if(ips.ui.autocomplete.getObj(autoComplete).hasErrors()){e.preventDefault();return;}
self._setLoading(true);ips.getAjax()(form.attr('action'),{type:'post',data:form.serialize(),dataType:'json'}).done(function(response){self.scope.trigger('tagsUpdated',{tagEditID:self._tagEditID,tags:response.tags,prefix:response.prefix,tagsChanged:response.tagsChanged});self.scope.trigger('closeMenu');}).fail(function(jqXHR,textStatus,errorThrown){if(jqXHR.responseJSON){ips.ui.alert.show({type:'alert',icon:'warn',message:jqXHR.responseJSON,callbacks:{}});}});},500);},_setLoading:function(loading){if(loading){if(!this._placeholder){this._buildPlaceholder();}
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.tagEditorForm',{_placeholder:null,_menuID:'',_tagEditID:'',initialize:function(){this.on(document,'menuOpened',this.menuOpened);this.on(document,'menuClosed',this.menuClosed);this.on('submit','form',this.submitForm);this.setup();},setup:function(){this._menuID=this.scope.closest('i-dropdown').attr('id').replace('_menu','');this._tagEditID=this._menuID.replace('elTagEditor_','');},menuClosed:function(e,data=e.detail){if(data.elemID!==this._menuID){return;}
ips.cleanContentsOf(this.elem);this.scope.html(ips.templates.render('core.edittags.default'));this._buildPlaceholder();},menuOpened:function(e,data=e.detail){if(data.elemID!=this._menuID){return;}
var self=this;var url=$(e.target).attr('data-href');ips.getAjax()(url).done(function(response){self._setLoading(false);self.scope.html(response);$(document).trigger('contentChange',[self.scope]);}).fail(function(){window.location=url;});},submitForm:function(e){e.preventDefault();var self=this;var form=$(e.currentTarget);var autoComplete=this.scope.find('[data-ipsAutocomplete]');autoComplete.trigger('blur');setTimeout(function(){if(ips.ui.autocomplete.getObj(autoComplete).hasErrors()){e.preventDefault();return;}
self._setLoading(true);ips.getAjax()(form.attr('action'),{type:'post',data:form.serialize(),dataType:'json'}).done(function(response){self.scope.trigger('tagsUpdated',{tagEditID:self._tagEditID,tags:response.tags,prefix:response.prefix,tagsChanged:response.tagsChanged});self.scope[0].closest("[popover]")?.hidePopover();}).fail(function(jqXHR,textStatus,errorThrown){if(jqXHR.responseJSON){ips.ui.alert.show({type:'alert',icon:'warn',message:jqXHR.responseJSON,callbacks:{}});}});},500);},_setLoading:function(loading){if(loading){if(!this._placeholder){this._buildPlaceholder();}
var width=this.scope.outerWidth();var height=this.scope.outerHeight();this.scope.hide();this._placeholder.show().css({width:width+'px',height:height+'px'});}else{if(this._placeholder){this._placeholder.hide();this.scope.show();}}},_buildPlaceholder:function(){this._placeholder?.remove?.();this._placeholder=$('<div/>').addClass('ipsLoading').hide();this.scope.after(this._placeholder);}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.announcementBanner',{initialize:function(){this.setup();this.on('click','[data-role="dismissAnnouncement"]',this.dismissAnnouncement);},setup:function(){this.scope.find('[data-announcementId]').each(function(){var announcement=$(this);if(ips.utils.cookie.get('announcement_'+announcement.attr('data-announcementId'))){announcement.hide();}});},dismissAnnouncement:function(e){var element=$(e.target).closest('[data-announcementId]');var id=element.attr('data-announcementId');var date=new Date();date.setTime(date.getTime()+(7*86400000));ips.utils.cookie.set('announcement_'+id,true,date.toUTCString());element.slideUp({duration:400,complete:function(){$(this).remove();}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.announcementBanner',{initialize:function(){this.setup();this.on('click','[data-role="dismissAnnouncement"]',this.dismissAnnouncement);},setup:function(){this.scope.find('[data-announcementId]').each(function(){var announcement=$(this);if(ips.utils.cookie.get('announcement_'+announcement.attr('data-announcementId'))){announcement.attr('hidden',true);}});},dismissAnnouncement:function(e){var element=$(e.target).closest('[data-announcementId]');var id=element.attr('data-announcementId');var date=new Date();date.setTime(date.getTime()+(7*86400000));ips.utils.cookie.set('announcement_'+id,true,date.toUTCString());element.slideUp({duration:400,complete:function(){$(this).remove();}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.articlePages',{_currentPage:1,_pages:null,_articleID:'',initialize(){this.on('paginationClicked',this.paginationClicked);this.setup();},setup(){this._articleID=this._getArticleID();this.on(window,`historychange:article-${this._articleID}`,this.stateChange);this._setupPages();},stateChange(){if(!(('article-'+this._articleID)in ips.utils.history.getState())){return;}
const state=ips.utils.history.getState(`article-${this._articleID}`)
const newPage=parseInt(state?.['page'+this._articleID]);if(!Number.isInteger(newPage)||this._pages[newPage-1]===undefined){return;}
@@ -38,12 +39,12 @@ else if(this.scope.attr('data-role')=='guestTermsBar'&&ips.utils.cookie.get('gue
if(this.scope.attr('data-role')=='cookieConsentBar'&&(!ips.getSetting('memberID')&&!ips.utils.cookie.get('cookie_consent_optional'))){$('#elNavTheme').hide();}
if(this.scope.attr('data-role')=='cookieConsentBar'&&!ips.utils.cookie.get('cookie_consent_optional')){$('[data-role="dismissAnnouncement"]').hide();}
this.scope.toggle(!hide);$('body').toggleClass('cWithGuestTerms',!hide);},dismissTerms:function(e){e.preventDefault();ips.utils.cookie.set('guestTermsDismissed',1);this.hideGuestBar();},hideGuestBar:function(){this.scope.toggle(false);$('body').toggleClass('cWithGuestTerms',false);}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.followForm',{initialize:function(){this.on('submit',this.submitForm);this.on('click','[data-action="unfollow"]',this.unfollow);this.setup();},setup:function(){this._app=this.scope.attr('data-followApp');this._area=this.scope.attr('data-followArea');this._id=this.scope.attr('data-followID');},unfollow:function(e){e.preventDefault();this._doFollowAction($(e.currentTarget).attr('href'),{},true);},submitForm:function(e){e.preventDefault();this._doFollowAction(this.scope.attr('action'),this.scope.serialize(),false);},_doFollowAction:function(url,data,unfollow){var self=this;var dims=ips.utils.position.getElemDims(this.scope.parent('div'));this.scope.hide().parent('div').css({width:dims.outerWidth+'px',height:dims.outerHeight+'px'}).addClass('ipsLoading');ips.getAjax()(url,{data:data,type:'post'}).done(function(response){if(unfollow){self.trigger('followingItem',{feedID:self._area+'-'+self._id,unfollow:true});}else{self.trigger('followingItem',{feedID:self._area+'-'+self._id,notificationType:self.scope.find('[name="follow_type"]:checked').val(),anonymous:!self.scope.find('[name="follow_public_checkbox"]').is(':checked')});}
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.followForm',{initialize:function(){this.on('submit',this.submitForm);this.on('click','[data-action="unfollow"]',this.unfollow);this.on('click','[data-action="followSettings"]',this.notificationSettings);this.setup();},setup:function(){this._app=this.scope.attr('data-followApp');this._area=this.scope.attr('data-followArea');this._id=this.scope.attr('data-followID');},notificationSettings:function(e){$(this.scope.parents('.ipsHovercard')[0]).hide();},unfollow:function(e){e.preventDefault();this._doFollowAction($(e.currentTarget).attr('href'),{},true);},submitForm:function(e){e.preventDefault();this._doFollowAction(this.scope.attr('action'),this.scope.serialize(),false);},_doFollowAction:function(url,data,unfollow){var self=this;var dims=ips.utils.position.getElemDims(this.scope.parent('div'));this.scope.hide().parent('div').css({width:dims.outerWidth+'px',height:dims.outerHeight+'px'}).addClass('ipsLoading');ips.getAjax()(url,{data:data,type:'post'}).done(function(response){if(unfollow){self.trigger('followingItem',{feedID:self._area+'-'+self._id,unfollow:true});}else{self.trigger('followingItem',{feedID:self._area+'-'+self._id,notificationType:self.scope.find('[name="follow_type"]:checked').val(),anonymous:!self.scope.find('[name="follow_public_checkbox"]').is(':checked')});}
ips.ui.flashMsg.show(ips.getString('followUpdated'));}).fail(function(jqXHR,textStatus,errorThrown){window.location=url;}).always(function(){self.scope.parents('.ipsHovercard').remove();});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.followButton',{initialize:function(){this.setup();this.on(document,'followingItem',this.followingItemChange);},setup:function(){this._app=this.scope.attr('data-followApp');this._area=this.scope.attr('data-followArea');this._id=this.scope.attr('data-followID');this._feedID=this._area+'-'+this._id;this._button=this.scope.find('[data-role="followButton"]');},followingItemChange:function(e,data){if(data.feedID===this._feedID){this._reloadButton();}},_reloadButton:function(){this._button.addClass('i-opacity_3');var self=this;var pos=ips.utils.position.getElemPosition(this._button);var dims=ips.utils.position.getElemDims(this._button);this.scope.append(ips.templates.render('core.follow.loading'));this.scope.find('.ipsLoading').css({width:dims.outerWidth+'px',height:dims.outerHeight+'px',top:"0",left:"0",position:'absolute',zIndex:ips.ui.zIndex()});ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=notifications&do=button',{data:_.extend({follow_app:this._app,follow_area:this._area,follow_id:this._id,},(this.scope.attr('data-buttonType'))?{button_type:this.scope.attr('data-buttonType')}:{},(this.scope.attr('data-buttonSize'))?{button_size:this.scope.attr('data-buttonSize')}:{})}).done(function(response){self.scope.html(response);$(document).trigger('contentChange',[self.scope]);if($('input[data-toggle-id="auto_follow_toggle"]').length){var val=self.scope.find('[data-role="followButton"]').attr('data-following');if(val=='false'&&$('input[data-toggle-id="auto_follow_toggle"]').is(':checked')){$('input[data-toggle-id="auto_follow_toggle"]').prop('checked',false).change();}else if(val=='true'&&!$('input[data-toggle-id="auto_follow_toggle"]').is(':checked')){$('input[data-toggle-id="auto_follow_toggle"]').prop('checked',true).change();}}}).fail(function(){self._button.removeClass('i-opacity_3');}).always(function(){self.scope.find('.ipsLoading').remove();});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.followButton',{initialize:function(){this.setup();this.on(document,'followingItem',this.followingItemChange);},setup:function(){this._app=this.scope.attr('data-followApp');this._area=this.scope.attr('data-followArea');this._id=this.scope.attr('data-followID');this._feedID=this._area+'-'+this._id;this._button=this.scope.find('[data-role="followButton"]');},followingItemChange:function(e,data){if(data.feedID===this._feedID){document.body.dispatchEvent(new CustomEvent('ipsDataLayerSync',{bubbles:true}));this._reloadButton();}},_reloadButton:function(){this._button.addClass('i-opacity_3');var self=this;var pos=ips.utils.position.getElemPosition(this._button);var dims=ips.utils.position.getElemDims(this._button);this.scope.append(ips.templates.render('core.follow.loading'));this.scope.find('.ipsLoading').css({width:dims.outerWidth+'px',height:dims.outerHeight+'px',top:"0",left:"0",position:'absolute',zIndex:ips.ui.zIndex()});ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=notifications&do=button',{data:_.extend({follow_app:this._app,follow_area:this._area,follow_id:this._id,},(this.scope.attr('data-buttonType'))?{button_type:this.scope.attr('data-buttonType')}:{},(this.scope.attr('data-buttonSize'))?{button_size:this.scope.attr('data-buttonSize')}:{})}).done(function(response){self.scope.html(response);$(document).trigger('contentChange',[self.scope]);if($('input[data-toggle-id="auto_follow_toggle"]').length){var val=self.scope.find('[data-role="followButton"]').attr('data-following');if(val=='false'&&$('input[data-toggle-id="auto_follow_toggle"]').is(':checked')){$('input[data-toggle-id="auto_follow_toggle"]').prop('checked',false).change();}else if(val=='true'&&!$('input[data-toggle-id="auto_follow_toggle"]').is(':checked')){$('input[data-toggle-id="auto_follow_toggle"]').prop('checked',true).change();}}}).fail(function(){self._button.removeClass('i-opacity_3');}).always(function(){self.scope.find('.ipsLoading').remove();});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.dataLayer',{eventHandlers:[],propertiesHandlers:[],initialize:function(){if(this.verify()){this.on('ipsDataLayer',this.handleEvent);this.on('ipsDataLayerProperties',this.handleProperties);this.setup();Debug.log('Pushing events to the dataLayer');}},setup:function(){for(let i in IpsDataLayerEventHandlers){let handler=IpsDataLayerEventHandlers[i];if(handler instanceof Function){try{let callback=handler();if(callback instanceof Function){this.eventHandlers.push(callback);}else{Debug.error(`Invalid Handler Callback Found: Returned value of type '${typeof (callback || undefined)}', expected a callback Function!`);}}catch(e){Debug.error(e);}}}
for(let i in IpsDataLayerPropertiesHandlers){let handler=IpsDataLayerPropertiesHandlers[i];if(handler instanceof Function){try{let callback=handler();if(callback instanceof Function){this.propertiesHandlers.push(callback);}else{Debug.error(`Invalid Handler Callback Found: Returned value of type '${typeof (callback || undefined)}', expected a callback Function!`);}}catch(e){Debug.error(e);}}}
this.unsetOldUniqueKeys();setTimeout(_.bind(this.loginLogout,this),200);setTimeout(_.bind(this.handleInitialEvents,this),202);this.on('ipsDataLayerSync',this.remoteFetchEvents);this.scope.find('[data-datalayer-postfetch]').on('click',function(e){setTimeout(function(){$(e.currentTarget).trigger('ipsDataLayerSync');},1500);});},handleEvent:function(evt,event){let Events=IpsDataLayerConfig._events;let Properties=IpsDataLayerConfig._properties;let PII=IpsDataLayerConfig._pii;if(!Object.keys(Events).length||!this.eventHandlers.length){return;}
this.unsetOldUniqueKeys();setTimeout(_.bind(this.loginLogout,this),200);setTimeout(_.bind(this.handleInitialEvents,this),202);this.on('ipsDataLayerSync',_.debounce(this.remoteFetchEvents,1000));this.scope.find('[data-datalayer-postfetch]').on('click',function(e){setTimeout(function(){$(e.currentTarget).trigger('ipsDataLayerSync');},1500);});},handleEvent:function(evt,event){let Events=IpsDataLayerConfig._events;let Properties=IpsDataLayerConfig._properties;let PII=IpsDataLayerConfig._pii;if(!Object.keys(Events).length||!this.eventHandlers.length){return;}
try{if(event._key&&event._properties instanceof Object){if(!Events[event._key]||!Events[event._key].enabled)return;if(event._uniquekeys&&event._uniquekeys instanceof Object){try{let same=true;let saved=ips.utils.db.get('ipsDataLayer',event._key)||{};saved.exp=saved.exp||0;event._uniquekeys.exp=event._uniquekeys.exp||(Math.floor(Date.now()/1000)+300);if((saved.exp)<=Math.floor(Date.now()/1000)){same=false;}
if(same){for(let savedKey in saved){if(savedKey==='exp'){continue;}
if(saved[savedKey]!==event._uniquekeys[savedKey]){same=false;break;}}}
@@ -51,14 +52,16 @@ if(same){saved.exp=Math.max(event._uniquekeys.exp,saved.exp);ips.utils.db.set('i
ips.utils.db.set('ipsDataLayer',event._key,event._uniquekeys,false);}catch(e){Debug.error(e);}}
let _event={'_key':Events[event._key].formatted_name,'_properties':{}};for(let propertyKey in Properties){let property=Properties[propertyKey];if(property.enabled&&!(!PII&&property.pii)){let validForEvent=false;for(let j in property.event_keys){let pattern=property.event_keys[j].replaceAll('*','.*');if(event._key.match(pattern)){validForEvent=true;break;}}
if(!validForEvent){continue;}
let formatted=property.formatted_name;let value='';if(propertyKey==='ips_key'){value=this.uniqueId();}else if(Object.keys(event._properties).includes(propertyKey)){value=event._properties[propertyKey];}else if(property.custom){value=(property.value===null||property.value===undefined)?undefined:property.value;}else if(propertyKey==='ips_time'){value=Math.floor(Date.now()/1000);}else if(IpsDataLayerContext[formatted]){value=IpsDataLayerContext[formatted];}else{value=property.default||undefined;}
if(value!==null&&value!==undefined){let types=property.type.toLowerCase().split(' ');if(types.includes('number')){try{if(!isNaN(value)){value=Number(value);}}catch(e){}}
if(typeof value==='object'&&Object.keys(value).length===0&&Object.getPrototypeOf(value)===Object.prototype&&types.includes('array')){value=[];}else if(!((types.includes('array')&&value instanceof Array)||types.includes(typeof value))){Debug.error(`Invalid Data Layer Property Type: Event property "${propertyKey}" was overridden to undefined because it could not be cast from "${typeof value}" to an allowed type`);value=undefined;}}else{value=undefined;}
let formatted=property.formatted_name;let value='';if(propertyKey==='ips_key'){value=this.uniqueId();}else if(propertyKey in event._properties){value=event._properties[propertyKey];}else if(property.custom){value=(property.value===null||property.value===undefined)?undefined:property.value;}else if(propertyKey==='ips_time'){value=Math.floor(Date.now()/1000);}else if(IpsDataLayerContext[formatted]){value=IpsDataLayerContext[formatted];}else{value=property.default;}
if(value!==null&&value!==undefined){let types=property.type.toLowerCase().split(' ');if(!types.includes('array')&&types.some(type=>type.endsWith('[]'))){types.push('array');}
if(types.includes('number')){try{if(!isNaN(value)){value=Number(value);}}catch(e){}}
if(typeof value==='object'&&Object.keys(value).length===0&&Object.getPrototypeOf(value)===Object.prototype&&types.includes('array')){value=[];}else if(!((types.includes('array')&&value instanceof Array)||types.includes(typeof value))){Debug.error(`Invalid Data Layer Property Type: Event property "${propertyKey}" was overridden to undefined because it could not be cast from "${typeof value}" to an allowed type`);value=property.default!==null?property.default:undefined;}}else{value=property.default!==null?property.default:undefined;}
_event._properties[formatted]=value;}}
Debug.log('Pushing an event to the Data Layer Event Handlers');Debug.log(_event)
for(let i in this.eventHandlers){try{this.eventHandlers[i](_event);}catch(e){Debug.error('Bad Data Layer Event Handler: An event handler failed to handle an event!');}}}}catch(e){Debug.log(e);}},handleProperties:function(evt,event){let Properties=IpsDataLayerConfig._properties;let PII=IpsDataLayerConfig._pii;if(this.propertiesHandlers.length&&event._properties instanceof Object){let properties={};for(let propertyKey in event._properties){let property=Properties[propertyKey];if(!(property||property===null)||!property.enabled||!property.page_level||(!PII&&property.pii)){continue;}
let value=event._properties[propertyKey];if(value!==null&&value!==undefined){let types=property.type.toLowerCase().split(' ');if(types.includes('number')){try{if(!isNaN(value)){value=Number(value);}}catch(e){}}
if(typeof value==='object'&&Object.keys(value).length===0&&Object.getPrototypeOf(value)===Object.prototype&&types.includes('array')){value=[];}else if(!((types.includes('array')&&value instanceof Array)||types.includes(typeof value))){Debug.error(`Invalid Data Layer Property Type: Property "${propertyKey}" was overridden to undefined because it could not be cast from "${typeof value}" to an allowed type`);value=undefined;}}else{value=undefined;}
let value=event._properties[propertyKey];if(value!==null&&value!==undefined){let types=property.type.toLowerCase().split(' ');if(!types.includes('array')&&types.some(type=>type.endsWith('[]'))){types.push('array');}
if(types.includes('number')){try{if(!isNaN(value)){value=Number(value);}}catch(e){}}
if(typeof value==='object'&&Object.keys(value).length===0&&Object.getPrototypeOf(value)===Object.prototype&&types.includes('array')){value=[];}else if(!((types.includes('array')&&value instanceof Array)||types.includes(typeof value))){Debug.error(`Invalid Data Layer Property Type: Property "${propertyKey}" was overridden to undefined because it could not be cast from "${typeof value}" to an allowed type`);value=property.default!==null?property.default:undefined;}}else{value=property.default!==null?property.default:undefined;}
properties[propertyKey]=value;}
if(Object.keys(properties).length){Debug.log('Pushing properties to the Data Layer Properties Handlers');Debug.log(properties);for(let i in this.propertiesHandlers){try{this.propertiesHandlers[i](properties);}catch(e){Debug.error('Bad Data Layer Properties Handler: A properties handler failed to handle a collection (object) of properties');}}}}},handleInitialEvents:function(){let self=this;IpsDataLayerEvents.forEach(function(event){self.handleEvent({},event);});},verify:function(){try{return((!window.IpsDataLayerContext&&IpsDataLayerContext)&&(!window.IpsDataLayerConfig&&IpsDataLayerConfig)&&(!window.IpsDataLayerEventHandlers&&IpsDataLayerEventHandlers)&&(!window.IpsDataLayerPropertiesHandlers&&IpsDataLayerPropertiesHandlers)&&IpsDataLayerContext instanceof Object&&IpsDataLayerEvents instanceof Array&&IpsDataLayerEventHandlers instanceof Array&&IpsDataLayerPropertiesHandlers instanceof Array&&IpsDataLayerConfig instanceof Object&&IpsDataLayerConfig._properties instanceof Object&&IpsDataLayerConfig._events instanceof Object&&IpsDataLayerConfig._pii!==undefined);}catch(e){return false;}},loginLogout:function(){let stored=ips.utils.db.get('ipsDataLayer','login')||{};if(ipsSettings.memberID){if(stored.logged_in===0){this.scope.trigger('ipsDataLayer',{_key:'account_login',_properties:{}});}
ips.utils.db.set('ipsDataLayer','login',{logged_in:1},false)}else{if(stored.logged_in===1){this.scope.trigger('ipsDataLayer',{_key:'account_logout',_properties:{}});}
@@ -70,4 +73,5 @@ inputNode.on('blur',function(){inputNode.addClass('ipsField_loading');const oldT
else
{params={...params,...{"newTitle":newTitle}};ips.getAjax()(anchor.attr('href'),{method:'post',data:params}).done(function(response){anchor.text(response);}).fail(function(response){ips.ui.alert.show({type:'alert',icon:'warn',message:response.responseJSON,});}).always(function(){inputNode.remove();anchor.show();self._editingTitle=false;});}});inputNode.on('keypress',function(e){if(e.keyCode==ips.ui.key.ENTER){e.stopPropagation();e.preventDefault();inputNode.blur();return false;}});inputNode.on('keydown',function(e){if(e.keyCode==ips.ui.key.ESCAPE){inputNode.remove();anchor.show();self._editingTitle=false;return false;}});},1000);},editTitleMouseup:function(e){clearTimeout(this._editTimeout);},editTitleMouseclick:function(e){if(this._editingTitle){e.preventDefault();}},moderationSubmit:function(e){if(this._editingTitle){e.preventDefault();}
var action=this.scope.find('[data-role="moderationAction"]').val();switch(action){case'delete':this._modActionDelete(e);break;case'move':this._modActionDialog(e,'move','narrow');break;case'hide':this._modActionDialog(e,'hide','narrow');break;case'split':this._modActionDialog(e,'split','wide');break;case'merge':this._modActionDialog(e,'merge','medium');break;case'tag':this._modActionDialog(e,'tag','narrow');break;case'untag':this._modActionDialog(e,'untag','narrow');break;default:$(document).trigger('moderationSubmitted');break;}},_modActionDelete:function(e){var self=this;var form=this.scope.find('[data-role="moderationTools"]');if(self._bypassDeleteCheck){return;}
e.preventDefault();var count=parseInt(this.scope.find('[data-role="moderation"]:checked').length)+parseInt(this.scope.find('[data-role="moderation"]:hidden').length);ips.ui.alert.show({type:'confirm',icon:'warn',message:(count>1)?ips.pluralize(ips.getString('delete_confirm_many'),count):ips.getString('delete_confirm'),callbacks:{ok:function(){$(document).trigger('moderationSubmitted');self._bypassDeleteCheck=true;self.scope.find('[data-role="moderationTools"]').submit();}}});},_modActionDialog:function(e,title,size){e.preventDefault();var form=this.scope.find('[data-role="moderationTools"]');var moveDialog=ips.ui.dialog.create({url:form.attr('action')+'&'+form.serialize().replace(/%5B/g,'[').replace(/%5D/g,']'),modal:true,title:ips.getString(title),forceReload:true,size:size});moveDialog.show();$(document).trigger('moderationSubmitted');}});}(jQuery,_));;
e.preventDefault();let count=parseInt(this.elem.querySelector('[data-role="moderationTools"][data-ipspageaction][data-ipspageaction-selected-count]')?.dataset.ipspageactionSelectedCount);if(Number.isNaN(count)){count=(parseInt(this.scope.find('[data-role="moderation"]:checked').length)+parseInt(this.scope.find('[data-role="moderation"]:hidden').length));}
ips.ui.alert.show({type:'confirm',icon:'warn',message:(count>1)?ips.pluralize(ips.getString('delete_confirm_many'),count):ips.getString('delete_confirm'),callbacks:{ok:function(){$(document).trigger('moderationSubmitted');self._bypassDeleteCheck=true;self.scope.find('[data-role="moderationTools"]').submit();}}});},_modActionDialog:function(e,title,size){e.preventDefault();var form=this.scope.find('[data-role="moderationTools"]');var moveDialog=ips.ui.dialog.create({url:form.attr('action')+'&'+form.serialize().replace(/%5B/g,'[').replace(/%5D/g,']'),modal:true,title:ips.getString(title),forceReload:true,size:size});moveDialog.show();$(document).trigger('moderationSubmitted');}});}(jQuery,_));;
+1 -1
View File
@@ -1,4 +1,4 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.front.ignore.new',{initialize:function(){this.on('submit','#elIgnoreForm',this.addIgnoredUser);this.on('tokenAdded',this.showExtraControls);this.setup();},setup:function(){if(parseInt(this.scope.attr('data-id'))===0){$('#elIgnoreTypes, #elIgnoreSubmitRow').hide();}},addIgnoredUser:function(e){var form=this.scope.find('#elIgnoreForm');if(form.attr('data-bypassValidation')){return;}
e.preventDefault();var self=this;var scope=this.scope;ips.getAjax()(form.attr('action'),{data:form.serialize(),type:'post'}).done(function(response,textStatus,jqXHR){if(jqXHR.responseJSON){ips.utils.anim.go('fadeOut',$('#elIgnoreTypes, #elIgnoreSubmitRow')).then(function(){var field=scope.find('[name="member"]');ips.ui.autocomplete.getObj(field).removeAll();form.find("[type='checkbox']").attr('checked','').change();});ips.ui.flashMsg.show(ips.getString('addedIgnore',{user:response.name}));self.triggerOn('core.global.core.table','refreshResults');}else{form.attr('data-bypassValidation',true).submit();}}).fail(function(jqXHR,textStatus,errorThrown){form.attr('data-bypassValidation',true).submit();});},showExtraControls:function(e,data){var field=this.scope.find('[name="member"]');var wrapper=$('#'+field.attr('id')+'_wrapper');wrapper.addClass('ipsField_loading');var form=this.scope.find('#elIgnoreForm');ips.getAjax()(form.attr('action'),{type:'post',data:{do:'add',name:this.scope.find('[name="member"]').val()}}).done(function(response){var i;for(i in response){form.find("[name='ignore_"+i+"_checkbox']").attr('checked',response[i]==1).change();}
ips.utils.anim.go('fadeIn',$('#elIgnoreTypes, #elIgnoreSubmitRow'));}).fail(function(jqXHR,textStatus,errorThrown){ips.ui.alert.show({message:jqXHR.responseJSON['error']});field.data('_autocomplete').removeAll();}).always(function(){wrapper.removeClass('ipsField_loading');});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.ignore.existing',{initialize:function(){this.on('menuItemSelected','[data-action="ignoreMenu"]',this.ignoreMenu);this.on('submitDialog',this.editedUser);},editedUser:function(e,data){this.trigger('refreshResults');ips.ui.flashMsg.show(ips.getString('editedIgnore'));},ignoreMenu:function(e,data){data.originalEvent.preventDefault();switch(data.selectedItemID){case'remove':this._removeIgnore(e,data);break;}},_removeIgnore:function(e,data){var url=data.menuElem.find('[data-ipsMenuValue="remove"] a').attr('href');var self=this;Debug.log('here');ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('confirm_unignore'),subText:ips.getString('confirm_unignore_desc'),callbacks:{ok:function(){ips.getAjax()(url+'&wasConfirmed=1').done(function(response){self.trigger('refreshResults');});}}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.ignore.existing',{initialize:function(){this.on('menuItemSelected','[data-action="ignoreMenu"]',this.ignoreMenu);this.on('submitDialog',this.editedUser);},editedUser:function(e,data){this.trigger('refreshResults');ips.ui.flashMsg.show(ips.getString('editedIgnore'));},ignoreMenu:function(e,data=e.detail){data.originalEvent.preventDefault();switch(data.selectedItemID){case'remove':this._removeIgnore(e,data);break;}},_removeIgnore:function(e,data){var url=$(data.menuElem).find('[data-ipsMenuValue="remove"] a').attr('href');var self=this;Debug.log('here');ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('confirm_unignore'),subText:ips.getString('confirm_unignore_desc'),callbacks:{ok:function(){ips.getAjax()(url+'&wasConfirmed=1').done(function(response){self.trigger('refreshResults');});}}});}});}(jQuery,_));;
+16 -16
View File
@@ -1,13 +1,14 @@
ips.templates.set('messages.view.placeholder'," <div class='ipsEmpty'> <i class='fa-solid fa-inbox i-opacity_2'></i> <p class='i-margin-top_1'>{{#lang}}no_message_selected{{/lang}}</p></div>");ips.templates.set('messages.main.folderMenu',"<li class='ipsMenu_item' data-ipsMenuValue='{{key}}'><a href='#'><span data-role='folderName'>{{name}}</span> <span class='ipsMenu_itemCount'>{{count}}</span></a></li>");;
;(function($,_){"use strict";ips.controller.register('core.front.messages.view',{_currentMessageID:null,_currentPage:1,initialize(){this.on('paginationClicked paginationJump',this.paginationClicked);this.on('addToCommentFeed',this.addToCommentFeed);this.on('deletedComment.comment',this.deleteComment);this.on(document,'menuItemSelected','#elConvoMove',this.moveConversation);this.on(document,'click','[data-action="deleteConversation"]',this.deleteConversation);this.on('menuOpened',"[data-action='inviteUsers']",this.inviteMenuOpened);this.on(document,'menuItemSelected','[data-role="userActions"]',this.userAction);this.on('submit','[data-role="addUser"]',this.addUsersSubmit);this.on(document,'selectedMessage.messages',this.selectedMessage);this.on(document,'setInitialMessage.messages',this.setInitialMessage);this.on(document,'getFolder.messages',this.getFolder);this.on(document,'loadMessageLoading.messages',this.loadMessageLoading);this.on(document,'loadMessageDone.messages',this.loadMessageDone);this.on(document,'deleteMessageDone.messages',this.deleteMessageDone);this.on(document,'blockUserDone.messages',this.blockUserDone);this.on(document,'addUserDone.messages',this.addUserDone);this.on(document,'addUserError.messages',this.addUserError);this.on(window,'historychange:messages',this.stateChange);this.setup();},setup(){if(this.scope.attr('data-current-id')){this._currentMessageID=this.scope.attr('data-current-id');}},addToCommentFeed(e,data){if(data.totalItems){this.trigger('updateReplyCount.messages',{messageID:this._currentMessageID,count:data.totalItems});}},addUserError(e,data){if(data.error){ips.ui.alert.show({type:'alert',icon:'warn',message:data.error,callbacks:{}});}},addUserDone(e,data){if(data.id!==this._currentMessageID){return;}
ips.templates.set('messages.view.placeholder'," <div class='ipsEmpty'> <i class='fa-solid fa-inbox i-opacity_2'></i> <p class='i-margin-top_1'>{{#lang}}no_message_selected{{/lang}}</p></div>");ips.templates.set('messages.main.folderMenu',"<li data-role='folderInMenu'><button type='button' data-ipsMenuValue='{{key}}'><span data-role='folderName'>{{name}}</span> <span class='ipsMenu_itemCount' data-role='folderCount'>{{count}}</span></button></li>");;
;(function($,_){"use strict";ips.controller.register('core.front.messages.view',{_currentMessageID:null,_currentPage:1,initialize(){this.on('paginationClicked paginationJump',this.paginationClicked);this.on('addToCommentFeed',this.addToCommentFeed);this.on('deletedComment.comment',this.deleteComment);this.on(document,'menuItemSelected','#elConvoMove',this.moveConversation);this.on(document,'click','[data-action="deleteConversation"]',this.deleteConversation);this.on(document,'menuItemSelected','[data-role="userActions"]',this.userAction);this.on('submit','[data-role="addUser"]',this.addUsersSubmit);this.on(document,'selectedMessage.messages',this.selectedMessage);this.on(document,'setInitialMessage.messages',this.setInitialMessage);this.on(document,'getFolder.messages',this.getFolder);this.on(document,'loadMessageLoading.messages',this.loadMessageLoading);this.on(document,'loadMessageDone.messages',this.loadMessageDone);this.on(document,'deleteMessageDone.messages',this.deleteMessageDone);this.on(document,'blockUserDone.messages',this.blockUserDone);this.on(document,'addUserDone.messages',this.addUserDone);this.on(document,'addUserError.messages',this.addUserError);this.on(window,'historychange:messages',this.stateChange);this.setup();},setup(){if(this.scope.attr('data-current-id')){this._currentMessageID=this.scope.attr('data-current-id');}},addToCommentFeed(e,data){if(data.totalItems){this.trigger('updateReplyCount.messages',{messageID:this._currentMessageID,count:data.totalItems});}},addUserError(e,data){if(data.error){ips.ui.alert.show({type:'alert',icon:'warn',message:data.error,callbacks:{}});}},addUserDone(e,data){if(data.id!==this._currentMessageID){return;}
if(data.error){ips.ui.alert.show({type:'alert',icon:'warn',message:data.error,callbacks:{}});return;}
const numberMembers=_.size(data.members);if(data.members&&numberMembers){for(const i in data.members){const participant=this.scope.find('.cMessage_members').find('[data-participant="'+i+'"]');Debug.log('Ajax response:');Debug.log(data.members[i]);if(participant.length){participant.replaceWith(data.members[i]);}else{this.scope.find('.cMessage_members [data-role="addUserItem"]').before(data.members[i]);}}}
let message=ips.getString('messageUserAdded');if(numberMembers>1){message=ips.pluralize(ips.getString('messageUsersAdded'),numberMembers);}
ips.ui.flashMsg.show(message);if(data.failed&&parseInt(data.failed)>0){ips.ui.flashMsg.show(ips.getString('messageNotAllUsers'));}
this.scope.find('#elInviteMember'+this._currentMessageID).trigger('closeMenu');var autocomplete=ips.ui.autocomplete.getObj(this.scope.find('input[name="member_names"]'));autocomplete.removeAll();},inviteMenuOpened(e){this.scope.find('[data-role="addUser"] input[type="text"][id$="dummyInput"]').focus();},addUsersSubmit(e){e.preventDefault();const names=$(e.currentTarget).find('[name="member_names"]').val();this.trigger('addUser.messages',{id:this._currentMessageID,names:names});},blockUserDone(e,data){if(data.id!=this._currentMessageID){return;}
var participant=this.scope.find('.cMessage_members').find('[data-participant="'+data.member+'"]');participant.replaceWith(data.response);ips.ui.flashMsg.show(ips.getString('messageRemovedUser'));},userAction(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
const menu=this.scope.find('#elInviteMember'+this._currentMessageID+'_menu');if(menu[0].matches("[popover]")){menu[0].hidePopover();}
var autocomplete=ips.ui.autocomplete.getObj(this.scope.find('textarea[name="member_names"]'));autocomplete.removeAll();},addUsersSubmit(e){e.preventDefault();const names=$(e.currentTarget).find('[name="member_names"]').val();this.trigger('addUser.messages',{id:this._currentMessageID,names:names});},blockUserDone(e,data){if(data.id!=this._currentMessageID){return;}
var participant=this.scope.find('.cMessage_members').find('[data-participant="'+data.member+'"]');participant.replaceWith(data.response);ips.ui.flashMsg.show(ips.getString('messageRemovedUser'));},userAction(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
var userID=$(data.triggerElem).closest('[data-participant]').attr('data-participant');switch(data.selectedItemID){case'block':this.trigger('blockUser.messages',{member:userID,id:this._currentMessageID});break;case'unblock':this.trigger('addUser.messages',{member:userID,id:this._currentMessageID,unblock:true});break;}},deleteMessageDone(e,data){var url=ipsSettings['baseURL']+'?app=core&module=messaging&controller=messenger'
window.location=url;},moveConversation(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
window.location=url;},moveConversation(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
var self=this;var realName=$('#elConvoMove_menu').find('[data-ipsMenuValue="'+data.selectedItemID+'"] a').html();ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('conversationMove',{name:realName}),callbacks:{ok(){self.trigger('moveMessage.messages',{id:self._currentMessageID,folder:data.selectedItemID});}}});},deleteConversation(e){e.preventDefault();var self=this;ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('messagesDelete'),subText:ips.getString('messagesDeleteSubText'),callbacks:{ok(){self.trigger('deleteMessage.messages',{id:self._currentMessageID});}}});},loadMessageLoading(e,data){this.cleanContents();this.scope.html($('<div/>').addClass('ipsLoading').html('&nbsp;').css({minHeight:'150px'}));},loadMessageDone(e,data){this.scope.html(data.response);$(document).trigger('contentChange',[this.scope]);},paginationClicked(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}},selectedMessage(e,data){this.trigger('loadMessage.messages',{messageID:data.messageID,messageURL:data.messageURL,messageTitle:data.messageTitle});this._currentMessageID=data.messageID;},stateChange(){const state=ips.utils.history.getState('messages');if(state?.controller!=='messages'){return;}
if(state.id==null){this.cleanContents();this.scope.html(ips.templates.render('messages.view.placeholder'));this._currentMessageID=null;this._currentPage=null;return;}
if(state.id!==this._currentMessageID){this.trigger('fetchMessage.messages',{id:state.id,page:state.page||1});ips.utils.analytics.trackPageView(window.location.href);this._currentMessageID=state.id;this._currentPage=state.page||1;}else if(state.page!==this._currentPage){this.trigger('fetchMessage.messages',{id:this._currentMessageID,page:state.page});this._currentPage=state.page;}},setInitialMessage(e,data){this._currentMessageID=data.messageID;},getFolder(){this.cleanContents();this.scope.html(ips.templates.render('messages.view.placeholder'));ips.utils.anim.go('fadeIn',this.scope);},});}(jQuery,_));;
@@ -18,33 +19,32 @@ if(state.id!==this._currentMessageID){this.trigger('fetchMessage.messages',{id:s
'markFolderFinished.messages emptyFolderFinished.messages '+
'deleteMessageFinished.messages deleteMessagesFinished.messages moveMessageFinished.messages '+
'deleteFolderFinished.messages',this.folderActionDone);this.on(document,'deleteFolderDone.messages deleteMessageDone.messages deleteMessagesDone.messages '+
'emptyFolderDone.messages moveMessageDone.messages',this.updateCounts);this.on(document,'addFolderDone.messages',this.addFolderDone);this.on(document,'renameFolderDone.messages',this.renameFolderDone);this.on(document,'markFolderDone.messages',this.markFolderDone);this.on(document,'emptyFolderDone.messages',this.emptiedFolder);this.on(document,'deleteFolderDone.messages',this.deletedFolder);this.on('setInitialMessage.messages',this.setInitialMessage);this.on('setInitialFolder.messages',this.setInitialFolder);this.on('changeSort.messages changeFilter.messages',this.updateParam);this.on('input','[data-role="moderation"]',this.moderationInput);this.applyModMenuSelection();this.on('loadMessage.messages',this.loadMessage);this.on('changePage.messages',this.changePage);this.on(document,'controllerReady',this.controllerReady);this.on(document,'openDialog','#elAddFolder',this.addFolderDialogOpen);this.on(document,'openDialog','#elFolderRename',this.renameFolderDialogOpen);this.on(window,'historychange:messages',this.stateChange);},controllerReady(e,data){this._ready[data.controllerType]=true;if(this._ready['messages.list']&&this._ready['messages.view']&&data.controllerType=='core.front.messages.list'||data.controllerType=='core.front.messages.view'){this.trigger('messengerReady.messages');}},setInitialMessage(e,data){this._currentMessageID=data.messageID;},setInitialFolder(e,data){Debug.log(data);this._currentFolder=data.folderID;},changePage(e,data){this._updateURL({id:data.id,page:data.pageNo},{id:data.id,page:data.pageNo});},folderAction(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
'emptyFolderDone.messages moveMessageDone.messages',this.updateCounts);this.on(document,'addFolderDone.messages',this.addFolderDone);this.on(document,'renameFolderDone.messages',this.renameFolderDone);this.on(document,'markFolderDone.messages',this.markFolderDone);this.on(document,'emptyFolderDone.messages',this.emptiedFolder);this.on(document,'deleteFolderDone.messages',this.deletedFolder);this.on('setInitialMessage.messages',this.setInitialMessage);this.on('setInitialFolder.messages',this.setInitialFolder);this.on('changeSort.messages changeFilter.messages',this.updateParam);this.on('input','[data-role="moderation"]',this.moderationInput);this.applyModMenuSelection();this.on('loadMessage.messages',this.loadMessage);this.on('changePage.messages',this.changePage);this.on(document,'controllerReady',this.controllerReady);this.on(document,'openDialog','#elAddFolder',this.addFolderDialogOpen);this.on(document,'openDialog','#elFolderRename',this.renameFolderDialogOpen);this.on(window,'historychange:messages',this.stateChange);},controllerReady(e,data){this._ready[data.controllerType]=true;if(this._ready['messages.list']&&this._ready['messages.view']&&data.controllerType=='core.front.messages.list'||data.controllerType=='core.front.messages.view'){this.trigger('messengerReady.messages');}},setInitialMessage(e,data){this._currentMessageID=data.messageID;},setInitialFolder(e,data){Debug.log(data);this._currentFolder=data.folderID;},changePage(e,data){this._updateURL({id:data.id,page:data.pageNo},{id:data.id,page:data.pageNo});},folderAction(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
if(this._currentFolder==null){}
if(_.indexOf(this._protectedFolders,this._currentFolder)!==-1&&_.indexOf(['delete','rename'],data.selectedItemID)!==-1){return;}
switch(data.selectedItemID){case'markRead':this._actionMarkRead(data);break;case'delete':this._actionDelete(data);break;case'empty':this._actionEmpty(data);break;case'rename':this._actionRename(data);break;}},folderActionLoading(e,data){var loading=this.scope.find('[data-role="loadingFolderAction"]');ips.utils.anim.go('fadeIn',loading);},folderActionDone(e,data){var loading=this.scope.find('[data-role="loadingFolderAction"]');ips.utils.anim.go('fadeOut',loading);},addFolder(e){var button=$(e.currentTarget);if(ips.ui.dialog.getObj(button)){ips.ui.dialog.getObj(button).show();}else{button.ipsDialog({content:'#elAddFolder_content',title:ips.getString('addFolder'),size:'narrow'});}},addFolderDone(e,data){var newItem=ips.templates.render('messages.main.folderMenu',{key:data.key,count:0,name:data.folderName});$('#elMessageFolders_menu').find('[data-ipsMenuValue]').last().after(newItem);$('#elMessageFolders_menu').find('[data-ipsMenuValue="'+data.key+'"]').click();},renameFolderDone(e,data){var realFolderName=this._getRealFolder(data.folder);$('#elMessageFolders_menu').find('[data-ipsMenuValue="'+data.folder+'"]').find('[data-role="folderName"]').text(data.folderName);this.scope.find('[data-role="currentFolder"]').text(data.folderName);ips.ui.flashMsg.show(ips.getString('renamedTo',{folderName:realFolderName,newFolderName:data.folderName}));},markFolderDone(e,data){var realFolderName=this._getRealFolder(data.folder);ips.ui.flashMsg.show(ips.getString('messengerMarked',{folderName:realFolderName}));},emptiedFolder(e,data){var menuItem=$('#elMessageFolders_menu').find('[data-ipsMenuValue="'+data.folder+'"]');menuItem.find('.ipsMenu_itemCount').html('0');this.trigger('loadFolder',{folder:this._currentFolder,sortBy:this._params['sortBy'],filter:this._params['filter']});},deletedFolder(e,data){this.scope.find('#elMessageFolders_menu').find('[data-ipsMenuValue="'+data.folder+'"]').remove().end().find('[data-ipsMenuValue="myconvo"]').click();ips.ui.flashMsg.show(ips.getString('folderDeleted'));},loadMessage(e,data){if(!data.messageID){return;}
switch(data.selectedItemID){case'markRead':this._actionMarkRead(data);break;case'delete':this._actionDelete(data);break;case'empty':this._actionEmpty(data);break;case'rename':this._actionRename(data);break;}},folderActionLoading(e,data){var loading=this.scope.find('[data-role="loadingFolderAction"]');ips.utils.anim.go('fadeIn',loading);},folderActionDone(e,data){var loading=this.scope.find('[data-role="loadingFolderAction"]');ips.utils.anim.go('fadeOut',loading);},addFolder(e){var button=$(e.currentTarget);if(ips.ui.dialog.getObj(button)){ips.ui.dialog.getObj(button).show();}else{button.ipsDialog({content:'#elAddFolder_content',title:ips.getString('addFolder'),size:'narrow'});}},addFolderDone(e,data){var newItem=ips.templates.render('messages.main.folderMenu',{key:data.key,count:0,name:data.folderName});$('#elMessageFolders_menu').find('[data-role="folderInMenu"]').last().after(newItem);$('#elMessageFolders_menu [data-ipsMenuValue="'+data.key+'"]')[0].dispatchEvent(new Event("click",{bubbles:true}));},renameFolderDone(e,data){var realFolderName=this._getRealFolder(data.folder);$('#elMessageFolders_menu').find('[data-ipsMenuValue="'+data.folder+'"]').find('[data-role="folderName"]').text(data.folderName);this.scope.find('[data-role="currentFolder"]').text(data.folderName);ips.ui.flashMsg.show(ips.getString('renamedTo',{folderName:realFolderName,newFolderName:data.folderName}));},markFolderDone(e,data){var realFolderName=this._getRealFolder(data.folder);ips.ui.flashMsg.show(ips.getString('messengerMarked',{folderName:realFolderName}));},emptiedFolder(e,data){var menuItem=$('#elMessageFolders_menu').find('[data-ipsMenuValue="'+data.folder+'"]');menuItem.find('.ipsMenu_itemCount').html('0');this.trigger('loadFolder',{folder:this._currentFolder,sortBy:this._params['sortBy'],filter:this._params['filter']});},deletedFolder(e,data){this.scope.find('#elMessageFolders_menu').find('[data-ipsMenuValue="'+data.folder+'"]').remove();this.scope.find('[data-ipsMenuValue="myconvo"]')[0].dispatchEvent(new Event("click",{bubbles:true}));ips.ui.flashMsg.show(ips.getString('folderDeleted'));},loadMessage(e,data){if(!data.messageID){return;}
this._newMessageID=data.messageID;this._updateURL({id:data.messageID,url:data.messageURL},{},data.messageTitle);},updateParam(e,data){if(!_.isUndefined(data.param)&&!_.isUndefined(data.value)){this._params[data.param]=data.value;}
this._updateURL(false,this._params);},changeFolder(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
var folderID=data.selectedItemID;var folderURL=data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"] a').attr('href');var folderName=data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"]').find('[data-role="folderName"]').text();if(_.isUndefined(folderID)){return;}
this._updateURL(false,this._params);},changeFolder(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
var folderID=data.selectedItemID;var folderURL=$(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"] a').attr('href');var folderName=$(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"]').find('[data-role="folderName"]').text();if(_.isUndefined(folderID)){return;}
this._currentMessageID=null;this.scope.find('[data-ipsFilterBar]').trigger('switchTo.filterBar',{switchTo:'filterBar'});this._updateURL(_.extend({folder:folderID,url:folderURL},this._params),{folder:folderID,id:null,page:null},folderName);},addFolderDialogOpen(e,data){$(data.dialog).find('input[type="text"]').attr('data-folderID',this._currentFolder).val('').focus();},renameFolderDialogOpen(e,data){var realFolderName=this._getRealFolder(this._currentFolder);$(data.dialog).find('[data-role="folderName"]').attr('data-folderID',this._currentFolder).val(_.unescape(realFolderName)).focus();},stateChange(){const state=ips.utils.history.getState('messages')
if(state?.controller==='messages'&&state.folder!==this._currentFolder){this._updateFolder(state.folder);}},_updateURL(urlParams,newValues,newTitle){let url='';const title=newTitle||document.title;if(urlParams===false){url=window.location.href;if(window.location.hash){url=url.substr(0,url.length-window.location.hash.length);}}else if(urlParams.url){url=urlParams.url;}else{url=[];url.push('?app=core&module=messaging&controller=messenger');_.each(urlParams,function(value,idx){if(idx!='page'||(idx=='page'&&value!=1)){url.push(idx+"="+value);}});url=url.join('&');}
const defaultObj={id:this._newMessageID,folder:this._currentFolder,params:this._params,controller:'messages',};ips.utils.history.pushState({...defaultObj,...(newValues||{})},'messages',url);document.title=title},updateCounts(e,data){this.scope.find('[data-role="quotaTooltip"]').attr('data-ipsTooltip-label',data.quotaText).find('[data-role="quotaWidth"]').val(parseInt(data.quotaPercent)).end().find('[data-role="quotaValue"]').text(parseInt(data.quotaPercent));$('#elMessageFolders_menu').find('[data-ipsMenuValue]').each(function(){if(data.counts){$(this).find('.ipsMenu_itemCount').text(parseInt(data.counts[$(this).attr('data-ipsMenuValue')]?data.counts[$(this).attr('data-ipsMenuValue')]:'0'));}});},_updateFolder(newFolder){var folderName=$('[data-ipsMenuValue="'+newFolder+'"]').find('[data-role="folderName"]').text();var self=this;$('#elFolderSettings_menu').find('.ipsMenu_item').removeClass('ipsMenu_itemDisabled').show();$('#elFolderSettings_menu .ipsMenu_item a').each(function(){$(this).attr('href',$(this).attr('href').replace('&folder='+self._currentFolder,'&folder='+newFolder));});if(_.indexOf(this._protectedFolders,newFolder)!==-1){$('#elFolderSettings_menu').find('[data-ipsMenuValue="delete"], [data-ipsMenuValue="rename"]').addClass('ipsMenu_itemDisabled').hide();}
const defaultObj={id:this._newMessageID,folder:this._currentFolder,params:this._params,controller:'messages',};ips.utils.history.pushState({...defaultObj,...(newValues||{})},'messages',url);document.title=title},updateCounts(e,data){this.scope.find('[data-role="quotaTooltip"]').attr('data-ipsTooltip-label',data.quotaText).find('[data-role="quotaWidth"]').val(parseInt(data.quotaPercent)).end().find('[data-role="quotaValue"]').text(parseInt(data.quotaPercent));$('#elMessageFolders_menu').find('[data-ipsMenuValue]').each(function(){if(data.counts){$(this).find('.ipsMenu_itemCount').text(parseInt(data.counts[$(this).attr('data-ipsMenuValue')]?data.counts[$(this).attr('data-ipsMenuValue')]:'0'));}});},_updateFolder(newFolder){var folderName=$('[data-ipsMenuValue="'+newFolder+'"]').find('[data-role="folderName"]').text();var self=this;$('#elFolderSettings_menu').find('[hidden]').removeAttr('hidden');$('#elFolderSettings_menu a').each(function(){$(this).attr('href',$(this).attr('href').replace('&folder='+self._currentFolder,'&folder='+newFolder));});if(_.indexOf(this._protectedFolders,newFolder)!==-1){$('#elFolderSettings_menu').find('[data-ipsMenuValue="delete"], [data-ipsMenuValue="rename"]').attr('hidden',true);}
this.scope.find('[data-role="currentFolder"]').text(folderName);this._currentFolder=newFolder;},_actionRename(data){var dialog=$('#elFolderSettings_menu').find('[data-ipsMenuValue="rename"]');if(ips.ui.dialog.getObj(dialog)){ips.ui.dialog.getObj(dialog).show();}else{dialog.ipsDialog({content:'#elFolderRename_content',title:ips.getString('renameFolder'),size:'narrow'});}},_actionDelete(data){var self=this;ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('messengerDeleteConfirm'),subText:ips.getString('cantBeUndone'),callbacks:{ok(){self.trigger('deleteFolder.messages',{folder:self._currentFolder});}}});},_actionMarkRead(data){var realFolderName=this._getRealFolder(this._currentFolder);var self=this;ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('messengerMarkRead',{folderName:realFolderName}),callbacks:{ok(){self.trigger('markFolder.messages',{folder:self._currentFolder});}}});},_actionEmpty(data){var realFolderName=this._getRealFolder(this._currentFolder);var self=this;ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('messengerDeleteContents',{folderName:realFolderName}),subText:ips.getString('cantBeUndone'),callbacks:{ok(){self.trigger('emptyFolder.messages',{folder:self._currentFolder});}}});},_getRealFolder(folder){var menuItem=$('#elMessageFolders_menu').find('[data-ipsMenuValue="'+folder+'"]');return menuItem.find('[data-role="folderName"]').html();},moderationInput(e){const currentData=ips.utils.db.get('messages','mod_menu_checked')||{};const id=e.target.name;if(!id){return;}
if(e.target.checked){currentData[id]=e.target.dataset.actions||"";}else{delete currentData[id];}
ips.utils.db.set('messages','mod_menu_checked',currentData);},applyModMenuSelection(){const currentData=ips.utils.db.get('messages','mod_menu_checked');const pageAction=this.elem.querySelector('[data-ipspageaction]');if(pageAction&&currentData&&typeof currentData==="object"&&Object.keys(currentData).length){const messageSelector=[...Object.keys(currentData)].map(id=>`[name="${id}"]`).join(',');const remainingIds=new Set(Object.keys(currentData));this.elem.querySelectorAll(`input[data-role="moderation"]:is(${messageSelector})`).forEach(el=>{remainingIds.delete(el.name);el.checked=true;$(el).trigger('change');});if(remainingIds.size){remainingIds.forEach(id=>{$(pageAction).trigger("addManualItem.pageAction",{id:id,actions:typeof currentData[id]==="string"?currentData[id]:''})});$(this.elem.querySelector('[data-ipsautocheck]')).trigger('setInitialCount.autoCheck',{count:remainingIds.size})}}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.messages.list',{_messageList:null,_searchTimer:null,_currentFolder:null,_currentMessageID:null,_currentOptions:{sortBy:'mt_last_post_time',filter:'all'},_infScrollURL:null,initialize(){this.on(document,'messengerReady.messages',this.messengerReady);this.on('menuItemSelected','#elSortByMenu',this.changeSort);this.on('menuItemSelected','#elFilterMenu',this.changeFilter);this.on('menuItemSelected','#elSearchTypes',this.selectedMenuItem);this.on('click','[data-messageid]',this.clickMessage);this.on('submit','[data-role="moderationTools"]',this.moderationSubmit);this.on('input','[data-role="messageSearchText"]',this.inputSearch);this.on('click','[data-action="messageSearchCancel"]',this.cancelSearch);this.on(document,'loadFolderDone.messages',this.loadFolderDone);this.on(document,'loadFolderLoading.messages, searchFolderLoading.messages',this.loadFolderLoading);this.on(document,'loadFolderFinished.messages',this.loadFolderFinished);this.on(document,'searchFolderLoading.messages',this.searchFolderLoading);this.on(document,'searchFolderDone.messages',this.searchFolderDone);this.on(document,'searchFolderFinished.messages',this.searchFolderFinished);this.on(document,'markFolderDone.messages',this.markFolderDone);this.on(document,'deleteMessagesDone.messages',this.deleteMessagesDone);this.on(document,'loadMessageDone.messages',this.markMessageRead);this.on(document,'deleteMessageDone.messages',this.deleteMessageDone);this.on(document,'moveMessageDone.messages',this.moveMessageDone);this.on(document,'addToCommentFeed',this.newMessage);this.on(document,'deletedComment.comment',this.deletedMessage);this.on(window,'historychange:messages',this.stateChange);this.setup();},setup(){this._messageList=this.scope.find('[data-role="messageList"]');this._currentFolder=this.scope.attr('data-folderID');this.trigger('setInitialFolder.messages',{folderID:this._currentFolder});},moderationSubmit(e,data){e.preventDefault();var self=this;var form=this.scope.find('[data-role="moderationTools"]');var count=parseInt(this.scope.find('[data-role="moderation"]:checked').length);if(this.scope.find('[data-role="pageActionOptions"]').find('select option:selected').val()=='move'){var dialog=ips.ui.dialog.create({remoteVerify:false,size:'narrow',remoteSubmit:false,title:ips.getString('messagesMove'),url:form.attr('action')+'&do=moveForm&ids='+_.map(self.scope.find('[data-role="moderation"]:checked'),function(item){return $(item).closest('[data-messageid]').attr('data-messageid');}).join(',')});dialog.show();}else{ips.ui.alert.show({type:'confirm',icon:'question',message:(count>1)?ips.pluralize(ips.getString('messagesDeleteMany'),count):ips.getString('messagesDelete'),subText:(count>1)?ips.getString('messagesDeleteManySubText'):ips.getString('messagesDeleteSubText'),callbacks:{ok(){var ids=_.map(self.scope.find('[data-role="moderation"]:checked'),function(item){return $(item).closest('[data-messageid]').attr('data-messageid');});self.trigger('deleteMessages.messages',{id:ids});}}});}},deleteMessagesDone(e,data){var selector=_.map(data.id,function(item){return'[data-messageid="'+item+'"]';}).join(',');var self=this;var messages=this._messageList.find(selector);if(messages.length){messages.slideUp({complete(){messages.remove();if(data.id.indexOf(self._currentMessageID)!==-1){self._currentMessageID=null;if(self._messageList.find('[data-messageid]').length){self._messageList.find('[data-messageid]').first().click();}else{self.trigger('getFolder',{folderID:self._currentFolder});}}
;(function($,_,undefined){"use strict";ips.controller.register('core.front.messages.list',{_messageList:null,_searchTimer:null,_currentFolder:null,_currentMessageID:null,_currentOptions:{sortBy:'mt_last_post_time',filter:'all'},_infScrollURL:null,initialize(){this.on(document,'messengerReady.messages',this.messengerReady);this.on('menuItemSelected','#elSortByMenu',this.changeSort);this.on('menuItemSelected','#elFilterMenu',this.changeFilter);this.on('click','[data-messageid]',this.clickMessage);this.on('submit','[data-role="moderationTools"]',this.moderationSubmit);this.on('input','[data-role="messageSearchText"]',this.inputSearch);this.on('click','[data-action="messageSearchCancel"]',this.cancelSearch);this.on(document,'loadFolderDone.messages',this.loadFolderDone);this.on(document,'loadFolderLoading.messages, searchFolderLoading.messages',this.loadFolderLoading);this.on(document,'loadFolderFinished.messages',this.loadFolderFinished);this.on(document,'searchFolderLoading.messages',this.searchFolderLoading);this.on(document,'searchFolderDone.messages',this.searchFolderDone);this.on(document,'searchFolderFinished.messages',this.searchFolderFinished);this.on(document,'markFolderDone.messages',this.markFolderDone);this.on(document,'deleteMessagesDone.messages',this.deleteMessagesDone);this.on(document,'loadMessageDone.messages',this.markMessageRead);this.on(document,'deleteMessageDone.messages',this.deleteMessageDone);this.on(document,'moveMessageDone.messages',this.moveMessageDone);this.on(document,'addToCommentFeed',this.newMessage);this.on(document,'deletedComment.comment',this.deletedMessage);this.on(window,'historychange:messages',this.stateChange);this.setup();},setup(){this._messageList=this.scope.find('[data-role="messageList"]');this._currentFolder=this.scope.attr('data-folderID');this.trigger('setInitialFolder.messages',{folderID:this._currentFolder});},moderationSubmit(e,data){e.preventDefault();var self=this;var form=this.scope.find('[data-role="moderationTools"]');var count=parseInt(this.scope.find('[data-role="moderation"]:checked').length);if(this.scope.find('[data-role="pageActionOptions"]').find('select option:selected').val()=='move'){var dialog=ips.ui.dialog.create({remoteVerify:false,size:'narrow',remoteSubmit:false,title:ips.getString('messagesMove'),url:form.attr('action')+'&do=moveForm&ids='+_.map(self.scope.find('[data-role="moderation"]:checked'),function(item){return $(item).closest('[data-messageid]').attr('data-messageid');}).join(',')});dialog.show();}else{ips.ui.alert.show({type:'confirm',icon:'question',message:(count>1)?ips.pluralize(ips.getString('messagesDeleteMany'),count):ips.getString('messagesDelete'),subText:(count>1)?ips.getString('messagesDeleteManySubText'):ips.getString('messagesDeleteSubText'),callbacks:{ok(){var ids=_.map(self.scope.find('[data-role="moderation"]:checked'),function(item){return $(item).closest('[data-messageid]').attr('data-messageid');});self.trigger('deleteMessages.messages',{id:ids});}}});}},deleteMessagesDone(e,data){var selector=_.map(data.id,function(item){return'[data-messageid="'+item+'"]';}).join(',');var self=this;var messages=this._messageList.find(selector);if(messages.length){messages.slideUp({complete(){messages.remove();if(data.id.indexOf(self._currentMessageID)!==-1){self._currentMessageID=null;if(self._messageList.find('[data-messageid]').length){self._messageList.find('[data-messageid]').first().click();}else{self.trigger('getFolder',{folderID:self._currentFolder});}}
self._resetListActions();},queue:false}).fadeOut({queue:false});}},inputSearch(e){clearTimeout(this._searchTimer);this._searchTimer=setTimeout(_.bind(this._startSearch,this),500);},searchFolderLoading(e,data){this.scope.find('[data-role="messageSearchText"]').addClass('ipsField_loading');},searchFolderDone(e,data){this._messageList.html(data.data).show().end().find('[data-role="messageListPagination"]').html(data.pagination).end().find('[data-role="loading"]').attr('hidden',true).end().find('[data-role="messageListFilters"]').attr('hidden',true);this.scope.find('[data-action="messageSearchCancel"]').removeAttr('hidden');if(this.scope.is('[data-ipsInfScroll]')){var params=decodeURIComponent($.param(ips.utils.form.serializeAsObject($('[data-role="messageSearch"]'))));var base=this.scope.find('#elMessageList > form').attr('action');this._infScrollURL=this.scope.attr('data-ipsInfScroll');this.scope.attr('data-ipsInfScroll-url',base+'&'+params+'&folder='+this._currentFolder);this.scope.trigger('refresh.infScroll');}
$(document).trigger('contentChange',[this._messageList]);this._resetListActions();},searchFolderFinished(e,data){this.scope.find('[data-role="messageSearchText"]').removeClass('ipsField_loading');},cancelSearch(e){if(!_.isUndefined(e)){e.preventDefault();}
this._resetSearch();this._getFolder(this._currentFolder);},deletedReply(e,data){var count=this._messageList.find('[data-messageid="'+data.messageID+'"] [data-role="replyCount"]').text();this._messageList.find('[data-messageid="'+data.messageID+'"] [data-role="replyCount"]').text(parseInt(count)-1);},updateReplyCount(e,data){this._messageList.find('[data-messageid="'+data.messageID+'"] [data-role="replyCount"]').text(data.count);},markFolderDone(e,data){if(data.folder==this._currentFolder){this._messageList.find('[data-messageid]').removeAttr('data-ips-unread').find('.ipsIndicator').remove();}},deleteMessageDone(e,data){var message=this._messageList.find('[data-messageid="'+data.id+'"]');if(message.length){ips.utils.anim.go('fadeOutDown',message).done(function(){message.remove();});this._currentMessageID=null;}},moveMessageDone(e,data){var message=this._messageList.find('[data-messageid="'+data.id+'"]');var next=null;if(this._currentMessageID==data.id){if(message.prev('[data-messageid]').length){next=message.prev('[data-messageid]');}else if(message.next('[data-messageid]').length){next=message.next('[data-messageid]');}}
$(document).trigger('contentChange',[this._messageList]);this._resetListActions();},searchFolderFinished(e,data){this.scope.find('[data-role="messageSearchText"]').removeClass('ipsField_loading');},cancelSearch(e){this._resetSearch();this._getFolder(this._currentFolder);},deletedReply(e,data){var count=this._messageList.find('[data-messageid="'+data.messageID+'"] [data-role="replyCount"]').text();this._messageList.find('[data-messageid="'+data.messageID+'"] [data-role="replyCount"]').text(parseInt(count)-1);},updateReplyCount(e,data){this._messageList.find('[data-messageid="'+data.messageID+'"] [data-role="replyCount"]').text(data.count);},markFolderDone(e,data){if(data.folder==this._currentFolder){this._messageList.find('[data-messageid]').removeAttr('data-ips-unread').find('.ipsIndicator').remove();}},deleteMessageDone(e,data){var message=this._messageList.find('[data-messageid="'+data.id+'"]');if(message.length){ips.utils.anim.go('fadeOutDown',message).done(function(){message.remove();});this._currentMessageID=null;}},moveMessageDone(e,data){var message=this._messageList.find('[data-messageid="'+data.id+'"]');var next=null;if(this._currentMessageID==data.id){if(message.prev('[data-messageid]').length){next=message.prev('[data-messageid]');}else if(message.next('[data-messageid]').length){next=message.next('[data-messageid]');}}
if(message.length&&data.to!=this._currentFolder){ips.utils.anim.go('fadeOutDown',message).done(function(){message.remove();});this._currentMessageID=null;}
ips.ui.flashMsg.show(ips.getString('conversationMoved'));if(next){next.click();}},loadFolderDone(e,data){this.scope.attr('data-ipsInfScroll-url',data.listBaseUrl).find('#elMessageList').scrollTop(0);this._messageList.html(data.data).show().end().find('[data-role="messageListPagination"]').html(data.pagination).end().find('[data-role="loading"]').attr('hidden',true);this.scope.trigger('refresh.infScroll');$(document).trigger('contentChange',[this._messageList]);this._resetListActions();},loadFolderLoading(e,data){if(!this.scope.find('[data-role="loading"]').length){this._messageList.after($('<div/>').addClass('ipsLoading').html('&nbsp;').css({minHeight:'150px'}).attr('data-role','loading'));}
this._messageList.hide();this._hideEmpty();this.scope.find('[data-role="loading"]').removeAttr('hidden');},loadFolderFinished(e,data){this._messageList.show();this._resetSearch();},messengerReady(){this._currentMessageID=this._messageList.find('.ipsData__item--active').attr('data-messageid');this.trigger('setInitialMessage.messages',{messageID:this._currentMessageID});},clickMessage(e){if($(e.target).is('input[type="checkbox"]')){return;}
e.preventDefault();var messageID=$(e.currentTarget).attr('data-messageid');var messageURL=$(e.currentTarget).find('[data-role="messageURL"]').attr('href');var messageTitle=$(e.currentTarget).find('[data-role="messageURL"]').text();this.trigger('selectedMessage.messages',{messageID:messageID,messageURL:messageURL,messageTitle:messageTitle});this.trigger('switchTo.filterBar',{switchTo:'filterContent'});this._selectMessage(messageID);},newMessage(e,data){this._updateRow(data.feedID.substr(data.feedID.indexOf('-')+1));},deletedMessage(e,data){var feedId=$(e.target).closest('[data-feedid]').attr('data-feedid');this._updateRow(feedId.substr(feedId.indexOf('-')+1));},_updateRow:function(conversationId){var scope=$(this.scope);ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=messaging&controller=messenger&id='+conversationId+'&getRow=1').done(function(response){scope.find('[data-messageid="'+conversationId+'"]').replaceWith(response);$(document).trigger('contentChange',[scope]);});},changeSort(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
var sort=data.selectedItemID;if(sort){this.trigger('changeSort.messages',{param:'sortBy',value:sort});}},changeFilter(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
e.preventDefault();var messageID=$(e.currentTarget).attr('data-messageid');var messageURL=$(e.currentTarget).find('[data-role="messageURL"]').attr('href');var messageTitle=$(e.currentTarget).find('[data-role="messageURL"]').text();this.trigger('selectedMessage.messages',{messageID:messageID,messageURL:messageURL,messageTitle:messageTitle});this.trigger('switchTo.filterBar',{switchTo:'filterContent'});this._selectMessage(messageID);},newMessage(e,data){this._updateRow(data.feedID.substr(data.feedID.indexOf('-')+1));},deletedMessage(e,data){var feedId=$(e.target).closest('[data-feedid]').attr('data-feedid');this._updateRow(feedId.substr(feedId.indexOf('-')+1));},_updateRow:function(conversationId){var scope=$(this.scope);ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=messaging&controller=messenger&id='+conversationId+'&getRow=1').done(function(response){scope.find('[data-messageid="'+conversationId+'"]').replaceWith(response);$(document).trigger('contentChange',[scope]);});},changeSort(e,data=e.detail){e.preventDefault();if(data.originalEvent){data.originalEvent.preventDefault();}
var sort=data.selectedItemID;if(sort){this.trigger('changeSort.messages',{param:'sortBy',value:sort});}},changeFilter(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
var filter=data.selectedItemID;if(filter){this.trigger('changeFilter.messages',{param:'filter',value:filter});}},stateChange(){const state=ips.utils.history.getState('messages')||{}
if(state.controller!=='messages'){return;}
let newFilters=false;if(typeof state.params==='object'&&(state.params.sortBy!==this._currentOptions.sortBy||state.params.filter!==this._currentOptions.filter)){this._currentOptions.sortBy=state.params.sortBy;this._currentOptions.filter=state.params.filter;newFilters=true;}
if(state.folder!==this._currentFolder||newFilters){this._getFolder(state.folder);}
if(state.mid!==this._currentMessageID){if(Array.isArray(state.mid)){this._selectMessages(state.mid);}else{this._selectMessage(state.mid);}}},markMessageRead:function(e,data){this._messageList.find('[data-messageid="'+data.id+'"]').removeAttr('data-ips-unread');},_startSearch(e){var serialized=ips.utils.form.serializeAsObject($('[data-role="messageSearch"]'));if(!serialized.q.length){this.cancelSearch();return;}
if(!serialized.q.length){this.cancelSearch();return;}
var gotSomething=false;_.each(['topic','post','recipient','sender'],function(item){if(_.has(serialized.search,item)){gotSomething=true;}});if(!gotSomething){var self=this;ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('messageSearchFail'),subText:ips.getString('messageSearchFailSubText'),callbacks:{ok(){self._resetSearch();return false;}}});}else{this.trigger('searchFolder.messages',_.extend({folder:this._currentFolder},serialized));}},_resetSearch(){this.scope.find('[data-role="messageSearchText"]').removeClass('ipsField_loading').val('');this.scope.find('[data-action="messageSearchCancel"]').attr('hidden',true);this.scope.find('[data-role="messageListFilters"]').removeAttr('hidden');this._resetListActions();this.scope.attr('data-ipsInfScroll',this._infScrollURL);this.scope.trigger('refresh.infScroll');},_selectMessage(id){this._messageList.find('[data-messageid]').removeClass('ipsData__item--active').end().find('[data-messageid="'+id+'"]').addClass('ipsData__item--active');this._currentMessageID=id;},_selectMessages(IDs){var self=this;this._messageList.find('[data-messageid]').removeClass('ipsData__item--active');_.each(IDs,function(id){self._messageList.find('[data-messageid="'+id+'"]').addClass('ipsData__item--active');});this._currentMessageID=IDs;},_getFolder(newFolder){this.trigger('loadFolder.messages',{folder:newFolder,filter:this._currentOptions.filter,sortBy:this._currentOptions.sortBy});this._currentFolder=newFolder;},_hideEmpty(){this.scope.find('[data-role="emptyMsg"]').hide();},_resetListActions(){try{ips.ui.pageAction.getObj(this.scope.find('[data-ipsPageAction]')).reset();ips.ui.autoCheck.getObj(this.scope.find('[data-ipsAutoCheck]')).refresh();}catch(err){}},selectedMenuItem(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}}});}(jQuery,_));;
var gotSomething=false;_.each(['topic','post','recipient','sender'],function(item){if(_.has(serialized.search,item)){gotSomething=true;}});if(!gotSomething){var self=this;ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('messageSearchFail'),subText:ips.getString('messageSearchFailSubText'),callbacks:{ok(){self._resetSearch();return false;}}});}else{this.trigger('searchFolder.messages',_.extend({folder:this._currentFolder},serialized));}},_resetSearch(){this.scope.find('[data-role="messageSearchText"]').removeClass('ipsField_loading').val('');this.scope.find('[data-action="messageSearchCancel"]').attr('hidden',true);this.scope.find('[data-role="messageListFilters"]').removeAttr('hidden');this._resetListActions();this.scope.attr('data-ipsInfScroll',this._infScrollURL);this.scope.trigger('refresh.infScroll');},_selectMessage(id){this._messageList.find('[data-messageid]').removeClass('ipsData__item--active').end().find('[data-messageid="'+id+'"]').addClass('ipsData__item--active');this._currentMessageID=id;},_selectMessages(IDs){var self=this;this._messageList.find('[data-messageid]').removeClass('ipsData__item--active');_.each(IDs,function(id){self._messageList.find('[data-messageid="'+id+'"]').addClass('ipsData__item--active');});this._currentMessageID=IDs;},_getFolder(newFolder){this.trigger('loadFolder.messages',{folder:newFolder,filter:this._currentOptions.filter,sortBy:this._currentOptions.sortBy});this._currentFolder=newFolder;},_hideEmpty(){this.scope.find('[data-role="emptyMsg"]').hide();},_resetListActions(){try{ips.ui.pageAction.getObj(this.scope.find('[data-ipsPageAction]')).reset();ips.ui.autoCheck.getObj(this.scope.find('[data-ipsAutoCheck]')).refresh();}catch(err){}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.messages.folderDialog',{_events:{add:'addFolder',rename:'renameFolder'},initialize:function(){this.on('submit','form',this.submitName);},submitName:function(e){e.preventDefault();e.stopPropagation();var type=this.scope.attr('data-type');var field=this.scope.find('[data-role="folderName"]');var val=field.val();var folderID=field.attr('data-folderID');this.trigger(this._events[type]+'.messages',{folder:folderID,name:val});this.trigger('closeDialog');}});}(jQuery,_));;
+16 -17
View File
@@ -1,22 +1,21 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.report',{initialize:function(){this.on(document,'submitDialog','[data-role="warnUserDialog"]',this.dialogSubmitted);this.on('menuItemSelected',this.menuItemSelected);},menuItemSelected:function(e,data){data.originalEvent.preventDefault();var link=data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"] a');var langString=(data.selectedItemID=='spamFlagButton')?ips.getString('confirmFlagAsSpammer'):ips.getString('confirmUnFlagAsSpammer');var descString=(data.selectedItemID=='spamUnFlagButton')?ips.getString('confirmUnFlagAsSpammerDesc'):'';var self=this;if(data.selectedItemID=='spamFlagButton'||data.selectedItemID=='spamUnFlagButton'){ips.ui.alert.show({type:'confirm',message:langString,subText:descString,callbacks:{ok:function(){self._startLoading();ips.getAjax()(link.attr('href'),{bypassRedirect:true}).done(function(response){self._refreshPanel();});},}});}},dialogSubmitted:function(e,data){this._startLoading();this._refreshPanel();},_startLoading:function(){this.scope.find('[data-role="authorPanel"]').css('height',this.scope.find('[data-role="authorPanel"]').height()+'px').addClass('ipsLoading').find('*').hide();},_refreshPanel:function(){var self=this;ips.getAjax()(window.location,{bypassRedirect:true}).done(function(response){self.scope.find('[data-role="authorPanel"]').css('height','auto').removeClass('ipsLoading').html(response);});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.report',{initialize:function(){this.on(document,'submitDialog','[data-role="warnUserDialog"]',this.dialogSubmitted);this.on('menuItemSelected',this.menuItemSelected);},menuItemSelected:function(e,data=e.detail){data.originalEvent.preventDefault();var link=$(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"] a');var langString=(data.selectedItemID=='spamFlagButton')?ips.getString('confirmFlagAsSpammer'):ips.getString('confirmUnFlagAsSpammer');var descString=(data.selectedItemID=='spamUnFlagButton')?ips.getString('confirmUnFlagAsSpammerDesc'):'';var self=this;if(data.selectedItemID=='spamFlagButton'||data.selectedItemID=='spamUnFlagButton'){ips.ui.alert.show({type:'confirm',message:langString,subText:descString,callbacks:{ok:function(){self._startLoading();ips.getAjax()(link.attr('href'),{bypassRedirect:true}).done(function(response){self._refreshPanel();});},}});}},dialogSubmitted:function(e,data){this._startLoading();this._refreshPanel();},_startLoading:function(){this.scope.find('[data-role="authorPanel"]').css('height',this.scope.find('[data-role="authorPanel"]').height()+'px').addClass('ipsLoading').find('*').hide();},_refreshPanel:function(){var self=this;ips.getAjax()(window.location,{bypassRedirect:true}).done(function(response){self.scope.find('[data-role="authorPanel"]').css('height','auto').removeClass('ipsLoading').html(response);});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.approveQueue',{initialize:function(){this.on('click','[data-action="approvalQueueAction"]',this.doConfirm);},doConfirm:function(e,data){e.preventDefault();var self=this;var action=$(e.currentTarget).attr('data-type');if(action!=='delete'){self.doAction(e,data);return;}
var alert={type:'confirm',icon:'warn',message:ips.getString('generic_confirm'),subText:'',callbacks:{ok:function(){self.doAction(e,data);},no:function(){return;}}};ips.ui.alert.show(alert);},doAction:function(e,data){e.preventDefault();var element=$(e.target).closest('a');ips.getAjax()($(element).attr('href')+'&_fromApproval=1',{bypassRedirect:true}).done(function(){ips.getAjax()(ips.getSetting('baseURL')+'?app=core&module=modcp&controller=modcp&tab=approval&action=getCount').done(function(response){$('#elModCPApprovalCount').html(response.count);$(element).parents('.ipsApprovalQueueItem, .ipsData__item').slideUp("slow").remove();}).fail(function(failresponse){window.location=ips.getSetting('baseURL')+'?app=core&module=modcp&controller=modcp&tab=approval';});}).fail(function(){window.location=$(e.currentTarget).attr('href');});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.reportToggle',{initialize:function(){this.on('click','[data-action="_ipsMenu_ping"]',this.reportToggleClicked);},reportToggleClicked:function(e){e.preventDefault();var elem=$(e.currentTarget);var self=this;var menuButton=this.scope.find('[data-action="menubutton"]');var reportId=this.scope.find('[data-reportId]').attr('data-reportId');var newStatus=$(elem).closest('li.ipsMenu_item').attr('data-ipsMenuValue');var newStatusText=$(elem).find('[data-role="ipsMenu_selectedText"]').text();if($(elem).attr('data-showconfirm')!==undefined){if($(elem).attr('data-hasNotifications')==1){var dialogRef=ips.ui.dialog.create({title:ips.getString('report_status_change_confirm',{newstatus:newStatusText}),size:'narrow',url:'?app=core&module=modcp&controller=modcp&tab=reports&action=reportCenterConfirmModal&id='+reportId+'&status='+newStatus,forceReload:true});dialogRef.show();}else{ips.ui.alert.show({type:'confirm',title:ips.getString('report_status_change_confirm',{newstatus:newStatusText}),icon:'fa fa-question-circle',buttons:{ok:ips.getString('ok'),cancel:ips.getString('cancel')},callbacks:{ok:function(){menuButton.addClass('ipsLoading ipsLoading_small');menuButton.find('span').html('&nbsp;');$(elem).attr('data-action','ipsMenu_ping').trigger('click');},}});}}else{menuButton.addClass('ipsLoading ipsLoading_small');menuButton.find('span').html('&nbsp;');$(elem).attr('data-action','ipsMenu_ping').trigger('click');}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.warnForm',{pointsEdited:false,expirationEdited:false,editorSetTo:'',initialize:function(){var self=this;this.on('change','[name="warn_reason"]',this.changeReason);this.on('change','[name="warn_points"]',this.changePoints);this.on('change','[name="warn_remove"],[name="warn_remove_time"]',function(e){self.expirationEdited=true;});this.on('editorWidgetInitialized',this.editorInitialized);},editorInitialized:function(e,data){if(data.id=='warn_member_note'){$('[name="warn_reason"]').change();const editor=ips.ui.editorv5.getObj($('textarea[name="warn_member_note"]').closest('[data-ipsEditorv5]'));this.editorSetTo=editor.getInstance().getHTML();}},changeReason:function(e){var scope=this.scope;var self=this;ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=warnings&do=reasonAjax&id='+$(e.target).val()).done(function(response){if(self.pointsEdited==false||response.points_override==0){var pointsNow=scope.find('[name="warn_points"]').val();scope.find('[name="warn_points"]').val(response.points).prop('disabled',response.points_override==0);if(pointsNow!=response.points){scope.find('[name="warn_points"]').change();}
self.pointsEdited=false;}
var removePointsUnlimited=scope.find('[name="warn_remove_unlimited"]');if(response.remove.unlimited){if(self.expirationEdited==false||response.remove_override==0){if(removePointsUnlimited.prop('checked')==false){if(removePointsUnlimited.prop('disabled')==true){removePointsUnlimited.prop('disabled',false).click().prop('disabled',true);}else{removePointsUnlimited.click();}}}}else if(self.expirationEdited==false||response.remove_override==0){removePointsUnlimited.prop('checked',false);scope.find('[name="warn_remove"]').val(response.remove.date).prop('disabled',response.remove_override==0);scope.find('[name="warn_remove_time"]').val(response.remove.time).prop('disabled',response.remove_override==0);}
removePointsUnlimited.prop('disabled',response.remove_override==0);var cheevPoints=scope.find('[name="warn_cheeve_point_reduction"]');if(response.cheev_override==0){cheevPoints.prop('disabled',true);}else{cheevPoints.prop('disabled',false);}
cheevPoints.val(response.cheev_point_reduction);var editor=ips.ui.editorv5.getObj($('textarea[name="warn_member_note"]').closest('[data-ipsEditorv5]'));if(response.notes){var currentContents=editor.getInstance().getHTML();var previousContents=self.editorSetTo;editor.unminimize(function(){if(currentContents==previousContents){editor.reset();}else{editor.insertHtml('<p></p>');}
editor.insertHtml(response.notes);self.editorSetTo=editor.getInstance().getHTML();});}});},changePoints:function(e){this.pointsEdited=true;var scope=this.scope;ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=warnings&do=actionAjax&points='+$(e.target).val()+'&member='+scope.attr('data-member')).done(function(response){var types=['mq','rpa','suspend'];scope.find('ul#elWarningPenalties').remove();if(parseInt(response.override)){scope.find('li#form_warn_punishment .ipsFieldRow__content').show();}
else{scope.find('li#form_warn_punishment .ipsFieldRow__content').hide();var enforcedPenalties=[];for(var i=0;i<3;i++){if(parseInt(response.actions[types[i]].unlimited)){enforcedPenalties.push(ips.getString('warningPunishmentIndefinitely',{type:ips.getString('warningPunishment_'+types[i])}));}
else if(response.actions[types[i]].date!=""){var date=new Date(response.actions[types[i]].date+' '+response.actions[types[i]].time);enforcedPenalties.push(ips.getString('warningPunishmentDate',{type:ips.getString('warningPunishment_'+types[i]),date:ips.utils.time.localeDateString(date,{dateStyle:"long",timeStyle:"short"})}));}
scope.find('[name="warn_punishment['+types[i]+']"]').prop('checked',false).change();}
scope.find('li#form_warn_punishment').append(ips.templates.render('system.warningpenalty.nomodify',{penalties:enforcedPenalties}));}
for(var i=0;i<3;i++){if(parseInt(response.override)){scope.find('[name="warn_punishment['+types[i]+']"]').prop('checked',(response.actions[types[i]].date||response.actions[types[i]].unlimited)).change();}
scope.find('[name="warn_'+types[i]+'"]').val(response.actions[types[i]].date).prop('disabled',!parseInt(response.override));scope.find('[name="warn_'+types[i]+'_time"]').val(response.actions[types[i]].time).prop('disabled',!parseInt(response.override));scope.find('[name="warn_'+types[i]+'_unlimited"]').prop('checked',response.actions[types[i]].unlimited).prop('disabled',!parseInt(response.override));}});}});}(jQuery,_));;
var alert={type:'confirm',icon:'warn',message:ips.getString('generic_confirm'),subText:'',callbacks:{ok:function(){self.doAction(e,data);},no:function(){return;}}};ips.ui.alert.show(alert);},doAction:function(e,data){e.preventDefault();var element=$(e.target).closest('a');ips.getAjax()($(element).attr('href')+'&_fromApproval=1',{bypassRedirect:true}).done(function(){ips.getAjax()(ips.getSetting('baseURL')+'?app=core&module=modcp&controller=modcp&tab=approval&action=getCount').done(function(response){$('#elModCPApprovalCount').html(response.count);$(element).parents('[data-role="approvalItem"]').slideUp("slow",function(){$(this).remove();});}).fail(function(failresponse){window.location=ips.getSetting('baseURL')+'?app=core&module=modcp&controller=modcp&tab=approval';});}).fail(function(){window.location=$(e.currentTarget).attr('href');});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.reportToggle',{initialize:function(){this.on('click','[data-action="_ipsMenu_ping"]',this.reportToggleClicked);},reportToggleClicked:function(e){e.preventDefault();var elem=$(e.currentTarget);var reportId=this.scope.find('[data-reportId]').attr('data-reportId');var newStatus=$(elem).closest('[data-ipsMenuValue]').attr('data-ipsMenuValue');var newStatusText=$(elem).find('[data-role="ipsMenu_selectedText"]').text();if($(elem).attr('data-showconfirm')!==undefined){if($(elem).attr('data-hasNotifications')>0){var dialogRef=ips.ui.dialog.create({title:ips.getString('report_status_change_confirm',{newstatus:newStatusText}),size:'narrow',url:'?app=core&module=modcp&controller=modcp&tab=reports&action=reportCenterConfirmModal&id='+reportId+'&status='+newStatus,forceReload:true});dialogRef.show();}else{ips.ui.alert.show({type:'confirm',title:ips.getString('report_status_change_confirm',{newstatus:newStatusText}),icon:'fa fa-question-circle',buttons:{ok:ips.getString('ok'),cancel:ips.getString('cancel')},callbacks:{ok:function(){$(elem).attr('data-action','ipsMenu_ping');$(elem)[0].dispatchEvent(new Event("click",{bubbles:true}));},}});}}else{$(elem).attr('data-action','ipsMenu_ping');$(elem)[0].dispatchEvent(new Event("click",{bubbles:true}));}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.warnForm',{pointsEdited:false,expirationEdited:false,editorSetTo:'',initialize(){this.on('change','[name="warn_reason"]',this.changeReason);this.on('change','[name="warn_points"]',this.changePoints);this.on('change','[name="warn_remove"],[name="warn_remove_time"]',e=>{this.expirationEdited=true;});this.on('editorWidgetInitialized',this.editorInitialized);},editorInitialized(e,data){if(data.id==='warn_member_note'){$('[name="warn_reason"]').change();const editor=ips.ui.editorv5.getObj($('textarea[name="warn_member_note"]').closest('[data-ipsEditorv5]'));this.editorSetTo=editor.getInstance().getHTML();}},async changeReason(e){const response=await ips.fetch(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=warnings&do=reasonAjax&id='+$(e.target).val())
if(!this.pointsEdited||!response.points_override){const pointsNow=parseInt(this.scope.find('[name="warn_points"]').val());this.scope.find('[name="warn_points"]').val(response.points).prop('disabled',parseInt(response.points_override)===0);if(pointsNow!==response.points){this.scope.find('[name="warn_points"]').change();}
this.pointsEdited=false;}
const removePointsUnlimited=this.scope.find('[name="warn_remove_unlimited"]');if(response.remove.unlimited){if(!this.expirationEdited||!response.remove_override){if(!removePointsUnlimited.prop('checked')){if(removePointsUnlimited.prop('disabled')){removePointsUnlimited.prop('disabled',false).click().prop('disabled',true);}else{removePointsUnlimited.click();}}}}else if(!this.expirationEdited||!response.remove_override){removePointsUnlimited.prop('checked',false);this.scope.find('[name="warn_remove"]').val(response.remove.date).prop('disabled',!response.remove_override);this.scope.find('[name="warn_remove_time"]').val(response.remove.time).prop('disabled',!response.remove_override);}
removePointsUnlimited.prop('disabled',!response.remove_override);const cheevPoints=this.scope.find('[name="warn_cheeve_point_reduction"]');if(!response.cheev_override){cheevPoints.prop('disabled',true);}else{cheevPoints.prop('disabled',false);}
cheevPoints.val(response.cheev_point_reduction);const editor=ips.ui.editorv5.getObj($('textarea[name="warn_member_note"]').closest('[data-ipsEditorv5]'));if(response.notes){const currentContents=editor.getInstance().getHTML();const previousContents=this.editorSetTo;editor.unminimize(()=>{if(currentContents===previousContents){editor.reset();}else{editor.insertHtml('<p></p>');}
editor.insertHtml(response.notes);this.editorSetTo=editor.getInstance().getHTML();});}},async changePoints(e){this.pointsEdited=true;const response=await ips.fetch(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=warnings&do=actionAjax&points='+$(e.target).val()+'&member='+this.elem.dataset.member);const types=['mq','rpa','suspend'];this.elem.querySelectorAll('ul#elWarningPenalties').forEach(e=>e.remove());if(response.override){this.elem.querySelectorAll('li#form_warn_punishment .ipsFieldRow__content').ipsShow();}else{this.elem.querySelectorAll('li#form_warn_punishment .ipsFieldRow__content').ipsHide();const enforcedPenalties=[];types.forEach(type=>{if(parseInt(response.actions[type].unlimited)){enforcedPenalties.push(ips.getString('warningPunishmentIndefinitely',{type:ips.getString('warningPunishment_'+type)}));}
else if(response.actions[type].date!==""){const date=new Date(response.actions[type].date+' '+response.actions[type].time);enforcedPenalties.push(ips.getString('warningPunishmentDate',{type:ips.getString('warningPunishment_'+type),date:ips.utils.time.localeDateString(date,{dateStyle:"long",timeStyle:"short"})}));}
this.scope.find('[name="warn_punishment['+type+']"]').prop('checked',false).change();});this.scope.find('li#form_warn_punishment').append(ips.templates.render('system.warningpenalty.nomodify',{penalties:enforcedPenalties}));}
types.forEach(type=>{if(parseInt(response.override)){this.scope.find('[name="warn_punishment['+type+']"]').prop('checked',(response.actions[type].date||response.actions[type].unlimited)).change();}
this.scope.find('[name="warn_'+type+'"]').val(response.actions[type].date).prop('disabled',!parseInt(response.override));this.scope.find('[name="warn_'+type+'_time"]').val(response.actions[type].time).prop('disabled',!parseInt(response.override));this.scope.find('[name="warn_'+type+'_unlimited"]').prop('checked',response.actions[type].unlimited).prop('disabled',!parseInt(response.override));});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.warnPopup',{initialize:function(){this.on('click','[data-action="revoke"]',this.revokeWarning);},revokeWarning:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');ips.ui.alert.show({type:'verify',icon:'question',message:ips.getString('revokeWarning'),buttons:{yes:ips.getString('reverseAndDelete'),no:ips.getString('justDelete'),cancel:ips.getString('cancel')},callbacks:{yes:function(){window.location=url+'&undo=1';},no:function(){window.location=url+'&undo=0';}}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.reportList',{initialize:function(){this.on('menuItemSelected','[data-action="changeStatus"]',this.changeReportStatus);this.on('menuItemSelected','[data-role="filterButton"]',this.filterList);},changeReportStatus:function(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
var row=$(e.currentTarget).closest('.ipsData__item');row.removeClass('ipsData__item--warning');switch(data.selectedItemID){case'1':break;case'2':row.addClass('ipsData__item--warning');break;}},filterList:function(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.reportList',{initialize:function(){this.on('menuItemSelected','[data-action="changeStatus"]',this.changeReportStatus);this.on('menuItemSelected','[data-role="filterButton"]',this.filterList);},changeReportStatus:function(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
var row=$(e.currentTarget).closest('.ipsData__item');row.removeClass('ipsData__item--warning');switch(data.selectedItemID){case'1':break;case'2':row.addClass('ipsData__item--warning');break;}},filterList:function(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}
var filter=data.selectedItemID||'';var container=$(this.scope).find('[data-baseUrl]');ips.getAjax()($(container).data('baseUrl'),{data:{filter:filter}}).done(function(response){$(container).replaceWith(response);$(document).trigger('contentChange',[container]);});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.modcp.announcementForm',{_lastValue:'',_textField:null,_timer:0,initialize:function(){this._textField=$('#elInput_announce_url');this.on('blur','#elInput_announce_url',this.fieldKeyUp);},fieldKeyUp:function(){clearTimeout(this._timer);this._timer=setTimeout(_.bind(this._checkPermissions,this),700);},_checkPermissions:function(){var value=this._textField.val().trim();if(value.length<3){return;}
ips.getAjax()('?app=core&module=system&controller=announcement&do=permissionCheck',{dataType:'json',data:{url:value}}).done(function(response){if(_.isUndefined(response.html)&&$('#elAnnouncementGroupWarning').length){$('#elAnnouncementGroupWarning').remove();}
+2 -2
View File
@@ -1,8 +1,8 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.front.profile.followers',{_feedID:null,initialize:function(){this.on(document,'followingItem',this.followUser);this.on('menuItemSelected',"[data-role='followOption']",this.toggleFollowOption);this.setup();},setup:function(){this._feedID=this.scope.attr('data-feedID');},followUser:function(e,data){if(data.feedID!=this._feedID){return;}
var self=this;var memberID=data.feedID.replace('member-','');ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=members&controller=profile&do=followers&id='+parseInt(memberID)).done(function(response){self.scope.html(response);}).fail(function(){Debug.log('Error fetching follower HTML');});},toggleFollowOption:function(e,data){data.originalEvent.preventDefault();var url=data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"] a').attr('href');ips.getAjax()(url).done(function(response){ips.ui.flashMsg.show(ips.getString('followerSettingToggled'));}).fail(function(){window.location=url;});}});}(jQuery,_));;
var self=this;var memberID=data.feedID.replace('member-','');ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=members&controller=profile&do=followers&id='+parseInt(memberID)).done(function(response){self.scope.html(response);}).fail(function(){Debug.log('Error fetching follower HTML');});},toggleFollowOption:function(e,data=e.detail){data.originalEvent.preventDefault();var url=$(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"]').attr('href');ips.getAjax()(url).done(function(response){ips.ui.flashMsg.show(ips.getString('followerSettingToggled'));}).fail(function(){window.location=url;});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.profile.toggleBlock',{initialize:function(){this.on('click','[data-action="disable"]',this.toggleBlock);this.on('click','[data-action="enable"]',this.toggleBlock);},toggleBlock:function(e){e.preventDefault();var self=this;this.scope.css({opacity:"0.6"});ips.getAjax()($(e.currentTarget).attr('href'),{showLoading:true}).done(function(response){self.scope.html(response);$(document).trigger('contentChange',[self.scope]);}).fail(function(){window.location=$(e.currentTarget).attr('href');}).always(function(){self.scope.css({opacity:"1"});});}});}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register('core.front.profile.main',{contentArea:null,lastType:null,initialize(){this.on('click','[data-action="goToProfile"]',this.changeType);this.on('click','[data-action="browseContent"]',this.changeType);this.on('click','[data-action="repLog"]',this.changeType);this.on('click','[data-action="badgeLog"]',this.changeType);this.on('click','[data-action="solutionLog"]',this.changeType);this.on(window,'historychange',this.stateChange);this.setup();},_getHistoryStateFromPage(){const elem=this.scope.get(0)
const selectorMap={browseContent:'#elUserContent',repLog:'#elUserReputation',badgeLog:'.cProfileBadgeGrid'}
const selectorMap={browseContent:'#elUserContent',repLog:'#elUserReputation',badgeLog:'.cProfileBadgeGrid',solutionLog:'#elUserSolutions'}
for(const state in selectorMap){if(elem.querySelector(selectorMap[state])){return state}}
return"goToProfile"},setup(){this.contentArea=this.scope.find('[data-role="profileContent"]');this.contentHeader=this.scope.find('[data-role="profileHeader"]');if(!ips.utils.history.getState('profile')?.section){ips.utils.history.replaceState({section:this._getHistoryStateFromPage()},'profile',window.location.href);}},stateChange(e){if(e.detail?.type==='load'||e.detail?.type==='replace'){return}
const url=window.location.href
+7 -5
View File
@@ -1,12 +1,14 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.front.search.filters',{initialize:function(){this.on('click','[data-action="showFilters"]',this.showFilters);this.on('click','[data-action="searchByTags"]',this.toggleSearchFields);this.on('click','[data-action="searchByAuthors"]',this.toggleSearchFields);this.on('click','[data-action="cancelFilters"]',this.cancelFilters);this.on('change','input[name="type"]',this.toggleFilterByCounts);this.on('itemClicked.sideMenu','[data-filterType="dateCreated"]',this.filterDate);this.on('itemClicked.sideMenu','[data-filterType="dateUpdated"]',this.filterDate);this.on('itemClicked.sideMenu','[data-filterType="joinedDate"]',this.filterDate);this.on('change','[name^="search_min_"]',this.changeValue);this.on('tokenDeleted tokenAdded',this.tokenChanged);this.on('resultsLoading.search',this.resultsLoading);this.on('resultsDone.search',this.resultsDone);this.on('cancelResults.search',this.cancelResults);this.on('submit',this.submitForm);this.on('tabShown',this.tabShown);this.on('nodeInitialValues',this.setup);if(!this.scope.find('[data-role="hints"] ul li').length){this.scope.find('[data-role="hints"]').hide();}
this.setup();},setup:function(){var data=this.scope.find('form').serializeArray();this.trigger('initialData.search',{data:data});this.toggleFilterByCounts();},toggleFilterByCounts:function(){var type=this.scope.find('input[name="type"]:checked').val();if(!type){$('#elSearch_filter_by_number').hide();}else{$('#elSearch_filter_by_number').show();}},cancelResults:function(){this.showFilters();this.scope.find('[data-role="hints"]').remove();this.scope.find('#elMainSearchInput').val('').focus();this.scope.find('[data-action="cancelFilters"], [data-action="searchAgain"]').hide();},changeValue:function(e){var field=$(e.currentTarget);var name=field.attr('name');var bubble=this.scope.find('[data-role="'+name+'_link"] [data-role="fieldCount"]');if(field.val()==0){bubble.text('0').addClass('ipsHide');}else{bubble.text(field.val()).removeClass('ipsHide');}},tokenChanged:function(e,data){var tags=this.scope.find('input[name="tags"]');var term=this.scope.find('input[name="q"]');var andOr=this.scope.find('[data-role="searchTermsOrTags"]');if(tags.val()&&term.val()&&!andOr.is(':visible')){andOr.slideDown();}else if((!tags.val()||!term.val())&&andOr.is(':visible')){andOr.slideUp();}},tabShown:function(e,data){if(data.tabID=='ipsTabs_search_searchMembers'){this.scope.find('input[name="type"][value="core_members"]').prop('checked',true).change().end().find('[data-action="updateResults"]').text(ips.getString('searchMembers'));}else{this.scope.find('[data-role="searchApp"] .ipsSideMenu_itemActive input[type="radio"]').prop('checked',true).change().end().find('[data-action="updateResults"]').text(ips.getString("searchContent"));}},cancelFilters:function(e){var self=this;this.scope.find('[data-role="searchFilters"]').slideUp('fast',function(){self.scope.find('[data-action="showFilters"]').slideDown();});},showFilters:function(e){if(e){e.preventDefault();}
;(function($,_,undefined){"use strict";ips.controller.register('core.front.search.filters',{initialize:function(){this.on('click','[data-action="showFilters"]',this.showFilters);this.on('click','[data-action="searchByTags"]',this.toggleSearchFields);this.on('click','[data-action="searchByAuthors"]',this.toggleSearchFields);this.on('click','[data-action="cancelFilters"]',this.cancelFilters);this.on('ips:refreshTogglesDone',this.toggleFilterByCounts);this.on('itemClicked.sideMenu','[data-filterType="dateCreated"]',this.filterDate);this.on('itemClicked.sideMenu','[data-filterType="dateUpdated"]',this.filterDate);this.on('itemClicked.sideMenu','[data-filterType="joinedDate"]',this.filterDate);this.on('change','[name^="search_min_"]',this.changeValue);this.on('tokenDeleted tokenAdded',this.tokenChanged);this.on('resultsLoading.search',this.resultsLoading);this.on('resultsDone.search',this.resultsDone);this.on('cancelResults.search',this.cancelResults);this.on('submit',this.submitForm);this.on('tabShown',this.tabShown);this.on('nodeInitialValues',this.setup);if(!this.scope.find('[data-role="hints"] ul li').length){this.scope.find('[data-role="hints"]').hide();}
this.setup();},setup:function(){var data=this.scope.find('form').serializeArray();this.trigger('initialData.search',{data:data});this.toggleFilterByCounts();},toggleFilterByCounts:function(){const searchTitleEl=document.getElementById('elSearch_filter_by_number');if(!searchTitleEl){return;}
const searchByNumberOptions=document.querySelector("#elSearch_filter_by_number + ul");if(!searchByNumberOptions||!searchByNumberOptions.querySelector(':scope > :not([hidden])')){searchTitleEl.hidden=true;}else{searchTitleEl.hidden=!this.elem.querySelector('input[name="type"]:checked').value;}},cancelResults:function(){this.showFilters();this.scope.find('[data-role="hints"]').remove();this.scope.find('#elMainSearchInput').val('').focus();this.scope.find('[data-action="cancelFilters"], [data-action="searchAgain"]').hide();},changeValue:function(e){var field=$(e.currentTarget);var name=field.attr('name');var bubble=this.scope.find('[data-role="'+name+'_link"] [data-role="fieldCount"]');if(field.val()==0){bubble.text('0').addClass('ipsHide');}else{bubble.text(field.val()).removeClass('ipsHide');}},tokenChanged:function(e,data){var tags=this.scope.find('#elInput_tags_wrapper li.cToken');var term=this.scope.find('input[name="q"]');var andOr=this.scope.find('[data-role="searchTermsOrTags"]');if(tags.length&&term.val()&&!andOr.is(':visible')){andOr.slideDown();}else if((!tags.length||!term.val())&&andOr.is(':visible')){andOr.slideUp();}},tabShown:function(e,data){if(data.tabID=='ipsTabs_search_searchMembers'){this.scope.find('input[name="type"][value="core_members"]').prop('checked',true).change().end().find('[data-action="updateResults"]').text(ips.getString('searchMembers'));}else{this.scope.find('[data-role="searchApp"] .ipsSideMenu_itemActive input[type="radio"]').prop('checked',true).change().end().find('[data-action="updateResults"]').text(ips.getString("searchContent"));}},cancelFilters:function(e){var self=this;this.scope.find('[data-role="searchFilters"]').slideUp('fast',function(){self.scope.find('[data-action="showFilters"]').slideDown();});},showFilters:function(e){if(e){e.preventDefault();}
this.scope.find('[data-action="showFilters"]').hide();this.scope.find('[data-role="searchFilters"]').slideDown();$(document).trigger('contentChange',[this.scope]);},resultsDone:function(e,data){var searchButton=this.scope.find('[data-action="updateResults"]');searchButton.prop('disabled',false).text(searchButton.attr('data-originalText'));this.scope.find('[data-role="searchFilters"]').hide();this.scope.find('[data-action="showFilters"]').removeClass('ipsHide').show();this.scope.find('[data-action="searchAgain"]').removeClass('ipsHide ipsButton--disabled').show();if(!_.isUndefined(data.hints)){this.scope.find('[data-role="hints"]').html(data.hints).show();}
if(!this.scope.find('[data-role="hints"] ul li').length){this.scope.find('[data-role="hints"]').hide();}
$(document).trigger('contentChange',[this.scope]);},resultsLoading:function(e,data){var searchButton=this.scope.find('[data-action="updateResults"]');this.scope.find('[data-action="searchAgain"]').addClass('ipsButton--disabled');searchButton.prop('disabled',true).attr('data-originalText',searchButton.text()).text(ips.getString("searchFetchingResults"));},toggleSearchFields:function(e){e.preventDefault();var link=$(e.currentTarget);var opens=link.attr('data-opens').split(',');var i;for(i=0;i<opens.length;i++){this.scope.find('[data-role="'+opens[i]+'"]').slideDown(function(){if(!link.closest('ul').find('li').length){link.closest('ul').remove();}
$(this).find('input[type="text"]').focus();});}
link.closest('li').hide();},filterDate:function(e,data){var elem=$(e.currentTarget);if(data.selectedItemID=='custom'){elem.find('[data-role="dateForm"]').slideDown();}else{elem.find('[data-role="dateForm"]').slideUp();}},submitForm:function(e){e.preventDefault();this.scope.find('#elMainSearchInput').blur();var self=this;var app=this.scope.find('[data-role="searchApp"] .ipsSideMenu_itemActive');var appKey=app.attr('data-ipsMenuValue');var appTitle=app.find('[data-role="searchAppTitle"]').text();var isMemberSearch=$('#ipsTabs_search_searchMembers').attr('aria-selected')=='true';var searchTerm=this.scope.find('#elMainSearchInput').val().trim();var tagExists=(this.scope.find('#elInput_tags').length&&this.scope.find('#ipsTabs_search_searchContent').attr('aria-selected')==='true');if(tagExists){var tagField=ips.ui.autocomplete.getObj(this.scope.find('#elInput_tags'));var tokens=tagField.getTokens();}
if(!isMemberSearch){if(!searchTerm&&!tagExists||!searchTerm&&tagExists&&tokens.length===0){ips.ui.alert.show({type:'alert',message:(!searchTerm&&!tagExists)?ips.getString('searchRequiresTerm'):ips.getString('searchRequiresTermTags'),icon:'info',callbacks:{ok:function(){setTimeout(function(){self.scope.find('#elMainSearchInput').focus();},300);}}});return;}}
this.trigger('formSubmitted.search',{data:this.scope.find('form').serializeArray(),appKey:appKey,tabType:this.scope.closest('data-tabType').attr('data-tabType'),appTitle:appTitle});}});}(jQuery,_));;
if(!isMemberSearch){if((!searchTerm&&!tagExists)||(!searchTerm&&tagExists&&tokens.length===0)){ips.ui.alert.show({type:'alert',message:(!searchTerm&&!tagExists)?ips.getString('searchRequiresTerm'):ips.getString('searchRequiresTermTags'),icon:'info',callbacks:{ok:function(){setTimeout(function(){self.scope.find('#elMainSearchInput').focus();},300);}}});return;}}
const el=document.createElement('div');const data=this.scope.find('form').serializeArray();const tagsObject=data.find(item=>item.name==='tags');if(tagsObject){el.innerHTML=tagsObject.value;tagsObject.value=el.textContent;}
this.trigger('formSubmitted.search',{data,appKey:appKey,tabType:this.scope.closest('data-tabType').attr('data-tabType'),appTitle:appTitle});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.search.main',{_content:null,_formData:{},_loadingDiv:null,_initialURL:'',_initialData:{},initialize(){this.on('initialData.search',this.initialData);this.on('formSubmitted.search',this.submittedSearch);this.on('paginationClicked paginationJump',this.paginationClicked);this.on(window,'historychange:search',this.stateChange);this.setup();},setup(){this._content=this.scope.find('#elSearch_main');this._baseURL=this.scope.attr('data-baseURL');if(this._baseURL.match(/\?/)){this._baseURL+='&';}else{this._baseURL+='?';}
if(this._baseURL.slice(-1)==='&'){this._baseURL=this._baseURL.slice(0,-1)}
this._initialURL=window.location.href;},initialData(e,data){this._formData=this._getFormData(data.data);this._initialData=_.clone(this._formData);},stateChange(){const state={data:ips.utils.history.getState('search'),url:window.location.href};if(this._initialURL===state.url&&!Object.keys(state.data).length){this._cancelSearch();}else if(this._initialURL===state.url&&state.data.url===undefined){this._loadResults(this._getUrlFromData(this._initialData));}else{this._loadResults(state.data.url);}},submittedSearch(e,data){this._formData=this._getFormData(data.data);const url=this._getUrlFromData(this._formData);try{if(IpsDataLayerContext&&!window.IpsDataLayerContext){let unique='';let self=this;Object.keys(this._formData).sort().forEach(function(index){let value=self._formData[index];if(value.join){value=value.join();}
@@ -18,7 +20,7 @@ if(!_.isUndefined(data['group'])){if(!_.isArray(data['group'])){data['group']=[d
for(var i=0;i<data['group'].length;i++){params.push('group['+data['group'][i]+']=1');}}
_.each(data,function(val,key){if(!key.startsWith('core_pfield')||val===0||val===''){return;}
params.push(key+'='+val);});}else{_.each(['item','author','search_min_replies','search_min_views','search_min_comments','search_min_reviews'],function(val){if(!_.isUndefined(data[val])&&data[val]!==''&&parseInt(data[val])!==0){if(val==='author'){params.push(val+'='+encodeURIComponent(data[val]));return;}
params.push(val+'='+data[val]);}});if(!_.isUndefined(data['tags'])){params.push('tags='+data['tags'].replace(/\n/g,','));}
params.push(val+'='+data[val]);}});if(!_.isUndefined(data['tags'])){params.push('tags='+encodeURIComponent(data['tags'].replace(/\n/g,',')));}
if(!_.isUndefined(data['nodes'])){params.push('nodes='+data['nodes'].replace(/\n/g,','));}
else if(!_.isUndefined(data[data['type']+'_node'])){params.push('nodes='+data[data['type']+'_node']);}
if(!_.isUndefined(data['club[]'])){if(_.isArray(data['club[]'])){params.push('club='+data['club[]'].filter(function(v){return v!=='__EMPTY';}));}else if(data['club[]'].replace('__EMPTY','')){params.push('club='+data['club[]'].replace('__EMPTY',''));}}
+14 -15
View File
@@ -12,8 +12,8 @@ ips.templates.set('core.streams.teaser',`
<a href='#' class='ipsButton ipsButton--inherit' data-action='loadMore'>{{#lang}}loadNewActivity{{/lang}}</a>
`);;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.streams.form',{loaded:{},formSnapshot:false,reloaded:false,_loadedContainer:{},_loadedClubs:false,_formData:{},initialize:function(){this.on('streamStateUpdate.streamForm',this.streamStateUpdate);this.on('itemClicked.sideMenu','[data-filterType="type"]',this.selectedType);this.on('menuItemSelected','#elStreamReadStatus, #elStreamShowMe',this.checkFormUpdate);this.on('tokenAdded tokenDeleted',this.tokensChanged);this.on('menuItemSelected','#elStreamSortEdit',this.changeSort);this.on('click','[data-action="saveStream"], [data-action="newStream"]',this.submitForm);this.on('click','[data-role="streamContainer"]',this.openStreamContainer);this.on('click','[data-role="streamClubs"]',this.openStreamClubs);this.on('click','[data-action="dismissSave"]',this.dismissSave);this.on('keydown','input',this.inputKeydown);if(this.scope.attr('data-formType')=='createStream'){this.on('itemClicked.sideMenu','[data-filterType="date"]',this.selectedDate);this.on('itemClicked.sideMenu','[data-filterType="ownership"]',this.selectedOwnership);}else{this.on('menuItemSelected','#elStreamFollowStatus',this.selectedFollowStatus);this.on('menuItemSelected','#elStreamTimePeriod',this.selectedDate);this.on('menuItemSelected','#elStreamOwnership',this.selectedOwnership);}
this.on('change','#elSelect_stream_club_filter',this.clubSelectionChanged);this.on('change','#stream_club_filter_unlimited',this.clubSelectionChanged);this.on('nodeItemSelected',this.toggleApplyFilterButton);this.on('nodeItemUnselected',this.toggleApplyFilterButton);this.on('click','[data-action="applyFilters"]',this.applyFilters);this.on('menuItemSelected','#elStreamSortEdit, #elStreamFollowStatus',this.selectedMenuItem);this.on('menuItemSelected','#elStreamTimePeriod, #elStreamOwnership, #elStreamShowMe',this.selectedMenuItem);this.on('menuItemSelected','#elStreamReadStatus',this.selectedReadStatus);this.on('menuClosed',this.menuClosed);this.setup();},setup:function(){this._serializeConfig={'stream_date_range[start]':this._serializeDate,'stream_date_range[end]':this._serializeDate};if(this.scope.attr('data-formType')!='createStream'){this._formData=ips.getSetting('stream_config');this._changeReadStatus(this._formData['stream_read']);this._updateFilterOverview();this.takeFormSnapshot();}
this.trigger('initialFormData.stream',{data:this._formData});},inputKeydown:function(e){if(e.which==13){e.preventDefault();}},toggleApplyFilterButton:function(e){var button=$('.ipsMenu').filter(':visible').first().find('[data-action="applyFilters"]');if(this.hasFormChanged()){button.removeClass('ipsButton--disabled');}else{button.addClass('ipsButton--disabled');}},applyFilters:function(e){var button=$(e.currentTarget);button.closest('.ipsMenu').trigger('closeMenu');},streamStateUpdate:function(e,data){this._formData=data.filterData;this._updateFieldValues();if(!_.isUndefined(data.hideSaveBar)&&data.hideSaveBar){this.scope.find('[data-role="saveButtonContainer"]').slideUp();}else{this.scope.find('[data-role="saveButtonContainer"]').slideDown();}},_updateFilterOverview:function(){if(this.scope.attr('data-formType')=='createStream'){return;}
this.on('change','#elSelect_stream_club_filter',this.clubSelectionChanged);this.on('change','#stream_club_filter_unlimited',this.clubSelectionChanged);this.on('menuItemSelected','#elStreamSortEdit, #elStreamFollowStatus',this.selectedMenuItem);this.on('menuItemSelected','#elStreamTimePeriod, #elStreamOwnership, #elStreamShowMe',this.selectedMenuItem);this.on('menuItemSelected','#elStreamReadStatus',this.selectedReadStatus);this.on('menuClosed',this.menuClosed);this.setup();},setup:function(){this._serializeConfig={'stream_date_range[start]':this._serializeDate,'stream_date_range[end]':this._serializeDate};if(this.scope.attr('data-formType')!='createStream'){this._formData=ips.getSetting('stream_config');this._changeReadStatus(this._formData['stream_read']);this._updateFilterOverview();this.takeFormSnapshot();}
this.trigger('initialFormData.stream',{data:this._formData});},inputKeydown:function(e){if(e.which==13){e.preventDefault();}},streamStateUpdate:function(e,data){this._formData=data.filterData;this._updateFieldValues();if(!_.isUndefined(data.hideSaveBar)&&data.hideSaveBar){this.scope.find('[data-role="saveButtonContainer"]').slideUp();}else{this.scope.find('[data-role="saveButtonContainer"]').slideDown();}},_updateFilterOverview:function(){if(this.scope.attr('data-formType')=='createStream'){return;}
var self=this;var values=this._formData;var _overview=function(type){return self.scope.find('[data-filter="'+type+'"] [data-role="filterOverview"]');};_.each(['stream_include_comments','stream_read','stream_sort','stream_solved'],function(val){var lang='streamFilter_'+val+'_'+values[val];_overview(val).html(ips.getString(lang));});if(!_.isUndefined(values['stream_tags'])&&values['stream_tags'].trim()!==''){var tags=_.compact(values['stream_tags'].split(/\n/));if(tags.length<=2){var tagLang=ips.getString('streamFilter_stream_tags_tags',{'tags':_.escape(tags.join(','))});}else{var tagLang=ips.pluralize(ips.getString('streamFilter_stream_tags_count'),tags.length);}
_overview('stream_include_comments').append('; '+tagLang);}else{_overview('stream_include_comments').append('; '+ips.getString('streamFilter_stream_tags_noTags'));}
if(values['stream_ownership']=='custom'&&(_.isUndefined(values['stream_custom_members'])||values['stream_custom_members']==null||values['stream_custom_members']=='')){values['stream_ownership']='all'}
@@ -29,19 +29,18 @@ _overview('stream_date_type').text(dateLang);}
if(!values['stream_classes']||values['stream_classes_type']==0){if(values['stream_club_select']=='none'){_overview('stream_classes').html(ips.getString('streamFilter_stream_classes_no_clubs'));}else if(values['stream_club_select']=='all'){_overview('stream_classes').html(ips.getString('streamFilter_stream_classes_all'));}else if(values['stream_club_filter']){_overview('stream_classes').text(ips.getString('loading'));this._loadClubs(function(){var elem=this.scope.find('#elSelect_stream_club_filter');var clubIds=values['stream_club_filter'].split(',');var clubNames=[];for(var i=0;i<clubIds.length;i++){var option=elem.find('option[value="'+clubIds[i]+'"]');if(option.length){clubNames.push(option.text().trim());}}
_overview('stream_classes').text(clubNames.join(', '));}.bind(this));}}else{var classKeys=_.keys(values['stream_classes']);var classes=[];for(var i=0;i<classKeys.length;i++){var elem=this.scope.find('[data-class="'+classKeys[i].replace(/\\/g,'\\\\')+'"] > span');if(elem.length){classes.push(elem.text().trim());}}
_overview('stream_classes').text(classes.join(', '));}},_updateFieldValues:function(){var self=this;var data=this._formData;if(data['stream_read']=='unread'){data['stream_include_comments']=0;}
_.each(['stream_include_comments','stream_read','stream_sort','stream_follow','stream_ownership','stream_date_type'],function(key){self.scope.find('[name="'+key+'"]').prop('checked',false).closest('.ipsMenu_item').removeClass('ipsMenu_itemChecked').end().filter('[value="'+data[key]+'"]').prop('checked',true).change().closest('.ipsMenu_item').addClass('ipsMenu_itemChecked');});var followSelector=_.map(data['stream_followed_types'],function(val,key){return'[name="stream_followed_types['+key+']"]';});this.scope.find('[name^="stream_followed_types"]').prop('checked',false).closest('.ipsMenu_item').removeClass('ipsMenu_itemChecked').end().filter(followSelector.join(',')).prop('checked',true).change().closest('.ipsMenu_item').addClass('ipsMenu_itemChecked');if(this.scope.find('#elInput_stream_custom_members').length){var ownerAC=ips.ui.autocomplete.getObj(this.scope.find('#elInput_stream_custom_members'));ownerAC.removeAll();if(data['stream_ownership']=='custom'){var names=_.compact(data['stream_custom_members'].split(/\n/));for(var i=0;i<names.length;i++){ownerAC.addToken(names[i]);}}}
_.each(['stream_include_comments','stream_read','stream_sort','stream_follow','stream_ownership','stream_date_type'],function(key){self.scope.find('[name="'+key+'"]').prop('checked',false).filter('[value="'+data[key]+'"]').prop('checked',true).change();});var followSelector=_.map(data['stream_followed_types'],function(val,key){return'[name="stream_followed_types['+key+']"]';});this.scope.find('[name^="stream_followed_types"]').prop('checked',false).filter(followSelector.join(',')).prop('checked',true).change();if(this.scope.find('#elInput_stream_custom_members').length){var ownerAC=ips.ui.autocomplete.getObj(this.scope.find('#elInput_stream_custom_members'));ownerAC.removeAll();if(data['stream_ownership']=='custom'){var names=_.compact(data['stream_custom_members'].split(/\n/));for(var i=0;i<names.length;i++){ownerAC.addToken(names[i]);}}}
if(!_.isUndefined(data['stream_tags'])){var tags=_.compact(data['stream_tags'].split(/\n/));var tagAC=ips.ui.autocomplete.getObj(this.scope.find('#elInput_stream_tags'));tagAC.removeAll();if(tags.length){for(var i=0;i<tags.length;i++){tagAC.addToken(tags[i]);}}}
this.scope.find('[name="stream_date_relative_days"], [name="stream_date_range[start]"], [name="stream_date_range[end]"]').val('');if(data['stream_date_type']=='relative'){this.scope.find('[name="stream_date_relative_days"]').val(data['stream_date_relative_days']);}else if(data['stream_date_type']=='custom'){var html5=ips.utils.time.supportsHTMLDate();if(data['stream_date_range']['start']){var startDateObj=new Date(data['stream_date_range']['start']);if(html5){this.scope.find('[name="stream_date_range[start]"]').get(0).valueAsDate=startDateObj;}else{this.scope.find('[name="stream_date_range[start]"]').datepicker('setDate',ips.utils.time.removeTimezone(startDateObj));}}
if(data['stream_date_range']['end']){var endDateObj=new Date(data['stream_date_range']['end']);if(html5){this.scope.find('[name="stream_date_range[end]"]').get(0).valueAsDate=endDateObj;}else{this.scope.find('[name="stream_date_range[end]"]').datepicker('setDate',ips.utils.time.removeTimezone(endDateObj));}}}
var classChecks=$('#elStreamContentTypes_menu').find('[type="checkbox"][name^="stream_classes"]');var classSelector=[];classChecks.prop('checked',false).change().closest('.ipsSideMenu_item').removeClass('ipsSideMenu_itemActive');if(data['stream_classes_type']==0){this.scope.find('[name="stream_classes_type"]').first().closest('.ipsSideMenu_item').addClass('ipsSideMenu_itemActive');}else{var classKeys=_.keys(data['stream_classes']);_.each(classKeys,function(val){self.scope.find('[data-class="'+val.replace(/\\/g,'\\\\')+'"] input[type="checkbox"]').prop('checked',true).change().closest('.ipsSideMenu_item').addClass('ipsSideMenu_itemActive');});}
this._updateFilterOverview();},openStreamContainer:function(e,data){e.preventDefault();var self=this;var link=$(e.currentTarget);var className=link.attr('data-class');var contentKey=link.attr('data-contentKey');var nodeContainer=link.next('.cStreamForm_nodes');if(!this._loadedContainer[className]){nodeContainer.slideDown();var containers=[];if(_.isObject(ips.getSetting('stream_config'))&&!_.isEmpty(ips.getSetting('stream_config')['containers'])){var keys=_.keys(ips.getSetting('stream_config')['containers']);var values=_.values(ips.getSetting('stream_config')['containers']);for(var i=0;i<keys.length;i++){containers.push('stream_containers['+keys[i]+']='+values[i]);}}
ips.getAjax()(this.scope.find('form').attr('action').replace('do=create',''),{type:'post',data:'do=getContainerNodeElement&className='+className+'&key='+contentKey+'&'+containers.join('&')}).done(function(returnedData){nodeContainer.html(returnedData.node);self._loadedContainer[className]=true;$(document).trigger('contentChange',[nodeContainer.parent()]);});}else{nodeContainer.slideToggle();}},openStreamClubs:function(e,data){e.preventDefault();var clubContainer=$('#elStreamClubs');if(!this._loadedClubs){clubContainer.slideDown();this._loadClubs(null);}else{clubContainer.slideToggle();}},_loadClubs:function(callback){if(!this._loadedClubs){var clubContainer=$('#elStreamClubs');var extra=null;if(_.isObject(ips.getSetting('stream_config'))){extra='&stream_club_select='+ips.getSetting('stream_config')['stream_club_select']+'&stream_club_filter='+ips.getSetting('stream_config')['stream_club_filter'];}
var self=this;ips.getAjax()(this.scope.find('form').attr('action').replace('do=create',''),{type:'post',data:'do=getClubElement&'+extra}).done(function(returnedData){clubContainer.html(returnedData.field);self._loadedClubs=true;$(document).trigger('contentChange',[clubContainer.parent()]);if(callback){callback();}});}else if(callback){callback();}},menuClosed:function(e,data){if(data.elemID=='elStreamContentTypes'||($('#'+data.elemID+'_menu').length&&data.elemID!='elSaveStream')){_.delay(function(self){$('[data-action="applyFilters"]').addClass('ipsButton--disabled');self.checkFormUpdate();self.reloaded=true;},500,this);}},checkFormUpdate:function(){if(this.hasFormChanged()){this.updateResults();this.scope.find('#elSaveStream').removeClass('i-opacity_4');this.takeFormSnapshot();}},hasFormChanged:function(){if(_.isEqual(this.formSnapshot,ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig))){return false;}
return true;},takeFormSnapshot:function(){this.formSnapshot=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);},tokensChanged:function(){this.reloaded=false;},changeSort:function(e,data){this.checkFormUpdate();},selectedMenuItem:function(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}},selectedReadStatus:function(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
this._changeReadStatus(data.selectedItemID);},_changeReadStatus:function(type){if(type=='unread'){this._formData['stream_include_comments']=0;this.scope.find('#stream_ownership_0').closest('a').trigger('click');this.scope.find('#elStreamShowMe_menu li[data-ipsmenuvalue=1]').addClass('ipsMenu_itemDisabled');}else{this.scope.find('#elStreamShowMe_menu li[data-ipsmenuvalue=1]').removeClass('ipsMenu_itemDisabled');}},dismissSave:function(e){e.preventDefault();this.scope.find('[data-role="saveButtonContainer"]').slideUp();},submitForm:function(e){var button=$(e.currentTarget);var form=button.closest('form');if(this.scope.attr('data-formType')=='createStream'){return;}
if(button.attr('data-action')=='newStream'){form.prepend($('<input />').attr('type','hidden').attr('name','do').attr('value','create'));}else{this._formData=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);this.trigger('formSubmitted.stream',{data:this._formData,action:(button.attr('data-action')=='newStream')?'createForm':'saveForm'});}},updateResults:function(){this._formData=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);this._updateFilterOverview();this.trigger('formSubmitted.stream',{data:this._formData,action:'updateForm'});},selectedDate:function(e,data){this.reloaded=false;if(data.selectedItemID=='custom'){this.scope.find('[data-role="dateRelativeForm"]').slideUp();this.scope.find('[data-role="dateForm"]').slideDown();}else if(data.selectedItemID=='relative'){this.scope.find('[data-role="dateForm"]').slideUp();this.scope.find('[data-role="dateRelativeForm"]').slideDown();this.scope.find('[name="stream_date_relative_days"]').focus();}else{if(!_.isUndefined(data.selectedItemID)){this.scope.find('[data-role="dateForm"]').slideUp();this.scope.find('[data-role="dateRelativeForm"]').slideUp();this.checkFormUpdate();}}},selectedFollowStatus:function(e,data){var selectedItems=data.selectedItems;if(!_.size(selectedItems)){this.scope.find('[name="stream_follow"]').val('all');}else{this.scope.find('[name="stream_follow"]').val('followed');}
this.checkFormUpdate();},selectedOwnership:function(e,data){if(data.selectedItemID=='custom'){this.scope.find('[data-role="ownershipMemberForm"]').slideDown();}else{if(!_.isUndefined(data.selectedItemID)){this.scope.find('[data-role="ownershipMemberForm"]').slideUp();this.checkFormUpdate();}}},clubSelectionChanged:function(e,data){if(this.scope.find('[name="stream_club_filter_dummy_unlimited"]').is(':checked')){this.scope.find('[name="stream_club_select"]').val('all');}else{this.scope.find('[name="stream_club_select"]').val('select');this.scope.find('[name="stream_club_filter"]').val($('#elSelect_stream_club_filter').val());}
this.toggleApplyFilterButton();},selectedType:function(e,data){var self=this;var typeMenu=this.scope.find('[data-filterType="type"]');var all=typeMenu.find('[data-ipsMenuValue="__all"]');var allButAll=typeMenu.find('[data-ipsMenuValue]:not( [data-ipsMenuValue="__all"] )');var allButAllChecks=allButAll.find('> input[type="checkbox"]');this.reloaded=false;this.toggleApplyFilterButton();if(data.selectedItemID=='__all'){allButAll.removeClass('ipsSideMenu_itemActive').find('> input[type="checkbox"]').prop('checked',false);all.addClass('ipsSideMenu_itemActive');this.scope.find('input[type="radio"][name="stream_classes_type"][value="0"]').prop('checked',true);this.scope.find('[data-contentType]').closest('.cStreamForm_nodes').slideUp();}else{if(allButAllChecks.filter(':checked').length){all.removeClass('ipsSideMenu_itemActive')
ips.getAjax()(this.scope.find('form').attr('action').replace('do=create',''),{type:'post',data:'do=getContainerNodeElement&className='+className+'&key='+contentKey+'&'+containers.join('&')}).done(function(returnedData){nodeContainer.html(returnedData.node);self._loadedContainer[className]=true;$(document).trigger('contentChange',[nodeContainer.parent()]);});}else{nodeContainer.slideToggle();}},openStreamClubs:function(e){e.preventDefault();var clubContainer=$('#elStreamClubs');if(!this._loadedClubs){clubContainer.slideDown();this._loadClubs(null);}else{clubContainer.slideToggle();}},_loadClubs:function(callback){if(!this._loadedClubs){var clubContainer=$('#elStreamClubs');var extra=null;if(_.isObject(ips.getSetting('stream_config'))){extra='&stream_club_select='+ips.getSetting('stream_config')['stream_club_select']+'&stream_club_filter='+ips.getSetting('stream_config')['stream_club_filter'];}
var self=this;ips.getAjax()(this.scope.find('form').attr('action').replace('do=create',''),{type:'post',data:'do=getClubElement&'+extra}).done(function(returnedData){clubContainer.html(returnedData.field);self._loadedClubs=true;$(document).trigger('contentChange',[clubContainer.parent()]);if(callback){callback();}});}else if(callback){callback();}},menuClosed:function(e,data=e.detail){if(data.elemID=='elStreamContentTypes'||($('#'+data.elemID+'_menu').length&&data.elemID!='elSaveStream')){_.delay(function(self){self.checkFormUpdate();self.reloaded=true;},500,this);}},checkFormUpdate:function(){if(this.hasFormChanged()){this.updateResults();this.scope.find('#elSaveStream').removeClass('i-opacity_4');this.takeFormSnapshot();}},hasFormChanged:function(){if(_.isEqual(this.formSnapshot,ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig))){return false;}
return true;},takeFormSnapshot:function(){this.formSnapshot=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);},tokensChanged:function(){this.reloaded=false;},changeSort:function(){this.checkFormUpdate();},selectedMenuItem:function(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}},selectedReadStatus:function(e,data=e.detail){if(data.originalEvent){}
this._changeReadStatus(data.selectedItemID);},_changeReadStatus:function(type){if(type=='unread'){this._formData['stream_include_comments']=0;this.scope.find('#stream_ownership_0').click();this.scope.find('#stream_ownership_1').attr('disabled',true);}else{this.scope.find('#stream_ownership_1').removeAttr('disabled');}},dismissSave:function(e){this.scope.find('[data-role="saveButtonContainer"]').slideUp();},submitForm:function(e){var button=$(e.currentTarget);var form=button.closest('form');if(this.scope.attr('data-formType')=='createStream'){return;}
if(button.attr('data-action')=='newStream'){form.prepend($('<input />').attr('type','hidden').attr('name','do').attr('value','create'));}else{this._formData=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);this.trigger('formSubmitted.stream',{data:this._formData,action:(button.attr('data-action')=='newStream')?'createForm':'saveForm'});}},updateResults:function(){this._formData=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);this._updateFilterOverview();this.trigger('formSubmitted.stream',{data:this._formData,action:'updateForm'});},selectedDate:function(e,data=e.detail){this.reloaded=false;if(data.selectedItemID=='custom'){this.scope.find('[data-role="dateRelativeForm"]').slideUp();this.scope.find('[data-role="dateForm"]').slideDown();}else if(data.selectedItemID=='relative'){this.scope.find('[data-role="dateForm"]').slideUp();this.scope.find('[data-role="dateRelativeForm"]').slideDown();this.scope.find('[name="stream_date_relative_days"]').focus();}else{if(!_.isUndefined(data.selectedItemID)){this.scope.find('[data-role="dateForm"]').slideUp();this.scope.find('[data-role="dateRelativeForm"]').slideUp();this.checkFormUpdate();}}},selectedFollowStatus:function(e,data=e.detail){var selectedItems=data.selectedItems;if(!_.size(selectedItems)){this.scope.find('[name="stream_follow"]').val('all');}else{this.scope.find('[name="stream_follow"]').val('followed');}
this.checkFormUpdate();},selectedOwnership:function(e,data=e.detail){if(data.selectedItemID=='custom'){this.scope.find('[data-role="ownershipMemberForm"]').slideDown();}else{if(!_.isUndefined(data.selectedItemID)){this.scope.find('[data-role="ownershipMemberForm"]').slideUp();this.checkFormUpdate();}}},clubSelectionChanged:function(){if(this.scope.find('[name="stream_club_filter_dummy_unlimited"]').is(':checked')){this.scope.find('[name="stream_club_select"]').val('all');}else{this.scope.find('[name="stream_club_select"]').val('select');this.scope.find('[name="stream_club_filter"]').val($('#elSelect_stream_club_filter').val());}},selectedType:function(e,data=e.detail){var self=this;var typeMenu=this.scope.find('[data-filterType="type"]');var all=typeMenu.find('[data-ipsMenuValue="__all"]');var allButAll=typeMenu.find('[data-ipsMenuValue]:not( [data-ipsMenuValue="__all"] )');var allButAllChecks=allButAll.find('> input[type="checkbox"]');this.reloaded=false;if(data.selectedItemID=='__all'){allButAll.removeClass('ipsSideMenu_itemActive').find('> input[type="checkbox"]').prop('checked',false);all.addClass('ipsSideMenu_itemActive');this.scope.find('input[type="radio"][name="stream_classes_type"][value="0"]').prop('checked',true);this.scope.find('[data-contentType]').closest('.cStreamForm_nodes').slideUp();}else{if(allButAllChecks.filter(':checked').length){all.removeClass('ipsSideMenu_itemActive')
this.scope.find('input[type="radio"][name="stream_classes_type"][value="1"]').prop('checked',true);allButAllChecks.filter(':checked').each(function(){var type=$(this).closest('[data-ipsMenuValue]').attr('data-ipsMenuValue');if(self.scope.find('[data-contentType="'+type+'"]').length){self.scope.find('[data-contentType="'+type+'"]').slideDown();}});allButAllChecks.filter(':not( :checked )').each(function(){var type=$(this).closest('[data-ipsMenuValue]').attr('data-ipsMenuValue');if(self.scope.find('[data-contentType="'+type+'"]').length){self.scope.find('[data-contentType="'+type+'"]').slideUp();}})}else{all.addClass('ipsSideMenu_itemActive').find('> input[type="checkbox"]').prop('checked',true);this.scope.find('[data-contentType]').slideUp();}}},_serializeDate:function(name,value){if(ips.utils.time.supportsHTMLDate()){return value;}
var dateObj=ips.utils.time.getDateFromInput($('input[name='+ips.utils.css.escapeSelector(name)+']'));if(!ips.utils.time.isValidDateObj(dateObj)){return'';}
var month=('0'+(dateObj.getUTCMonth()+1)).slice(-2);var day=('0'+(dateObj.getUTCDate())).slice(-2);return dateObj.getUTCFullYear()+'-'+month+'-'+day;}});}(jQuery,_));;
@@ -59,7 +58,7 @@ ips.getAjax()(ips.getSetting('stream_config')['url'],{type:'post',data:data||{}}
promise.resolve(response);}).fail(function(response){if(!silent){ips.ui.alert.show({type:'alert',message:ips.getString('errorLoadingStream'),icon:'warn'});}
promise.reject();});return promise;},resultsUpdated:function(e,data){if(this.scope.find('[data-role="activityItem"]').length===0){this.scope.find('[data-role="loadMoreContainer"]').hide();this.scope.find('[data-role="streamContent"]').removeClass('ipsStream_withTimeline');}
else{this.scope.find('[data-role="streamContent"]').addClass('ipsStream_withTimeline');this.scope.find('[data-role="loadMoreContainer"]').show();}},_updateStreamUI(response){Debug.log("Updating stream UI...");this.scope.find('[data-role="streamBlurb"]').text(response.blurb.replace(/&#039;/g,"'"));this.scope.find('[data-role="streamTitle"]').html(response.title);if(response.count===0){this.scope.find('[data-role="loadMoreContainer"]').show().html(ips.templates.render('core.streams.noMore'));}else{this.scope.find('[data-role="loadMoreContainer"]').show().html(ips.templates.render('core.streams.loadMore'));}
if(response.id){var menuItem=$('body').find('[data-streamid="'+response.id+'"] > a');menuItem.html(response.title);}},_getFormData(data){var returnValues={};_.each(data,function(val,key){if(key.startsWith('stream_')){returnValues[key]=val;}});try{if(!_.isUndefined(returnValues['stream_classes']['__EMPTY'])){returnValues['stream_classes']=_.omit(returnValues['stream_classes'],'__EMPTY');}}catch(err){}
if(response.id){var menuItem=$('body').find('[data-streamid="'+response.id+'"] .ipsNavBar__text');menuItem.html(response.title);}},_getFormData(data){var returnValues={};_.each(data,function(val,key){if(key.startsWith('stream_')){returnValues[key]=val;}});try{if(!_.isUndefined(returnValues['stream_classes']['__EMPTY'])){returnValues['stream_classes']=_.omit(returnValues['stream_classes'],'__EMPTY');}}catch(err){}
return returnValues;},_getUrlDiff(data){var returnedValues={};var defaultValues=ips.getSetting('stream_config');if(!_.isUndefined(defaultValues['changed'])){_.each(defaultValues['changed'],function(val,key){returnedValues[(key==='containers')?'stream_containers':key]=defaultValues[key];});}
if(!_.size(data)){return returnedValues;}
_.each(['stream_sort','stream_include_comments','stream_read','stream_default_view','stream_club_select','stream_club_filter'],function(val){if(defaultValues[val]!==data[val]&&!_.isUndefined(data[val])){returnedValues[val]=data[val];}});if(data['stream_ownership']==='custom'){var newNames=_.isObject(data['stream_custom_members'])?data['stream_custom_members']:data['stream_custom_members'].split(/\n/);var oldNames=defaultValues['stream_custom_members'];if(!_.isObject(oldNames)){oldNames=[];}
@@ -76,12 +75,12 @@ if(data['stream_classes_type']===0&&defaultValues['stream_classes_type']===1){re
var containers={};if(!_.isUndefined(data['stream_classes'])&&_.isObject(data['stream_classes'])){_.each(_.without(_.keys(data['stream_classes']),'__EMPTY'),function(val,key){var contentType=$('div[data-role="streamContainer"][data-className="'+val.replace(/\\/g,'\\\\')+'"]').attr('data-contentKey');if(!_.isUndefined(contentType)&&$('input[name="stream_containers_'+contentType+'"]').length){containers[val]=$('input[name="stream_containers_'+contentType+'"]').val();}});}
if(!_.isEmpty(containers)){if(!_.isUndefined(defaultValues['containers'])&&!_.isEqual(containers,defaultValues['containers'])){returnedValues['stream_containers']=containers;}}
return returnedValues;},_buildRequestURL(extraParams){var urlDiff=this._getUrlDiff(this._formData);var params=[];_.each(urlDiff,function(val,key){if(_.isObject(val)){if(!_.size(val)){params.push(key+'=');}else{var keys=_.keys(val);var values=_.values(val);for(var i=0;i<keys.length;i++){var paramValue=(!_.isUndefined(values[i])?values[i]:1);params.push(key+'['+encodeURIComponent(keys[i])+']='+paramValue);}}}else{params.push(key+'='+encodeURIComponent(val));}});if(_.isObject(extraParams)){_.each(extraParams,function(val,key){params.push(key+'='+encodeURIComponent(val));});}
return this._baseURL+'&'+params.join('&');},menuOpened(e,data){data.menu.find('input[type="text"]').focus().get(0).select();},removeStream(e){e.preventDefault();ips.ui.alert.show({type:'confirm',message:ips.getString('confirmRemoveStream'),callbacks:{ok(){window.location=$(e.currentTarget).attr('href')+'&wasConfirmed=1';},}});},toggleDefault(e){e.preventDefault();var self=this;var link=$(e.currentTarget);var value=link.attr('data-change');var url=link.attr('href');ips.getAjax()(url).done(function(response){if(value==1){self.scope.find('[data-role="toggleDefaultTrue"]').attr('hidden','');self.scope.find('[data-role="toggleDefaultFalse"]').removeAttr('hidden');}else{self.scope.find('[data-role="toggleDefaultTrue"]').removeAttr('hidden');self.scope.find('[data-role="toggleDefaultFalse"]').attr('hidden','');}
return this._baseURL+'&'+params.join('&');},menuOpened(e,data=e.detail){$(data.menu).find('input[type="text"]').focus().get(0).select();},removeStream(e){e.preventDefault();ips.ui.alert.show({type:'confirm',message:ips.getString('confirmRemoveStream'),callbacks:{ok(){window.location=$(e.currentTarget).attr('href')+'&wasConfirmed=1';},}});},toggleDefault(e){e.preventDefault();var self=this;var link=$(e.currentTarget);var value=link.attr('data-change');var url=link.attr('href');ips.getAjax()(url).done(function(response){if(value==1){self.scope.find('[data-role="toggleDefaultTrue"]').attr('hidden','');self.scope.find('[data-role="toggleDefaultFalse"]').removeAttr('hidden');}else{self.scope.find('[data-role="toggleDefaultTrue"]').removeAttr('hidden');self.scope.find('[data-role="toggleDefaultFalse"]').attr('hidden','');}
if(!response.title){$('a[data-action="defaultStream"]').hide();}else{$('a[data-action="defaultStream"]').attr('href',response.url).attr('aria-label',response.title).show().find('[data-role="defaultStreamName"]').html(response.title);}
if(value==1){if(!ips.utils.responsive.enabled||!ips.utils.responsive.currentIs('phone')&&$('a[data-action="defaultStream"]').is(':visible')){self._showStreamTooltip(response.tooltip);}else{ips.utils.anim.go('pulseOnce',$('a[data-action="defaultStream"]'));}}});},_showStreamTooltip(title){if(!this._tooltip){var tooltipHTML=ips.templates.render('core.tooltip',{id:'elDefaultStreamTooltip_'+this.controllerID});ips.getContainer().append(tooltipHTML);this._tooltip=$('#elDefaultStreamTooltip_'+this.controllerID);}else{this._tooltip.hide();}
if(value==1){if(!ips.utils.responsive.enabled||!ips.utils.responsive.currentIs('phone')&&$('a[data-action="defaultStream"]').is(':visible')){self._showStreamTooltip(response.tooltip);}else{ips.utils.anim.go('pulseOnce',$('a[data-action="defaultStream"]'));}}});},_showStreamTooltip(title){if(!this._tooltip){var tooltipHTML=ips.templates.render('core.tooltip',{id:'elDefaultStreamTooltip_'+this.controllerID});ips.getContainer().append(tooltipHTML);this._tooltip=$('#elDefaultStreamTooltip_'+this.controllerID);}else{this._tooltip[0].hidePopover();}
if(this._tooltipTimer){clearTimeout(this._tooltipTimer);}
this._tooltip.text(ips.getString('streamDefaultTooltip',{title:title}));var streamLink=$('a[data-action="defaultStream"]:visible');var self=this;var positionInfo={trigger:streamLink.first(),target:this._tooltip,center:true,above:true};var tooltipPosition=ips.utils.position.positionElem(positionInfo);$(this._tooltip).css({left:tooltipPosition.left+'px',top:tooltipPosition.top+'px',position:(tooltipPosition.fixed)?'fixed':'absolute',zIndex:ips.ui.zIndex()});if(tooltipPosition.location.vertical==='top'){this._tooltip.addClass('ipsTooltip_top');}else{this._tooltip.addClass('ipsTooltip_bottom');}
this._tooltip.show();setTimeout(function(){if(self._tooltip&&self._tooltip.is(':visible')){ips.utils.anim.go('fadeOut',self._tooltip);}},3000);},_setStreamLoading(loading){var stream=this.scope.find('[data-role="streamContent"]');if(!loading){this._streamLoadingOverlay.hide();stream.css({opacity:"1"});return;}else{if(!this._streamLoadingOverlay){this._streamLoadingOverlay=$('<div/>').addClass('ipsLoading');ips.getContainer().append(this._streamLoadingOverlay);}
this._tooltip.text(ips.getString('streamDefaultTooltip',{title:title}));var streamLink=$('a[data-action="defaultStream"]:visible');var self=this;var positionInfo={trigger:streamLink.first(),target:this._tooltip,center:true,above:true};var tooltipPosition=ips.utils.position.positionElem(positionInfo);$(this._tooltip).css({left:tooltipPosition.left+'px',top:tooltipPosition.top+'px'});if(tooltipPosition.location.vertical==='top'){this._tooltip.addClass('ipsTooltip_top');}else{this._tooltip.addClass('ipsTooltip_bottom');}
this._tooltip[0].showPopover();setTimeout(function(){if(self._tooltip&&self._tooltip.is(':visible')){self._tooltip[0].hidePopover();}},3000);},_setStreamLoading(loading){var stream=this.scope.find('[data-role="streamContent"]');if(!loading){this._streamLoadingOverlay.hide();stream.css({opacity:"1"});return;}else{if(!this._streamLoadingOverlay){this._streamLoadingOverlay=$('<div/>').addClass('ipsLoading');ips.getContainer().append(this._streamLoadingOverlay);}
var dims=ips.utils.position.getElemDims(stream);var position=ips.utils.position.getElemPosition(stream);this._streamLoadingOverlay.show().css({left:position.viewportOffset.left+'px',top:position.viewportOffset.top+$(document).scrollTop()+'px',width:dims.width+'px',height:dims.height+'px',position:'absolute',zIndex:ips.ui.zIndex()});stream.css({opacity:"0.5"});}},_startTimer(interval){if(!this._autoUpdate){return;}
if(!interval){interval=this._shortInterval;}
if(this._timer){clearInterval(this._timer);}
+1 -4
View File
@@ -24,10 +24,7 @@ else
e.preventDefault();var self=this;form.find('.ipsButton').prop('disabled',true).addClass('ipsButton--disabled');ips.getAjax()(form.attr('action'),{data:form.serialize(),type:'post'}).done(function(){ips.ui.flashMsg.show(ips.getString('metaTagsSaved'));form.find('.ipsButton').prop('disabled',false).removeClass('ipsButton--disabled');self._changed=false;if(form.find('[name="meta_tag_title"]').val()){document.title=form.find('[name="meta_tag_title"]').val();}
else
{document.title=self.scope.attr('data-defaultPageTitle');}}).fail(function(){form.attr('data-noAjax','true');form.submit();});},beforeUnload:function(){if(this._changed){return ips.getString('metaTagsUnsaved');}},addMetaBlock:function(e){var copy=this.scope.find('[data-role="metaTemplate"]').clone().attr('data-role','metaTagRow').hide();$('#elMetaTagEditor_customTags').append(copy);ips.utils.anim.go('fadeIn',copy);$(document).trigger('contentChange',[copy]);this.changed();this._showHideNoTagsMessage();},changed:function(e){this._changed=true;}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.system.notificationSettings',{initialize:function(){this.on('click','[data-action="enablePush"]',this.enablePush);this.on(document,'subscribePending.notifications',this.subscribePending);this.on(document,'subscribeSuccess.notifications',this.subscribeSuccess);this.on(document,'subscribeFail.notifications',this.subscribeFail);this.on(document,'permissionDenied.notifications',this.permissionDenied);this.on('click','[data-action="showNotificationSettings"]',this.showNotificationSettings);this.on('click','[data-action="closeNotificationSettings"]',this.closeNotificationSettings);this.on('change','[data-role="notificationSettingsWindow"]',this.saveNotificationSettings);this.on('change','#elBrowserNotifications',this.promptMe);this.setup();},setup:function(){this._showNotificationOptions();},_showNotificationOptions:function(){const pushElement=this.scope.find('[data-action="enablePush"]');if(ips.utils.notification.supported&&ips.utils.serviceWorker.supported){if(Notification.permission==='granted'){ips.utils.notification.getSubscription().then(subscription=>{if(!subscription){return;}
const enableLink=pushElement.contents();pushElement.html(ips.templates.render('core.notifications.checking'));const jsonSubscription=JSON.parse(JSON.stringify(subscription));const key=jsonSubscription.keys.p256dh;ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=notifications&do=verifySubscription',{type:'post',data:{key}}).done((response,status,jqXHR)=>{if(jqXHR.status===200){pushElement.html(ips.templates.render('core.notifications.success'));return;}
pushElement.html(enableLink);}).fail(()=>{pushElement.html(enableLink);});}).catch(err=>{Debug.error(err);pushElement.html(ips.templates.render('core.notifications.notSupported'));});}else if(Notification.permission==='denied'){pushElement.html(ips.templates.render('core.notifications.fail'));}}else{Debug.log("Notifications not supported");pushElement.html(ips.templates.render('core.notifications.notSupported'));}
pushElement.slideDown();},enablePush:function(e){e.preventDefault();ips.utils.notification.requestPermission();},subscribePending:function(e,data){this.scope.find('[data-action="enablePush"]').html(ips.templates.render('core.notifications.pending')).show();},subscribeSuccess:function(e,data){this.scope.find('[data-action="enablePush"]').html(ips.templates.render('core.notifications.success')).show();},subscribeFail:function(e,data){this.scope.find('[data-action="enablePush"]').html(ips.templates.render('core.notifications.fail')).show();},permissionDenied:function(){this.scope.find('[data-action="enablePush"]').html(ips.templates.render('core.notifications.fail')).show();},promptMe:function(e){if($(e.target).is(':checked')){ips.utils.cookie.unset('noBrowserNotifications');if(!ips.utils.notification.hasPermission()){ips.utils.notification.requestPermission();}else{ips.ui.flashMsg.show(ips.getString('saved'));}}else{ips.utils.cookie.set('noBrowserNotifications',true,true);ips.ui.flashMsg.show(ips.getString('saved'));}},_showNotificationChoice:function(){this.scope.find('[data-role="browserNotifyInfo"]').show();var type=ips.utils.notification.permissionLevel();switch(type){case'denied':$('#elBrowserNotifications').prop('checked',false).prop('disabled',true);this.scope.find('[data-role="browserNotifyDisabled"]').show();break;case'granted':$('#elBrowserNotifications').prop('checked',!ips.utils.cookie.get('noBrowserNotifications'));break;default:break;}},showNotificationSettings:function(e){e.preventDefault();var target=$(e.currentTarget);var expandedContainer=target.parent().find('[data-role="notificationSettingsWindow"]');this.scope.find('.cNotificationTypes__row--selected').removeClass('cNotificationTypes__row--selected');this.scope.find('[data-action="showNotificationSettings"]').show();this.scope.find('[data-role="notificationSettingsWindow"]').hide();target.parent().addClass('cNotificationTypes__row--selected');target.find('.cNotificationSettings_expand').addClass('ipsLoading ipsLoading--tiny').find('i').addClass('ipsHide');ips.getAjax()(target.attr('href')).done(function(response){expandedContainer.html(response).show();target.hide();target.find('.cNotificationSettings_expand').removeClass('ipsLoading').find('i').removeClass('ipsHide');}).fail(function(){window.location=target.attr('href');})},closeNotificationSettings:function(e){e.preventDefault();this.scope.find('.cNotificationTypes__row--selected').removeClass('cNotificationTypes__row--selected');this.scope.find('[data-action="showNotificationSettings"]').show();this.scope.find('[data-role="notificationSettingsWindow"]').hide();},saveNotificationSettings:function(e){e.preventDefault();var target=$(e.target);var form=target.closest('form');var container=form.closest('[data-role="notificationSettingsWindow"]');var containerParent=container.closest('.cNotificationTypes__row');var closeIcon=container.find('[data-action="closeNotificationSettings"]');closeIcon.addClass('ipsLoading ipsLoading--tiny').text('');ips.getAjax()(form.attr('action'),{data:form.serialize(),type:'post'}).done(function(response){closeIcon.removeClass('ipsLoading').html('&times;');containerParent.find('[data-action="showNotificationSettings"]').html(response);ips.ui.flashMsg.show(ips.getString('saved'));});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.system.notificationSettings',{initialize:function(){this.on('click','[data-action="showNotificationSettings"]',this.showNotificationSettings);this.on('click','[data-action="closeNotificationSettings"]',this.closeNotificationSettings);this.on('change','[data-role="notificationSettingsWindow"]',this.saveNotificationSettings);},showNotificationSettings:function(e){e.preventDefault();var target=$(e.currentTarget);var expandedContainer=target.parent().find('[data-role="notificationSettingsWindow"]');this.scope.find('.cNotificationTypes__row--selected').removeClass('cNotificationTypes__row--selected');this.scope.find('[data-action="showNotificationSettings"]').show();this.scope.find('[data-role="notificationSettingsWindow"]').hide();target.parent().addClass('cNotificationTypes__row--selected');target.find('.cNotificationSettings_expand').addClass('ipsLoading ipsLoading--tiny').find('i').addClass('ipsHide');ips.getAjax()(target.attr('href')).done(function(response){expandedContainer.html(response).show();target.hide();target.find('.cNotificationSettings_expand').removeClass('ipsLoading').find('i').removeClass('ipsHide');}).fail(function(){window.location=target.attr('href');})},closeNotificationSettings:function(e){e.preventDefault();this.scope.find('.cNotificationTypes__row--selected').removeClass('cNotificationTypes__row--selected');this.scope.find('[data-action="showNotificationSettings"]').show();this.scope.find('[data-role="notificationSettingsWindow"]').hide();},saveNotificationSettings:function(e){e.preventDefault();var target=$(e.target);var form=target.closest('form');var container=form.closest('[data-role="notificationSettingsWindow"]');var containerParent=container.closest('.cNotificationTypes__row');var closeIcon=container.find('[data-action="closeNotificationSettings"]');closeIcon.addClass('ipsLoading ipsLoading--tiny').text('');ips.getAjax()(form.attr('action'),{data:form.serialize(),type:'post'}).done(function(response){closeIcon.removeClass('ipsLoading').html('&times;');containerParent.find('[data-action="showNotificationSettings"]').html(response);ips.ui.flashMsg.show(ips.getString('saved'));});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.system.referrals',{initialize:function(){$('.cReferrer_copy').each(function(){$(this).hide();});ips.loader.getStatic("/applications/core/interface/static/clipboard/clipboard.min.js").then(function(){if(ClipboardJS.isSupported()){$('.cReferrer_copy').each(function(){$(this).show();});var clipboard=new ClipboardJS('.cReferrer_copy');clipboard.on('success',function(e){ips.ui.flashMsg.show(ips.getString('copied'));e.clearSelection();});}else{$('.cReferrals_directLink_input').removeClass('ipsHide');$('.cReferrals_directLink_link').addClass('ipsHide');}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.system.register',{usernameField:null,timers:{'username':null,'email':null},ajax:ips.getAjax(),popup:null,passwordBlurred:true,dirty:false,initialize:function(){this.on('keyup','#elInput_username',this.changeUsername);this.on('blur','#elInput_username',this.changeUsername);this.on('keyup','#elInput_password_confirm',this.confirmPassword);this.on('blur','#elInput_password_confirm',this.confirmPassword);this.on('click','a[data-ipsPbrCancel]',this.cancelPbr);this.setup();},setup:function(){this.usernameField=this.scope.find('#elInput_username');this.passwordField=this.scope.find('#elInput_password');this.confirmPasswordField=this.scope.find('#elInput_password_confirm');this.usernameField.after($('<span/>').attr('data-role','validationCheck'));this.confirmPasswordField.after($('<span/>').attr('data-role','validationCheck'));this.convertExistingErrors();},convertExistingErrors:function(){var fields=this.scope.find('#elInput_username, #elInput_password, #elInput_password_confirm');var self=this;fields.each(function(){var elem=$(this);var wrapper=elem.closest('.ipsFieldRow');if(!wrapper.hasClass('ipsFieldRow_error')){return;}
var message=wrapper.find('.i-color_warning').html();self._clearResult(elem);wrapper.find('[data-role="validationCheck"]').show().html(ips.templates.render('core.forms.validateFailText',{message:message}));elem.removeClass('ipsField_success').addClass('ipsField_error');});},cancelPbr:function(e){var url=$(e.target).closest('[data-ipsPbrCancel]').attr('href');e.preventDefault();e.stopPropagation();ips.ui.alert.show({type:'confirm',message:ips.getString('pbr_confirm_title'),subText:ips.getString('pbr_confirm_text'),icon:'warn',buttons:{ok:ips.getString('pbr_confirm_ok'),cancel:ips.getString('pbr_confirm_cancel')},callbacks:{ok:function(){window.location=url;},cancel:function(){return false;}}});},changeUsername:function(e){if(this.timers['username']){clearTimeout(this.timers['username']);}
+19 -13
View File
@@ -14,7 +14,7 @@ rootClone?.querySelectorAll('details > summary > input').forEach(titleInput=>{co
titleInput.parentElement.replaceChild(titleNode,titleInput)})
rootClone?.querySelectorAll('[draggable]').forEach(el=>el.removeAttribute('draggable'))
const newState=rootClone?.querySelector(`[data-depth="0"]`)?.innerHTML;this.reactRoot?.unmount();this.reactContainer?.remove();document.querySelectorAll('[data-role="widgetAreaConfigForm"]').forEach(el=>el.remove())
this.reactContainer=null;this.reactRoot=null;if(newState!==undefined){this.elem.innerHTML=newState;const widgets=[...this.elem.querySelectorAll('.cWidgetContainer > .ipsWidget__content--wrap > .ipsWidget')];if(newState&&widgets.some(widget=>!!widget.innerHTML.match(/\S/))){widgets.forEach(widget=>{if(!widget.innerHTML.match(/\S/)){widget.closest('.cWidgetContainer').setAttribute('hidden','');}})
this.reactContainer=null;this.reactRoot=null;if(newState!==undefined){ips.cleanContentsOf(this.elem);this.elem.innerHTML=newState;const widgets=[...this.elem.querySelectorAll('.cWidgetContainer > .ipsWidget__content--wrap > .ipsWidget')];if(newState&&widgets.some(widget=>!!widget.innerHTML.match(/\S/))){widgets.forEach(widget=>{if(!widget.innerHTML.match(/\S/)){widget.closest('.cWidgetContainer').setAttribute('hidden','');}})
this.elem.ipsShow();}
this.cleanContents()
this.elem.querySelectorAll('section.cWidgetContainer').forEach(element=>{if(!element.dataset.controller?.split(',').includes('core.front.widgets.area')){element.dataset.controller=[(element.dataset.controller||''),'core.front.widgets.area'].filter(i=>!!i).join(',')}})
@@ -27,22 +27,29 @@ Object.assign(data,pageID?{pageID}:{pageArea:this.elem.closest('[data-widgetArea
const response=await ips.fetch(ips.getSetting('baseURL'),{method:'GET',data});this.scope.hide().html(response.html);if('devices'in response&&Array.isArray(response.devices)){this.resetResponsiveClasses(response.devices);}
ips.utils.anim.go('fadeIn',this.scope);this.trigger('loadedWidget.widgets',{blockID:this._blockID});}catch(e){this.scope.html('Error');}
this._setLoading(false);},resetResponsiveClasses(deviceList){this.scope.removeClass('ipsResponsive_hidePhone').removeClass('ipsResponsive_hideDesktop').removeClass('ipsResponsive_hideTablet');for(const value of["Phone","Tablet","Desktop"].filter(i=>!deviceList.includes(i))){this.scope.addClass('ipsResponsive_hide'+value);}},markAllRead(){this.scope.find('[data-ips-unread]').removeAttr('data-ips-unread');},_setLoading(status){if(status){this.scope.html('').addClass('ipsLoading cSidebarBlock_loading');}else{this.scope.removeClass('ipsLoading cSidebarBlock_loading');}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.widgets.carouselControls',{initialize(){if(this.elem.closest('.pageBuilderRoot')||!this.getCarousel()){return;}
this._area=undefined;this.setupCarousel();},_area:undefined,getCarousel(){if(this._area===undefined){const container=this.elem.closest('.cWidgetContainer');if(!container?.classList.contains('cWidgetContainer--carousel')){this._area=null;}else{this._area=container.querySelector(":scope > .cWidgetContainer__carousel-wrap")||container;}}
return this._area;},_carouselIndicator:undefined,_isScrolling:false,_actualCarouselIndex:0,getCarouselOffset(){let children=[...this.getCarousel().querySelectorAll(':scope > .cWidgetContainer:not([hidden])')];if(this._isScrolling){return[this._actualCarouselIndex,children.length,children];}
;(function($,_,undefined){"use strict";ips.controller.register('core.front.widgets.carouselControls',{_area:undefined,_carouselInterval:undefined,_carouselIndicator:undefined,_isScrolling:false,_actualCarouselIndex:0,_container:undefined,initialize(){if(this.elem.closest('.pageBuilderRoot')||!this.getCarousel()){return;}
this._area=undefined;this.setupCarousel();},destroy(){if(this._carouselInterval){clearInterval(this._carouselInterval);}},getCarousel(){if(this._area===undefined){const container=this.getContainer();if(!container?.classList.contains('cWidgetContainer--carousel')){this._area=null;}else{this._area=container.querySelector(":scope > .cWidgetContainer__carousel-wrap")||container;}}
return this._area;},getContainer(){if(this._container===undefined){const container=this.elem.closest('.cWidgetContainer');if(!container?.classList.contains('cWidgetContainer--carousel')){this._container=null;}else{this._container=container;}}
return this._container;},getCarouselOffset(){let children=[...this.getCarousel().querySelectorAll(':scope > .cWidgetContainer:not([hidden])')];if(this._isScrolling){return[this._actualCarouselIndex,children.length,children];}
const box=this.getScrollerBox();let index;for(index=0;index<children.length-1;index++){if(!this.isRTL()&&Math.ceil(children[index].getBoundingClientRect().left)>=Math.floor(box.left)){return[index,children.length,children];}else if(this.isRTL()&&Math.floor(children[index].getBoundingClientRect().right)<=Math.ceil(box.right)){return[index,children.length,children];}}
return[children.length-1,children.length,children];},isRTL(){return ips.ui.carousel.isRTL(this.getCarousel());},getCarouselIndicator(){if(this._carouselIndicator===undefined){this._carouselIndicator=this.elem.querySelector(`.cWidgetContainer__carousel-indicator`);}
return this._carouselIndicator;},updateCarouselIndicator(){const indicator=this.getCarouselIndicator();if(!indicator){Debug.warn(`Couldn't find a carousel indicator for a carousel`);return;}
let[index,total]=this.getCarouselOffset();index=Math.min(index,this.getPageCount());total=Math.min(total,this.getPageCount());indicator.innerHTML=this.shouldUseCarouselLinks()?`<a href="#${this.getCarouselHref(index)}">${index + 1}/${total}</a>`:`${index + 1}/${total}`;this.elem.querySelectorAll('button').forEach(el=>total<=1?el.setAttribute('disabled',''):el.removeAttribute('disabled'));},carouselScroll(e){const button=e.target?.closest?.(`[data-carousel-arrow]`);if(!button){return;}
const[index,total,children]=this.getCarouselOffset();const dir=button.dataset.carouselArrow||'next';const box=this.getScrollerBox();let atEnd=false;if(dir==='next'){if(index===total-1){atEnd=true;}else if(!this.isRTL()){atEnd=Math.floor(children[total-1].getBoundingClientRect().right)<=Math.ceil(box.right);}else{atEnd=Math.ceil(children[total-1].getBoundingClientRect().left)>=Math.floor(box.left);}}else{if(index===0){atEnd=true;}else if(this.isRTL()){atEnd=Math.floor(children[0].getBoundingClientRect().right)<=Math.ceil(box.right);}else{atEnd=Math.ceil(children[0].getBoundingClientRect().left)>=Math.floor(box.left);}}
let[index,total]=this.getCarouselOffset();index=Math.min(index,this.getPageCount());total=Math.min(total,this.getPageCount());indicator.innerHTML=this.shouldUseCarouselLinks()?`<a href="#${this.getCarouselHref(index)}">${index + 1}/${total}</a>`:`${index + 1}/${total}`;this.elem.querySelectorAll('button').forEach(el=>total<=1?el.setAttribute('disabled',''):el.removeAttribute('disabled'));},carouselScroll(e){let dir;if(e instanceof PointerEvent){const button=e.target?.closest?.(`[data-carousel-arrow]`);if(!button){return;}
dir=button.dataset.carouselArrow||'next';}else if(e.detail.dir){dir=e.detail.dir}
if(!dir||!['prev','next'].includes(dir)){Debug.warn("Not scrolling because the direction could not be determined")
return;}
if(this._carouselInterval&&e instanceof PointerEvent){clearInterval(this._carouselInterval);this._carouselInterval=null;}
const[index,total,children]=this.getCarouselOffset();const box=this.getScrollerBox();let atEnd=false;if(dir==='next'){if(index===total-1){atEnd=true;}else if(!this.isRTL()){atEnd=Math.floor(children[total-1].getBoundingClientRect().right)<=Math.ceil(box.right);}else{atEnd=Math.ceil(children[total-1].getBoundingClientRect().left)>=Math.floor(box.left);}}else{if(index===0){atEnd=true;}else if(this.isRTL()){atEnd=Math.floor(children[0].getBoundingClientRect().right)<=Math.ceil(box.right);}else{atEnd=Math.ceil(children[0].getBoundingClientRect().left)>=Math.floor(box.left);}}
const toIndex=((dir==='prev'&&atEnd)?(total-1):(atEnd?0:index+(dir==='prev'?-1:1)))%total;const childBox=children[toIndex].getBoundingClientRect();const paddedBox=this.getPaddedScrollBox();let scrollAmount;if(this.isRTL()){scrollAmount=(toIndex===total-1?childBox.left:childBox.right)-paddedBox.right;}else{scrollAmount=(toIndex===total-1?childBox.right:childBox.left)-paddedBox.left;}
this._isScrolling=true;this._actualCarouselIndex=toIndex;children.forEach(child=>child.style.scrollSnapStop="normal")
this.getCarousel().scrollTo({left:this.getCarousel().scrollLeft+scrollAmount,behavior:"smooth"});this.updateCarouselIndicator();},getScrollerBox(){return this.getCarousel().getBoundingClientRect();},getPaddedScrollBox(){const box=this.getScrollerBox();const padding=this.getScrollPadding();return new DOMRect(box.x+padding.left,box.y,box.width-(padding.left+padding.right),box.height);},getScrollPadding(){return ips.ui.carousel.getScrollPadding(this.getCarousel());},carouselScrollEnd(){this._isScrolling=false;const children=this.getCarousel().querySelectorAll(":scope > .cWidgetContainer:not([hidden])");children.forEach(child=>child.style.scrollSnapStop="")
this.updateCarouselIndicator();},getCarouselHref(idx){if(this.shouldUseCarouselLinks()){return`carouselwidget_${this.getCarousel().dataset.widgetarea}_${this.getCarousel().dataset.widgetAreaId}_${idx + 1}`;}
return'';},shouldUseCarouselLinks(){return!!(this.getCarousel().dataset.widgetAreaId&&this.getCarousel().dataset.widgetarea);},setupCarousel(){if(!(this.getCarousel()instanceof Element)||this.getCarousel().closest('body')!==document.body||!this.getCarousel().querySelector(`:scope > .cWidgetContainer`)||(this.getCarousel().querySelectorAll(`:scope > .cWidgetContainer`).length===1&&this.getCarousel().querySelector(`:scope > .cWidgetContainer`).getBoundingClientRect().width>=this.elem.getBoundingClientRect().width)){this.elem.ipsHide();return;}
this.elem.ipsShow();const buttonContainer=this.elem;buttonContainer.querySelectorAll('[data-carousel-arrow]').forEach(button=>button.addEventListener('click',e=>this.carouselScroll(e)));if('onscrollend'in this.getCarousel()){this.getCarousel().addEventListener('scrollend',()=>this.carouselScrollEnd(),{capture:true});}else{this.getCarousel().addEventListener('scroll',_.debounce(()=>this.carouselScrollEnd(),200),{capture:true});}
this.updateCarouselIndicator();if(this.shouldUseCarouselLinks()&&window.location.hash){const[_,total,children]=this.getCarouselOffset();for(let i=0;i<total;i++){const hash=this.getCarouselHref(i);if(hash&&window.location.hash===`#${hash}`){this._actualCarouselIndex=i;this._isScrolling=true;children[i].scrollIntoView({behavior:"instant",block:"start",inline:"start"});break;}}}
this.setupObserver();},getPageCount(){const box=this.getCarousel()?.getBoundingClientRect();if(!box){return 1;}
this.updateCarouselIndicator();if(this.shouldUseCarouselLinks()&&window.location.hash){const[_,total,children]=this.getCarouselOffset();for(let i=0;i<total;i++){const hash=this.getCarouselHref(i);if(hash&&window.location.hash===`#${hash}`){this._actualCarouselIndex=i;this._isScrolling=true;children[i].scrollIntoView({behavior:"instant",block:"start",inline:"start"});break;}}}else{this.setupLoop();}
this.getContainer()?.addEventListener('ips:scrollCarousel',e=>this.carouselScroll(e));this.setupObserver();},setupLoop(){if(this._carouselInterval){return;}
const container=this.getContainer();if(container&&container.dataset.widgetInterval){const interval=parseInt(container.dataset.widgetInterval);if(interval>0){this._carouselInterval=setInterval(()=>{if(this.elem?.ownerDocument!==document){Debug.log('not scrolling because the carousel is no longer in the document');clearInterval(this._carouselInterval);return;}
this.elem.dispatchEvent(new CustomEvent('ips:scrollCarousel',{bubbles:true,detail:{dir:"next"}}))},interval*1000);}}},getPageCount(){const box=this.getCarousel()?.getBoundingClientRect();if(!box){return 1;}
let children=[...this.getCarousel().querySelectorAll(`:scope > .cWidgetContainer:not([hidden])`)];if(children.length<2){return 1;}
if(this.isRTL()){children=children.reverse();}
let basePages=Math.ceil(Math.abs(children[children.length-1].getBoundingClientRect().right-children[0].getBoundingClientRect().left)/box.width);if(children.length>2&&(children[children.length-1].getBoundingClientRect().right-children[children.length-2].getBoundingClientRect().left)>box.width){basePages++;}
@@ -65,18 +72,17 @@ this.getSearchBar().addEventListener('input',e=>{const value=e.target.value;cons
return;}
const blocks=group.querySelectorAll('[data-blockid][data-blocktitle]');let groupHasVisibleBlocks=(!value.trim()&&"showWhenEmpty"in group.dataset);blocks.forEach(block=>{if(!value.trim()||widgetIds.has(block.dataset.blockid)){groupHasVisibleBlocks=true;block.removeAttribute('hidden');}else{block.setAttribute('hidden','');}});if(!groupHasVisibleBlocks){group.setAttribute('hidden','');}else{group.removeAttribute('hidden');}})}})},sidebarSetup:false,setupFavorites(){if(!this.sidebarSetup){this.getSidebar().addEventListener('click',e=>{const indicator=e.target.closest('[data-blockid] [data-role="favorite-indicator"]');if(indicator){this.toggleFavorite(indicator);}});}
this.getSidebar().querySelectorAll(`[data-role="favorite-indicator"]`).forEach(indicator=>{if('isFavorite'in indicator.dataset){indicator.title=ips.getString('cSidebarBlock_unset-favorite')}else{indicator.title=ips.getString('cSidebarBlock_set-favorite')}});this.sidebarSetup=true;},async toggleFavorite(indicator){const block=indicator.closest('[data-blockid]');const blockID=block.dataset.blockid;const isFavorite="isFavorite"in indicator.dataset;const favoriteGroup=this.getSidebar().querySelector('[data-favorites]');const favoriteList=favoriteGroup.querySelector('ul');if(!isFavorite){if(!favoriteList.querySelector(`[data-blockid="${blockID}"]`)){const clone=block.cloneNode(true);clone.querySelector(`[data-role="favorite-indicator"]`).dataset.isFavorite='';clone.querySelector(`[data-role="favorite-indicator"]`).title=ips.getString('cSidebarBlock_unset-favorite');this._setupDraggingOnItem(clone);favoriteList.appendChild(clone);favoriteGroup.removeAttribute('hidden');}}else{favoriteList.querySelectorAll(`[data-blockid="${blockID}"]`).forEach(itemInFavorites=>{itemInFavorites.remove();});if(!favoriteGroup.querySelectorAll(`[data-blockid]`).length){favoriteGroup.setAttribute('hidden','');}}
this.getSidebar().querySelectorAll(`[data-blockid="${blockID}"] [data-role="favorite-indicator"]`).forEach(indicator=>{if(isFavorite){delete indicator.dataset.isFavorite;indicator.title=ips.getString('cSidebarBlock_set-favorite');}else{indicator.dataset.isFavorite="";indicator.title=ips.getString('cSidebarBlock_unset-favorite');}});try{await ips.fetch(ips.getSetting('baseURL'),{method:"get",data:{app:'core',module:'system',controller:'widgets',do:isFavorite?"removeFavorite":"addFavorite",blockID:blockID.split('_',3).pop()}});}catch(e){ips.ui.alert.show({"message":"Something went wrong, the favorites may not have been saved"});}},getSearchBar(){return this.elem.querySelector('input[data-role="widgetSearch"]');},async openSidebarManager(e){const userMenu=document.querySelector('#ipsMenu_elUserLink_menu');$(userMenu).trigger("closeMenu",true);e?.preventDefault();await whenLoaded();if(this._inManagingState){return}
this.getSidebar().querySelectorAll(`[data-blockid="${blockID}"] [data-role="favorite-indicator"]`).forEach(indicator=>{if(isFavorite){delete indicator.dataset.isFavorite;indicator.title=ips.getString('cSidebarBlock_set-favorite');}else{indicator.dataset.isFavorite="";indicator.title=ips.getString('cSidebarBlock_unset-favorite');}});try{await ips.fetch(ips.getSetting('baseURL'),{method:"get",data:{app:'core',module:'system',controller:'widgets',do:isFavorite?"removeFavorite":"addFavorite",blockID:blockID.split('_',3).pop()}});}catch(e){ips.ui.alert.show({"message":"Something went wrong, the favorites may not have been saved"});}},getSearchBar(){return this.elem.querySelector('input[data-role="widgetSearch"]');},async openSidebarManager(e){const userMenu=document.getElementById('elUserLink_menu');userMenu.hidePopover();e?.preventDefault();await whenLoaded();if(this._inManagingState){return}
document.querySelectorAll('.ipsTableOfContents__linkOptions').forEach(el=>el.dispatchEvent(new CustomEvent('remove')));if(!this.elem.querySelector('[data-role="manager"]')){this._buildSidebar();}else{this.elem.querySelectorAll('#elSidebarManager .ipsToolbox__tools').forEach(elem=>Object.assign(elem.style,{overflow:'',position:'',top:''}));}
this.triggerOn('core.front.widgets.area','managingStarted.widgets');this._showManager();if(!window.location.search.includes('_blockManager')){let anchor=window.location.href.match(/(#.*)$/)?.[1]||''
let url=window.location.href.replaceAll(/#.*$|\b_blockManager=1?\b/g,'')
url+=url.includes('?')?'&_blockManager=1':'?_blockManager=1'
url+=anchor
ips.utils.history.pushState({artificial:true},'pagebuilder',url)}
this.scope.addClass('cWidgetsManaging');},closeSidebarManager(e){e?.preventDefault();if(this._inManagingState){document.querySelectorAll('.ipsMenu[data-page-editor-menu]').forEach(element=>{element.dispatchEvent(new CustomEvent('closeMenu'));element.remove();})
this.scope.removeClass('cWidgetsManaging');this._hideManager();try{this.triggerOn('core.front.widgets.area','managingFinished.widgets');}catch(e){Debug.error(e);}
this.scope.addClass('cWidgetsManaging');},closeSidebarManager(e){e?.preventDefault();let self=this;let pageUrl=window.location.href.replace(/\?(.*?)&?_blockManager=[^&]*/,'?$1').replace(/[?&]+$/,'');if(this._inManagingState){document.querySelectorAll('.ipsMenu[data-page-editor-menu]').forEach(element=>{element.dispatchEvent(new CustomEvent('closeMenu'));element.remove();});ips.getAjax()(pageUrl,{showLoading:true,data:{do:'storeRevision'}}).done(function(response){self.scope.removeClass('cWidgetsManaging');self._hideManager();try{self.triggerOn('core.front.widgets.area','managingFinished.widgets');}catch(e){Debug.error(e);}
if(ips.utils.url.getParam('_blockManager')){if(ips.utils.history.getState('pagebuilder').artificial){window.history.back()}
setTimeout(()=>ips.utils.history.replaceState({},'pagebuilder',window.location.href.replace(/\?(.*?)&?_blockManager=[^&]*/,'?$1').replace(/[?&]+$/,'')))}}},_setUpDragging(){this.elem.querySelectorAll('[data-role="availableBlocks"] ul').forEach(list=>{list.style.zIndex=ips.ui.zIndex();list.querySelectorAll(':scope > .cSidebarManager_block').forEach(item=>this._setupDraggingOnItem(item));})},_setupDraggingOnItem(item){item.setAttribute('draggable','true');const wrapBehavior=item.dataset.widgetLayouts?.split(',')?.[0]?.trim()||'table'
item.addEventListener('dragstart',function(e){e.stopPropagation();e.dataTransfer.clearData();const data={blockID:e.target.dataset.blockid,blockTitle:e.target.dataset.blocktitle,allowReuse:e.target.dataset.allowreuse,config:!!e.target.dataset.blockconfig,blank:e.target.dataset.blockerrormessage,menustyle:e.target.dataset.menustyle,ipsWrapBehavior:wrapBehavior,};e.dataTransfer.setData('application/x.ipsblock',JSON.stringify(data));ipsSettings.__pageeditor_last_dragged_widget_data__=data;item.addEventListener('dragend',e=>{delete ipsSettings.__pageeditor_last_dragged_widget_data__;},{once:true});})},async _showManager(){this.scope.find('#elSidebarManager').removeAttr('hidden');this._fadeUnmanagedRoots();if(!this._loadedManager&&!this._loadingManager){try{const response=await ips.fetch(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=widgets&do=getBlockList',{data:{pageApp:$('body').attr('data-pageApp')}})
setTimeout(()=>ips.utils.history.replaceState({},'pagebuilder',pageUrl));}}).fail(function(){window.location=pageUrl;});}},_setUpDragging(){this.elem.querySelectorAll('[data-role="availableBlocks"] ul').forEach(list=>{list.style.zIndex=ips.ui.zIndex();list.querySelectorAll(':scope > .cSidebarManager_block').forEach(item=>this._setupDraggingOnItem(item));})},_setupDraggingOnItem(item){item.setAttribute('draggable','true');const wrapBehavior=item.dataset.widgetLayouts?.split(',')?.[0]?.trim()||'table'
item.addEventListener('dragstart',function(e){e.stopPropagation();e.dataTransfer.clearData();const data={blockID:e.target.dataset.blockid,blockTitle:e.target.dataset.blocktitle,allowReuse:e.target.dataset.allowreuse,config:!!e.target.dataset.blockconfig,blank:e.target.dataset.blockerrormessage,menustyle:e.target.dataset.menustyle,ipsWrapBehavior:wrapBehavior,};e.dataTransfer.setData('application/x.ipsblock',JSON.stringify(data));ipsSettings.__pageeditor_last_dragged_widget_data__=data;item.addEventListener('dragend',e=>{delete ipsSettings.__pageeditor_last_dragged_widget_data__;},{once:true});})},async _showManager(){this.scope.find('#elSidebarManager').removeAttr('hidden');this._fadeUnmanagedRoots();if(!this._loadedManager&&!this._loadingManager){try{const response=await ips.fetch(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=widgets&do=getBlockList',{data:{pageApp:$('body').attr('data-pageApp'),pageModule:$('body').attr('data-pageModule'),pageController:$('body').attr('data-pageController')}})
this._loadedManager=true;this.scope.find('[data-role="availableBlocks"]').html(response);this.scope.find('[data-role="availableBlocks"]').attr("data-unloaded",null);this._setUpDragging();this.setupSearch();this.setupFavorites();try{$(document).trigger('contentChange',[$('#elSidebarManager')]);}catch(e){Debug.error(e);}
document.dispatchEvent(new CustomEvent('ipsWidgetManagerLoaded',{bubbles:true,cancelable:true}))}catch(e){Debug.error(e)
ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('sidebar_fetch_blocks_error'),callbacks:{}});}
+14 -14
View File
@@ -1,27 +1,27 @@
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.2fa',{initialize:function(){this.on('tabShown',this.tabShown);this.on('tabChanged',this.tabChanged);this.setup();},setup:function(){this.scope.css({zIndex:ips.ui.zIndex()});this.scope.find('input[type="text"]:visible').first().focus();},tabShown:function(e,data){this.scope.find('input[type="text"]:visible').first().focus();},tabChanged:function(e,data){if(data.tab){data.tab.find('input[name="mfa_method"]').prop('checked',true);}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.authyOneTouch',{initialize:function(){var scope=$(this.scope);setInterval(function(){ips.getAjax()(scope.closest('form').attr('action'),{data:{'onetouchCheck':scope.find('[data-role="onetouchCode"]').val()}}).done(function(response){if(response.status==1){scope.closest('form').submit();}});},3000);}});}(jQuery,_));;
;(function($,undefined){"use strict";ips.controller.register('core.global.core.coverPhoto',{_image:null,_existingPosition:0,_tooltip:null,_expandedCover:false,_newPosition:0,_container:null,_editingPosScroll:0,_editingPosMouse:0,initialize:function(){var self=this;this.on('menuItemSelected',function(e,data){var button=$(data.originalEvent.target).closest('a[data-action]');switch($(button).attr('data-action')){case'removeCoverPhoto':self.removePhoto(data);break;case'positionCoverPhoto':self.positionPhoto(data.originalEvent);break;}});this.on('click','[data-action="savePosition"]',this.savePosition);this.on('click','[data-action="cancelPosition"]',this.cancelPosition);this.on('click','[data-action="toggleCoverPhoto"]',this.toggleCoverPhoto);this.setup();},setup:function(){this._image=this.scope.find('.ipsCoverPhoto__image');var doPosition=ips.utils.url.getParam('_position');if(doPosition!=undefined)this.positionPhoto();this.scope.find('a[data-action="positionCoverPhoto"]').parent().removeClass('ipsHide');},removePhoto:function(data){data.originalEvent.preventDefault();var self=this;var target=$(data.originalEvent.target).closest('[data-action="removeCoverPhoto"]');ips.ui.alert.show({type:'confirm',icon:'warn',message:ips.getString('confirmRemoveCover'),callbacks:{ok:function(){ips.getAjax()($(target).attr('href')+'&wasConfirmed=1').done(function(){ips.utils.anim.go('fadeOut',self._image).done(function(){ips.ui.flashMsg.show(ips.getString('removeCoverDone'));});data.menuElem.find('[data-role="photoEditOption"]').hide();}).fail(function(err){window.location=$(target).attr('href');});}}});},savePosition:function(e){e.preventDefault();let newPos=((this._container.scrollTop/(this._container.scrollHeight-this._container.clientHeight))*100);newPos=newPos||0;this._newPosition=newPos;this.scope.attr('data-coverOffset',this._newPosition);this.scope.css({'--offset':this._newPosition});ips.getAjax()(this.scope.attr('data-url')+'&do=coverPhotoPosition'+'&offset='+this._newPosition).fail(function(err){this.scope.attr('data-url')+'&do=coverPhotoPosition'+'&offset='+this._newPosition;});this._resetImage();},cancelPosition:function(e){e.preventDefault();this._resetImage();},positionPhoto:function(e){if(e!=undefined)e.preventDefault();this.scope.addClass('ipsCoverPhoto--editing');this._existingPosition=parseInt(this.scope.attr('data-coveroffset'))||0;this._container=this.scope.find('.ipsCoverPhoto__container')[0];this._mouseDownHandler=this._mouseDownHandler.bind(this);this._container.addEventListener('mousedown',this._mouseDownHandler);this._mouseUpHandler=this._mouseUpHandler.bind(this);this._container.addEventListener('mouseup',this._mouseUpHandler);this._mouseOutHandler=this._mouseOutHandler.bind(this);this._container.addEventListener('mouseout',this._mouseOutHandler);this._container.scrollTop=(this._container.scrollHeight-this._container.clientHeight)*(this._existingPosition/100);this.scope.find('.ipsCoverPhoto__container').after(ips.templates.render('core.coverPhoto.controls'));this._showTooltip();},_mouseDownHandler:function(e){e.preventDefault();this._editingPosMouse=e.clientY;this._editingPosScroll=this._container.scrollTop;this._mouseMoveHandler=this._mouseMoveHandler.bind(this);this._container.addEventListener('mousemove',this._mouseMoveHandler);},_mouseMoveHandler:function(e){let dy=(e.clientY-this._editingPosMouse)*2.3;this._container.scrollTop=this._editingPosScroll-dy;},_mouseUpHandler:function(e){this._container.removeEventListener('mousemove',this._mouseMoveHandler);},_mouseOutHandler:function(e){this._container.removeEventListener('mousemove',this._mouseMoveHandler);},_resetImage:function(){this._container.removeEventListener('mousedown',this._mouseDownHandler);this.scope.removeClass('ipsCoverPhoto--editing');this.scope.find('[data-role="reposition"]').remove();this.scope.find('[data-role="coverPhotoControls"]').remove();this._hideTooltip();ips.utils.history.pushState({},'core.global.core.coverPhoto',ips.utils.url.removeParam('csrfKey',this.scope.attr('data-url')));},_showTooltip:function(msg){if(!this._tooltip){this._buildTooltip();}
this._tooltip.hide().text(ips.getString('dragCoverPhoto'));this._positionTooltip();},_hideTooltip:function(){if(this._tooltip&&this._tooltip.is(':visible')){ips.utils.anim.go('fadeOut',this._tooltip);}},_positionTooltip:function(){var positionInfo={trigger:this.scope.find('.ipsCoverPhoto__container'),target:this._tooltip,center:true,above:true};var tooltipPosition=ips.utils.position.positionElem(positionInfo);this._tooltip.css({left:tooltipPosition.left+'px',top:tooltipPosition.top+'px',position:(tooltipPosition.fixed)?'fixed':'absolute',zIndex:ips.ui.zIndex()});if(tooltipPosition.location.vertical=='top'){this._tooltip.addClass('ipsTooltip_top');}else{this._tooltip.addClass('ipsTooltip_bottom');}
this._tooltip.show();},_buildTooltip:function(){var tooltipHTML=ips.templates.render('core.tooltip',{id:'elCoverPhotoTooltip'});ips.getContainer().append(tooltipHTML);this._tooltip=$('#elCoverPhotoTooltip');},toggleCoverPhoto:function(){if(this._expandedCover==false){let naturalImage=this.scope.find('.ipsCoverPhoto__image')[0],ratio=naturalImage.naturalWidth/naturalImage.naturalHeight;this.scope.find('.ipsCoverPhoto__container').css("--coverPhoto--ratio",ratio);this._expandedCover=true;this.scope.addClass('ipsCoverPhoto--expanded');}else{this._expandedCover=false;this.scope.removeClass('ipsCoverPhoto--expanded');}},});}(jQuery));;
;(function($,undefined){"use strict";ips.controller.register('core.global.core.coverPhoto',{_image:null,_existingPosition:0,_tooltip:null,_expandedCover:false,_newPosition:0,_container:null,_editingPosScroll:0,_editingPosMouse:0,initialize:function(){var self=this;this.on('menuItemSelected',function(e){var button=$(e.detail.originalEvent.target).closest('[data-action]');switch($(button).attr('data-action')){case'removeCoverPhoto':self.removePhoto(e.detail);break;case'positionCoverPhoto':self.positionPhoto(e.detail.originalEvent);break;}});this.on('click','[data-action="savePosition"]',this.savePosition);this.on('click','[data-action="cancelPosition"]',this.cancelPosition);this.on('click','[data-action="toggleCoverPhoto"]',this.toggleCoverPhoto);this.setup();},setup:function(){this._image=this.scope.find('.ipsCoverPhoto__image');var doPosition=ips.utils.url.getParam('_position');if(doPosition!=undefined)this.positionPhoto();},removePhoto:function(data){data.originalEvent.preventDefault();var self=this;var target=$(data.originalEvent.target).closest('[data-action="removeCoverPhoto"]');ips.ui.alert.show({type:'confirm',icon:'warn',message:ips.getString('confirmRemoveCover'),callbacks:{ok:function(){ips.getAjax()($(target).attr('href')+'&wasConfirmed=1').done(function(){ips.utils.anim.go('fadeOut',self._image).done(function(){ips.ui.flashMsg.show(ips.getString('removeCoverDone'));});$(data.menuElem).find('[data-role="photoEditOption"]').prop('hidden',true);document.body.dispatchEvent(new CustomEvent('ipsDataLayerSync',{bubbles:true}));}).fail(function(err){window.location=$(target).attr('href');});}}});},savePosition:function(e){e.preventDefault();let newPos=((this._container.scrollTop/(this._container.scrollHeight-this._container.clientHeight))*100);newPos=newPos||0;this._newPosition=newPos;this.scope.attr('data-coverOffset',this._newPosition);this.scope.css({'--offset':this._newPosition});ips.getAjax()(this.scope.attr('data-url')+'&do=coverPhotoPosition'+'&offset='+this._newPosition).done(()=>{document.body.dispatchEvent(new CustomEvent('ipsDataLayerSync',{bubbles:true}));}).fail(function(err){this.scope.attr('data-url')+'&do=coverPhotoPosition'+'&offset='+this._newPosition;});this._resetImage();},cancelPosition:function(e){e.preventDefault();this._resetImage();},positionPhoto:function(e){if(e!=undefined)e.preventDefault();this.scope.addClass('ipsCoverPhoto--editing');this._existingPosition=parseInt(this.scope.attr('data-coveroffset'))||0;this._container=this.scope.find('.ipsCoverPhoto__container')[0];this._mouseDownHandler=this._mouseDownHandler.bind(this);this._container.addEventListener('mousedown',this._mouseDownHandler);this._mouseUpHandler=this._mouseUpHandler.bind(this);this._container.addEventListener('mouseup',this._mouseUpHandler);this._mouseOutHandler=this._mouseOutHandler.bind(this);this._container.addEventListener('mouseout',this._mouseOutHandler);this._container.scrollTop=(this._container.scrollHeight-this._container.clientHeight)*(this._existingPosition/100);this.scope.find('.ipsCoverPhoto__container').after(ips.templates.render('core.coverPhoto.controls'));this._showTooltip();},_mouseDownHandler:function(e){e.preventDefault();this._editingPosMouse=e.clientY;this._editingPosScroll=this._container.scrollTop;this._mouseMoveHandler=this._mouseMoveHandler.bind(this);this._container.addEventListener('mousemove',this._mouseMoveHandler);},_mouseMoveHandler:function(e){let dy=(e.clientY-this._editingPosMouse)*2.3;this._container.scrollTop=this._editingPosScroll-dy;},_mouseUpHandler:function(e){this._container.removeEventListener('mousemove',this._mouseMoveHandler);},_mouseOutHandler:function(e){this._container.removeEventListener('mousemove',this._mouseMoveHandler);},_resetImage:function(){this._container.removeEventListener('mousedown',this._mouseDownHandler);this.scope.removeClass('ipsCoverPhoto--editing');this.scope.find('[data-role="reposition"]').remove();this.scope.find('[data-role="coverPhotoControls"]').remove();this._hideTooltip();ips.utils.history.pushState({},'core.global.core.coverPhoto',ips.utils.url.removeParam('csrfKey',this.scope.attr('data-url')));},_showTooltip:function(msg){if(!this._tooltip){this._buildTooltip();}
this._tooltip[0].hidePopover();this._tooltip.text(ips.getString('dragCoverPhoto'));this._positionTooltip();},_hideTooltip:function(){if(this._tooltip&&this._tooltip.is(':visible')){this._tooltip[0].hidePopover();}},_positionTooltip:function(){var positionInfo={trigger:this.scope.find('.ipsCoverPhoto__container'),target:this._tooltip,center:true,above:true};var tooltipPosition=ips.utils.position.positionElem(positionInfo);this._tooltip.css({left:tooltipPosition.left+'px',top:tooltipPosition.top+'px'});if(tooltipPosition.location.vertical=='top'){this._tooltip.addClass('ipsTooltip_top');}else{this._tooltip.addClass('ipsTooltip_bottom');}
this._tooltip[0].showPopover();},_buildTooltip:function(){var tooltipHTML=ips.templates.render('core.tooltip',{id:'elCoverPhotoTooltip'});ips.getContainer().append(tooltipHTML);this._tooltip=$('#elCoverPhotoTooltip');},toggleCoverPhoto:function(){if(this._expandedCover==false){let naturalImage=this.scope.find('.ipsCoverPhoto__image')[0],ratio=naturalImage.naturalWidth/naturalImage.naturalHeight;this.scope.find('.ipsCoverPhoto__container').css("--coverPhoto--ratio",ratio);this._expandedCover=true;this.scope.addClass('ipsCoverPhoto--expanded');}else{this._expandedCover=false;this.scope.removeClass('ipsCoverPhoto--expanded');}},});}(jQuery));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.cropper',{_image:null,_coords:{},initialize:function(){this.setup();},setup:function(){var self=this;this._image=this.scope.find('[data-role="profilePhoto"]');this._coords={topLeftX:this.scope.find('[data-role="topLeftX"]'),topLeftY:this.scope.find('[data-role="topLeftY"]'),bottomRightX:this.scope.find('[data-role="bottomRightX"]'),bottomRightY:this.scope.find('[data-role="bottomRightY"]'),};this._image.css({maxWidth:'100%'});ips.loader.getStatic(['applications/core/interface/static/cropper/cropper.min.js']).then(function(){self._image.imagesLoaded(_.bind(self._startCropper,self));});},_startCropper:function(){var self=this;var width=this._image.width();var height=this._image.height();this._image.closest('[data-role="cropper"]').css({width:width+'px',height:height+'px'});var cropper=new Cropper(this._image.get(0),{aspectRatio:1/1,autoCropArea:0.9,responsive:true,zoomOnWheel:false,crop:function(e){self._coords.topLeftX.val(e.detail.x);self._coords.topLeftY.val(e.detail.y);self._coords.bottomRightX.val(e.detail.width+e.detail.x);self._coords.bottomRightY.val(e.detail.height+e.detail.y);}});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.datetime',{initialize:function(){this.setup();},setup:function(){var formatObject={format:$(this.scope).attr('data-format')};var localeTimeFormat=ips.utils.time.localeTimeFormat($('html').attr('lang'));if(localeTimeFormat.meridiem){formatObject.meridiem=localeTimeFormat.meridiem;}
$(this.scope).text(ips.utils.time.formatTime(new Date($(this.scope).attr('data-time')),formatObject));}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.embeddedvideo',{initialize:function(){var video=this.scope.get(0);var canPlay=false;this.scope.find('source').each(function(){if(video.canPlayType($(this).attr('type'))){canPlay=true;}});if(!canPlay){if(this.scope.find('embed').length){this.scope.replaceWith(this.scope.find('embed'));}else{this.scope.replaceWith($(this.scope).find('a'));}}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.framebust',{initialize:function(){if(top!=self){$(this.scope).html('');}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.genericTable',{_curSearchValue:'',_urlParams:{},_baseURL:'',_searchField:null,_timer:null,_currentValue:'',initialize:function(){this.on('paginationClicked paginationJump',this.paginationClicked);this.on('click','[data-action="tableFilter"]',this.changeFiltering);this.on('menuItemSelected','[data-role="tableFilterMenu"]',this.changeFilteringFromMenu);this.on('focus','[data-role="tableSearch"]',this.startLiveSearch);this.on('blur','[data-role="tableSearch"]',this.endLiveSearch);this.on('click','[data-action="tableSort"]',this.changeSorting);this.on('menuItemSelected','#elSortMenu',this.sortByMenu);this.on('menuItemSelected','#elOrderMenu',this.orderByMenu);this.on('refreshResults',this._getResults);this.on('buttonAction',this.buttonAction);this.on(window,'historychange:core.global.core.genericTable',this.stateChange);this.setup();},setup:function(){this._baseURL=this.scope.attr('data-baseurl');if(this.scope.attr('data-baseurl').match(/\?/)){this._baseURL+='&';}else{this._baseURL+='?';}
this._searchField=this.scope.find('[data-role="tableSearch"]');var sort=this._getSortValue();this._urlParams={filter:this._getFilterValue()||'',sortby:sort.by||'',sortdirection:sort.order||'',quicksearch:this._getSearchValue()||'',page:ips.utils.url.getParam('page')||1};ips.utils.history.replaceState(this._urlParams,'core.global.core.genericTable',window.location.href);this.scope.find('[data-role="tableSearch"]').removeClass('ipsHide').show();},buttonAction:function(e,data){this._getResults();},sortByMenu:function(e,data){data.originalEvent.preventDefault();this._updateSort({by:data.selectedItemID});},orderByMenu:function(e,data){data.originalEvent.preventDefault();this._updateSort({order:data.selectedItemID});},stateChange:function(){const state={data:ips.utils.history.getState('core.global.core.genericTable'),url:window.location.href};if(state.data?.controller!=='genericTable'){return;}
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.genericTable',{_curSearchValue:'',_urlParams:{},_baseURL:'',_searchField:null,_timer:null,_currentValue:'',initialize:function(){this.on('paginationClicked paginationJump',this.paginationClicked);this.on('click','[data-action="tableFilter"]',this.changeFiltering);this.on('menuItemSelected','[data-role="tableFilterMenu"]',this.changeFilteringFromMenu);this.on('focus','[data-role="tableSearch"]',this.startLiveSearch);this.on('blur','[data-role="tableSearch"]',this.endLiveSearch);this.on('click','[data-action="tableSort"]',this.changeSorting);this.on('menuItemSelected','#elSortMenu',this.sortByMenu);this.on('menuItemSelected','#elOrderMenu',this.orderByMenu);this.on('refreshResults',this._getResults);this.on('buttonAction',this.buttonAction);this.on(window,'historychange:genericTable',this.stateChange);this.setup();},setup:function(){this._baseURL=this.scope.attr('data-baseurl');if(this.scope.attr('data-baseurl').match(/\?/)){this._baseURL+='&';}else{this._baseURL+='?';}
this._searchField=this.scope.find('[data-role="tableSearch"]');var sort=this._getSortValue();this._urlParams={filter:this._getFilterValue()||'',sortby:sort.by||'',sortdirection:sort.order||'',quicksearch:this._getSearchValue()||'',page:ips.utils.url.getParam('page')||1};ips.utils.history.replaceState({...this._urlParams,controller:this.controllerID},'genericTable',window.location.href);this.scope.find('[data-role="tableSearch"]').removeClass('ipsHide').show();},buttonAction:function(e,data){this._getResults();},sortByMenu:function(e,data=e.detail){data.originalEvent.preventDefault();this._updateSort({by:data.selectedItemID});},orderByMenu:function(e,data=e.detail){data.originalEvent.preventDefault();this._updateSort({order:data.selectedItemID});},stateChange:function(){const state={data:ips.utils.history.getState('genericTable'),url:window.location.href};if(state.data?.controller!==this.controllerID){return;}
if(!_.isUndefined(state.data.filter)&&state.data.filter!==this._urlParams.filter){this._updateFilter(state.data.filter);}
if((!_.isUndefined(state.data.sortby)&&!_.isUndefined(state.data.sortdirection))&&(state.data.sortby!==this._urlParams.sortby||state.data.sortdirection!==this._urlParams.sortdirection)){this._updateSort({by:state.data.sortby,order:state.data.sortdirection});}
if(!_.isUndefined(state.data.quicksearch)&&state.data.quicksearch!==this._urlParams.quicksearch){this._updateSearch(state.data.quicksearch);}
if(!_.isUndefined(state.data.page)&&state.data.page!==this._urlParams.page){this._updatePage(state.data.page);}
this._urlParams=state.data;this._getResults();},updateURL:function(newParams){_.extend(this._urlParams,newParams);const tmpStateData=_.extend(_.clone(this._urlParams),{controller:'genericTable'});const newUrlParams=this._getURL();if(newUrlParams.match(/page=\d/)){this._baseURL=this._baseURL.replace(/page=\d+?(&|\s)/,'');}
this._urlParams=state.data;this._getResults();},updateURL:function(newParams){_.extend(this._urlParams,newParams);const tmpStateData={...this._urlParams,...newParams,controller:this.controllerID};const newUrlParams=this._getURL();if(newUrlParams.match(/page=\d/)){this._baseURL=this._baseURL.replace(/page=\d+?(&|\s)/,'');}
let newUrl=this._baseURL+newUrlParams;if(newUrl.endsWith('?')){newUrl=newUrl.substring(0,newUrl.length-1);}
ips.utils.history.pushState(tmpStateData,'core.global.core.genericTable',newUrl);},_getURL:function(){var tmpUrlParams={};for(var i in this._urlParams){if(this._urlParams[i]!=''&&i!='controller'&&(i!='page'||(i=='page'&&this._urlParams[i]!=1))){tmpUrlParams[i]=this._urlParams[i];}}
ips.utils.history.pushState(tmpStateData,'genericTable',newUrl);},_getURL:function(){var tmpUrlParams={};for(var i in this._urlParams){if(this._urlParams[i]!=''&&i!='controller'&&(i!='page'||(i=='page'&&this._urlParams[i]!=1))){tmpUrlParams[i]=this._urlParams[i];}}
return $.param(tmpUrlParams);},paginationClicked:function(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
if(data.pageNo!=this._urlParams.page){this.updateURL({page:data.pageNo});}},_updatePage:function(newPage){this.scope.find('[data-role="tablePagination"] [data-page]').removeClass('ipsPagination_pageActive').end().find('[data-page="'+newPage+'"]').addClass('ipsPagination_pageActive');},changeFiltering:function(e){e.preventDefault();var newFilter=$(e.currentTarget).attr('data-filter');this._updateFilter(newFilter);if(newFilter!=this._urlParams.filter){this.updateURL({filter:newFilter,page:1});}},changeFilteringFromMenu:function(e,data){var newFilter=$(data.originalEvent.target).closest('li').attr('data-filter');this._updateFilter(newFilter);if(newFilter!=this._urlParams.filter){this.updateURL({filter:newFilter,page:1});}},_updateFilter:function(newFilter){this.scope.find('[data-role="tableSortBar"] [data-action="tableFilter"] a').removeClass('ipsButtonRow_active').end().find('[data-action="tableFilter"][data-filter="'+newFilter+'"] a').addClass('ipsButtonRow_active');},startLiveSearch:function(e){this._timer=setInterval(_.bind(this._checkSearchValue,this),500);},endLiveSearch:function(e){clearInterval(this._timer);},_checkSearchValue:function(){var val=this._searchField.val();if(this._currentValue!=val){this.updateURL({quicksearch:val,page:1});this._currentValue=val;}},_updateSearch:function(searchValue){this._searchField.val(searchValue);},changeSorting:function(e){e.preventDefault();var cell=$(e.currentTarget);var order='';if(cell.hasClass('ipsTable_sortableActive')){order=(cell.hasClass('ipsTable_sortableDesc'))?'asc':'desc';}else{order=(cell.hasClass('ipsTable_sortableDesc'))?'desc':'asc';}
if(data.pageNo!=this._urlParams.page){this.updateURL({page:data.pageNo});}},_updatePage:function(newPage){this.scope.find('[data-role="tablePagination"] [data-page]').removeClass('ipsPagination_pageActive').end().find('[data-page="'+newPage+'"]').addClass('ipsPagination_pageActive');},changeFiltering:function(e){e.preventDefault();var newFilter=$(e.currentTarget).attr('data-filter');this._updateFilter(newFilter);if(newFilter!=this._urlParams.filter){this.updateURL({filter:newFilter,page:1});}},changeFilteringFromMenu:function(e,data=e.detail){var newFilter=$(data.originalEvent.target).closest('[data-filter]').attr('data-filter');this._updateFilter(newFilter);if(newFilter!=this._urlParams.filter){this.updateURL({filter:newFilter,page:1});}},_updateFilter:function(newFilter){this.scope.find('[data-role="tableSortBar"] [data-action="tableFilter"] a').removeClass('ipsButtonRow_active').end().find('[data-action="tableFilter"][data-filter="'+newFilter+'"] a').addClass('ipsButtonRow_active');},startLiveSearch:function(e){this._timer=setInterval(_.bind(this._checkSearchValue,this),500);},endLiveSearch:function(e){clearInterval(this._timer);},_checkSearchValue:function(){var val=this._searchField.val();if(this._currentValue!=val){this.updateURL({quicksearch:val,page:1});this._currentValue=val;}},_updateSearch:function(searchValue){this._searchField.val(searchValue);},changeSorting:function(e){e.preventDefault();var cell=$(e.currentTarget);var order='';if(cell.hasClass('ipsTable_sortableActive')){order=(cell.hasClass('ipsTable_sortableDesc'))?'asc':'desc';}else{order=(cell.hasClass('ipsTable_sortableDesc'))?'desc':'asc';}
this._updateSort({by:cell.attr('data-key'),order:order});},_updateSort:function(data){var directions='ipsTable_sortableAsc ipsTable_sortableDesc';var current=this._getSortValue();if(!data.by){data.by=current.by;}
if(!data.order){data.order=current.order;}
this.scope.find('[data-role="table"] [data-action="tableSort"]').removeClass('ipsTable_sortableActive').removeAttr('aria-sort').end().find('[data-action="tableSort"][data-key="'+data.by+'"]').addClass('ipsTable_sortableActive').removeClass(directions).addClass('ipsTable_sortable'+data.order.charAt(0).toUpperCase()+data.order.slice(1)).attr('aria-sort',(data.order=='asc')?'ascending':'descending');$('#elSortMenu_menu, #elOrderMenu_menu').find('.ipsMenu_item').removeClass('ipsMenu_itemChecked').end().find('[data-ipsMenuValue="'+data.by+'"], [data-ipsMenuValue="'+data.order+'"]').addClass('ipsMenu_itemChecked');this.updateURL({sortby:data.by,sortdirection:data.order,page:1});},_getResults:function(){var self=this;ips.getAjax()(this._baseURL+this._getURL()+'&'+this.scope.attr('data-resort')+'=1',{dataType:'json',showLoading:true}).done(function(response){self._updateTable(response);}).fail(function(jqXHR,textStatus,errorThrown){if(Debug.isEnabled()){Debug.error("Ajax request failed ("+status+"): "+errorThrown);Debug.error(jqXHR.responseText);}else{window.location=self._baseURL+self._getURL();}});},_updateTable:function(response){this.scope.find('[data-role="tableRows"]').html(response.rows);this.scope.find('[data-role="tablePagination"]').toggle((response.pagination&&response.pagination.trim()!=="")||!_.isUndefined(this.scope.find('[data-role="tablePagination"]').attr('data-showEmpty'))).html(response.pagination||"");$(document).trigger('contentChange',[this.scope]);},_getFilterValue:function(){var sortBar=this.scope.find('[data-role="tableSortBar"]');if(!sortBar.length){return'';}
this.scope.find('[data-role="table"] [data-action="tableSort"]').removeClass('ipsTable_sortableActive').removeAttr('aria-sort').end().find('[data-action="tableSort"][data-key="'+data.by+'"]').addClass('ipsTable_sortableActive').removeClass(directions).addClass('ipsTable_sortable'+data.order.charAt(0).toUpperCase()+data.order.slice(1)).attr('aria-sort',(data.order=='asc')?'ascending':'descending');$('#elSortMenu_menu, #elOrderMenu_menu').find('[aria-selected="true"]').removeAttr('aria-selected').end().find('[data-ipsMenuValue="'+data.by+'"], [data-ipsMenuValue="'+data.order+'"]').attr('aria-selected','true');this.updateURL({sortby:data.by,sortdirection:data.order,page:1});},_getResults:function(){var self=this;ips.getAjax()(this._baseURL+this._getURL()+'&'+this.scope.attr('data-resort')+'=1',{dataType:'json',showLoading:true}).done(function(response){self._updateTable(response);}).fail(function(jqXHR,textStatus,errorThrown){if(Debug.isEnabled()){Debug.error("Ajax request failed ("+status+"): "+errorThrown);Debug.error(jqXHR.responseText);}else{window.location=self._baseURL+self._getURL();}});},_updateTable:function(response){this.scope.find('[data-role="tableRows"]').html(response.rows);this.scope.find('[data-role="tablePagination"]').toggle((response.pagination&&response.pagination.trim()!=="")||!_.isUndefined(this.scope.find('[data-role="tablePagination"]').attr('data-showEmpty'))).html(response.pagination||"");$(document).trigger('contentChange',[this.scope]);},_getFilterValue:function(){var sortBar=this.scope.find('[data-role="tableSortBar"]');if(!sortBar.length){return'';}
return sortBar.find('.ipsButtonRow_active').closest('[data-filter]').attr('data-filter');},_getSortValue:function(){var sortBy=this.scope.find('[data-role="table"] thead .ipsTable_sortable.ipsTable_sortableActive');var sortOrder='desc';if(sortBy.hasClass('ipsTable_sortableAsc')){sortOrder='asc';}
return{by:sortBy.attr('data-key'),order:sortOrder};},_getSearchValue:function(){if(ips.utils.url.getParam('quicksearch')){return ips.utils.url.getParam('quicksearch');}
return this.scope.find('[data-role="tableSearch"]').val();},_actionReplace:function(target,contents){var tr=$(target).closest('tr');var prevElem=tr.prev();tr.replaceWith(contents);$(document).trigger('contentChange',[prevElem.next()]);}});}(jQuery,_));;
@@ -31,7 +31,7 @@ progressBar.css('width',((100-(100/(waitUntil-start)*(waitUntil-Date.now()))))+'
if('key'in mapData){this._mapData=mapData;ips.ui.map.afterGoogleMapsLoaded(()=>this.setupGoogleMaps())}},setupGoogleMaps(){let position={lat:this._mapData.lat,lng:this._mapData.long};let elem=this.scope.find('[data-role="mapContainer"]').get(0);let maptype='ROADMAP';if(this._mapData.maptype&&window.google.maps.MapTypeId[this._mapData.maptype.toUpperCase()]){maptype=this._mapData.maptype.toUpperCase();}
let map=new window.google.maps.Map(elem,{center:position,zoom:this._mapData.zoom?this._mapData.zoom*8:15,scale:this._mapData.scale||undefined,mapTypeId:window.google.maps.MapTypeId[maptype.toUpperCase()]});let marker=new window.google.maps.Marker({position,map});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.licenseRenewal',{initialize:function(){this.on('click','[data-action="notNow"]',this.renewalPrompt);this.on(document,'click','[data-action="closeLicenseRenewal"]',this.close);},renewalPrompt:function(e){e.preventDefault();this._modal=ips.ui.getModal();if(!$('body').find('[data-role="licenseRenewal"]').length){$('body').append(ips.templates.render('licenseRenewal.wrapper'));}
this._container=$('body').find('[data-role="licenseRenewal"]').css({opacity:"0.001",transform:"scale(0.8)"});$('body').find('[data-role="survey"]').attr('href',$(this.scope).attr('data-surveyUrl'));this._modal.css({zIndex:ips.ui.zIndex()});var self=this;setTimeout(function(){self._container.css({zIndex:ips.ui.zIndex()});self._container.animate({opacity:"1",transform:"scale(1)"},'fast');},500);ips.utils.anim.go('fadeIn',this._modal);},close:function(e){if($('body').find('[data-role="licenseRenewal"]').find('input[type=checkbox][name=hideRenewalNotice]').is(':checked')){var notification=$(this.scope).closest('.cNotification,.cAcpNotificationBanner');ips.getAjax()($(this.scope).find('[data-action="notNow"]').attr('href')).done(function(response){ips.utils.anim.go('fadeOut',notification);if(!notification.closest('.cNotificationList').children().count){ips.utils.anim.go('fadeIn',notification.closest('.cNotificationList').find('[data-role="empty"]').removeClass('ipsHide'));}
this._container=$('body').find('[data-role="licenseRenewal"]').css({opacity:"0.001"});$('body').find('[data-role="survey"]').attr('href',$(this.scope).attr('data-surveyUrl'));this._modal.css({zIndex:ips.ui.zIndex()});var self=this;self._container.css({zIndex:ips.ui.zIndex()});self._container.animate({opacity:"1",},'fast');ips.utils.anim.go('fadeIn',this._modal);},close:function(e){if($('body').find('[data-role="licenseRenewal"]').find('input[type=checkbox][name=hideRenewalNotice]').is(':checked')){var notification=$(this.scope).closest('.cNotification,.cAcpNotificationBanner');ips.getAjax()($(this.scope).find('[data-action="notNow"]').attr('href')).done(function(response){ips.utils.anim.go('fadeOut',notification);if(!notification.closest('.cNotificationList').children().count){ips.utils.anim.go('fadeIn',notification.closest('.cNotificationList').find('[data-role="empty"]').removeClass('ipsHide'));}
$('body').trigger('updateNotificationCount');});}
$('body').find('[data-role="licenseRenewal"]').animate({transform:"scale(0.7)",opacity:"0"},'fast');ips.utils.anim.go('fadeOut',this._modal);}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.multipleRedirect',{_iterator:0,initialize:function(){var self=this;this.setup();},setup:function(){this.scope.find('.ipsRedirect').removeClass('ipsHide');$('.ipsRedirect_manualButton').hide();this.step(this.scope.attr('data-url')+'&mr=0&_mrReset=1');},step:function(url){this._iterator++;var elem=this.scope;var self=this;ips.getAjax()(url).done(function(response){if(_.isObject(response)&&response.custom){var originalContent=$(elem.html()).removeClass('ipsHide');var newContent=elem.html(response.custom);newContent.find('[data-action="redirectContinue"]').click(function(e){e.preventDefault();elem.html(originalContent);self.step($(this).attr('href'));});$(document).trigger('contentChange',[elem]);return;}
@@ -44,7 +44,7 @@ var div=$('<div data-role="autoCompleteWrapper" />').html(this.scope.contents())
var self=this;var autoCompleteObj=ips.ui.autocomplete.getObj(this._autoComplete);this.scope.find('[data-action="showAutocomplete"]').hide();this.scope.find('[data-role="autoCompleteWrapper"]').show();this.scope.closest('.ipsFieldRow').find('.ipsFieldRow__label').show();setTimeout(function(){if(self._closedTagging){self.scope.find('[data-action="addToken"]').click();}else{autoCompleteObj.focus();}},100);}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.prefixedAutocomplete',{initialize:function(){this.setup();this.on('autoCompleteReady',this.autoCompleteReady);this.on('tokenAdded',this.tokensChanged);this.on('tokenDeleted',this.tokensChanged);this.on('menuItemSelected','[data-role="prefixButton"]',this.prefixSelected);this.scope.find('[data-ipsAutocomplete]').trigger('reissueReady');},setup:function(){this._prefixRow=this.scope.find('[data-role="prefixRow"]');this._prefixValue=this.scope.find('[data-role="prefixValue"]');this._prefixButton=this.scope.find('[data-role="prefixButton"]');this._prefixMenu=this.scope.find('[data-role="prefixMenu"]');},autoCompleteReady:function(e,data){var tokens=data.currentValues;if(this._prefixValue&&tokens.length){this._prefixMenu.html(this._buildTokenList(tokens,this._prefixValue.val()));this._prefixButton.find('span').html(this._getPrefixText(_.escape(this._prefixValue.val())));this._prefixRow.show();}},tokensChanged:function(e,data){if(data.totalTokens>0&&!this._prefixRow.is(':visible')){ips.utils.anim.go('fadeIn',this._prefixRow);}else if(data.totalTokens===0&&this._prefixRow.is(':visible')){ips.utils.anim.go('fadeOut',this._prefixRow);this._prefixRow.find('input[type="checkbox"]').prop('checked',false);}
if(e&&e.type=='tokenDeleted'&&data.token==this._prefixValue.val()){this._prefixButton.find('span').html(ips.getString('selectPrefix'));this._prefixValue.val('');}
var value=this._prefixValue.val();var list=this._buildTokenList(data.tokenList,value);this._prefixMenu.html(list);},prefixSelected:function(e,data){data.originalEvent.preventDefault();var itemValue=(data.selectedItemID=='-')?'':data.selectedItemID;var selectedText=this._getPrefixText(data.selectedItemID);this._prefixButton.find('span').html(selectedText);this._prefixValue.val(itemValue);this._prefixRow.find('input[type="checkbox"]').prop('checked',true);},_buildTokenList:function(tokens,value){var output='';output+=ips.templates.render('core.menus.menuItem',{value:'',title:ips.getString('selectedNone'),checked:(value=='')});output+=ips.templates.render('core.menus.menuSep');$.each(tokens,function(i,item){output+=ips.templates.render('core.menus.menuItem',{value:item,title:_.unescape(item),checked:(item==value)});});return output;},_getPrefixText:function(prefix){var selectedText='';if(prefix&&prefix!='-'){selectedText=ips.getString('selectedPrefix',{tag:prefix});}else{selectedText=ips.getString('selectedPrefix',{tag:ips.getString('selectedNone')});}
var value=this._prefixValue.val();var list=this._buildTokenList(data.tokenList,value);this._prefixMenu.html(list);},prefixSelected:function(e,data=e.detail){data.originalEvent.preventDefault();var itemValue=(data.selectedItemID=='-')?'':data.selectedItemID;var selectedText=this._getPrefixText(data.selectedItemID);this._prefixButton.find('span').html(selectedText);this._prefixValue.val(itemValue);this._prefixRow.find('input[type="checkbox"]').prop('checked',true);},_buildTokenList:function(tokens,value){var output='';output+=ips.templates.render('core.menus.menuItem',{value:'',title:ips.getString('selectedNone'),checked:(value=='')});output+=ips.templates.render('core.menus.menuSep');$.each(tokens,function(i,item){output+=ips.templates.render('core.menus.menuItem',{value:item,title:_.unescape(item),checked:(item==value)});});return output;},_getPrefixText:function(prefix){var selectedText='';if(prefix&&prefix!='-'){selectedText=ips.getString('selectedPrefix',{tag:prefix});}else{selectedText=ips.getString('selectedPrefix',{tag:ips.getString('selectedNone')});}
return selectedText;}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.core.table',{_urlParams:{},_baseURL:'',_otherParams:[],_pageParam:'page',_updateURL:true,_currentPage:1,_seoPagination:false,_initialURL:'',_ajax:null,initialize:function(){this.on('paginationClicked paginationJump',this.paginationClicked);this.on('refreshResults',this.refreshResults);this.on('buttonAction',this.buttonAction);this.on('click','[data-action="tableFilter"]',this.changeFiltering);this.on('menuItemSelected','[data-role="tableFilterMenu"]',this.changeFilteringFromMenu);this.on('click','tr[data-tableClickTarget]',this.rowClick);this.setup();},setup:function(){if(this.scope.attr('data-pageParam')&&this.scope.attr('data-pageParam')!='page'){this._pageParam=this.scope.attr('data-pageParam');}
this._otherParams.push(this._pageParam);this._baseURL=this.scope.attr('data-baseurl');const safeURL=[...(new TextEncoder()).encode(this.scope.attr('data-baseurl')?ips.utils.url.pageParamToPath(this._cleanUpURL(this.scope.attr('data-baseurl')),this._pageParam,1):'')].map(char=>String.fromCodePoint(char)).join('');this._stateKey=`table${btoa(safeURL)}`;this._originalBaseURL=this._baseURL;this._currentPage=ips.utils.url.getPageNumber(this._pageParam,window.location.href);this._cleanUpBaseURL();if(this._baseURL.match(/\?/)){if(this._baseURL.slice(-1)!='?'){this._baseURL+='&';}}else{this._baseURL+='?';}
@@ -66,10 +66,10 @@ return out;},updateURL(newParams){newParams=this._filterParamsForChanges(newPara
if(!Object.keys(newParams).length){return;}
const tmpStateData={...this._urlParams,...newParams,controller:this.controllerID};let newUrl=(this._baseURL+this._getURL(tmpStateData)).replace(/^([^?]*)?$/,'$1').replace(/&$/,'');if(this._seoPagination){newUrl=ips.utils.url.pageParamToPath(newUrl,this._pageParam,newParams[this._pageParam]);}
ips.utils.history.pushState(tmpStateData,this._stateKey,newUrl);},paginationClicked(e,data){e.stopPropagation?.();e.stopImmediatePropagation?.();data.originalEvent?.preventDefault()
this._seoPagination=data.seoPagination;this.updateURL({[this._pageParam]:parseInt(data.pageNo)});},changeFiltering(e){e.preventDefault();this.updateURL({filter:$(e.currentTarget).attr('data-filter'),[this._pageParam]:1});},_updateFilter(newFilter){},_updateSort(data){},_updatePage(newPage){if(newPage===this._currentPage){return;}
this._seoPagination=data.seoPagination;this.updateURL({[this._pageParam]:parseInt(data.pageNo)});},changeFiltering(e){e.preventDefault();let newTableFilter=$(e.currentTarget).attr('data-filter');if(newTableFilter){this.updateURL({filter:newTableFilter,[this._pageParam]:1});}},_updateFilter(newFilter){},_updateSort(data){},_updatePage(newPage){if(newPage===this._currentPage){return;}
const boundingBox=this.scope.get(0).getBoundingClientRect();let padding=parseInt(ips.getSetting('tableScrollTopPadding'));if(!Number.isInteger(padding)){padding=30;}
if(boundingBox.top<padding){window.scrollBy({top:boundingBox.top-padding,behavior:'smooth'});}
this._currentPage=newPage;},changeFilteringFromMenu(e,data){data.originalEvent?.preventDefault();if(!('selectedItemID'in data)){return;}
this._currentPage=newPage;},changeFilteringFromMenu(e,data=e.detail){data.originalEvent?.preventDefault();if(!('selectedItemID'in data)){return;}
this.updateURL({filter:data.selectedItemID,[this._pageParam]:1});},_cleanUpURL(url){const urlObj=ips.utils.url.getURIObject(url);const params=_.clone(urlObj.queryKey);url=urlObj.protocol+'://'+urlObj.host+(urlObj.port?(':'+urlObj.port):'')+urlObj.path+'?';if(urlObj.file==='index.php'){let hasFURL=false;for(const key of Object.keys(params)){if(key.startsWith('/')){hasFURL=true;url+=encodeURIComponent(key).replace(/%2f/ig,'/');delete params[key];}}
if(hasFURL){url+='&';}}
for(const param of['sortby','sortdirection','filter',...this._otherParams]){delete params[param]}
@@ -91,7 +91,7 @@ let page=Number(e.currentTarget.dataset['page']);if(isNaN(page))return;$('body')
const tmpUrlParams={};for(const i in params){if(['','controller','app','module','bypassState'].includes(i)||(i===this._pageParam&&parseInt(params[i])===1)||!params[i]){continue}
tmpUrlParams[i]=params[i];}
return $.param(tmpUrlParams);},_getUrlParams:function(){var sort=this._getSortValue();var obj={filter:this._getFilterValue()||'',sortby:sort.by||'',sortdirection:sort.order||'',};obj[this._pageParam]=ips.utils.url.getParam(this._pageParam)||1
return obj;},rowClick:function(e){var target=$(e.target);if(target.is('a')||target.is('i')||target.is('input')||target.is('textarea')||target.is('code')||target.closest('a').length||target.closest('.ipsMenu').length){return;}
return obj;},rowClick:function(e){var target=$(e.target);if(target.is('a')||target.is('button')||target.is('i')||target.is('input')||target.is('textarea')||target.is('code')||target.closest('a').length||target.closest('.ipsMenu').length){return;}
if(e.which!==1&&e.which!==2){return;}
if(e.altKey||e.shiftKey){return;}
if(target.is('td')){var checkbox=target.find('input[type="checkbox"]');if(checkbox.length){checkbox.prop('checked',!checkbox.prop('checked'));return;}}
@@ -2,4 +2,4 @@
var parentLink=elem.closest('a');if(parentLink.length){parentLink.off('click',this._boundHandler);if(parentLink.attr('data-vleHref')){parentLink.attr('href',parentLink.attr('data-vleHref')).removeAttr('data-vleHref');}}},_preventDefaultHandler:function(e){e.preventDefault();},_enableLangEditing:function(e){var elem=$(e.currentTarget);var parentLink=elem.closest('a');if(parentLink.length){parentLink.on('click',this._boundHandler).attr('data-vleHref',parentLink.attr('href')).attr('href','#');}
var inputNode=$('<input/>').attr({type:'text'}).addClass('ipsField_loading ipsField_vle').attr('data-role','vle');elem.html('').append(inputNode);ips.getAjax()('?app=core&module=system&controller=vle&do=get&key='+elem.attr('data-vle')).done(function(response){console.log(elem.attr('data-vle'));inputNode.val(response).attr({'data-original':response}).removeClass('ipsField_loading').focus().select()}).fail(function(){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('js_login_both'),});});},_removeLangTag:function(element){if(_.isUndefined(element)){return;}
var elem=$(element);elem.contents().filter(function(){return this.nodeType===3||this.tagName==="LABEL"||this.tagName==="SPAN";}).each(function(){$(this).replaceWith($(this).text().replace(/#VLE#(.+?)#!#/gm,function(match,key){return(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined)?ipsVle[key]:'';}));});elem.find('i[class]').each(function(){$(this).attr('class',$(this).attr('class').replace(/#VLE#(.+?)#!#/gm,function(match,key){return(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined)?ipsVle[key]:'';}));});elem.find('[placeholder]').each(function(){$(this).attr('placeholder',$(this).attr('placeholder').replace(/#VLE#(.+?)#!#/gm,function(match,key){return(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined)?ipsVle[key]:'';}));});elem.find('[title]').each(function(){$(this).attr('title',$(this).attr('title').replace(/#VLE#(.+?)#!#/gm,function(match,key){return(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined)?ipsVle[key]:'';}));});elem.find('[aria-label]').each(function(){$(this).attr('aria-label',$(this).attr('aria-label').replace(/#VLE#(.+?)#!#/gm,function(match,key){return(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined)?ipsVle[key]:'';}));});},_setUpTextNodes:function(element){if(_.isUndefined(element)){return;}
var regex=/#VLE#([0-9a-z_-]+?)#!#/igm;$(element).find('*').contents().filter(function(){var elem=$(this);return!elem.is('iframe')&&!elem.closest('[data-ipsEditor]').length&&!elem.is('textarea')&&(elem.is('[value]')||this.nodeType==3);}).each(function(idx,elem){var elem=$(elem);if(elem.get(0).nodeType===3){elem.replaceWith(elem.text().replace(regex,function(match,key){if(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined){return'<span data-vle="'+key+'" data-original="'+ipsVle[key]+'">'+ipsVle[key]+'</span>';}else{return Debug.isEnabled()?key:'';}}));}else if(elem.is('[value]')){if(elem.val()!==''){elem.attr('data-vle',elem.val().replace(regex,'$1')).val(elem.val().replace(regex,function(match,key){if(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined){return ipsVle[key];}else{return Debug.isEnabled()?key:'';}}));}}});}});}(jQuery,_));;
var regex=/#VLE#([0-9a-z_-]+?)#!#/igm;$(element).find('*').contents().filter(function(){var elem=$(this);return!elem.is('iframe')&&!elem.closest('[data-ipsEditor]').length&&!elem.is('textarea')&&(elem.is('[value]')||this.nodeType==3);}).each(function(idx,elem){var elem=$(elem);if(elem.get(0).nodeType===3){elem.replaceWith(elem.text().replace(regex,function(match,key){if(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined){return'<span data-vle="'+key+'" data-original="'+ipsVle[key]+'">'+ipsVle[key]+'</span>';}else{return Debug.isEnabled()?key:'';}}));}else if(elem.is('[value]')){if(elem.val()!==''&&elem.val().length){elem.attr('data-vle',elem.val().replace(regex,'$1')).val(elem.val().replace(regex,function(match,key){if(ipsVle.hasOwnProperty(key)&&ipsVle[key]!==undefined){return ipsVle[key];}else{return Debug.isEnabled()?key:'';}}));}}});}});}(jQuery,_));;
+1 -1
View File
@@ -10,7 +10,7 @@ if(!this._hasExistingScreenshots()&&this._requireScreenshots){this._ui.fileInfo.
if(data.count===0){this.scope.find('#elDownloadsSubmit_progress .ipsProgress__progress').attr('data-progress','0%').css({width:'0%'});this._ui.progressBar.hide();this._hiddenUploader=false;this._overriddenUploader=true;}},uploadCounter:function(e,data){if(data.uploader!='files'){return;}
this._uploadedCount=data.count;this._toggleFileImportOptions();},uploadProgress:function(e,data){if(data.uploader!='files'){return;}
var self=this;this._showProgress();this.scope.find('#elDownloadsSubmit_progress .ipsProgress__progress').attr('data-progress',data.percent+'%').css({width:data.percent+'%'});if(data.percent===100&&!this._progressbarTimeout){this._progressbarTimeout=setTimeout(function(){self._ui.progressBar.find('.ipsProgress').removeClass('ipsProgress--animated');self._progressbarTimeout=null;},300);}},_confirmMenu:function(inputName,elemID){var length=0;var invalid=0;this.scope.find('input[name^="'+inputName+'"]').each(function(){if($(this).val().trim()){length++;}
if(!_.isUndefined(this.checkValidity)&&!this.checkValidity()){invalid++;}});if(!invalid){this.scope.find('#'+elemID).trigger('closeMenu');}
if(!_.isUndefined(this.checkValidity)&&!this.checkValidity()){invalid++;}});if(!invalid){this.elem.querySelector(`#${elemID}_menu`)?.closest("[popover]")?.hidePopover();}
this._toggleFileImportOptions();this.scope.find('#'+elemID+' [data-role="fileCount"]').text(length);if(length){this.scope.find('#'+elemID+' [data-role="fileCount"]').show();return true;}else{this.scope.find('#'+elemID+' [data-role="fileCount"]').hide();return false;}},_hasExistingFiles:function(){if(this._uploadedCount||this.scope.find('input[name^="files_existing"]').length){return true;}
var hasURL=[];var hasImport=[];if(this.scope.find('input[name^="url_files"]').length){hasURL=_.filter(this.scope.find('input[name^="url_files"]'),function(item){if($(item).val().trim()!=''){return true;}
return false;});}
+2 -2
View File
@@ -1,7 +1,7 @@
;(function($,_,undefined){"use strict";ips.controller.register('downloads.front.view.changeLog',{initialize:function(){this.on('menuItemSelected',this.changeVersion);this.setup();this.on(window,'historychange:downloads.front.view.changeLog',this.stateChange);},setup:function(){ips.utils.history.replaceState({controller:'changelog'},'downloads.front.view.changeLog',window.location.href);},changeVersion:function(e,data){data.originalEvent.preventDefault();var url=data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"] > a').attr('href');ips.utils.history.pushState({controller:'changelog',version:data.selectedItemID},'downloads.front.view.changeLog',url);this._loadVersion(url,data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"]').attr('data-changelogTitle'));},stateChange:function(){const state=ips.utils.history.getState('downloads.front.view.changeLog')
;(function($,_,undefined){"use strict";ips.controller.register('downloads.front.view.changeLog',{initialize:function(){this.on('menuItemSelected',this.changeVersion);this.setup();this.on(window,'historychange:downloads.front.view.changeLog',this.stateChange);},setup:function(){ips.utils.history.replaceState({controller:'changelog'},'downloads.front.view.changeLog',window.location.href);},changeVersion:function(e,data=e.detail){data.originalEvent.preventDefault();var url=$(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"]').attr('href');ips.utils.history.pushState({controller:'changelog',version:data.selectedItemID},'downloads.front.view.changeLog',url);this._loadVersion(url,$(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"]').attr('data-changelogTitle'));},stateChange:function(){const state=ips.utils.history.getState('downloads.front.view.changeLog')
if(!state||!Object.keys(state).length){return;}
let item;if(state.version){item=$('#elChangelog_menu').find('[data-ipsMenuValue="'+state.version+'"]');}else{item=$('#elChangelog_menu').find('[data-ipsMenuValue]').first();}
this._loadVersion(item.find('a').attr('href'),item.attr('data-ipsMenuValue'));},_loadVersion:function(url,versionTitle){var self=this;this.scope.find('[data-role="versionTitle"]').text(versionTitle);this.scope.find('[data-role="changeLogData"]').css({height:this.scope.find('[data-role="changeLogData"]').height()+'px'}).addClass('ipsLoading').html('');ips.getAjax()(url).done(function(response){self.scope.find('[data-role="changeLogData"]').html(response).removeClass('ipsLoading').css({height:'auto'});}).fail(function(jqXHR,textStatus,errorThrown){window.location=url;});}});}(jQuery,_));;
this._loadVersion(item.attr('href'),item.attr('data-ipsMenuValue'));},_loadVersion:function(url,versionTitle){var self=this;this.scope.find('[data-role="versionTitle"]').text(versionTitle);this.scope.find('[data-role="changeLogData"]').css({height:this.scope.find('[data-role="changeLogData"]').height()+'px'}).addClass('ipsLoading').html('');ips.getAjax()(url).done(function(response){self.scope.find('[data-role="changeLogData"]').html(response).removeClass('ipsLoading').css({height:'auto'});}).fail(function(jqXHR,textStatus,errorThrown){window.location=url;});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('downloads.front.view.download',{initialize:function(){this.on('click','[data-action="dialogClose"]',this.closeDialog);this.on('click','[data-action="selectFile"]',this.selectFile);this.on('click','[data-action="download"]',this.doDownload);},selectFile:function(e){var url=$(e.currentTarget).attr('href');var self=this;e.preventDefault();this.scope.html('').css({height:'250px'}).addClass('ipsLoading');ips.getAjax()(url).done(function(response){self.scope.html(response).css({height:'auto'}).removeClass('ipsLoading');}).fail(function(jqXHR,textStatus,errorThrown){window.location=url;});},closeDialog:function(e){e.preventDefault();this._closeDialog($(e.currentTarget).attr('href'));},_closeDialog:function(href){if(this.scope.closest('.ipsDialog').length){this.scope.closest('.ipsDialog').trigger('closeDialog');}else{window.location=href;}},doDownload:function(e){var that=this;if($(e.currentTarget).attr('data-wait')){e.preventDefault();ips.getAjax()($(e.currentTarget).attr('href')).done(function(response){$(e.currentTarget).trigger('ipsDataLayerSync');var secondsRemaining=response.download-response.currentTime;$(e.currentTarget).hide().siblings().find('[data-role="downloadCounter"]').html(secondsRemaining).end().end().siblings('[data-role="downloadCounterContainer"]').removeClass('ipsHide');var interval=setInterval(function(){secondsRemaining--;$(e.currentTarget).siblings().find('[data-role="downloadCounter"]').html(secondsRemaining);if(secondsRemaining===0){clearInterval(interval);window.location=$(e.currentTarget).attr('href');that.scope.closest('.ipsDialog').trigger('closeDialog');}},1000);}).fail(function(){window.location=$(e.currentTarget).attr('href');})}
else
{this.scope.closest('.ipsDialog').trigger('closeDialog');}}});}(jQuery,_));;
+3 -3
View File
@@ -4,12 +4,12 @@ var _ids=ips.utils.url.getParam(this.urlParam);if(!_.isUndefined(_ids)){this._id
if(!found){this.scope.find('[data-node-id]').each(function(i,node){var id=$(node).attr('data-node-id');self._ids.push(id);});}}else if(!_.isUndefined(ips.utils.cookie.get('forums_flowIds'))){this._ids=ips.utils.cookie.get('forums_flowIds').split(',');}
if(_.isObject(this._ids)&&_.size(this._ids)){_.each(this._ids,function(val,key){if(val){self.childSelect(val,true);}});}
if(_.isUndefined(_ids)&&this._ids.length&&this._rootForum===null){$(document).trigger('updateTableURL',{[this.urlParam]:_.uniq(_.values(this._ids)).join(',')});}
this._button=$('body').find('[data-role="fluidForumMobileDesc"]');this._updateButtonText();},toggleFilters:function(e){e.preventDefault();var link=$(e.currentTarget);var id=link.attr('data-node-id');var parentId=link.attr('data-parent-id');var hasChildren=link.attr('data-has-children');if(_.indexOf(this._ids,id)==-1){this.childSelect(id,false);}else{this.childUnselect(id);}
this._button=$('body').find("[data-ipsDialog-content='#elFluidFormFilters']");this._buttonText=$('body').find('[data-role="fluidForumMobileDesc"]');this._updateButtonText();},toggleFilters:function(e){e.preventDefault();var link=$(e.currentTarget);var id=link.attr('data-node-id');var parentId=link.attr('data-parent-id');var hasChildren=link.attr('data-has-children');if(_.indexOf(this._ids,id)==-1){this.childSelect(id,false);}else{this.childUnselect(id);}
this._updateButtonText();$(document).trigger('updateTableURL',{[this.urlParam]:_.uniq(_.values(this._ids)).join(',')});},isSelected:function(id){return this.scope.find('[data-node-id="'+id+'"]').hasClass('cForumMiniList__selected')?true:false;},childSelect:function(id,skipChildren){Debug.log("Select child: "+id);this._ids.push(id);var node=this.scope.find('[data-node-id="'+id+'"]');node.addClass('cForumMiniList__selected');var parentId=node.attr('data-parent-id');if(skipChildren===false&&(node.attr('data-has-children')||id==parentId)){var self=this;_.each(this.scope.find('[data-parent-id="'+id+'"]'),function(v,k){var _cId=$(v).attr('data-node-id');if(_cId!=id){self.childSelect(_cId,false);}});}
this.updateCookie();},childUnselect:function(id){Debug.log("UNselect child: "+id);this.scope.find('[data-node-id="'+id+'"]').removeClass('cForumMiniList__selected');this._ids=_.without(this._ids,id);this.updateCookie();if(this._rootForum===null){var self=this;_.each(this.scope.find('[data-parent-id="'+id+'"]'),function(v,k){var _cId=$(v).attr('data-node-id');if(_cId!=id){self.childUnselect(_cId);}});this.parentUnselect(this.scope.find('[data-node-id="'+id+'"]').closest('[data-category]').find('[data-node-id]').first().attr('data-node-id'));}},parentSelect:function(parentId){Debug.log("Select parent: "+parentId);this.scope.find('[data-node-id="'+parentId+'"]').addClass('cForumMiniList__selected');if(this._rootForum===null){var self=this;_.each(this.scope.find('[data-parent-id="'+parentId+'"]'),function(v,k){var _cId=$(v).attr('data-node-id');if(_cId!=parentId){self.childUnselect(_cId);}});}else{this.updateCookie();}},parentUnselect:function(parentId){Debug.log("UNselect parent: "+parentId);var node=this.scope.find('[data-node-id="'+parentId+'"]');node.removeClass('cForumMiniList__selected');this._ids=_.without(this._ids,parentId);this.updateCookie();Debug.log("Looking for parent ID "+node.attr('data-parent-id'));if(this._rootForum===null){var self=this;_.each(this.scope.find('[data-node-id="'+node.attr('data-parent-id')+'"]'),function(v,k){var _cId=$(v).attr('data-node-id');if(_cId!=parentId){Debug.log("Found "+_cId);self.parentUnselect(_cId);}});}},updateCookie:function(id){var cookie=_.uniq(_.values(this._ids)).join(',');Debug.log("Updating cookie: "+cookie);if(!this._rootForum){ips.utils.cookie.set('forums_flowIds',cookie,true);}else{var _json={};if(!_.isUndefined(ips.utils.cookie.get('forums_flowIdsRoots'))){_json=JSON.parse(ips.utils.cookie.get('forums_flowIdsRoots'));}
_json[this._rootForum]=_.uniq(_.values(this._ids));ips.utils.cookie.set('forums_flowIdsRoots',JSON.stringify(_json),true);Debug.log("Updating cookie: "+JSON.stringify(_json));}},_updateButtonText:function(){var blobs=this.scope.find('.cForumMiniList__blob');var selectedBlobRows=blobs.filter(function(){if($(this).closest('.cForumMiniList__selected').length){return true;}
return false;});var text='';if(blobs.length==selectedBlobRows.length||selectedBlobRows.length===0){text=ips.getString('topicsFromAllForums');}else{text=ips.pluralize(ips.getString('topicsFromXForums'),selectedBlobRows.length);}
this._button.text(text);}});}(jQuery,_));;
return false;});var text='',buttonClass='';if(blobs.length==selectedBlobRows.length||selectedBlobRows.length===0){text=ips.getString('topicsFromAllForums');buttonClass='ipsButton--inherit';}else{text=ips.pluralize(ips.getString('topicsFromXForums'),selectedBlobRows.length);buttonClass='ipsButton--secondary';}
this._buttonText.text(text);this._button.removeClass("ipsButton--inherit ipsButton--secondary").addClass(buttonClass);}});}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register('forums.front.forum.forumList',{initialize(){this.on('ips:toggleForumCategory',this.toggleCategory);this.setup();},setup(){let hiddenCategories=ips.utils.db.get('hiddenCategories');if(_.isObject(hiddenCategories)&&_.size(hiddenCategories)){_.each(hiddenCategories,function(val,key){document.querySelector("[aria-controls='forum-category_"+key+"']")?.setAttribute('aria-expanded','false');document.getElementById('forum-category_'+key)?.setAttribute('hidden','');});}},toggleCategory(e){const category=e.target;const categoryID=category.closest('[data-categoryID]')?.dataset.categoryid;if(!category||!categoryID){Debug.warn(`The forum list got a category hidden toggle event but couldn't determine which category was toggled`);return;}
if(e.detail.hidden){ips.utils.db.set('hiddenCategories',categoryID,true);}else{ips.utils.db.remove('hiddenCategories',categoryID);}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('forums.front.forum.forumPage',{initialize:function(){this.on('click','[data-action="markForumRead"]',this.markForumRead);},markForumRead(e){e.preventDefault();ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('markForumAsReadConfirm'),subText:'',callbacks:{ok:()=>{const url=$(e.currentTarget).attr('href');ips.getAjax()(url,{showLoading:true,bypassRedirect:true}).done(()=>{this.triggerOn('core.global.core.table','markTableRead');ips.utils.anim.go('fadeOut',$(e.currentTarget));ips.ui.flashMsg.show(ips.getString('forumMarkedRead'));}).fail(function(jqXHR,textStatus,errorThrown){window.location=url;});}}});}});}(jQuery,_));;
-14
View File
@@ -1,18 +1,4 @@
;(function($,_,undefined){"use strict";ips.controller.register('forums.front.topic.activity',{initialize:function(){this.on('click','[data-action="toggleOverview"]',this.toggleOverview);},toggleOverview:function(e){this.scope.toggleClass('cTopicOverview--expanded');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('forums.front.topic.answers',{ajaxObj:null,initialize:function(){this.on('click','a.cAnswerRate',this.rate);},rate:function(e){e.preventDefault();var self=this;var clicked=$(e.currentTarget);if(this.scope.find('.cAnswerRate_up').is('.i-color_positive')){var currentVote='positive';}
else if(this.scope.find('.cAnswerRate_down').is('.i-color_negative')){var currentVote='negative';}
else{var currentVote=false;}
var positive=clicked.hasClass('cAnswerRate_up');var voteCount=this.scope.find('[data-role="voteCount"]');var currentVotes=parseInt(voteCount.attr('data-voteCount'));var newVoteCount=0;var setPositive=false;var setNegative=false;if(currentVote!==false){if(positive&&currentVote=='positive'){newVoteCount=currentVotes-1;}
else if(!positive&&currentVote=='negative'){newVoteCount=currentVotes+1;}
else if(!positive&&currentVote=='positive'){newVoteCount=currentVotes-2;setNegative=true;}
else if(positive&&currentVote=='negative'){newVoteCount=currentVotes+2;setPositive=true;}}
else if(positive){newVoteCount=currentVotes+1;setPositive=true;}
else{newVoteCount=currentVotes-1;setNegative=true;}
this.setStyles(setPositive,setNegative);voteCount.toggleClass('i-color_positive',setPositive).toggleClass('i-color_negative',setNegative).text(newVoteCount).attr('data-voteCount',newVoteCount);if(this.ajaxObj&&_.isFunction(this.ajaxObj.abort)){this.ajaxObj.abort();}
this.ajaxObj=ips.getAjax()(clicked.attr('href')).done(function(response){Debug.log(response);voteCount.text(response.votes);self.scope.find('.i-color_soft').text(ips.pluralize(ips.getString('votes_no_number'),response.votes));});},setStyles:function(setPositive,setNegative){this.scope.find('.cAnswerRate_up').toggleClass('i-color_positive',setPositive);this.scope.find('.cAnswerRate_down').toggleClass('i-color_negative',setNegative);this.scope.toggleClass('cRatingColumn_up',setPositive).toggleClass('cRatingColumn_down',setNegative);this.scope.find('a.cAnswerRate_up').removeAttr('_title');this.scope.find('a.cAnswerRate_down').removeAttr('_title');if(setPositive){this.scope.find('a.cAnswerRate_up').attr('title',ips.getString('js_remove_your_vote'));}
else{this.scope.find('a.cAnswerRate_up').attr('title',ips.getString('js_vote_answer_up'));}
if(setNegative){this.scope.find('a.cAnswerRate_down').attr('title',ips.getString('js_remove_your_vote'));}
else{this.scope.find('a.cAnswerRate_down').attr('title',ips.getString('js_vote_answer_down'));}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('forums.front.topic.reply',{initialize:function(){this.on('click','[data-action="replyToTopic"]',this.replyToTopic);},replyToTopic:function(e){e.preventDefault();$(document).trigger('replyToTopic');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('forums.front.topic.solved',{initialize:function(){this.on('click','[data-action="mailSolvedReminders"]',this.mailSolvedReminders);},mailSolvedReminders:function(e){e.preventDefault();var _self=this;ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ajax&do=subscribeToSolved').done(function(response){var elem=_self.scope.find('[data-action="mailSolvedReminders"]');ips.utils.anim.go('fadeOutDown',elem);ips.ui.flashMsg.show(response.message,{timeout:5});});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('forums.front.topic.view',{initialize:function(){$(document).on('replyToTopic',_.bind(this.replyToTopic,this));this.on('paginationClicked',this.paginationClicked);this.on('click','[data-action="showMoreActivity"]',this.showActivity);this.on('click','[data-action="closeMoreActivity"]',this.hideActivity);},paginationClicked:function(e,data){document.getElementById('ipsTopicView').dataset.ipsTopicFirstPage=(data.pageNo==1);},showActivity:function(e){e.preventDefault();this.scope.find('[data-role="moreActivity"]').show();this.scope.find('[data-action="showMoreActivity"]').hide();this.scope.find('[data-action="closeMoreActivity"]').show();},hideActivity:function(e){e.preventDefault();this.scope.find('[data-role="moreActivity"]').hide();this.scope.find('[data-action="showMoreActivity"]').show();this.scope.find('[data-action="closeMoreActivity"]').hide();},replyToTopic:function(e){ips.ui.editorv5.getObjWithInit(this.scope.find('[data-role="replyArea"] [data-ipsEditorv5]'),function(editor){editor.unminimize(function(){editor.focus();});});}});}(jQuery,_));;
+1 -1
View File
@@ -12,7 +12,7 @@ if($('#image_details_'+imageId).length){$('#image_details_'+imageId).remove();}}
if(data.error>0){this.trigger('gallery.uploadErrors');}
if(!this.sortableInitialized){this.scope.find('[data-role="fileList"] > .cGallerySubmit_fileList').sortable({forcePlaceholderSize:true});this.sortableInitialized=true;}},sortableInitialized:false,filesAdded:function(e,data){this.trigger('gallery.disableSubmitButton');$('[data-role="addFiles"]').removeClass('ipsHide');$('[data-role="imageDetails"]').removeClass('ipsHide');if(!ips.utils.responsive.enabled()||!ips.utils.responsive.currentIs('phone')){this.scope.closest('.cGalleryDialog').addClass('cGalleryDialog_uploadStep');}
$(window).trigger('resize');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('gallery.front.submit.wrapper',{_expanded:false,_currentErrors:{},initialize:function(){this.on('submit','form',this.submitForm);this.on('click','[data-role="submitForm"]',this.maybeSubmitForm);this.on('gallery.submit.response',this._updateWrapper);this.on('click','[data-role="addFiles"]',this.dropzoneClick);this.on('click','[data-action="closeDialog"]',this.confirmClose);this.on('click','[data-role="file"][data-fileid]',this.setUpImageDetailsForm);this.on('click','[data-role="imageDescriptionUseEditor"]',this.setUpImageDescriptionRich);this.on('click','[data-role="imageDescriptionUseTextarea"]',this.setUpImageDescriptionPlain);this.on('click','[data-role="addCopyrightCredit"]',this.showCopyrightCredit);this.on('click','[data-role="saveDetails"]',this.saveDetails);this.on('click','[data-role="saveInfo"]',this.saveInfo);this.on('gallery.activateSubmitButton',this.activateSubmitButton);this.on('gallery.disableSubmitButton',this.disableSubmitButton);this.on('gallery.uploadErrors',this.uploadErrors);this.on('gallery.enlargeUploader',this.enlargeUploader);this.on('gallery.updateTitle',this.updateTitle);this.setup();this.trigger('gallery.wrapperInit');},setup:function(){ips.ui.editorv5.destruct(this.scope.find('[data-ipseditorv5]'));if(this.scope.find('.cGalleryDialog_imageForm').is(':visible')){this._enlargeUploadStep();}},updateTitle:function(e,data){if(data.title){this._updateTitle(data.title);}},_updateTitle:function(title){this.scope.find('[data-role="dialogTitle"]').text(title);},enlargeUploader:function(e,data){this._enlargeUploadStep(data.callback||$.noop);},activateSubmitButton:function(){this.scope.find('[data-role="submitForm"]').prop('disabled',false);},disableSubmitButton:function(){this.scope.find('[data-role="submitForm"]').prop('disabled',true);},uploadErrors:function(){this.scope.find('[data-role="imageErrors"]').show();},dropzoneClick:function(){this.scope.find('.ipsAttachment_dropZone').trigger('click');},showCopyrightCredit:function(e){e.preventDefault();var link=$(e.currentTarget);link.hide().next().slideDown();},saveInfo:function(e){e.preventDefault();$(e.currentTarget).trigger('closeMenu');},saveDetails:function(e){if(e){e.preventDefault();}
;(function($,_,undefined){"use strict";ips.controller.register('gallery.front.submit.wrapper',{_expanded:false,_currentErrors:{},initialize:function(){this.on('submit','form',this.submitForm);this.on('click','[data-role="submitForm"]',this.maybeSubmitForm);this.on('gallery.submit.response',this._updateWrapper);this.on('click','[data-role="addFiles"]',this.dropzoneClick);this.on('click','[data-action="closeDialog"]',this.confirmClose);this.on('click','[data-role="file"][data-fileid]',this.setUpImageDetailsForm);this.on('click','[data-role="imageDescriptionUseEditor"]',this.setUpImageDescriptionRich);this.on('click','[data-role="imageDescriptionUseTextarea"]',this.setUpImageDescriptionPlain);this.on('click','[data-role="addCopyrightCredit"]',this.showCopyrightCredit);this.on('click','[data-role="saveDetails"]',this.saveDetails);this.on('gallery.activateSubmitButton',this.activateSubmitButton);this.on('gallery.disableSubmitButton',this.disableSubmitButton);this.on('gallery.uploadErrors',this.uploadErrors);this.on('gallery.enlargeUploader',this.enlargeUploader);this.on('gallery.updateTitle',this.updateTitle);this.setup();this.trigger('gallery.wrapperInit');},setup:function(){ips.ui.editorv5.destruct(this.scope.find('[data-ipseditorv5]'));if(this.scope.find('.cGalleryDialog_imageForm').is(':visible')){this._enlargeUploadStep();}},updateTitle:function(e,data){if(data.title){this._updateTitle(data.title);}},_updateTitle:function(title){this.scope.find('[data-role="dialogTitle"]').text(title);},enlargeUploader:function(e,data){this._enlargeUploadStep(data.callback||$.noop);},activateSubmitButton:function(){this.scope.find('[data-role="submitForm"]').prop('disabled',false);},disableSubmitButton:function(){this.scope.find('[data-role="submitForm"]').prop('disabled',true);},uploadErrors:function(){this.scope.find('[data-role="imageErrors"]').show();},dropzoneClick:function(){this.scope.find('.ipsAttachment_dropZone').trigger('click');},showCopyrightCredit:function(e){e.preventDefault();var link=$(e.currentTarget);link.hide().next().slideDown();},saveDetails:function(e){if(e){e.preventDefault();}
this._markActiveImageAsSaved();$(e.currentTarget).next('[data-role="savedMessage"]').fadeIn();setTimeout(function(){$(e.currentTarget).next('[data-role="savedMessage"]').fadeOut();},2000);if(e){$(e.currentTarget).closest('.cGallerySubmit_details').find('[data-errorField]').hide();}
if(ips.utils.responsive.enabled()&&ips.utils.responsive.currentIs('phone')){this._toggleDetailsPanelMobile(false);this.scope.find('.cGallerySubmit_activeFile').removeClass('cGallerySubmit_activeFile');}},confirmClose:function(e){if(!this.scope.find('[data-fileid]').length){this.trigger('closeDialog');return;}
if(e){e.preventDefault();}
+34 -2
View File
@@ -1,6 +1,38 @@
ips.templates.set('gallery.notes.wrapper'," <div class='cGalleryNote' data-controller='gallery.front.view.note' data-noteID='{{id}}' data-note=\"{{note}}\" {{#editable}}data-editable{{/editable}} data-posLeft='{{left}}' data-posTop='{{top}}' data-dimWidth='{{width}}' data-dimHeight='{{height}}'> <div class='cGalleryNote_border'></div> <div class='cGalleryNote_note' style='display: none'> <div>{{note}}</div> </div></div>");ips.templates.set('gallery.notes.delete'," <a href='#' data-action='delete' class='cGalleryNote_delete' data-ipsTooltip title='{{#lang}}delete_note{{/lang}}'>&times;</a>");ips.templates.set('gallery.notes.edit'," <textarea>{{note}}</textarea> <ul class='ipsButtons i-justify-content_start i-margin-top_2'> <li><button data-action='save' class='ipsButton ipsButton--positive'>{{#lang}}save_note{{/lang}}</button></li> <li><a href='#' class='ipsButton ipsButton--inherit' data-action='cancel'>{{#lang}}cancel_note{{/lang}}</a></li> </ul>");;
;(function($,_,undefined){"use strict";ips.controller.register('gallery.front.view.image',{initialize:function(){this.on('menuOpened',this.menuOpened);this.on('menuClosed',this.menuClosed);this.on(document,'keydown',this.keyDown);this.on('click','[data-action="setAsCover"]',this.setAsCover);this.on('click','[data-action="setAsProfile"]',this.setAsProfile);this.on('click','[data-action="rotateImage"]',this.rotateImage);},menuOpened:function(){this.scope.find('.elGalleryImage').addClass('cGalleryImageHover');},menuClosed:function(e){this.scope.find('.elGalleryImage').removeClass('cGalleryImageHover');},keyDown:function(e){if($(e.target).closest('input, textarea, .ipsComposeArea, .ipsComposeArea_editor').length){return;}
switch(e.keyCode){case ips.ui.key.LEFT:this.scope.find('[data-action="prevMedia"]')[0].click();break;case ips.ui.key.RIGHT:this.scope.find('[data-action="nextMedia"]')[0].click();break;}},setAsProfile:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('set_as_photo_confirm'),callbacks:{ok:function(){ips.getAjax()(url,{showLoading:true}).done(function(response){ips.ui.flashMsg.show(response.message);}).fail(function(){window.location=url;});}}});},setAsCover:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');ips.getAjax()(url,{showLoading:true}).done(function(response){ips.ui.flashMsg.show(response.message);}).fail(function(){window.location=url;});},rotateImage:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');var self=this;ips.getAjax()(url,{showLoading:true}).done(function(response){self.scope.find('[data-role="theImage"]')[0].src=response.src;self.scope.find('[data-role="theImage"]').css({'width':response.width+'px','height':response.height+'px'});self.scope.find('[data-role="theImage"]').closest('.cGalleryViewImage').css({'width':response.width+'px','height':response.height+'px'});ips.ui.flashMsg.show(response.message);}).fail(function(){window.location=url;});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";const selectorPropertyMap={comments:'[data-role="imageComments"]',image:'[data-role="imageFrame"]',info:'[data-role="imageInfo"]',breadcrumb_top:'nav.ipsBreadcrumb--top',breadcrumb_bottom:'nav.ipsBreadcrumb--bottom',breadcrumb_mobile:'nav.ipsBreadcrumb--mobile',breadcrumb_off_canvas:'nav.ipsOffCanvas__breadcrumb'};ips.controller.register('gallery.front.view.image',{initialize:function(){this.on('menuOpened',this.menuOpened);this.on('menuClosed',this.menuClosed);this.on(document,'keydown',this.keyDown);this.on('click','[data-action="setAsCover"]',this.setAsCover);this.on('click','[data-action="setAsProfile"]',this.setAsProfile);this.on('click','[data-action="rotateImage"]',this.rotateImage);this.on('click','[data-action="changeImage"]',this.changeImage);this._stateUpdate=e=>this.stateUpdate(e);ips.utils.history.replaceState({id:this.getCurrentImageId()},'gallery.view.image',window.location.href);window.addEventListener('historychange',this._stateUpdate);},destroy(){window.removeEventListener('historychange:gallery.view.image',this._stateUpdate);},menuOpened:function(){this.scope.find('.elGalleryImage').addClass('cGalleryImageHover');},menuClosed:function(e){this.scope.find('.elGalleryImage').removeClass('cGalleryImageHover');},keyDown:function(e){if($(e.target).closest('input, textarea, .ipsComposeArea, .ipsComposeArea_editor').length){return;}
switch(e.keyCode){case ips.ui.key.LEFT:this.scope.find('[data-action="changeImage"][data-direction="prev"]')[0].click();break;case ips.ui.key.RIGHT:this.scope.find('[data-action="changeImage"][data-direction="next"]')[0].click();break;}},setAsProfile:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('set_as_photo_confirm'),callbacks:{ok:function(){ips.getAjax()(url,{showLoading:true}).done(function(response){ips.ui.flashMsg.show(response.message);}).fail(function(){window.location=url;});}}});},setAsCover:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');ips.getAjax()(url,{showLoading:true}).done(function(response){ips.ui.flashMsg.show(response.message);}).fail(function(){window.location=url;});},rotateImage:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');var self=this;ips.getAjax()(url,{showLoading:true}).done(function(response){self.scope.find('[data-role="theImage"]')[0].src=response.src;self.scope.find('[data-role="theImage"]').css({'width':response.width+'px','height':response.height+'px'});self.scope.find('[data-role="theImage"]').closest('.cGalleryViewImage').css({'width':response.width+'px','height':response.height+'px'});ips.ui.flashMsg.show(response.message);}).fail(function(){window.location=url;});},changeImage:async function(e){e.preventDefault();let commentTab;const tabsContainer=this.elem.querySelector(`${selectorPropertyMap.comments} i-tabs`);if(tabsContainer){let tab=tabsContainer.querySelector(`[href][aria-selected="true"]`)?.href;if(tab&&tab.endsWith('comments')){commentTab='comments';}else if(tab){commentTab='reviews';}}
let url=$(e.currentTarget).attr('href');const currentId=this.getCurrentImageId();const urlObj=new URL(url,window.location.href);urlObj.updateSearchParams({param:'browse',value:'1'});try{let selectedId;if(urlObj.searchParams.get('do')==='previous'&&currentId&&currentId in this._prevIdCache){selectedId=this._prevIdCache[currentId];}else if(urlObj.searchParams.get('do')==='next'&&currentId&&currentId in this._nextIdCache){selectedId=this._nextIdCache[currentId];}else if(e.currentTarget.closest(`#gallery-image-thumbs > [data-image-id]`)){selectedId=e.currentTarget.closest(`#gallery-image-thumbs > [data-image-id]`).dataset.imageId;}
if(selectedId&&selectedId===currentId){Debug.log(`Not loading image ${selectedId} from ${urlObj} because it is the current image`);return;}
for(const selector of Object.values(selectorPropertyMap)){this.elem.querySelectorAll(`${selector}:not(${selector} *)`).forEach(el=>el.classList.add('ipsLoading'));}
const response=await this.fetchImageData(urlObj.toString(),commentTab,selectedId);url=new URL(response.url,window.location.href)
if(commentTab){url.updateSearchParams({param:"tab",value:commentTab});}
ips.utils.history.pushState({url:url.toString(),response,commentTab,id:response.id.toString()},`gallery.view.image`,url.toString(),e);if(this.historyPromise){await this.historyPromise;}
const currentThumbIDs=new Set([...this.elem.querySelectorAll("#gallery-image-thumbs [data-image-id]")].map(elem=>elem.dataset.imageId));let thumbsChanged=false;for(const thumb of this.elem.querySelectorAll("#gallery-image-thumbs [data-image-id]")){if(!currentThumbIDs.has(thumb.dataset.imageId)){thumbsChanged=true;break;}
currentThumbIDs.delete(thumb.dataset.imageId);}
if(currentThumbIDs.size&&!thumbsChanged){thumbsChanged=true;}
selectedId=this.getCurrentImageId();if(selectedId){if(thumbsChanged){this._prevIdCache={};this._nextIdCache={};}
const urlObj=new URL(response.url,window.location.href);if(urlObj.searchParams.get('do')==='previous'&&currentId){this._prevIdCache[currentId]=selectedId;this._nextIdCache[selectedId]=currentId;}else if(urlObj.searchParams.get('do')==='next'&&currentId){this._nextIdCache[currentId]=selectedId;this._prevIdCache[selectedId]=currentId;}}}catch(e){Debug.warn(e);}},async fetchImageData(url,commentTab,id){url=new URL(url,window.location.href).updateSearchParams({params:{tab:['comments','reviews'].includes(commentTab)?commentTab:null,browse:1,}}).toString();commentTab=commentTab||'reviews';const response=this._resultCache?.[commentTab]?.[id]||await ips.fetch(url,{bypassRedirect:'none'});if(typeof response!=='object'||['image','url','info','title','id'].some(prop=>!(prop in response))){throw new RangeError(`The response from the endpoint ${urlObj} is not a JSON object containing image, url, info and title properties.`);}
if(id){this._resultCache[commentTab]=this._resultCache[commentTab]||{};this._resultCache[commentTab][id]=response;}
return response;},async stateUpdate(e){if(e.detail.type==='replace'){return;}
let _resolve,_reject;let{response,commentTab,id}=e.detail.state['gallery.view.image'];this.historyPromise=new Promise(((resolve,reject)=>{_resolve=resolve;_reject=reject;}));if(!id||id===this.getCurrentImageId()){Debug.log(`Not handling a state update for the gallery view because the id has not changed`);_reject(`The view wasn't actually changed`);return;}
if(!response||!commentTab){let tab=this.elem.querySelector(`${selectorPropertyMap.comments} i-tabs [href][aria-selected="true"]`)?.href;if(tab&&tab.endsWith('comments')){commentTab='comments';}else if(tab){commentTab='reviews';}
response=await this.fetchImageData(window.location.href,commentTab,id);ips.utils.history.replaceState({...e.detail.state['gallery.view.image'],response,commentTab,id,url:response.url});}
for(const[property,selector]of Object.entries(selectorPropertyMap)){const root=['breadcrumb_top','breadcrumb_bottom','breadcrumb_mobile','breadcrumb_off_canvas'].includes(property)?document.body:this.elem;root.querySelectorAll(`${selector}:not(${selector} *)`).forEach(el=>{el.insertAdjacentHTML("afterend",response[property]||"");el.remove();});}
this.updateActiveThumb(response);document.title=response.title;$(document).trigger('contentChange',[$(this.elem)]);if(response.dataLayer){this.scope.trigger('ipsDataLayerProperties',{_properties:response.dataLayer});}
_resolve();},historyPromise:undefined,getCurrentImageId(){const id=this.elem.querySelector("[data-role='imageFrame'][data-image-id]")?.dataset.imageId;if(id===undefined){Debug.warn(new RangeError(`Could not determine the current image id from the image frame`));}
return id;},_nextIdCache:{},_prevIdCache:{},_resultCache:{},updateActiveThumb(response){if(response){const allImages=[...this.elem.querySelectorAll(`#gallery-image-thumbs > [data-image-id]`)];const remainingIds=new Set(allImages.map(img=>parseInt(img.dataset.imageId)));const toInsert=[...response.images_prev,{id:response.id,content:response.image_link_current},...response.images_next];const overlap=toInsert.findIndex(val=>remainingIds.has((parseInt(val.id))));if(overlap!==-1){const id=parseInt(toInsert[overlap].id);const overlapDOMIdx=allImages.findIndex(img=>parseInt(img.dataset.imageId)===id);const prevInDOM=allImages.slice(0,overlapDOMIdx).reverse();const prevIdsRemaining=new Set(prevInDOM.map(img=>parseInt(img.dataset.imageId)));const prevToInsert=toInsert.slice(0,overlap).reverse();for(let i=0;i<prevToInsert.length;i++){const id=parseInt(prevToInsert[i].id);if(!prevInDOM.length&&!remainingIds.has(id)){requestAnimationFrame(()=>{this.elem.querySelector(`#gallery-image-thumbs`).insertAdjacentHTML('afterbegin',prevToInsert[i].content);});continue;}
if(prevIdsRemaining.has(id)){prevIdsRemaining.delete(id);while(prevInDOM.length>1&&parseInt(prevInDOM[0].dataset.imageId)!==id){const skipped=prevInDOM.shift();prevIdsRemaining.delete(parseInt(skipped.dataset.imageId));}
continue;}
if(remainingIds.has(id)){continue;}
const chunk=[];while(i<prevToInsert.length&&!remainingIds.has(parseInt(prevToInsert[i].id))){chunk.unshift(prevToInsert[i].content);i++;}
requestAnimationFrame(()=>{prevInDOM[0].insertAdjacentHTML('beforebegin',chunk.join(''));});}
const nextToInsert=toInsert.slice(overlap+1);const nextInDOM=allImages.slice(overlapDOMIdx);const nextIdsRemaining=new Set(nextInDOM.map(img=>parseInt(img.dataset.imageId)));for(let i=0;i<nextToInsert.length;i++){const id=parseInt(nextToInsert[i].id);if(!nextInDOM.length){requestAnimationFrame(()=>{this.elem.querySelector(`#gallery-image-thumbs`).insertAdjacentHTML('beforeend',nextToInsert[i].content);});continue;}
if(nextIdsRemaining.has(id)){nextIdsRemaining.delete(id);while(nextInDOM.length>1&&parseInt(nextInDOM[0].dataset.imageId)!==id){const skipped=nextInDOM.shift();nextIdsRemaining.delete(parseInt(skipped.dataset.imageId));}
continue;}
if(remainingIds.has(id)){continue;}
let chunk=[];while(i<nextToInsert.length&&!remainingIds.has(parseInt(nextToInsert[i].id))){chunk.push(nextToInsert[i].content);i++;}
requestAnimationFrame(()=>{nextInDOM[0].insertAdjacentHTML('afterend',chunk.join(''));});}}else if(toInsert.length){requestAnimationFrame(()=>{this.elem.querySelector('#gallery-image-thumbs').innerHTML=toInsert.map(img=>img.content).join('\n');});}}
const currentlyActiveThumb=this.getCurrentImageId();requestAnimationFrame(()=>{this.elem.querySelectorAll(`#gallery-image-thumbs > [data-active]`).forEach(el=>delete el.dataset.active);});if(currentlyActiveThumb){let img;requestAnimationFrame(()=>{this.elem.querySelectorAll(`#gallery-image-thumbs > [data-image-id="${currentlyActiveThumb}"]`).forEach(el=>{el.dataset.active='';img=el;});if(img){requestAnimationFrame(()=>{const imgRect=img.getBoundingClientRect();const scroller=img.closest('#gallery-image-thumbs');const scrollerRect=scroller.getBoundingClientRect();if(imgRect.left<scrollerRect.left){scroller.scrollBy({left:imgRect.left-scrollerRect.left});}else if(imgRect.right>scrollerRect.right){scroller.scrollBy({left:imgRect.right-scrollerRect.right});}});}});}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('gallery.front.view.note',{_editing:false,_editable:false,_draggingNotEditing:false,_hoverTimerOn:null,_hoverTimerOff:null,_note:'',initialize:function(){this.on('click','.cGalleryNote_border',this.startEditing);this.on('click','[data-action="save"]',this.saveNote);this.on('click','[data-action="cancel"]',this.cancelNote);this.on('click','[data-action="delete"]',this.deleteNote);this.on('mousedown','.cGalleryNote_note',this.mouseDown);this.on('mouseenter',this.mouseEnter);this.on('mouseleave',this.mouseLeave);this.setup();},setup:function(){var self=this;if(!_.isUndefined(this.scope.attr('data-editable'))&&!ips.utils.responsive.currentIs('phone')){this._editable=true;}
this._note=this.scope.attr('data-note');this._baseURL=ips.getSetting('baseURL')+'index.php?app=gallery&module=gallery&controller=notes&imageId='+this.scope.closest('.cGalleryViewImage').attr('data-imageID');this._buildNote();this._setUpEditable();this._initialPosition();if(this.scope.attr('data-noteID')=='new'){this.scope.find('.cGalleryNote_border').click();}},saveNote:function(e){e.preventDefault();var self=this;var note=this.scope.find('.cGalleryNote_note textarea').val();var savePosition=false;this.scope.draggable('enable');if(!note.trim()){return;}
if(this.scope.attr('data-noteID')=='new'){savePosition=true;}
+31 -25
View File
@@ -1,7 +1,5 @@
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.controlStrip',function(){var respond=function(elem,options){if(!$(elem).data('_controlStrip')){$(elem).data('_controlStrip',controlStripObj(elem));}};ips.ui.registerWidget('controlStrip',ips.ui.controlStrip);return{respond:respond};});var controlStripObj=function(elem){var init=function(){var buttons=elem.find('.ipsControlStrip_button:not(.ipsJS_hide)');if(buttons.length>3){_buildMenu(buttons);}
elem.on('click','[data-replace], [data-remove], [data-bubble]',_remoteAction);},_remoteAction=function(e){e.preventDefault();var link=$(e.currentTarget);var url=link.attr('href');ips.getAjax()(url,{dataType:'json',showLoading:true}).done(function(response){if(link.is('[data-replace]')){_replaceButton(link,response);}else if(link.is('[data-remove]')){_removeButton(link,response);}else if(link.is('[data-bubble]')){_bubbleAction(link,response);}}).fail(function(){window.location=url;});},_bubbleAction=function(link,response){link.trigger('buttonAction',response);},_replaceButton=function(link,response){ips.ui.flashMsg.show(response);var item=link.closest('.ipsControlStrip_button, .ipsControlStrip_menuItem');var newItem=$('#'+link.attr('data-replacewith'));if(item.hasClass('ipsControlStrip_button')){item.hide();newItem.show();}else{if(!newItem.hasClass('ipsControlStrip_menuItem')){var newHTML=_getMenuItemFromButton(newItem);item.hide().after(newHTML);}else{item.hide();newItem.show();}}},_removeButton=function(link,response){ips.ui.flashMsg.show(response);var dropdown=$(elem).find('[data-dropdown]');if(link.attr('data-alsoremove')){var also=ips.utils.getIDsFromList(link.attr('data-alsoremove'));}
var toRemove=$(link).add(also||'').closest('.ipsControlStrip_button, .ipsControlStrip_menuItem');toRemove.remove();if(dropdown.length){var menu=$(dropdown.attr('id')+'_menu');if(!menu.find('.ipsControlStrip_menuItem').length){menu.remove();dropdown.remove();}}},_buildMenu=function(buttons){var buttonsToMove=buttons.slice(2);var menu=ips.templates.render('core.controlStrip.menu',{id:elem.identify().attr('id')+'_more',content:_moveButtonsToMenu(buttonsToMove)});$(elem).after(menu);buttonsToMove.remove();elem.find('.ipsControlStrip_button').last().after(ips.templates.render('core.controlStrip.dropdown',{id:elem.identify().attr('id')+'_more'}));elem.parent().wrapInner($('<div/>').css({position:'relative'})).find('[data-dropdown]').attr('aria-haspopup','true').ipsMenu({appendTo:'#'+elem.parent().identify().attr('id')});$(document).trigger('contentChange',[elem]);},_moveButtonsToMenu=function(buttons){var menuContent='';for(var i=0;i<buttons.length;i++){menuContent+=_getMenuItemFromButton(buttons[i]);}
return menuContent;},_getMenuItemFromButton=function(button){var buttonLink=$(button).find('> a');$(button).find('[data-ipsTooltip]').removeAttr('data-ipsTooltip');return ips.templates.render('core.controlStrip.menuItem',{id:$(button).attr('id')||'',item:$(button).html()});};init();return{};};}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.controlStrip',function(){var respond=function(elem,options){if(!$(elem).data('_controlStrip')){$(elem).data('_controlStrip',controlStripObj(elem));}};ips.ui.registerWidget('controlStrip',ips.ui.controlStrip);return{respond:respond};});var controlStripObj=function(elem){var init=function(){elem.on('click','[data-replace], [data-remove], [data-bubble]',_remoteAction);},_remoteAction=function(e){e.preventDefault();var link=$(e.currentTarget);var url=link.attr('href');ips.getAjax()(url,{dataType:'json',showLoading:true}).done(function(response){if(link.is('[data-replace]')){_replaceButton(link,response);}else if(link.is('[data-remove]')){_removeButton(link,response);}else if(link.is('[data-bubble]')){_bubbleAction(link,response);}}).fail(function(){window.location=url;});},_bubbleAction=function(link,response){link.trigger('buttonAction',response);},_replaceButton=function(link,response){ips.ui.flashMsg.show(response);var item=link.closest('.ipsControlStrip_button, .ipsControlStrip_menuItem');var newItem=$('#'+link.attr('data-replacewith'));if(item.hasClass('ipsControlStrip_button')){item.hide();newItem.show();}else{if(!newItem.hasClass('ipsControlStrip_menuItem')){var newHTML=_getMenuItemFromButton(newItem);item.hide().after(newHTML);}else{item.hide();newItem.show();}}},_removeButton=function(link,response){ips.ui.flashMsg.show(response);var dropdown=$(elem).find('[data-dropdown]');if(link.attr('data-alsoremove')){var also=ips.utils.getIDsFromList(link.attr('data-alsoremove'));}
var toRemove=$(link).add(also||'').closest('.ipsControlStrip_button, .ipsControlStrip_menuItem');toRemove.remove();if(dropdown.length){var menu=$(dropdown.attr('id')+'_menu');if(!menu.find('.ipsControlStrip_menuItem').length){menu.remove();dropdown.remove();}}},_getMenuItemFromButton=function(button){$(button).find('[data-ipsTooltip]').removeAttr('data-ipsTooltip');return ips.templates.render('core.controlStrip.menuItem',{id:$(button).attr('id')||'',item:$(button).html()});};init();return{};};}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('textarea.customtags',{initialize:function(){this.on('click','[data-textareacustomtag]',this.insertTag);},insertTag:function(e){console.log('Inserting custom tag: '+$(e.currentTarget).attr('data-textareacustomtag'));$('#'+this.scope.data('textareaid')).focus();$('#'+this.scope.data('textareaid')).insertText($(e.currentTarget).attr('data-textareacustomtag'),$('#'+this.scope.data('textareaid')).getSelection().start,"collapseToEnd");}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.matrix',function(){var defaults={manageable:true,sortable:false,squashFields:false};var respond=function(elem,options){var matrix=$(elem).data('_matrix');if(!matrix){$(elem).data('_matrix',matrixObj(elem,_.defaults(options,defaults)));}else{matrix.checkRows();}},refresh=function(elem){try{var obj=$(elem).data('_matrix');obj.checkRows();}catch(err){Debug.log("Couldn't refresh matrix "+$(elem).identify().attr('id'));}};ips.ui.registerWidget('matrix',ips.ui.matrix,['manageable','sortable','squashFields']);return{respond:respond,refresh:refresh};});var matrixObj=function(elem,options){var init=function(){_setUpEvent();if(options.manageable){_setUpManageable();}
if(options.sortable){ips.loader.get(['core/interface/jquery/jquery-ui.js']).then(function(){elem.find('tbody').sortable({handle:'.ipsTree_drag'});});}
@@ -30,16 +28,16 @@ if(row.hasClass('ipsTree_acceptsChildren')&&!subList.length){var newRow=$('<ol/>
outputArray.push('ajax_order['+id+']='+((dataArray[i].parent_id==null)?rootID:dataArray[i].parent_id));}
data=outputArray.join('&');}else{data=$(this).nestedSortable('serialize',{key:'ajax_order'});}
if(failed){window.location.reload();}
data=data+'&csrfKey='+ips.getSetting('csrfKey');ips.getAjax()(url,{data:data,method:'POST'}).fail(function(){window.location=url+"&"+data;});},toleranceElement:'> div',listType:'ol',isTree:true,isAllowed:function(placeholder,placeholderParent,currentItem){$('#ipsTooltip').hide();var parent=null;if(_.isUndefined(placeholderParent)||placeholderParent===null){parent=elem.find('> .ipsTree_root');}else{parent=placeholderParent.closest('[data-role="node"]').find('> .ipsTree_row');}
data=data+'&csrfKey='+ips.getSetting('csrfKey');ips.getAjax()(url,{data:data,method:'POST'}).fail(function(){window.location=url+"&"+data;});},toleranceElement:'> div',listType:'ol',isTree:true,isAllowed:function(placeholder,placeholderParent,currentItem){$('#ipsTooltip')[0].hidePopover();var parent=null;if(_.isUndefined(placeholderParent)||placeholderParent===null){parent=elem.find('> .ipsTree_root');}else{parent=placeholderParent.closest('[data-role="node"]').find('> .ipsTree_row');}
if(parent.hasClass('ipsTree_acceptsChildren')||(!parent.length&&!currentItem.find('> .ipsTree_row').hasClass('ipsTree_noRoot'))){placeholder.removeAttr('data-error');return true;}else{placeholder.attr('data-error',ips.getString('cannotDragInto'));return false;}},expand:function(event,ui){var row=$(this).find('.mjs-nestedSortable-hovering > .ipsTree_parent[data-nodeid]').first();if(!row.hasClass('ipsTree_open')){_openRow(row);}},change:function(event,ui){$(this).find('.ipsTree_draggingInto').removeClass('ipsTree_draggingInto');ui.placeholder.closest('[data-role="node"]').find('> .ipsTree_row').addClass('ipsTree_draggingInto');},start:function(event,ui){ui.placeholder.closest('[data-role="node"]').find('> .ipsTree_row').addClass('ipsTree_draggingInto');},stop:function(event,ui){$(this).find('.ipsTree_draggingInto').removeClass('ipsTree_draggingInto');}};if(options.lockParents){sortableOptions['disableParentChange']=true;}
if(options.protectRoots){sortableOptions['protectRoot']=true;}
elem.find('.ipsTree_rows > .ipsTree').nestedSortable(sortableOptions);};init();return{init:init};};}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.mixin('acpTable','core.global.core.table',true,function(){this._timer=null;this._searchField=null;this._curSearchValue='';this._currentValue='';this.after('initialize',function(){this.on('focus','[data-role="tableSearch"]',this.startLiveSearch);this.on('blur','[data-role="tableSearch"]',this.endLiveSearch);this.on('click','[data-action="tableSort"]',this.changeSorting);this.on('paginationClicked',this.adminPaginationClicked);this.on('menuItemSelected','#elSortMenu',this.sortByMenu);this.on('menuItemSelected','#elOrderMenu',this.orderByMenu);});this.before('setup',function(){this._searchField=this.scope.find('[data-role="tableSearch"]');this.scope.find('[data-role="tableSearch"]').removeClass('ipsHide').show();});this.around('_getUrlParams',function(origFn){return _.extend(origFn(),{quicksearch:this._getSearchValue()||''});});this.after('_updateSort',function(data){var directions='ipsTable_sortableAsc ipsTable_sortableDesc';this.scope.find('[data-role="table"] [data-action="tableSort"]').removeClass('ipsTable_sortableActive').removeAttr('aria-sort').end().find('[data-action="tableSort"][data-key="'+data.by+'"]').addClass('ipsTable_sortableActive').removeClass(directions).addClass('ipsTable_sortable'+data.order.charAt(0).toUpperCase()+data.order.slice(1)).attr('aria-sort',(data.order=='asc')?'ascending':'descending');$('#elSortMenu_menu, #elOrderMenu_menu').find('.ipsMenu_item').removeClass('ipsMenu_itemChecked').end().find('[data-ipsMenuValue="'+data.by+'"], [data-ipsMenuValue="'+data.order+'"]').addClass('ipsMenu_itemChecked');});this.after('_handleStateChanges',function(state){if(!_.isUndefined(state.data.quicksearch)&&state.data.quicksearch!=this._urlParams.quicksearch){this._updateSearch(state.data.quicksearch);}});this.adminPaginationClicked=function(){var wrappingDialog=this.scope.closest('.ipsDialog');var elemPosition=ips.utils.position.getElemPosition(wrappingDialog.length?wrappingDialog:this.scope);$('html, body').animate({scrollTop:(elemPosition.absPos.top-60)+'px'});};this.sortByMenu=function(e,data){data.originalEvent.preventDefault();this.updateURL({sortby:data.selectedItemID});};this.orderByMenu=function(e,data){data.originalEvent.preventDefault();this.updateURL({sortdirection:data.selectedItemID});};this.changeSorting=function(e){e.preventDefault();var cell=$(e.currentTarget);var order='';if(cell.hasClass('ipsTable_sortableActive')){order=(cell.hasClass('ipsTable_sortableDesc'))?'asc':'desc';}else{order=(cell.hasClass('ipsTable_sortableDesc'))?'desc':'asc';}
;(function($,_,undefined){"use strict";ips.controller.mixin('acpTable','core.global.core.table',true,function(){this._timer=null;this._searchField=null;this._curSearchValue='';this._currentValue='';this.after('initialize',function(){this.on('focus','[data-role="tableSearch"]',this.startLiveSearch);this.on('blur','[data-role="tableSearch"]',this.endLiveSearch);this.on('click','[data-action="tableSort"]',this.changeSorting);this.on('paginationClicked',this.adminPaginationClicked);this.on('menuItemSelected','#elSortMenu',this.sortByMenu);this.on('menuItemSelected','#elOrderMenu',this.orderByMenu);});this.before('setup',function(){this._searchField=this.scope.find('[data-role="tableSearch"]');this.scope.find('[data-role="tableSearch"]').removeClass('ipsHide').show();});this.around('_getUrlParams',function(origFn){return _.extend(origFn(),{quicksearch:this._getSearchValue()||''});});this.after('_updateSort',function(data){var directions='ipsTable_sortableAsc ipsTable_sortableDesc';this.scope.find('[data-role="table"] [data-action="tableSort"]').removeClass('ipsTable_sortableActive').removeAttr('aria-sort').end().find('[data-action="tableSort"][data-key="'+data.by+'"]').addClass('ipsTable_sortableActive').removeClass(directions).addClass('ipsTable_sortable'+data.order.charAt(0).toUpperCase()+data.order.slice(1)).attr('aria-sort',(data.order=='asc')?'ascending':'descending');$('#elSortMenu_menu, #elOrderMenu_menu').find('[aria-selected="true"]').removeAttr('aria-selected').end().find('[data-ipsMenuValue="'+data.by+'"], [data-ipsMenuValue="'+data.order+'"]').attr('aria-selected','true');});this.after('_handleStateChanges',function(state){if(!_.isUndefined(state.data.quicksearch)&&state.data.quicksearch!=this._urlParams.quicksearch){this._updateSearch(state.data.quicksearch);}});this.adminPaginationClicked=function(){var wrappingDialog=this.scope.closest('.ipsDialog');var elemPosition=ips.utils.position.getElemPosition(wrappingDialog.length?wrappingDialog:this.scope);$('html, body').animate({scrollTop:(elemPosition.absPos.top-60)+'px'});};this.sortByMenu=function(e,data=e.detail){data.originalEvent.preventDefault();this.updateURL({sortby:data.selectedItemID});};this.orderByMenu=function(e,data=e.detail){data.originalEvent.preventDefault();this.updateURL({sortdirection:data.selectedItemID});};this.changeSorting=function(e){e.preventDefault();var cell=$(e.currentTarget);var order='';if(cell.hasClass('ipsTable_sortableActive')){order=(cell.hasClass('ipsTable_sortableDesc'))?'asc':'desc';}else{order=(cell.hasClass('ipsTable_sortableDesc'))?'desc':'asc';}
this.updateURL({sortby:cell.attr('data-key'),sortdirection:order});};this.startLiveSearch=function(e){this._timer=setInterval(_.bind(this._checkSearchValue,this),500);};this.endLiveSearch=function(e){clearInterval(this._timer);};this._checkSearchValue=function(){var val=this._searchField.val();if(this._currentValue!=val){this.updateURL({quicksearch:val,page:1});this._currentValue=val;}};this._updateSearch=function(searchValue){this._searchField.val(searchValue);};this._updateFilter=function(newFilter){this.scope.find('[data-role="tableSortBar"] [data-action="tableFilter"] a').removeClass('ipsDataFilters__button--active').end().find('[data-action="tableFilter"][data-filter="'+newFilter+'"] a').addClass('ipsDataFilters__button--active');};this._getSortValue=function(){var sortBy=this.scope.find('[data-role="table"] thead .ipsTable_sortable.ipsTable_sortableActive');var sortOrder='desc';if(sortBy.hasClass('ipsTable_sortableAsc')){sortOrder='asc';}
return{by:sortBy.attr('data-key'),order:sortOrder};};this._getFilterValue=function(){var sortBar=this.scope.find('[data-role="tableSortBar"]');if(!sortBar.length){return'';}
return sortBar.find('.ipsDataFilters__button--active').closest('[data-filter]').attr('data-filter');};this._getSearchValue=function(){if(ips.utils.url.getParam('quicksearch')){return ips.utils.url.getParam('quicksearch');}
return this.scope.find('[data-role="tableSearch"]').val();};});}(jQuery,_));;
ips.templates.set('core.appMenu.reorder'," <span data-role='reorder' style='display: none'><i class='fa-solid fa-bars'></i></span>");ips.templates.set('core.controlStrip.menu'," <ul class='ipsMenu ipsMenu_auto' role='menu' id='{{id}}_menu' style='display: none'> {{{content}}} </ul>");ips.templates.set('core.controlStrip.menuItem'," <li class='ipsMenu_item ipsControlStrip_menuItem' role='menuitem' id='{{id}}'> {{{item}}} </li>");ips.templates.set('core.controlStrip.dropdown'," <li class='ipsControlStrip_button ipsControlStrip_dropdown' data-dropdown id='{{id}}'> <a href='#'> <i class='ipsControlStrip_icon fa-solid fa-angle-down'></i> </a> </li>");ips.templates.set('core.trees.childWrapper'," {{{content}}}");ips.templates.set('core.trees.loadingRow'," <ol class='ipsTree'><li class='ipsTree_loadingRow ipsLoading ipsLoading--tiny'>{{#lang}}loading{{/lang}}</li></ol>");ips.templates.set('core.trees.loadingPane'," <div class='ipsLoading' style='height: 150px'>&nbsp;</div>");ips.templates.set('core.trees.noRows'," <div class='i-text-align_center i-padding_3 i-color_soft'>{{#lang}}no_results{{/lang}}</div>");ips.templates.set('core.livesearch.noResults'," <li class='i-text-align_center i-padding_3 i-color_soft' data-role='result'> <br><br> </li>");ips.templates.set('languages.translateString'," <div class='cTranslateTable_field'> <textarea class='ipsInput'>{{value}}</textarea> <button type='button' href='#' data-action='saveWords' tabindex='-1' class='ipsButton ipsButton--positive ipsButton--tiny ipsButton--icon'><i class='fa-solid fa-check'></i> {{#lang}}languageSave{{/lang}}</button> </div>");ips.templates.set('support.guideSearch'," <li> <a href=\"{{link}}\" target='_blank' rel='noopener'>{{title}}</a> </li>");ips.templates.set('support.guideSearch.noResults'," <li class='i-color_soft'> {{#lang}}no_results{{/lang}} </li>");ips.templates.set('support.ticket.supportSummary'," <div class='i-padding-top_3'> {{#lang}}health_ticket_beforeproceeding{{/lang}} </div>");;
ips.templates.set('core.appMenu.reorder'," <span data-role='reorder' style='display: none'><i class='fa-solid fa-bars'></i></span>");ips.templates.set('core.controlStrip.menuItem'," <li class='ipsMenu_item ipsControlStrip_menuItem' role='menuitem' id='{{id}}'> {{{item}}} </li>");ips.templates.set('core.trees.childWrapper'," {{{content}}}");ips.templates.set('core.trees.loadingRow'," <ol class='ipsTree'><li class='ipsTree_loadingRow ipsLoading ipsLoading--tiny'>{{#lang}}loading{{/lang}}</li></ol>");ips.templates.set('core.trees.loadingPane'," <div class='ipsLoading' style='height: 150px'>&nbsp;</div>");ips.templates.set('core.trees.noRows'," <div class='i-text-align_center i-padding_3 i-color_soft'>{{#lang}}no_results{{/lang}}</div>");ips.templates.set('core.livesearch.noResults'," <li class='i-text-align_center i-padding_3 i-color_soft' data-role='result'> <br><br> </li>");ips.templates.set('languages.translateString'," <div class='cTranslateTable_field'> <textarea class='ipsInput'>{{value}}</textarea> <button type='button' href='#' data-action='saveWords' tabindex='-1' class='ipsButton ipsButton--positive ipsButton--tiny ipsButton--icon'><i class='fa-solid fa-check'></i> {{#lang}}languageSave{{/lang}}</button> </div>");ips.templates.set('support.guideSearch'," <li> <a href=\"{{link}}\" target='_blank' rel='noopener'>{{title}}</a> </li>");ips.templates.set('support.guideSearch.noResults'," <li class='i-color_soft'> {{#lang}}no_results{{/lang}} </li>");ips.templates.set('support.ticket.supportSummary'," <div class='i-padding-top_3'> {{#lang}}health_ticket_beforeproceeding{{/lang}} </div>");;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.app',{initialize:function(){this.on('click','[data-clickshow]',this.clickShow);this.on('click','[data-clickhide]',this.clickHide);this.on('click','[data-clickempty]',this.clickEmpty);this.on('click','[data-delete]',this.deleteSomething);this.on('click','a[data-confirm]',this.confirmSomething);this.on('click','[data-doajax]',this.doAjaxAction);this.on(document,'contentChange',this._checkAndClearAutosave);this.setup();},setup:function(){if(ips.utils.serviceWorker.supported){ips.utils.serviceWorker.registerServiceWorker('admin',false);}
this._checkAndClearAutosave();if(!ips.getSetting('memberID')&&ips.utils.url.getParam('_fromLogout')){ips.utils.db.removeByType('editorSave');}},_checkAndClearAutosave:function(){if(ips.utils.cookie.get('clearAutosave')){var autoSaveKeysToClear=ips.utils.cookie.get('clearAutosave').split(',');for(var i=0;i<autoSaveKeysToClear.length;i++){ips.utils.db.remove('editorSave',autoSaveKeysToClear[i]);}
ips.utils.cookie.unset('clearAutosave');}},doAjaxAction:function(e){e.preventDefault();ips.getAjax()($(e.currentTarget).attr('href'),{dataType:'json'}).done(function(response){ips.ui.flashMsg.show(response);}).fail(function(jqXHR){if(Debug.isEnabled()){Debug.error(jqXHR.responseText);}else{window.location=$(e.currentTarget).attr('href');}});},deleteSomething:function(e){e.preventDefault();var elem=$(e.currentTarget);var deleteTitle=elem.attr('data-delete-message');var extraWarning=elem.attr('data-delete-warning');ips.ui.alert.show({type:'confirm',icon:'warn',message:deleteTitle||ips.getString('delete_confirm'),subText:extraWarning||'',focus:'cancel',callbacks:{ok:function(){if(elem.attr('data-noajax')!==undefined){window.location=elem.attr('href')+'&csrfKey='+ips.getSetting('csrfKey')+'&wasConfirmed=1';return;}
@@ -47,33 +45,41 @@ var row=null;if(elem.attr('data-deleterow')){row=$(elem.attr('data-deleterow'));
let bypassRedirect=!(elem.attr('data-accept-redirect'));ips.getAjax()(elem.attr('href'),{showLoading:true,bypassRedirect:bypassRedirect,data:{form_submitted:1,wasConfirmed:1}}).done(function(response){if(row.hasClass('parent')){row.next().remove();}
ips.utils.anim.go('fadeOut',row);}).fail(function(){window.location=elem.attr('href')+'&csrfKey='+ips.getSetting('csrfKey')+'&wasConfirmed=1';});}}});},confirmSomething:function(e){e.preventDefault();var elem=$(e.currentTarget);var customMessage=$(e.currentTarget).attr('data-confirmMessage');var customSubMessage=$(e.currentTarget).attr('data-confirmSubMessage');var type=$(e.currentTarget).attr('data-confirmType');var icon=$(e.currentTarget).attr('data-confirmIcon');var alert={type:(type)?type:'confirm',icon:(icon)?icon:'warn',message:(customMessage)?customMessage:ips.getString('generic_confirm'),subText:(customSubMessage)?customSubMessage:'',callbacks:{ok:function(){window.location=elem.attr('href')+'&wasConfirmed=1';},yes:function(){window.location=elem.attr('href')+'&prompt=1';},no:function(){window.location=elem.attr('href')+'&prompt=0';}}};if($(e.currentTarget).attr('data-confirmButtons')){alert.buttons=$.parseJSON($(e.currentTarget).attr('data-confirmButtons'));}
ips.ui.alert.show(alert);},clickShow:function(e){e.preventDefault();var elems=ips.utils.getIDsFromList($(e.currentTarget).attr('data-clickshow'));this.scope.find(elems).show().removeClass('ipsHide');},clickHide:function(e){e.preventDefault();var elems=ips.utils.getIDsFromList($(e.currentTarget).attr('data-clickhide'));this.scope.find(elems).hide().addClass('ipsHide');},clickEmpty:function(e){e.preventDefault();var elems=ips.utils.getIDsFromList($(e.currentTarget).attr('data-clickempty'));this.scope.find(elems).val('');}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.dynamicChart',{storedValues:{},identifier:'',type:'',initialize:function(){this.on('click','[data-timescale]',this.changeTimescale);this.on(document,'submit','[data-role="dateForm"]',this.changeDateRange);this.on(document,'click','[data-role="clearSearchTerm"]',this.resetSearch);this.on(document,'submit','[data-role="searchForm"]',this.changeSearch);this.scope.find('[data-role="clearSearchTerm"]').hide();this.on('menuItemSelected','[data-action="chartFilter"]',this.changeFilter);this.on('click','[data-type]',this.changeChartType);$('[data-role="filterMenu"] [data-role="selectAll"]').on('click',_.bind(this.selectAllFilters,this));$('[data-role="filterMenu"] [data-role="unselectAll"]').on('click',_.bind(this.unselectAllFilters,this));$('button[data-role="applyFilters"]').on('click',function(){$('[data-action="chartFilter"]').trigger('closeMenu');});this.on('click','[data-role="saveReport"]',_.bind(this.saveFilters,this));this.on('click','[data-role="renameChart"]',_.bind(this.renameFilters,this));this.setup();},selectAllFilters:function(e){$(e.currentTarget).closest('.ipsMenu').find('.ipsMenu_item:not(.ipsMenu_itemChecked) a:not(.ipsMenu_itemNonSelect)').trigger('click');$('button[data-role="applyFilters"]').prop('disabled',false);},unselectAllFilters:function(e){$(e.currentTarget).closest('.ipsMenu').find('.ipsMenu_item.ipsMenu_itemChecked a').trigger('click');$('button[data-role="applyFilters"]').prop('disabled',false);},setup:function(){var self=this;this.identifier=this.scope.attr('data-chart-identifier');this.storedValues.timescale=this.scope.find('[data-timescale][data-selected]').attr('data-timescale');this.storedValues.type=this.scope.find('[data-type][data-selected]').attr('data-type');if(this.scope.find('[data-role="searchForm"] input')){this.storedValues.term=null;}
this.storedValues.filters=[];this.storedValues.dates={start:'',end:''};this.type=this.scope.attr('data-chart-type');this.timescale=this.scope.attr('data-chart-timescale');$('#el'+this.identifier+'Filter_menu').find('.ipsMenu_itemChecked').each(function(){self.storedValues.filters.push($(this).attr('data-ipsMenuValue'));});this.checkType();},changeTimescale:function(e){this.timescale=$(e.currentTarget).attr('data-timescale');this._toggleButtonRow(e,'timescale');},changeChartType:function(e){this.type=$(e.currentTarget).attr('data-type');this._toggleButtonRow(e,'type');this.checkType();},checkType:function(){if(this.type=='Table'||this.type=='PieChart'||this.type=='GeoChart'){$(this.scope).find('[data-role="groupingButtons"] a.ipsButton').addClass('ipsButton--disabled');}else{$(this.scope).find('[data-role="groupingButtons"] a.ipsButton').removeClass('ipsButton--disabled');}},updateUrlBound:false,changeFilter:function(e,data){data.originalEvent.preventDefault();this._resetFilters();if(this.updateUrlBound===false){$('[data-action="chartFilter"]').one('menuClosed',_.bind(this.fetchNewResults,this));this.updateUrlBound=true;}
$('button[data-role="applyFilters"]').prop('disabled',false);},fetchNewResults:function(e){this._updateURL();this.updateUrlBound=false;},saveFilters:function(event){var identifier=this.scope.closest('.ipsTabs__panel').closest('section').attr('id');var self=this;var pieces=[];_.each(this.storedValues.filters,function(value,idx){pieces.push("chartFilters["+idx+"]="+value);});$('#el'+this.identifier+'CustomFiltersForm input[data-role="nodeValue"]').each(function(){pieces.push('customform_'+$(this).attr('name')+"="+$(this).val());});var newFilters=pieces.join('&');if(this.timescale){newFilters=newFilters+"&timescale="+this.timescale;}
;(function($,_,undefined){"use strict";ips.controller.register('core.admin.core.dynamicChart',{storedValues:{},identifier:'',type:'',initialize:function(){this.on('click','[data-timescale]',this.changeTimescale);this.on(document,'submit','[data-role="dateForm"]',this.changeDateRange);document.addEventListener('ips:stats.setDateFilters',e=>this.globalDateRangeSet(e));this.on(document,'click','[data-role="clearSearchTerm"]',this.resetSearch);this.on(document,'submit','[data-role="searchForm"]',this.changeSearch);this.on('menuItemSelected','[data-action="chartFilter"]',this.changeFilter);this.on('click','[data-type]',this.changeChartType);this.on('click','[data-role="filterMenu"] [data-role="selectAll"]',this.selectAllFilters);this.on('click','[data-role="filterMenu"] [data-role="unselectAll"]',this.unselectAllFilters);this.on('click','[data-role="saveReport"]',_.bind(this.saveFilters,this));this.on('click','[data-role="renameChart"]',_.bind(this.renameFilters,this));this.setup();},selectAllFilters:function(e){$(e.currentTarget).closest('i-dropdown').find('[data-ipsMenuValue]:not([aria-selected="true"])').each(function(){this.click();});},unselectAllFilters:function(e){$(e.currentTarget).closest('i-dropdown').find('[data-ipsMenuValue][aria-selected="true"]').each(function(){this.click();});},setup:function(){var self=this;this.identifier=this.scope.attr('data-chart-identifier');this.storedValues.timescale=this.scope.find('[data-timescale][data-selected]').attr('data-timescale');this.storedValues.type=this.scope.find('[data-type][data-selected]').attr('data-type');if(this.scope.find('[data-role="searchForm"] input')){this.storedValues.term=null;}
this.storedValues.filters=[];this.storedValues.dates={start:'',end:''};this.type=this.scope.attr('data-chart-type');this.timescale=this.scope.attr('data-chart-timescale');$('#el'+this.identifier+'Filter_menu').find('[aria-selected="true"]').each(function(){self.storedValues.filters.push($(this).attr('data-ipsMenuValue'));});this.checkType();const url=new URL(window.location.href);const action=new URL(this.elem.dataset.chartUrl,window.location.href);if(parseInt(url.searchParams.get('highlight'))&&url.searchParams.get('highlight')===action.searchParams.get('chartId')){this.pulse();ips.utils.history.replaceState(window.history.state?._current?.[window.history.state?._lastKey]||{},window.history.state?._lastKey||"",url.updateSearchParams({params:{highlight:null}}).toString());}},pulse(){setTimeout(()=>{requestAnimationFrame(()=>{this.elem.animate([{boxShadow:"0 0 0px 0px color-mix(in srgb-linear, var(--i-primary) 50%, transparent)",offset:0},{boxShadow:"0 0 4px 4px color-mix(in srgb-linear, var(--i-primary) 50%, transparent)",offset:0.15},{boxShadow:"0 0 4px 4px color-mix(in srgb-linear, var(--i-primary) 50%, transparent)",offset:0.85},{boxShadow:"0 0 0px 0px color-mix(in srgb-linear, var(--i-primary) 50%, transparent)",offset:1},],4000);});},1000);},changeTimescale:function(e){this.timescale=$(e.currentTarget).attr('data-timescale');this._toggleButtonRow(e,'timescale');},changeChartType:function(e){this.type=$(e.currentTarget).attr('data-type');this._toggleButtonRow(e,'type');this.checkType();},checkType:function(){if(this.type=='Table'||this.type=='PieChart'||this.type=='GeoChart'){$(this.scope).find('[data-role="groupingButtons"] a.ipsButton').addClass('ipsButton--disabled');}else{$(this.scope).find('[data-role="groupingButtons"] a.ipsButton').removeClass('ipsButton--disabled');}},updateUrlBound:false,changeFilter:function(e,data=e.detail){data.originalEvent.preventDefault();this._resetFilters();if(this.updateUrlBound===false){$('[data-action="chartFilter"]').one('menuClosed',_.bind(this.fetchNewResults,this));this.updateUrlBound=true;}},fetchNewResults:function(e){this._updateURL();this.updateUrlBound=false;},saveFilters:function(event){var identifier=this.scope.closest('.ipsTabs__panel').closest('section').attr('id');var self=this;var pieces=[];_.each(this.storedValues.filters,function(value,idx){pieces.push("chartFilters["+idx+"]="+value);});$('#el'+this.identifier+'CustomFiltersForm input[data-role="nodeValue"]').each(function(){pieces.push('customform_'+$(this).attr('name')+"="+$(this).val());});$('#el'+this.identifier+'CustomFiltersForm select').each(function(){pieces.push('customform_'+$(this).attr('name')+'='+$(this).val());})
var newFilters=pieces.join('&');if(this.timescale){newFilters=newFilters+"&timescale="+this.timescale;}
if(!$(event.currentTarget).attr('data-chartId')){this._skipUpdate=true;$('#el'+this.identifier+'FilterSave_menu').one('submit','form',function(e){if($(this).attr('data-bypassValidation')){return false;}
$(this).trigger('closeMenu');var tabTitle=$(this).find('[name="custom_chart_title"]').val();e.preventDefault();ips.getAjax()($(this).attr('action'),{data:$(this).serialize()+'&'+newFilters,type:'post'}).done(function(response,status,jqXHR){$('[data-ipsTabBar-contentArea="#'+identifier+'"]').find('[role="tablist"]').append("<a href='"+response.tabHref+"' id='ipsTabs_"+response.tabId+"_"+response.chartId+"' class='ipsTabs__tab' title='"+tabTitle+"' role='tab' aria-controls='ipsTabs_"+response.tabId+"_"+response.chartId+"_panel' aria-selected='false'>"+tabTitle+"</a>");$('#'+identifier).append("<div id='ipsTabs_"+response.tabId+"_"+response.chartId+"_panel' class='ipsTabs__panel' role'tabpanel' aria-labelledby='ipsTabs_"+response.tabId+"_"+response.chartId+"' hidden></div>");self._skipUpdate=false;$(document).trigger('contentChange',[self.scope]);$('#el'+self.identifier+'FilterSave_menu').find('[name="custom_chart_title"]').val('');$('#'+response.tabId+"_"+response.chartId).click();ips.ui.flashMsg.show(ips.getString('saved'));}).fail(function(){$(this).attr('data-bypassValidation',true).submit();});});}
$(this)[0].closest("[popover]")?.hidePopover();var tabTitle=$(this).find('[name="custom_chart_title"]').val();e.preventDefault();ips.getAjax()($(this).attr('action'),{data:$(this).serialize()+'&'+newFilters,type:'post'}).done(function(response,status,jqXHR){if(response.reportURL){window.location.href=response.reportURL;return;}
$('[data-ipsTabBar-contentArea="#'+identifier+'"]').find('[role="tablist"]').append("<a href='"+response.tabHref+"' id='ipsTabs_"+response.tabId+"_"+response.chartId+"' class='ipsTabs__tab' title='"+tabTitle+"' role='tab' aria-controls='ipsTabs_"+response.tabId+"_"+response.chartId+"_panel' aria-selected='false'>"+tabTitle+"</a>");$('#'+identifier).append("<div id='ipsTabs_"+response.tabId+"_"+response.chartId+"_panel' class='ipsTabs__panel' role'tabpanel' aria-labelledby='ipsTabs_"+response.tabId+"_"+response.chartId+"' hidden></div>");self._skipUpdate=false;$(document).trigger('contentChange',[self.scope]);$('#el'+self.identifier+'FilterSave_menu').find('[name="custom_chart_title"]').val('');$('#'+response.tabId+"_"+response.chartId).click();ips.ui.flashMsg.show(ips.getString('saved'));}).fail(function(){$(this).attr('data-bypassValidation',true).submit();});});}
else
{ips.getAjax()(this.scope.attr('data-chart-url')+'&saveFilters=1&chartId='+$(event.currentTarget).attr('data-chartId'),{data:newFilters,type:'post'});this._updateURL();ips.ui.flashMsg.show(ips.getString('saved'));}},renameFilters(){const identifier=this.scope.closest('.ipsTabs__panel').closest('section').attr('id');const titlefield=()=>identifier?$(`[data-ipsTabBar-contentArea="#${identifier}"] [role="tablist"] [aria-selected="true"]`):this.scope.find('.ipsTitle');$('#el'+this.identifier+'FilterRename_menu').on('submit','form',async function(e){if($(this).attr('data-bypassValidation')){return false;}
$(this).trigger('closeMenu');e.preventDefault();try{const{title}=await ips.fetch($(this).attr('action'),{data:$(this).serialize(),type:'post'});titlefield().text(title);}catch(e){console.log(e)
$(this).attr('data-bypassValidation',true).submit();}});},changeSearch:function(e){e.preventDefault();var form=$('#el'+this.identifier+'Search_menu');this.storedValues.term=form.find('[name="search"]').val();this.scope.find('[data-role="searchSummary"]').text(this.storedValues.term);if(this.storedValues.term){Debug.log(this.scope.find('[data-role="clearSearchTerm"]'));form.find('[data-role="clearSearchTerm"]').show();}
else
{form.find('[data-role="clearSearchTerm"]').hide();}
form.trigger('closeMenu');this._updateURL();},resetSearch:function(e){$('#el'+this.identifier+'Search_menu').find('[name="search"]').val('');},changeDateRange:function(e){e.preventDefault();var form=$('#el'+this.identifier+'Date_menu');this.storedValues.dates.start=form.find('[name="start"]').val();this.storedValues.dates.end=form.find('[name="end"]').val();form.trigger('closeMenu');if(this.storedValues.dates.start&&this.storedValues.dates.end){this.scope.find('[data-role="dateSummary"]').text('('+ips.getString('betweenXandX',{start:ips.utils.time.localeDateString(ips.utils.time.removeTimezone(new Date(this.storedValues.dates.start))),end:ips.utils.time.localeDateString(ips.utils.time.removeTimezone(new Date(this.storedValues.dates.end)))})+')');}
e.preventDefault();$(this)[0].closest("[popover]")?.hidePopover();try{const{title}=await ips.fetch($(this).attr('action'),{data:$(this).serialize(),type:'post'});titlefield().text(title);}catch(e){Debug.error(e)
$(this).attr('data-bypassValidation',true).submit();}});},changeSearch:function(e){e.preventDefault();var form=$('#el'+this.identifier+'Search_menu');this.storedValues.term=form.find('[name="search"]').val();this.scope.find('[data-role="searchSummary"]').text(this.storedValues.term);form.find('[data-role="clearSearchTerm"]').prop('hidden',!this.storedValues.term);form[0].closest("[popover]")?.hidePopover();this._updateURL();},resetSearch:function(e){$('#el'+this.identifier+'Search_menu').find('[name="search"]').val('');},changeDateRange:function(e){const identifier=this.elem.querySelector('[data-action="chartDate"]')?.id;if(identifier&&!e.target?.closest(`#${identifier}_menu`)){return;}
e.preventDefault();var form=$('#el'+this.identifier+'Date_menu');this.storedValues.dates.start=form.find('[name="start"]').val();this.storedValues.dates.end=form.find('[name="end"]').val();form[0].closest("[popover]")?.hidePopover();if(this.storedValues.dates.start&&this.storedValues.dates.end){this.scope.find('[data-role="dateSummary"]').text('('+ips.getString('betweenXandX',{start:ips.utils.time.localeDateString(ips.utils.time.removeTimezone(new Date(this.storedValues.dates.start))),end:ips.utils.time.localeDateString(ips.utils.time.removeTimezone(new Date(this.storedValues.dates.end)))})+')');}
else if(this.storedValues.dates.start){this.scope.find('[data-role="dateSummary"]').text('('+ips.getString('afterX',{start:ips.utils.time.localeDateString(ips.utils.time.removeTimezone(new Date(this.storedValues.dates.start)))})+')');}
else if(this.storedValues.dates.end){this.scope.find('[data-role="dateSummary"]').text('('+ips.getString('beforeX',{end:ips.utils.time.localeDateString(ips.utils.time.removeTimezone(new Date(this.storedValues.dates.end)))})+')');}
else
{this.scope.find('[data-role="dateSummary"]').text('');}
this._updateURL();},_toggleButtonRow:function(e,type){e.preventDefault();var val=$(e.currentTarget).attr('data-'+type);this.scope.find('[data-'+type+']').removeClass('ipsButton--active').removeAttr('data-selected').filter('[data-'+type+'="'+val+'"]').addClass('ipsButton--active').attr('data-selected',true);this.storedValues[type]=val;this._resetFilters();this._updateURL();},_resetFilters:function(){var self=this;this.storedValues.filters=[];$('#el'+this.identifier+'Filter_menu').find('.ipsMenu_itemChecked').each(function(){self.storedValues.filters.push($(this).attr('data-ipsMenuValue'));});},_skipUpdate:false,_updateURL:function(){if(this._skipUpdate===true){this._skipUpdate=false;return;}
var url=this._buildURL();var chartArea=this.scope.find('[data-role="chart"]');chartArea.css('height',chartArea.height()).html('').addClass('ipsLoading');ips.getAjax()(this.scope.attr('data-chart-url'),{data:url,type:'post'}).done(function(response){chartArea.css('height','auto').html(response);$(document).trigger('contentChange',[chartArea]);}).always(function(){chartArea.removeClass('ipsLoading');});$('button[data-role="applyFilters"]').prop('disabled',true);this.scope.find('[data-role="downloadChart"]').attr('href',this.scope.attr('data-chart-url')+'&'+url+'&download=1');},_buildURL:function(){var pieces=[];var self=this;pieces.push("noheader=1");pieces.push("timescale["+this.identifier+"]="+this.storedValues.timescale);if(!_.isUndefined(this.storedValues.type)){pieces.push("type["+this.identifier+"]="+this.storedValues.type);}
if(!_.isUndefined(this.storedValues.term)&&!_.isNull(this.storedValues.term)){pieces.push("search["+this.identifier+"]="+this.storedValues.term);}
_.each(this.storedValues.filters,function(value,idx){pieces.push("filters["+self.identifier+"]["+idx+"]="+value);});if(this.storedValues.dates.start||this.storedValues.dates.end){pieces.push("start["+this.identifier+"]="+this.storedValues.dates.start);pieces.push("end["+this.identifier+"]="+this.storedValues.dates.end);}
$('#el'+this.identifier+'CustomFiltersForm input[data-role="nodeValue"]').each(function(){pieces.push('customform_'+$(this).attr('name')+"="+$(this).val());});return pieces.join('&');}});}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register('core.admin.core.editorRestrictions',{_restrictions:[],initialize(){if(!this._getHeader()||!this._getTextarea()){return;}
this.hideRealElements();ips.ui.editorv5.getExtensionRestrictions().then(restrictions=>this.addFormElements(restrictions));this.elem.addEventListener('input',e=>this.updateTextarea(e));},hideRealElements(){this._getHeader()?.setAttribute('hidden','');this._getTextarea()?.closest('.ipsFieldRow')?.setAttribute('hidden','');},_getHeader(){return this.elem.querySelector("#form_header_editor_extensions");},_getTextarea(){return this.elem.querySelector("textarea#el_editor_extension_restrictions_input, #el_editor_extension_restrictions_input textarea");},async addFormElements(restrictions){this._restrictions=restrictions;if(!restrictions.length){return;}
try{const content=await ips.fetch("/admin/?app=core&module=settings&controller=posting&do=getRestrictionInput",{data:{restrictionKey:restrictions.join(','),restrictionLang:JSON.stringify(restrictions.map(restriction=>ips.getString(restriction))),restrictionDesc:JSON.stringify(restrictions.map(restriction=>ips.haveString(restriction+':description')?ips.getString(restriction+":description"):""))}});if(!content?.content||typeof content.content!=='string'){throw new TypeError(`content.content is not a string or is an empty string, so it cannot be added to the form`);}
this._updateURL();},globalDateRangeSet(e){let{start,end,range}=e?.detail?.dateFilters||{};if(!start&&!end&&!range){return;}
if(range){const days=parseInt(range);if(Number.isNaN(days)){throw new RangeError(`Expected range to be an integer representing a number of days`);}else if(days>=0){end=Math.round(Date.now()/1000);start=days>0?end-(86400*days):0;}}
if(typeof start==='string'){start=Math.round((new Date(start)).getTime()/1000);}
if(typeof end==='string'){end=Math.round((new Date(end)).getTime()/1000);}
if(Number.isNaN(start)||Number.isNaN(end)){throw new RangeError(`Could not determine either the start or end of the interval`);}
this.storedValues.dates.start=start;this.storedValues.dates.end=end;this.storedValues.dates.range=range;this._updateURL();},_toggleButtonRow:function(e,type){e.preventDefault();var val=$(e.currentTarget).attr('data-'+type);this.scope.find('[data-'+type+']').removeClass('ipsButton--active').removeAttr('data-selected').filter('[data-'+type+'="'+val+'"]').addClass('ipsButton--active').attr('data-selected',true);this.storedValues[type]=val;this._resetFilters();this._updateURL();},_resetFilters:function(){var self=this;this.storedValues.filters=[];$('#el'+this.identifier+'Filter_menu').find('[aria-selected="true"]').each(function(){self.storedValues.filters.push($(this).attr('data-ipsMenuValue'));});},_skipUpdate:false,_updateURL:function(){if(this._skipUpdate===true){this._skipUpdate=false;return;}
var url=this._buildURL();var chartArea=this.scope.find('[data-role="chart"]');chartArea.css('height',chartArea.height()).html('').addClass('ipsLoading');ips.getAjax()(this.scope.attr('data-chart-url'),{data:url,type:'post'}).done(function(response){chartArea.css('height','auto').html(response);$(document).trigger('contentChange',[chartArea]);}).always(function(){chartArea.removeClass('ipsLoading');});this.scope.find('[data-role="downloadChart"]').attr('href',this.scope.attr('data-chart-url')+'&'+url+'&download=1');},_buildURL:function(){const params=new URLSearchParams();params.set('noheader','1');params.set(`timescale[${this.identifier}]`,this.storedValues.timescale);if('type'in this.storedValues){params.set(`type[${this.identifier}]`,this.storedValues.type);}
if(this.storedValues.term!==undefined&&this.storedValues.term!==null){params.set(`search[${this.identifier}]`,this.storedValues.term);}
if(this.storedValues.filters&&Symbol.iterator in this.storedValues.filters){let idx=0;for(const value of this.storedValues.filters){params.set(`filters[${this.identifier}][${idx++}]`,value);}}
if(this.storedValues.dates.start||this.storedValues.dates.end){params.set(`start[${this.identifier}]`,this.storedValues.dates.start);params.set(`end[${this.identifier}]`,this.storedValues.dates.end);}
if(document.body.dataset.pagecontroller==='mycharts'&&document.body.dataset.pageapp==='core'&&document.body.dataset.pagemodule==='overview'){if(this.storedValues.dates.range){params.set('predate',this.storedValues.dates.range);}
if((!this.storedValues.dates.range||parseInt(this.storedValues.dates.range)===-1)&&(this.storedValues.dates.start||this.storedValues.dates.end)){params.delete('predate');params.set('date[start]',this.storedValues.dates.start||null);params.set('date[end]',this.storedValues.dates.end||null);}}
$('#el'+this.identifier+'CustomFiltersForm input[data-role="nodeValue"]').each(function(){params.set('customform_'+$(this).attr('name'),$(this).val());});$('#el'+this.identifier+'CustomFiltersForm select').each(function(){params.set('customform_'+$(this).attr('name'),$(this).val());});return params.toString();}});}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register('core.admin.core.editorRestrictions',{_restrictions:[],_restrictionDefaults:{},initialize(){if(!this._getHeader()||!this._getTextarea()){return;}
this.hideRealElements();document.dispatchEvent(new CustomEvent('ips:editorBeforeInit',{detail:{textarea:null,elem:null,content:"",options:{}},bubbles:true,}));ips.ui.editorv5.getExtensionRestrictions(true).then(restrictions=>this.addFormElements(restrictions));this.elem.addEventListener('input',e=>this.updateTextarea(e));},hideRealElements(){this._getHeader()?.setAttribute('hidden','');this._getTextarea()?.closest('.ipsFieldRow')?.setAttribute('hidden','');},_getHeader(){return this.elem.querySelector("#form_header_editor_extensions");},_getTextarea(){return this.elem.querySelector("textarea#el_editor_extension_restrictions_input, #el_editor_extension_restrictions_input textarea");},async addFormElements(restrictions){this._restrictions=restrictions.map(r=>r[0]);this._restrictionDefaults=Object.fromEntries(restrictions);if(!restrictions.length){return;}
try{const content=await ips.fetch("/admin/?app=core&module=settings&controller=posting&do=getRestrictionInput",{data:{restrictionKey:this._restrictions.join(','),restrictionDefault:JSON.stringify(Object.fromEntries(restrictions)),restrictionLang:JSON.stringify(this._restrictions.map(restriction=>ips.getString(restriction))),restrictionDesc:JSON.stringify(this._restrictions.map(restriction=>ips.haveString(restriction+':description')?ips.getString(restriction+":description"):""))}});if(!content?.content||typeof content.content!=='string'){throw new TypeError(`content.content is not a string or is an empty string, so it cannot be added to the form`);}
this._getHeader().removeAttribute('hidden');const clean=(new DOMParser()).parseFromString(content.content,'text/html').body;let lastNode=this._getHeader();clean.querySelectorAll(':scope > *').forEach(node=>{lastNode.after(node);lastNode=node;})}catch(e){Debug.error(e);}},updateTextarea(e){const name=e.target.getAttribute('name');if(!name?.match(/^ipsCustom(?:Node|Mark|Extension)__/)){return}
const restrictionSetting=JSON.parse(this._getTextarea().innerText||'{}');restrictionSetting.removed=restrictionSetting.removed||[]
const value=parseInt(e.target.value);for(const level in restrictionSetting){if(level==='removed'){continue;}
let value=parseInt(e.target.value);if([-1,0,1,2].includes(this._restrictionDefaults[name])&&this._restrictionDefaults[name]===value){restrictionSetting.removed.push(name);value=Number.NaN;}else if([0,1,2,-1].includes(value)&&!(value.toString()in restrictionSetting)){restrictionSetting[value.toString()]=[name];}
for(const level in restrictionSetting){if(level==='removed'){continue;}
if(parseInt(level)===value&&!Number.isNaN(value)){if(!restrictionSetting[level].includes(name)){restrictionSetting[level].push(name)}}else if(restrictionSetting[level].includes(name)){restrictionSetting[level]=restrictionSetting[level].filter(restriction=>restriction!==name);}
restrictionSetting[level]=restrictionSetting[level].filter(restriction=>{if(restriction.match(/^ipsCustom(Node|Mark|Extension)__/)&&!this._restrictions.includes(restriction)){if(!restrictionSetting.removed.includes(restriction)){restrictionSetting.removed.push(restriction)}
return false;}
+12
View File
@@ -0,0 +1,12 @@
;(function(){"use strict";class iCard extends HTMLElement{constructor(){super();this.supportsPopover=CSS.supports("selector(:popover-open)");this.supportsAnimationTimeline=CSS.supports("(animation-timeline: scroll())");this.addEventListener("beforetoggle",this);this.addEventListener("toggle",this);}
handleEvent(e){return this[`${e.type}Event`]&&this[`${e.type}Event`](e);}
beforetoggleEvent(e){if(e.newState==="open"){if(this.hasAttribute("data-i-card-append")){const appendMenuTo=this.getAttribute("data-i-card-append")||"body";document.querySelector(appendMenuTo).append(this);}
if(!this.swipeElement){this.createSwipeElement();}}}
toggleEvent(e){if(e.newState==="open"){this.scrollTop=this.scrollHeight;this.swipeObserver.observe(this.swipeElement);if(!this.supportsAnimationTimeline){this.addEventListener("scroll",this);this.addEventListener("transitionend",this);}}else{this.swipeObserver.disconnect();if(!this.supportsAnimationTimeline){this.removeEventListener("scroll",this);this.removeEventListener("transitionend",this);}}}
transitionendEvent(e){if(e.target===this&&!this.supportsAnimationTimeline){this.style.setProperty('--_card-backdrop-height',this.scrollHeight-this.clientHeight);}}
scrollEvent(e){requestAnimationFrame(()=>{this.style.setProperty('--_card-backdrop-scroll',this.scrollTop);});}
createSwipeElement(){let addBackdropElements=``;if(!this.querySelector(".iCardSwipe")){addBackdropElements+=`<div class='iCardSwipe'></div>`;}
if(!this.querySelector(".iCardDismiss")){addBackdropElements+=`<button class="iCardDismiss" type="button" popovertarget="${this.id}" popovertargetaction="hide" aria-label="Close" tabindex="-1"></button>`;}
this.insertAdjacentHTML("afterbegin",addBackdropElements);this.swipeElement=this.querySelector(".iCardSwipe");}
swipeObserver=new IntersectionObserver(entries=>{if(entries.some(entry=>entry.isIntersecting)){this.hidePopover();}},{root:this,threshold:.1})}
ips.ui.registerWebComponent("card",iCard);Debug.log(`Submitted the web component constructor, iCard, for ${"card"}`);})();;
@@ -0,0 +1,41 @@
;(function(){"use strict";class iDropdown extends HTMLElement{connectedCallback(){this.supportsAnchor=CSS.supports("(top: anchor(bottom)) and (not (-webkit-hyphens: auto))");this.supportsPopover=CSS.supports("selector(:popover-open)");this.supportsAnimationTimeline=CSS.supports("(animation-timeline: scroll())");this.addEventListener("beforetoggle",this);this.addEventListener("toggle",this);if(this.matches(":popover-open")){this.beforetoggleEvent({newState:"open",oldState:"closed"});this.toggleEvent({newState:"open",oldState:"closed"});}}
handleEvent(e){return this[`${e.type}Event`]&&this[`${e.type}Event`](e);}
clickEvent(e){let itemClicked=e.target.closest(".iDropdown__items a, .iDropdown__items button");this.handleClick(e,itemClicked);}
changeEvent(e){let itemClicked=e.target.closest(".iDropdown__items label");this.handleClick(e,itemClicked);}
handleClick(e,itemClicked){if(!itemClicked)return;if(!itemClicked.closest("[data-i-dropdown-persist]")){setTimeout(()=>{itemClicked.closest("i-dropdown")?.hidePopover();},150);}
if(itemClicked.closest("[data-i-dropdown-noselect]"))return;const pingItems=itemClicked.closest('[data-action="ipsMenu_ping"]');if(pingItems){e.preventDefault();ips.getAjax()(pingItems.getAttribute('href')).done(()=>{this.trigger.dispatchEvent(new CustomEvent('menuPingSuccessful',{}));});}
const selectedTextTrigger=this.trigger.closest('[data-role="ipsMenu_selectedText"]'),selectedTextMenu=e.target.closest('[data-role="ipsMenu_selectedText"]');if(selectedTextTrigger&&selectedTextMenu){selectedTextTrigger.innerText=selectedTextMenu.innerText;}
const selectedIconTrigger=this.trigger.closest('[data-role="ipsMenu_selectedIcon"]'),selectedIconMenu=e.target.closest('[data-role="ipsMenu_selectedIcon"]');if(selectedIconTrigger&&selectedIconMenu){selectedIconTrigger.replaceWith(selectedIconMenu.cloneNode(true));}
let eventDetail={triggerElem:this.trigger,triggerID:this.trigger.getAttribute("popovertarget"),menuElem:this,originalEvent:e};let selectableList=itemClicked.closest("[data-i-dropdown-selectable]");if(selectableList&&itemClicked.matches("a, button")){if(selectableList.getAttribute("data-i-dropdown-selectable")==="radio"){selectableList.querySelectorAll('[aria-selected="true"]').forEach(el=>el.removeAttribute("aria-selected"));itemClicked.setAttribute("aria-selected","true");}else{if(itemClicked.hasAttribute("aria-selected")){itemClicked.removeAttribute("aria-selected")}else{itemClicked.setAttribute("aria-selected","true")}}}
if(itemClicked.hasAttribute("data-ipsMenuValue")){eventDetail.selectedItemID=itemClicked.getAttribute("data-ipsMenuValue");}else{let inputValue=itemClicked.querySelector("input[value]");if(inputValue){eventDetail.selectedItemID=inputValue.value;}}
let selectedListItems=this.querySelectorAll("[aria-selected='true'], :checked"),selectedItemObj={};if(selectedListItems.length){selectedListItems.forEach(el=>{let input=el.closest("label");if(input){el=input;}
if(!el.id){el.id='ips_uid_'+Math.floor(Math.random()*9999)+1;}
selectedItemObj[el.getAttribute('id')]=el;})
eventDetail.selectedItems=selectedItemObj;}
this.trigger.dispatchEvent(new CustomEvent("menuItemSelected",{detail:eventDetail,bubbles:true}));}
beforetoggleEvent(e){this.open=e.newState==='open';if(e.newState==="open"){this.removeAttribute("hidden-via-swipe");if(e.source){this.trigger=e.source}else if(document.activeElement.matches("[popovertarget]")){this.trigger=document.activeElement;}else{this.trigger=document.querySelector(`[popovertarget="${this.id}"]`);}
if(this.hasAttribute("data-i-dropdown-append")){const appendMenuTo=this.getAttribute("data-i-dropdown-append")||"body";document.querySelector(appendMenuTo)?.append(this);}
if(!this._remoteContentLoaded){this.resetRemoteContent().catch(err=>Debug.error(err)).finally(()=>{if(this.open){this.scrollTop=this.scrollHeight;}});}
this.positionAnchors(e);if(!this.swipeElement){this.createSwipeElement();}}}
toggleEvent(e){if(e.newState==="open"){this.scrollTop=this.scrollHeight;this.trigger.ariaExpanded="true";this.swipeObserver.observe(this.swipeElement);this.addEventListener("change",this);this.addEventListener("click",this);if(!this.supportsAnimationTimeline){this.addEventListener("transitionend",this);}
if(!this.supportsPopover){document.addEventListener("scroll",this,{passive:true});}
this.trigger.dispatchEvent(new CustomEvent("menuOpened",{detail:{elemID:(this.trigger.id)?this.trigger.id:this.trigger.getAttribute("popovertarget"),menu:this},bubbles:true}));}else{this.swipeObserver.disconnect();if(!this.supportsAnimationTimeline){this.removeEventListener("scroll",this,{passive:true});this.removeEventListener("transitionend",this);}
if(!this.supportsPopover&&!document.querySelector('i-dropdown[class*=":popover-open"]')){document.removeEventListener("scroll",this,{passive:true});}
this.trigger.ariaExpanded="false";this.trigger.dispatchEvent(new CustomEvent("menuClosed",{detail:{elemID:(this.trigger.id)?this.trigger.id:this.trigger.getAttribute("popovertarget"),menu:this},bubbles:true}));}}
transitionendEvent(e){if(e.target===this){this.addEventListener("scroll",this,{passive:true});}}
scrollEvent(e){requestAnimationFrame(()=>{if(e.target===this){this.style.setProperty('--i-dropdown--backdrop-scroll',Math.floor(this.scrollTop/(this.scrollHeight-this.clientHeight)*100)+"%");}else{this.style.setProperty("--_anchor-scroll",window.scrollY+"px");}});}
createContentElement(){this.contentElement=this.querySelector(':scope > :is(.iDropdown, [data-i-dropdown-wrapper]) > :is(.iDropdown__content, [data-i-dropdown-content])');if(this.contentElement instanceof HTMLElement){return;}
let contentWrapper=this.querySelector(`:scope > :is(.iDropdown, [data-i-dropdown-wrapper])`);if(!contentWrapper){this.insertAdjacentHTML("beforeend","<div class='iDropdown' data-i-dropdown-wrapper></div>");contentWrapper=this.querySelector(`:scope > :is(.iDropdown, [data-i-dropdown-wrapper])`);}
contentWrapper.insertAdjacentHTML("beforeend","<div class='iDropdown__content' data-i-dropdown-content=''></div>");this.contentElement=contentWrapper.querySelector(':scope > :is(.iDropdown__content, [data-i-dropdown-content])');}
async resetRemoteContent(){if(this.dataset.iDropdownSource){this._remoteContentLoaded=true;if(!this.contentElement){this.createContentElement();}
this.contentElement.classList.add('ipsLoading','ipsLoading--small');if(!this.open){this._remoteContentLoaded=false;return;}
try{let res=await ips.fetch(this.dataset.iDropdownSource);if(!this._remoteContentLoaded){return;}
if(typeof res==='object'){res=res.content;}
if(typeof res!=='string'){throw new TypeError(`Expected a string as the content type`);}
this.contentElement.classList.remove('ipsLoading','ipsLoading--small');this.contentElement.innerHTML=res;$(document).trigger('contentChange',[this.contentElement]);}catch(err){this._remoteContentLoaded=false;throw err;}}}
createSwipeElement(){let addBackdropElements=``;if(!this.querySelector(".iDropdownSwipe")){addBackdropElements+=`<div class='iDropdownSwipe'></div>`;}
if(!this.querySelector(".iDropdownDismiss")){addBackdropElements+=`<button class="iDropdownDismiss" type="button" popovertarget="${this.id}" popovertargetaction="hide" aria-label="Close"></button>`;}
this.insertAdjacentHTML("afterbegin",addBackdropElements);this.swipeElement=this.querySelector(".iDropdownSwipe");}
swipeObserver=new IntersectionObserver(entries=>{entries.forEach(entry=>{if(entry.isIntersecting){this.setAttribute("hidden-via-swipe",true);this.style.removeProperty('--i-dropdown--backdrop-scroll');this.hidePopover();}});},{root:this,threshold:.1})
positionAnchors(e){if(!this.supportsAnchor){this.triggerPos=this.trigger.getBoundingClientRect();this.style.setProperty("--_anchor-v",window.scrollY+this.triggerPos.bottom+"px");this.style.setProperty("--_anchor-h",this.triggerPos.left+(this.triggerPos.width/2)+"px");this.style.setProperty("--_anchor-height",this.triggerPos.height+"px");this.style.setProperty("--_remaining-height",document.documentElement.scrollHeight-window.scrollY-this.triggerPos.bottom+"px");if(!this.supportsPopover){this.style.setProperty("--_anchor-scroll",window.scrollY+"px");}}else if(!e.source){if(!this.anchorCounter)this.anchorCounter=1;let anchorName=`--${this.id}-${this.anchorCounter++}`;this.trigger.style.setProperty("anchor-name",anchorName);this.style.setProperty("position-anchor",anchorName);}}}
ips.ui.registerWebComponent("dropdown",iDropdown);Debug.log(`Submitted the web component constructor, iDropdown, for ${"dropdown"}`);})();;
+9
View File
@@ -0,0 +1,9 @@
;(function(){"use strict";class iLatex extends HTMLElement{_latexHTML=null;get latexHTML(){return this._latexHTML;}
_originalText="";get originalText(){return this._originalText;}
constructor(){super();this._originalText=this.textContent;this.addEventListener('fillLatex',this.fill);this.addEventListener('unfillLatex',this.unfill);this.fill().then(()=>{});}
async katexLoaded(){await ips.ui._codehighlighting.whenLoaded();}
async fill(text){if(typeof text==='string'&&text!==this._originalText){this._originalText=text;this._latexHTML=null;}
if(!this._latexHTML){await this.katexLoaded();this._latexHTML=await ips.ui.codehighlighting.renderKatexRaw(this._originalText);}
this.innerHTML=this._latexHTML;}
unfill(){this.textContent=this._originalText;}}
ips.ui.registerWebComponent("latex",iLatex);Debug.log(`Submitted the web component constructor, iLatex, for ${"latex"}`);})();;
@@ -0,0 +1,13 @@
;(function(){"use strict";class iLatexNodeview extends HTMLElement{_preview=null;get preview(){return this._preview;}
_source=null;get source(){return this._source;}
_childObserver=null;_sourceObserver=null;constructor(){super();this._childObserver=new MutationObserver(_.throttle(entries=>this._identifyComponentsInChildren(),100));this._sourceObserver=new MutationObserver(_.debounce(entries=>this._updateView(),500));this._childObserver.observe(this,{childList:true,subtree:true});this._identifyComponentsInChildren();this.addEventListener('click',this);}
handleEvent(e){if(!(e instanceof Event)){throw new TypeError(`A non-event object passed to handleEvent.`);}
switch(e.type){case'click':if(e.target.closest('i-latex')===this.preview&&this.source&&this.preview){this._focusSource()}
break;}}
_focusSource(){if(!this.source){return;}
this.source.classList.remove('ipsInvisible');this.preview.classList.add('iLatex--no-decoration');this.preview.querySelector(":scope > .latex")?.classList.add('ipsInvisible');const selection=document.getSelection();selection.removeAllRanges();const range=new Range();range.setStart(this.source.childNodes[0]||this.source,1);range.setEnd(this.source.childNodes[0]||this.source,0);selection.addRange(range);}
_identifyComponentsInChildren(){const preview=this.querySelector('i-latex');if(preview!==this._preview){this._preview=preview;}
const source=this.querySelector('[data-latex-source]');if(source!==this._source){this._source=source;this._sourceObserver.disconnect();if(source){this._sourceObserver.observe(this._source,{subtree:true,characterData:true});this._updateView();}}}
_updateView(){if(!this._source||!this._preview){Debug.warn(`Cannot update view of i-latex-nodeview element because either its source or its preview is undefined`);return;}
customElements.whenDefined('i-latex').then(()=>this._preview.fill(this._source.textContent));}}
ips.ui.registerWebComponent("latexNodeview",iLatexNodeview);Debug.log(`Submitted the web component constructor, iLatexNodeview, for ${"latexNodeview"}`);})();;
@@ -0,0 +1,6 @@
;(function(){"use strict";class IPullToRefresh extends HTMLElement{constructor(){super();}
connectedCallback(){this.dragDistance=150;this.swipeObserver.observe(this);}
handleEvent(e){requestAnimationFrame(()=>{this.style.setProperty("--_scroll",(window.scrollY>0)?0:window.scrollY);if(window.scrollY<this.dragDistance*-1){document.removeEventListener("scroll",this);document.documentElement.setAttribute("data-ips-pwa-refreshing","");setTimeout(()=>{location.reload();},16);}});}
setDragDistance(){this.dragDistance=Math.min(150,window.innerHeight*0.25);this.style.setProperty("--_limit",this.dragDistance);}
swipeObserver=new IntersectionObserver(entries=>{entries.forEach(entry=>{if(entry.isIntersecting){document.addEventListener("scroll",this);this.setDragDistance();}else{document.removeEventListener("scroll",this);}});},{threshold:.1})}
ips.ui.registerWebComponent("pullToRefresh",IPullToRefresh);Debug.log(`Submitted the web component constructor, IPullToRefresh, for ${"pullToRefresh"}`);})();;
@@ -0,0 +1,12 @@
;(function(){"use strict";class iPushNotificationsPrompt extends HTMLElement{constructor(){super();}
connectedCallback(){if(!("Notification"in window))return;this.addEventListener("click",this);if((this.hasAttribute("data-persistent"))||(Notification.permission==="default")){this.updateUI(Notification.permission);this.hidden=false;}}
handleEvent(e){return this[`${e.type}Event`]&&this[`${e.type}Event`](e);}
clickEvent(e){const el=e.target.closest('[data-click]');if(!el)return;const method=el.getAttribute("data-click");if(method&&typeof this[method]==="function"){return this[method](e);}else{console.warn(`No method named "${method}" found on`,this);}}
hideMessage(e){this.hidden=true;}
async requestPermission(){try{const permission=await Notification.requestPermission();if(permission==="granted"){$(document).trigger('permissionGranted.notifications');}
else
{$(document).trigger('permissionDenied.notifications');}
document.querySelectorAll("i-push-notifications-prompt").forEach(el=>{el.updateUI(permission);});}catch(error){console.error('Permission request failed:',error);document.querySelectorAll("i-push-notifications-prompt").forEach(el=>{el.updateUI('error');});}}
updateUI(permission){this.setAttribute("data-permission",permission);const contentEl=this.querySelector('[data-role="content"]');if(!contentEl)return;const template=this.querySelector(`template[data-value="${permission}"]`);if(!template){console.warn(`Cannot update message. There is no template[data-value="${permission}"] element`);return;}
const clone=template.content.cloneNode(true);contentEl.innerHTML='';contentEl.appendChild(clone);}}
ips.ui.registerWebComponent("pushNotificationsPrompt",iPushNotificationsPrompt);Debug.log(`Submitted the web component constructor, iPushNotificationsPrompt, for ${"pushNotificationsPrompt"}`);})();;
@@ -0,0 +1,8 @@
;(function(){"use strict";class IPwaInstall extends HTMLElement{constructor(){super();this.deferredAndroidPrompt=null;this.dismissed=ips.utils.cookie.get('pwaInstallBanner');}
handleEvent(e){return this[e.type+"Event"]&&this[e.type+"Event"](e);}
connectedCallback(){this.addEventListener("click",this);window.addEventListener('appinstalled',this);window.addEventListener('beforeinstallprompt',this);}
clickEvent(e){if(e.target.closest("#iPwaInstall__dismiss")){ips.utils.cookie.set('pwaInstallBanner',"dismissed",true);this.hideBanner();}}
beforeinstallpromptEvent(e){if(this.dismissed)return;e.preventDefault();this.deferredAndroidPrompt=e;}
appinstalledEvent(e){ips.utils.cookie.set('pwaInstallBanner',"installed",true);this.hideBanner();}
hideBanner(){this.hidden=true;}}
ips.ui.registerWebComponent("pwaInstall",IPwaInstall);Debug.log(`Submitted the web component constructor, IPwaInstall, for ${"pwaInstall"}`);})();;
@@ -0,0 +1,6 @@
;(function(){"use strict";class iPwaLoading extends HTMLElement{constructor(){super();}
connectedCallback(){document.addEventListener("click",this);window.addEventListener('pageshow',this);}
handleEvent(e){return this[`${e.type}Event`]&&this[`${e.type}Event`](e);}
pageshowEvent(e){if(e.persisted){this.hidden=true;}}
clickEvent(e){const link=e.target.closest("a[href]");if(!link)return;setTimeout(()=>{if(e.defaultPrevented)return;if(link.matches('[href^="#"], [href^="javascript:"], [target="_blank"]')||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;this.hidden=false;});}}
ips.ui.registerWebComponent("pwaLoading",iPwaLoading);Debug.log(`Submitted the web component constructor, iPwaLoading, for ${"pwaLoading"}`);})();;
@@ -0,0 +1,101 @@
;(function(){"use strict";class IThemeEditor extends HTMLElement{constructor(){super();this.form=this.querySelector('form');this.inputs=this.form.elements;this.panels=this.querySelectorAll('editor-panel');this.currentPanel=document.getElementById('panel__start');this.panelHistory=[];this.settings={vars:{},text:{},layouts:{},images:{},headerPositions:{},dataAttributes:{}};this.iframe=document.getElementById('themeEditorIframe').contentWindow;this.iframeStyleTag='';this.iframeTempStyleTag='';this.styleTag=document.getElementById('themeEditorStyles');this.tempStyleTag=document.getElementById('themeEditorTempStyles');this.colorPickerText=this.querySelector('[data-color-picker-text]');this.colorPreview=this.querySelector('#panel__colorSelector [data-color-preview]');this.customCssDialog=this.querySelector("#dialog__customCSS");this.customCSSEditor=this.querySelector("#customCSS");this.customCssDialog.addEventListener('close',e=>this.updateCustomCSS(e));this.activeColor='';this.init();this.form.addEventListener('click',this);this.form.addEventListener('input',this);this.form.addEventListener('change',this);this.form.addEventListener('ips:codeboxAfterInit',e=>{if(e?.detail?.instance){this.cssEditorInstance=e.detail.instance;this.showOrHideCSSWarning();}
this.showOrHideRevertButton();});this.debounceTimeout=undefined;this.form.addEventListener('ips:codebox#update',e=>{if(e?.detail?.instance){this.cssEditorInstance=e.detail.instance;}
if(this.customCSSEditor instanceof Element&&e?.detail?.elem?.closest('#customCSS')===this.customCSSEditor){if(this.debounceTimeout!==undefined){clearTimeout(this.debounceTimeout);}
this.debounceTimeout=setTimeout(()=>{this.showOrHideCSSWarning();this.showOrHideRevertButton();},200);}})
this.form.addEventListener('change',e=>this.unsavedChanges=true);this.form.addEventListener('keydown',e=>this.preventReturnKeySubmission(e));window.addEventListener("beforeunload",e=>this.handleBeforeUnload(e));document.getElementById('themeEditorIframe').addEventListener('load',e=>this.iframeSync());document.addEventListener("ips:colorScheme",this.closeColorPicker);window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change',()=>{if(document.documentElement.getAttribute('data-ips-scheme-active')!='system')return;let active=(window.matchMedia('(prefers-color-scheme: dark)').matches)?'dark':'light';this.querySelector(`[data-workspace='color'] [value='${active}']`).click();});}
init(){ips.utils.color.loadIro().then(()=>{this.colorPicker=new ips.utils.iro.ColorPicker(this.querySelector('color-picker'),{width:250,color:"hsl(0 0% 0%)",layout:[{component:ips.utils.iro.ui.Box,options:{}},{component:ips.utils.iro.ui.Slider,options:{sliderType:'hue'}}]});this.colorPicker.on('input:change',color=>this.colorPickerChange(color));this.colorPicker.on('input:end',color=>this.colorPickerDone(color));});this.unsavedChanges=false;if(document.referrer&&!document.referrer.includes("/admin/")){document.getElementById('themeEditorIframe').src=document.referrer;}
this.setAttribute('data-loading',true);setTimeout(()=>{this.removeAttribute('data-loading');},3000);this.customSettingUIs();}
customSettingUIs(){let headerDrag=`
<div id="content__header__design">
<p class="i-padding-block_2 i-text-align_center i-color_soft i-flex_11">
<span class="i-display_hover">Click and drag to reorder header elements</span><span class="i-display_no-hover">Tap, hold and then drag to reorder header elements for the desktop header.</span>
</p>
<ul class="theme-editor__reorder" data-ips-reorder>
<li draggable="true" style="view-transition-name: el-1" data-pos="1"></li>
<li draggable="true" style="view-transition-name: el-2" data-pos="2"></li>
<li draggable="true" style="view-transition-name: el-3" data-pos="3"></li>
<li class="theme-editor__reorder-break"></li>
<li draggable="true" style="view-transition-name: el-4" data-pos="4"></li>
<li draggable="true" style="view-transition-name: el-5" data-pos="5"></li>
<li draggable="true" style="view-transition-name: el-6" data-pos="6"></li>
<li class="theme-editor__reorder-break"></li>
<li draggable="true" style="view-transition-name: el-7" data-pos="7"></li>
<li draggable="true" style="view-transition-name: el-8" data-pos="8"></li>
<li draggable="true" style="view-transition-name: el-9" data-pos="9"></li>
<li class="theme-editor__reorder-break"></li>
<li draggable="true" style="view-transition-name: el-10" data-pos="10"></li>
<li draggable="true" style="view-transition-name: el-11" data-pos="11"></li>
<li draggable="true" style="view-transition-name: el-12" data-pos="12"></li>
</ul>
</div>`;this.querySelector('[data-setting="set__i-position-search"]').insertAdjacentHTML('afterend',headerDrag);let positionInputs=this.form.querySelectorAll('[name^="set__i-position-"]');positionInputs.forEach(input=>{let label=this.querySelector(`[for="${input.id}"]`),draggableEl=this.querySelector(`[data-ips-reorder] [data-pos='${input.value}']`);draggableEl.setAttribute('data-label',label.textContent);draggableEl.setAttribute('data-name',input.id);});this.dragLabels=document.querySelectorAll('[data-ips-reorder] [draggable]');this.dragLabels.forEach(item=>{item.addEventListener('dragstart',ev=>this.handleDragStart(ev),false);item.addEventListener('dragenter',ev=>this.handleDragEnter(ev),false);item.addEventListener('dragover',ev=>this.handleDragOver(ev),false);item.addEventListener('dragleave',ev=>this.handleDragLeave(ev),false);item.addEventListener('drop',ev=>this.handleDrop(ev),false);item.addEventListener('dragend',ev=>this.handleDragEnd(ev),false);});}
changeWorkspace(e,target){let type=target.parentElement.getAttribute('data-workspace');if(target.matches(':only-child')){target.toggleAttribute('data-active');document.documentElement.setAttribute(`data-workspace-${type}`,target.hasAttribute('data-active'));}else{for(let el of target.parentElement.children){el.removeAttribute('data-active');}
target.setAttribute('data-active',true);document.documentElement.setAttribute(`data-workspace-${type}`,target.value);}}
panelNavigation(event,target){this.panels.forEach(p=>{p.setAttribute('aria-hidden','true');p.inert=true;});if(target.getAttribute('data-panel-nav')==='back'){this.currentPanel=document.getElementById(this.panelHistory.pop());this.currentPanel.setAttribute('aria-hidden','false');this.currentPanel.inert=false;this.currentPanel.removeAttribute('data-panel-prev');this.currentPanel.querySelector("button")?.focus();}else{if(target.hasAttribute('data-color-tool')){this.toggleColorPanel(target);}
let oldPanel=target.closest('editor-panel');this.currentPanel=document.getElementById(target.getAttribute('aria-controls'));this.currentPanel.setAttribute('aria-hidden','false');this.currentPanel.inert=false;this.currentPanel.querySelector("button, input, select, textarea")?.focus();this.currentPanel.querySelector(`[data-panel-nav="back"]`).innerText=oldPanel.querySelector('[data-panel-name]')?.innerText??'Back';this.panelHistory.push(oldPanel.id);oldPanel.setAttribute('data-panel-prev',true);}}
buildVariablesStyleTag(){this.styleContent='';this.iframeTempStyleTag.textContent='';for(const[key,value]of Object.entries(this.settings.vars)){if(['set__i-logo-text','set__i-logo-slogan'].includes(key))continue;if(this.settings.images[key]){if(this.settings.images[key].length){this.styleContent+=`--${key}: url("`+this.settings.images[key]+`");`;}}else{this.styleContent+=`--${key}: ${value};`}}
this.styleTag.textContent=`:root{ ${this.styleContent} }`;this.iframeStyleTag.textContent=`:root{ ${this.styleContent} }`;window.Debug?.log(this.iframeStyleTag.textContent);}
updateLiveText(setting,value){this.iframe.document.querySelectorAll(`[data-ips-theme-text='${setting}']`).forEach(le=>le.innerText=value);}
updateImagePreview(e){const preview=e.target.parentElement.querySelector('[data-file-preview]');preview.textContent='';delete this.settings.images[e.target.name];if(e.target.files.length>0){const src=URL.createObjectURL(e.target.files[0]);preview.innerHTML=`<img src="${src}" alt="">`;preview.parentElement.querySelector('[data-delete-logo]')?.remove();this.settings.images[e.target.name]=src;this.applyUploadedImageToIframe(e.target.name,src);}}
applyUploadedImageToIframe(name,value=null){let setting=name.replace("set__",""),elements=this.iframe.document.querySelectorAll(`[data-ips-theme-image='${setting}']`);elements.forEach(el=>{let picture=el.closest('picture');if(value){el.src=value;el.offsetHeight;el.hidden=false;if(picture)picture.hidden=false;el.removeAttribute('width');el.removeAttribute('height');}else{el.hidden=true;if(picture)picture.hidden=true;}});}
deleteLogoImage(event,target){const fileInput=target.parentElement.querySelector('[type=file]');fileInput.value='';delete this.settings.images[target.getAttribute('data-file-preview-delete')];fileInput.dispatchEvent(new Event("change",{bubbles:true}));if(!fileInput.parentElement.querySelector('[data-delete-logo]')){fileInput.insertAdjacentHTML('afterend',`<input type='hidden' name='delete__${fileInput.id}' value='1' data-delete-logo>`);}
this.applyUploadedImageToIframe(target.getAttribute('data-file-preview-delete'));}
updateLogoMaxHeightController(){}
updateDynamicMaxValueFor(receiver){}
closeColorPicker(event){if(document.querySelector("#panel__colorSelector[aria-hidden='false']")){document.querySelector('#panel__colorSelector [data-panel-nav="back"]').click();}}
preventReturnKeySubmission(e){let input=e.target;if(input.matches('i-theme-editor input')&&e.keyCode==13){e.preventDefault();if(input.min&&input.min>Number(input.value)){input.value=input.min;}else if(input.max&&input.max<Number(input.value)){input.value=input.max;}
input.dispatchEvent(new Event("change",{bubbles:true}));return false;}}
changingRangeInput(e,target){cancelAnimationFrame(this.rebuildStyleDebounce);this.rebuildStyleDebounce=requestAnimationFrame(()=>{this.iframeTempStyleTag.textContent=`:root{ --${e.target.id}: ${e.target.value}; }`;if(e.target.matches("#panel__oklch input")){this.tempStyleTag.textContent=`:root{ --${e.target.id}: ${e.target.value}; }`;}
let numInput=this.querySelector(`[data-range-output=${e.target.id}]`);if(numInput)numInput.value=e.target.value;});}
changingTextInput(e,target){this.updateLiveText(e.target.name,e.target.value);}
settingHasBeenChanged(e,target){let setting=target.name,value=target.value;this.settings.vars[setting]=value;if(e.target.matches('[type="range"]')){let numInput=this.querySelector(`[data-range-output=${e.target.id}]`);if(numInput)numInput.value=value;}else if(target.matches('[type="text"]')){this.settings.text[setting]=value;}
let attr='data-ips-theme-setting-'+setting.replace('set__i-','');if(this.iframe.document.documentElement.hasAttribute(attr)){this.settings.dataAttributes[attr]=value;this.applyDataAttributes(attr,value);}
if(target.matches('[type="file"]'))this.updateImagePreview(e);this.toggleRevertButton(target);let container=document.querySelector(`theme-setting[data-setting='${setting}']`);if(container.matches('[data-setting-refresh]'))this.refreshIframe(e);this.buildVariablesStyleTag();this.updateCustomCSS();}
syncInputsWithPseudo(e,target){let pseudoInput=e.target,input=document.getElementById(e.target.getAttribute('data-range-output'));if(pseudoInput.max)pseudoInput.value=Math.min(parseInt(pseudoInput.max),Math.max(parseInt(pseudoInput.min)||0,parseInt(pseudoInput.value)||0));if(e.target.type=='checkbox'){input.value=(e.target.checked)?1:0;}else{input.value=e.target.value;}
input.dispatchEvent(new Event("change",{bubbles:true}));}
async updateCustomCSS(){let content=document.querySelector('#customCSS').textContent;this.customCSSEditor.value=content;if(content.length){const{content:parsed}=await ips.fetch('?app=core&module=system&controller=themeeditor',{method:'post',data:{do:'customCss',content:content}});this.iframeCustomCSS.textContent=parsed;}else{this.iframeCustomCSS.textContent=content;}}
revertCustomCSS(event,target){if(confirm("This will revert your CSS back to its previously saved value. Any unsaved changes will be lost.")){const originalContent=this.querySelector('#customCSS-saved').innerText;document.querySelector("#customCSS").value=originalContent;this.cssEditorInstance?.setValue(originalContent);this.updateCustomCSS();target.hidden=true;}}
async showOrHideCSSWarning(){await ips.ui._codehighlighting.whenLoaded();const dialog=this.querySelector('#dialog__customCSS');const warning=dialog.querySelector('#customCSS-warning');if(!this.cssEditorInstance){Debug.warn('No editor instance found!');warning.removeAttribute('hidden');return;}
const preTag=document.createElement('pre');preTag.classList.add('language-ipscss');preTag.innerText=this.cssEditorInstance.getValue();const highlighted=await ips.ui.codehighlighting.highlight(this.cssEditorInstance.getValue(),'ipscss');preTag.innerHTML=highlighted.value;const hasTemplateTag=!!preTag.querySelector('.language-ipscss :is(.ipsShortcut, .ipsVarTag, .ipsVarTagFilter, .ipsBlockTag)');if(hasTemplateTag){warning.removeAttribute('hidden');}else{warning.setAttribute('hidden','');}
preTag.remove();}
showOrHideRevertButton(){const originalContent=this.querySelector('#customCSS-saved').innerHTML;const currentContent=this.querySelector('#customCSS').innerHTML;this.querySelectorAll('[data-revert-custom-css]').forEach(revertButton=>{if(currentContent===originalContent){revertButton.setAttribute('hidden','');}else{this.unsavedChanges=true;revertButton.removeAttribute('hidden');}});}
setColorPickerFromComputedStyle(){this.colorPreview.style.setProperty('--_background',this.activeColor.value);let color=window.getComputedStyle(this.colorPreview).getPropertyValue('background-color');if(color.startsWith("color(srgb")){let values=color.replace(/color\(srgb |\)/g,'').split(" ");this.colorPicker.color.set(`rgb(${values[0] * 255} ${values[1] * 255} ${values[2] * 255})`);}else{this.colorPicker.color.set(color);}}
toggleColorPanel(target){let panel=document.getElementById('panel__colorSelector');this.activeColor=this.inputs[target.getAttribute('data-controls')];this.querySelector('[data-active-name]').innerText=target.innerText;if(target.hasAttribute('data-swatch-categories')){panel.setAttribute('data-show-swatches',target.getAttribute('data-swatch-categories'));}else{panel.removeAttribute('data-show-swatches');}
let swatchTab=document.querySelector('[aria-controls="content__colorSelector__swatches_panel"]');if(swatchTab.getAttribute("aria-expanded")==="false"){swatchTab.click()}
if(target.getAttribute('data-color-tool')!=''){panel.setAttribute('data-show-tool',target.getAttribute('data-color-tool'));}
this.querySelector('[data-swatch][aria-current]')?.removeAttribute('aria-current');this.querySelector(`[data-swatch][value='${this.activeColor.value}']`)?.setAttribute('aria-current','true');this.setColorPickerFromComputedStyle();this.colorPickerText.value=`hsl(${this.colorPicker.color.hsl.h} ${this.colorPicker.color.hsl.s}% ${this.colorPicker.color.hsl.l}%)`;}
colorPickerChange(color){cancelAnimationFrame(this.rebuildStyleDebounce);this.rebuildStyleDebounce=requestAnimationFrame(()=>{let newValue=`hsl(${color.hsl.h} ${color.hsl.s}% ${color.hsl.l}%)`,styleContent=`--${this.activeColor.name}: ${newValue};`;this.iframeTempStyleTag.textContent=`:root{ ${styleContent} }`;this.colorPickerText.value=newValue;this.colorPreview.style.setProperty('--_background',newValue);});}
colorPickerContrastPolyfill(color){let relativeLightness=((color.red*299)+(color.green*587)+(color.blue*114))/1000/256*100;return Math.floor(relativeLightness);}
colorPickerDone(color){this.querySelector('[data-swatch][aria-current]')?.removeAttribute('aria-current');let newValue=`hsl(${color.hsl.h} ${color.hsl.s}% ${color.hsl.l}%)`;this.activeColor.value=newValue;this.settings.vars[this.activeColor.name]=this.activeColor.value;if(this.activeColor.matches('[name=light__i-primary], [name=light__i-secondary], [name=dark__i-primary], [name=dark__i-secondary]')){this.inputs[this.activeColor.name+'-relative-l'].value=this.colorPickerContrastPolyfill(color);this.settings.vars[this.activeColor.name+'-relative-l']=this.colorPickerContrastPolyfill(color);}
this.colorPickerText.value=newValue;this.colorPreview.style.setProperty('--_background',newValue);this.toggleRevertButton(this.activeColor);this.unsavedChanges=true;this.buildVariablesStyleTag();}
colorPickerTextBlur(e,target){if(!e.target.value.startsWith('#')&&!e.target.value.startsWith('hsl(')&&!e.target.value.startsWith('rgb(')){window.Debug?.log('Not a supported color. Hex, RGB and HSL are supported.');return;}
this.activeColor.value=e.target.value;this.settings.vars[this.activeColor.name]=this.activeColor.value;this.setColorPickerFromComputedStyle();this.colorPickerDone(this.colorPicker.color);}
swatchClick(event,target){this.querySelector('[data-swatch][aria-current]')?.removeAttribute('aria-current');target.setAttribute('aria-current','true');this.activeColor.value=target.value;this.settings.vars[this.activeColor.name]=this.activeColor.value;this.colorPreview.style.setProperty('--_background',target.value);this.buildVariablesStyleTag();this.toggleRevertButton(this.activeColor);this.setColorPickerFromComputedStyle();this.unsavedChanges=true;}
toggleRevertButton(settingInput){let revertButton=document.querySelector(`[data-revert="${settingInput.name}"]`),hasDefaultValue=settingInput.hasAttribute("data-default");if(revertButton&&hasDefaultValue){revertButton.hidden=(settingInput.value==settingInput.getAttribute("data-default"));}}
revertSetting(event,target){target.hidden=true;let controls=target.getAttribute('data-revert'),defaultValue=this.inputs[controls].getAttribute('data-default'),fieldType=target.parentElement.getAttribute('data-type');if(fieldType==='image'){delete this.settings.images[controls];if(defaultValue.length){const preview=target.parentElement.querySelector('[data-file-preview]');preview.textContent='';preview.innerHTML=`<img src="${defaultValue}" alt="">`;}
this.applyUploadedImageToIframe(controls,defaultValue);}else{this.inputs[controls].value=defaultValue;let checkbox=document.getElementById(`${controls}__checkbox`);if(checkbox){checkbox.checked=(defaultValue==="1")?true:false;}}
this.settings.vars[controls]=defaultValue;if(fieldType!=="image"){this.inputs[controls].dispatchEvent(new Event("change",{bubbles:true}));}
this.buildVariablesStyleTag();this.updateCustomCSS();}
refreshIframe(e){this.settings.vars[e.target.name]=e.target.value;ips.fetch('?app=core&module=system&controller=themeeditor',{method:'post',data:{do:'store',data:this.settings}});this.setAttribute('data-loading',true);setTimeout(()=>{this.removeAttribute('data-loading');},3000);document.getElementById('themeEditorIframe').contentDocument.location.reload(true);}
applyDataAttributes(attr,value){this.iframe.document.documentElement.setAttribute(attr,value);}
iframeSync(){this.iframeStyleTag=this.iframe.document.getElementById('themeEditorStyles');this.iframeTempStyleTag=this.iframe.document.getElementById('themeEditorTempStyles');this.iframeCustomCSS=this.iframe.document.getElementById('themeCustomCSS');this.buildVariablesStyleTag();for(const[setting,value]of Object.entries(this.settings.images)){this.applyUploadedImageToIframe(setting,value);}
this.updateCustomCSS();for(const[setting,value]of Object.entries(this.settings.text)){this.updateLiveText(setting,value);}
for(const[setting,value]of Object.entries(this.settings.headerPositions)){this.repositionHeaderElement(setting,value);}
this.repositionHeaderElementPolyfills();for(const[attr,value]of Object.entries(this.settings.dataAttributes)){this.applyDataAttributes(attr,value);}
this.removeAttribute('data-loading');}
handleEvent(event){const target=event.target.closest(`[data-on-${event.type}]`);if(!target)return;const method=target.getAttribute(`data-on-${event.type}`);if(this[`${method}`]){return this[`${method}`](event,target)}else{(window.Debug||console).warn(`The ${method} method, triggered by [data-on-${event.type}="${method}"] was not found`);}}
handleDragStart(e){e.currentTarget.setAttribute('data-dragging',true);this.firstDrag=e.currentTarget;e.dataTransfer.effectAllowed='move';e.dataTransfer.setData('text/html',e.currentTarget.outerHTML);}
handleDragOver(e){e?.preventDefault();e.dataTransfer.dropEffect='move';return false;}
handleDragEnter(e){e.currentTarget.setAttribute('data-dropzone',true);}
handleDragLeave(e){e.currentTarget.removeAttribute('data-dropzone');}
handleDrop(e){e?.stopPropagation();if(this.firstDrag!=e.currentTarget){this.secondDrag=e.currentTarget;if(document.startViewTransition){document.startViewTransition(()=>this.swapDraggables(this.firstDrag,this.secondDrag))}else{this.swapDraggables(this.firstDrag,this.secondDrag)}}}
handleDragEnd(e){e.currentTarget.removeAttribute('data-dragging');this.dragLabels.forEach(item=>item.removeAttribute('data-dropzone'));}
swapDraggables(origin,destination){let el={fromName:origin.getAttribute('data-name'),fromPos:origin.getAttribute('data-pos'),fromDrag:origin.previousSibling,toName:destination.getAttribute('data-name'),toPos:destination.getAttribute('data-pos'),toDrag:destination.previousSibling}
el.fromDrag.after(destination);el.toDrag.after(origin);origin.setAttribute('data-pos',el.toPos);destination.setAttribute('data-pos',el.fromPos);let input;if(input=this.form.querySelector(`[id='${el.fromName}']`)){input.value=el.toPos;this.settings.vars[input.name]=input.value;this.settings.headerPositions[input.name]=input.value;this.repositionHeaderElement(input.name,input.value);}
if(input=this.form.querySelector(`[id='${el.toName}']`)){input.value=el.fromPos;this.settings.vars[input.name]=input.value;this.settings.headerPositions[input.name]=input.value;this.repositionHeaderElement(input.name,input.value);}
this.repositionHeaderElementPolyfills();this.updateLogoMaxHeightController();this.buildVariablesStyleTag();this.unsavedChanges=true;}
repositionHeaderElement(settingName,settingValue){let name=settingName.replace(/(^set__i-position-)/gi,""),elementOne=this.iframe.document.querySelector(`[data-ips-header-content='${name}']`),destination=this.iframe.document.querySelector(`[data-ips-header-position='${settingValue}']`);if(!elementOne||!destination||destination.contains(elementOne))return;const parentOne=elementOne.closest(`[data-ips-header-position]`);destination.append(elementOne);if(destination.firstElementChild!=destination.lastElementChild){parentOne.append(destination.firstElementChild);}}
repositionHeaderElementPolyfills(){this.iframe.document.querySelectorAll('.ipsHeader__top, .ipsHeader__primary, .ipsHeader__secondary, .ipsHeaderExtra').forEach(h=>{h.hidden=!h.querySelector('[data-ips-header-content]');})}
saveChanges(event,target){this.unsavedChanges=false;}
closeEditor(e,target){ips.utils.cookie.set('themeEditorLocation',document.getElementById('themeEditorIframe').contentDocument.location);if(this.unsavedChanges){e.preventDefault();document.getElementById('toggleCloseConfirmationDialog').click();}}
handleBeforeUnload(e){if(this.unsavedChanges&&!(document.getElementById('closeConfirmationDialog').open)){e.preventDefault();e.returnValue=true;}}}
ips.ui.registerWebComponent("themeEditor",IThemeEditor);Debug.log(`Submitted the web component constructor, IThemeEditor, for ${"themeEditor"}`);})();;
File diff suppressed because it is too large. Load diff
+55 -37
View File
@@ -8,8 +8,8 @@ var template='table.row.loading';if(this.scope.attr('data-dummyLoadingTemplate')
var newRows=[];for(var i=0;i<=rows.length;i++){var rnd=parseInt(Math.random()*(10-1)+1);newRows.push(ips.templates.render(template,{extraClass:this.scope.attr('data-dummyLoadingClass')||'',rnd:rnd}));}
this.scope.find('[data-role="tableRows"]').html(newRows.join(''));};this._basicLoading=function(loading){var rowElem=this.scope.find('[data-role="tableRows"]');if(!rowElem.length){return;}
if(!this._tableOverlay){this._tableOverlay=$('<div/>').addClass('ipsLoading').hide();ips.getContainer().append(this._tableOverlay);}
if(loading){var dims=ips.utils.position.getElemDims(rowElem);var position=ips.utils.position.getElemPosition(rowElem);this._tableOverlay.show().css({left:position.viewportOffset.left+'px',top:position.viewportOffset.top+$(document).scrollTop()+'px',width:dims.width+'px',height:dims.height+'px',position:'absolute',zIndex:ips.ui.zIndex()});rowElem.css({opacity:"0.5"});}else{rowElem.animate({opacity:"1"});this._tableOverlay.hide();}};this.changeSorting=function(e,data){data.originalEvent.preventDefault();if(_.isUndefined(data.selectedItemID)){return;}
var current=this._getSortValue();var menuItem=data.menuElem.find('[data-ipsMenuValue="'+data.selectedItemID+'"]');var sortBy=data.selectedItemID;var sortDirection=current.order;if(menuItem.attr('data-sortDirection')){sortDirection=menuItem.attr('data-sortDirection');}
if(loading){var dims=ips.utils.position.getElemDims(rowElem);var position=ips.utils.position.getElemPosition(rowElem);this._tableOverlay.show().css({left:position.viewportOffset.left+'px',top:position.viewportOffset.top+$(document).scrollTop()+'px',width:dims.width+'px',height:dims.height+'px',position:'absolute',zIndex:ips.ui.zIndex()});rowElem.css({opacity:"0.5"});}else{rowElem.animate({opacity:"1"});this._tableOverlay.hide();}};this.changeSorting=function(e,data=e.detail){data.originalEvent.preventDefault();if(_.isUndefined(data.selectedItemID)){return;}
var current=this._getSortValue();var menuItem=$(data.menuElem).find('[data-ipsMenuValue="'+data.selectedItemID+'"]');var sortBy=data.selectedItemID;var sortDirection=current.order;if(menuItem.attr('data-sortDirection')){sortDirection=menuItem.attr('data-sortDirection');}
this.updateURL({sortby:sortBy,sortdirection:sortDirection,page:1});};this._getSortValue=function(){var by=ips.utils.url.getParam('sortby');var order=ips.utils.url.getParam('sortdirection');return{by:by||'',order:order||''};};this._getFilterValue=function(){var filter=ips.utils.url.getParam('filter');return filter||'';};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.app',{initialize:function(){this.on('click','a[data-confirm],button[data-confirm]',this.confirmSomething);this.on(document,'contentChange',this._checkAndClearAutosave);this.on(document,'contentChange',this.checkOldEmbeds);this.on(document,'contentChange',this.updateExternalLinks);document.addEventListener("ips:colorScheme",this.colorScheme);window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change',this.updatePrefersColorScheme);if(ips.utils.broadcastChannel.enabled){ips.utils.broadcastChannel.channel.addEventListener("message",this.broadcastChannelEvent);}
this.setup();},setup:function(){if(ips.utils.serviceWorker.supported){ips.utils.serviceWorker.registerServiceWorker('front',!_.isUndefined(ips.utils.cookie.get('loggedIn')));}
@@ -27,12 +27,12 @@ ips.controller.register('core.front.core.autoSizeIframe',{_origin:ips.utils.url.
this.on(window,'message',this.receiveMessage);this.on(document,'breakpointChange',this.breakpointChange);this.setup();},getEmbedSrc(){return this.elem.src;},setup(){this._lastDims={height:0,width:0};let cachedDims;if(PREINITIALIZED_DIMS_FLAG in this.elem){Object.assign(this._lastDims,this.elem[PREINITIALIZED_DIMS_FLAG]);}else if(this.getEmbedSrc()&&(cachedDims=ips.utils.db.get('embedDimsCache',this.getEmbedSrc()))&&cachedDims){if(typeof cachedDims?.height==='number'&&cachedDims.height>0){Debug.log(`(EMBED) - Using cached height and width while the embed initializes`);if(typeof cachedDims?.width==='number'&&cachedDims.width>0){this.dims(cachedDims);}else{this.height({height:cachedDims.height});}}}
var iframe=this.scope.get(0);iframe.style.overflow='hidden';this._getBorderAdjustment();if(this.scope.height()>800){this.scope.css({height:'800px'});}
this._iframe=iframe.contentWindow;this._embedId='embed'+parseInt(Math.random()*(10000000000-1)+1);this.scope.attr('data-embedId',this._embedId);if(!window.postMessage||!window.JSON.parse){this.scope.css({height:'400px'});Debug.error("Can't resize embed: "+this._embedId);return;}
this._startReadyTimeout();},_startReadyTimeout(){this._readyTimeout=setInterval(_.bind(function(){this._postMessage('ready');},this),100);setTimeout(_.bind(function(){this._stopReadyTimeout();},this),10000);},_stopReadyTimeout(){if(this._readyTimeout!==null){Debug.log("Stopped posting to embed "+this._embedId);clearInterval(this._readyTimeout);this._readyTimeout=null;}},destruct(){Debug.log('Destruct autoSizeIframe '+this._embedId);this._stopReadyTimeout();this._postMessage('stop');},receiveMessage(e){if(e.originalEvent.origin!==this._origin){return;}
this._intersectionObserver=new IntersectionObserver(entries=>{if(entries.some(entry=>entry.isIntersecting)){this._intersectionObserver.disconnect();this._startReadyTimeout();}},{threshold:0});this._intersectionObserver.observe(iframe);},_startReadyTimeout(){this._readyTimeout=setInterval(_.bind(function(){this._postMessage('ready');},this),100);setTimeout(_.bind(function(){this._stopReadyTimeout();},this),10000);},_stopReadyTimeout(){if(this._readyTimeout!==null){Debug.log("Stopped posting to embed "+this._embedId);clearInterval(this._readyTimeout);this._readyTimeout=null;}},destruct(){Debug.log('Destruct autoSizeIframe '+this._embedId);this._intersectionObserver?.disconnect();this._stopReadyTimeout();this._postMessage('stop');},receiveMessage(e){if(e.originalEvent.origin!==this._origin){return;}
try{const pmData=typeof e.originalEvent.data==='string'?JSON.parse(e.originalEvent.data):e.originalEvent.data;const method=pmData.method;if(pmData.embedId===undefined||pmData.embedId!==this._embedId){return;}
this._stopReadyTimeout();this[method]?.call(this,pmData);}catch(err){Debug.error(err.message);}},_postMessage(method,obj){Debug.log("Posting to iframe "+this._embedId);this._iframe.postMessage(JSON.stringify(_.extend(obj||{},{method:method,embedId:this._embedId})),this._origin);},_getBorderAdjustment(){this._border.vertical=parseInt(this.scope.css('border-top-width'))+parseInt(this.scope.css('border-bottom-width'));this._border.horizontal=parseInt(this.scope.css('border-left-width'))+parseInt(this.scope.css('border-right-width'));},breakpointChange(e,data){this._postMessage('responsiveState',{currentIs:data.curBreakName});},dialog(data){var options=ips.ui.getAcceptedOptions('dialog');var dialogOptions={};_.each(options,function(opt){if(!_.isUndefined(data.options['data-ipsdialog-'+opt.toLowerCase()])){dialogOptions[opt]=data.options['data-ipsdialog-'+opt.toLowerCase()];}});if(_.isUndefined(dialogOptions['url'])){dialogOptions['url']=data.url;}
var dialogRef=ips.ui.dialog.create(dialogOptions);dialogRef.show();},height(data){if(this._lastDims.height!==data.height){this.scope.css({height:parseInt(data.height)+this._border.vertical+'px'});this._lastDims.height=data.height;if(this.getEmbedSrc()){ips.utils.db.set('embedDimsCache',this.getEmbedSrc(),this._lastDims);}}},dims(data){if(parseInt(this._lastDims.height)!==parseInt(data.height)||this._lastDims.width!==data.width){this.scope.css({height:parseInt(data.height)+this._border.vertical+'px',maxWidth:(data.width.toString().indexOf('%')==-1)?parseInt(data.width)+this._border.horizontal+'px':'100%'});this._lastDims.height=data.height;this._lastDims.width=data.width;if(this.getEmbedSrc()){ips.utils.db.set('embedDimsCache',this.getEmbedSrc(),this._lastDims);}}},ok(){this._stopReadyTimeout();this.scope.addClass('ipsEmbed_finishedLoading');this._postMessage('responsiveState',{currentIs:ips.utils.responsive.getCurrentKey()});}});}(jQuery,_));;
;(function(){"use strict";ips.controller.register('core.front.core.colorScheme',{initialize(){this.menu=this.scope[0];this.on(this.menu,'click',this.changeColorScheme);if(!this.menu.querySelector("[aria-current")){this.schemePref=ips.utils.cookie.get('scheme_preference')||document.documentElement.dataset.ipsSchemeDefault;document.querySelectorAll('[data-ips-prefers-color-scheme='+this.schemePref+']').forEach(el=>el.setAttribute('aria-current','true'));}},changeColorScheme(ev){let el=ev.target.closest('[data-controller="core.front.core.colorScheme"] [data-ips-prefers-color-scheme]');if(!el)return;document.dispatchEvent(new CustomEvent("ips:colorScheme",{bubbles:true,detail:{scheme:el.dataset.ipsPrefersColorScheme}}));if(ips.utils.broadcastChannel.enabled){ips.utils.broadcastChannel.channel.postMessage({command:'colorScheme',value:el.dataset.ipsPrefersColorScheme});}}});}());;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.comment',{_quoteData:null,_commentContents:'',_quotingDisabled:false,_quoteTimeout:null,_isEditing:false,_clickHandler:null,_observer:null,initialize:function(){for(const link of this.scope.find('[data-ipsMenu]')){const menuSelector=$(link).attr('href');for(const action of['editComment','deleteComment','approveComment']){this.on(document,'click',`${menuSelector} [data-action="${action}"]`,this[action]);}}
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.comment',{_quoteData:null,_commentContents:'',_quotingDisabled:false,_quoteTimeout:null,_isEditing:false,_clickHandler:null,_observer:null,initialize:function(){for(const link of this.scope.find('[popovertarget^="elcomment_"]')){const menuSelector=$(link).attr('popovertarget');for(const action of['editComment','deleteComment','approveComment']){this.on(document,'click',`#${menuSelector} [data-action="${action}"]`,this[action]);}}
for(const action of['quoteComment','multiQuoteComment','rateReview','cancelEditComment']){this.on('click',`[data-action="${action}"]`,this[action]);}
this.on('submit','form',this.submitEdit);this.on('change','input[type="checkbox"][data-role="moderation"]',this.commentCheckbox);this.elem.addEventListener('ipsCalcQuote',()=>this.inlineQuote())
this.on('click','[data-action="quoteSelection"]',this.quoteSelection);this.on('submitDialog','[data-action="recommendComment"]',this.recommendComment);this.on('click','[data-action="unrecommendComment"]',this.unrecommendComment);this.on('tabChanged',this.tabChanged);this.on('setMultiQuoteEnabled.comment setMultiQuoteDisabled.comment',this.setMultiQuote);this.on('disableQuoting.comment',this.disableQuoting);this.on(document,'getEditFormLoading.comment saveEditCommentLoading.comment '+
@@ -45,16 +45,16 @@ var commentHtml=$('<div>'+data.comment+'</div>').find('[data-controller="core.fr
window.reload();},_checkQuoteStatus:function(){var selectedText=ips.utils.selection.getSelectedText('[data-role="commentContent"]',this.scope.find('[data-role="commentContent"]').parent());var ancestor=ips.utils.selection.getCommonAncestor();if(selectedText.trim()===''){this._hideQuoteTooltip();return;}
if(ancestor&&ancestor.closest('.ipsCode').length){selectedText="<pre class='ipsCode prettyprint'>"+selectedText+"</pre>";}else if(!selectedText.startsWith('<')){selectedText='<p>'+selectedText+'</p>';}
if(this._selectedText===selectedText){return;}
this._selectedText=selectedText;this._showQuoteTooltip();},_showQuoteTooltip:function(){var selection=ips.utils.selection.getSelection();var range=ips.utils.selection.getRange(this.scope.find('[data-role="commentContent"]'));var tooltip=this.scope.find('[data-role="inlineQuoteTooltip"]');var scopeOffset=this.scope.offset();var position={left:0,top:0};if(range===false||!_.isObject(range)||_.isUndefined(range.type)){Debug.log("No selection found");return;}
this._selectedText=selectedText;this._showQuoteTooltip();},_showQuoteTooltip:function(){var selection=ips.utils.selection.getSelection();var range=ips.utils.selection.getRange(this.scope.find('[data-role="commentContent"]'));var tooltip=this.scope.find('[data-role="inlineQuoteTooltip"]');var position={left:0,top:0};if(range===false||!_.isObject(range)||_.isUndefined(range.type)){Debug.log("No selection found");return;}
if(!tooltip.length){this.scope.append(ips.templates.render('core.selection.quote',{direction:'bottom'}));tooltip=this.scope.find('[data-role="inlineQuoteTooltip"]');$(document).on('click dblclick',this._clickHandler);}
if(range.type==='outside'){var boundingBox=range.range.getBoundingClientRect();var offset=this.scope.offset();position.left=boundingBox.left+(boundingBox.width/2)+$(window).scrollLeft()-offset.left;position.top=boundingBox.top+boundingBox.height+$(window).scrollTop()-offset.top;}else{var cloneRange=range.range.cloneRange();var invisibleElement=document.createElement('span');invisibleElement.appendChild(document.createTextNode('\ufeff'));cloneRange.collapse(false);cloneRange.insertNode(invisibleElement);var tmpPosition=ips.utils.position.getElemPosition($(invisibleElement));position.left=tmpPosition.absPos.left-scopeOffset.left;position.top=tmpPosition.absPos.top-scopeOffset.top+25;invisibleElement.parentNode.removeChild(invisibleElement);}
var tooltipSize={width:tooltip.show().outerWidth(),height:tooltip.show().outerHeight()};var leftAdjustment=ips.utils.events.isTouchDevice()?tooltipSize.width:(tooltipSize.width/2);tooltip.css({position:'absolute',left:Math.round(position.left-leftAdjustment)+'px',top:Math.round(position.top)+'px',zIndex:ips.ui.zIndex()});if(!tooltip.is(':visible')){tooltip.hide().fadeIn('fast');}else{tooltip.show();}},_hideQuoteTooltip:function(){$(document).off('click dblclick',this._clickHandler);clearInterval(this._quoteTimeout);this.scope.find('[data-role="inlineQuoteTooltip"]').fadeOut('fast');this._selectedText='';},feedJQ(){if(this.elem.dataset.feedid){const closest=this.elem.closest(`[data-feedid=${this.elem.dataset.feedid}][data-controller*="core.front.core.commentFeed"]`);if(closest){return $(closest);}
if(range.type==='outside'){var boundingBox=range.range.getBoundingClientRect();var offset=this.scope.offset();position.left=boundingBox.left+(boundingBox.width/2)+$(window).scrollLeft()-offset.left;position.top=boundingBox.top+boundingBox.height+$(window).scrollTop()-offset.top;}else{var cloneRange=range.range.cloneRange();var invisibleElement=document.createElement('span');invisibleElement.appendChild(document.createTextNode('\ufeff'));cloneRange.collapse(false);cloneRange.insertNode(invisibleElement);var tmpPosition=ips.utils.position.getElemPosition($(invisibleElement));position.left=tmpPosition.absPos.left;position.top=tmpPosition.absPos.top+25;invisibleElement.parentNode.removeChild(invisibleElement);}
tooltip[0].showPopover();var tooltipSize={width:tooltip.outerWidth(),height:tooltip.outerHeight()};var leftAdjustment=ips.utils.events.isTouchDevice()?tooltipSize.width:(tooltipSize.width/2);tooltip.css({left:Math.round(position.left-leftAdjustment)+'px',top:Math.round(position.top)+'px'});tooltip[0].showPopover();},_hideQuoteTooltip:function(){$(document).off('click dblclick',this._clickHandler);clearInterval(this._quoteTimeout);this.scope.find('[data-role="inlineQuoteTooltip"]')[0]?.hidePopover();this._selectedText='';},feedJQ(){if(this.elem.dataset.feedid){const closest=this.elem.closest(`[data-feedid=${this.elem.dataset.feedid}][data-controller*="core.front.core.commentFeed"]`);if(closest){return $(closest);}
const feed=document.querySelector(`[data-feedid=${this.elem.dataset.feedid}][data-controller*="core.front.core.commentFeed"]`);if(feed){return $(feed);}
Debug.warn(`The comment feed for a comment could not be identified. This can be prevented by ensuring the comment and its feed have macthing data-feedid attributes (comment's feedid: ${this.elem.dataset.feedid})`);}else{Debug.warn(`A comment is missing its data-feedid attribute, so its comment feed could not be identified. This can be prevented by ensuring the comment and its feed have macthing data-feedid attributes`);}
Debug.warn(this.elem);return $(this.elem.closest(`[data-controller*="core.front.core.commentFeed"]`)||this.elem);},quoteSelection:function(e){e.preventDefault();this._getQuoteData();if(this._selectedText){this.feedJQ().trigger('quoteComment.comment',{userid:this._quoteData.userid,username:this._quoteData.username,timestamp:this._quoteData.timestamp,contentapp:this._quoteData.contentapp,contenttype:this._quoteData.contenttype,contentclass:this._quoteData.contentclass,contentid:this._quoteData.contentid,contentcommentid:this._quoteData.contentcommentid,quoteHtml:this._selectedText,citeurl:$(this.elem).get(0).querySelector(".ipsEntry__date[href]")?.getAttribute('href')});}
this._hideQuoteTooltip();},commentCheckbox:function(e){var checked=$(e.currentTarget).is(':checked');this.scope.closest('.js-ipsEntry').toggleClass('ipsEntry--selected',checked);this.scope.closest('.js-ipsEntry').find('label[for='+$(e.currentTarget).attr('id')+']').toggleClass('ipsInput--pseudoChecked',checked);this.feedJQ().trigger('checkedComment.comment',{commentID:this._commentID,actions:$(e.currentTarget).attr('data-actions'),checked:checked});},disableQuoting:function(){this._quotingDisabled=true;this.scope.find('[data-ipsQuote-editor]').remove();},rateReview:function(e){e.preventDefault();var self=this;ips.getAjax()($(e.currentTarget).attr('href')).done(function(response){var content=$("<div>"+response+"</div>");self.scope.html(content.find('[data-controller="core.front.core.comment"]').contents());$(document).trigger('contentChange',[self.scope]);}).fail(function(err){window.location=$(e.currentTarget).attr('href');});},_menu:undefined,getMenu(){if(!this._menu){let activeTabId=this.elem.closest(`[data-commentstype="reviews"]`)?'elReview':'elComment';let commentFeed=this.scope.get(0)?.closest('[data-controller]')
while(commentFeed&&!commentFeed.dataset.controller?.includes('core.front.core.commentFeed')){commentFeed=commentFeed.parentElement?.closest('[data-controller]')}
const menuLink=(commentFeed||document).querySelector('#'+activeTabId+`_${this.scope.get(0)?.dataset['commentid']} [href][data-ipsmenu]`);this._menu=menuLink?document.querySelector(menuLink.getAttribute('href')):null;}
const menuLink=(commentFeed||document).querySelector('#'+activeTabId+`_${this.scope.get(0)?.dataset['commentid']} [popovertarget]`);this._menu=menuLink?document.querySelector('#'+menuLink.getAttribute('popovertarget')):null;}
return this._menu;},_setupShareCommentDialog(){const shareButton=this.getMenu()?.querySelector('[data-role="shareComment"], [data-role="shareReview"]');const shareMenu=shareButton?.dataset.ipsdialogContent?document.querySelector(shareButton.dataset.ipsdialogContent):null;const copyToClipboard=shareMenu?.querySelector('[data-role="shareButton"]');let shared=false;if(window.isSecureContext&&copyToClipboard){copyToClipboard.onclick=e=>e.preventDefault()
copyToClipboard?.addEventListener('pointerdown',async e=>{e.preventDefault();const href=copyToClipboard.getAttribute('href');const cb=async e=>{copyToClipboard.removeEventListener('pointerup',cb)
if(window.navigator?.clipboard?.writeText instanceof Function){e.preventDefault()
@@ -98,7 +98,7 @@ var commentLoading=this.scope.find('[data-role="commentLoading"]');commentLoadin
this.scope.find('[data-role="commentLoading"]').addClass('ipsHide');},getEditFormDone:function(e,data){if(data.commentID!=this._commentID){return;}
const showForm=_.once(()=>{this._isEditing=true;this.scope.find('[data-action="expandTruncate"], [data-role="commentControls"]').hide();this.scope.find('[data-action="editComment"]').parent('li').hide();this.scope.find('[data-role="commentContent"]').html(data.response);this.scope.find('[data-role="commentContent"]').removeClass('ipsRichText');$(document).trigger('contentChange',[this.scope.find('[data-role="commentContent"]')]);});var elemPosition=ips.utils.position.getElemPosition(this.scope);var windowScroll=$(window).scrollTop();var viewHeight=$(window).height();if(elemPosition.absPos.top<windowScroll||elemPosition.absPos.top>(windowScroll+viewHeight)){$('html, body').animate({scrollTop:elemPosition.absPos.top+'px'},function(){showForm();});}else{showForm();}},getEditFormError:function(e,data){if(data.commentID!=this._commentID){return;}
window.location=data.url;},saveEditCommentDone:function(e,data){if(data.commentID!=this._commentID){return;}
ips.ui.editorv5.destruct(this.scope.find('[data-ipseditorv5]'));this._isEditing=false;this.scope.find('[data-role="commentContent"]').replaceWith($('<div>'+data.response+'</div>').find('[data-role="commentContent"]'));this.scope.trigger('refreshContent');this.scope.find('[data-action="expandTruncate"], [data-role="commentControls"]').show();this.scope.find('[data-action="editComment"]').parent('li').show();$(document).trigger('contentChange',[this.scope]);},saveEditCommentError:function(e,data){if(data.commentID!=this._commentID){return;}
ips.ui.editorv5.destruct(this.scope.find('[data-ipseditorv5]'));this._isEditing=false;this.scope.find('[data-role="commentContent"]').replaceWith($('<div>'+data.response+'</div>').find('[data-role="commentContent"]'));this.scope.trigger('refreshContent');this.scope.find('[data-action="expandTruncate"], [data-role="commentControls"]').show();this.scope.find('[data-action="editComment"]').parent('li').show();$(document).trigger('contentChange',[this.scope]);setTimeout(()=>{document.body.dispatchEvent(new CustomEvent('ipsDataLayerSync',{bubbles:true}))},10);},saveEditCommentError:function(e,data){if(data.commentID!=this._commentID){return;}
ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('editCommentError'),});},approveComment:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');this.trigger('approveComment.comment',{url:url,commentID:this._commentID});},approveCommentLoading:function(e,data){if(data.commentID!=this._commentID){return;}
this.scope.find('[data-role="commentControls"]').addClass('i-opacity_4').find('[data-action="approveComment"]').addClass('ipsButton--disabled').text(ips.getString('commentApproving'));},approveCommentDone:function(e,data){if(data.commentID!=this._commentID){return;}
var commentHtml=$('<div>'+data.response+'</div>').find('[data-controller="core.front.core.comment"]').html();this.scope.html(commentHtml).removeClass('ipsModerated').closest('.ipsEntry').removeClass('ipsModerated');$(document).trigger('contentChange',[this.scope]);if(ips.utils.db.isEnabled()){this.scope.find('[data-action="multiQuoteComment"]').removeClass('ipsHide');}
@@ -107,7 +107,7 @@ window.location=data.url;},deleteComment:function(e){e.preventDefault();var url=
var deleteLink=this.scope.find('[data-action="deleteComment"]');var toHide=null;var toShow=null;if(deleteLink.attr('data-hideOnDelete')){toHide=this.scope.find(deleteLink.attr('data-hideOnDelete'));}else{toHide=this.scope.closest('article');}
toHide.animationComplete(function(){toHide.remove();});ips.utils.anim.go('fadeOutDown',toHide);if(deleteLink.attr('data-updateOnDelete')){$(deleteLink.attr('data-updateOnDelete')).text(parseInt($(deleteLink.attr('data-updateOnDelete')).text())-1);}
if(deleteLink.attr('data-showOnDelete')){toShow=this.scope.find(deleteLink.attr('data-showOnDelete'));ips.utils.anim.go('fadeIn',toShow);}
this.feedJQ().trigger('deletedComment.comment',{commentID:this._commentID,response:data.response});},deleteCommentError:function(e,data){if(data.commentID!=this._commentID){return;}
this.feedJQ().trigger('deletedComment.comment',{commentID:this._commentID,response:data.response});setTimeout(()=>document.body.dispatchEvent(new CustomEvent('ipsDataLayerSync',{bubbles:true})),10);},deleteCommentError:function(e,data){if(data.commentID!=this._commentID){return;}
window.location=data.url;},_prepareQuote:function(html){html=$(html);html.find('[data-action="expandTruncate"]').remove();if(![...html.find('> :not(blockquote.ipsQuote)')].some(elem=>elem.matches('img,video,iframe,audio,object,embed')||elem.innerText.trim().length||elem.querySelector(':is(img,video,iframe,audio,object,embed):not(blockquote.ipsQuote *)'))&&html.find('> blockquote.ipsQuote')){const self=this;html.find('> blockquote.ipsQuote').each(function(){let child=this.querySelector(':scope > .ipsQuote_contents')||this;child.innerHTML=self._prepareQuote($(child.innerHTML)).html();});}else{if(html.find('blockquote.ipsQuote')?.parent()?.get(0)?.matches('div')&&html.find('blockquote.ipsQuote').siblings().length===0){var div=html.find('blockquote.ipsQuote').closest('div');div.next('p').find("br:first-child").remove();div.remove();}else{html.find('blockquote.ipsQuote').remove();}
html.find('.ipsStyle_spoilerFancy,.ipsStyle_spoiler').replaceWith(ips.templates.render('core.posts.quotedSpoiler'));html.find("[data-excludequote]").remove();html.find('.ipsQuote_citation').remove();html.find('[data-quote-value]').each(function(){$(this).replaceWith('<p>'+$(this).attr('data-quote-value')+'</p>');});}
return html;},_getQuoteData:function(){if(!this._quoteData){try{this._quoteData=$.parseJSON(this.scope.attr('data-quoteData'));return this._quoteData;}catch(err){Debug.log("Couldn't parse quote data");return{};}}
@@ -116,20 +116,20 @@ function clearMouseUpResolvers(){mouseState='up'
const resolves=[...mouseUpResolvers]
mouseUpResolvers.clear()
resolves.forEach(resolve=>resolve())}
document.addEventListener('mousedown',()=>mouseState='down',{capture:true})
document.addEventListener('touchstart',()=>mouseState='down',{capture:true})
document.addEventListener('touchend',clearMouseUpResolvers,{capture:true})
document.addEventListener('mouseup',clearMouseUpResolvers,{capture:true})
document.addEventListener('selectionchange',_.debounce(()=>{const selection=document.getSelection();for(let i=0;i<selection.rangeCount;i++){const range=selection.getRangeAt(i);const quoteBox=range.commonAncestorContainer instanceof Text?range.commonAncestorContainer.parentElement.closest('[data-role="commentContent"]'):range.commonAncestorContainer.closest('[data-role="commentContent"]')
document.addEventListener('pointerdown',()=>mouseState='down',{capture:true})
document.addEventListener('pointerup',clearMouseUpResolvers,{capture:true})
document.addEventListener('contextmenu',clearMouseUpResolvers,{capture:true})
document.addEventListener('selectionchange',_.throttle(()=>{const selection=document.getSelection();for(let i=0;i<selection.rangeCount;i++){const range=selection.getRangeAt(i);const quoteBox=range.commonAncestorContainer instanceof Text?range.commonAncestorContainer.parentElement.closest('[data-role="commentContent"]'):range.commonAncestorContainer.closest('[data-role="commentContent"]')
if(quoteBox instanceof Element){mouseUp().then(()=>quoteBox.dispatchEvent(new CustomEvent('ipsCalcQuote',{bubbles:true})))
break;}}},400))}(jQuery,_));;
break;}}},1000,{leading:true,trailing:true}))}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.commentFeed',{_overlay:null,_commentFeedID:0,_newRepliesFlash:null,_maximumMultiQuote:50,_pageParam:'page',_seoPagination:false,_urlParams:{},_baseURL:'',_doneInitialState:false,_initialURL:'',_pollingEnabled:true,_pollingActive:false,_pollingPaused:false,_initialPoll:10000,_currentPoll:10000,_decay:20000,_maxInterval:(30*60)*1000,_pollingTimeout:null,_pollAjax:null,_pollOnUnpaused:false,_notification:null,_lastSeenTotal:0,initialize(){this._containerID=this.scope.closest('[data-commentsContainer]').length?this.scope.closest('[data-commentsContainer]').attr('data-commentsContainer'):this.scope.identify().attr('id');this.on('submit','[data-role="replyArea"]',this.quickReply);this.on('quoteComment.comment',this.quoteComment);this.on('addMultiQuote.comment',this.addMultiQuote);this.on('removeMultiQuote.comment deleteComment.comment',this.removeMultiQuote);this.on('click','[data-action="filterClick"]',this.filterClick);this.on('menuItemSelected','[data-role="signatureOptions"]',this.signatureOptions);this.on('editorCompatibility',this.editorCompatibility);this.on('checkedComment.comment',this.checkedComment);if(this.elem?.dataset.pageParam){this._pageParam=this.elem.dataset.pageParam;}
this._boundMQ=_.bind(this.doMultiQuote,this);this._boundCMQ=_.bind(this.clearMultiQuote,this);$(document).on('click','[data-role="multiQuote_'+this._containerID+'"]',this._boundMQ);$(document).on('click','[data-action="clearQuoted_'+this._containerID+'"]',this._boundCMQ);$(document).on('moderationSubmitted',this.clearLocalStorage);this.on('paginationClicked paginationJump',this.paginationClick);this.on(document,'addToCommentFeed',this.addToCommentFeed);this.on('deletedComment.comment',this.deletedComment);this.on(document,'click','[data-action="loadNewPosts"]',this.loadNewPosts);this.on(window,'historychange',this.stateChange);this.on(document,"socket.new_comment",this.handleSocketCommentTrigger);this.setup();},setup:function(){const replyForm=this.scope.find('[data-role="replyArea"] form');this._commentFeedID=this.scope.attr('data-feedID');this._urlParams=this._getUrlParams();this._baseURL=this.scope.attr('data-baseURL');this._initialURL=window.location.href;this._currentPage=ips.utils.url.getPageNumber(this._pageParam);this._urlParams[this._pageParam]=this._currentPage;if(this._baseURL.match(/\?[^?]+$/)){this._baseURL+='&';}else{this._baseURL+='?';}
if(replyForm.attr('data-noAjax')){this._pollingEnabled=false;}
if(!('commentFeed'in ips.utils.history.getState())){this._updateState({})
ips.utils.history.replaceState(this.historyState,'commentFeed',window.location.href)}
if(!_.isUndefined(this.scope.attr('data-lastPage'))&&this._pollingEnabled){this._startPolling();}
$(document).ready(()=>{this._setUpMultiQuote();this._findCheckedComments();});this.on('updateTimestamps',this._updateTimestamps);for(const ev of['ips:editorUpdated','ips:editorAfterInit']){this.elem.addEventListener(ev,_.debounce(e=>{const{elem,instance}=e.detail;const submit=elem.closest(CSS.supports('selector(a:has(b))')?'form:has(input[type="submit"],button[type="submit"])':'form').querySelectorAll(':is(button, input)[type="submit"]');if(!submit.length){return;}
$(document).ready(()=>{this._setUpMultiQuote();this._findCheckedComments();});if(ips.getSetting('relativeDates')){this.on('updateTimestamps',this._updateTimestamps);}
for(const ev of['ips:editorUpdated','ips:editorAfterInit']){this.elem.addEventListener(ev,_.debounce(e=>{const{elem,instance}=e.detail;const submit=elem.closest(CSS.supports('selector(a:has(b))')?'form:has(input[type="submit"],button[type="submit"])':'form').querySelectorAll(':is(button, input)[type="submit"]');if(!submit.length){return;}
function nodeHasContent(node){if(node.textContent?.trim()?.length){return true;}
if(node.isAtom&&!node.isText){return true;}
if(node.children&&Symbol.iterator in node.children){for(const child of node.children){if(nodeHasContent(child)){return true;}}}
@@ -164,7 +164,10 @@ ips.utils.history.pushState(this.historyState,'commentFeed',newUrl);this._update
Object.assign(this.historyState,{controller:this.controllerID,feedID:this._commentFeedID})},_getURL:function(){const urlObj=new URL(this._baseURL);const skipParams=new Set(['controller','feedID','bypassState']);const params={};for(const param in this._urlParams){if(this._urlParams[param]&&!skipParams.has(param)){params[param]=this._urlParams[param].toString();}}
urlObj.updateSearchParams({params});return urlObj.toString();},editorCompatibility:function(e,data){if(!data.compatible){this.triggerOn('core.front.core.comment','disableQuoting.comment');}},checkedComment:function(e,data){var dataStore=ips.utils.db.get('moderation',this._commentFeedID)||{};if(data.checked){if(_.isUndefined(dataStore[data.commentID])){dataStore[data.commentID]=data.actions;}}else{delete dataStore[data.commentID];}
if(_.size(dataStore)){ips.utils.db.set('moderation',this._commentFeedID,dataStore,undefined,(Date.now()/1000)+86400);}else{ips.utils.db.remove('moderation',this._commentFeedID);}},_findCheckedComments:function(){if(!this.scope.find('input[type="checkbox"]').length){return;}
var dataStore=ips.utils.db.get('moderation',this._commentFeedID)||{};var self=this;var pageAction=this.scope.find('[data-ipsPageAction]');if(_.size(dataStore)){var sizeOtherPage=0;_.each(dataStore,function(val,key){if(self.scope.find('[data-commentID="'+key+'"]').length){self.scope.find('[data-commentID="'+key+'"] input[type="checkbox"][data-role="moderation"]').attr('checked',true).trigger('change');}else{sizeOtherPage++;pageAction.trigger('addManualItem.pageAction',{id:'multimod['+key+']',actions:val});}});if(this.scope.find('[data-ipsAutoCheck]')){this.scope.find('[data-ipsAutoCheck]').trigger('setInitialCount.autoCheck',{count:sizeOtherPage});}}},signatureOptions:function(e,data){data.originalEvent.preventDefault();if(data.selectedItemID=='oneSignature'){this._ignoreSingleSignature($(e.currentTarget).attr('data-memberID'));}else{this._ignoreAllSignatures();}},_ignoreAllSignatures:function(){var self=this;var url=ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=settings&do=toggleSigs';var signatures=this.scope.find('[data-role="memberSignature"]');signatures.slideUp();ips.getAjax()(url).done(function(response){ips.ui.flashMsg.show(ips.getString('signatures_hidden'));signatures.remove();}).fail(function(){signatures.show();ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('signatures_error'),callbacks:{}});});},_ignoreSingleSignature:function(memberID){var url=ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ignore&do=ignoreType&type=signatures';var signatures=this.scope.find('[data-role="memberSignature"]').find('[data-memberID="'+memberID+'"]').closest('[data-role="memberSignature"]');signatures.slideUp();ips.getAjax()(url,{data:{member_id:parseInt(memberID)}}).done(function(response){ips.ui.flashMsg.show(ips.getString('single_signature_hidden'));signatures.remove();}).fail(function(){signatures.show();ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('single_signature_error'),callbacks:{}});});},filterClick:function(e){e.preventDefault();var urlObj=ips.utils.url.getURIObject($(e.target).attr('href'));var queryKey=urlObj.queryKey;this._updateURL(queryKey);},quoteComment:function(e,data){if(this.scope.find('[data-role="replyArea"] [data-ipsEditorv5]').length){ips.ui.editorv5.getObjWithInit(this.scope.find('[data-role="replyArea"] [data-ipsEditorv5]'),function(editor){editor.insertQuotes([data]);});}},windowBlur:function(e){if(this._pollingEnabled){Debug.log('Window blurred, pausing polling...');this._pollingPaused=true;}},windowFocus:function(e){if(this._pollingEnabled&&this._pollingPaused){Debug.log('Window focused...');this._pollingPaused=false;if(this._pollOnUnpaused){this._pollOnUnpaused=false;this.pollForNewReplies();}}},handleSocketCommentTrigger:function(){if(!_.isUndefined(this.scope.attr('data-lastPage'))&&this._pollingEnabled){this.pollForNewReplies();}},_startPolling:function(){if(ips.utils.sockets.enabled()&&ips.utils.sockets.connected()){return;}
var dataStore=ips.utils.db.get('moderation',this._commentFeedID)||{};var self=this;var pageAction=this.scope.find('[data-ipsPageAction]');if(_.size(dataStore)){var sizeOtherPage=0;_.each(dataStore,function(val,key){if(self.scope.find('[data-commentID="'+key+'"]').length){self.scope.find('[data-commentID="'+key+'"] input[type="checkbox"][data-role="moderation"]').attr('checked',true).trigger('change');}else{sizeOtherPage++;pageAction.trigger('addManualItem.pageAction',{id:'multimod['+key+']',actions:val});}});if(this.scope.find('[data-ipsAutoCheck]')){this.scope.find('[data-ipsAutoCheck]').trigger('setInitialCount.autoCheck',{count:sizeOtherPage});}}},signatureOptions:function(e,data=e.detail){data.originalEvent.preventDefault();if(data.selectedItemID=='oneSignature'){this._ignoreSingleSignature($(e.currentTarget).attr('data-memberID'));}else{this._ignoreAllSignatures();}},_ignoreAllSignatures:function(){var self=this;var url=ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=settings&do=toggleSigs';var signatures=this.scope.find('[data-role="memberSignature"]');signatures.slideUp();ips.getAjax()(url).done(function(response){ips.ui.flashMsg.show(ips.getString('signatures_hidden'));signatures.remove();}).fail(function(){signatures.show();ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('signatures_error'),callbacks:{}});});},_ignoreSingleSignature:function(memberID){var url=ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ignore&do=ignoreType&type=signatures';var signatures=this.scope.find('[data-role="memberSignature"]').find('[data-memberID="'+memberID+'"]').closest('[data-role="memberSignature"]');signatures.slideUp();ips.getAjax()(url,{data:{member_id:parseInt(memberID)}}).done(function(response){ips.ui.flashMsg.show(ips.getString('single_signature_hidden'));signatures.remove();}).fail(function(){signatures.show();ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('single_signature_error'),callbacks:{}});});},filterClick:function(e){e.preventDefault();var urlObj=ips.utils.url.getURIObject($(e.target).attr('href'));var queryKey=urlObj.queryKey;this._updateURL(queryKey);},quoteComment:function(e,data){if(this.scope.find('[data-role="replyArea"] [data-ipsEditorv5]').length){ips.ui.editorv5.getObjWithInit(this.scope.find('[data-role="replyArea"] [data-ipsEditorv5]'),function(editor){editor.insertQuotes([data]);});}},windowBlur:function(e){if(this._pollingEnabled){Debug.log('Window blurred, pausing polling...');this._pollingPaused=true;}},windowFocus:function(e){if(this._pollingEnabled&&this._pollingPaused){Debug.log('Window focused...');this._pollingPaused=false;if(this._pollOnUnpaused){this._pollOnUnpaused=false;this.pollForNewReplies();}}},handleSocketCommentTrigger:function(){if(!_.isUndefined(this.scope.attr('data-lastPage'))&&this._pollingEnabled){this.pollForNewReplies();}},_startPolling:function(){if(ips.utils.sockets.enabled()&&ips.utils.sockets.connected()){if(ips.getSetting('relativeDates')){if(this._timestampTimeout){clearTimeout(this._timestampTimeout);}
Debug.log('Setting interval to poll for relative dates');this._timestampTimeout=setTimeout(()=>{this._updateTimestamps();if((this._currentPoll+this._decay)<this._maxInterval){this._currentPoll+=this._decay;}else{this._currentPoll=this._maxInterval;}
this._startPolling();},this._currentPoll);}
return;}
this._pollingActive=true;Debug.log('Starting polling with interval '+(this._currentPoll/1000)+'s');this._pollingTimeout=setTimeout(()=>{this.pollForNewReplies();},this._currentPoll);},_stopPolling:function(){this._pollingActive=false;if(this._pollingTimeout){clearTimeout(this._pollingTimeout);}
Debug.log("Stopped polling for new replies in comment feed.");},pollForNewReplies(){const replyForm=this.scope.find('[data-role="replyArea"] form');const commentsOnThisPage=document.querySelectorAll(`[data-feedid="${this.elem.dataset.feedid}"] [data-commentid]`);if(!commentsOnThisPage.length){return;}
const lastSeenId=this._getLastSeenID($(commentsOnThisPage));const type=$(commentsOnThisPage[commentsOnThisPage.length-1]).attr('data-commentType');if(type.match(/-review$/)){Debug.log("Polling disabled for reviews");this._stopPolling();return;}
@@ -172,7 +175,7 @@ if(this._pollingPaused){Debug.log('Window blurred, delaying poll until focused..
if(this._pollAjax&&this._pollAjax.abort!==undefined){this._pollAjax.abort();}
this._pollAjax=ips.getAjax();this._pollAjax(replyForm.attr('action'),{dataType:'json',data:'do=checkForNewReplies&type=count&lastSeenID='+lastSeenId+'&csrfKey='+ips.getSetting('csrfKey'),type:'post'}).done(response=>{if(response.error&&response.error==='auto_polling_disabled'){this._stopPolling();return;}
if(parseInt(response.count)>0){this._currentPoll=this._initialPoll;if(this.getCurrentCommentPageCount()<parseInt(response.perPage)){this._importNewReplies(false);}else{this._buildFlashMsg(response);if(parseInt(response.totalCount)>parseInt(this._lastSeenTotal)){this._buildNotifications(response);this._lastSeenTotal=parseInt(response.totalCount);}}}else{if((this._currentPoll+this._decay)<this._maxInterval){this._currentPoll+=this._decay;}else{this._currentPoll=this._maxInterval;}}
if(this.scope.attr('data-lastPage')!==undefined){this._startPolling();}});this._updateTimestamps();},getCurrentCommentPageCount(){if(this.scope){return $(this.scope).get(0).querySelectorAll(`[data-commentid]`).length}else{return 0}},_buildFlashMsg(response){const spaceForMore=parseInt(response.perPage)-this.getCurrentCommentPageCount();let html;if(parseInt(response.count)>spaceForMore){html=ips.templates.render('core.postNotify.multipleSpillOver',{text:ips.pluralize(ips.getString('newPostMultipleSpillOver'),[response.totalNewCount]),canLoadNew:(spaceForMore>0),showFirstX:ips.pluralize(ips.getString('showFirstX'),[spaceForMore]),spillOverUrl:response.spillOverUrl});}else if(parseInt(response.count)===1&&!_.isUndefined(response.photo)&&!_.isUndefined(response.name)){html=ips.templates.render('core.postNotify.single',{photo:response.photo,text:ips.getString('newPostSingle',{name:response.name})});}else{html=ips.templates.render('core.postNotify.multiple',{text:ips.pluralize(ips.getString('newPostMultiple'),[response.count])});}
if(this.scope.attr('data-lastPage')!==undefined){this._startPolling();}});if(ips.getSetting('relativeDates')){this._updateTimestamps();}},getCurrentCommentPageCount(){if(this.scope){return $(this.scope).get(0).querySelectorAll(`[data-commentid]`).length}else{return 0}},_buildFlashMsg(response){const spaceForMore=parseInt(response.perPage)-this.getCurrentCommentPageCount();let html;if(parseInt(response.count)>spaceForMore){html=ips.templates.render('core.postNotify.multipleSpillOver',{text:ips.pluralize(ips.getString('newPostMultipleSpillOver'),[response.totalNewCount]),canLoadNew:(spaceForMore>0),showFirstX:ips.pluralize(ips.getString('showFirstX'),[spaceForMore]),spillOverUrl:response.spillOverUrl});}else if(parseInt(response.count)===1&&!_.isUndefined(response.photo)&&!_.isUndefined(response.name)){html=ips.templates.render('core.postNotify.single',{photo:response.photo,text:ips.getString('newPostSingle',{name:response.name})});}else{html=ips.templates.render('core.postNotify.multiple',{text:ips.pluralize(ips.getString('newPostMultiple'),[response.count])});}
if($('#elFlashMessage').is(':visible')&&$('#elFlashMessage').find('[data-role="newPostNotification"]').length){$('#elFlashMessage').find('[data-role="newPostNotification"]').replaceWith(html);}else{ips.ui.flashMsg.show(html,{sticky:true,position:'bottom',extraClasses:'cPostFlash',dismissable:()=>this._stopPolling(),escape:false});}},_buildNotifications(response){const hiddenProp=ips.utils.events.getVisibilityProp();if(hiddenProp===undefined||!document[hiddenProp]||!ips.utils.notification.hasPermission()){return;}
const notifyData={onClick:e=>{try{window.focus();}catch(err){}
this.loadNewPosts(e);}};if(this._notification){this._notification.hide();}
@@ -199,7 +202,8 @@ const id=parseInt(actualContent?.querySelector(`[data-commentid]`)?.dataset.comm
if(data.scrollToItem&&(newItemTop<windowScroll||newItemTop>(windowScroll+viewHeight))){$('html, body').animate({scrollTop:newItemTop+'px'},'fast',function(){setTimeout(_showComment,100);});}else{_showComment();}
if(ips.utils.db.isEnabled()){const buttons=comment.find('[data-action="multiQuoteComment"]');buttons.hide().removeClass('ipsHide');ips.utils.anim.go('fadeIn',buttons);}}}else{Debug.log(`core.front.core.commentFeed:addToCommentFeed() - Invalid content provided to addToCommentFeed. The data.content property is supposed to contain HTML with an element that has the \`js-ipsEntry\` class. This may be expected, as in the case of posts held for approval.`);if(Debug.isEnabled()){console.log(data);}}
if(!('resetEditor'in data)||data.resetEditor!==false){this.scope.find('[data-role="replyArea"] [data-ipsEditorv5]').data('_editor').reset();}
this._updateCount(data.totalItems);this._updateTimestamps();$(document).trigger('contentChange',[this.scope]);},deletedComment:function(e,data){data=$.parseJSON(data.response);var self=this;if(data.type=='redirect'){window.location=data.url;}
this._updateCount(data.totalItems);if(ips.getSetting('relativeDates')){this._updateTimestamps();}
$(document).trigger('contentChange',[this.scope]);},deletedComment:function(e,data){data=$.parseJSON(data.response);var self=this;if(data.type=='redirect'){window.location=data.url;}
else{this._updateCount(data.total);}},_updateCount:function(newTotal){if(this.scope.find('[data-role="comment_count"]')){var langString='js_num_comments';if(this.scope.find('[data-role="comment_count"]').attr('data-commentCountString')){langString=this.scope.find('[data-role="comment_count"]').attr('data-commentCountString');}
this.scope.find('[data-role="comment_count"]').text(ips.pluralize(ips.getString(langString),newTotal));}},doMultiQuote:function(e){var mqData=this._getMultiQuoteData();var replyArea=this.scope.find('[data-role="replyArea"]');var output=[];var self=this;if(!_.size(mqData)||!replyArea.is(':visible')){return;}
_.each(mqData,function(value){output.push(value);});ips.ui.editorv5.getObjWithInit(this.scope.find('[data-role="replyArea"] [data-ipsEditorv5]'),function(editor){editor.insertQuotes(output);});this._removeAllMultiQuoted();},clearMultiQuote:function(e){e.preventDefault();this._removeAllMultiQuoted();},_removeAllMultiQuoted:function(){var mqData=this._getMultiQuoteData();var self=this;ips.utils.db.set('mq','data',{});this._buildMultiQuote(0);if(!_.size(mqData)){return;}
@@ -208,7 +212,8 @@ mqData[key]=data;ips.utils.db.set('mq','data',mqData);this._buildMultiQuote(_.si
return mqData;},_setUpMultiQuote:function(){if(!ips.utils.db.isEnabled()){return;}
var buttons=this.scope.find('[data-action="multiQuoteComment"]');var self=this;var mqData=this._getMultiQuoteData();buttons.show();if(_.size(mqData)){this._buildMultiQuote(_.size(mqData));_.each(mqData,function(value){self.triggerOn('core.front.core.comment','setMultiQuoteEnabled.comment',{contentapp:value.contentapp,contenttype:value.contenttype,contentcommentid:value.contentcommentid});});}},_buildMultiQuote:function(count){var quoterElem=$('#ipsMultiQuoter');if(!quoterElem.length&&count){ips.getContainer().append(ips.templates.render('core.posts.multiQuoter',{count:ips.getString('multiquote_count',{count:ips.pluralize(ips.getString('multiquote_count_plural'),[count])}),commentFeedId:this._containerID}));ips.utils.anim.go('zoomIn fast',$('#ipsMultiQuoter'));}else{if(quoterElem.attr('data-commentsContainer')!==this._containerID){quoterElem.attr('data-commentsContainer',this._containerID).find('[data-role^="multiQuote_"]').attr('data-role','multiQuote_'+this._containerID).end().find('[data-action^="clearQuoted_"]').attr('data-action','clearQuoted_'+this._containerID);}
quoterElem.find('[data-role="quotingTotal"]').text(ips.pluralize(ips.getString('multiquote_count_plural'),[count]));if(count&&quoterElem.is(':visible')){ips.utils.anim.go('pulseOnce fast',quoterElem);}else if(count&&!quoterElem.is(':visible')){ips.utils.anim.go('zoomIn fast',quoterElem);}else{ips.utils.anim.go('zoomOut fast',quoterElem);}}},_getLastSeenID:function(commentsOnThisPage){var commentFeed=this.scope.find('[data-role="commentFeed"]');var maxComment=_.max(commentsOnThisPage,function(comment){return parseInt($(comment).attr('data-commentid'));});var max=$(maxComment).attr('data-commentid');if(commentFeed.attr('data-topicAnswerID')&&parseInt(commentFeed.attr('data-topicAnswerID'))>max){max=parseInt(commentFeed.attr('data-topicAnswerID'));}
Debug.log("Max comment ID is "+max);return max;},async _updateTimestamps(){Debug.log('Updating the comment feed timestamps')
Debug.log("Max comment ID is "+max);return max;},async _updateTimestamps(){if(!ips.getSetting('relativeDates')){return;}
Debug.log('Updating the comment feed timestamps')
const timestampMap=new Map();const roots=new Set([this.elem]);if(this.elem.dataset.feedid){for(const el of document.querySelectorAll(`[data-feedid="${this.elem.dataset.feedid}"]`)){roots.add(el);}}
roots.forEach(root=>{for(const el of root.querySelectorAll('time.ipsTime[datetime]:not(.ipsTime .ipsTime, time time)')){if(OLD_TIME_ELEMENTS.has(el)){continue;}
if(el instanceof HTMLTimeElement){const unixts=Math.round((new Date(el.dateTime)).getTime()/1000);if(unixts<=Math.round(Date.now()/1000)-86400){OLD_TIME_ELEMENTS.add(el);continue;}
@@ -222,7 +227,7 @@ parsedResults[ts]=timeEl;}}}}
for(const[timeEl,timeStamp]of timestampMap.entries()){const key="time_"+timeStamp;if(key in parsedResults){timeEl.innerHTML=parsedResults[key].innerHTML;timeEl.dataset.short=parsedResults[key].dataset.short;}else{Debug.warn(`Didn't get a formatted time for the timestamp ${timeStamp}.`)}}}});const OLD_TIME_ELEMENTS=new WeakSet();}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.commentsWrapper',{initialize:function(){this.on(document,'addToCommentFeed',this.addToCommentFeed);this.on('deletedComment.comment',this.deletedComment);},addToCommentFeed:function(e,data){this._updateCount($(e.target).attr('data-commentsType'),data.totalItems);},deletedComment:function(e,data){try{var newTotal=$.parseJSON(data.response).total;}catch(err){var newTotal=0;}
this._updateCount($(e.target).closest('[data-commentsType]').attr('data-commentsType'),newTotal);},_updateCount:function(type,number){var langString='js_num_'+type;var elem=$('#'+$(this.scope).attr('data-tabsId')+'_tab_'+type);elem.text(ips.pluralize(ips.getString(langString),number));}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.ignoredComments',{initialize:function(){this.on('menuItemSelected','[data-action="ignoreOptions"]',this.commentIgnore);},commentIgnore:function(e,data){switch(data.selectedItemID){case'showPost':data.originalEvent.preventDefault();this._showHiddenPost(e,data);break;case'stopIgnoring':data.originalEvent.preventDefault();this._stopIgnoringFromComment(e,data);break;}},_showHiddenPost:function(e,data){var ignoreRow=$(data.triggerElem).closest('.ipsEntry--ignored');var commentID=ignoreRow.attr('data-ignoreCommentID');var comment=this.scope.find('#'+commentID);ignoreRow.remove();comment.removeClass('ipsHide');},_stopIgnoringFromComment:function(e,data){var ignoreRow=$(data.triggerElem).closest('.ipsEntry--ignored');var userID=ignoreRow.attr('data-ignoreUserID');var self=this;var posts=this.scope.find('[data-ignoreUserID="'+userID+'"]');posts.each(function(){self.scope.find('#'+$(this).attr('data-ignoreCommentID')).removeClass('ipsHide');$(this).remove();});var url=ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ignore&do=ignoreType&type=topics&off=1';ips.getAjax()(url,{data:{member_id:parseInt(userID)}}).done(function(){ips.ui.flashMsg.show(ips.getString('ignore_prefs_updated'));}).fail(function(){window.location=ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ignore&do=ignoreType&off=1type=topics&member_id='+userID;});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.ignoredComments',{initialize:function(){this.on('menuItemSelected','[data-action="ignoreOptions"]',this.commentIgnore);},commentIgnore:function(e,data=e.detail){switch(data.selectedItemID){case'showPost':data.originalEvent.preventDefault();this._showHiddenPost(e,data);break;case'stopIgnoring':data.originalEvent.preventDefault();this._stopIgnoringFromComment(e,data);break;}},_showHiddenPost:function(e,data){var ignoreRow=$(data.triggerElem).closest('.ipsEntry--ignored');var commentID=ignoreRow.attr('data-ignoreCommentID');var comment=this.scope.find('#'+commentID);ignoreRow.remove();comment.removeClass('ipsHide');},_stopIgnoringFromComment:function(e,data){var ignoreRow=$(data.triggerElem).closest('.ipsEntry--ignored');var userID=ignoreRow.attr('data-ignoreUserID');var self=this;var posts=this.scope.find('[data-ignoreUserID="'+userID+'"]');posts.each(function(){self.scope.find('#'+$(this).attr('data-ignoreCommentID')).removeClass('ipsHide');$(this).remove();});var url=ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ignore&do=ignoreType&type=topics&off=1';ips.getAjax()(url,{data:{member_id:parseInt(userID)}}).done(function(){ips.ui.flashMsg.show(ips.getString('ignore_prefs_updated'));}).fail(function(){window.location=ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ignore&do=ignoreType&off=1type=topics&member_id='+userID;});}});}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register('core.front.core.instantNotifications',{_pollTimeout:60,_windowInactivePoll:0,_pollMultiplier:1,_messagesEnabled:null,_ajaxObj:null,_debugPolling:true,_browserNotifications:{},_paused:false,_interval:null,_usingRealtime:false,initialize(){this.on(document,ips.utils.events.getVisibilityEvent(),this.windowVisibilityChange);this.on(window,'storage',this.storageChange);this.setup();},setup(){if(!ips.utils.db.isEnabled()||!(window.JSON?.parse instanceof Function)){Debug.warn("Sorry, your browser doesn't support localStorage or JSON so we can't load instant notifications for you.");return;}
if(ips.utils.sockets.enabled()){if(ips.utils.sockets.connected()){this._useRealtime();}else{this.on(document,'socket.connected',this._useRealtime)}}
this.on(document,`socket.notifications_available`,()=>{Debug.log('Notifications: fetching the latest notification counts');this._useRealtime();this._doAjaxRequest(this._getCurrentCounts());})
@@ -252,20 +257,32 @@ if($('#elFlashMessage').is(':visible')&&$('#elFlashMessage').find('[data-role="n
if(this._messagesEnabled){if(parseInt(newData.messages)!==oldData.messages){this._updateIcon('inbox',newData.messages);this.scope.trigger('clearUserbarCache',{type:'inbox'});}
notifyData.messages=parseInt(newData.messages);}},_updateIcon(type,count){const icon=this._getIcon(type);icon.attr('data-currentCount',count).text(count);if(parseInt(count)){ips.utils.anim.go((!icon.is(':visible'))?'zoomIn':'pulseOnce',$(icon).each(function(){this.ipsShow()}));}else{icon.fadeOut();}},_getIcon(type){return $('body').find('[data-notificationType="'+type+'"]');},_getCurrentCounts(){const messages=this.scope.find('[data-notificationType="inbox"]');const notifications=this.scope.find('[data-notificationType="notify"]');return{notifications:parseInt(notifications.attr('data-currentCount')),messages:(messages.length)?parseInt(messages.attr('data-currentCount')):null};},_stopPolling(){Debug.info("Stopping instant notification polling");clearInterval(this._interval);this._paused=true;}});}(jQuery,_));;
;(function($,_,undefined){"use strict";const IMAGE_EXTENSIONS=new Set(['gif','jpeg','jpe','jpg','png','svg','webp','avif'])
ips.controller.register('core.front.core.lightboxedImages',{_random:null,initialize:function(){var self=this;this.on('initializeImages',this.refreshContent);this.on('refreshContent',this.refreshContent);this.on(document,'imageRotated',function(e,data){var attachment=$(self.scope).find('.ipsAttachLink_image img[data-fileId='+data.fileId+']');self._updateAttachmentImage(attachment,data);});this.setup();},setup:function(){this._random='g'+(Math.round(Math.random()*100000));this._initializeAttachments();this._initializeImages();},refreshContent:function(e){Debug.log("Refreshing content in lightboxedImages");this.scope.removeAttr('data-loaded');this._initializeAttachments();this._initializeImages();e.stopPropagation();},_initializeAttachments:function(){var fileIDsToFetch={};var self=this;var attachments=this.scope.find('[data-fileid]').not(function(idx,elem){var elem=$(elem);return elem.is('source, video')||elem.find('source, video').length;});if(!attachments.length){return;}
attachments.each(function(){var attachment=$(this);if(!_.isUndefined(attachment.attr('data-loaded'))){return;}
if(!(attachment.is('img, .ipsAttachLink_image'))){var parent=attachment.parent();var clone=parent.clone();clone.children().remove();clone.text(clone.text().replace(/\s/g,''));if(!clone.text().length&&attachment.parentsUntil(this.scope,'li').length===0){attachment.addClass('ipsAttachLink_block');if(attachment.children().length){return;}
var title=attachment.text();attachment.html(ips.templates.render('core.attachments.attachmentPreview',{title:title}));}else{attachment.addClass('ipsAttachLink_inline');attachment.attr('title',ips.getString('attachmentPending'));attachment.attr('data-ipstooltip',true);}}
fileIDsToFetch[attachment.attr('data-fileid')]=true;});if(!_.size(fileIDsToFetch)){return;}
ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ajax&do=attachmentInfo',{dataType:'json',data:{attachIDs:fileIDsToFetch}}).done(function(response){attachments.each(function(){var attachment=$(this);var attachmentID=attachment.attr('data-fileid');if(_.isUndefined(response[attachmentID])){self._updateAttachmentMetaDataError(attachment);}else if(!_.isUndefined(response[attachmentID].rotate)){self._updateAttachmentImage(attachment,response[attachmentID]);}else{self._updateAttachmentMetaData(attachment,response[attachmentID]);}});}).fail(function(){attachments.each(function(){var attachment=$(this);self._updateAttachmentMetaDataError(attachment);});});},_updateAttachmentMetaData:function(attachment,response){var attachmentID=attachment.attr('data-fileid');if(attachment.hasClass('ipsAttachLink_block')){attachment.find('.ipsAttachLink_metaInfo').html(ips.templates.render('core.attachments.metaInfo',{size:response.size,downloads:ips.pluralize(ips.getString('attachmentDownloads'),response.downloads)}));}else{attachment.attr('title',response.size+' - '+ips.pluralize(ips.getString('attachmentDownloads'),response.downloads));}
attachment.attr('data-loaded',true);},_updateAttachmentImage:function(attachment,response){return;if(!(attachment.is('img'))){return;}
const DISABLE_LIGHTBOX_ROTATE=true;ips.controller.register('core.front.core.lightboxedImages',{_random:null,initialize(){this.on('initializeImages',this.refreshContent);this.on('refreshContent',this.refreshContent);this.on(document,'imageRotated',(e,data)=>{const attachment=this.elem.querySelector('.ipsAttachLink_image img[data-fileId='+data.fileId+']');this._updateAttachmentImage(attachment,data);});this.setup();},setup(){this._random='g'+(Math.round(Math.random()*100000));this._initializeAttachments();this._initializeImages();},async refreshContent(e){Debug.log("Refreshing content in lightboxedImages");delete this.elem.dataset.loaded;e.stopPropagation();await Promise.allSettled([this._initializeAttachments(),this._initializeImages()]);},async _initializeAttachments(){const fileIDsToFetch={};const attachments=this.elem.querySelectorAll('[data-fileid]:not([data-loaded], audio, source, video, :has(audio, source, video))')
if(!attachments.length){return;}
const isInlineCache=new WeakMap();const calcIsInline=attachment=>{const listAncestor=attachment.closest('li');if(listAncestor&&(this.elem.contains(listAncestor)||this.elem===listAncestor)){return true;}
let parent=attachment;const ancestors=[attachment];while(parent&&this.elem.contains(parent)&&(parent===attachment||parent.matches('[data-fileid]:not([data-loaded], audio, source, video, :has(audio, source, video)), a, span, b, i, u, strong, strike'))){if(isInlineCache.has(parent)){return isInlineCache.get(parent);}
ancestors.push(parent)
parent=parent.parentElement;}
if(!parent){ancestors.forEach(ancestor=>isInlineCache.set(ancestor,false));return false;}
const clone=parent.cloneNode(true);clone.querySelectorAll('[data-fileid]').forEach(cloneAttachment=>cloneAttachment.remove());const hasText=!!clone.innerText.trim();ancestors.forEach(ancestor=>isInlineCache.set(ancestor,hasText));return hasText;}
attachments.forEach((attachment)=>{if(attachment.matches(':not(img, .ipsAttachLink_image)')){if(!calcIsInline(attachment)){attachment.classList.add('ipsAttachLink_block');if(attachment.children.length){return;}
attachment.innerHTML=ips.templates.render('core.attachments.attachmentPreview',{title:attachment.textContent});}else{attachment.classList.add('ipsAttachLink_inline');attachment.setAttribute('title',ips.getString('attachmentPending'));attachment.dataset.ipstooltip="true";}}
fileIDsToFetch[attachment.dataset.fileid]=true;});if(![...Object.keys(fileIDsToFetch)].length){return;}
try{const response=await ips.fetch(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ajax&do=attachmentInfo',{dataType:'json',data:{attachIDs:fileIDsToFetch}});if(typeof response!=='object'||response instanceof Array){throw new RangeError("Expected response to be an object mapping file ids to details");}
attachments.forEach(attachment=>{const attachmentID=attachment.dataset.fileid;if(!(attachmentID in response)||typeof response[attachmentID]!=='object'||response[attachmentID]instanceof Array){this._updateAttachmentMetaDataError(attachment);}else if('rotate'in response[attachmentID]){this._updateAttachmentImage(attachment,response[attachmentID]);}else{this._updateAttachmentMetaData(attachment,response[attachmentID]);}});}catch(e){Debug.warn("Failed to get attachment info for one or more lightboxed attachments on the page");attachments.forEach(attachment=>this._updateAttachmentMetaDataError(attachment));}},_updateAttachmentMetaData(attachment,response){if(attachment.classList.contains('ipsAttachLink_block')){const infoEl=attachment.querySelector('.ipsAttachLink_metaInfo')
if(infoEl){infoEl.innerHTML=ips.templates.render('core.attachments.metaInfo',{size:response.size,downloads:ips.pluralize(ips.getString('attachmentDownloads'),response.downloads)});}}else{attachment.setAttribute('title',response.size+' - '+ips.pluralize(ips.getString('attachmentDownloads'),response.downloads));}
attachment.dataset.loaded='true';},_updateAttachmentImage(attachment,response){if(DISABLE_LIGHTBOX_ROTATE){return;}
attachment=$(attachment);if(!(attachment.is('img'))){return;}
if(!_.isUndefined(response.rotate)&&response.rotate!==null){attachment.attr('data-rotate',response.rotate).css('transform','');attachment.parents('a.ipsAttachLink_image').css({'transform':'rotate('+response.rotate+'deg)','position':'absolute','top':0});if(response.rotate==90||response.rotate==-270){if(attachment.width()>attachment.height()){attachment.parents('a.ipsAttachLink_image').css({'right':'40%','height':'100%'});}else{attachment.parents('a.ipsAttachLink_image').css({'left':'5%','transform-origin':'right'});}}else if(response.rotate==-90||response.rotate==270){if(attachment.width()>attachment.height()){attachment.parents('a.ipsAttachLink_image').css({'right':'40%','height':'100%'});}else{attachment.parents('a.ipsAttachLink_image').css({'left':'40%','transform-origin':'left'});}}
var containerHeight=attachment.height();if(response.rotate!=0&&response.rotate!=180&&response.rotate!=-180){containerHeight=attachment.width();}
var parent=attachment.parents('p:first');if($(parent).height()<containerHeight){$(parent).css({'height':parseInt(containerHeight+5).toString()+'px','position':'relative'});}}},_updateAttachmentMetaDataError:function(attachment){if(attachment.hasClass('ipsAttachLink_block')){attachment.find('.ipsAttachLink_metaInfo').html(ips.getString('attachmentUnavailable'));}else{attachment.attr('title',ips.getString('attachmentUnavailable'));}
attachment.attr('data-loaded',true);},async _addOrUpdateWrappingLink(image){const closestLink=image.closest('a');const imageSrc=image.attr('src');const fileId=image.attr('data-fileid');if(closestLink.length&&closestLink.hasClass('ipsAttachLink')&&closestLink.hasClass('ipsAttachLink_image')){const href=closestLink.attr('href');const ext=href?.includes('.')?href.split('.').pop():'';if(IMAGE_EXTENSIONS.has(ext)||(await ips.ui.lightbox.getImageDimensions(imageSrc)).solid){closestLink.attr('data-fileId',fileId).attr('data-ipsLightbox','').attr('data-ipsLightbox-group',this._random);if(href){closestLink.attr('data-fullurl',href)}}}else if(!closestLink.length){let link=$('<a data-wrappedLink data-ipslightbox>').attr('href',imageSrc).attr('title',ips.getString('enlargeImage')).attr('data-fileid',fileId).attr('data-lightbox-group',this._random);image.wrap(link);}},_initializeImages:function(){var self=this;var images=this.scope.find('img:not(.ipsEmoji *, .tiptap *, [data-emoticon] *)');if(images.length){_.each(images,function(image,i){let rawImage
if(image instanceof $){rawImage=image.get(0);}else{rawImage=image;image=$(image);}
const embedAncestor=rawImage?.closest('.ipsEmbedded_og[data-og-url]')
if(embedAncestor){if(!('linkified'in embedAncestor.dataset)){const toLink=embedAncestor.querySelector(`.ipsEmbedded_og__title`)||rawImage
var parent=attachment.parents('p:first');if($(parent).height()<containerHeight){$(parent).css({'height':parseInt(containerHeight+5).toString()+'px','position':'relative'});}}},_updateAttachmentMetaDataError(attachment){if(attachment.classList.contains('ipsAttachLink_block')){attachment.querySelector('.ipsAttachLink_metaInfo').innerHTML=ips.getString('attachmentUnavailable');}else{attachment.setAttribute('title',ips.getString('attachmentUnavailable'));}
attachment.dataset.loaded='true';},async _addOrUpdateWrappingLink(image){const closestLink=image.closest(':is(a, i-lightbox):is([data-wrapped-link], .ipsAttachLink.ipsAttachLink_image)');const imageSrc='fullImage'in image.dataset?image.dataset.fullImage:image.getAttribute('src');const fileId=image.dataset.fileid;if(closestLink){const href=closestLink.getAttribute('href');const ext=href?.includes('.')?href.split('.').pop():'';if(IMAGE_EXTENSIONS.has(ext)||(await ips.ui.lightbox.getImageDimensions(imageSrc)).solid){closestLink.dataset.fileid=fileId;closestLink.dataset.ipslightbox='';closestLink.dataset.ipslightboxGroup=this._random;if(href){closestLink.dataset.fullurl=href;}}}else{const link=document.createElement('i-lightbox');link.dataset.wrappedlink='';link.dataset.ipslightbox='';link.setAttribute('href',imageSrc)
if(image.hasAttribute('title')){image.setAttribute('data-original-title',image.getAttribute('title'));}
image.setAttribute('title',ips.getString('enlargeImage'))
link.dataset.fileid=fileId
link.dataset.ipslightboxGroup=this._random;image.parentElement.insertBefore(link,image)
link.append(image);}},async _initializeImages(){const images=this.elem.querySelectorAll('img:not(.ipsEmoji *, .tiptap *, [data-emoticon] *, .ipsEmoji, [data-emoticon], [data-ipslightbox] *, a *)');const promises=[];if(images.length){images.forEach(image=>{const embedAncestor=image?.closest('.ipsEmbedded_og[data-og-url]')
if(embedAncestor){if(!('linkified'in embedAncestor.dataset)){const toLink=embedAncestor.querySelector(`.ipsEmbedded_og__title`)||image
const toWrap=document.createElement('a')
toWrap.href=embedAncestor.dataset.ogUrl
toWrap.target="_blank"
@@ -274,8 +291,8 @@ toLink.parentElement.insertBefore(toWrap,toLink)
toWrap.append(toLink)
embedAncestor.dataset.linkified=''}
return;}
if((!image.is('img')||image.is('[data-emoticon], .ipsEmoji'))&&!image.hasClass('ipsImage_thumbnailed')){return;}
image.addClass('ipsImage_thumbnailed');self._addOrUpdateWrappingLink(image).then(()=>Debug.log('Wrapped the image if it\'s an image'));});}}});}(jQuery,_));;
promises.push(this._addOrUpdateWrappingLink(image));});}
await Promise.allSettled(promises);}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.markRead',{initialize:function(){this.on('click',this.markSiteRead);},markSiteRead:function(e){e.preventDefault();ips.ui.alert.show({type:'confirm',icon:'question',message:ips.getString('markAsReadConfirm'),subText:'',callbacks:{ok:function(){var url=$(e.currentTarget).attr('href');ips.getAjax()(url,{showLoading:true}).done(function(){$(document).trigger('markAllRead');}).fail(function(jqXHR,textStatus,errorThrown){window.location=url;});}}});}});}(jQuery,_));;
;(function(_){"use strict";ips.controller.register('core.front.core.navigationPanel',{initialize(){let collapsedPanels=[];try{collapsedPanels=JSON.parse(ips.utils.cookie.get('collapsedNavigationPanels')||'[]');if(!Array.isArray(collapsedPanels))throw new TypeError();}catch(e){collapsedPanels=[]
ips.utils.cookie.set('collapsedNavigationPanels','[]');}
@@ -314,7 +331,8 @@ $(document).trigger('contentChange',[newComment]);newComment.fadeIn().slideDown(
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.sharelink',{initialize:function(){this.on('click','[data-role="shareLink"]',this.launchWindow);},launchWindow:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');if(!ips.utils.url.getParam('url',url)){url+="&url="+encodeURIComponent(location.href);}
if(!ips.utils.url.getParam('title',url)){url+="&title="+encodeURIComponent(document.title);}
window.open(url,'delicious','toolbar=no,width=550,height=550');},});}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register('core.front.core.userbar',{loaded:{inbox:false,notify:false,reports:false},initialize(){this.on(document,'menuOpened',(...args)=>this.menuOpened(...args));this.on(document,'clearUserbarCache',(...args)=>this.clearUserbarCache(...args));},menuOpened(e,data){if(data.elemID==='elFullInbox'||data.elemID==='ipsOffCanvas--messenger'){this._loadMenu('inbox',ips.getSetting('baseURL')+'index.php?app=core&module=messaging&controller=messenger&overview=1&_fromMenu=1');}else if(data.elemID==='elFullNotifications'||data.elemID==='ipsOffCanvas--notifications'){this._loadMenu('notify',ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=notifications');}else if(data.elemID==='elFullReports'||data.elemID==='elMobReports'){this._loadMenu('reports',ips.getSetting('baseURL')+'index.php?app=core&module=modcp&controller=modcp&tab=reports&overview=1');}},clearUserbarCache(e,data){this.loaded[data.type]=false;},async _loadMenu(type,url){if(!this.loaded[type]){const list=$(`[data-role="${type}List"]`);list.html('').css({height:'100px'}).addClass('ipsLoading');try{const returnedData=await ips.fetch(url,{dataType:'json'});list.css({height:'auto'}).removeClass('ipsLoading').html(returnedData.data);this.loaded[type]=true;if(type!=='reports'){const thisBubble=$(`[data-notificationtype="${type}"]`);const thisTotal=Math.max(0,parseInt(thisBubble.html()))||0;const globalBubble=$(`[data-notificationtype="total"]`);const globalCount=Math.max(0,parseInt(globalBubble.html()))||0;ips.utils.anim.go('fadeOut',thisBubble);if(globalCount-thisTotal<=0){ips.utils.anim.go('fadeOut',globalBubble);}else{globalBubble.html(globalCount-thisTotal)}}
;(function($,_){"use strict";ips.controller.register('core.front.core.userbar',{loaded:{inbox:false,notify:false,reports:false},initialize(){this.on(document,'menuOpened',(...args)=>this.menuOpened(...args));this.on(document,'clearUserbarCache',(...args)=>this.clearUserbarCache(...args));},menuOpened(e,data=e.detail){if(data.elemID==='elFullInbox'||data.elemID==='ipsOffCanvas--messenger'){this._loadMenu('inbox',ips.getSetting('baseURL')+'index.php?app=core&module=messaging&controller=messenger&overview=1&_fromMenu=1');}else if(data.elemID==='elFullNotifications'||data.elemID==='ipsOffCanvas--notifications'){this._loadMenu('notify',ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=notifications');}else if(data.elemID==='elFullReports'||data.elemID==='elMobReports'){this._loadMenu('reports',ips.getSetting('baseURL')+'index.php?app=core&module=modcp&controller=modcp&tab=reports&overview=1');}},clearUserbarCache(e,data){this.loaded[data.type]=false;},async _loadMenu(type,url){if(!this.loaded[type]){const list=$(`[data-role="${type}List"]`);list.html('').css({height:'100px'}).addClass('ipsLoading');try{const returnedData=await ips.fetch(url,{dataType:'json'});list.css({height:'auto'}).removeClass('ipsLoading').html(returnedData.data);this.loaded[type]=true;if(type!=='reports'){const thisBubble=$(`[data-notificationtype="${type}"]`);const thisTotal=Math.max(0,parseInt(thisBubble.html()))||0;const globalBubble=$(`[data-notificationtype="total"]`);const globalCount=Math.max(0,parseInt(globalBubble.html()))||0;ips.utils.anim.go('fadeOut',thisBubble);if(globalCount-thisTotal<=0){ips.utils.anim.go('fadeOut',globalBubble);}else{globalBubble.html(globalCount-thisTotal)}}
if(type==='notify'){ips.utils.notification.clearBadgeCount();}
$(document).trigger('contentChange',[list]);}catch(e){Debug.log("Failed to load a userbar menu")}}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.webshare',{initialize:function(){if(navigator.share){this._render();this.on('click',this.initShare);}},_render:function(){$('[data-role="webShare"]').removeClass('ipsHide');},initShare:function(e){try{navigator.share({title:this.scope.attr('data-webShareTitle'),text:this.scope.attr('data-webShareText'),url:this.scope.attr('data-webShareUrl')});}catch(err){Debug.log("Failed to use web share API: ",err);}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.model.register('core.comment',{initialize:function(){this.on('getEditForm.comment',this.getEditForm);this.on('saveEditComment.comment',this.saveEditComment);this.on('deleteComment.comment',this.deleteComment);this.on('newComment.comment',this.newComment);this.on('approveComment.comment',this.approveComment);this.on('unrecommendComment.comment',this.unrecommendComment);},getEditForm:function(e,data){this.getData({url:data.url,dataType:'html',data:{},events:'getEditForm',namespace:'comment'},data);},saveEditComment:function(e,data){var url=data.url;this.getData({url:data.url,dataType:'html',type:'post',data:data.form||{},events:'saveEditComment',namespace:'comment'},data);},approveComment:function(e,data){this.getData({url:data.url,dataType:'html',data:data.form||{},events:'approveComment',namespace:'comment'},data);},unrecommendComment:function(e,data){this.getData({url:data.url,dataType:'json',data:data.form||{},events:'unrecommendComment',namespace:'comment'},data);},deleteComment:function(e,data){this.getData({url:data.url,dataType:'html',data:data.form||{},events:'deleteComment',namespace:'comment'},data);},newComment:function(e,data){this.getData({url:data.url,dataType:'json',data:data.form||{},events:'newComment',namespace:'comment'},data);}});}(jQuery,_));;
+7 -5
View File
@@ -10,10 +10,12 @@ return Debug;},clearAdapters=function(){options.adapters=[];return Debug;};retur
break;case 2:console.info(msg);break;case 3:console.warn(msg);break;case 4:console.error(msg);break;}}};Debug.addAdapter(new Console);if(ipsDebug||(!_.isUndefined(window.localStorage)&&'localStorage'in window&&window['localStorage']!==null&&window.localStorage.getItem('DEBUG'))){Debug.setEnabled(true).setLevel('DEBUG').info("Enabled logging");}}(jQuery,_));;
var ips=ips||{};jQuery.migrateMute=true;(function($,_,undefined){class CustomSubmitEvent extends Event{submitter=undefined;originalEvent=undefined;constructor(originalEvent){super('submit',{bubbles:true});this.submitter=originalEvent.submitter;this.originalEvent=originalEvent;}}
"use strict";let logTimeIndent=0;ips=(function(){var _settings,_strings={},_graphData={},uid=1,urand=Math.ceil(Math.random()*10000),elemContainer,_location='front';var boot=function(config){_settings=config;_setAjaxConfig();_setAjaxEventListeners();document.addEventListener('submit',e=>{const form=e.target;if(e instanceof SubmitEvent&&form instanceof HTMLFormElement&&form.method.toUpperCase()==='POST'&&!getSetting('memberID')&&getCsrfKeyExpiry()<Date.now()/1000){Debug.log(`Intercepted form submission... fetching fresh CSRF key`);e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();getFreshCsrfKey().then(()=>{Debug.log(`Got a new CSRF key, resuming the form submission`);let submitButton=(e instanceof SubmitEvent||e.submitter instanceof Element)?e.submitter:form.querySelector('button[type="submit"], button:not([type]), input[type="submit"]');if(submitButton){submitButton.click();}else{const ev=new CustomSubmitEvent(e);form.dispatchEvent(ev);if(ev.defaultPrevented){return;}
form.submit();}});}},{capture:true});$.fn.animationComplete=function(callback){if('getAnimations'in Element.prototype){const elements=[...this];(new Promise(resolve=>setTimeout(resolve,0))).then(()=>Promise.allSettled((elements.map(el=>el.getAnimations()).flat()).map(anim=>anim.finished))).then(()=>callback.apply(this));return $(this);}
form.submit();}});}},{capture:true});if(!(HTMLElement.prototype.showPopover instanceof Function)){Debug.log(`Loading popover polyfill`);setTimeout(()=>{ips.loader.getStatic('/applications/core/interface/static/popover/popover.min.js');});}
$.fn.animationComplete=function(callback){if('getAnimations'in Element.prototype){const elements=[...this];(new Promise(resolve=>setTimeout(resolve,0))).then(()=>Promise.allSettled((elements.map(el=>el.getAnimations()).flat()).map(anim=>anim.finished))).then(()=>callback.apply(this));return $(this);}
return $(this).one('webkitAnimationEnd animationend',function(e){if(e.target==this){callback.apply(this);}});};$.fn.identify=function(){return this.each(function(){if(!this.id){this.id='ips_uid_'+urand+'_'+(++uid);}});};var oldProp=$.fn.prop;var newProp=function(){var retFunc=oldProp.apply(this,arguments);this.trigger('propChanged',this);return retFunc;};$.fn.prop=newProp;Function.prototype.method=function(name,func){this.prototype[name]=func;return this;};_.templateSettings={interpolate:/\{\{(.+?)\}\}/g
};if(!Debug.isEnabled()&&window.console){window.console.log("%cThis is a browser feature intended for developers. Do not paste any code here given to you by someone else. It may compromise your account or have other negative side effects.","font-weight: bold; font-size: 14px;");}
$(document).trigger('doneBooting').ready(function(){_location=$('body').attr('data-pageLocation')||'front';});},getAjax=function(){const wrap=method=>(...args)=>{let options={},url;if(typeof args[0]==='string'){url=args[0];options=args[1]||{};}else if(typeof args[0]==='object'&&args[0]){options=args[0];}
if(options?.bypassRedirect==='none'){options.headers=options.headers||{};options.headers['x-bypass-ajax-redirect']='1';}
if((options.method||options.type)?.toLowerCase()!=='post'||getSetting('memberID')||getCsrfKeyExpiry()>=Date.now()/1000){return method(...args);}
let requestInstance;const decoratorQueues={};const properties={};let thenResolve,thenReject,mimeTypeOverride;const uploadEventListeners=new Map();const uploadDispatchedEvents=[];const proxyXHRObject={_promise:new Promise((resolve,reject)=>{thenResolve=resolve;thenReject=reject}),then(cb){this._promise.then(cb);},catch(...args){this._promise.catch(...args)},finally(...args){this._promise.finally(...args);},_aborted:false,get aborted(){return this._aborted;},_abortedStatusText:undefined,get abortedStatusText(){return this._abortedStatusText;},abort(statusText){this._aborted=true;this._abortedStatusText=statusText;requestInstance?.abort(statusText);},getAllResponseHeaders(){return requestInstance?.getAllResponseHeaders()||null;},getResponseHeader(header){return requestInstance?.getResponseHeader(header)||null;},overrideMimeType(mimeType){if(requestInstance){requestInstance.overrideMimeType(mimeType);return;}
mimeTypeOverride=mimeType;},get readyState(){return requestInstance?requestInstance.readyState:0;},get response(){return requestInstance?('response'in requestInstance?requestInstance.response:null):null;},get responseText(){if(typeof requestInstance?.responseText==='string'){return requestInstance.responseText;}
@@ -34,7 +36,7 @@ if(getSetting('mock_ajax')){return wrap(getSetting('mock_ajax'));}
return wrap($.ajax);},fetch=function(url,settings={}){return new Promise((resolve,reject)=>{const options={};if(typeof settings==='object'){Object.assign(options,settings)}else if(settings){return resolve(new TypeError(`Could not generate an ajax request because the settings is supposed to be of type object. Got a(n) ${typeof settings}`));}
if(typeof url==='string'){options.url=url;}else if(typeof url==='object'){Object.assign(options,url)}else{return reject(new TypeError(`Could not generate an ajax request because url is supposed to be a string or an object. Got a ${typeof url}`));}
options.async=true
delete options.error
const getXHRHook=options.getXHRHook;delete options.getXHRHook;delete options.error
delete options.success
delete options.complete
delete options.contents
@@ -51,7 +53,7 @@ delete options.traditional
delete options.xhr
delete options.xhrFields
if(options.type&&!options.method){options.method=options.type;delete options.type;}
getAjax()(options).done(resolve).fail(reject)})},getContainer=function(){var tryThis=$(getSetting('container'));return(tryThis.length)?tryThis:$('body');},_refreshCsrfKey=async function(){setSetting('csrfKeyExpiry',Math.floor(Date.now()/1000+20));try{const response=await window.fetch(getSetting('baseURL').toString().replace(/\/+$/,'')+'/?app=core&module=system&controller=ajax&do=getCsrfKey&path='+window.location.pathname);const data=await response.json();Debug.log(`Got new CSRF Key: ${data.key}`);setSetting('csrfKey',data.key);setSetting('csrfKeyExpiry',typeof data.expiry==="number"?data.expiry:Math.floor(Date.now()/1000+500));_setAjaxConfig();document.querySelectorAll(`form input[name="csrfKey"]`).forEach(input=>{input.value=data.key;});document.querySelectorAll(`form:is([action*="?csrfKey="],[action*="&csrfKey="])`).forEach(form=>{const url=new URL(form.action);if((url.toString().startsWith('https:'+ips.getSetting('baseURL'))||url.toString().startsWith('http:'+ips.getSetting('baseURL')))&&(url.searchParams.has('csrfKey')||form.method.toLowerCase()!=='get')){url.updateSearchParams({param:'csrfKey',value:data.key});form.action=url.toString();}});document.querySelectorAll(`[href*="?csrfKey="], [href*="&csrfKey="]`).forEach(linkLikeEl=>{const url=new URL(linkLikeEl.href||linkLikeEl.getAttribute('href'));if((url.toString().startsWith('https:'+ips.getSetting('baseURL'))||url.toString().startsWith('http:'+ips.getSetting('baseURL')))&&url.searchParams.has('csrfKey')){url.updateSearchParams({param:'csrfKey',value:data.key});linkLikeEl.setAttribute('href',url.toString());}});document.dispatchEvent(new CustomEvent('ips:csrfKeyUpdated'));}catch(e){Debug.warn(e);}},getCsrfKeyExpiry=function(){const setting=getSetting('csrfKeyExpiry');if(typeof setting==="number"&&!Number.isNaN(setting)&&getSetting('csrfKey')){return setting;}
let jqxhr;jqxhr=getAjax()(options).done(resolve).fail((e,...args)=>{try{if(e instanceof Error||typeof e==='object'){e.jqxhr=jqxhr;e.additionalArgs=args;reject(e);}else{throw new Error("Expected the first argument of the fail method to be an Error or a writable Object");}}catch(anotherError){let finalError=new Error("Got a really weird type passed to the fail method of a jquery ajax call");finalError.additionalArgs=args;finalError.jqxhr=jqxhr;finalError.additionalError=anotherError;Debug.error(anotherError);reject(anotherError);}});if(getXHRHook instanceof Function){try{getXHRHook(jqxhr);}catch(e){e.message=`Something went wrong when assigning the jqxhr hook - ${e.message}`;Debug.error(e);}}})},getContainer=function(){var tryThis=$(getSetting('container'));return(tryThis.length)?tryThis:$('body');},_refreshCsrfKey=async function(){setSetting('csrfKeyExpiry',Math.floor(Date.now()/1000+20));try{const response=await window.fetch(getSetting('baseURL').toString().replace(/\/+$/,'')+'/?app=core&module=system&controller=ajax&do=getCsrfKey&path='+window.location.pathname);const data=await response.json();Debug.log(`Got new CSRF Key: ${data.key}`);setSetting('csrfKey',data.key);setSetting('csrfKeyExpiry',typeof data.expiry==="number"?data.expiry:Math.floor(Date.now()/1000+500));_setAjaxConfig();document.querySelectorAll(`form input[name="csrfKey"]`).forEach(input=>{input.value=data.key;});document.querySelectorAll(`form:is([action*="?csrfKey="],[action*="&csrfKey="])`).forEach(form=>{const url=new URL(form.action);if((url.toString().startsWith('https:'+ips.getSetting('baseURL'))||url.toString().startsWith('http:'+ips.getSetting('baseURL')))&&(url.searchParams.has('csrfKey')||form.method.toLowerCase()!=='get')){url.updateSearchParams({param:'csrfKey',value:data.key});form.action=url.toString();}});document.querySelectorAll(`[href*="?csrfKey="], [href*="&csrfKey="]`).forEach(linkLikeEl=>{const url=new URL(linkLikeEl.href||linkLikeEl.getAttribute('href'));if((url.toString().startsWith('https:'+ips.getSetting('baseURL'))||url.toString().startsWith('http:'+ips.getSetting('baseURL')))&&url.searchParams.has('csrfKey')){url.updateSearchParams({param:'csrfKey',value:data.key});linkLikeEl.setAttribute('href',url.toString());}});document.dispatchEvent(new CustomEvent('ips:csrfKeyUpdated'));}catch(e){Debug.warn(e);}},getCsrfKeyExpiry=function(){const setting=getSetting('csrfKeyExpiry');if(typeof setting==="number"&&!Number.isNaN(setting)&&getSetting('csrfKey')){return setting;}
return 0;},getFreshCsrfKey=async function(){if(getSetting('memberID')&&getSetting('csrfKey')){return getSetting('csrfKey');}
if(Date.now()/1000>=getCsrfKeyExpiry()){await _refreshCsrfKey();}
return getSetting('csrfKey');},_setAjaxConfig=function(){var data={csrfKey:getSetting('csrfKey')};$.ajaxSetup({data:data,cache:true});},_setAjaxEventListeners=function(){var count=0;$(document).ajaxSend(function(event,request,settings){if(!_.isUndefined(settings)&&settings.showLoading===true){if(!$('#elAjaxLoading').length){getContainer().append(templates.render('core.general.ajax'));}
@@ -91,8 +93,8 @@ logTimeIndent--;}
const res=cb();if(res instanceof Promise){return res.then((result)=>{doneExecuting();return result;})}
doneExecuting();return res;}};}());ips.boot(ipsSettings);}(jQuery,_));!function(){var lastBtn=null
document.addEventListener('click',function(e){if(!e.target.closest)return;lastBtn=e.target.closest('button, input[type=submit]');},true);document.addEventListener('submit',function(e){if('submitter'in e)return;var canditates=[document.activeElement,lastBtn];lastBtn=null;for(var i=0;i<canditates.length;i++){var candidate=canditates[i];if(!candidate)continue;if(!candidate.form)continue;if(!candidate.matches('button, input[type=button], input[type=image]'))continue;e.submitter=candidate;return;}
e.submitter=e.target.querySelector('button, input[type=button], input[type=image]');},true);}();if(navigator.standalone){document.addEventListener("scroll",iosPwaScrollFix,{passive:true});function iosPwaScrollFix(){if(window.scrollY===0){document.documentElement.scrollTop=0;}}
document.addEventListener("ips:toggleComplete",iosPwaOffcanvasFix);function iosPwaOffcanvasFix(e){if(e.target.matches('[data-ips-hidden-group="offcanvas"]')){document.documentElement.scrollTop+=0;};}};
e.submitter=e.target.querySelector('button, input[type=button], input[type=image]');},true);}();if(CSS.supports("-webkit-hyphens: none")){document.addEventListener("click",safariTogglePopoverFix);function safariTogglePopoverFix(e){const trigger=e.target.closest("[popovertarget]");if(!trigger)return;const popoverEl=document.querySelector(`#${trigger.getAttribute("popovertarget")}`);if(!popoverEl)return;trigger.focus({focusVisible:false});if((!CSS.supports("selector(::details-content)")&&popoverEl.querySelector('input:not([type="radio"], [type="checkbox"]), select'))||(!CSS.supports("text-box-edge: auto")&&trigger.closest("form"))){e.preventDefault();popoverEl[`${trigger.popoverTargetAction || "toggle"}Popover`]({source:trigger});}}
if(!CSS.supports("selector(::details-content)")){document.addEventListener("pointerdown",e=>{});}};
!function(){"use strict";var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};!function(e){function n(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=Object.create(t.prototype);for(var a in n)o[a]=n[a];return o.constructor=e,e.prototype=o,e}function o(t){t=t||{},this.defaultProtocol=t.defaultProtocol||h.defaultProtocol,this.events=t.events||h.events,this.format=t.format||h.format,this.formatHref=t.formatHref||h.formatHref,this.nl2br=t.nl2br||h.nl2br,this.tagName=t.tagName||h.tagName,this.target=t.target||h.target,this.validate=t.validate||h.validate,this.ignoreTags=[],this.attributes=t.attributes||t.linkAttributes||h.attributes,this.className=t.className||t.linkClass||h.className;for(var e=t.ignoreTags||h.ignoreTags,n=0;n<e.length;n++)this.ignoreTags.push(e[n].toUpperCase())}function a(t,e){for(var n=0;n<t.length;n++)if(t[n]===e)return!0;return!1}function r(t){return t}function i(t,e){return"url"===e?"_blank":null}function s(){return function(t){this.j=[],this.T=t||null}}function c(t,e,n,o){for(var a=0,r=t.length,i=e,s=[],c=void 0;a<r&&(c=i.next(t[a]));)i=c,a++;if(a>=r)return[];for(;a<r-1;)c=new m(o),s.push(c),i.on(t[a],c),i=c,a++;return c=new m(n),s.push(c),i.on(t[r-1],c),s}function l(){return function(t){t&&(this.v=t)}}function u(t){var e=t?{v:t}:{};return n(b,l(),e)}function p(t){return t instanceof v||t instanceof R}var h={defaultProtocol:"http",events:null,format:r,formatHref:r,nl2br:!1,tagName:"a",target:i,validate:!0,ignoreTags:[],attributes:null,className:"linkified"};o.prototype={resolve:function(t){var e=t.toHref(this.defaultProtocol);return{formatted:this.get("format",t.toString(),t),formattedHref:this.get("formatHref",e,t),tagName:this.get("tagName",e,t),className:this.get("className",e,t),target:this.get("target",e,t),events:this.getObject("events",e,t),attributes:this.getObject("attributes",e,t)}},check:function(t){return this.get("validate",t.toString(),t)},get:function(e,n,o){var a=this[e];if(!a)return a;switch("undefined"==typeof a?"undefined":t(a)){case"function":return a(n,o.type);case"object":var r=a[o.type]||h[e];return"function"==typeof r?r(n,o.type):r}return a},getObject:function(t,e,n){var o=this[t];return"function"==typeof o?o(e,n.type):o}};var g=Object.freeze({defaults:h,Options:o,contains:a}),f=s();f.prototype={defaultTransition:!1,on:function(t,e){if(t instanceof Array){for(var n=0;n<t.length;n++)this.j.push([t[n],e]);return this}return this.j.push([t,e]),this},next:function(t){for(var e=0;e<this.j.length;e++){var n=this.j[e],o=n[0],a=n[1];if(this.test(t,o))return a}return this.defaultTransition},accepts:function(){return!!this.T},test:function(t,e){return t===e},emit:function(){return this.T}};var m=n(f,s(),{test:function(t,e){return t===e||e instanceof RegExp&&e.test(t)}}),d=n(f,s(),{jump:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=this.next(new t(""));return n===this.defaultTransition?(n=new this.constructor(e),this.on(t,n)):e&&(n.T=e),n},test:function(t,e){return t instanceof e}}),b=l();b.prototype={toString:function(){return this.v+""}};var v=u(),y=u("@"),k=u(":"),w=u("."),j=u(),x=u(),z=u("\n"),O=u(),S=u("+"),N=u("#"),T=u(),A=u("mailto:"),L=u("?"),E=u("/"),C=u("_"),P=u(),R=u(),q=u(),H=u("{"),B=u("["),U=u("<"),M=u("("),D=u("}"),I=u("]"),K=u(">"),_=u(")"),G=u("&"),Y=Object.freeze({Base:b,DOMAIN:v,AT:y,COLON:k,DOT:w,PUNCTUATION:j,LOCALHOST:x,NL:z,NUM:O,PLUS:S,POUND:N,QUERY:L,PROTOCOL:T,MAILTO:A,SLASH:E,UNDERSCORE:C,SYM:P,TLD:R,WS:q,OPENBRACE:H,OPENBRACKET:B,OPENANGLEBRACKET:U,OPENPAREN:M,CLOSEBRACE:D,CLOSEBRACKET:I,CLOSEANGLEBRACKET:K,CLOSEPAREN:_,AMPERSAND:G}),Q="aaa|aarp|abb|abbott|abogado|ac|academy|accenture|accountant|accountants|aco|active|actor|ad|adac|ads|adult|ae|aeg|aero|af|afl|ag|agency|ai|aig|airforce|airtel|al|alibaba|alipay|allfinanz|alsace|am|amica|amsterdam|an|analytics|android|ao|apartments|app|apple|aq|aquarelle|ar|aramco|archi|army|arpa|arte|as|asia|associates|at|attorney|au|auction|audi|audio|author|auto|autos|avianca|aw|ax|axa|az|azure|ba|baidu|band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bb|bbc|bbva|bcg|bcn|bd|be|beats|beer|bentley|berlin|best|bet|bf|bg|bh|bharti|bi|bible|bid|bike|bing|bingo|bio|biz|bj|black|blackfriday|bloomberg|blue|bm|bms|bmw|bn|bnl|bnpparibas|bo|boats|boehringer|bom|bond|boo|book|boots|bosch|bostik|bot|boutique|br|bradesco|bridgestone|broadway|broker|brother|brussels|bs|bt|budapest|bugatti|build|builders|business|buy|buzz|bv|bw|by|bz|bzh|ca|cab|cafe|cal|call|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|cc|cd|ceb|center|ceo|cern|cf|cfa|cfd|cg|ch|chanel|channel|chase|chat|cheap|chloe|christmas|chrome|church|ci|cipriani|circle|cisco|citic|city|cityeats|ck|cl|claims|cleaning|click|clinic|clinique|clothing|cloud|cLine truncated
"use strict";!function(e,t,n){var i=function(t,n){function i(e,t,n){var i=n[n.length-1];e.replaceChild(i,t);for(var r=n.length-2;r>=0;r--)e.insertBefore(n[r],i),i=n[r]}function r(e,t,n){for(var i=[],r=e,a=Array.isArray(r),o=0,r=a?r:r[Symbol.iterator]();;){var l;if(a){if(o>=r.length)break;l=r[o++]}else{if(o=r.next(),o.done)break;l=o.value}var f=l;if("nl"===f.type&&t.nl2br)i.push(n.createElement("br"));else if(f.isLink&&t.check(f)){var s=t.resolve(f),c=s.formatted,u=s.formattedHref,d=s.tagName,m=s.className,y=s.target,h=s.events,k=s.attributes,v=n.createElement(d);if(v.setAttribute("href",u),m&&v.setAttribute("class",m),y&&v.setAttribute("target",y),k)for(var g in k)v.setAttribute(g,k[g]);if(h)for(var b in h)v.addEventListener?v.addEventListener(b,h[b]):v.attachEvent&&v.attachEvent("on"+b,h[b]);v.appendChild(n.createTextNode(c)),i.push(v)}else i.push(n.createTextNode(f.toString()))}return i}function a(e,t,n){if(!e||e.nodeType!==d)throw new Error("Cannot linkify "+e+" - Invalid DOM Node type");var o=t.ignoreTags;if("A"===e.tagName||s.contains(o,e.tagName))return e;for(var l=e.firstChild;l;){switch(l.nodeType){case d:a(l,t,n);break;case m:var c=l.nodeValue,y=f(c);if(0===y.length||1===y.length&&y[0]instanceof u)break;var h=r(y,t,n);i(e,l,h),l=h[h.length-1]}l=l.nextSibling}return e}function o(t,n){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{i=i||document||e&&e.document||global&&global.document}catch(r){}if(!i)throw new Error("Cannot find document implementation. If you are in a non-browser environment like Node.js, pass the document implementation as the third argument to linkifyElement.");return n=new c(n),a(t,n,i)}function l(t){function n(e){return e=o.normalize(e),this.each(function(){o.helper(this,e,i)})}var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];t.fn=t.fn||{};try{i=i||document||e&&e.document||global&&global.document}catch(r){}if(!i)throw new Error("Cannot find document implementation. If you are in a non-browser environment like Node.js, pass the document implementation as the second argument to linkify/jquery");"function"!=typeof t.fn.linkify&&(t.fn.linkify=n,t(i).ready(function(){t("[data-linkify]").each(function(){var e=t(this),n=e.data(),i=n.linkify,r=n.linkifyNlbr,a={attributes:n.linkifyAttributes,defaultProtocol:n.linkifyDefaultProtocol,events:n.linkifyEvents,format:n.linkifyFormat,formatHref:n.linkifyFormatHref,nl2br:!!r&&0!==r&&"false"!==r,tagName:n.linkifyTagname,target:n.linkifyTarget,className:n.linkifyClassName||n.linkifyLinkclass,validate:n.linkifyValidate,ignoreTags:n.linkifyIgnoreTags},o="this"===i?e:e.find(i);o.linkify(a)})}))}t="default"in t?t["default"]:t;var f=n.tokenize,s=n.options,c=s.Options,u=n.parser.TOKENS.TEXT,d=1,m=3;o.helper=a,o.normalize=function(e){return new c(e)};try{!define&&(e.linkifyElement=o)}catch(y){}return l}(n,t);"function"!=typeof n.fn.linkify&&i(n)}(window,linkify,jQuery);;
"use strict";function eventSuppressor(e){e.preventDefault();e.stopPropagation();}
+2 -2
View File
@@ -1,5 +1,5 @@
ips.templates.set('nexus.store.productImage'," <a href='{{fullURL}}' data-fullURL='{{fullURL}}' class='cNexusProduct_primaryImage' data-ipsLightbox data-ipsLightbox-group='product' style='background-image:url({{thumbURL}})'> <img src='{{thumbURL}}' alt=''> </a>");;
;(function($,_,undefined){"use strict";ips.controller.register('nexus.front.store.cartReview',{initialize:function(){this.on('click','[data-action="removeFromCart"]',this.removeFromCart);this.on('submit','[data-role="quantityForm"]',this.quantityForm);this.on('click','[data-action="checkout"]',this.checkout);},checkout:function(e){if($(e.target).hasClass('ipsButton--disabled')){e.preventDefault();}else{$(e.target).addClass('ipsButton--disabled');}},removeFromCart:function(e){e.preventDefault();var self=this;var url=$(e.currentTarget).attr('href');ips.ui.alert.show({type:'confirm',message:ips.getString('confirmRemoveItem'),icon:'warn',callbacks:{ok:function(){ips.getAjax()(url).done(function(response){self.scope.find('[data-role="cart"]').html(response);});}}});},quantityForm:function(e){e.preventDefault();var self=this;var form=$(e.currentTarget);var menu=form.closest('.ipsMenu');menu.css({height:menu.outerHeight()+'px'}).addClass('ipsLoading');form.hide();ips.getAjax()(form.attr('action'),{data:form.serialize()}).done(function(response){self.scope.find('[data-role="cart"]').html(response);}).fail(function(response){menu.removeClass('ipsLoading');form.show();ips.ui.alert.show({type:'alert',icon:'warn',message:response.responseJSON});});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('nexus.front.store.cartReview',{initialize:function(){this.on('click','[data-action="removeFromCart"]',this.removeFromCart);this.on('submit','[data-role="quantityForm"]',this.quantityForm);this.on('click','[data-action="checkout"]',this.checkout);},checkout:function(e){if($(e.target).hasClass('ipsButton--disabled')){e.preventDefault();}else{$(e.target).addClass('ipsButton--disabled');}},removeFromCart:function(e){e.preventDefault();var self=this;var url=$(e.currentTarget).attr('href');ips.ui.alert.show({type:'confirm',message:ips.getString('confirmRemoveItem'),icon:'warn',callbacks:{ok:function(){ips.getAjax()(url).done(function(response){self.scope.find('[data-role="cart"]').html(response);});}}});},quantityForm:function(e){e.preventDefault();var self=this;var form=$(e.currentTarget);ips.getAjax()(form.attr('action'),{data:form.serialize()}).done(function(response){self.scope.find('[data-role="cart"]').html(response);}).fail(function(response){ips.ui.alert.show({type:'alert',icon:'warn',message:response.responseJSON});});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('nexus.front.store.category',{_ajaxObj:null,initialize:function(){this.on('click','[data-action="filter"],[data-page]',this.changeView);this.setup();},setup:function(){ips.utils.history.replaceState({controller:'storeCategoryView'},'nexus.front.store.category',window.location.href);window.addEventListener('historychange:nexus.front.store.category',e=>this.stateChange(e));},changeView:function(e){e.preventDefault();if($(e.target).hasClass('ipsSideMenu_item')){$(e.target).toggleClass('ipsSideMenu_itemActive');}
const url=$(e.currentTarget).attr('href');ips.utils.history.pushState({controller:'storeCategoryView'},'nexus.front.store.category',$(e.currentTarget).attr('href'));},stateChange:function(){const url=window.location.href;if(!('nexus.front.store.category'in ips.utils.history.getState())){return;}
ips.utils.analytics.trackPageView(url);this._updateView(url)},async _updateView(url){if(this._ajaxObj&&_.isFunction(this._ajaxObj.abort)){this._ajaxObj.abort();}
@@ -20,7 +20,7 @@ form.replaceWith(newForm);$(document).trigger('contentChange');}});},insertCssUr
_.each(urls,function(url){if(url.indexOf('?')!=-1){url=url+'&v='+ips.getSetting('antiCache');}
else
{url=url+'?v='+ips.getSetting('antiCache');}
if(!$('link[href="'+url+'"]').length){var stylesheet=document.createElement("link");stylesheet.setAttribute("href",url);stylesheet.setAttribute("rel","stylesheet");stylesheet.setAttribute("media","all");$('head')[0].appendChild(stylesheet);Debug.log("Added stylesheet "+url+" to document");}});},updatePriceAndStock:function(){var self=this;var form=this.scope.find('form');ips.getAjax()(form.attr('action'),{dataType:'json',data:form.serialize()+'&stockCheck=1',type:'post'}).done(function(response){self.scope.find('[data-role="price"]').html(response.price);self.scope.find('[data-role="stock"]').html(response.stock);self.scope.find('[data-role="renewalTerm"]').html(response.renewal);self.scope.find('[data-role="initialTerm"]').html(response.initialTerm);if(response.okay){self.scope.find('button').removeAttr('disabled').text(ips.getString('add_to_cart_js'));}else{self.scope.find('button').attr('disabled','disabled').text(ips.getString('out_of_stock'));}}).fail(function(response){Debug.error(response);});}});}(jQuery,_));;
if(!$('link[href="'+url+'"]').length){var stylesheet=document.createElement("link");stylesheet.setAttribute("href",url);stylesheet.setAttribute("rel","stylesheet");stylesheet.setAttribute("media","all");$('head')[0].appendChild(stylesheet);Debug.log("Added stylesheet "+url+" to document");}});},updatePriceAndStock:function(){var self=this;var form=this.scope.find('form');ips.getAjax()(form.attr('action'),{dataType:'json',data:form.serialize()+'&stockCheck=1',type:'post'}).done(function(response){self.scope.find('[data-role="price"]').html(response.price);self.scope.find('[data-role="stock"]').html(response.stock);self.scope.find('[data-role="renewalTerm"]').html(response.renewal);self.scope.find('[data-role="initialTerm"]').html(response.initialTerm);if(response.okay){self.scope.find('[type="submit"]').removeAttr('disabled').text(ips.getString('add_to_cart_js'));}else{self.scope.find('[type="submit"]').attr('disabled','disabled').text(ips.getString('out_of_stock'));}}).fail(function(response){Debug.error(response);});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('nexus.front.store.register',{_infoPaneWrapper:null,_infoPane:null,initialize:function(){this.on('click','[data-role="productCarousel"] .cNexusProduct',this.selectProduct);this.on('click','[data-action="closeInfo"]',this.closeInfo);this.on('addToCart.nexus',this.addToCart);this.setup();},setup:function(){this._infoPaneWrapper=this.scope.find('[data-role="productInformationWrapper"]');this._infoPane=this.scope.find('[data-role="productInformation"]');},closeInfo:function(e){e.preventDefault();this.scope.find('[data-role="productCarousel"] .cNexusProduct').removeClass('cNexusProduct_selected');this._infoPaneWrapper.hide().find('[data-action="closeInfo"]').hide();},selectProduct:function(e){e.preventDefault();var selectedProduct=$(e.currentTarget);var self=this;this.scope.find('[data-role="productCarousel"] .cNexusProduct').removeClass('cNexusProduct_selected');selectedProduct.addClass('cNexusProduct_selected');var url=selectedProduct.find('[data-role="productLink"]').attr('href');var height=200;if(this._infoPaneWrapper.is(':visible')){height=this._infoPane.height();}
this._infoPaneWrapper.show().find('[data-action="closeInfo"]').hide();this._infoPane.css({height:height+'px'}).html('').addClass('ipsLoading');ips.getAjax()(url).done(function(response){self._infoPaneWrapper.find('[data-action="closeInfo"]').show();self._infoPane.removeClass('ipsLoading').css({height:'auto'}).html(response);$(document).trigger('contentChange',[self._infoPane]);});},addToCart:function(e,data){e.stopPropagation();var self=this;ips.getAjax()(data.url,{data:data.formData+'&registerCheckout=1',type:'post'}).done(function(response){self._infoPane.html(response.dialog);$(document).trigger('contentChange',[self._infoPane]);}).fail(function(response){var loadingElem=self.scope.find('form').next('.ipsLoading');loadingElem.remove();if(response.responseJSON){ips.ui.alert.show({type:'alert',message:response.responseJSON,icon:'warn'});}else{var form=$(e.target).find('form');try{var newForm=$(response.responseText);}catch(err){form.attr('data-noajax','true');form.submit();}
form.replaceWith(newForm);$(document).trigger('contentChange');}});},});}(jQuery,_));;