1;(function($){"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',this.markRowRead.bind(this));$(document).on('markAllRead',this.markAllRead.bind(this));$(document).on('updateTableURL',this.updateTableURL.bind(this));$(document).on('moderationSubmitted',this.clearLocalStorage.bind(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');} 2this._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;} 3var dataStore=ips.utils.db.get('moderation',this._storeID)||{};var self=this;var pageAction=this.scope.find('[data-ipsPageAction]');if(Object.keys(dataStore).length){var sizeOtherPage=0;Object.entries(dataStore).forEach(function([key,val]){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"]').prop('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 this.scope.attr('data-dummyLoading')===undefined;};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((data.tableID)===undefined||data.tableID!=this._tableID){return;} 4this.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(dataStore[rowID]===undefined){dataStore[rowID]=rowActions;}}else{delete dataStore[rowID];} 5if(Object.keys(dataStore).length){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(this.scope.attr('data-dummyLoading')===undefined){this._basicLoading(loading);return;} 6if(!loading||!rowElem.length||!rows.length){return;} 7var template='table.row.loading';if(this.scope.attr('data-dummyLoadingTemplate')){template=this.scope.attr('data-dummyLoadingTemplate');} 8var 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}));} 9this.scope.find('[data-role="tableRows"]').html(newRows.join(''));};this._basicLoading=function(loading){var rowElem=this.scope.find('[data-role="tableRows"]');if(!rowElem.length){return;} 10if(!this._tableOverlay){this._tableOverlay=$('<div/>').addClass('ipsLoading').hide();ips.getContainer().append(this._tableOverlay);} 11if(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(data.selectedItemID===undefined){return;} 12var 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');} 13this.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));; 14;(function($){"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);
14this.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);} 15this.setup();},setup:function(){if(ips.utils.serviceWorker.supported){ips.utils.serviceWorker.registerServiceWorker('front',ips.utils.cookie.get('loggedIn')!==undefined);} 16if(!ips.utils.events.isTouchDevice()){this.scope.addClass('ipsApp_noTouch');} 17ips.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');} 18if($('#elInlineMessage').length){var dialogRef=ips.ui.dialog.create({content:'#elInlineMessage',title:$('#elInlineMessage').attr('title')});setTimeout(function(){dialogRef.show();},800);} 19ips.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(element===undefined){return;} 20var 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]);} 21ips.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;} 22let 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;} 23ips.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));; 24;(function($){"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;} 25const 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";});}}})} 26ips.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;} 27this.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});}}} 28var iframe=this.scope.get(0);
28iframe.style.overflow='hidden';this._getBorderAdjustment();if(this.scope.height()>800){this.scope.css({height:'800px'});} 29this._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;} 30this._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(function(){this._postMessage('ready');}.bind(this),100);setTimeout(function(){this._stopReadyTimeout();}.bind(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;} 31try{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;} 32this._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(Object.assign(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={};for(const opt of options){if(data.options['data-ipsdialog-'+opt.toLowerCase()]!==undefined){dialogOptions[opt]=data.options['data-ipsdialog-'+opt.toLowerCase()];}};if(dialogOptions['url']===undefined){dialogOptions['url']=data.url;} 33var 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));; 34;(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});}}});}());; 35;(function($){"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]);}} 36for(const action of['quoteComment','multiQuoteComment','rateReview','cancelEditComment']){this.on('click',`[data-action="${action}"]`,this[action]);} 37this.on('submit','form',this.submitEdit);this.on('change','input[type="checkbox"][data-role="moderation"]',this.commentCheckbox);this.elem.addEventListener('ipsCalcQuote',()=>
37this.inlineQuote()) 38this.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 '+ 39'deleteCommentLoading.comment',this.commentLoading);this.on(document,'getEditFormDone.comment saveEditCommentDone.comment '+ 40'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=this._hideQuoteTooltip.bind(this);this._setupIntersectionObserver();this._setupShareCommentDialog();const fragment=window.location.hash;const match=fragment.match(/#find(Review|Comment)-(\d+)/);if(match){const type=match[1] 41const 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;} 42let activeReviewsTab=document.querySelector('[data-controller="core.front.core.commentsWrapper"] i-tabs [id$="_reviews"][aria-selected="true"]');if(activeReviewsTab){return;} 43self._checkQuoteStatus();},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');} 44this.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;} 45var 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;} 46window.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;} 47if(ancestor&&ancestor.closest('.ipsCode').length){selectedText="<pre class='ipsCode prettyprint'>"+selectedText+"</pre>";}else if(!selectedText.startsWith('<')){selectedText='<p>'+selectedText+'</p>';} 48if(this._selectedText===selectedText){return;} 49this._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||typeof range!=="object"||range===null||range.type===undefined){Debug.log("No selection found");return;} 50if(!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);} 51if(range.type==='outside'){var boundingBox=range.range.getBoundingClientRect();var offset=this.scope.offset();
51position.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);} 52tooltip[0].showPopover();var tooltipSize={width:tooltip.outerWidth(),height:tooltip.outerHeight()};var leftAdjustment=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);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);} 53const feed=document.querySelector(`[data-feedid=${this.elem.dataset.feedid}][data-controller*="core.front.core.commentFeed"]`);if(feed){return $(feed);} 54Debug.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`);} 55Debug.warn(this.elem);return $(this.elem.closest(`[data-controller*="core.front.core.commentFeed"]`)||this.elem);},quoteSelection:function(e){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')});} 56this._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]') 57while(commentFeed&&!commentFeed.dataset.controller?.includes('core.front.core.commentFeed')){commentFeed=commentFeed.parentElement?.closest('[data-controller]')} 58const menuLink=(commentFeed||document).querySelector('#'+activeTabId+`_${this.scope.get(0)?.dataset['commentid']} [popovertarget]`);this._menu=menuLink?document.querySelector('#'+menuLink.getAttribute('popovertarget')):null;} 59return 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() 60copyToClipboard?.addEventListener('pointerdown',async e=>{e.preventDefault();const href=copyToClipboard.getAttribute('href');const cb=async e=>{copyToClipboard.removeEventListener('pointerup',cb) 61if(window.navigator?.clipboard?.writeText instanceof Function){e.preventDefault() 62await window.navigator.clipboard.writeText(href);}else{const fakeElement=document.createElement('span') 63fakeElement.innerText=href;document.body.appendChild(fakeElement) 64const range=new Range();range.setStart(fakeElement,0)
65range.setEnd(fakeElement,fakeElement.childNodes.length) 66const originalRanges=[] 67for(let i=0;i<document.getSelection().rangeCount;i++){originalRanges.push(document.getSelection().getRangeAt(i))} 68document.getSelection().removeAllRanges() 69document.getSelection().addRange(range) 70document.execCommand('copy') 71fakeElement.remove();document.getSelection().removeAllRanges() 72for(const range of originalRanges){document.getSelection().addRange(range)}} 73ips.ui.flashMsg.show(ilang`copied`) 74if(!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");})}} 75copyToClipboard.addEventListener('pointerup',cb) 76copyToClipboard.addEventListener('pointercancel',()=>copyToClipboard.removeEventListener('pointerup',cb)) 77copyToClipboard.addEventListener('pointerleave',()=>copyToClipboard.removeEventListener('pointerup',cb))})}else if(copyToClipboard){copyToClipboard.setAttribute('hidden','') 78const shareArea=document.createElement('span') 79const wrap=document.createElement('span') 80if(copyToClipboard.querySelector(':scope > i')){const icon=copyToClipboard.querySelector(':scope > i') 81icon.dataset.ipstooltip='' 82icon.setAttribute('title',ips.getString('core_comment_share_copy_prompt')) 83wrap.appendChild(icon) 84wrap.append(document.createTextNode('\u00a0'))} 85wrap.appendChild(shareArea) 86wrap.classList.add('ipsPageActions__mainLink') 87wrap.dataset.role='shareButton' 88shareArea.innerText=copyToClipboard.getAttribute('href') 89copyToClipboard.parentElement.insertBefore(wrap,copyToClipboard) 90wrap.onclick=()=>{const range=new Range();range.setStart(shareArea,0) 91range.setEnd(shareArea,shareArea.childNodes.length) 92document.getSelection().removeAllRanges() 93document.getSelection().addRange(range) 94try{if(document.execCommand instanceof Function){document.execCommand?.('copy') 95ips.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(e!==null&&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(e===null||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;} 96var 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;} 97var 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')}
97,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;} 98var commentLoading=this.scope.find('[data-role="commentLoading"]');commentLoading.removeClass('ipsHide');},commentDone:function(e,data){if(data.commentID!=this._commentID){return;} 99this.scope.find('[data-role="commentLoading"]').addClass('ipsHide');},getEditFormDone:function(e,data){if(data.commentID!=this._commentID){return;} 100let called=false;const showForm=()=>{if(called)return;called=true;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;} 101window.location=data.url;},saveEditCommentDone:function(e,data){if(data.commentID!=this._commentID){return;} 102ips.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;} 103ips.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;} 104this.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;} 105var 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');} 106ips.ui.flashMsg.show(ips.getString('commentApproved'));},approveCommentError:function(e,data){if(data.commentID!=this._commentID){return;} 107window.location=data.url;},deleteComment:function(e){e.preventDefault();var url=$(e.currentTarget).attr('href');var commentData=this._getQuoteData();var eventData=Object.assign(commentData,{url:url,commentID:this._commentID});ips.ui.alert.show({type:'confirm',icon:'warn',message:ips.getString('delete_confirm'),callbacks:{ok:()=>{this.feedJQ().trigger('deleteComment.comment',eventData);}}});},deleteCommentDone:function(e,data){if(data.commentID!=this._commentID){return;} 108var 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');} 109toHide.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);} 110if(deleteLink.attr('data-showOnDelete')){toShow=this.scope.find(deleteLink.attr('data-showOnDelete'));ips.utils.anim.go('fadeIn',toShow);} 111this.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;} 112window.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();} 113html.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>');});} 114html.find('.ipsCode[data-ips-text-highlighted="yes"]').each(function(){const text=this.innerText;this.innerHTML='';this.innerText=text;this.removeAttribute('data-ips-text-highlighted');this.classList.remove('hljs');});return html;},_getQuoteData:function(){if(!this._quoteData){try{this._quoteData=JSON.parse(this.scope.attr('data-quoteData'));return this._quoteData;}catch(err){Debug.log("Couldn't parse quote data");return{};}} 115return this._quoteData;},_setupIntersectionObserver(){const elem=this.scope.get(0);let observer;if(ips.utils.contentViews.enabled()&&elem.dataset.viewHash){const otherData=typeof elem.dataset.viewTrackingData==='string'?JSON.parse(atob(elem.dataset.viewTrackingData)):{};const key=elem.dataset.viewHash;ips.utils.contentViews.registerEntity(key,false,otherData,true,()=>{observer?.disconnect();});if(this._observer===null){const target=this.scope.get(0);if(target instanceof HTMLElement){this._observer=new IntersectionObserver(this.handleIntersection.bind(this),{rootMargin:'20px',threshold:0.8});this._observer.observe(target);observer=this._observer;}else{this._observer=false;}}}},handleIntersection(entries){const key=this.scope?.get(0).dataset.viewHash;if(key){ips.utils.contentViews.setIsViewing(key,entries[0].intersectionRatio>=0.8);}},});
115let mouseState='up';const mouseUpResolvers=new Set();function mouseUp(){return new Promise(resolve=>{if(mouseState==="up"){resolve()}else{mouseUpResolvers.add(resolve)}})} 116function clearMouseUpResolvers(){mouseState='up' 117const resolves=[...mouseUpResolvers] 118mouseUpResolvers.clear() 119resolves.forEach(resolve=>resolve())} 120document.addEventListener('pointerdown',()=>mouseState='down',{capture:true}) 121document.addEventListener('pointerup',clearMouseUpResolvers,{capture:true}) 122document.addEventListener('contextmenu',clearMouseUpResolvers,{capture:true}) 123document.addEventListener('selectionchange',ips.utils.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"]') 124if(quoteBox instanceof Element){mouseUp().then(()=>quoteBox.dispatchEvent(new CustomEvent('ipsCalcQuote',{bubbles:true}))) 125break;}}},1000))}(jQuery));; 126;(function($){"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;} 127this._boundMQ=this.doMultiQuote.bind(this);this._boundCMQ=this.clearMultiQuote.bind(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+='?';} 128if(replyForm.attr('data-noAjax')){this._pollingEnabled=false;} 129if(!('commentFeed'in ips.utils.history.getState())){this._updateState({}) 130ips.utils.history.replaceState(this.historyState,'commentFeed',window.location.href)} 131if(this.scope.attr('data-lastPage')!==undefined&&this._pollingEnabled){this._startPolling();} 132$(document).ready(()=>{this._setUpMultiQuote();this._findCheckedComments();});if(ips.getSetting('relativeDates')){this.on('updateTimestamps',this._updateTimestamps);} 133for(const ev of['ips:editorUpdated','ips:editorAfterInit']){this.elem.addEventListener(ev,ips.utils.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;} 134function nodeHasContent(node){if(node.textContent?.trim()?.length){return true;} 135if(node.isAtom&&!node.isText){return true;} 136if(node.children&&Symbol.iterator in node.children){for(const child of node.children){if(nodeHasContent(child)){return true;}}} 137return false;} 138const 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;} 139const state={data:ips.utils.history.getState('commentFeed'),url:window.location.href} 140if(typeof state.data!=="object"){return;} 141const lastChange=e.detail.type==='pop'?'pop':ips.utils.history.getLastChangeType() 142if(lastChange&&lastChange!=='commentFeed'&&typeof this.historyState==="object"){let commentFeedChanged=false;if(Object.keys(this.historyState).length!==Object.keys(state.data).length){commentFeedChanged=true;}else{for(const key in this.historyState){if(!(key in state.data)||this.historyState[key]!==state.data[key]){commentFeedChanged=true;break;}}} 143if(!commentFeedChanged){return}} 144if((state.data.controller!==this.controllerID||state.data.feedID!==this._commentFeedID)){if(state.data.controller===undefined&&state.url===this._initialURL){Debug.log("No controller state, but state URL matched initial URL");}else{return;}} 145this.historyState=state.data;
145this._urlParams=state.data;ips.utils.analytics.trackPageView(state.url);this._getResults();},_getResults(url){this._setLoading(true);ips.getAjax()(url||this._getURL(),{showLoading:true}).done(response=>this._getResultsDone(response)).fail((...args)=>this._getResultsFail(...args)).always(()=>this._getResultsAlways());},_getResultsDone(response){const feed=Array.from((new DOMParser()).parseFromString(`<div>${response}</div>`,'text/html').querySelectorAll(`[data-feedid="${this.scope.attr('data-feedid')}"]`)).find(el=>el.dataset.controller?.match(/core\.front\.core\.commentFeed/i)) 146if(!feed){this._getResultsFail(new RangeError(`The response did not include a content feed element with a feed id matching this one`)) 147return;} 148const newContents=feed.innerHTML;const scrollPos=window.scrollY;this.cleanContents();this.scope.html(newContents);window.scrollTo({top:scrollPos,behavior:'auto'}) 149if(this._updateDoneCallback instanceof Function){setTimeout(this._updateDoneCallback,10);} 150this._updateDoneCallback=null;this._overlay.hide();this.scope.removeAttr("data-ips-comments-loading");const currentPageNo=ips.utils.url.getPageNumber(this._pageParam,window.location.href),lastPageNo=this.scope.find('li.ipsPagination__last > a').first().attr('data-page');if(currentPageNo!==lastPageNo){this.scope.removeAttr('data-lastPage');this._stopPolling();}else{this.scope.attr('data-lastPage',true);if(this._pollingEnabled){this._currentPoll=this._initialPoll;this._startPolling();}} 151this._setUpMultiQuote();$(document).trigger('contentChange',[this.scope]);this._findCheckedComments();ips.ui.tableOfContents.refreshElems();},_getResultsFail:function(jqXHR,textStatus,errorThrown){if(Debug.isEnabled()){if(jqXHR instanceof RangeError){Debug.error(jqXHR) 152return;} 153Debug.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);} 154var 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.attr("data-ips-comments-loading","");}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}));})} 155this._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;} 156this._seoPagination=data.seoPagination;this._updateURL(queryKey,()=>{const elem=this.elem.querySelector(`.ipsButtonBar--top`) 157if(!(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") 158return;} 159const boundingBox=elem.getBoundingClientRect() 160if(boundingBox.top>30&&boundingBox.bottom<window.innerHeight-30){return;} 161window.scrollBy({top:boundingBox.top-30,behavior:'smooth'})});}},_updateURL:function(newParams,callback){this._updateState(newParams) 162let newUrl=this._getURL();if(newUrl.slice(-1)==='?'){newUrl=newUrl.substring(0,newUrl.length-1);} 163if(this._seoPagination===true){newUrl=ips.utils.url.pageParamToPath(newUrl,this._pageParam,this.historyState[this._pageParam]);} 164ips.utils.history.pushState(this.historyState,'commentFeed',newUrl);this._updateDoneCallback=callback;}
164,_updateState(newParams){Object.assign(this._urlParams,newParams);this.historyState={...this._urlParams} 165Object.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();}} 166urlObj.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(dataStore[data.commentID]===undefined){dataStore[data.commentID]=data.actions;}}else{delete dataStore[data.commentID];} 167if(Object.keys(dataStore).length){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;} 168var dataStore=ips.utils.db.get('moderation',this._commentFeedID)||{};var self=this;var pageAction=this.scope.find('[data-ipsPageAction]');if(Object.keys(dataStore).length){var sizeOtherPage=0;for(const[key,val]of Object.entries(dataStore)){if(self.scope.find('[data-commentID="'+key+'"]').length){self.scope.find('[data-commentID="'+key+'"] input[type="checkbox"][data-role="moderation"]').prop('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(this.scope.attr('data-lastPage')!==undefined&&this._pollingEnabled){this.pollForNewReplies();}},_startPolling:function(){if(ips.utils.sockets.enabled()&&ips.utils.sockets.connected()){if
168(ips.getSetting('relativeDates')){if(this._timestampTimeout){clearTimeout(this._timestampTimeout);} 169Debug.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;} 170this._startPolling();},this._currentPoll);} 171return;} 172this._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);} 173Debug.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;} 174const 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;} 175if(this._pollingPaused){Debug.log('Window blurred, delaying poll until focused...');this._pollOnUnpaused=true;return;} 176if(this._pollAjax&&this._pollAjax.abort!==undefined){this._pollAjax.abort();} 177this._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;} 178if(parseInt(response.count)>0){this._currentPoll=this._initialPoll;if(this.getCurrentCommentPageCount()<parseInt(response.perPage)){this._importNewRepl
178ies(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;}} 179if(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&&response.photo!==undefined&&response.name!==undefined){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])});} 180if($('#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;} 181const notifyData={onClick:e=>{try{window.focus();}catch(err){} 182this.loadNewPosts(e);}};if(this._notification){this._notification.hide();} 183if(parseInt(response.count)===1&&'photo'in response&&'name'in response){Object.apply(notifyData,{title:ips.getString('notificationNewPostSingleTitle',response),body:ips.getString('notificationNewPostSingleBody',response),icon:response.photo});}else{Object.apply(notifyData,{title:ips.pluralize(ips.getString('notificationNewPostMultipleTitle'),[response.count]),body:ips.pluralize(ips.getString('notificationNewPostMultipleBody',response),[response.count])});} 184this._notification=ips.utils.notification.create(notifyData);this._notification.show();}
184,async _importNewReplies(loadNewPage=true){const form=this.scope.find('[data-role="replyArea"] form');const commentsOnThisPage=this.scope.find('[data-commentid]');const _lastSeenID=this._getLastSeenID(commentsOnThisPage);try{const response=await ips.fetch(form.attr('action'),{data:{do:'checkForNewReplies',type:'fetch',lastSeenID:_lastSeenID,showing:this.getCurrentCommentPageCount()},type:'post'});if(loadNewPage&&commentsOnThisPage.length+parseInt(response.totalNewCount)>response.perPage){if(response.spillOverUrl){window.location=response.spillOverUrl;}else{window.location.reload();}}else{for(const item of[response.content].flat()){this.trigger('addToCommentFeed',{content:item,feedID:this._commentFeedID,resetEditor:false,totalItems:response.totalCount});}} 185this._clearNotifications();}catch(e){Debug.warn(`Could not import new replies for the comment feed!`);Debug.error(e);}},_clearNotifications:function(){if(this._notification&&typeof this._notification.hide()==="function"){this._notification.hide();} 186if($('#elFlashMessage').find('[data-role="newPostNotification"]').length){$('#elFlashMessage').find('[data-role="newPostNotification"]').trigger('closeFlashMsg.flashMsg');}},quickReply:function(e){const form=this.scope.find('[data-role="replyArea"] form');if(form.attr('data-noAjax')){return;} 187e.preventDefault();e.stopPropagation();const self=this;const replyArea=this.scope.find('[data-role="replyArea"]');const submit=form.find('[type="submit"]');const autoFollow=this.scope.find('input[name$="auto_follow_checkbox"]');const commentsOnThisPage=this.scope.find('[data-commentid]');const _lastSeenID=this._getLastSeenID(commentsOnThisPage);const submitButtons=[...submit];const submitRestorations=[];submitButtons.forEach(button=>{if(button.closest('.ipsIconPicker')){return;} 188const initialText=button.innerText;button.setAttribute('disabled','');button.innerText=ips.getString('saving');submitRestorations.push(()=>{button.removeAttribute('disabled');button.innerText=initialText;});});let page=ips.utils.url.getPageNumber(this._pageParam);if(!page){page=1;} 189this._clearNotifications();ips.getAjax()(form.attr('action'),{data:form.serialize()+'¤tPage='+page+'&_lastSeenID='+_lastSeenID,type:'post'}).done(function(response){if(response.type=='error'){Debug.error(response);Debug.error('Failed to submit content via quick reply');if(response.form){if(replyArea.find('[data-ipseditorv5]')){ips.ui.editorv5.getObj(replyArea.find('[data-ipseditorv5]')).destruct(false);} 190form.replaceWith($(response.form));$(document).trigger('contentChange',[self.scope]);}else{ips.ui.alert.show({type:'alert',icon:'warn',message:response.message,callbacks:{}});}} 191else if(response.type=='redirect'){self.paginationClick(e,{href:response.url,originalEvent:e});}else if(response.type=='merge'){var comment=$(self.findCommentInFeed(response.id));comment.find('[data-role="commentContent"]').html(response.content);if(comment.find('pre.prettyprint').length){comment.find('pre.prettyprint').each(function(){$(this).html(window.PR.prettyPrintOne(ips.utils.escapeHTML($(this).text())));});} 192self.scope.find('[data-role="replyArea"] [data-ipsEditorv5]').data('_editor').reset();if(self.scope.find('[data-role="replyArea"] input[name="guest_name"]').length){self.scope.find('[data-role="replyArea"] input[name="guest_name"]').val('');} 193form.find("[data-role='commentFormError']").each(function(){$(this).remove();});const container=comment.closest('.js-ipsEntry');if(container.length){ips.utils.anim.go('pulseOnce',container);}else{ips.utils.anim.go('pulseOnce',comment);} 194ips.ui.flashMsg.show(ips.getString('mergedConncurrentPosts'));$(document).trigger('contentChange',[self.scope]);}else{if(response.postedByLoggedInMember){self.trigger('ipsDataLayer',{_key:'content_comment',_properties:response.dataLayer});} 195self.trigger('addToCommentFeed',{content:response.content,totalItems:response.total,feedID:self._commentFeedID,scrollToItem:true});if(response.message){ips.ui.flashMsg.show(response.message);} 196if(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();} 197form.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')});}} 198self._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.trigger('submit');}}).always(function(){submitRestorations.forEach(cb=>cb());});},loadNewPosts:function(e){e?.preventDefault?.();
198this._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;} 199return null;},addToCommentFeed(e,data){if(typeof data?.content!=="string"||data.feedID!==this._commentFeedID){return;} 200const 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"]');} 201this.scope.find('[data-role="noComments"]').remove();const actualContent=comment.get(0) 202const 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)'));} 203if(data.scrollToItem&&(newItemTop<windowScroll||newItemTop>(windowScroll+viewHeight))){$('html, body').animate({scrollTop:newItemTop+'px'},'fast',function(){setTimeout(_showComment,100);});}else{_showComment();} 204if(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);}} 205if(!('resetEditor'in data)||data.resetEditor!==false){this.scope.find('[data-role="replyArea"] [data-ipsEditorv5]').data('_editor').reset();} 206this._updateCount(data.totalItems);if(ips.getSetting('relativeDates')){this._updateTimestamps();} 207$(document).trigger('contentChange',[this.scope]);},deletedComment:function(e,data){data=JSON.parse(data.response);var self=this;if(data.type=='redirect'){window.location=data.url;} 208else{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');} 209this.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=[];if(!Object.keys(mqData).length||!replyArea.is(':visible')){return;} 210for(const value of Object.values(mqData)){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){this._removeAllMultiQuoted();},_removeAllMultiQuoted:function(){var mqData=this._getMultiQuoteData();var self=this;ips.utils.db.set('mq','data',{});this._buildMultiQuote(0);if(!Object.keys(mqData).length){return;} 211for(const value of Object.values(mqData)){self.triggerOn('core.front.core.comment','setMultiQuoteDisabled.comment',{contentapp:value.contentapp,contenttype:value.contenttype,contentcommentid:value.contentcommentid});};},addMultiQuote:function(e,data){var mqData=this._getMultiQuoteData();var key=data.contentapp+'-'+data.contenttype+'-'+data.contentcommentid;if(Object.keys(mqData).length==this._maximumMultiQuote){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.pluralize(ips.getString('maxmultiquote'),this._maximumMultiQuote),callbacks:{ok:function(){$("button[data-mqId='"+data.button+"']").removeClass('ipsButton--secondary').addClass('ipsButton--simple').removeAttr('data-mqActive').html(ips.templates.render('core.posts.multiQuoteOff'));}}});return false;} 212mqData[key]=data;ips.utils.db.set('mq','data',mqData);this._buildMultiQuote(Object.keys(mqData).length);},removeMultiQuote:function(e,data){var mqData=this._getMultiQuoteData();var key=data.contentapp+'-'+data.contenttype+'-'+data.contentcommentid;if(mqData[key]!==undefined){delete mqData[key];ips.utils.db.set('mq','data',mqData);this._buildMultiQuote(Object.keys(mqData).length);}},_getMultiQuoteData:function(){var mqData=ips.utils.db.get('mq','data');if(mqData===null||typeof mqData!=="object"){return{};} 213return mqData;},_setUpMultiQuote:function(){if(!ips.utils.db.isEnabled()){return;} 214var buttons=this.scope.find('[data-action="multiQuoteComment"]');var self=this;var mqData=this._getMultiQuoteData();buttons.show();if(Object.keys(mqData).length){this._buildMultiQuote(Object.keys(mqData).length);for(const value of Object.values(mqData)){self.triggerOn('core.front.core.comment','setMultiQuoteEnabled.comment',{contentapp:value.contentapp,contenttype:value.contenttype,contentcommentid:value.contentcommentid});};}}
214,_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}));document.getElementById("ipsMultiQuoter").showPopover();}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);} 215quoterElem.find('[data-role="quotingTotal"]').text(ips.pluralize(ips.getString('multiquote_count_plural'),[count]));quoterElem[0].togglePopover(count);}},_getLastSeenID:function(commentsOnThisPage){var commentFeed=this.scope.find('[data-role="commentFeed"]');var max=0;for(const comment of commentsOnThisPage){const id=Number(comment.dataset.commentid);if(id>max){max=id;}} 216const topicAnswerID=Number(commentFeed.attr('data-topicAnswerID'));if(topicAnswerID&&topicAnswerID>max){max=topicAnswerID;} 217Debug.log("Max comment ID is "+max);return max;},async _updateTimestamps(){if(!ips.getSetting('relativeDates')){return;} 218Debug.log('Updating the comment feed timestamps') 219const 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);}} 220roots.forEach(root=>{for(const el of root.querySelectorAll('time.ipsTime[datetime]:not(.ipsTime .ipsTime, time time)')){if(OLD_TIME_ELEMENTS.has(el)){continue;} 221if(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;} 222timestampMap.set(el,unixts);}}}) 223const parsedResults={};const timestamps=Array.from(new Set(timestampMap.values()));if(!timestamps.length){return;} 224const timestampCacheKeys={};const unknownTimestamps=[];for(const timestamp of timestamps){const deltaMinutes=Math.round(((Date.now()/1000)-timestamp)/60);timestampCacheKeys[timestamp.toString()]=`time_${deltaMinutes < 0 ? 'neg' : 'pos'}_${Math.abs(deltaMinutes)}`;const cached=ips.utils.db.get('formatted_timestamps',timestampCacheKeys[timestamp.toString()]) 225if(cached){const cachedEl=(new DOMParser()).parseFromString(cached,"text/html").querySelector("body > time");if(cachedEl instanceof HTMLTimeElement){parsedResults[`time_${timestamp}`]=cachedEl;continue;}} 226unknownTimestamps.push(timestamp);} 227if(unknownTimestamps.length){const result=await ips.fetch(ips.getSetting('baseURL'),{data:{app:'core',module:'system',controller:'ajax',do:"getFormattedTimes",timestamps:unknownTimestamps.join(',')}});if(typeof result?.timestamps!=='object'){Debug.warn("Unexpected response from ajax timestamps!");}else{for(const ts in result.timestamps){const timeEl=(new DOMParser()).parseFromString(result.timestamps[ts],'text/html').querySelector("body > time");if(timeEl instanceof HTMLTimeElement){if(ts.match(/time_(\d+)/)?.[1]in timestampCacheKeys){ips.utils.db.set('formatted_timestamps',timestampCacheKeys[ts.match(/time_(\d+)/)?.[1]],timeEl.outerHTML);} 228parsedResults[ts]=timeEl;}}}} 229for(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));; 230;(function($){"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=JSON.parse(data.response).total;}catch(err){var newTotal=0;} 231this._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));; 232;(function($){"use strict";
232ips.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&csrfKey='+ips.getSetting('csrfKey');ips.getAjax()(url,{data:{member_id:parseInt(userID)}}).done(function(){ips.ui.flashMsg.show(ips.getString('ignore_prefs_updated'));}).fail(function(){window.location=url+'&member_id='+userID;});}});}(jQuery));; 233;(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;} 234if(ips.utils.sockets.enabled()){if(ips.utils.sockets.connected()){this._useRealtime();}else{this.on(document,'socket.connected',this._useRealtime)}} 235this.on(document,`socket.notifications_available`,()=>{Debug.log('Notifications: fetching the latest notification counts');this._useRealtime();
235this._doAjaxRequest(this._getCurrentCounts());}) 236this._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;} 237if(this._debugPolling){Debug.log('Notifications: updating instantly from storage event');} 238try{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(hiddenProp!==undefined&&!document[hiddenProp]){this._updateBrowserTitle(0);if(!this._usingRealtime){this._pollMultiplier=1;this._windowInactivePoll=0;if(this._paused){this._checkNotifications();this._setInterval(this._pollTimeout);} 239if(this._debugPolling){Debug.log("Notifications: Resetting inactive poll.");}}}},_setInterval(timeoutInSecs){clearInterval(this._interval);if(this._usingRealtime){return;} 240this._interval=setInterval(this._checkNotifications.bind(this),timeoutInSecs*1000);},_doInitialCheck(){const storage=ips.utils.db.get('notifications',ips.getSetting('baseURL'));const counts=this._getCurrentCounts();if(!storage||typeof storage!=="object"){return;} 241if((this._messagesEnabled&&counts.messages>storage.messages)||counts.notifications>storage.notifications){if(this._debugPolling){Debug.log("Notifications: bubbles reporting higher counts for notifications or messages.");} 242const dataToSend={notifications:storage.notifications};if(this._messagesEnabled)dataToSend.messages=storage.message 243this._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");} 244this._pollMultiplier=2;this._setInterval(this._pollTimeout*this._pollMultiplier);}else if(this._windowInactivePoll>=7&&this._pollMultiplier===2){if(this._debugPolling){Debug.log("Notifications: Polled over 10 minutes, increasing multiplier to 3");} 245this._pollMultiplier=3;this._setInterval(this._pollTimeout*this._pollMultiplier);}else if(this._windowInactivePoll>=25&&this._pollMultiplier===3){if(this._debugPolling){Debug.log("Notifications: Polled over 60 mins, stopping polling");} 246this._stopPolling();return;} 247this._windowInactivePoll++;} 248if(storage!==null&&typeof storage==='object'&&parseInt(storage.timestamp)>(timestamp-((currentTimeout-1)*1000))){this._updateIcons(storage,counts);if(this._debugPolling){Debug.log("Notifications: fetching from localStorage");}}else{if(!this._messagesEnabled){delete counts.messages;} 249this._doAjaxRequest(counts);}},async _doAjaxRequest(data){const url=ips.getSetting('baseURL')+'?app=core&module=system&controller=ajax&do=instantNotifications';if(this._debugPolling){Debug.log("Notifications: sending ajax request");} 250this._updateTimestamp();try{this._handleResponse(await ips.fetch(url,{data}));}catch(e){this._stopPolling();Debug.error("Problem polling for new notifications; stopping.");}},_handleResponse(response){const total=response.messages.data.length+response.notifications.data.length;try{if(response.error&&response.error==='auto_polling_disabled'){this._stopPolling();return;} 251const counts=this._getCurrentCounts();if(response.notifications.count>counts.notifications&&this._debugPolling){Debug.log("Notifications: I'm the winner! I found there's "+response.notifications.count+" new notifications");} 252this._updateIcons({messages:response.messages.count,notifications:response.notifications.count},counts);ips.utils.db.set('notifications',ips.getSetting('baseURL'),{timestamp:ips.utils.time.timestamp(),messages:response.messages.count,notifications:response.notifications.count});if(response.notifications.data.length){this._showNotification(this._buildNotifyData(response.notifications.data,'notification'),'notification');} 253if(response.messages.data.length){this._showNotification(this._buildNotifyData(response.messages.data,'message'),'message');}}catch(err){this._stopPolling();return;} 254if(total>0){if(document[ips.utils.events.getVisibilityProp()]){this._updateBrowserTitle(total);}}},_updateBrowserTitle(count){const cleanTitle=document.title.replace(/^\(\d+\)/,'').trim();if(count){document.title="("+count+") "+cleanTitle;}else{document.title=cleanTitle;}},_buildNotifyData(items,type){const self=this;let notifyData={count:items.length};if(items.length===1){notifyData=Object.assign(notifyData,{title:ips.getString(type+'GeneralSingle'),icon:items[0].author_photo,body:items[0].title,url:items[0].url,onClick:function(){try{window.focus();}catch(err){} 255window.location=items[0].url;}});}else{notifyData=Object.assign(notifyData,{title:ips.pluralize(ips.getString(type+'GeneralMultiple'),[items.length]),body:items[0].title,icon:ips.getSetting(type+'_imgURL'),onClick:function(){try{window.focus();}catch(err){} 256self._getIcon((type==='message')?'inbox':'notify').trigger('click');}});} 257return notifyData;},_showNotification(notifyData,type){if(!document[ips.utils.events.getVisibilityProp()]){this._showFlashMessage(notifyData,type);}},_showFlashMessage(notifyData,type){let html='';const self=this;if(notifyData.count===1){notifyData=Object.assign(notifyData,{text:ips.getString(type+'FlashSingle')});html=ips.templates.render('core.notification.flashSingle',notifyData);}else{notifyData=Object.assign(notifyData,{text:ips.pluralize(ips.getString(type+'FlashMultiple'),[notifyData.count])});html=ips.templates.render('core.notification.flashMultiple',notifyData);} 258if($('#elFlashMessage').is(':visible')&&$('#elFlashMessage').find('[data-role="newNotification"]').length){$('#elFlashMessage').find('[data-role="newNotification"]').replaceWith(html);}else{ips.ui.flashMsg.show(html,{timeout:8,position:'bottom',extraClasse
258s:'cNotificationFlash',dismissable:function(){self._stopPolling();},escape:false});}},_updateTimestamp(){let storage=ips.utils.db.get('notifications',ips.getSetting('baseURL'));storage=Object.assign(storage,{timestamp:ips.utils.time.timestamp()});ips.utils.db.set('notifications',ips.getSetting('baseURL'),storage);},_updateIcons(newData,oldData){const reportBadge=this.scope.find('[data-notificationType="reports"]');const reportCount=reportBadge.length?parseInt(reportBadge.text()):0;const notifyData={notifications:parseInt(newData.notifications),reports:reportCount};if(parseInt(newData.notifications)!==oldData.notifications){this._updateIcon('notify',newData.notifications);this.scope.trigger('clearUserbarCache',{type:'notify'});} 259if(this._messagesEnabled){if(parseInt(newData.messages)!==oldData.messages){this._updateIcon('inbox',newData.messages);this.scope.trigger('clearUserbarCache',{type:'inbox'});} 260notifyData.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));; 261;(function($){"use strict";const IMAGE_EXTENSIONS=new Set(['gif','jpeg','jpe','jpg','png','svg','webp','avif']) 262const 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))') 263if(!attachments.length){return;} 264const isInlineCache=new WeakMap();const calcIsInline=attachment=>{const listAncestor=attachment.closest('li');if(listAncestor&&(this.elem.contains(listAncestor)||this.elem===listAncestor)){return true;} 265let 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);} 266ancestors.push(parent) 267parent=parent.parentElement;} 268if(!parent){ancestors.forEach(ancestor=>isInlineCache.set(ancestor,false));return false;} 269const 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;} 270attachments.forEach((attachment)=>{if(attachment.matches(':not(img, .ipsAttachLink_image)')){if(!calcIsInline(attachment)){attachment.classList.add('ipsAttachLink_block');if(attachment.children.length){return;} 271attachment.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";}}
272fileIDsToFetch[attachment.dataset.fileid]=true;});if(![...Object.keys(fileIDsToFetch)].length){return;} 273try{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");} 274attachments.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') 275if(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));} 276attachment.dataset.loaded='true';},_updateAttachmentImage(attachment,response){if(DISABLE_LIGHTBOX_ROTATE){return;} 277attachment=$(attachment);if(!(attachment.is('img'))){return;} 278if(response.rotate!==undefined&&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'});}} 279var containerHeight=attachment.height();if(response.rotate!=0&&response.rotate!=180&&response.rotate!=-180){containerHeight=attachment.width();} 280var 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'));} 281attachment.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) 282if(image.hasAttribute('title')){image.setAttribute('data-original-title',image.getAttribute('title'));} 283image.setAttribute('title',ips.getString('enlargeImage'))
284link.dataset.fileid=fileId 285link.dataset.ipslightboxGroup=this._random;image.parentElement.insertBefore(link,image) 286link.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]') 287if(embedAncestor){if(!('linkified'in embedAncestor.dataset)){const toLink=embedAncestor.querySelector(`.ipsEmbedded_og__title`)||image 288const toWrap=document.createElement('a') 289toWrap.href=embedAncestor.dataset.ogUrl 290toWrap.target="_blank" 291toWrap.rel="noopener noreferrer" 292toWrap.classList.add('ipsEmbedded_og__link') 293toLink.parentElement.insertBefore(toWrap,toLink) 294toWrap.append(toLink) 295embedAncestor.dataset.linkified=''} 296return;} 297promises.push(this._addOrUpdateWrappingLink(image));});} 298this.elem.querySelectorAll('.ipsEmbedded_og[data-og-url]:not([data-linkified])').forEach(embedAncestor=>{const toLink=embedAncestor.querySelector('.ipsEmbedded_og__title');if(!toLink){return;} 299const toWrap=document.createElement('a');toWrap.href=embedAncestor.dataset.ogUrl;toWrap.target='_blank';toWrap.rel="noopener noreferrer" 300toWrap.classList.add('ipsEmbedded_og__link');toLink.parentElement.insertBefore(toWrap,toLink);toWrap.append(toLink);embedAncestor.dataset.linkified='';});await Promise.allSettled(promises);}});}(jQuery));; 301;(function($){"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));; 302;(function($){"use strict";ips.controller.register('core.front.core.rating',{initialize:function(){this.on('ratingSaved','[data-ipsRating]',this.ratingClick);var scope=this.scope;},ratingClick:function(e,data){var scope=$(this.scope);ips.getAjax()(scope.attr('action'),{data:scope.serialize(),type:'post'}).done(function(response,textStatus,jqXHR){}).fail(function(){scope.trigger('submit');});}});}(jQuery));; 303;(function($){"use strict";ips.controller.register('core.front.core.reaction',{_reactTypeContainer:null,_reactButton:null,_reactTypes:null,_reactClose:null,_ajaxObj:null,initialize(){this.on('click','[data-role="reactionInteraction"]',this.clickLaunchReaction);this.on('mouseenter','[data-role="reactionInteraction"]',this.launchReaction);this.on('mouseleave','[data-role="reactionInteraction"]',this.unlaunchReaction);this.on('click','[data-role="reaction"]',this.clickReaction);this.on('click','[data-action="unreact"]',this.unreact);this.on(document,'socket.reaction-count',this._updateReactionCountsFromSocket);this._reactTypeContainer=this.scope.find('[data-role="reactionInteraction"]');this._reactTypes=this._reactTypeContainer.find('[data-role="reactTypes"]');this._reactButton=this._reactTypeContainer.find('[data-action="reactLaunch"]');this._reactClose=this._reactTypeContainer.find('[data-action="unreact"]');this._reactBlurb=this.scope.find('[data-role="reactionBlurb"]');this._reactCount=this.scope.find('[data-role="reactCount"]');this._singleReaction=!this._reactTypes.length;},async _updateReactionCountsFromSocket(event,{payload:data}){if(data.memberReacted===ips.getSetting('memberID')){return;} 304if(!data.content?.content_id||parseInt(data.content.content_id)!==this._getItemId()){return;} 305if((data?.content?.comment_id||null)!==this._getCommentId()){return;} 306if('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();} 307if(typeof data.blurb!=="string"){return;} 308this._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()) 309if(typeof response?.blurb==='string'){return response.blurb;}}catch(e){} 310return null;},_getCommentId(){if($(this.scope).get(0)?.closest(`[data-commentid]`)){return parseInt($(this.scope).get(0)?.closest(`[data-commentid]`).dataset.commentid)||null} 311return 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;} 312this._reactTypeContainer.addClass('ipsReact_types_active');this._launchReaction();}
312,launchReaction(){if(ips.utils.events.isTouchDevice()){return;} 313this._launchReaction();},_launchReaction(){this._reactTypes.prop('hidden',false).removeClass('ipsReact_hoverOut').addClass('ipsReact_hover');},unlaunchReaction(){this._reactTypes.animationComplete(()=>{if(this._reactTypes.hasClass('ipsReact_hoverOut')){this._reactTypes.removeClass('ipsReact_hoverOut').prop('hidden',true);}});this._reactTypes.removeClass('ipsReact_hover').addClass('ipsReact_hoverOut');this._reactTypeContainer.removeClass('ipsReact_types_active');},async unreact(e){e?.preventDefault();e?.stopPropagation();const defaultReaction=this.scope.find('[data-defaultReaction]');const url=this._reactTypeContainer.attr('data-unreact');if(!defaultReaction.closest('[data-action="reactLaunch"]').length){const currentReaction=this._reactButton.find('[data-role="reaction"]');const defaultReactionCopy=defaultReaction.clone();const currentReactionCopy=currentReaction.clone();currentReaction.replaceWith(defaultReactionCopy.removeClass('ipsReact_active'));defaultReaction.replaceWith(currentReactionCopy.removeClass('ipsReact_active'));} 314this._reactButton.removeClass('ipsReact_reacted');this._reactClose.fadeOut();this.unlaunchReaction();const response=await ips.fetch(url);this._updateReaction(response,ips.getString('removedReaction'));},_updateReaction(response,flashMsg){if(this._reactCount.hasClass('ipsReact_reactCountOnly')){this._reactCount.find('[data-role="reactCountText"]').text(response.score).removeClass('i-background_positive i-background_negative i-background_2');if(parseInt(response.score)>=1){this._reactCount.addClass('i-background_positive');}else if(parseInt(response.score)<0){this._reactCount.addClass('i-background_negative');}else{this._reactCount.addClass('i-background_2');} 315if(parseInt(response.count)===0){this._reactCount.prop('hidden',true);}else{this._reactCount.prop('hidden',false);}}else{this._reactBlurb.html(response.blurb);this._reactCount.text(response.count);if(parseInt(response.count)>0){this._reactBlurb.removeClass('ipsHide').fadeIn();}else{this._reactBlurb.fadeOut();}} 316this._reactTypeContainer.removeClass('ipsReact_types_active');if(flashMsg){ips.ui.flashMsg.show(flashMsg);}},async clickReaction(e){e?.preventDefault();if(this._singleReaction&&this._reactButton.hasClass('ipsReact_reacted')){this.unreact(null);return;} 317if(ips.utils.events.isTouchDevice()&&!this._singleReaction&&!this._reactTypeContainer.hasClass('ipsReact_types_active')){return;} 318const reaction=$(e.currentTarget);const url=reaction.attr('href');const currentButton=this.scope.find('[data-action="reactLaunch"] > [data-role="reaction"]');const newReaction=(!$(e.currentTarget).closest('[data-action="reactLaunch"]').length||!this._reactButton.hasClass('ipsReact_reacted'));this._removeActiveReaction();reaction.addClass('ipsReact_active');this._reactButton.addClass('ipsReact_reacted');setTimeout(()=>{if(reaction.closest('[data-action="reactLaunch"]').length===0){const currentButtonCopy=currentButton.clone(),reactionCopy=reaction.clone();currentButton.replaceWith(reactionCopy.removeClass('ipsReact_active'));reaction.replaceWith(currentButtonCopy.removeClass('ipsReact_active'));setTimeout(()=>this._reactClose.fadeIn(),400);this.unlaunchReaction();this._removeActiveReaction();}else{setTimeout(()=>this._reactClose.fadeIn(),400);this.unlaunchReaction();this._removeActiveReaction();}},400);if(newReaction){let reactionTitle=reaction.innerText;let reactionIcon=reaction.find('img[data-ipsTooltip]');if(reactionIcon){reactionTitle=reactionIcon.attr('data-ipstooltip')||reactionIcon.attr('title');} 319reactionTitle=reactionTitle||undefined;try{const response=await ips.fetch(url) 320this._updateReaction(response);try{if(IpsDataLayerConfig&&IpsDataLayerConfig._events.content_react.enabled){let context=IpsDataLayerContext||{};$('body').trigger('ipsDataLayer',{_key:'content_react',_properties:{...context,'reaction_type':reactionTitle,...(response.datalayer||{})},});}}catch(e){}}catch(jqXHR){Debug.log('Failed to send a reaction to the server');if('responseJSON'in jqXHR&&jqXHR.responseJSON.error==='react_daily_exceeded'){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('reactDailyExceeded'),
320callbacks:{}});}else{ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('reactError'),callbacks:{}});} 321this._reactButton.removeClass('ipsReact_reacted');this._reactClose.remove();}}},_removeActiveReaction(){this._reactTypeContainer.find('.ipsReact_active').removeClass('ipsReact_active');}});}(jQuery));; 322;(function($){"use strict";ips.controller.register('core.front.core.recommendedComments',{initialize:function(){this.on(document,'refreshRecommendedComments',this.refresh);this.on(document,'removeRecommendation',this.removeRecommendation);},refresh:function(e,data){var self=this;if(data.scroll){if(!this.scope.is(':visible')){this.scope.show();} 323let called=false;const doRefreshOnce=(recommended)=>{if(called)return;called=true;this._doRefresh(recommended);} 324$('html, body').animate({scrollTop:this.scope.offset().top+'px'},function(){doRefreshOnce(data.recommended);});}else{self.doRefreshOnce(data.recommended);}},removeRecommendation:function(e,data){var self=this;var comment=this.scope.find('[data-commentID="'+data.commentID+'"]');if(comment.length){comment.fadeOut().slideUp(function(){comment.remove();if(!self.scope.find('[data-commentID]').length){self.scope.hide();}});}},_doRefresh:function(newId){var self=this;ips.getAjax()(this.scope.attr('data-url')).done(function(response){self._handleResponse(response,newId);}).fail(function(){window.reload();});},_handleResponse:function(response,newId){var content=$('<div>'+response.html+'</div>').find('[data-controller="core.front.core.recommendedComments"]');if(parseInt(response.count)>0){this.scope.show();}else{this.scope.hide();} 325if(!response.count){return;} 326if(newId){var newComment=content.find('[data-commentID="'+newId+'"]');newComment.hide();if(newComment.is(':last-child')){this.scope.find('[data-role="recommendedComments"]').append(newComment);}else if(newComment.is(':first-child')){this.scope.find('[data-role="recommendedComments"]').prepend(newComment);}else{var prev=newComment.prev('[data-commentID]');prev.after(newComment);} 327$(document).trigger('contentChange',[newComment]);newComment.fadeIn().slideDown();}else{this.scope.html(content);$(document).trigger('contentChange',[this.scope]);}}});}(jQuery));; 328;(function($){"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);} 329if(!ips.utils.url.getParam('title',url)){url+="&title="+encodeURIComponent(document.title);} 330window.open(url,'delicious','toolbar=no,width=550,height=550');},});}(jQuery));; 331;(function($,_){"use strict";ips.controller.register('core.front.core.userbar',{initialize(){this.on(document,'clearUserbarCache',(...args)=>this.clearUserbarCache(...args));this.on(document,'submitDialog','#elMessengerPopup_compose',(e)=>this.clearUserbarCache(e,{type:'inbox'}));this.on(document,'ipsFetch','[data-ipsfetch-type]',this.emptyNotificationBubble);},emptyNotificationBubble(e){const type=e.target.getAttribute('data-ipsfetch-type');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;thisBubble.prop('hidden',true);if(globalCount-thisTotal<=0){globalBubble.prop('hidden',true);}else{globalBubble.html(globalCount-thisTotal)}} 332if(type==='notify'){ips.utils.notification.clearBadgeCount();}},clearUserbarCache(e,data){document.querySelectorAll(`[data-ipsfetch-type="${data.type}"]`).forEach(el=>{el.removeAttribute("data-ipsfetch-loaded");})},});}(jQuery));; 333;(function($){"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));; 334;(function($){"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));;
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.