Version 5.0.6
This commit is contained in:
1 parent
a3a4a9ccbd
commit
b89858b2ff
1214 files changed
+92828
-14859
No files matched your search
@@ -1,6 +1,6 @@
|
||||
;(function($,_,undefined){"use strict";ips.controller.mixin('contentListing','core.global.core.table',true,function(){this._rowSelector='li';this.after('initialize',function(){this.on('menuItemSelected','[data-role="sortButton"]',this.changeSorting);this.on('change','[data-role="moderation"]',this.selectRow);this.on('paginationClicked',this.frontPaginationClicked);this.on('markTableRead',this.markAllRead);$(document).on('markTableRowRead',_.bind(this.markRowRead,this));$(document).on('markAllRead',_.bind(this.markAllRead,this));$(document).on('updateTableURL',_.bind(this.updateTableURL,this));$(document).on('moderationSubmitted',_.bind(this.clearLocalStorage,this));});this.after('setup',function(){this._tableID=this.scope.attr('data-tableID');this._storeID='table-'+this._stateKey;if(this.scope.attr('data-dummyLoadingSelector')){this._rowSelector=this.scope.attr('data-dummyLoadingSelector');}
|
||||
this._findCheckedRows();this.on('pageActionReady',this._findCheckedRows);});this.before('_handleStateChanges',function(state){ips.utils.analytics.trackPageView(state.url);});this.before('_getResults',function(){this._setTableLoading(true);});this.after('_getResultsAlways',function(){this._setTableLoading(false);});this.after('_updateTable',function(){this.scope.find('[data-ipsPageAction]').trigger('refresh.pageAction');this.scope.find('[data-role="tableRows"]').css({opacity:"0.0001"}).animate({opacity:"1"});this._findCheckedRows();});this._findCheckedRows=function(){if(!this.scope.find('input[type="checkbox"]').length){return;}
|
||||
var dataStore=ips.utils.db.get('moderation',this._storeID)||{};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-rowid="'+key+'"]').length){self.scope.find('[data-rowid="'+key+'"]').addClass('ipsData__item--selected').find('input[type="checkbox"][data-role="moderation"]').attr('checked',true).trigger('change');}else{sizeOtherPage++;pageAction.trigger('addManualItem.pageAction',{id:'moderate['+key+']',actions:val});}});if(this.scope.find('[data-ipsAutoCheck]')){this.scope.find('[data-ipsAutoCheck]').trigger('setInitialCount.autoCheck',{count:sizeOtherPage});}}};this.clearLocalStorage=function(){ips.utils.db.remove('moderation',this._storeID);};this._showLoading=function(){return _.isUndefined(this.scope.attr('data-dummyLoading'));};this.markAllRead=function(){this.scope.find('.ipsSubList__item--unread').removeClass('ipsSubList__item--unread').addClass('ipsSubList__item--read');this.scope.find('[data-ips-unread]').removeAttr('data-ips-unread').attr('data-ips-read','');this.elem.querySelectorAll('.ipsIndicator').forEach(unreadIcon=>unreadIcon.remove())};this.markRowRead=function(e,data){if(_.isUndefined(data.tableID)||data.tableID!=this._tableID){return;}
|
||||
var dataStore=ips.utils.db.get('moderation',this._storeID)||{};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-rowid="'+key+'"]').length){self.scope.find('[data-rowid="'+key+'"]').addClass('ipsData__item--selected').find('input[type="checkbox"][data-role="moderation"]').attr('checked',true).trigger('change');}else{sizeOtherPage++;pageAction.trigger('addManualItem.pageAction',{id:'moderate['+key+']',actions:val});}});if(this.scope.find('[data-ipsAutoCheck]')){this.scope.find('[data-ipsAutoCheck]').trigger('setInitialCount.autoCheck',{count:sizeOtherPage});}}};this.clearLocalStorage=function(){ips.utils.db.remove('moderation',this._storeID);};this._showLoading=function(){return _.isUndefined(this.scope.attr('data-dummyLoading'));};this.markAllRead=function(){this.scope.find('.ipsSubList__item--unread').removeClass('ipsSubList__item--unread').addClass('ipsSubList__item--read');this.scope.find('[data-ips-unread]').removeAttr('data-ips-unread').attr('data-ips-read','');this.scope.find('[data-ips-badge-new]').remove();this.elem.querySelectorAll('.ipsIndicator').forEach(unreadIcon=>unreadIcon.remove())};this.markRowRead=function(e,data){if(_.isUndefined(data.tableID)||data.tableID!=this._tableID){return;}
|
||||
this.scope.find('[data-rowID="'+data.rowID+'"]').removeAttr('data-ips-unread').attr('data-ips-read','');};this.updateTableURL=function(e,data){this.updateURL(data);};this.frontPaginationClicked=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+'px'});};this.selectRow=function(e){var row=$(e.currentTarget).closest('.ipsData__item');var rowID=row.attr('data-rowID');var dataStore=ips.utils.db.get('moderation',this._storeID)||{};var rowActions=row.find('[data-role="moderation"]').attr('data-actions');row.toggleClass('ipsData__item--selected',$(e.currentTarget).is(':checked'));if(rowID){if($(e.currentTarget).is(':checked')){if(_.isUndefined(dataStore[rowID])){dataStore[rowID]=rowActions;}}else{delete dataStore[rowID];}
|
||||
if(_.size(dataStore)){ips.utils.db.set('moderation',this._storeID,dataStore,undefined,Date.now()/1000+86400);}else{ips.utils.db.remove('moderation',this._storeID);}}};this._setTableLoading=function(loading){var rowElem=this.scope.find('[data-role="tableRows"]');var rows=rowElem.find('> '+this._rowSelector);if(_.isUndefined(this.scope.attr('data-dummyLoading'))){this._basicLoading(loading);return;}
|
||||
if(!loading||!rowElem.length||!rows.length){return;}
|
||||
@@ -15,19 +15,22 @@ this.updateURL({sortby:sortBy,sortdirection:sortDirection,page:1});};this._getSo
|
||||
this.setup();},setup:function(){if(ips.utils.serviceWorker.supported){ips.utils.serviceWorker.registerServiceWorker('front',!_.isUndefined(ips.utils.cookie.get('loggedIn')));}
|
||||
if(!ips.utils.events.isTouchDevice()){this.scope.addClass('ipsApp_noTouch');}
|
||||
ips.utils.cookie.set('ipsTimezone',new Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC");this._checkAndClearAutosave();if(!ips.getSetting('memberID')&&ips.utils.url.getParam('_fromLogout')){ips.utils.db.removeByType('editorSave');}
|
||||
if($('#elInlineMessage').length){var dialogRef=ips.ui.dialog.create({showFrom:'#inbox',content:'#elInlineMessage',title:$('#elInlineMessage').attr('title')});setTimeout(function(){dialogRef.show();},800);}
|
||||
if($('#elInlineMessage').length){var dialogRef=ips.ui.dialog.create({content:'#elInlineMessage',title:$('#elInlineMessage').attr('title')});setTimeout(function(){dialogRef.show();},800);}
|
||||
ips.utils.links.updateExternalLinks(this.scope);this._upgradeOldEmbeds(this.scope);if(!ips.getSetting('viewProfiles')){this._removeProfileLinks();}},updateExternalLinks:function(e,data){ips.utils.links.updateExternalLinks(data);},checkOldEmbeds:function(e,data){this._upgradeOldEmbeds(data);},_removeProfileLinks:function(){this.scope.find('a[data-mentionid],a[href*="controller=profile"]').replaceWith(function(){return $(this).contents();});},_upgradeOldEmbeds:function(element){if(_.isUndefined(element)){return;}
|
||||
var oldEmbeds=element.find('[data-embedcontent]:not([data-controller], [data-embed-src])');var toRefresh=[];if(oldEmbeds.length){oldEmbeds.each(function(){$(this).attr('data-controller','core.front.core.autoSizeIframe');toRefresh.push(this);Debug.log("Upgraded old embed");});$(document).trigger('contentChange',[jQuery([]).pushStack(toRefresh)]);}},_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');}},confirmSomething:function(e){e.preventDefault();var elem=$(e.currentTarget);var customMessage=$(e.currentTarget).attr('data-confirmMessage');var subMessage=$(e.currentTarget).attr('data-confirmSubMessage');var icon=$(e.currentTarget).attr('data-confirmIcon');ips.ui.alert.show({type:'confirm',icon:(icon)?icon:'warn',message:(customMessage)?customMessage:ips.getString('generic_confirm'),subText:(subMessage)?subMessage:'',callbacks:{ok:function(){window.location=elem.attr('href')+'&wasConfirmed=1';}}});},broadcastChannelEvent(ev){if(ev.data.command==="colorScheme"){document.dispatchEvent(new CustomEvent("ips:colorScheme",{bubbles:true,detail:{scheme:ev.data.value}}));}},colorScheme(ev){if(document.documentElement.matches('[data-ips-scheme-toggle="false"]')){return;}
|
||||
let value=ev.detail.scheme;document.querySelectorAll('[data-ips-prefers-color-scheme]').forEach(el=>{if(el.matches('[data-ips-prefers-color-scheme='+value+']')){el.setAttribute('aria-current','true');}else{el.removeAttribute('aria-current');}});document.documentElement.dataset.ipsSchemeActive=value;if(value==='system'){document.documentElement.dataset.ipsScheme=(window.matchMedia('(prefers-color-scheme: dark)').matches)?'dark':'light';}else{document.documentElement.dataset.ipsScheme=value;}
|
||||
ips.utils.cookie.set('scheme_preference',value,true);},updatePrefersColorScheme:function(){if(document.documentElement.getAttribute('data-ips-scheme-active')==='system'){document.documentElement.setAttribute('data-ips-scheme',(window.matchMedia('(prefers-color-scheme: dark)').matches)?'dark':'light');}}});}(jQuery,_));;
|
||||
;(function($,_,undefined){"use strict";ips.controller.register('core.front.core.autoSizeIframe',{_origin:ips.utils.url.getOrigin(),_embedId:'',_iframe:null,_border:{vertical:0,horizontal:0},initialize(){if(!this.scope.is('iframe')){return;}
|
||||
this.on(window,'message',this.receiveMessage);this.on(document,'breakpointChange',this.breakpointChange);this.setup();},setup(){this._lastDims={height:0,width:0};var iframe=this.scope.get(0);iframe.style.overflow='hidden';this._getBorderAdjustment();if(this.scope.height()>800){this.scope.css({height:'800px'});}
|
||||
;(function($,_,undefined){"use strict";const PREINITIALIZED_DIMS_FLAG=Symbol('PREINITIALIZED_DIMS_FLAG');if(ips?.utils?.db?.get instanceof Function){document.querySelectorAll('iframe[data-controller*="core.front.core.autosizeiframe"][src]').forEach(embed=>{if(!embed.src||embed.src===window.location.href){return;}
|
||||
const currentDims=ips.utils.db.get("embedDimsCache",embed.src);if(typeof currentDims?.height==='number'&¤tDims.height>0){Debug.log(`(EMBED) - Filling in width and height before registering controller for embed ${embed.src}`);embed[PREINITIALIZED_DIMS_FLAG]={width:typeof currentDims.width==='number'?currentDims.width:0,height:typeof currentDims.height==='number'?currentDims.height:0};if(typeof currentDims.width==='number'&¤tDims.width>0){requestAnimationFrame(()=>{embed.style.height=currentDims.height+"px";embed.style.width=currentDims.style.width+"px";})}else{requestAnimationFrame(()=>{embed.style.height=currentDims.height+"px";});}}})}
|
||||
ips.controller.register('core.front.core.autoSizeIframe',{_origin:ips.utils.url.getOrigin(),_embedId:'',_iframe:null,_border:{vertical:0,horizontal:0},initialize(){if(!this.scope.is('iframe')){return;}
|
||||
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;}
|
||||
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._postMessage('setDimensions',{height:parseInt(data.height)});this._lastDims.height=data.height;}},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;}},ok(){this._stopReadyTimeout();this.scope.addClass('ipsEmbed_finishedLoading');this._postMessage('responsiveState',{currentIs:ips.utils.responsive.getCurrentKey()});}});}(jQuery,_));;
|
||||
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]);}}
|
||||
for(const action of['quoteComment','multiQuoteComment','rateReview','cancelEditComment']){this.on('click',`[data-action="${action}"]`,this[action]);}
|
||||
@@ -35,7 +38,7 @@ this.on('submit','form',this.submitEdit);this.on('change','input[type="checkbox"
|
||||
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 '+
|
||||
'deleteCommentLoading.comment',this.commentLoading);this.on(document,'getEditFormDone.comment saveEditCommentDone.comment '+
|
||||
'deleteCommentDone.comment',this.commentDone);this.on(document,'getEditFormDone.comment',this.getEditFormDone);this.on(document,'getEditFormError.comment',this.getEditFormError);this.on(document,'saveEditCommentDone.comment',this.saveEditCommentDone);this.on(document,'saveEditCommentError.comment',this.saveEditCommentError);this.on(document,'deleteCommentDone.comment',this.deleteCommentDone);this.on(document,'deleteCommentError.comment',this.deleteCommentError);this.on(document,'unrecommendCommentDone.comment',this.unrecommendCommentDone);this.on(document,'unrecommendCommentError.comment',this.unrecommendCommentError);this.on(document,'approveCommentLoading.comment',this.approveCommentLoading);this.on(document,'approveCommentDone.comment',this.approveCommentDone);this.on(document,'approveCommentError.comment',this.approveCommentError);this.setup();},setup:function(){this._commentID=this.scope.attr('data-commentID');this._clickHandler=_.bind(this._hideQuoteTooltip,this);this._setupIntersectionObserver();this._setupShareCommentDialog();const fragment=window.location.hash;const match=fragment.match(/#find(Review|Comment)-(\d+)/);if(match){const type=match[1]
|
||||
const commentId=match[2];const elementId=`find${type}-${commentId}`;const element=document.getElementById(elementId);if(!element){var currentUrl=new URL(window.location.href);currentUrl.searchParams.set('do',`find${type}`);currentUrl.searchParams.set(type.toLowerCase(),commentId);window.location.href=currentUrl;}}},destroy:function(){},tabChanged:function(e,data){this._menu=undefined;this.getMenu();},inlineQuote:function(){var self=this;var quoteButton=this.scope.find('[data-action="quoteComment"]');if(this._isEditing||this._quotingDisabled||!quoteButton.length){return;}
|
||||
const commentId=match[2];const elementId=`find${type}-${commentId}`;const element=document.getElementById(elementId);if(!element){const currentUrl=new URL(window.location.href);currentUrl.updateSearchParams({params:{do:`find${type}`,[type.toLowerCase()]:commentId.toString()}});window.location.href=currentUrl;}}},destroy:function(){},tabChanged:function(e,data){this._menu=undefined;this.getMenu();},inlineQuote:function(){var self=this;var quoteButton=this.scope.find('[data-action="quoteComment"]');if(this._isEditing||this._quotingDisabled||!quoteButton.length){return;}
|
||||
clearInterval(this._quoteTimeout);this._quoteTimeout=setInterval(function(){self._checkQuoteStatus();},400);},recommendComment:function(e,data){var commentHtml=$('<div>'+data.response.comment+'</div>').find('[data-controller="core.front.core.comment"]').html();this.scope.html(commentHtml).closest('.ipsEntry').addClass('ipsEntry--popular');$(document).trigger('contentChange',[this.scope]);if(ips.utils.db.isEnabled()){this.scope.find('[data-action="multiQuoteComment"]').removeClass('ipsHide');}
|
||||
this.trigger('refreshRecommendedComments',{scroll:true,recommended:data.response.recommended});},unrecommendComment:function(e,data){e.preventDefault();var url=$(e.currentTarget).attr('href');this.trigger('unrecommendComment.comment',{url:url,commentID:this._commentID});},unrecommendCommentDone:function(e,data){if(data.commentID!=this._commentID){return;}
|
||||
var commentHtml=$('<div>'+data.comment+'</div>').find('[data-controller="core.front.core.comment"]').html();console.log(commentHtml);this.scope.html(commentHtml).closest('.ipsEntry').removeClass('ipsEntry--popular').find('.ipsEntry__popularFlag').remove();ips.ui.flashMsg.show(ips.getString('commentUnrecommended'));this.trigger('removeRecommendation',{commentID:data.unrecommended});},unrecommendCommentError:function(e,data){if(data.commentID!=this._commentID){return;}
|
||||
@@ -49,7 +52,7 @@ var tooltipSize={width:tooltip.show().outerWidth(),height:tooltip.show().outerHe
|
||||
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';Debug.log(activeTabId);let commentFeed=this.scope.get(0)?.closest('[data-controller]')
|
||||
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;}
|
||||
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&©ToClipboard){copyToClipboard.onclick=e=>e.preventDefault()
|
||||
@@ -70,8 +73,7 @@ ips.ui.flashMsg.show(ilang`copied`)
|
||||
if(!shared&&ips.utils.contentViews.enabled()&&this.scope.get(0).dataset.commentapp==='forums'){shared=true;ips.getAjax()(`${location.protocol}${ips.getSetting("baseURL")}/?app=core&module=system&controller=ajax&do=trackPostShareIntent&commentId=${this.scope.get(0).dataset.commentid}`).done(()=>{Debug.log("Sent post share intent");})}}
|
||||
copyToClipboard.addEventListener('pointerup',cb)
|
||||
copyToClipboard.addEventListener('pointercancel',()=>copyToClipboard.removeEventListener('pointerup',cb))
|
||||
copyToClipboard.addEventListener('pointerleave',()=>copyToClipboard.removeEventListener('pointerup',cb))})}else if(copyToClipboard){Debug.log(`Converting share copy to clipboard links to contenteditable links`)
|
||||
copyToClipboard.setAttribute('hidden','')
|
||||
copyToClipboard.addEventListener('pointerleave',()=>copyToClipboard.removeEventListener('pointerup',cb))})}else if(copyToClipboard){copyToClipboard.setAttribute('hidden','')
|
||||
const shareArea=document.createElement('span')
|
||||
const wrap=document.createElement('span')
|
||||
if(copyToClipboard.querySelector(':scope > i')){const icon=copyToClipboard.querySelector(':scope > i')
|
||||
@@ -91,10 +93,10 @@ document.getSelection().addRange(range)
|
||||
try{if(document.execCommand instanceof Function){document.execCommand?.('copy')
|
||||
ips.ui.flashMsg.show(ips.getString('copied'))}}catch(e){}}}},setMultiQuote:function(e,data){var selector='[data-commentApp="'+data.contentapp+'"]';selector+='[data-commentType="'+data.contenttype+'"]';selector+='[data-commentID="'+data.contentcommentid+'"]';if(this.scope.is(selector)){if(!_.isNull(e)&&e.type=='setMultiQuoteEnabled'){this.scope.find('[data-action="multiQuoteComment"]').removeClass('ipsButton--simple').addClass('ipsButton--secondary').attr('data-mqActive',true).html(ips.templates.render('core.posts.multiQuoteOn'));}else if(_.isNull(e)||e.type=='setMultiQuoteDisabled'){this.scope.find('[data-action="multiQuoteComment"]').addClass('ipsButton--simple').removeClass('ipsButton--secondary').removeAttr('data-mqActive').html(ips.templates.render('core.posts.multiQuoteOff'));}}},quoteComment:function(e){e.preventDefault();if(!this._getQuoteData()){Debug.error("Couldn't get quote data");return;}
|
||||
var html=this._prepareQuote($('<div/>').html(this.scope.find('[data-role="commentContent"]').html()));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:html.html(),citeurl:$(this.elem).get(0).querySelector(".ipsEntry__date[href]")?.getAttribute('href')});},multiQuoteComment:function(e){e.preventDefault();if(!this._getQuoteData()){Debug.error("Couldn't get quote data");return;}
|
||||
var button=$(e.currentTarget);var mqActive=button.attr('data-mqActive');var html=this._prepareQuote($('<div/>').html(this.scope.find('[data-role="commentContent"]').html()));this.feedJQ().trigger((mqActive)?'removeMultiQuote.comment':'addMultiQuote.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:html.html(),button:button.attr('data-mqId'),citeurl:$(this.elem).get(0).querySelector(".ipsEntry__date[href]")?.getAttribute('href')});if(mqActive){button.removeClass('ipsButton--secondary').addClass('ipsButton--simple').removeAttr('data-mqActive').html(ips.templates.render('core.posts.multiQuoteOff'));}else{button.removeClass('ipsButton--simple').addClass('ipsButton--secondary').attr('data-mqActive',true).html(ips.templates.render('core.posts.multiQuoteOn'));}},editComment:function(e){e.preventDefault();this._commentContents=this.scope.find('[data-role="commentContent"]').html();var url=$(e.currentTarget).attr('href');this.scope.find('[data-role="commentContent"]').removeClass('ipsRichText');this.trigger('getEditForm.comment',{url:url,commentID:this._commentID});},cancelEditComment:function(e){e.preventDefault();var self=this;ips.ui.alert.show({type:'verify',icon:'warn',message:ips.getString('cancel_edit_confirm'),subText:'',buttons:{yes:ips.getString('yes'),no:ips.getString('no')},callbacks:{yes:function(){ips.ui.editorv5.destruct(self.scope.find('[data-ipseditorv5]'));self.scope.find('[data-role="commentContent"]').html(self._commentContents);self.scope.find('[data-role="commentControls"], [data-action="expandTruncate"]').show();self.scope.find('[data-action="editComment"]').parent('li').show();self.scope.find('[data-role="commentContent"]').addClass('ipsRichText');$(document).trigger('contentChange',[self.scope]);}}});},submitEdit:function(e){e.preventDefault();e.stopPropagation();var form=this.scope.find('form');var url=form.attr('action');var data=form.serialize();form.find('[data-action="cancelEditComment"]').remove();form.find('[type="submit"]').prop('disabled',true).text(ips.getString('saving'));this.trigger('saveEditComment.comment',{form:data,url:url,commentID:this._commentID});},commentLoading:function(e,data){if(data.commentID!=this._commentID){return;}
|
||||
var button=$(e.currentTarget);var mqActive=button.attr('data-mqActive');var html=this._prepareQuote($('<div/>').html(this.scope.find('[data-role="commentContent"]').html()));this.feedJQ().trigger((mqActive)?'removeMultiQuote.comment':'addMultiQuote.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:html.html(),button:button.attr('data-mqId'),citeurl:$(this.elem).get(0).querySelector(".ipsEntry__date[href]")?.getAttribute('href')});if(mqActive){button.removeClass('ipsButton--secondary').addClass('ipsButton--simple').removeAttr('data-mqActive').html(ips.templates.render('core.posts.multiQuoteOff'));}else{button.removeClass('ipsButton--simple').addClass('ipsButton--secondary').attr('data-mqActive',true).html(ips.templates.render('core.posts.multiQuoteOn'));}},editComment:function(e){e.preventDefault();this._commentContents=this.scope.find('[data-role="commentContent"]').html();var url=$(e.currentTarget).attr('href');this.trigger('getEditForm.comment',{url:url,commentID:this._commentID});},cancelEditComment:function(e){e.preventDefault();var self=this;ips.ui.alert.show({type:'verify',icon:'warn',message:ips.getString('cancel_edit_confirm'),subText:'',buttons:{yes:ips.getString('yes'),no:ips.getString('no')},callbacks:{yes:function(){ips.ui.editorv5.destruct(self.scope.find('[data-ipseditorv5]'));self.scope.find('[data-role="commentContent"]').html(self._commentContents);self.scope.find('[data-role="commentControls"], [data-action="expandTruncate"]').show();self.scope.find('[data-action="editComment"]').parent('li').show();self.scope.find('[data-role="commentContent"]').addClass('ipsRichText');$(document).trigger('contentChange',[self.scope]);}}});},submitEdit:function(e){e.preventDefault();e.stopPropagation();var form=this.scope.find('form');var url=form.attr('action');var data=form.serialize();form.find('[data-action="cancelEditComment"]').remove();form.find('[type="submit"]').prop('disabled',true).text(ips.getString('saving'));this.trigger('saveEditComment.comment',{form:data,url:url,commentID:this._commentID});},commentLoading:function(e,data){if(data.commentID!=this._commentID){return;}
|
||||
var commentLoading=this.scope.find('[data-role="commentLoading"]');commentLoading.removeClass('ipsHide');},commentDone:function(e,data){if(data.commentID!=this._commentID){return;}
|
||||
this.scope.find('[data-role="commentLoading"]').addClass('ipsHide');},getEditFormDone:function(e,data){if(data.commentID!=this._commentID){return;}
|
||||
var self=this;var showForm=_.once(function(){self._isEditing=true;self.scope.find('[data-action="expandTruncate"], [data-role="commentControls"]').hide();self.scope.find('[data-action="editComment"]').parent('li').hide();self.scope.find('[data-role="commentContent"]').html(data.response);$(document).trigger('contentChange',[self.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;}
|
||||
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.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;}
|
||||
@@ -127,9 +129,12 @@ 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,e=>{const{elem}=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;}
|
||||
const widget=ips.ui.editorv5.getObj(elem);if(!widget){return;}
|
||||
const empty=!widget.getInstanceHTML();submit.forEach(item=>{if(empty){item.setAttribute('disabled','');}else{item.removeAttribute('disabled');}})})}},clearLocalStorage:function(){ips.utils.db.remove('moderation',$(document).find("[data-feedID]").attr('data-feedID'));},destroy:function(){$(document).off('click','[data-role="multiQuote_'+this._containerID+'"]',this._boundMQ);$(document).off('click','[data-action="clearQuoted_'+this._containerID+'"]',this._boundCMQ);this._stopPolling();},_getUrlParams:function(){const sort=this._getSortValue();const obj={sortby:sort.by||'',sortdirection:sort.order||'',};obj[this._pageParam]=ips.utils.url.getPageNumber(this._pageParam)||1;return obj;},_getSortValue:function(){return{by:'',order:''};},stateChange(e){if(e.detail?.type==='replace'||!('commentFeed'in ips.utils.history.getState())){return;}
|
||||
$(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;}
|
||||
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;}}}
|
||||
return false;}
|
||||
const empty=!nodeHasContent(instance.state.doc);submit.forEach(item=>{if(empty){item.setAttribute('disabled','');}else{item.removeAttribute('disabled');}})},100));}},clearLocalStorage:function(){ips.utils.db.remove('moderation',$(document).find("[data-feedID]").attr('data-feedID'));},destroy:function(){$(document).off('click','[data-role="multiQuote_'+this._containerID+'"]',this._boundMQ);$(document).off('click','[data-action="clearQuoted_'+this._containerID+'"]',this._boundCMQ);this._stopPolling();},_getUrlParams:function(){const sort=this._getSortValue();const obj={sortby:sort.by||'',sortdirection:sort.order||'',};obj[this._pageParam]=ips.utils.url.getPageNumber(this._pageParam)||1;return obj;},_getSortValue:function(){return{by:'',order:''};},stateChange(e){if(e.detail?.type==='replace'||!('commentFeed'in ips.utils.history.getState())){return;}
|
||||
const state={data:ips.utils.history.getState('commentFeed'),url:window.location.href}
|
||||
if(typeof state.data!=="object"){return;}
|
||||
const lastChange=e.detail.type==='pop'?'pop':ips.utils.history.getLastChangeType()
|
||||
@@ -146,7 +151,7 @@ this._setUpMultiQuote();$(document).trigger('contentChange',[this.scope]);this._
|
||||
return;}
|
||||
Debug.error("Ajax request failed ("+textStatus+"): "+errorThrown);Debug.error(jqXHR.responseText);}else{window.location=this._getURL();}},_getResultsAlways:function(){},_setLoading:function(status){var commentFeed=this.scope.find('[data-role="commentFeed"]');if(status){if(!this._overlay){this._overlay=$('<div/>').addClass('ipsLoading').hide();ips.getContainer().append(this._overlay);}
|
||||
var dims=ips.utils.position.getElemDims(commentFeed);var position=ips.utils.position.getElemPosition(commentFeed);this._overlay.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()});commentFeed.animate({opacity:"0.5"});}else{}},_paginatedOnce:false,paginationClick:function(e,data){data.originalEvent.preventDefault();if(data.pageNo!==this._urlParams[this._pageParam]){Debug.log("Possibly collapsing elements as the user navigated away from the first page");if(parseInt(`${this._urlParams[this._pageParam]}`)===1&&!this._paginatedOnce){document.querySelectorAll(`[data-feedid="${this._commentFeedID}"] [data-collapse-off-first-page]`).forEach(toCollapse=>{toCollapse.dispatchEvent(new CustomEvent("ips:truncateCollapse",{bubbles:true}));})}
|
||||
this._paginatedOnce=true;var urlObj=ips.utils.url.getURIObject(data.href);var queryKey=urlObj.queryKey;if(_.isUndefined(queryKey[this._pageParam])){queryKey[this._pageParam]=data.pageNo;}
|
||||
this._paginatedOnce=true;const urlObj=new URL(data.href,location.href);const queryKey=Object.fromEntries(urlObj.searchParams.entries());if(!(this._pageParam in queryKey)){queryKey[this._pageParam]=data.pageNo;}
|
||||
this._seoPagination=data.seoPagination;this._updateURL(queryKey,()=>{const elem=this.elem.querySelector(`.ipsButtonBar--top`)
|
||||
if(!(elem instanceof HTMLElement)){Debug.warn("Couldn't find the .ipsButtonBar--top or .ipsButtonBar--bottom pagination container inside the comment feed controller. This is likely a theme error that needs to be addressed so that the content feed can be scrolled to the top or bottom after pagination")
|
||||
return;}
|
||||
@@ -156,12 +161,13 @@ window.scrollBy({top:boundingBox.top-30,behavior:'smooth'})});}},_updateURL:func
|
||||
let newUrl=this._getURL();if(newUrl.slice(-1)==='?'){newUrl=newUrl.substring(0,newUrl.length-1);}
|
||||
if(this._seoPagination===true){newUrl=ips.utils.url.pageParamToPath(newUrl,this._pageParam,this.historyState[this._pageParam]);}
|
||||
ips.utils.history.pushState(this.historyState,'commentFeed',newUrl);this._updateDoneCallback=callback;},_updateState(newParams){Object.assign(this._urlParams,newParams);this.historyState={...this._urlParams}
|
||||
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']);for(const param in this._urlParams){if(this._urlParams[param]&&!skipParams.has(param)&&!(param===this._pageParam&&Number(this._urlParams[this._pageParam])<=1)){urlObj.searchParams.set(param,this._urlParams[param])}}
|
||||
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];}
|
||||
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(){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=this.scope.find('[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;}
|
||||
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;}
|
||||
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;}
|
||||
if(this._pollingPaused){Debug.log('Window blurred, delaying poll until focused...');this._pollOnUnpaused=true;return;}
|
||||
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;}
|
||||
@@ -184,15 +190,15 @@ form.find("[data-role='commentFormError']").each(function(){$(this).remove();});
|
||||
ips.ui.flashMsg.show(ips.getString('mergedConncurrentPosts'));$(document).trigger('contentChange',[self.scope]);}else{if(response.postedByLoggedInMember){self.trigger('ipsDataLayer',{_key:'content_comment',_properties:response.dataLayer});}
|
||||
self.trigger('addToCommentFeed',{content:response.content,totalItems:response.total,feedID:self._commentFeedID,scrollToItem:true});if(response.message){ips.ui.flashMsg.show(response.message);}
|
||||
if(self.scope.find('[data-role="replyArea"] input[name="guest_name"]').length){self.scope.find('[data-role="replyArea"] input[name="guest_name"]').val('');self.scope.find('[data-role="replyArea"] [data-ipsEditorv5]').find('.ipsComposeArea_dummy').hide().end().find('[data-role="mainEditorArea"]').show().end().closest('.ipsComposeArea').removeClass('ipsComposeArea_minimized').find('[data-ipsEditor-toolList]').show();}
|
||||
form.find("[data-role='commentFormError']").each(function(){$(this).remove();});if(autoFollow.length){self.trigger('followingItem',{feedID:self.scope.attr('data-feedID'),following:autoFollow.is(':checked')});}}
|
||||
form.find("[data-role='commentFormError']").each(function(){$(this).remove();});if(autoFollow.length){self.trigger('followingItem',{feedID:self.scope.attr('data-follow-area-id')||self.scope.attr('data-feedID'),following:autoFollow.is(':checked')});}}
|
||||
self._clearNotifications();}).fail(function(jqXHR,textStatus,errorThrown){if(Debug.isEnabled()){Debug.error("Posting new reply failed: "+textStatus);Debug.log(jqXHR);Debug.log(errorThrown);}else{form.attr('data-noAjax','true');form.attr('action',form.attr('action')+((!form.attr('action').match(/\?/))?'?failedReply=1':'&failedReply=1'));form.submit();}}).always(function(){submitRestorations.forEach(cb=>cb());});},loadNewPosts:function(e){e?.preventDefault?.();this._importNewReplies();},findCommentInFeed(commentId){const commentSelector=`[data-commentid="${commentId}"]`;const comment=this.elem.querySelector(`[data-role="commentFeed"] ${commentSelector}`);if(comment){return comment;}else if(this.elem.dataset.feedid){const feedSelector=`[data-feedid="${this.elem.dataset.feedid}"]`;return document.querySelector(`${feedSelector}${commentSelector}, ${feedSelector} ${commentSelector}`)||null;}
|
||||
return null;},addToCommentFeed(e,data){if(typeof data?.content!=="string"||data.feedID!==this._commentFeedID){return;}
|
||||
const content=$('<div/>').append(data.content);const div=content.get(0);const comment=content.find('.js-ipsEntry');let commentFeed=this.scope.find('[data-role="commentFeed"]');if(commentFeed.find('[data-role="moderationTools"]').length){commentFeed=commentFeed.find('[data-role="moderationTools"]');}
|
||||
this.scope.find('[data-role="noComments"]').remove();const actualContent=div.querySelector(`[data-ips-hook="postWrapper"]`)
|
||||
const content=$('<div/>').append(typeof data.content==='string'?data.content:'');const comment=content.find('.js-ipsEntry');if(comment.length){let commentFeed=this.scope.find('[data-role="commentFeed"]');if(commentFeed.find('[data-role="moderationTools"]').length){commentFeed=commentFeed.find('[data-role="moderationTools"]');}
|
||||
this.scope.find('[data-role="noComments"]').remove();const actualContent=comment.get(0)
|
||||
const id=parseInt(actualContent?.querySelector(`[data-commentid]`)?.dataset.commentid);const existing=Number.isInteger(id)&&this.findCommentInFeed(id);if(existing&&existing.parentElement){existing.parentElement.replaceChild(existing,actualContent);}else{commentFeed.append(comment.css({opacity:"0.001"}));const newItemTop=comment.offset().top;const windowScroll=$(window).scrollTop();const viewHeight=$(window).height();function _showComment(){comment.css({opacity:"1"});ips.utils.anim.go('fadeInDown',comment.filter(':not(.ipsHide)'));}
|
||||
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();}
|
||||
if(ips.utils.db.isEnabled()){const buttons=comment.find('[data-action="multiQuoteComment"]');buttons.hide().removeClass('ipsHide');ips.utils.anim.go('fadeIn',buttons);}}
|
||||
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;}
|
||||
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;}
|
||||
@@ -218,12 +224,13 @@ for(const[timeEl,timeStamp]of timestampMap.entries()){const key="time_"+timeStam
|
||||
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($,_){"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)}}
|
||||
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());})
|
||||
this._messagesEnabled=this.scope.find('[data-notificationType="inbox"]').length;this._setInterval(this._pollTimeout);this._doInitialCheck();},_useRealtime(){if(!this._usingRealtime){this._stopPolling();this._usingRealtime=true;}},storageChange(e){var event=e.originalEvent;if(event.key!=='notifications.'+ips.getSetting('baseURL')){return;}
|
||||
if(this._debugPolling){Debug.log('Notifications: updating instantly from storage event');}
|
||||
try{var data=JSON.parse(event.newValue);var counts=this._getCurrentCounts();this._updateIcons({messages:parseInt(data.messages),notifications:parseInt(data.notifications)},counts);}catch(err){}},windowVisibilityChange(){var hiddenProp=ips.utils.events.getVisibilityProp();if(!_.isUndefined(hiddenProp)&&!document[hiddenProp]){this._updateBrowserTitle(0);if(!this._usingRealtime){this._pollMultiplier=1;this._windowInactivePoll=0;if(this._paused){this._checkNotifications();this._setInterval(this._pollTimeout);}
|
||||
if(this._debugPolling){Debug.log("Notifications: Resetting inactive poll.");}}}},_setInterval(timeoutInSecs){clearInterval(this._interval);this._interval=setInterval(_.bind(this._checkNotifications,this),timeoutInSecs*1000);},_doInitialCheck(){const storage=ips.utils.db.get('notifications',ips.getSetting('baseURL'));const counts=this._getCurrentCounts();if(!storage||typeof storage!=="object"){return;}
|
||||
if(this._debugPolling){Debug.log("Notifications: Resetting inactive poll.");}}}},_setInterval(timeoutInSecs){clearInterval(this._interval);if(this._usingRealtime){return;}
|
||||
this._interval=setInterval(_.bind(this._checkNotifications,this),timeoutInSecs*1000);},_doInitialCheck(){const storage=ips.utils.db.get('notifications',ips.getSetting('baseURL'));const counts=this._getCurrentCounts();if(!storage||typeof storage!=="object"){return;}
|
||||
if((this._messagesEnabled&&counts.messages>storage.messages)||counts.notifications>storage.notifications){if(this._debugPolling){Debug.log("Notifications: bubbles reporting higher counts for notifications or messages.");}
|
||||
const dataToSend={notifications:storage.notifications};if(this._messagesEnabled)dataToSend.messages=storage.message
|
||||
this._doAjaxRequest(dataToSend);}},_checkNotifications(){const storage=ips.utils.db.get('notifications',ips.getSetting('baseURL'));const timestamp=ips.utils.time.timestamp();const counts=this._getCurrentCounts();const currentTimeout=this._pollTimeout*this._pollMultiplier;if(document[ips.utils.events.getVisibilityProp()]){if(this._windowInactivePoll>=3&&this._pollMultiplier===1){if(this._debugPolling){Debug.log("Notifications: Polled over 3 minutes, increasing multiplier to 2");}
|
||||
@@ -284,8 +291,7 @@ if(!data.content?.content_id||parseInt(data.content.content_id)!==this._getItemI
|
||||
if((data?.content?.comment_id||null)!==this._getCommentId()){return;}
|
||||
if('count'in data&&'score'in data){if(typeof data.blurb!=="string"||this.scope.get(0).querySelector(`[data-action='reactLaunch'].ipsReact_reacted`)){data.blurb=await this._fetchBlurb();}
|
||||
if(typeof data.blurb!=="string"){return;}
|
||||
this._updateReaction(data);}},async _fetchBlurb(){try{const reactionUrl=this.scope.get(0).querySelector(`[data-role='reaction'][href]`)?.getAttribute('href');if(!reactionUrl)return null;let url=new URL(reactionUrl);url.searchParams.delete('csrfKey');url.searchParams.delete('reaction');url.searchParams.delete('do');url.searchParams.set('do',`reactionBlurb${this._getCommentId() ? 'Comment' : ''}`)
|
||||
const response=await ips.fetch(url.toString())
|
||||
this._updateReaction(data);}},async _fetchBlurb(){try{const reactionUrl=this.scope.get(0).querySelector(`[data-role='reaction'][href]`)?.getAttribute('href');if(!reactionUrl)return null;let url=new URL(reactionUrl);url.updateSearchParams({params:{csrfKey:null,reaction:null,do:`reactionBlurb${this._getCommentId() ? "Comment" : ""}`,}});const response=await ips.fetch(url.toString())
|
||||
if(typeof response?.blurb==='string'){return response.blurb;}}catch(e){}
|
||||
return null;},_getCommentId(){if($(this.scope).get(0)?.closest(`[data-commentid]`)){return parseInt($(this.scope).get(0)?.closest(`[data-commentid]`).dataset.commentid)||null}
|
||||
return null;},_getItemId(){return parseInt($(this.scope).get(0)?.closest('[data-feedid]')?.dataset.feedid.match(/(\d+)$/)?.[1])||parseInt(document.body.dataset?.pageid)||null},clickLaunchReaction(){if(!ips.utils.events.isTouchDevice()||this._singleReaction){return;}
|
||||
|
||||
Reference in new issue
Block a user