(()=> {
'use strict';
const root=document.getElementById('paper-play');
if(!root) return;
const find=selector=> root.querySelector(selector);
const status=find('[data-status]');
const field=find('#pp-search');
const dialog=find('[data-dialog]');
const results=find('[data-search-results]');
const feedback=find('[data-feedback]');
const shelf=find('#paper-shelf');
const publicShelf=find('[data-public-shelf]');
const publicCount=find('[data-result-count]')?.textContent;
const shelfTitle=find('[data-shelf-title]')?.textContent;
const books=JSON.parse(find('#pp-books').textContent);
const home=new URL(root.dataset.home);
const systemMotion=matchMedia('(prefers-reduced-motion: reduce)');
const running=new WeakMap();
const keys={saved:'tabll-paper-books-v1', quiet:'tabll-paper-quiet', pick:'tabll-paper-pick', arrival:'tabll-paper-arrival'};
const allRecords=new Map(books.map(item=> [item.id, item]));
const localResults=new Map();
let saved, quiet, lastEdit, searchTimer, searchController, searchTrigger;
let resultFor=null;
let searchVersion=0;
let savedView=false;
function stored(key, fallback, session=false){
try { return JSON.parse((session ? sessionStorage:localStorage).getItem(key)) ?? fallback; }
catch { return fallback; }}
function store(key, data, session=false){
try { (session ? sessionStorage:localStorage).setItem(key, JSON.stringify(data)); } catch {  }}
function safeRecord(item){
if(!item||!/^\d+$/.test(item.id)||typeof item.title!=='string') return false;
try { return new URL(item.url).origin===home.origin; } catch { return false; }}
function readSaved(){
const list=stored(keys.saved, []);
return new Map((Array.isArray(list) ? list:[]).filter(safeRecord).map(item=> [String(item.id), item]));
}
function textNode(tag, text, className){
const el=document.createElement(tag);
if(text!=null) el.textContent=text;
if(className) el.className=className;
return el;
}
function icon(name){
const svgNamespace='http://www.w3.org/2000/svg';
const svg=document.createElementNS(svgNamespace, 'svg');
const use=document.createElementNS(svgNamespace, 'use');
for (const [key, value] of Object.entries({viewBox:'0 0 24 24',fill:'none',stroke:'currentColor','stroke-linecap':'round','stroke-linejoin':'round','aria-hidden':'true',focusable:'false'})) svg.setAttribute(key, value);
use.setAttribute('href', '#paper-icon-' + (/^[a-z-]+$/.test(name) ? name:'file-text'));
svg.append(use);
return svg;
}
function useMotion(){ return !quiet&&!systemMotion.matches; }
function move(element, frames, options={}){
if(!element?.animate||!useMotion()) return;
running.get(element)?.cancel();
running.set(element, element.animate(frames, {duration:230, easing:'cubic-bezier(.2,.78,.2,1)', ...options}));
}
function paintMotion(){
const off = !useMotion();
root.dataset.motion=off ? 'off':'on';
const button=find('[data-quiet]');
button.disabled=systemMotion.matches;
button.setAttribute('aria-pressed', String(off));
find('[data-quiet-label]').textContent=systemMotion.matches ? '跟随系统减弱动效':'减弱动效';
if(off) root.getAnimations?.({subtree:true}).forEach(animation=> animation.cancel());
root.dispatchEvent(new Event('paper:motion'));
}
function makeLink(item, className){
const link=textNode('a', item.title, className);
link.href=item.url;
link.dataset.storyLink=item.id;
return link;
}
function savedCard(item){
const row=textNode('article', null, 'pp-story');
row.dataset.story=item.id;
const symbol=textNode('span', null, 'pp-subject-icon');
symbol.append(icon(item.icon));
const copy=textNode('div', null, 'pp-entry-copy');
const heading=textNode('h3');
heading.append(makeLink(item, 'pp-entry-link'));
copy.append(heading, textNode('p', [item.date,item.category].filter(Boolean).join(' · '), 'pp-entry-meta'));
const button=textNode('button', null, 'pp-icon-button pp-save');
button.type='button';
button.dataset.save=item.id;
const mark=textNode('span', null, 'pp-mark'), ink=textNode('span', null, 'pp-mark-ink');
ink.append(icon('bookmark-check'));
mark.append(icon('bookmark'), ink);
button.append(mark);
row.append(symbol, copy, button);
return row;
}
function refreshBookmarks(){
const count=saved.size;
const badge=find('[data-saved-badge]');
badge.hidden = !count;
badge.textContent=count;
find('[data-saved-open]').setAttribute('aria-label', count ? '打开稍后读，' + count + ' 篇':'打开稍后读');
if(shelf){
find('[data-saved-label]').textContent=count ? '稍后读 · ' + count:'稍后读';
find('[data-saved-toggle]').setAttribute('aria-pressed', String(savedView));
find('[data-result-count]').textContent=savedView ? count + ' 篇':publicCount;
find('[data-shelf-title]').textContent=savedView ? '稍后读':shelfTitle;
publicShelf.hidden=savedView;
find('[data-saved-shelf]').hidden = !savedView;
find('[data-filters]').hidden=savedView;
if(savedView){
const grid=find('[data-saved-grid]');
grid.className='pp-saved-entries';
const rows=[...saved.values()].reverse().map(savedCard);
if(!rows.length){
const empty=textNode('div', null, 'pp-empty');
const button=textNode('button', '回到文章书架');
button.type='button';
button.dataset.leaveSaved='';
empty.append(icon('bookmark'), textNode('h3','稍后读还是空的'), textNode('p','点文章旁的书签，就能把想读的内容留在这里。'), button);
rows.push(empty);
}
grid.replaceChildren(...rows);
}}
root.querySelectorAll('[data-save]').forEach(button=> {
const id=button.dataset.save, on=saved.has(id);
button.setAttribute('aria-pressed', String(on));
button.setAttribute('aria-label', (on ? '移出稍后读，':'稍后读，') + (allRecords.get(id)?.title||saved.get(id)?.title||'此文'));
const label=button.querySelector('[data-reader-save-label]');
if(label) label.textContent=on ? '已放入稍后读':'稍后读';
});
}
function closeFeedback(){
feedback.hidden=true;
if(feedback.parentNode!==root) root.append(feedback);
lastEdit=null;
}
function placeFeedback(){
if(!lastEdit||!lastEdit.anchor?.isConnected||feedback.hidden) return;
const a=lastEdit.anchor.getBoundingClientRect(), owner=feedback.offsetParent.getBoundingClientRect();
const surface=root.getBoundingClientRect();
const left=Math.max(surface.left+8, Math.min(surface.right-8, a.right+5) - feedback.offsetWidth);
const top=Math.min(a.bottom+4, surface.bottom-feedback.offsetHeight-4);
feedback.style.left=(left - owner.left) + 'px';
feedback.style.top=(top - owner.top) + 'px';
}
function anchorFor(id){
if(shelf&&savedView) return find('[data-saved-grid] [data-save="'+id+'"]')||find('[data-saved-toggle]');
return find('[data-save="'+id+'"]')||find('[data-saved-open]');
}
function toggleSave(button){
const id=button.dataset.save, item=allRecords.get(id)||saved.get(id);
if(!safeRecord(item)) return;
closeFeedback();
const wasSaved=saved.has(id);
if(wasSaved) saved.delete(id); else saved.set(id, item);
store(keys.saved, [...saved.values()]);
refreshBookmarks();
const anchor=anchorFor(id);
anchor.after(feedback);
lastEdit={item, wasSaved, anchor};
feedback.hidden=false;
find('[data-feedback-text]').textContent=wasSaved ? '已移出稍后读':'已放入稍后读';
placeFeedback();
if(!button.isConnected) anchor.focus({preventScroll:true});
move(anchor.querySelector('.pp-mark'), [{transform:'translateY(0)'},{transform:'translateY(-3px) rotate(-6deg)',offset:.38},{transform:'translateY(0)'}],{duration:300});
move(find('[data-saved-badge]'), [{scale:'.8'},{scale:'1.1',offset:.55},{scale:'1'}]);
status.textContent=(wasSaved ? '已移除《':'已收藏《') + item.title + '》，可以撤销。';
}
function undo(){
if(!lastEdit) return;
const {item, wasSaved}=lastEdit;
closeFeedback();
if(wasSaved) saved.set(item.id,item); else saved.delete(item.id);
store(keys.saved,[...saved.values()]);
refreshBookmarks();
anchorFor(item.id).focus({preventScroll:true});
status.textContent='已撤销书签操作。';
}
function switchSaved(on, scroll=true){
if(!shelf) return;
closeFeedback();
savedView=on;
refreshBookmarks();
positionFilter();
if(scroll) shelf.scrollIntoView({block:'start',behavior:useMotion()?'smooth':'instant'});
}
function navigateSaved(on){
const hash=on ? '#paper-saved':'#paper-shelf';
if(location.hash!==hash) history.pushState(history.state, '', hash);
switchSaved(on);
}
function positionFilter(){
const strip=find('[data-filters]');
const selected=strip?.querySelector('[aria-current=page]');
if(!selected||!strip.clientWidth) return;
strip.style.setProperty('--tab-x',selected.offsetLeft+'px');
strip.style.setProperty('--tab-width',selected.offsetWidth+'px');
strip.dataset.ready='';
}
function highlight(text, query){
const fragment=document.createDocumentFragment();
const pos=query&&text.toLocaleLowerCase().indexOf(query.toLocaleLowerCase());
if(!query||pos < 0) fragment.append(text);
else fragment.append(text.slice(0,pos), textNode('mark',text.slice(pos,pos+query.length)), text.slice(pos+query.length));
return fragment;
}
function displayResults(items, query, label, focusId){
resultFor=query;
results.replaceChildren(...items.map(item=> {
const link=makeLink(item,'pp-result');
const symbol=textNode('span',null,'pp-subject-icon');
symbol.append(icon(item.icon));
const copy=textNode('span',null,'pp-result-copy'), title=textNode('strong');
title.append(highlight(item.title,query));
copy.append(title,textNode('small',item.category));
link.replaceChildren(symbol,copy,icon('corner-down-left'));
return link;
}));
find('[data-search-label]').textContent=label;
if(focusId) results.querySelector('[data-story-link="'+focusId+'"]')?.focus();
}
async function search(focusId=null){
clearTimeout(searchTimer);
searchController?.abort();
const revision=++searchVersion, query=field.value.trim();
resultFor=null;
find('[data-search-clear]').hidden = !field.value;
if(!query) return displayResults(books,'','推荐阅读',focusId);
const cached=localResults.get(query);
if(cached) return displayResults(cached,query,cached.length ? '搜索结果':'没有找到相关内容',focusId);
results.replaceChildren();
find('[data-search-label]').textContent='正在搜索…';
searchTimer=setTimeout(async ()=> {
const controller=new AbortController();
searchController=controller;
try {
const url=new URL(home); url.searchParams.set('s', query);
const response=await fetch(url,{signal:controller.signal,credentials:'same-origin',headers:{Accept:'text/html'}});
if(!response.ok||new URL(response.url).origin!==home.origin) throw new Error('Search unavailable');
const doc=new DOMParser().parseFromString(await response.text(),'text/html');
if(!doc.querySelector('[data-public-shelf]')) throw new Error('Search page unavailable');
const items=Array.from(doc.querySelectorAll('[data-public-shelf] [data-story-info]'),el=> JSON.parse(el.dataset.storyInfo)).filter(safeRecord);
if(revision!==searchVersion||!dialog.open) return;
if(localResults.size >=20) localResults.delete(localResults.keys().next().value);
localResults.set(query,items);
displayResults(items,query,items.length ? '搜索结果':'没有找到相关内容，换个关键词试试。',focusId);
} catch (error){
if(error.name!=='AbortError'&&revision===searchVersion) find('[data-search-label]').textContent='按 Enter 查看完整搜索结果。';
}},180);
}
function openSearch(trigger, query='', focusId=null){
if(typeof dialog.showModal!=='function') return false;
closeFeedback();
searchTrigger=trigger||find('[data-search-open]');
if(!dialog.open) dialog.showModal();
field.value=query;
field.focus({preventScroll:true});
search(focusId);
move(dialog.querySelector('.pp-search-panel'),[{opacity:.4,translate:'0 -5px'},{opacity:1,translate:'0 0'}],{duration:180});
return true;
}
dialog.addEventListener('close', ()=> {
++searchVersion;
clearTimeout(searchTimer); searchController?.abort();
if(searchTrigger?.isConnected) searchTrigger.focus({preventScroll:true});
});
dialog.addEventListener('click',event=> { if(event.target===dialog) dialog.close(); });
field.addEventListener('input',()=> search());
const modifiers=event=> event.metaKey||event.ctrlKey||event.shiftKey||event.altKey;
function rememberLink(link){
const kind=dialog.open ? 'search':find('[data-reader]') ? 'reader':savedView ? 'saved':'shelf';
const id=link.dataset.storyLink;
if(!/^\d+$/.test(id)) return;
history.replaceState({...history.state, paperReturn:{kind,id,query:dialog.open ? field.value:'',fromHero:link.hasAttribute('data-recommend-open')}},'');
store(keys.arrival,{url:link.href,from:location.href,kind},true);
}
function returnFocus(){
const previous=history.state?.paperReturn;
if(!previous||!/^\d+$/.test(previous.id)) return;
const pageState={...history.state};
delete pageState.paperReturn; history.replaceState(pageState,'');
if(previous.kind==='search'){ openSearch(find('[data-search-open]'),previous.query,previous.id); return; }
if(previous.kind==='saved') switchSaved(true,false);
const scope=previous.kind==='saved' ? find('[data-saved-grid]'):previous.fromHero ? find('.pp-hero'):previous.kind==='reader' ? find('[data-reader]'):publicShelf;
const link=scope?.querySelector('[data-story-link="'+previous.id+'"]');
if(link){ link.focus({preventScroll:true});link.scrollIntoView({block:'nearest'});}}
const passage=stored(keys.arrival,null,true);
const samePage=(a,b)=> {
try { const x=new URL(a), y=new URL(b); return x.origin===home.origin&&x.origin===y.origin&&x.pathname===y.pathname&&x.search===y.search; } catch { return false; }};
if(find('[data-reader]')&&passage&&samePage(passage.url,location.href)&&samePage(passage.from,document.referrer)){
history.replaceState({...history.state,paperArrival:passage},'');
}
const arrival=history.state?.paperArrival;
if(arrival&&samePage(arrival.url,location.href)&&new URL(arrival.from).origin===home.origin){
root.querySelectorAll('[data-reader-back]').forEach(link=> {
link.href=arrival.from;
link.querySelector('span').textContent=({search:'返回搜索结果',reader:'返回上一篇',saved:'返回稍后读',shelf:'返回书架'})[arrival.kind]||'返回书房';
link.addEventListener('click',event=> {
if(!modifiers(event)&&event.button===0&&history.length > 1){ event.preventDefault(); history.back(); }});
});
}
root.addEventListener('click',event=> {
const el=event.target.closest('button,a');
if(!el||modifiers(event)||event.button!==0) return;
if(el.hasAttribute('data-search-open')&&openSearch(el)){ event.preventDefault(); return; }
if(el.hasAttribute('data-search-close')) return dialog.close();
if(el.hasAttribute('data-search-clear')){ field.value=''; field.focus(); search(); return; }
if(el.hasAttribute('data-save')) return toggleSave(el);
if(el.hasAttribute('data-undo')) return undo();
if(el.hasAttribute('data-dismiss')){ const anchor=lastEdit?.anchor; closeFeedback(); anchor?.focus(); return; }
if(el.hasAttribute('data-saved-open')&&shelf){ event.preventDefault(); navigateSaved(true); return; }
if(el.hasAttribute('data-saved-toggle')||el.hasAttribute('data-leave-saved')){ navigateSaved(!savedView); find('[data-saved-toggle]').focus({preventScroll:true});return; }
if(el.hasAttribute('data-quiet')){ quiet=!quiet; store(keys.quiet,quiet); paintMotion(); return; }
if(el.hasAttribute('data-story-link')) rememberLink(el);
if(el.matches('.pp-round,.pp-nav a,.pp-filters a,.pp-icon-button')) move(el,[{scale:'.965'},{scale:'1.018',offset:.6},{scale:'1'}],{duration:190});
});
root.addEventListener('pointerdown',event=> {
if(lastEdit&&!feedback.contains(event.target)&&!lastEdit.anchor.contains(event.target)) closeFeedback();
});
document.addEventListener('keydown',event=> {
if(event.isComposing||event.keyCode===229||event.defaultPrevented||event.altKey) return;
const editing=event.target.matches('input,textarea,select')||event.target.isContentEditable;
if(((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='k')||(event.key==='/'&&!editing&&!modifiers(event))){
if(dialog.open){ event.preventDefault(); dialog.close(); }
else if(openSearch(document.activeElement===document.body ? find('[data-search-open]'):document.activeElement)) event.preventDefault();
return;
}
if(dialog.open){
const links=[...results.querySelectorAll('a')], current=links.indexOf(document.activeElement);
if(event.key==='ArrowDown'&&links.length&&(event.target===field||current>=0)){
event.preventDefault(); links[Math.min(current+1,links.length-1)].focus();
}else if(event.key==='ArrowUp'&&current>=0){
event.preventDefault(); (links[current-1]||field).focus();
}else if(event.key==='Enter'&&event.target===field&&resultFor===field.value.trim()&&links.length){
event.preventDefault(); links[0].click();
}
return;
}
if(lastEdit&&event.key==='Escape'){ const anchor=lastEdit.anchor; const restore=feedback.contains(document.activeElement); closeFeedback(); if(restore) anchor.focus(); }
if(event.target.closest('[data-filters]')&&['ArrowLeft','ArrowRight','Home','End'].includes(event.key)){
const tabs=[...find('[data-filters]').querySelectorAll('a')], current=tabs.indexOf(event.target);
const index=event.key==='Home'?0:event.key==='End'?tabs.length-1:(current+(event.key==='ArrowRight'?1:-1)+tabs.length)%tabs.length;
event.preventDefault(); tabs[index].focus();
}});
root.querySelectorAll('[data-story-info]').forEach(el=> { const item=JSON.parse(el.dataset.storyInfo); if(safeRecord(item)) allRecords.set(item.id,item); });
saved=readSaved(); quiet=stored(keys.quiet,false)===true;
root.dataset.js='ready';
paintMotion();
switchSaved(location.hash==='#paper-saved',location.hash==='#paper-saved');
if(!shelf) refreshBookmarks();
find('[data-search-shortcut]').textContent=/mac|iphone|ipad/i.test(navigator.platform) ? '⌘ K':'Ctrl K';
window.tabllPaperBook?.({root,books,initialId:stored(keys.pick,''),choose:id=>store(keys.pick,id),useMotion,move,running,status});
systemMotion.addEventListener('change',paintMotion);
window.addEventListener('hashchange',()=>{ if(shelf) switchSaved(location.hash==='#paper-saved',false); });
window.addEventListener('resize',()=>{ positionFilter(); placeFeedback(); });
window.addEventListener('storage',event=> {
if(event.key===keys.saved||event.key===null){ closeFeedback(); saved=readSaved(); refreshBookmarks(); }
if(event.key===keys.quiet||event.key===null){ quiet=stored(keys.quiet,false)===true; paintMotion(); }});
window.addEventListener('pageshow',event=> {
if(event.persisted){ closeFeedback(); saved=readSaved(); refreshBookmarks(); }
if(event.persisted||performance.getEntriesByType('navigation')[0]?.type==='back_forward') returnFocus();
});
})();
window.WpStatisticsUserTracker||(window.WpStatisticsUserTracker={lastUrl:window.location.href,originalPushState:history.pushState,originalReplaceState:history.replaceState,isDndActive:parseInt(navigator.msDoNotTrack||window.doNotTrack||navigator.doNotTrack,10),hasTrackerInitializedOnce:!1,hasUrlChangeTrackerInitialized:!1,hitRequestSuccessful:!0,init:function(){this.hasTrackerInitializedOnce||(this.hasTrackerInitializedOnce=!0,WP_Statistics_Tracker_Object.option.isPreview)||(void 0===WP_Statistics_Tracker_Object?console.error("WP Statistics: Variable WP_Statistics_Tracker_Object not found. Ensure /wp-content/plugins/wp-statistics/assets/js/tracker.js is either excluded from cache settings or not dequeued by any plugin. Clear your cache if necessary."):this.checkHitRequestConditions(),this.trackUrlChange())},base64Encode:function(t){t=(new TextEncoder).encode(t);return btoa(String.fromCharCode.apply(null,t))},getPathAndQueryString:function(){var t=window.location.pathname,e=window.location.search;return this.base64Encode(t+e)},getReferred:function(){return this.base64Encode(document.referrer)},checkHitRequestConditions:function(){!WP_Statistics_Tracker_Object.option.dntEnabled||1!==this.isDndActive?this.sendHitRequest():console.log("WP Statistics: Do Not Track (DNT) is enabled. Hit request not sent.")},sendHitRequest:async function(){try{var t=this.getRequestUrl(),i=new URLSearchParams({...WP_Statistics_Tracker_Object.hitParams,referred:this.getReferred(),page_uri:this.getPathAndQueryString()}).toString();let e=new XMLHttpRequest;e.open("POST",t,!0),e.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),e.send(i),e.onreadystatechange=function(){var t;4===e.readyState&&(200===e.status?(t=JSON.parse(e.responseText),this.hitRequestSuccessful=!1!==t.status):(this.hitRequestSuccessful=!1,console.warn("WP Statistics: Hit request failed with status "+e.status)))}.bind(this)}catch(t){this.hitRequestSuccessful=!1,console.error("WP Statistics: Error sending hit request:",t)}},getRequestUrl:function(){let t=WP_Statistics_Tracker_Object.requestUrl+"/";return WP_Statistics_Tracker_Object.option.bypassAdBlockers?t=WP_Statistics_Tracker_Object.ajaxUrl:t+=WP_Statistics_Tracker_Object.hitParams.endpoint,t},updateTrackerObject:function(s){function r(){var t=document.getElementById("wp-statistics-tracker-js-extra");if(t)try{var e,i=t.innerHTML.match(/var\s+WP_Statistics_Tracker_Object\s*=\s*(\{[\s\S]*?\});/);i&&i[1]&&(e=JSON.parse(i[1]),!WP_Statistics_Tracker_Object.hitParams||JSON.stringify(WP_Statistics_Tracker_Object.hitParams)!==JSON.stringify(e.hitParams))?(WP_Statistics_Tracker_Object=e,!a&&s&&(a=!0,s())):++n<20?setTimeout(r,100):!a&&s&&(a=!0,s())}catch(t){console.error("WP Statistics: Error parsing WP_Statistics_Tracker_Object",t),!a&&s&&(a=!0,s())}else++n<20?setTimeout(r,100):!a&&s&&(a=!0,s())}let a=!1,n=0;setTimeout(r,50)},trackUrlChange:function(){if(!this.hasUrlChangeTrackerInitialized){this.hasUrlChangeTrackerInitialized=!0;let t=this;window.removeEventListener("popstate",t.handleUrlChange),history.pushState=function(){t.originalPushState.apply(history,arguments),t.handleUrlChange()},history.replaceState=function(){t.originalReplaceState.apply(history,arguments),t.handleUrlChange()},window.addEventListener("popstate",function(){t.handleUrlChange()})}},handleUrlChange:function(){let t=this;window.location.href!==this.lastUrl&&(this.lastUrl=window.location.href,this.updateTrackerObject(function(){t.checkHitRequestConditions()}))}});
window.WpStatisticsEventTracker||(window.WpStatisticsEventTracker={hasEventsInitializedOnce:!1,downloadTracker:!1,linkTracker:!1,init:async function(){this.hasEventsInitializedOnce||WP_Statistics_Tracker_Object.isLegacyEventLoaded||(this.hasEventsInitializedOnce=!0,"undefined"!=typeof WP_Statistics_DataPlus_Event_Object&&(this.downloadTracker=WP_Statistics_DataPlus_Event_Object.options.downloadTracker,this.linkTracker=WP_Statistics_DataPlus_Event_Object.options.linkTracker,this.downloadTracker||this.linkTracker)&&this.captureEvent(),window.wp_statistics_event=this.handleCustomEvent.bind(this),"undefined"!=typeof WP_Statistics_Marketing_Event_Object&&this.captureCustomClickEvents())},handleCustomEvent:function(t,e={}){var n=WP_Statistics_Tracker_Object.customEventAjaxUrl,t=(e.timestamp=Date.now(),e.resource_id||(e.resource_id=WP_Statistics_Tracker_Object.hitParams.source_id),{event_name:t,event_data:JSON.stringify(e)});this.sendEventData(t,n)},captureCustomClickEvents:function(){WP_Statistics_Marketing_Event_Object.events.clicks.forEach(e=>{!e.selector||null!=e.scope&&e.scope!=WP_Statistics_Tracker_Object.hitParams.source_id||document.querySelectorAll(""+e.selector).forEach(t=>{t.addEventListener("click",t=>{t={text:t.target.textContent,id:t.currentTarget.id,class:t.currentTarget.className,target:t.currentTarget.href};this.handleCustomEvent(e.name,t)})})})},captureEvent:function(){document.querySelectorAll("a").forEach(t=>{t.addEventListener("click",async t=>this.handleEvent(t)),t.addEventListener("mouseup",async t=>this.handleEvent(t))})},handleEvent:async function(t){var e;"mouseup"==t.type&&1!=t.button||(t=this.prepareEventData(t))&&(e=WP_Statistics_DataPlus_Event_Object.eventAjaxUrl,await this.sendEventData(t,e))},prepareEventData:function(t){let e={en:t.type,et:Date.now(),eid:t.currentTarget.id,ec:t.currentTarget.className,ev:"",mb:t.button,fn:"",fx:"",m:"",tu:"",pid:""};return"A"===t.currentTarget.tagName&&(e=this.extractLinkData(t,e)),"undefined"!=typeof WP_Statistics_Tracker_Object&&(e.pid=WP_Statistics_Tracker_Object.hitParams.source_id),e},extractLinkData(t,e){var n=t.target.textContent,a=t.currentTarget.href,i=WP_Statistics_DataPlus_Event_Object.fileExtensions,i=new RegExp("\\.("+i.join("|")+")$","i"),n=(n&&(e.ev=n),a&&(e.tu=a),t.currentTarget.classList.contains("woocommerce-MyAccount-downloads-file")||a.includes("download_file="));if(e.wcdl=n,(i.test(a)||n)&&(t=new URL(a).pathname,e.df=n?a.substring(a.lastIndexOf("download_file=")+14).split("&").shift():"",e.dk=n?a.substring(a.lastIndexOf("key=")+4).split("&").shift():"",e.en="file_download",e.fn=n?e.df:t.substring(t.lastIndexOf("/")+1).split(".").shift(),e.fx=n?e.df:t.split(".").pop()),"click"===e.en){if(!this.linkTracker)return!1;try{if(new URL(a).host===window.location.host)return!1}catch(t){}}return!("file_download"===e.en&&!this.downloadTracker)&&e},sendEventData:async function(t,e){var n,a=new URLSearchParams;for(n in t)a.append(n,t[n]);if(!e)throw new Error("AJAX URL is not defined.");try{(await fetch(e,{method:"POST",keepalive:!0,body:a})).ok}catch(t){console.error("Error:",t)}}});
function handleWpConsentApiIntegration(){(wp_has_consent("statistics")||wp_has_consent("statistics-anonymous"))&&(WpStatisticsUserTracker.init(),WpStatisticsEventTracker.init()),document.addEventListener("wp_listen_for_consent_change",function(t){var n,i=t.detail;for(n in i)!i.hasOwnProperty(n)||"statistics"!==n&&"statistics-anonymous"!==n||"allow"!==i[n]||(WpStatisticsUserTracker.init(),WpStatisticsEventTracker.init())})}function handleRealCookieBannerIntegration(){(window.consentApi?.consent("wp-statistics")||Promise.resolve()).then(()=>{WpStatisticsUserTracker.init(),WpStatisticsEventTracker.init()}).catch(()=>{var t=window.consentApi?.consentSync("wp-statistics-with-data-processing");null!=t.cookie&&t.cookieOptIn?(WpStatisticsUserTracker.init(),WpStatisticsEventTracker.init()):console.log("WP Statistics: Real Cookie Banner consent is not given to track visitor information.")})}document.addEventListener("DOMContentLoaded",function t(){var n;document.prerendering?document.addEventListener("prerenderingchange",t,{once:!0}):((n=WP_Statistics_Tracker_Object.option.consentIntegration.name)&&"borlabs_cookie"!==n||(WpStatisticsUserTracker.init(),WpStatisticsEventTracker.init()),"wp_consent_api"===n&&handleWpConsentApiIntegration(),"real_cookie_banner"===n&&handleRealCookieBannerIntegration())});