text: /* @alixlahuec/zotero-roam | 0.6.98 | 2022-03-17 */
  var zoteroRoam={};(()=>{zoteroRoam={Shortcut:function(e){for(k in this.action=e.action,this.template={altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1},this.watcher={altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1},e.template)this.template[""+k]=e.template[""+k],this.watcher[""+k]=!1;Object.keys(this.template).every(e=>!1===this.template[e])&&(this.template={})},Pagination:function(e){this.data=e.data,this.renderFunction=e.render,this.itemsPerPage=e.itemsPerPage||zoteroRoam.config.params.citations.itemsPerPage,this.currentPage=1,this.nbPages=Math.ceil(this.data.length/this.itemsPerPage),this.startIndex=(this.currentPage-1)*this.itemsPerPage+1,this.updateStartIndex=function(){this.startIndex=(this.currentPage-1)*this.itemsPerPage+1},this.getCurrentPageData=function(){return this.getPageData(this.currentPage)},this.getPageData=function(e){return this.data.slice(start=this.itemsPerPage*(e-1),end=this.itemsPerPage*e)},this.previousPage=function(){--this.currentPage,this.currentPage<1&&(this.currentPage=1),this.updateStartIndex(),this.renderResults()},this.nextPage=function(){this.currentPage+=1,this.currentPage>this.nbPages&&(this.currentPage=this.nbPages),this.updateStartIndex(),this.renderResults()},this.renderResults=function(){zoteroRoam.utils.executeFunctionByName(this.renderFunction,window)}},version:"0.6.98",data:{items:[],collections:[],semantic:new Map,libraries:new Map,keys:[],roamPages:[],tags:{}},librarySearch:{autocomplete:null},activeImport:{libraries:[],currentLib:{}},citations:{pagination:null,autocomplete:null,currentDOI:"",currentCitekey:"",currentType:"citations",activeImport:null},webImport:{currentBlock:null,activeImport:null},tagSelection:{cit_panel:null,aux_panel:null},tagManager:{lists:{},pagination:null,activeDisplay:{library:null,by:"usage"}},config:{autoComplete:{data:{src:async function(){let e=[];return 0<zoteroRoam.data.items.length&&(e=zoteroRoam.handlers.simplifyDataArray(zoteroRoam.data.items)),e},keys:["title","authorsString","year","tagsString","key","_multiField"],cache:!1,filter:e=>{var a=[...e].sort((t,a)=>zoteroRoam.config.autoComplete.data.keys.findIndex(e=>e==t.key)<zoteroRoam.config.autoComplete.data.keys.findIndex(e=>e==a.key)?-1:1);return Array.from(new Set(a.map(e=>e.value.key))).map(t=>a.find(e=>e.value.key==t))}},selector:"#zotero-roam-search-autocomplete",placeHolder:"Search by title, year, authors (last names), citekey, tags",wrapper:!1,trigger:e=>0!=e.length||(document.querySelector(".zotero-roam-library-results-count").innerHTML="",document.getElementById("zotero-roam-library-rendered").removeAttribute("has-results"),!1),searchEngine:(e,t)=>zoteroRoam.utils.multiwordMatch(e,t,highlight=['<span class="zr-search-match">',"</span>"]),resultsList:{class:"zotero-roam-search-results-list",id:"zotero-roam-search-results-list",destination:"#zotero-roam-library-search-div",position:"beforeend",maxResults:100,tabSelect:!0,element:(e,t)=>{e.classList.add("bp3-menu"),t.results&&0<t.results.length&&(document.querySelector(".zotero-roam-library-results-count").innerHTML=`
                              <strong>${t.results.length}</strong> / ${t.matches.length} results
                              `,e.closest("#zotero-roam-library-rendered").setAttribute("has-results","true"))}},resultItem:{tag:"li",class:"zotero-roam-search_result",id:"zotero-roam-search_result",highlight:!1,element:(e,t)=>{let a="",{title:o,authors:r,publication:i}=(a=t.value.inGraph?(e.setAttribute("in-graph","true"),'<span class="bp3-icon bp3-icon-symbol-circle"></span>'):(e.setAttribute("in-graph","false"),'<span class="bp3-icon bp3-icon-minus"></span>'),e.setAttribute("data-item-type",t.value.itemType),t.value);switch(r+=t.value.year?` (${t.value.year})`:"",t.key){case"title":o=t.match;break;case"authorsString":case"year":r=`<span class="zr-search-match">${r}</span>`}e.innerHTML=`
                          <div label="${t.value.key}" class="bp3-menu-item">
                              <div class="bp3-text-overflow-ellipsis zotero-roam-search-item-contents">
                              <span class="zotero-roam-search-item-title">${o}</span>
                                  <span class="zr-details">
                                      <span class="zotero-roam-search-item-authors zr-highlight">${r}</span><span class="zotero-roam-search-item-metadata zr-secondary"> ${i}</span>
                                  </span>
                              </div>
                              <span class="bp3-menu-item-label zotero-roam-search-item-key">
                              <span>@${t.value.key}</span>
                              ${a}
                              </span>
                          </div>`}},events:{input:{blur:e=>{},focus:e=>{zoteroRoam.interface.clearSelectedItem(),zoteroRoam.librarySearch.autocomplete.start()},results:e=>{zoteroRoam.interface.clearSelectedItem(),0<e.detail.query.length&&0==e.detail.results.length&&(document.querySelector(".zotero-roam-library-results-count").innerHTML=`
                                  <strong>No results</strong> for ${e.detail.query}
                                  `,document.getElementById("zotero-roam-library-rendered").removeAttribute("has-results"))},selection:a=>{var a=a.detail,o=(zoteroRoam.interface.search.input.blur(),document.querySelector(".zotero-roam-library-results-count").innerHTML="",document.querySelector("#zotero-roam-quick-copy-mode").checked);if(1==zoteroRoam.config.params.always_copy||o&&!zoteroRoam.config.params.override_quickcopy.overridden){let e=zoteroRoam.interface.search.overlay.querySelector("input.clipboard-copy-utility"),t="";if("citation"===zoteroRoam.config.params.quick_copy_format){let e=""+(a.selection.value.authors||"");a.selection.value.year&&(e+=` (${a.selection.value.year})`),t=`[${e}]([[@${a.selection.value.key}]])`}else t=zoteroRoam.utils.formatItemReference(item=a.selection.value,format=zoteroRoam.config.params.quick_copy_format);e.value=t,e.select(),document.execCommand("copy"),o&&!zoteroRoam.config.params.override_quickcopy.overridden?zoteroRoam.interface.toggleSearchOverlay("hide"):zoteroRoam.interface.renderItemInPanel("@"+a.selection.value.key)}else zoteroRoam.interface.renderItemInPanel("@"+a.selection.value.key)}}}},citationsSearch:{data:{src:async function(){if(0==zoteroRoam.citations.currentDOI.length)return[];{let a=zoteroRoam.data.semantic.get(zoteroRoam.citations.currentDOI)[""+zoteroRoam.citations.currentType],o=new Map(zoteroRoam.data.items.filter(e=>e.data.DOI).map(e=>[zoteroRoam.utils.parseDOI(e.data.DOI),e.key]));return a.forEach((e,t)=>{e.doi&&o.has(zoteroRoam.utils.parseDOI(e.doi))&&(a[t].inLibrary=!0,a[t].citekey=o.get(e.doi))}),a}},keys:["title","authorsString","year","meta"],filter:e=>{return Array.from(new Set(e.map(e=>e.value.doi))).map(t=>e.filter(e=>e.value.doi==t).sort((t,a)=>zoteroRoam.config.citationsSearch.data.keys.findIndex(e=>e==t.key)<zoteroRoam.config.citationsSearch.data.keys.findIndex(e=>e==a.key)?-1:1)[0])}},selector:"#zotero-roam-citations-autocomplete",placeHolder:"Search by title, year, authors (last names), publication",wrapper:!1,trigger:e=>0!=e.length||(zoteroRoam.interface.popCitationsOverlay(doi=zoteroRoam.citations.currentDOI,citekey=zoteroRoam.citations.currentCitekey,zoteroRoam.citations.currentType),!1),searchEngine:(e,t)=>zoteroRoam.utils.multiwordMatch(e,t,highlight=['<span class="zr-search-match">',"</span>"]),resultsList:!1,events:{input:{results:a=>{if(0<a.detail.results.length)zoteroRoam.citations.pagination=new zoteroRoam.Pagination({data:a.detail.results.map(e=>e.value),render:"zoteroRoam.interface.renderCitationsPagination"}),zoteroRoam.interface.renderCitationsPagination();else{let e=document.querySelector("#zotero-roam-citations-pagination"),t=(e.closest(".main-panel").querySelector(".zotero-roam-citations-results-count").innerHTML=`
                                  <strong>No results</strong> for ${a.detail.query}
                                  `,zoteroRoam.citations.pagination=new zoteroRoam.Pagination({data:[],render:"zoteroRoam.interface.renderCitationsPagination"}),e.querySelector("ul"));t.innerHTML=""}}}}},tagSelection:(o,a)=>new autoComplete({data:{src:async function(t){let e=Array.from(zoteroRoam.data.roamPages.keys());return e.includes(t)||e.push(t),e.map(e=>e==t?{title:e,identity:"self"}:{title:e})},keys:["title"],filter:e=>[...e].sort((e,t)=>e.value.identity&&"self"==e.value.identity?-1e3:e.value.title.length-t.value.title.length)},wrapper:!1,selector:o,trigger:e=>0!=e.length||(zoteroRoam.tagSelection[""+a].close(),!1),searchEngine:(e,t)=>zoteroRoam.utils.multiwordMatch(e,t),placeHolder:"Add tags...",resultsList:{class:"zotero-roam-import-tags-list",maxResults:20,element:(e,t)=>{if(e.classList.add("bp3-menu"),e.classList.add("bp3-elevation"),0<t.results.length)try{zoteroRoam.tagSelection[""+a].goTo(0)}catch(e){}}},resultItem:{class:"zotero-roam-tagselector_option"},events:{input:{blur:e=>{document.querySelector(""+o).value="",zoteroRoam.tagSelection[""+a].close()},selection:e=>{e=e.detail;let t=document.querySelector(o).closest(".options-tags").querySelector(".options-tags_selection"),a=(t.innerHTML+=zoteroRoam.utils.renderBP3Tag(string=e.selection.value.title,{tagRemove:!0,tagAttribute:`data-tag="${e.selection.value.title}"`}),JSON.parse(t.dataset.tags));a.push(e.selection.value.title),t.dataset.tags=JSON.stringify(a),document.querySelector(""+o).value=""}}}}),tribute:{trigger:"",selectClass:"zotero-roam-tribute-selected",containerClass:"zotero-roam-tribute",lookup:"display",menuItemLimit:15,menuItemTemplate:e=>e.original.display,requireLeadingSpace:!0,selectTemplate:e=>e.original.value,searchOpts:{skip:!0},values:(t,e)=>{let a=zoteroRoam.handlers.getLibItems(format=zoteroRoam.config.params.autocomplete.format,display=zoteroRoam.config.params.autocomplete.display);e(a.filter(e=>e[zoteroRoam.config.tribute.lookup].toLowerCase().includes(t.toLowerCase())))}},params:{override_quickcopy:{overridden:!1},always_copy:!1,quick_copy_format:"citekey",autocomplete:{enabled:!1,format:"citation",display:"citekey"},citations:{itemsPerPage:100},notes:{use:"text",split_char:"\n",func:"zoteroRoam.utils.formatItemNotes"},pageMenu:{defaults:["addMetadata","importNotes","viewItemInfo","openZoteroLocal","openZoteroWeb","pdfLinks","sciteBadge","connectedPapers","semanticScholar","googleScholar","citingPapers"],trigger:e=>3<e.length},webimport:{tags:[]},theme:""},requests:[],shortcuts:[],userSettings:{},ref_checking:null,page_checking:null,tag_checking:null,auto_update:null,render_inline:null,editingObserver:null},funcmap:{DEFAULT:"zoteroRoam.formatting.getItemMetadata"},typemap:{artwork:"Illustration",audioRecording:"Recording",bill:"Legislation",blogPost:"Blog post",book:"Book",bookSection:"Chapter",case:"Legal case",computerProgram:"Data",conferencePaper:"Conference paper",document:"Document",email:"Letter",encyclopediaArticle:"Encyclopaedia article",film:"Film",forumPost:"Forum post",hearing:"Hearing",instantMessage:"Instant message",interview:"Interview",journalArticle:"Article",letter:"Letter",magazineArticle:"Magazine article",manuscript:"Manuscript",map:"Image",newspaperArticle:"Newspaper article",patent:"Patent",podcast:"Podcast",presentation:"Presentation",radioBroadcast:"Radio broadcast",report:"Report",statute:"Legislation",thesis:"Thesis",tvBroadcast:"TV broadcast",videoRecording:"Recording",webpage:"Webpage"},addExtensionCSS(){let e=document.createElement("style");e.textContent=`
              #zotero-roam-portal .bp3-overlay-backdrop{opacity:0.4;}
              #zotero-roam-portal > .bp3-overlay > .bp3-dialog-container > .bp3-dialog > .bp3-dialog-body{flex-wrap:nowrap;display:flex;margin:0px;}
              #zotero-roam-portal .bp3-dialog-footer-actions{padding:5px 2.5%;justify-content:space-between;align-items:flex-end;transition:0.2s;}
              #zotero-roam-portal .side-panel{background-color:white;transition:0.5s;font-size:0.8em;overflow:auto;border-radius: 0 6px 6px 0;}
              #zotero-roam-portal [side-panel="hidden"] .side-panel{flex-basis:0%;}
              #zotero-roam-portal [side-panel="hidden"] .side-panel-contents{display: none;}
              #zotero-roam-portal .bp3-dark .side-panel{background-color:#30404d;}
              #zotero-roam-portal .side-panel > .side-panel-contents > *{padding:10px 20px;}
              .zotero-roam-dialog-overlay .bp3-dialog-container, .zotero-roam-dialog-small .bp3-dialog-container{justify-content:start;}
              .zotero-roam-search-overlay .bp3-dialog:not(.bp3-dark), .zotero-roam-citations-search-overlay .bp3-dialog:not(.bp3-dark), .zr-tab-panel-popover .bp3-dialog:not(.bp3-dark){background:white;}
              .zotero-roam-dialog-overlay > .bp3-dialog-container > .bp3-dialog{margin-left: calc(20vw + 2.5%);padding-bottom:0px;box-shadow:none;}
              .zotero-roam-dialog-overlay [side-panel="hidden"]{width:calc(95% - 40vw);}
              .zotero-roam-dialog-overlay [side-panel="visible"]{width:calc(95% - 20vw);}
              .zotero-roam-dialog-overlay [side-panel="visible"] .side-panel{flex-basis:20vw!important;}
              .zotero-roam-citations-search-overlay .main-panel{width:100%;}
              .zotero-roam-dialog-overlay .bp3-dialog .side-panel-contents{width:20vw;}
              .zotero-roam-dialog-small .bp3-dialog{margin-left: calc(18vw + 9.5%);padding-bottom:0px;box-shadow:none;}
              .zotero-roam-dialog-small [side-panel="hidden"]{width:calc(55% - 10vw);}
              .zotero-roam-dialog-small [side-panel="visible"]{width:calc(50% + 8vw);}
              .zotero-roam-dialog-small [side-panel="visible"] .side-panel{flex-basis:18vw!important;}
              .zotero-roam-dialog-small .bp3-dialog .side-panel-contents{width:18vw;}
              #zotero-roam-portal .controls-top{display:flex;width:100%;justify-content:flex-end;font-weight:300;}
              #zotero-roam-portal .header-content{width:100%;margin:0;display:flex;flex-wrap:wrap;}
              h5.panel-tt{font-weight:600;display:inline-block;padding-right:15px;}
              h5.panel-tt[list-type="library"], h5.panel-tt[list-type="references"], .zr-search-scope{color:#137cbd;}
              h5.panel-tt[list-type="citations"]{color:#d9822b;}
              .bp3-dark h5.panel-tt[list-type="library"], .bp3-dark h5.panel-tt[list-type="references"], .bp3-dark .zr-search-scope{color:#48aff0;}
              .bp3-dark h5.panel-tt[list-type="citations"]{color:#ffb366;}
              #zotero-roam-portal .header-left{flex: 0 1 66%;padding-top:5px;padding-left:min(20px, 2vw);overflow-wrap:anywhere;}
              #zotero-roam-portal .header-left .bp3-spinner{width:fit-content;}
              #zotero-roam-portal .header-right{flex: 0 1 34%;}
              .zotero-roam-search-overlay .header-right {position:absolute;right:0px;}
              #zotero-roam-portal .zotero-roam-citations-search-overlay .header-bottom {margin-top:0px;}
              #zotero-roam-portal .header-bottom{flex: 1 0 95%;display:flex;justify-content:space-between;margin: min(20px, 3vh) 2.5%;align-items:baseline;}
              .zr-search-scope {font-weight:500;flex:1 0 auto;}
              .zotero-roam-overlay-close.bp3-large{margin-right:3px;}
              .zotero-roam-overlay-close{margin:0;padding:0;min-width:41px;}
              #zotero-roam-search-autocomplete{flex:0 1 89%;}
              #zotero-roam-citations-autocomplete{flex:1 0 100%;}
              #zotero-roam-search-autocomplete, #zotero-roam-citations-autocomplete{padding:0px 10px;box-shadow:none;}
              #zotero-roam-search-autocomplete::placeholder, #zotero-roam-citations-autocomplete::placeholder{opacity:0.6;}
              #zotero-roam-search-autocomplete:focus, #zotero-roam-citations-autocomplete:focus, #zotero-roam-tagselector_citations:focus{box-shadow:none;}
              :not(.bp3-dark) #zotero-roam-search-autocomplete, :not(.bp3-dark) #zotero-roam-citations-autocomplete{border-bottom: 1px #ececec solid;color: #717171;}
              .bp3-dark #zotero-roam-search-autocomplete, .bp3-dark #zotero-roam-citations-autocomplete{border-bottom: 1px #2f4d75 solid;}
              #zotero-roam-portal .quick-copy-element{margin:0px;font-weight:600;}
              #zotero-roam-portal .clipboard-copy-utility{width:10px;height:5px;padding:0px;}
              li[aria-selected="true"] > .bp3-menu-item, .zotero-roam-tagselector_option[aria-selected="true"]{background-color:#e7f3f7;}
              .bp3-dark li[aria-selected="true"]{background-color:#191919;}
              #zotero-roam-citations-pagination > .bp3-button-group{margin:5px 0;}
              #zotero-roam-search-results-list.bp3-menu, .zotero-roam-citations-search-results-list.bp3-menu {max-height:70vh;overflow-y:scroll;background:unset;padding:0px;padding-bottom:10px;}
              #zotero-roam-search-results-list::-webkit-scrollbar, .zotero-roam-citations-search-results-list::-webkit-scrollbar, .zotero-roam-import-tags-list::-webkit-scrollbar{width: 5px;}
              #zotero-roam-search-results-list::-webkit-scrollbar:hover, .zotero-roam-citations-search-results-list::-webkit-scrollbar:hover{background:#ececec;}
              .zotero-roam-search-item-title{font-weight:500;display:block;}
              .zotero-roam-citation-link{padding-right: 10px;}
              .zotero-roam-library-results-count:empty {padding: 0px;}
              .zotero-roam-library-results-count{display:block;padding:min(6px, 0.2em) 0;}
              .zotero-roam-citations-results-count, .zotero-roam-tag-list-count {padding: 6px 10px;}
              .zotero-roam-search_result{padding:3px 0px;}
              .zotero-roam-citations-search_result{padding:3px 6px;}
              .zotero-roam-citations-search_result[in-library="true"]{background-color:#f3fdf3;border-left: 2px #a4f1a4 solid;}
              .bp3-dark .zotero-roam-citations-search_result[in-library="true"]{background-color:#5863582e;}
              .zotero-roam-page-control > span[icon]{margin-right:0px;}
              #zotero-roam-library-rendered, #zotero-roam-citations-pagination {width:97%;margin: 0 auto;}
              #zotero-roam-library-rendered[view="search"] #zotero-roam-search-selected-item, #zotero-roam-library-rendered[view="item"] #zotero-roam-library-search-div{display:none;}
              #zotero-roam-library-rendered[view="search"][has-results] + .bp3-dialog-footer-actions, #zotero-roam-citations-pagination + .bp3-dialog-footer-actions{box-shadow: 0px -4px 10px 0px #d6d6d6;}
              .bp3-dark #zotero-roam-library-rendered[view="search"][has-results] + .bp3-dialog-footer-actions, .bp3-dark #zotero-roam-citations-pagination + .bp3-dialog-footer-actions{box-shadow: 0px -4px 10px 0px #171717;}
              #zotero-roam-library-rendered[view="item"] + .bp3-dialog-footer-actions{opacity:0;}
              .selected-item-header, .selected-item-body{display:flex;justify-content:space-around;}
              .selected-item-body{flex-wrap:wrap;}
              .item-basic-metadata, .item-additional-metadata, .zotero-roam-citation-abstract{background:#f5f8fa;}
              .bp3-dark .item-basic-metadata, .bp3-dark .item-additional-metadata, .bp3-dark .zotero-roam-citation-abstract{background-color:#2b3135;}
              .item-basic-metadata, .item-additional-metadata{flex: 0 1 60%;padding: 20px;}
              .item-basic-metadata{padding-top:10px;}
              h4.item-title{margin-bottom:5px;}
              .item-citekey-section, .item-actions{flex:0 1 33%;}
              .item-abstract{padding:15px;border-top: 1px #e6e6e6 solid;border-bottom: 1px #e6e6e6 solid;}
              .bp3-dark .item-abstract{border-top-color: #4a4a4a;border-bottom-color: #4a4a4a;}
              .item-additional-metadata{padding-top:0px;}
              .item-additional-metadata p strong ~ span {margin:3px;}
              .item-pdf-notes, .item-actions-additional{margin-top: 25px;}
              .item-actions-additional{flex: 0 1 95%;}
              .item-actions > .bp3-card{background-color: #eff8ff;box-shadow:none;}
              .bp3-dark .item-actions > .bp3-card{background-color:#2b3135;}
              .item-citekey-section{margin:10px 0px; overflow-wrap:break-word;}
              .item-citekey-section .citekey-element{padding:0 10px;display:flex;align-items:baseline;overflow-wrap:anywhere;}
              .item-citekey-section .bp3-icon{margin-right:10px;}
              .copy-buttons > a.bp3-button{font-size:0.7em;margin:5px;}
              .copy-buttons > a.bp3-button, .copy-buttons > a.bp3-button:hover{border: 1px #f1f7ff solid;}
              .bp3-dark .copy-buttons > a.bp3-button, .bp3-dark .copy-buttons > a.bp3-button{border: 1px #2f4d75 solid;}
              .item-rendered-notes p{font-weight:350;}
              .zotero-roam-sequence{background-color:#c79f0c;padding:3px 6px;border-radius:3px;font-size:0.85em;font-weight:normal;color:white;}
              .controls-top .zotero-roam-sequence {background: unset;color: #c79f0c;}
              .zotero-roam-tribute {max-width:800px;max-height:300px;overflow:scroll;margin-top:5px;}
              .zotero-roam-tribute ul {list-style-type:none;padding:0px;background-color: white;border:1px #e4e4e4 solid; border-radius:2px;}
              .zotero-roam-tribute ul li {padding: 2px 5px;font-weight:300;}
              .zotero-roam-tribute-selected {background-color: #4f97d4;color:white;}
              .zotero-roam-page-doi{margin:10px;display:block;font-weight:600;letter-spacing:0.3mm;}
              .zotero-roam-page-menu{justify-content:space-between;border-width:0px;padding:5px;border-radius:5px;background-color: #f8f8f9;box-shadow:none;}
              .zotero-roam-page-menu-header{display:flex;}
              .zotero-roam-page-menu-actions{flex-wrap:wrap;flex: 1 1 auto;}
              .zotero-roam-page-menu hr{margin:2px 0;}
              .scite-badge{padding-top:5px;min-width:25%;}
              .scite-badge[style*='position: fixed; right: 1%;'] {display: none!important;}
              .zotero-roam-page-menu-actions.bp3-button-group .bp3-button {flex: 0 1 auto;}
              .zotero-roam-page-menu-pdf-link, .item-pdf-link{font-weight:600;text-align:left!important;}
              .zotero-roam-page-menu-citations{display:flex;padding:5px;flex-wrap:wrap;padding-bottom:0px;border-top: 1px #f1f1f1 solid;}
              .zotero-roam-page-menu-citations:empty{padding:0px;}
              .bp3-dark .zotero-roam-page-menu-citations{border-top-color:#f1f1f12e;}
              .zotero-roam-page-menu-citations > button{flex: 1 0 33%;}
              .zotero-roam-page-menu-backlinks-list {width:100%;display:flex;flex-direction:column;margin: 10px 0px;}
              .zotero-roam-page-menu-backlinks-total, .zotero-roam-page-menu-references-total {font-weight: 700;}
              .backlinks-list_divider{display: flex;align-items: center;margin: 10px 5px;}
              .backlinks-list_divider hr{flex: 0 1 100%;}
              .zotero-roam-search_result > .bp3-menu-item, .zotero-roam-citations-search_result > .bp3-menu-item {justify-content:space-between;user-select:initial;padding: 3px 10px;}
              .zotero-roam-citations-search_result > .bp3-menu-item:hover, .zotero-roam-list-item > .bp3-menu-item:hover, .zr-datalist-item > .bp3-menu-item:hover {background-color:unset;cursor:unset;}
              .zotero-roam-citation-metadata, .zotero-roam-search-item-contents{flex: 0 1 97%;white-space:normal;}
              .zotero-roam-citation-links-list{display:block;}
              .zotero-roam-citations-search_result .zotero-roam-search-item-key {flex-wrap:wrap;}
              .zotero-roam-search_result .zotero-roam-search-item-key {flex-wrap:nowrap;}
              .zotero-roam-search_result .zotero-roam-search-item-key .bp3-icon {padding:6px;}
              .zotero-roam-search-item-key{flex: 1 0 20%;text-align:right;overflow-wrap:anywhere;font-size:0.8em;display:flex;align-items:center;justify-content:flex-end;}
              .zotero-roam-search-item-key .zotero-roam-citation-identifier-link {display:block;flex: 0 0 100%;}
              .zotero-roam-search-item-key a, .zotero-roam-search-item-key button, .zotero-roam-list-item-actions button, .zotero-roam-list-item-actions a{overflow-wrap:break-word;}
              .zotero-roam-citation-toggle-abstract{font-size:0.8em;overflow-wrap:break-word;}
              .zotero-roam-citation-abstract, .item-abstract{white-space:break-spaces;}
              .zotero-roam-citation-abstract{padding:5px 10px;flex:0 1 100%;margin-top:5px;border-radius:5px;}
              .import-header{display:flex;justify-content:space-between;align-items:center;padding:10px 5px!important;margin-bottom:20px;}
              .import-options{display:flex;justify-content:space-between;flex-wrap:wrap;}
              .options-library-list, .options-collections-list{flex:1 0 50%;}
              .options-collections-list {max-height: 50vh;overflow-y:scroll;padding-top:2px;}
              .options-collections-list::-webkit-scrollbar {width:0.2em;}
              .options-collections-list label{font-weight:400;margin-left:40px;font-size:0.8em;margin-bottom:0px;}
              .options-collections-list label[data-option-depth="0"]{margin-left:0px;}
              .options-collections-list label[data-option-depth="1"]{margin-left:20px;}
              .options-library-list label{font-weight:600;}
              .options-tags{padding:20px 0px;flex: 1 0 100%;flex-wrap:wrap;display:flex;}
              .options-tags-select{flex: 1 0 50%;}
              .options-tags_selection{flex: 1 0 50%;padding:0px 8px;}
              .options-tags_selection .bp3-tag{word-break:break-word;}
              .zotero-roam-tags-autocomplete{box-shadow:none;background:none;}
              .zotero-roam-import-tags-list{position:fixed;max-width:calc(20vw - 40px);z-index:20;border:1px #e1eeff solid;max-height:250px;overflow:scroll;}
              .zotero-roam-import-tags-list > li{padding:3px 5px;}
              li.import-items_selected{display:flex;justify-content:space-between;background:#f9fafb;padding:5px 0 5px 15px;}
              .bp3-dark li.import-items_selected{background:#2e2f3187;}
              .selected_title{font-weight:500;}
              .selected_origin{display:block;font-weight:300;}
              .selected_info{flex: 0 1 90%;}
              .related-item_listed{display:flex;align-items:flex-start;padding:0px;}
              .related-sublist[list-type="references"] li:nth-child(even) {background-color:#e8f0ff;}
              .bp3-dark .related-sublist[list-type="references"] li:nth-child(even) {background-color:#2d3a52;}
              .related-sublist[list-type="citations"] li:nth-child(even) {background-color:#fdfcf6;}
              .bp3-dark .related-sublist[list-type="citations"] li:nth-child(even) {background-color:#52452d;}
              .related-item_listed[item-type="reference"]:hover {background-color:#e1ecff;}
              .related-item_listed[item-type="citation"]:hover {background-color:#fff6e1;}
              .related_year, .related_info{font-size:0.9em;padding: 0px 0px 6px 10px;}
              .related_year{flex: 0 0 auto;}
              .related_info{line-height:normal;flex: 1 2 90%;}
              .related_info > *:not(.zotero-roam-search-item-title), .related_year{line-height:2em;}
              .related_state{flex: 1 0 auto;overflow-wrap:anywhere;}
              .related_state button.bp3-button{padding:0px 0px;}
              .related_state button.bp3-button, .related_state button.bp3-button:hover{border-radius:0px;}
              [in-graph="true"] .related_state {align-self:stretch;text-align:right;}
              [in-graph="true"] .related_state button {height:100%;}
              .selected_state{flex: 1 0 10%;text-align:center;}
              [item-type="reference"] .related_year, [item-type="reference"] a {color:#136fce!important;}
              .bp3-dark [item-type="reference"] .related_year, .bp3-dark [item-type="reference"] a {color:#3fb8ff!important;}
              .bp3-dark [item-type="citation"] .related_year, .bp3-dark [item-type="citation"] a {color:#bf7326!important}
              [item-type="citation"] .related_year, [item-type="citation"] a {color:#e09f26!important;}
              .zotero-roam-page-related{opacity:0.6;position:absolute;right:10px;top:10px;}
              .roam-log-page{position:relative;}
              .roam-body.mobile .zotero-roam-page-menu-header .scite-badge{margin:0 auto;}
              .roam-body.mobile + #zotero-roam-portal .quick-copy-element{display:none;}
              .roam-body.mobile + #zotero-roam-portal .bp3-dialog-footer-actions{flex-direction:column;align-items:center;}
              .bp3-dialog-footer-actions button.zotero-roam-update-data{margin-left:0px;}
              .zotero-roam-item-timestamp{margin-right:20px;}
              .zotero-roam-list-item .zotero-roam-item-contents{flex:0 1 100%;}
              .zotero-roam-list-item > .bp3-menu-item{flex-wrap:nowrap;user-select:initial;}
              .zotero-roam-list-item-actions{text-align:right;flex: 0 0 15%;}
              .zotero-roam-auxiliary-overlay .zotero-roam-list-item-actions button, .zotero-roam-auxiliary-overlay .zotero-roam-list-item-actions a{opacity:0.6;}
              .zotero-roam-list-item-key {padding:0 5px;}
              .zotero-roam-auxiliary-overlay .main-panel{padding:0px 10px;}
              .zotero-roam-auxiliary-overlay .main-panel ul.bp3-list-unstyled {padding:15px 0;}
              .zotero-roam-explo-import{position:absolute;right:0px;opacity:0.7;z-index:10;}
              .zr-explo-list-item .bp3-menu-item{flex-wrap:wrap;}
              .zr-explo-title{flex:1 0 100%;}
              .zr-explo-title .bp3-checkbox{margin-bottom:0px;}
              .zr-explo-publication, .zr-explo-abstract{display:block;white-space:break-spaces;}
              .zr-explo-list-item .zotero-roam-item-contents{padding-left:30px;}
              .zotero-roam-search-item-authors, .zotero-roam-citation-origin {padding-right: 8px;}
              .zotero-roam-dashboard-overlay .main-panel {display: flex;}
              .zotero-roam-dashboard-overlay .side-section {padding:15px;}
              .zotero-roam-dashboard-overlay .side-section {flex: 1 0 20%;}
              .zotero-roam-dashboard-overlay .main-section {flex: 1 0 80%;padding-left:15px;padding-bottom:15px;}
              .zotero-roam-dashboard-overlay .side-section .bp3-tab-list {width: 100%;}
              .zotero-roam-dashboard-overlay .bp3-tab-panel {display: flex;flex-wrap: wrap;justify-content: space-between;margin-top: 0px;}
              .zr-tab-panel-header, .zr-tab-panel-contents {flex: 0 0 100%;}
              .zr-tab-panel-header {display:flex;justify-content:space-between;align-items:flex-start;}
              .zr-tab-panel-description {padding-top:15px;}
              .zr-tab-panel-contents {padding-right:30px;position:relative;}
              .zr-tab-panel-toolbar {display: flex;align-items: baseline;padding: 10px 0px;justify-content: space-between;flex: 0 0 100%;flex-wrap: wrap;border-bottom: 1px #cccccc solid;}
              .zr-tab-panel-toolbar > .bp3-button-group > span {font-size: 0.9em;}
              .zr-datalist-sort_option {padding: 3px 10px;}
              .zr-datalist-sort_option:first-child {padding-left:0px;}
              .zr-datalist-sort_option:last-child {padding-right:0px;}
              .zr-datalist-sort_option label {width: auto;display: inline-block;text-align: center;cursor: pointer;font-weight:500;margin-bottom: 0px;}
              .zr-datalist-sort_option input, .zr-datalist-sort_option input:focus {appearance: none;outline: none;cursor: pointer;padding: 0px;background: none;margin: 0px;}
              .zr-datalist-sort_option input:checked, .zr-datalist-sort_option input:checked ~ span, .zr-datalist-sort_option input:checked ~ label {color: #3081e4;}
              .zr-datalist-sort_option .bp3-icon {padding-right:5px;}
              .zr-tab-panel-popover .bp3-dialog {box-shadow:none;border: 1px #ececec solid;padding-bottom:0px;margin: 30px auto;width:80%;}
              .zr-tab-panel-popover .bp3-dialog-header {display:flex;padding:0px;}
              .zr-tab-panel-popover .bp3-dialog-header h4 {font-size:14px;text-align:center;}
              .zr-tab-panel-popover .bp3-dialog-body {display: flex;flex-wrap: wrap;align-items: baseline;margin: 15px 0px;}
              .zr-tab-panel-popover .bp3-dialog-body .zr-tag-entry {display:flex;flex: 0 0 100%;justify-content:space-around;}
              .zr-tag-column_input input {box-shadow:none;font-weight:bold;text-overflow:ellipsis;}
              .zr-tag-column_input input::placeholder {font-weight:normal;}
              .zr-tab-panel-popover .bp3-dialog-footer {display:flex;justify-content:flex-end;margin-bottom: 10px;}
              .zr-tab-panel-popover-footer {display: flex;flex: 0 1 auto;text-align: right;align-items: baseline;}
              .zr-tab-panel-popover-footer > * {margin: 10px 20px;}
              .zr-tab-panel-popover[overlay-visible="true"] + .zr-tab-panel-datalist {opacity: 0.4;}
              .zr-tab-panel-datalist {flex: 0 0 100%;padding:0px;max-height:70vh;overflow-y:scroll;background:unset;border-radius:0px;}
              .zr-tab-panel-datalist-footer{display:flex;justify-content: space-between;border-top:1px #e6e6e6 solid;align-items:baseline;}
              .zr-datalist-item {background:white;padding:5px 10px;display:flex;border-bottom:1px #f5f5f5 solid;}
              .zr-datalist-item:last-child{border-bottom:1px white solid;}
              .zr-datalist-item .bp3-menu-item {justify-content:space-between;align-items:baseline;width:100%;}
              .zr-datalist-item [zr-role="title"] {font-weight:600;margin-right:15px;}
              .zr-datalist-item [zr-role="title"]::before {content: '# '}
              .zr-datalist-item [zr-role="taglist"] {margin:5px;}
              [zr-role="taglist"] [data-tag-source] {padding: 3px 8px;margin: 3px 5px;margin-left:0px;border-radius: 3px;display:inline-block;}
              label[data-tag-source] {color: #b3b3b3;background:#f9f9f9;border: 1px #e9e9e9 solid;font-weight:400;padding-top:4px;padding-bottom:4px;padding-right:15px;border-radius:5px;max-width:fit-content;}
              [data-tag-source] .bp3-control-indicator {margin-left: -15px!important;border-radius:10px!important;}
              [data-tag-source="roam"] input:checked ~ .bp3-control-indicator {background-color: #48a5e7;box-shadow: none;}
              [data-tag-source="roam"] input:checked ~ .zr-tag-name {color: #48a5e7;}
              [data-tag-source="zotero"] input:checked ~ .bp3-control-indicator {background-color: #e1881a;box-shadow: none;}
              [data-tag-source="zotero"] input:checked ~ .zr-tag-name {color: #e1881a;}
              [zr-role="taglist"] [data-tag-source="zotero"] {color: #e1881a;background-color: #fff5e7;}
              [zr-role="taglist"] [data-tag-source="roam"] {color: #48a5e7;background-color: #e7f5ff;}
              .zr-datalist-item .bp3-menu-item-label > .bp3-button-group {opacity:0.6;}
              .zr-datalist-item:hover .bp3-menu-item-label > .bp3-button-group {opacity:1;transition:0.3s;}
              .zr-tag-stats {flex: 0 1 66%;text-align: right;}
              .zr-tag-stats span {display:block;}
              .zr-loading-overlay {position: absolute;width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;z-index: 5;}
              .zr-loading-overlay.bp3-dialog {box-shadow:none;margin:0px;padding:0px;opacity:0.7;}
              .zr-highlight {color: #206fe6;}
              .bp3-dark .zr-highlight{color:#3fb8ff;}
              .zr-highlight-2 {color:#d9822b;}
              .zr-secondary {color: #7b7b7b;font-weight:300;}
              .zr-auxiliary{color:#5c7080;}
              .bp3-dark .zr-auxiliary{color:#95a8b7;}
              [in-graph='true'] .bp3-menu-item-label > *, [in-graph='true'] .citekey-element {color: #21b377;}
              [in-graph='false'] .bp3-menu-item-label .bp3-icon, [in-graph='false'] .citekey-element .bp3-icon {color: #F29D49;}
              .zr-search-match {background-color: #fbde0f40;padding: 2px;border-radius: 3px;}
              .zotero-roam-cm-option .bp3-menu-item, .zotero-roam-cm-option .bp3-menu-item::before {font-size: 0.95rem;}
              .zr-text-small, .zr-text-small .bp3-button[class*='bp3-icon-']::before, .zr-text-small select, .zr-text-small button {font-size:0.85rem;}
              @media (max-width:600px){
                  .zotero-roam-page-menu-header{flex-direction:column-reverse;}
                  .zotero-roam-dialog-overlay .bp3-dialog, .zotero-roam-dialog-small .bp3-dialog{margin-left: calc(min(20vw, 30px) + 2.5%);padding-bottom:0px;box-shadow:none;}
                  .zotero-roam-dialog-overlay .bp3-dialog[side-panel="hidden"], .zotero-roam-dialog-small .bp3-dialog[side-panel="hidden"]{width:calc(95% - min(40vw, 60px));}
                  .zotero-roam-dialog-overlay .bp3-dialog[side-panel="visible"], .zotero-roam-dialog-small .bp3-dialog[side-panel="visible"]{width:calc(95% - min(20vw, 30px));}
                  .zotero-roam-dialog-overlay .bp3-dialog[side-panel="visible"] .side-panel, .zotero-roam-dialog-small .bp3-dialog[side-panel="visible"] .side-panel{flex-basis:min(20vw, 30px)!important;}
                  #zotero-roam-portal .bp3-dialog[side-panel="hidden"] .side-panel{flex-basis:0%;}
                  .zotero-roam-dialog-overlay .bp3-dialog .side-panel-contents, .zotero-roam-dialog-small .bp3-dialog .side-panel-contents{width:min(20vw, 30px);}
                  #zotero-roam-search-selected-item .item-citekey-section{margin:0px 0px;}
                  #zotero-roam-search-selected-item .selected-item-header .copy-buttons{display:none;}
                  #zotero-roam-search-selected-item .selected-item-header{flex-direction:column-reverse;}
                  #zotero-roam-search-selected-item .selected-item-body{flex-direction:column;}
                  .zotero-roam-page-menu-actions .bp3-button, .zotero-roam-page-menu-citations .bp3-button{font-size:0.85em;}
                  .zotero-roam-citations-search_result > .bp3-menu-item{flex-direction:column;}
                  .zotero-roam-citations-search_result .zotero-roam-citation-copy-doi, .zotero-roam-citations-search_result .zotero-roam-citation-add-import{display:none;}
                  .zotero-roam-search-item-key{text-align:left;}
                  .related_state{flex: 1 2 auto;}
              }
              `,document.head.append(e)}};var e=document.createElement("script"),e=(e.src="https://cdn.jsdelivr.net/npm/@tarekraafat/autocomplete.js@10.1.5/dist/autoComplete.js",e.type="text/javascript",document.getElementsByTagName("head")[0].appendChild(e),void 0===window.Tribute&&((e=document.createElement("script")).src="https://cdn.jsdelivr.net/npm/tributejs@5.1.3",e.type="text/javascript",document.getElementsByTagName("head")[0].appendChild(e)),document.createElement("script"));e.src="https://cdn.scite.ai/badge/scite-badge-latest.min.js",e.type="application/javascript",e.async=!0,document.getElementsByTagName("head")[0].appendChild(e)})(),zoteroRoam.utils={async addBlock(e,t,a=0,o={}){var r=window.roamAlphaAPI.util.generateUID();let i={string:t,uid:r};if(0<Object.keys(o).length)for(k of Object.keys(o))["children-view-type","alignment","heading"].includes(k)&&(i[k]=o[k]);return await window.roamAlphaAPI.createBlock({location:{"parent-uid":e,order:a},block:i}),r},categorizeTags(e,a,o){let r=[];e=[...e].sort((e,t)=>t<e?-1:1),o=[...o].sort((e,t)=>e.title>t.title?-1:1);for(let t of e){var i=r.findIndex(e=>zoteroRoam.utils.searchEngine(t,e.token,{match:"exact"})),n=a.get(t);-1==i?r.push({token:t.toLowerCase(),zotero:n.constructor===Array?n:[n],roam:[]}):n.constructor===Array?r[i].zotero.push(...n):r[i].zotero.push(n)}r=r.sort((e,t)=>e.token<t.token?-1:1);for(let t of o){var s=r.findIndex(e=>zoteroRoam.utils.searchEngine(t.title,e.token,{match:"exact"}));0<=s&&r[s].roam.push(t)}return r},escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},executeFunctionByName(e,t){for(var a=Array.prototype.slice.call(arguments,2),o=e.split("."),r=o.pop(),i=0;i<o.length;i++)t=t[o[i]];return t[r].apply(t,a)},findCommonTags(t,{exclude_attachments:e=!0,excluded_tags:a=[],more_than:o=0}={}){let r=t.data.tags.map(e=>e.tag.toLowerCase()).filter(e=>!a.includes(e)),i=1==e?zoteroRoam.data.items.filter(e=>!["attachment","note","annotation"].includes(e.data.itemType)):zoteroRoam.data.items;return i=i.filter(e=>e.key!=t.key),i.map(e=>{let t=e.data.tags.map(e=>e.tag.toLowerCase()),a=0,o=[];return t.forEach(e=>{r.includes(e)&&(a+=1,o.push(e))}),{item:e,proximity:a,commons:o}}).filter(e=>e.proximity>o)},findSameDay(t,{exclude_attachments:e=!0}={}){let a=zoteroRoam.data.items.filter(e=>new Date(e.data.dateAdded).toDateString()==t.toDateString());return 0==a.length?[]:1==e?a.filter(e=>!["attachment","annotation","note"].includes(e.data.itemType)):a},formatBib(e){e=e.match('csl-entry">(.+)</div>')[1];let t=document.createElement("textarea"),a=(t.innerHTML=e,t.innerText);a=a.replaceAll(/<\/?i>/g,"__");return a=a.replaceAll(/<a href="(.+)">(.+)<\/a>/g,"[$2]($1)"),a},splitNotes(e,t=zoteroRoam.config.params.notes.split_char){return 0!=e.length&&e.map(e=>e.data.note.split(t))},formatItemNotes(e){return e.flat(1).map(e=>zoteroRoam.utils.parseNoteBlock(e)).filter(e=>e.trim()).map(e=>e.split("\n").map(e=>({string:e}))).flat(1)},formatItemReference(a,o,{accent_class:r="zr-highlight"}={}){switch(o){case"tag":return`#[[@${a.key}]]`;case"pageref":return`[[@${a.key}]]`;case"citation":let e=a.meta.creatorSummary||"";return e=a.meta.parsedDate?`${e} (${new Date(a.meta.parsedDate).getUTCFullYear()})`:e,e=`[${0<e.length?e:a.key}]([[@${a.key}]])`,e;case"popover":let t=a.meta.creatorSummary||"";return t=a.meta.parsedDate?`${t} (${new Date(a.meta.parsedDate).getUTCFullYear()})`:t,t=`{{=: ${0<t.length?t:a.key} | {{embed: [[@${a.key}]]}} }}`,t;case"inline":return(a.meta.creatorSummary||"")+(a.meta.parsedDate?` (${new Date(a.meta.parsedDate).getUTCFullYear()})`:"");case"zettlr":return(a.meta.creatorSummary||"")+(a.meta.parsedDate?` (${new Date(a.meta.parsedDate).getUTCFullYear()})`:"")+" : "+a.data.title;case"zettlr_accent":return`<span class="${r}">`+(a.meta.creatorSummary||"")+(a.meta.parsedDate?` (${new Date(a.meta.parsedDate).getUTCFullYear()})`:"")+"</span>"+" : "+a.data.title;default:return"@"+a.key}},getRoamPages(){return roamAlphaAPI.q("[:find ?title ?uid :where[?e :node/title ?title][?e :block/uid ?uid]]")},getAllRefPages(){return roamAlphaAPI.q('[:find ?title ?uid :where[?e :node/title ?title][(clojure.string/starts-with? ?title "@")][?e :block/uid ?uid]]')},getSelectPages(e){return roamAlphaAPI.q("[:find (pull ?e [:node/title :block/uid]) :in $ [?k ...] :where[?e :node/title ?title][(clojure.string/starts-with? ?title ?k)]]",e).flat(1)},getItemPrefix(e){return e.library.type+"s/"+e.library.id},getLibraries(){return Array.from(zoteroRoam.data.libraries.values()).map(t=>{var e=zoteroRoam.data.keys.find(e=>e.key==t.apikey).access,[a,o]=t.path.split("/");let r={};"users"==a?r=e.user||{}:e.groups?r=Object.keys(e.groups).includes(o)?e.groups[o]:e.groups.all:console.log(e);a=zoteroRoam.data.collections.filter(e=>zoteroRoam.utils.getItemPrefix(e)==t.path);return{name:0<(a=zoteroRoam.utils.sortCollectionsList(a)).length?a[0].library.name:t.path,apikey:t.apikey,path:t.path,writeable:r.write||!1,collections:a,version:t.version}})},includes_anycase(e,t){return e.join("\n").toLowerCase().split("\n").includes(t.toLowerCase())},lookForPage(e){let t=null;e=window.roamAlphaAPI.q("[:find ?uid :in $ ?title :where[?p :node/title ?title][?p :block/uid ?uid]]",e);return t=0<e.length?{present:!0,uid:e[0][0]}:{present:!1},t},makeTimestamp(e){let t=e.constructor===Date?e:new Date(e);return t.getHours()+":"+("0"+t.getMinutes()).slice(-2)},makeDictionary(e){return e.reduce((e,t)=>{var a=t.charAt(0).toLowerCase();return e[a]?e[a].push(t):e[a]=[t],e},{})},makeTagList(a){let o=zoteroRoam.utils.makeDictionary(Array.from(a.keys())),e=Object.keys(o).sort((e,t)=>e<t?-1:1);return e.map(e=>{var t=zoteroRoam.utils.getSelectPages(Array.from(new Set([e,e.toUpperCase()])));return zoteroRoam.utils.categorizeTags(o[e],a,t)}).flat(1)},getTagUsage(e,{count_roam:t=!1}={}){return e.zotero.reduce((e,t)=>e+=t.meta.numItems,0)+(t?e.roam.length:0)},getTagListStats(e){return e.map(e=>({nTags:e.zotero.length,nAuto:0==e.zotero.length?0:e.zotero.filter(e=>1==e.meta.type).length,in_roam:0<e.roam.length?1:0})).reduce((e,t)=>(e.nTags+=t.nTags,e.nAuto+=t.nAuto,e.nRoam+=t.in_roam,e),{nTags:0,nAuto:0,nRoam:0})},sortTagList(e,t="alphabetical"){let a=[...e];switch(t){case"usage":return a.sort((e,t)=>zoteroRoam.utils.getTagUsage(e)>zoteroRoam.utils.getTagUsage(t)?-1:1);case"roam":return a.sort((e,t)=>e.roam.length>t.roam.length?-1:1);default:return a}},renderTagList(){let e=document.getElementById("zr-tag-manager-pagination"),t=zoteroRoam.tagManager.pagination.getCurrentPageData();var a=zoteroRoam.utils.getTagListStats(zoteroRoam.tagManager.pagination.data),o=zoteroRoam.tagManager.pagination.data.length;document.querySelector(".zotero-roam-tag-list-count").innerHTML=`
              <strong>${zoteroRoam.tagManager.pagination.startIndex}-${zoteroRoam.tagManager.pagination.startIndex+t.length-1}</strong> / ${o} entries
              `,document.querySelector(".zr-tag-stats").innerHTML=`<span>Zotero has ${a.nTags} tags (${a.nAuto} / ${Math.round(a.nAuto/a.nTags*100)}% automatic), matched in ${o} groups</span><span>${a.nRoam} are in Roam (${Math.round(a.nRoam/o*100)}%)</span>`,e.innerHTML=t.map(e=>{var t=1==e.zotero.length&&(0==e.roam.length||1==e.roam.length&&e.zotero[0].tag==e.roam[0].title);let a=e.token,o="",r="Merge",i="git-merge";var n=zoteroRoam.utils.getTagUsage(e);return t?(a=e.zotero[0].tag,r="Edit",i=!1):o=`
                    <div zr-role="taglist" class="zr-text-small">
                    ${e.roam.map(e=>`<span data-tag-source="roam" data-tag="${e.title}" data-uid="${e.uid}">${e.title}</span>`).join("\n")}
                    ${e.zotero.map(e=>`<span data-tag-source="zotero" data-tag="${e.tag}" data-tag-type="${e.type||""}">${e.tag} (${e.meta.numItems})</span>`).join("\n")}
                    </div>
                    `,`
                  <li role="option" class="zr-datalist-item" data-token="${e.token}" in-graph="${0<e.roam.length}">
                      <div class="bp3-menu-item">
                          <div style="flex:1 1 80%;">
                              <span zr-role="title">${a}</span>
                              <span class="zr-auxiliary zr-text-small">${n} item${1<n?"s":""}</span>
                              ${o}
                          </div>
                          <span class="bp3-menu-item-label">
                              <div class="bp3-button-group bp3-minimal zr-text-small">
                                  ${zoteroRoam.utils.renderBP3Button_group(r,{buttonClass:"bp3-intent-primary",icon:i,buttonAttribute:`zr-action="${r}"`})}
                                  ${zoteroRoam.utils.renderBP3Button_group("Delete",{buttonClass:"bp3-intent-danger",buttonAttribute:'zr-action="Delete"'})}
                              </div>
                          </span>
                      </div>
                  </li>
                  `}).join("\n");let r=document.querySelector('.bp3-tab-panel[name="tag-manager"] .zr-tab-panel-popover[overlay-visible="true"]');r&&(r.querySelector(".bp3-dialog-body").innerHTML="",r.querySelector(".bp3-dialog-footer").innerHTML="",r.style.display="none",r.setAttribute("overlay-visible","hidden"))},refreshTagLists(e=Object.keys(zoteroRoam.data.tags)){e.forEach(e=>{var t=zoteroRoam.data.libraries.get(e).version,a=zoteroRoam.tagManager.lists[e].lastUpdated,{library:o,by:r}=zoteroRoam.tagManager.activeDisplay;Number(t)>Number(a)&&(o&&o.path==e&&(document.querySelector('.bp3-tab-panel[name="tag-manager"] .zr-tab-panel-contents .zr-loading-overlay').style.display="flex"),zoteroRoam.tagManager.lists[e].data=zoteroRoam.utils.makeTagList(zoteroRoam.data.tags[e]),zoteroRoam.tagManager.lists[e].lastUpdated=t,o&&o.path==e&&(zoteroRoam.utils.updateTagPagination(o.path,{by:r}),document.querySelector('.bp3-tab-panel[name="tag-manager"] .zr-tab-panel-contents .zr-loading-overlay').style.display="none"))})},updateTagPagination(t,{by:e="usage"}={}){var{library:a,by:o}=zoteroRoam.tagManager.activeDisplay,o=!(!a||t!=a.path||e!=o);if(null==a){let e=document.querySelector('.bp3-tab-panel[name="tag-manager"] .zr-tab-panel-toolbar');e.querySelector(".bp3-html-select")||(a=Array.from(zoteroRoam.data.libraries.keys()).filter(e=>e!=t).map(e=>({value:e,label:e})),e.innerHTML+=zoteroRoam.utils.renderBP3HTMLSelect([{value:t,label:t},...a],{varName:"",divClass:"bp3-minimal zr-text-small"}))}zoteroRoam.tagManager.activeDisplay={library:zoteroRoam.data.libraries.get(t),by:e};a="alphabetical"==e?zoteroRoam.tagManager.lists[t].data:zoteroRoam.utils.sortTagList(zoteroRoam.tagManager.lists[t].data,e);o?zoteroRoam.tagManager.pagination.data=a:zoteroRoam.tagManager.pagination=new zoteroRoam.Pagination({data:a,itemsPerPage:30,render:"zoteroRoam.utils.renderTagList"}),zoteroRoam.tagManager.pagination.renderResults()},makeDNP(e,{brackets:t=!0}={}){e=`${["January","February","March","April","May","June","July","August","September","October","November","December"][(e=e.constructor!==Date?new Date(e):e).getMonth()]} ${zoteroRoam.utils.makeOrdinal(e.getDate())}, `+e.getFullYear();return t?`[[${e}]]`:e},readDNP(e){let[,t,a,o]=Array.from(e.matchAll(/(.+) ([0-9]+).{2}, ([0-9]{4})/g))[0];return new Date(parseInt(o),["January","February","March","April","May","June","July","August","September","October","November","December"].findIndex(e=>e==t),parseInt(a))},makeMetaString(e){let t="";var a=[e.data.publicationTitle,e.data.university,e.data.bookTitle].filter(Boolean);return 0<a.length&&(t+=" "+a[0]),e.data.publisher&&(t+=", "+e.data.publisher,e.data.place&&(t+=": "+e.data.place)),e.data.volume&&(t+=", "+e.data.volume,e.data.issue&&(t+=`(${e.data.issue})`)),t+=e.data.pages?`, ${e.data.pages}.`:".",t},makeOrdinal(e){var t=e%10;return 1==t&11!=e?e+"st":2==t&12!=e?e+"nd":3==t&13!=e?e+"rd":e+"th"},makeLinkToPDF(e){var t="group"==e.library.type?"groups/"+e.library.id:"library";return["linked_file","imported_file","imported_url"].includes(e.data.linkMode)?`[${e.data.filename||e.data.title}](zotero://open-pdf/${t}/items/${e.data.key})`:`[${e.data.title}](${e.data.url})`},makePDFLinks(e){return e.constructor===Array&&0<e.length?e.map(e=>zoteroRoam.utils.makeLinkToPDF(e)):e.constructor===Object&&zoteroRoam.utils.makeLinkToPDF(e)},matchArrays(e,t){return 0<e.filter(e=>t.includes(e)).length},matchUnnested(e,t,a,o=0){let r=e.indexOf(t,o);var i;return 0<=r&&((i=a.find(e=>r>=e.loc&&r<e.end))?zoteroRoam.utils.matchUnnested(e,t,a,o=i.end):{loc:r,end:r+t.length})},multiwordMatch(e,t,o=[]){var a=Array.from(new Set(e.toLowerCase().split(" ").filter(Boolean))).sort((e,t)=>e.length>t.length?-1:1),r=t.toLowerCase();let i=t,n=[],s=!1;for(let e=0;e<a.length;e++){var l=zoteroRoam.utils.matchUnnested(r,a[e],n);if(!l){s=!1;break}s=!0,n.push(l)}if(2==o.length){let[t,a]=o;n.sort((e,t)=>e.loc>t.loc?-1:1).forEach(e=>{i=i.substring(0,e.loc)+t+i.substring(e.loc,e.end)+a+i.substring(e.end)}),i=i.replaceAll(a+" ?"+t," "),i=i.replaceAll(""+a+t,"")}if(s)return i},addToSidebar(e,t="outline"){window.roamAlphaAPI.ui.rightSidebar.addWindow({window:{type:t,"block-uid":e}})},parseDOI(t){if(t){let e=t.match(/10\.([0-9]+?)\/(.+)/g);return!!e&&e[0].toLowerCase()}return!1},parseNoteBlock(e){let t=e;var a={"</p>":"\n","</div>":"","</span>":"","<blockquote>":"> ","</blockquote>":"","<strong>":"**","</strong>":"**","<em>":"__","</em>":"__","<b>":"**","</b>":"**","<br />":"\n","<br>":"\n","<u>":"","</u>":""};for(prop in a)t=t.replaceAll(""+prop,""+a[prop]);["p","div","span","h1","h2","h3"].forEach(e=>{e=new RegExp(`<${e}>|<${e} .+?>`,"g");t=t.replaceAll(e,"")});return t=t.replaceAll(/<a href="(.+?)">(.+?)<\/a>/g,"[$2]($1)"),t=zoteroRoam.utils.cleanNewlines(t),t},parseSemanticItem(e){let t={doi:zoteroRoam.utils.parseDOI(e.doi),intent:e.intent,isInfluential:e.isInfluential,links:{},meta:e.venue.split(/ ?:/)[0],title:e.title,url:e.url||"",year:e.year?e.year.toString():""};switch(t.authorsLastNames=e.authors.map(e=>{let t=e.name.replaceAll("."," ").split(" ").filter(Boolean);return 1==t.length?t[0]:t.slice(1).filter(e=>1<e.length).join(" ")}),t.authorsString=t.authorsLastNames.join(" "),t.authorsLastNames.length){case 0:t.authors="";break;case 1:t.authors=t.authorsLastNames[0];break;case 2:t.authors=t.authorsLastNames[0]+" & "+t.authorsLastNames[1];break;case 3:t.authors=t.authorsLastNames[0]+", "+t.authorsLastNames[1]+" & "+t.authorsLastNames[2];break;default:t.authors=t.authorsLastNames[0]+" et al."}return e.paperId&&(t.links.semanticScholar="https://www.semanticscholar.org/paper/"+e.paperId),e.arxivId&&(t.links.arxiv="https://arxiv.org/abs/"+e.arxivId),e.doi&&(t.links.connectedPapers="https://www.connectedpapers.com/api/redirect/doi/"+e.doi,t.links.googleScholar="https://scholar.google.com/scholar?q="+e.doi),t},cleanNewlines(e){let t=e;return t.startsWith("\n")?(t=t.slice(1),t=zoteroRoam.utils.cleanNewlines(t)):t.endsWith("\n")&&(t=t.slice(0,-1),t=zoteroRoam.utils.cleanNewlines(t)),t},renderBP3Button_link(e,{linkClass:t="",icon:a="",iconModifier:o="",target:r="",linkAttribute:i=""}={}){return`
              <a role="button" class="bp3-button ${t}" href="${r}" ${i}>
              ${a?`<span icon="${a}" class="bp3-icon bp3-icon-${a} ${o}"></span>`:""}
              <span class="bp3-button-text">${e}</span>
              </a>
              `},renderBP3Button_group(e,{buttonClass:t="",icon:a="",modifier:o="",buttonAttribute:r=""}={}){return`
              <button type="button" class="bp3-button ${t}" ${r}>
              ${a?`<span icon="${a}" class="bp3-icon bp3-icon-${a} ${o}"></span>`:""}
              ${""==e?"":`<span class="bp3-button-text">${e}</span>`}
              </button>
              `},renderBP3ButtonGroup(e,{divClass:t="bp3-minimal bp3-fill bp3-align-left",buttonClass:a="",modifier:o="",icon:r="",buttonModifier:i=""}={}){return`<div class="bp3-button-group ${t}">
                          ${zoteroRoam.utils.renderBP3Button_group(e,{buttonClass:a,icon:r,modifier:o,buttonAttribute:i})}
                      </div>`},renderBP3_list(e,o,{varName:r,has_value:i,has_string:n,optClass:s="",selectFirst:l=!1,active_if:c=""}={}){return e.map((e,t)=>{let a="";return c&&(a=e[c]?"":"disabled",s+=e[c]?"":"bp3-disabled"),l&&0==t&&""==a&&(a="checked"),zoteroRoam.utils.renderBP3_option(string=e[n],o,depth=e.depth||0,{varName:r,optClass:s,modifier:a,optValue:e[i]})}).join("\n")},renderBP3_option(e,t,a,{varName:o,optClass:r="",modifier:i="",labelModifier:n="",optValue:s=""}={}){return`
              <label class="bp3-control bp3-${t} ${r}" data-option-depth="${a}" ${n}>
                  <input type="${t}" name="${o}" value="${s}" ${i} />
                  <span class="bp3-control-indicator"></span>
                  ${e}
              </label>
              `},renderBP3_minimalradio(e,{varName:t,optValue:a,icon:o="",modifier:r="",labelClass:i=""}={}){return`
              <input type="radio" value="${a}" name="${t}" id="${t}_${a}" ${r} />
              ${o?`<span class="bp3-icon bp3-icon-${o}"></span>`:""}
              <label for="${t}_${a}" class="${i}">${e}</label>
              `},renderBP3HTMLSelect(e,{varName:t,icon:a="double-caret-vertical",modifier:o="",divClass:r=""}={}){return`
              <div class="bp3-html-select ${r}">
                  <select name="${t}" ${o}>
                      ${e.map((e,t)=>zoteroRoam.utils.renderBP3HTMLSelect_option(e,{selected:0==t})).join("\n")}
                  </select>
                  ${a?`<span class="bp3-icon bp3-icon-${a}"></span>`:""}
              </div>
              `},renderBP3HTMLSelect_option(e,{selected:t=!1}={}){return`<option value="${e.value}" ${t?"selected":""}>${e.label}</option>`},renderBP3Spinner(){return`
              <div class="bp3-spinner">
                  <div class="bp3-spinner-animation">
                      <svg width="20" height="20" stroke-width="8.00" viewBox="1.00 1.00 98.00 98.00">
                          <path class="bp3-spinner-track" d="M 50,50 m 0,-45 a 45,45 0 1 1 0,90 a 45,45 0 1 1 0,-90"></path>
                          <path class="bp3-spinner-head" d="M 50,50 m 0,-45 a 45,45 0 1 1 0,90 a 45,45 0 1 1 0,-90" pathLength="280" stroke-dasharray="280 280" stroke-dashoffset="210"></path>
                      </svg>
                  </div>
              </div>
              `},renderBP3Tag(e,{modifier:t="",icon:a="",tagRemove:o=!1,tagAttribute:r=""}={}){o=o?'<button class="bp3-tag-remove"></button>':"";return 0<a.length?`<span class="bp3-tag bp3-minimal ${t}" ${r}><span icon="${a}" class="bp3-icon bp3-icon-${a}"></span><span class="bp3-text-overflow-ellipsis bp3-fill">${e}</span>${o}</span>`:`<span class="bp3-tag bp3-minimal ${t}" style="margin:3px;" ${r}>${e}${o}</span>`},renderBP3Toast(e,{toastClass:t="",style:a="opacity:0;top:20px;transition: opacity 0.3s ease-out, top 0.3s ease-in;"}={}){return`
              <div class="bp3-toast ${t} bp3-overlay-content" tabindex="0" style="${a}">
              <span class="bp3-toast-message">${e}</span>
              </div>
              `},renderHTMLBlockObject(e){let t="";if(void 0===e.string)throw console.log(e),new Error("All blocks passed as an Object must have a string property");return t+="<li>"+e.string,void 0!==e.children&&0<e.children.length&&(t+=zoteroRoam.utils.renderHTMLMetadataArray(e.children)),t+=" </li>",t},renderHTMLMetadataArray(e){let t="<ul>";return e.forEach(e=>{if(e.constructor===Object)t+=zoteroRoam.utils.renderHTMLBlockObject(e);else{if(e.constructor!==String)throw console.log(e),new Error("All array items should be of type String or Object");t+=`<li>${e} </li>`}}),t+="</ul>",t},renderPageReference(e,t){return`<span data-link-title="${e}" data-link-uid="${t}">
              <span tabindex="-1" class="rm-page-ref rm-page-ref--link">${e}</span></span>`},renderPageTag(e){return`<span tabindex="-1" data-tag="${e}" class="rm-page-ref rm-page-ref--tag">#${e}</span>`},searchEngine(t,a,{any_case:o=!0,word_order:e="strict",match:r="partial",search_compounds:i=!0}={}){let n=t,s=a,l=(1==o&&(n=t.toLowerCase(),s=a.toLowerCase()),n.split(" ")),c=!1;if(l.forEach(e=>{e.includes("-")&&(c=!0)}),1==l.length){let e=n;return c&&1==i&&(e=n.replace("-","(?: |-)?")),"partial"==r?(o=new RegExp(zoteroRoam.utils.escapeRegExp(e),"g"),!!s.match(o)):"exact"==r?(t=new RegExp("^"+zoteroRoam.utils.escapeRegExp(e)+"$","g"),!!s.match(t)):(a=new RegExp("(?:\\W|^)"+zoteroRoam.utils.escapeRegExp(e)+"(?:\\W|$)","g"),!!s.match(a))}{let a=l.map(e=>zoteroRoam.utils.escapeRegExp(e));if(1==i&&(c?a=a.map(e=>e.includes("-")?e.replace("-","(?: |-)?"):e):c||"strict"!=e||(a=[a.join("(?: |-)?")])),"loose"!=e)return"exact"==r?(o=new RegExp("^"+a.join(" ")+"$","g"),!!s.match(o)):(t=new RegExp("(?:\\W|^)"+a.join(" ")+"(?:\\W|$)","g"),!!s.match(t));{let e=a.map(e=>"(?:\\W|^)"+e+"(?:\\W|$)"),t=!0;return e.forEach(e=>{e=new RegExp(e,"g");s.match(e)||(t=!1)}),t}}},setNativeValue(e,t){const a=Object.getOwnPropertyDescriptor(e,"value").set;var o=Object.getPrototypeOf(e);const r=Object.getOwnPropertyDescriptor(o,"value").set;(a&&a!==r?a:r).call(e,t)},sleep(t){return new Promise(e=>setTimeout(e,t))},sortCollectionChildren(e,a,o=0){let r=e;if(r.depth=o,0<a.length){var i=a.filter(e=>e.data.parentCollection==r.key);if(i){let t=[r];for(let e=0;e<i.length;e++)t.push(...zoteroRoam.utils.sortCollectionChildren(i[e],a,o+1));return t}return[r]}return[r]},sortCollectionsList(o){if(0<o.length){let e=[],a=(o=[...o].sort((e,t)=>e.data.name.toLowerCase()<t.data.name.toLowerCase()?-1:1)).filter(e=>!e.data.parentCollection),t=(a.forEach((e,t)=>{a[t].depth=0}),o.filter(e=>e.data.parentCollection));for(k=0;k<a.length;k++)t.filter(e=>e.data.parentCollection==a[k].key)?e.push(...zoteroRoam.utils.sortCollectionChildren(parent=a[k],children=t,depth=0)):e.push(a[k]);return e}return[]}},zoteroRoam.handlers={async addBlockObject(e,t){let{string:a,children:o,...r}=t;if(void 0===a)throw console.log(t),new Error("All blocks passed as an Object must have a string property");var i=await zoteroRoam.utils.addBlock(uid=e,a=a,order=0,r);if(void 0!==o)for(let e=o.length-1;0<=e;e--)if(o[e].constructor===Object)await zoteroRoam.handlers.addBlockObject(i,o[e]);else{if(o[e].constructor!==String)throw new Error("All children array items should be of type String or Object");await zoteroRoam.utils.addBlock(uid=i,a=o[e],order=0)}},async addMetadataArray(e,t){if(!(0<t.length))return console.log("The metadata array was empty ; nothing was done."),{success:null};try{for(k=t.length-1;0<=k;k--)if(t[k].constructor===Object)await zoteroRoam.handlers.addBlockObject(e,t[k]);else{if(t[k].constructor!==String)throw console.log(t[k]),new Error("All array items should be of type String or Object");await zoteroRoam.utils.addBlock(uid=e,blockString=t[k],order=0)}return{success:!0}}catch(e){return console.error(e),{success:!1}}},async importItemMetadata(e,t,{popup:a=!0}={}){let o={},r=e.replace("@","");var i,n=zoteroRoam.data.items.find(e=>e.key==r),s=t||window.roamAlphaAPI.util.generateUID();let l={title:e,uid:s},c=(s==t&&window.roamAlphaAPI.deletePage({page:{title:e,uid:s}}),window.roamAlphaAPI.createPage({page:{title:e,uid:s}}),l.new=!0,null);n?(i=(t=zoteroRoam.config.userSettings.metadata||{}).use||"function",o="smartblock"===i?(i=t.smartblock,c={config:i,context:{item:n,page:l}},await zoteroRoam.smartblocks.use_smartblock_metadata(config=i,context={item:n,page:l,uid:s})):(t=await zoteroRoam.handlers.formatData(n),c=t,await zoteroRoam.handlers.addMetadataArray(page_uid=s,arr=t)),i=o.success?"Metadata was successfully added.":"The metadata couldn't be properly processed.",t=o.success?"success":"danger",1==a?zoteroRoam.interface.popToast(message=i,t):console.log(i)):(o.success=null,console.error(`Citekey ${r} yielded the following library item : `+n),zoteroRoam.interface.popToast(message="Item could not be found in the library",intent="danger")),zoteroRoam.events.emit("metadata-added",{success:o.success,uid:s,title:e,item:n,meta:c})},async addItemNotes(t,o,{popup:r=!0}={}){let a=t.startsWith("@")?t.slice(1):t;var i=zoteroRoam.data.items.find(e=>e.key==a);try{var n=zoteroRoam.formatting.getItemChildren(i,{pdf_as:"raw",notes_as:"formatted",split_char:zoteroRoam.config.params.notes.split_char}).notes;let e={},a=o||"";if(o)e=await zoteroRoam.handlers.addMetadataArray(page_uid=o,arr=[{string:"[[Notes]]",children:n}]);else{a=window.roamAlphaAPI.util.generateUID(),window.roamAlphaAPI.createPage({page:{title:t,uid:a}}),e=await zoteroRoam.handlers.addMetadataArray(page_uid=a,arr=[{string:"[[Notes]]",children:n}]);try{let e=document.querySelector(".item-in-graph"),t=(null!=e&&(e.innerHTML='<span class="bp3-icon-tick bp3-icon bp3-intent-success"></span><span> In the graph</span>'),document.querySelector(".item-go-to-page"));null!=t&&(t.setAttribute("data-uid",a),t.disabled=!1)}catch(e){}}var s=e.success?"Notes successfully imported.":"The notes couldn't be imported.",l=e.success?"success":"danger";1==r?zoteroRoam.interface.popToast(s,l):console.log(s),zoteroRoam.events.emit("notes-added",{success:e.success,uid:a,title:t,item:i,notes:n})}catch(e){console.error(e),console.log(i),console.log(itemChildren)}},extractCitekeys(e){return e.map(e=>(void 0!==e.data.extra&&e.data.extra.includes("Citation Key: ")&&(e.key=e.data.extra.match("Citation Key: (.+)")[1]),e))},async fetchZoteroData(r,n,e){var t=`https://api.zotero.org/${n}?`+e;let s=[],a=null;try{if(a=await fetch(t,{method:"GET",headers:{"Zotero-API-Version":3,"Zotero-API-Key":r}}),1==a.ok){var l=a.headers.get("Total-Results");let o=new URLSearchParams(e);var c=Number(o.get("start")||"0"),d=Number(o.get("limit")||"100"),m=(s=await a.json(),c+s.length);if(m<l){var p=Math.ceil((l-m)/d);let e=[];for(i=1;i<=p;i++){var u=m+d*(i-1);o.set("start",u),o.set("limit",d),e.push(fetch(`https://api.zotero.org/${n}?`+o.toString(),{method:"GET",headers:{"Zotero-API-Version":3,"Zotero-API-Key":r}}))}let t=await Promise.all(e),a=await Promise.all(t.map(e=>e.json()));a=a.flat(1),s.push(...a)}}else console.log(`The request for ${a.url} returned a code of `+a.status)}catch(e){console.error(e),zoteroRoam.interface.popToast("The extension encountered an error while requesting Zotero data. Please check the console for details.","danger")}finally{return{req:a,data:s}}},async formatData(e){var t=e.data.itemType;let a=zoteroRoam.funcmap.DEFAULT;var o=(zoteroRoam.config.userSettings.metadata||{}).func||!1;o?a=o:zoteroRoam.config.userSettings.funcmap&&(a=zoteroRoam.config.userSettings.funcmap[""+t]||zoteroRoam.config.userSettings.funcmap.DEFAULT||a);try{return await zoteroRoam.utils.executeFunctionByName(a,window,e)}catch(e){return console.error(e),console.log("There was a problem when formatting the item with function "+a),[]}},formatNotes(e,t=zoteroRoam.config.params.notes.use,a=zoteroRoam.config.params.notes.split_char){let o=[];var r=zoteroRoam.config.params.notes.func;try{switch(t){case"raw":return o=zoteroRoam.utils.executeFunctionByName(r,window,e),o;case"text":var i=zoteroRoam.utils.splitNotes(e,a);return o=zoteroRoam.utils.executeFunctionByName(r,window,i),o;default:console.error("Unsupported format : "+t)}}catch(e){return console.error(e),console.log("There was a problem when formatting the item with function "+r),[]}},setupUserRequests(){if(!zoteroRoam.config.userSettings.dataRequests)throw new Error("At least one data request object needs to be specified in order to use the extension. Read through the docs for basic setup examples.");{let a=zoteroRoam.config.userSettings.dataRequests,n=(a=a.constructor===Array?a:[a],a.find(e=>void 0!==e.apikey).apikey),s=a.find(e=>void 0!==e.params).params,e=(a=a.map((e,t)=>{let{name:a=""+t,apikey:o=n,dataURI:r,params:i=s}=e;return{apikey:o,dataURI:r,params:i,name:a,library:r.match(/(users|groups)\/(.+?)\//g)[0].slice(0,-1)}}),Array.from(new Set(a.map(e=>e.library))));e.forEach((t,e)=>{zoteroRoam.data.libraries.set(t,{path:t,version:"0",apikey:a.find(e=>e.library==t).apikey}),zoteroRoam.tagManager.lists[t]={data:[],lastUpdated:"0"}}),zoteroRoam.config.requests=a}},async checkForSemantic_citations(e){try{let t=e.parentElement.dataset.linkTitle.replace("@","");var a,o,r=zoteroRoam.data.items.find(e=>e.key==t);r&&((a=zoteroRoam.utils.parseDOI(r.data.DOI))?(o=await zoteroRoam.handlers.getSemantic(a)).citations?0==o.citations.length?zoteroRoam.interface.popToast("This item has no available citing papers"):zoteroRoam.interface.popCitationsOverlay(a,t,type="citations"):zoteroRoam.interface.popToast("No data could be retrieved.","danger"):zoteroRoam.interface.popToast("This item has no DOI (required for citations lookup).","danger"))}catch(e){console.error(e)}},async checkForSemantic_references(e){try{let t=e.parentElement.dataset.linkTitle.replace("@","");var a,o,r=zoteroRoam.data.items.find(e=>e.key==t);r&&((a=zoteroRoam.utils.parseDOI(r.data.DOI))?(o=await zoteroRoam.handlers.getSemantic(a)).references?0==o.references.length?zoteroRoam.interface.popToast("This item has no available references"):zoteroRoam.interface.popCitationsOverlay(a,t,type="references"):zoteroRoam.interface.popToast("No data could be retrieved.","danger"):zoteroRoam.interface.popToast("This item has no DOI (required for references lookup).","danger"))}catch(e){console.error(e)}},async importSelectedItems(e){let o={};var t=e.getAttribute("zr-import"),r=zoteroRoam.activeImport.currentLib;let i=Array.from(e.querySelectorAll('.options-collections-list [name="collections"]')).filter(e=>e.checked).map(e=>e.value),n=e.querySelector(".options-tags_selection").dataset.tags;if(n=JSON.parse(n),"citations"==t){let e=zoteroRoam.citations.activeImport.items,t=[],a=(e.forEach(e=>{t.push(zoteroRoam.handlers.requestCitoid(query=e,{collections:i,tag_with:n}))}),o.harvest=await Promise.all(t),{identifiers:[],data:[]});o.harvest.forEach(e=>{1==e.success&&(a.identifiers.push(e.query),a.data.push(e.data))}),o.write=await zoteroRoam.write.importItems(a.data,r),o.write.identifiers=a.identifiers,zoteroRoam.events.emit("write",{collections:i,identifiers:e,library:r,tags:n,outcome:o,context:{doi:zoteroRoam.citations.currentDOI,key:zoteroRoam.citations.currentCitekey,type:zoteroRoam.citations.currentType}})}else if("weblinks"==t){let a=zoteroRoam.webImport.activeImport.items;e=a.map(e=>e.url);a.forEach((e,t)=>{a[t].collections=i,a[t].tags=n.map(e=>({tag:e}))}),o.harvest=a,o.write=await zoteroRoam.write.importItems(a,r),o.write.identifiers=e,zoteroRoam.events.emit("write",{collections:i,identifiers:e,library:r,tags:n,outcome:o,context:{block:zoteroRoam.webImport.currentBlock}})}return console.log(o),o},async modifySelectedTags(t,a='.bp3-tab-panel[name="tag-manager"] .zr-tab-panel-popover'){let r=zoteroRoam.tagManager.activeDisplay.library;switch(t){case"Edit":case"Merge":for(entry of Array.from(document.querySelectorAll(a+" .zr-tag-entry[data-entry-index]"))){let o=entry.querySelector('input[name*="zr-tag-rename_"]').value,e=Array.from(entry.querySelectorAll('input[name*="zr-tag-select_"]')).filter(e=>1==e.checked);var i=e.reduce((e,t)=>{let a=t.closest("[data-tag-source]");return"roam"==a.getAttribute("data-tag-source")?e.roam.push({page:{title:o,uid:a.getAttribute("data-uid")}}):"zotero"==a.getAttribute("data-tag-source")&&e.zotero.push(t.value),e},{roam:[],zotero:[]});await zoteroRoam.handlers.renameSelectedTags(r,i,o)}break;case"Delete":let e=Array.from(document.querySelectorAll(a+' input[name*="zr-tag-select_"]')).filter(e=>1==e.checked);var o=e.reduce((e,t)=>{let a=t.closest("[data-tag-source]");return"roam"==a.getAttribute("data-tag-source")?e.roam.push({page:{uid:a.getAttribute("data-uid")}}):"zotero"==a.getAttribute("data-tag-source")&&e.zotero.push(t.value),e},{roam:[],zotero:[]});await zoteroRoam.handlers.deleteSelectedTags(r,o)}await zoteroRoam.extension.update(popup=!1,reqs=zoteroRoam.config.requests.filter(e=>e.dataURI.startsWith(r.path+"/")))},async deleteSelectedTags(e,t){0<t.zotero.length?1==(e=await zoteroRoam.write.deleteTags(e,t.zotero)).success?(t.roam.forEach(e=>window.roamAlphaAPI.deletePage(e)),console.log(e.response),await zoteroRoam.extension.update(popup=!1,reqs=zoteroRoam.config.requests.filter(e=>e.dataURI.startsWith(zoteroRoam.tagManager.activeDisplay.library.path+"/")))):console.log(e):t.roam.forEach(e=>window.roamAlphaAPI.deletePage(e))},async renameSelectedTags(e,t,a){0<t.zotero.length?1==(e=await zoteroRoam.write.editTags(e,t.zotero,a)).success?(console.log(e.data),0<(a=e.data.successful).length&&zoteroRoam.handlers.incorporateUpdates(a),t.roam.forEach(e=>window.roamAlphaAPI.updatePage(e))):console.log(e):t.roam.forEach(e=>window.roamAlphaAPI.updatePage(e))},async requestCitoid(t,{format:a="zotero",has_relation:o=!1,tag_with:r=[],collections:i=[]}={}){let n={};try{let e=await fetch(`https://en.wikipedia.org/api/rest_v1/data/citation/${a}/`+encodeURIComponent(t),{method:"GET"});var s,l,c;n=1==e.ok?({key:s,version:l,...c}=(await e.json())[0],c.collections=i,c.tags=r.map(e=>({tag:e})),c.relations={},0!=o&&(c.relations.dc_relation=`http://zotero.org/${zoteroRoam.utils.getItemPrefix(o)}/items/`+o.data.key),{query:t,success:!0,data:c}):(console.log(`The request for ${e.url} returned a code of `+e.status),{query:t,success:!1,response:e})}catch(e){n={query:t,success:null,error:e}}finally{return n}},async getSemantic(e){if(!zoteroRoam.data.semantic.has(e)){let o=await zoteroRoam.handlers.requestSemantic(e);if(1!=o.success)return console.log(o),{};{let a=zoteroRoam.data.items.map(e=>zoteroRoam.utils.parseDOI(e.data.DOI)).filter(Boolean);o.data.citations.forEach((e,t)=>{e.doi&&zoteroRoam.utils.includes_anycase(a,e.doi)&&(o.data.citations[t].inLibrary=!0)}),o.data.references.forEach((e,t)=>{e.doi&&zoteroRoam.utils.includes_anycase(a,e.doi)&&(o.data.references[t].inLibrary=!0)}),zoteroRoam.data.semantic.set(e,o.data)}}return zoteroRoam.data.semantic.get(e)},async requestSemantic(a){let o={};try{let t=await fetch(`https://api.semanticscholar.org/v1/paper/${a}?include_unknown_references=true`,{method:"GET"});if(1==t.ok){var r=await t.json(),{citations:i,references:n}=r;let e={doi:a,data:r,citations:i||[],references:n||[]};e.citations=e.citations.filter(e=>e.doi||e.url).map(e=>zoteroRoam.utils.parseSemanticItem(e)),e.references=e.references.filter(e=>e.doi||e.url).map(e=>zoteroRoam.utils.parseSemanticItem(e)),o={success:!0,data:e}}else console.log(`The request for ${t.url} returned a code of `+t.status),o={doi:a,success:!1,response:t}}catch(e){o={doi:a,success:null,error:e}}finally{return o}},async requestData(a,m=!1,p=!0){let t=[],o=[],u=[],r=[],i=[],n=[],s=[],l=Array.from(zoteroRoam.data.libraries.values());if(0==a.length)throw new Error("No data requests were added to the config object - check for upstream problems");try{a.forEach(e=>{t.push(zoteroRoam.handlers.fetchZoteroData(apiKey=e.apikey,dataURI=e.dataURI,params=e.params))});let e=await Promise.all(t);if(e=e.map((e,t)=>e.data.map(e=>(e.requestLabel=a[t].name,e.requestIndex=t,e))).flat(1),e=zoteroRoam.handlers.extractCitekeys(e),l.forEach(e=>{zoteroRoam.data.tags[""+e.path]=new Map,o.push(zoteroRoam.handlers.fetchZoteroData(e.apikey,e.path+"/tags","limit=100"))}),u=await Promise.all(o),u.forEach((e,t)=>{e.data.reduce(function(t,a){if(t.has(a.tag)){let e=t.get(a.tag);e.constructor===Array?e.find(e=>e.tag==a.tag&&e.meta.type==a.meta.type)||t.set(a.tag,[...e,a]):t.set(a.tag,[e,a])}else t.set(a.tag,a);return t},zoteroRoam.data.tags[""+l[t].path])}),1==p){for(const c of l)r.push(zoteroRoam.handlers.fetchZoteroData(c.apikey,c.path+"/collections",`since=${c.version}&limit=100`));i=await Promise.all(r),i=i.map(e=>{let{req:t,data:a}=e;var e=t.headers.get("Last-Modified-Version"),o=t.url.match(/(user|group)s\/([^\/]+)/g)[0];return e&&(zoteroRoam.data.libraries.get(o).version=e),a}).flat(1)}if(1==m){for(const d of l)n.push(zoteroRoam.handlers.fetchZoteroData(d.apikey,d.path+"/deleted","since="+d.version));s=await Promise.all(n);let t=new Map(s.map(e=>{let{req:t,data:a}=e;return[t.url.match(/(user|group)s\/([^\/]+)/g)[0],{items:a.items,collections:a.collections}]}));zoteroRoam.data.items=zoteroRoam.data.items.filter(e=>!t.get(zoteroRoam.utils.getItemPrefix(e)).items.includes(e.data.key)),zoteroRoam.data.collections=zoteroRoam.data.collections.filter(e=>!t.get(zoteroRoam.utils.getItemPrefix(e)).collections.includes(e.key))}return{success:!0,data:{items:e,collections:i,deleted:s}}}catch(e){return console.error(e),console.log({dataCalls:t,collectionsCalls:r,deletedCalls:n}),{success:!1,data:null}}},async requestItemBib(e,{include:t="bib",style:a,linkwrap:o,locale:r}={}){var i="user"==e.library.type?"users":"groups",n=zoteroRoam.config.requests[""+e.requestIndex].apikey;let s=await fetch(`https://api.zotero.org/${i}/${e.library.id}/items/${e.data.key}?include=${t}&style=${a}&linkwrap=${o}&locale=`+r,{method:"GET",headers:{"Zotero-API-Version":3,"Zotero-API-Key":n}});return(await s.json())[""+t]},async requestItemChildren(e){var t=zoteroRoam.config.requests[""+e.requestIndex].apikey;let a=await fetch(e.links.self.href+"/children",{method:"GET",headers:{"Zotero-API-Version":3,"Zotero-API-Key":t}});return await a.json()},incorporateUpdates(e){let r=zoteroRoam.handlers.extractCitekeys(e).length,i=0;return e.forEach(a=>{var e=zoteroRoam.data.items.findIndex(e=>e.data.key==a.data.key&&e.library.id==a.library.id&&e.library.type==a.library.type);if(-1==e){let t=a.library.type+"s/"+a.library.id;var o=zoteroRoam.config.requests.findIndex(e=>e.library==t);a.requestIndex=o,a.requestLabel=o.name,zoteroRoam.data.items.push(a)}else{var{requestIndex:o,requestLabel:t}=zoteroRoam.data.items[e];a.requestIndex=o,a.requestLabel=t,zoteroRoam.data.items[e]=a,i+=1,--r}}),{new:r,modified:i,items:e}},simplifyDataArray(e){let t=e.filter(e=>!["attachment","note","annotation"].includes(e.data.itemType));return t=t.map(e=>{let t={key:e.key,itemKey:e.data.key,title:""+(e.data.title||""),abstract:""+(e.data.abstractNote||""),authors:""+(e.meta.creatorSummary||""),year:""+(e.meta.parsedDate?new Date(e.meta.parsedDate).getUTCFullYear().toString():""),meta:""+zoteroRoam.utils.makeMetaString(e),publication:""+(e.data.publicationTitle||e.data.bookTitle||e.data.university||""),tags:e.data.tags.map(e=>e.tag),authorsFull:e.data.creators.map(e=>e.name||[e.firstName,e.lastName].filter(Boolean).join(" ")),authorsRoles:e.data.creators.map(e=>e.creatorType),authorsLastNames:e.data.creators.map(e=>e.lastName||e.name),authorsString:e.data.creators.map(e=>e.lastName||e.name).join(" "),tagsString:e.data.tags.map(e=>"#"+e.tag).join(", "),location:zoteroRoam.utils.getItemPrefix(e),itemType:e.data.itemType};return t._multiField=t.authorsString+" "+t.year+" "+t.title+" "+t.tagsString,t.inGraph=!!zoteroRoam.data.roamPages.has("@"+e.key),t}),t},simplifyCitationsObject(e){return 0<e.length?e.map(e=>{let t={abstract:e.abstract||"",doi:e.doi||"",keywords:e.keywords||[],keywordsString:e.keywords?e.keywords.join(" "):"",links:{scite:"https://scite.ai/reports/"+e.slug},title:e.title,year:""+e.year||"",meta:""},a=0<e.authors.length?e.authors.map(e=>e.family):[];return t.authorsLastNames=0<e.authors.length?e.authors.map(e=>e.family):[],t.authorsString=t.authorsLastNames.join(" "),a=0<a.length?2<a.length?a.slice(0,1).join(", ")+" et al.":a.map((e,t)=>0==t?e:t<a.length-1?", "+e:" and "+e).join(""):"",t.authors=a,t.meta=""+(e.journal||e.publisher)+(e.volume?", "+e.volume+"("+e.issue+")":"")+(e.page?", "+e.page+".":"."),e.inLibrary&&(t.inLibrary=!0),t.links.connectedPapers="https://www.connectedpapers.com/"+(e.doi?"api/redirect/doi/"+e.doi:"search?q="+encodeURIComponent(e.title)),e.doi&&(t.links.semanticScholar="https://api.semanticscholar.org/"+e.doi),t.links.googleScholar="https://scholar.google.com/scholar?q="+(e.doi||encodeURIComponent(e.title)),t}):[]},getCitationsKeywordsCounts(t){if(0<t.length){let e=t.map(e=>e.keywords?e.keywords.map(e=>e.toLowerCase()):[]).flat(1),a=[];for(var o=0;o<e.length;o++){let t=e[o];a.push({keyword:t,count:e.filter(e=>e==t).length}),e=e.filter(e=>e!=t)}return a.sort((e,t)=>e.count<t.count?1:-1)}return[]},getLibItems(t="citekey",a="citekey"){return zoteroRoam.data.items.filter(e=>!["attachment","note","annotation"].includes(e.data.itemType)).map(e=>({key:e.key,source:"zotero",value:zoteroRoam.utils.formatItemReference(e,t)||e.key,display:zoteroRoam.utils.formatItemReference(e,a)}))}},zoteroRoam.write={async patchItemData(t,e){let a=zoteroRoam.config.requests.find(e=>e.name==t.requestLabel);var o=a.dataURI.match(/(users|groups)\/(.+?)\//g)[0].slice(0,-1);let r=await fetch(`https://api.zotero.org/${o}/items/`+t.data.key,{method:"PATCH",body:JSON.stringify(e),headers:{"Zotero-API-Version":3,"Zotero-API-Key":a.apikey,"If-Unmodified-Since-Version":t.version}});return 204==r.status?(o=r.headers.get("Last-Modified-Version"),{success:!0,version:zoteroRoam.data.items.find(e=>e.key==t.key).version=o}):{success:!1,response:r}},async postItemData(o,r){let n={};try{if(50<r.length){var s=Math.ceil(r.length/50);let e={success:[],failed:[]},t=[];for(i=0;i<s;i++)t.push(zoteroRoam.write.postItemData(o,r.slice(50*i,50*(i+1))));let a=await Promise.all(t);e.success=a.filter(e=>1==e.success),e.failed=a.filter(e=>!e.success),n=e.success.length==s?{success:!0,data:e.success}:{success:!1,response:e}}else{let e=await fetch(`https://api.zotero.org/${o.path}/items`,{method:"POST",body:JSON.stringify(r),headers:{"Zotero-API-Version":3,"Zotero-API-Key":o.apikey}});n=1==e.ok?{success:!0,data:await e.json()}:{success:!1,response:e}}}catch(e){n={success:null,error:e}}finally{return n}},async editTags(t,e,r){let i=Array.from(new Set(e)),n=[],a=zoteroRoam.data.items.filter(e=>e.library.type+"s/"+e.library.id==t.path);return a.forEach(t=>{let a=t.data.tags;if(0<a.length){var o=a.findIndex(e=>e.tag==r&&(0==e.type||!e.type));-1<o&&a.splice(o,1);let e=a.filter(e=>!i.includes(e.tag));e.length<a.length&&(e.push({tag:r,type:0}),n.push({key:t.data.key,version:t.version,tags:e}))}}),zoteroRoam.write.postItemData(t,n)},async deleteTags(e,t){t=t.constructor===String?encodeURIComponent(t):Array.from(new Set(t)).map(e=>encodeURIComponent(e)).join("||");let a={};try{var o=await fetch(`https://api.zotero.org/${e.path}/tags?tag=`+t,{method:"DELETE",headers:{"Zotero-API-Version":3,"Zotero-API-Key":e.apikey,"If-Unmodified-Since-Version":e.version}});a={success:o.ok,response:o}}catch(e){a={success:null,error:e}}finally{return a}},async editItemTags(e,{add:t=[],remove:a=[]}={}){let o=e.data.tags.map(e=>e.tag);t=o.filter(e=>!a.includes(e)).push(...t).map(e=>({tag:e}));return await zoteroRoam.write.patchItemData(e,{tags:t})},async toggleTags(o,r=[]){let i=o.data.tags.map(e=>e.tag);if(1<r.length){let a=-1,e=(r.forEach((e,t)=>{-1==a&&(a=i.includes(e)?t:-1)}),{});if(e=-1==a?await zoteroRoam.write.editItemTags(o,{add:[r[0]]}):a==r.length-1?await zoteroRoam.write.editItemTags(o,{add:[r[0]],remove:r.slice(1)}):await zoteroRoam.write.editItemTags(o,{add:[r[a]],remove:r.filter(t!=r[a])}),1==e.success)return r[a]}},async importItems(t,a,o=!0){t=t.constructor===Array?t:[t];let r={};try{let e=await fetch(`https://api.zotero.org/${a.path}/items`,{method:"POST",body:JSON.stringify(t),headers:{"Zotero-API-Version":3,"Zotero-API-Key":a.apikey,"If-Unmodified-Since-Version":a.version}});r=1==e.ok?(await zoteroRoam.extension.update(popup=!1,reqs=zoteroRoam.config.requests.filter(e=>e.library==a.path)),zoteroRoam.activeImport.libraries=zoteroRoam.utils.getLibraries(),zoteroRoam.activeImport.currentLib=zoteroRoam.activeImport.libraries.find(e=>e.path==zoteroRoam.activeImport.currentLib.path),{success:!0,data:await e.json()}):412==e.status&&1==o?(await zoteroRoam.extension.update(popup=!1,reqs=zoteroRoam.config.requests.filter(e=>e.library==a.path)),zoteroRoam.activeImport.libraries=zoteroRoam.utils.getLibraries(),zoteroRoam.activeImport.currentLib=zoteroRoam.activeImport.libraries.find(e=>e.path==zoteroRoam.activeImport.currentLib.path),await zoteroRoam.write.importItems(t,a=zoteroRoam.activeImport.currentLib,o=!1)):(console.log(`The request for ${e.url} returned a code of ${e.status} (${e.statusText}).`),{success:!1,response:e})}catch(e){r={success:null,error:e}}finally{return r}},async checkImport(e){var t=zoteroRoam.activeImport.currentLib;let a=Object.values(e).map(e=>e.data.key);var o,r=Object.values(e)[0].version;let i=r,n=!1;try{let e=await fetch(`https://api.zotero.org/${t.path}/items?itemKey=${a.join(",")}&since=`+r,{method:"GET",headers:{"Zotero-API-Version":3,"Zotero-API-Key":t.apikey}});!e.ok||0<(o=await e.json()).length&&(n={...zoteroRoam.handlers.extractCitekeys(o)},i=e.headers.get("Last-Modified-Version"))}catch(e){console.log(e)}return{updated:i>r,data:n||e}}},zoteroRoam.interface={icon:null,portal:{div:null,id:"zotero-roam-portal"},contextTarget:null,contextMenu:{div:null,class:"zotero-roam-context-menu",overlay:{div:null,class:"zotero-roam-context-overlay"},options:{list:[],class:"zotero-roam-context-menu-option",labels:["View item information","Add metadata","Check for citing papers","Convert to citation"]},visible:!1,position({top:e,left:t}){zoteroRoam.interface.contextMenu.div.style.left=t+"px",zoteroRoam.interface.contextMenu.div.style.top=e+"px",zoteroRoam.interface.toggleContextOverlay("contextMenu","show")}},iconContextMenu:{div:null,class:"zotero-roam-icon-context-menu",overlay:{div:null,class:"zotero-roam-icon-context-overlay"},options:{list:[],class:"zotero-roam-icon-context-menu-option",labels:["Update Zotero data","Search in library"]},visible:!1,position({top:e,left:t}){zoteroRoam.interface.iconContextMenu.div.style.left=t>=.9*window.innerWidth?`calc(${t}px - 10%)`:t+"px",zoteroRoam.interface.iconContextMenu.div.style.top=`calc(${e}px + 3%)`,zoteroRoam.interface.toggleContextOverlay("iconContextMenu","show")}},citations:{overlay:null,input:null,closeButton:null,overlayClass:"zotero-roam-citations-search"},search:{overlay:null,input:null,selectedItemDiv:null,closeButton:null,updateButton:null,overlayClass:"zotero-roam-search"},tributeTrigger:"",tributeBlockTrigger:null,tributeNewText:"",create(){zoteroRoam.interface.createIcon(id="zotero-roam-icon"),zoteroRoam.interface.portal.div=zoteroRoam.interface.createPortal(id=zoteroRoam.interface.portal.id),zoteroRoam.interface.createContextMenu(elementKey="contextMenu"),zoteroRoam.interface.createContextMenu(elementKey="iconContextMenu"),zoteroRoam.interface.createOverlay(divClass=zoteroRoam.interface.search.overlayClass),zoteroRoam.interface.fillSearchOverlay(),zoteroRoam.interface.createOverlay(divClass=zoteroRoam.interface.citations.overlayClass),zoteroRoam.interface.fillCitationsOverlay(),zoteroRoam.interface.createOverlay(divClass="zotero-roam-auxiliary",dialogCSS="align-self:start;transition:0.5s;",useBackdrop=!0,commonTag="zotero-roam-dialog-small"),zoteroRoam.interface.fillAuxiliaryOverlay(),zoteroRoam.interface.createOverlay(divClass="zotero-roam-dashboard"),zoteroRoam.interface.fillDashboardOverlay(),zoteroRoam.interface.createToastOverlay()},setup(){zoteroRoam.interface.icon.addEventListener("click",zoteroRoam.extension.toggle),zoteroRoam.interface.setupContextMenus(["contextMenu","iconContextMenu"]),zoteroRoam.interface.search.updateButton.addEventListener("click",function(){zoteroRoam.extension.update(popup=!0)}),document.addEventListener("click",a=>{if(a.target.closest(".zotero-roam-page-div")||a.target.closest(".zotero-roam-page-related")||a.target.closest(".zotero-roam-explo-import"))zoteroRoam.inPage.handleClicks(a.target);else if(a.target.closest(".zotero-roam-overlay-close")||a.target.closest(".bp3-overlay-backdrop")){let e=a.target.closest(".zotero-roam-dialog-overlay")||a.target.closest(".zotero-roam-dialog-small");e&&(e.classList.contains("zotero-roam-citations-search-overlay")?zoteroRoam.interface.closeCitationsOverlay():e.classList.contains("zotero-roam-search-overlay")?zoteroRoam.interface.toggleSearchOverlay("hide"):e.classList.contains("zotero-roam-auxiliary-overlay")?zoteroRoam.interface.closeAuxiliaryOverlay():e.classList.contains("zotero-roam-dashboard-overlay")&&zoteroRoam.interface.toggleDashboardOverlay())}else if(a.target.closest(".item-actions button")){let e=a.target.closest("button");var t=e.getAttribute("data-uid"),o="@"+e.getAttribute("data-citekey");e.classList.contains("item-go-to-page")&&t?(console.log(`Navigating to ${o} (${t})`),roamAlphaAPI.ui.mainWindow.openPage({page:{uid:t}})):e.classList.contains("item-add-metadata")&&(console.log("Importing metadata..."),zoteroRoam.handlers.importItemMetadata(o,t,{popup:!0}))}else if(a.target.closest(".item-additional-metadata")){let e=a.target.closest("[data-link-uid]"),t=a.target.closest("[data-tag]");e?window.roamAlphaAPI.ui.mainWindow.openPage({page:{uid:e.getAttribute("data-link-uid")}}):t&&window.roamAlphaAPI.ui.mainWindow.openPage({page:{title:t.getAttribute("data-tag")}})}else if(a.target.closest("[zr-import]"))zoteroRoam.interface.handleImportPanelClicks(a);else if(a.target.closest(".zotero-roam-page-control")){let e=a.target.closest(".zotero-roam-page-control");zoteroRoam.interface.changePage(pagination=e.getAttribute("pagination"),goto=e.getAttribute("goto"))}})},createIcon(e){try{document.getElementById(e).closest(".bp3-popover-wrapper").remove()}catch(e){}var t=document.createElement("span");t.classList.add("bp3-popover-wrapper"),t.setAttribute("style","margin-left: 4px;"),t.innerHTML=`<span class="bp3-popover-target"><span id="${e}" status="off" class="bp3-button bp3-icon-manual bp3-minimal bp3-small"></span>`,document.querySelector(".rm-topbar").appendChild(t),zoteroRoam.interface.icon=document.getElementById(e)},createPortal(e){try{document.getElementById(e).remove()}catch(e){}var t=document.createElement("div");return t.classList.add("bp3-portal"),t.id=e,document.getElementById("app").appendChild(t),t},createContextMenu(e){let r=zoteroRoam.interface[""+e];try{document.querySelector("."+r.overlay.class).remove()}catch(e){}var t=r.options.labels.map(e=>{let t="",a="",o="";switch(e){case"Add metadata":t="bp3-icon-add",a="bp3-intent-primary";break;case"View item information":t="bp3-icon-info-sign";break;case"Check for citing papers":t="bp3-icon-chat",a="bp3-intent-warning";break;case"Convert to citation":o='<li class="bp3-menu-divider"></li>';break;case"Update Zotero data":t="bp3-icon-refresh";break;case"Search in library":t="bp3-icon-search"}return`
                  ${o}
                  <li class="${r.options.class} zotero-roam-cm-option">
                      <a class="bp3-menu-item bp3-popover-dismiss ${t} ${a}">
                          <div class="bp3-fill bp3-text-overflow-ellipsis">${e}</div>
                      </a>
                  </li>`}).join(""),a=document.createElement("div");a.classList.add("bp3-overlay"),a.classList.add("bp3-overlay-open"),a.classList.add(""+r.overlay.class),a.style="display:none;",a.innerHTML=`
              <div class="bp3-overlay-backdrop bp3-popover-backdrop bp3-popover-appear-done bp3-popover-enter-done" style="z-index:25;"></div>
              <div class="bp3-transition-container bp3-popover-appear-done bp3-popover-enter-done ${r.class}" style="width: auto; position: fixed;z-index:25;">
                  <div class="bp3-popover bp3-minimal ${zoteroRoam.config.params.theme||""}">
                      <div class="bp3-popover-content">
                          <div>
                              <ul class="bp3-menu">
                                  ${t}
                              </ul>
                          </div>
                      </div>
                  </div>
              </div>`,zoteroRoam.interface.portal.div.appendChild(a),zoteroRoam.interface[""+e].overlay.div=document.querySelector("."+zoteroRoam.interface[""+e].overlay.class),zoteroRoam.interface[""+e].div=document.querySelector("."+zoteroRoam.interface[""+e].class),zoteroRoam.interface[""+e].options.list=document.querySelectorAll("."+zoteroRoam.interface[""+e].options.class)},createToastOverlay(){let e=document.createElement("div");e.classList.add("bp3-overlay"),e.classList.add("bp3-overlay-open"),e.classList.add("bp3-toast-container"),e.classList.add("bp3-toast-container-top"),e.classList.add("bp3-toast-container-in-portal"),e.classList.add("zotero-roam-toast-overlay"),zoteroRoam.interface.portal.div.appendChild(e)},async popToast(e,t="primary"){let a=zoteroRoam.interface.portal.div.querySelector(".zotero-roam-toast-overlay");a.innerHTML=zoteroRoam.utils.renderBP3Toast(string=e,{toastClass:"bp3-intent-"+t}),a.setAttribute("role","alert"),a.querySelector(".bp3-toast").style.opacity="1",await zoteroRoam.utils.sleep(700),a.querySelector(".bp3-toast").style.top="-100px",a.removeAttribute("role")},createOverlay(t,e="align-self:baseline;transition:0.5s;",d=!0,a="zotero-roam-dialog-overlay"){try{document.querySelector(`.${t}-overlay`).remove()}catch(e){}let o=document.createElement("div");if(o.classList.add("bp3-overlay"),o.classList.add("bp3-overlay-open"),o.classList.add("bp3-overlay-scroll-container"),o.classList.add(t+"-overlay"),a&&o.classList.add(a),o.setAttribute("overlay-visible","false"),o.style="display:none;",d){let e=document.createElement("div");e.classList.add("bp3-overlay-backdrop"),e.classList.add("bp3-overlay-appear-done"),e.classList.add("bp3-overlay-enter-done"),e.classList.add(t+"-backdrop"),e.tabIndex="0",o.appendChild(e)}let r=document.createElement("div"),i=(r.classList.add("bp3-dialog-container"),r.classList.add("bp3-overlay-content"),r.classList.add("bp3-overlay-appear-done"),r.classList.add("bp3-overlay-enter-done"),r.tabIndex="0",document.createElement("div")),n=(i.classList.add("bp3-dialog"),zoteroRoam.config.params.theme&&i.classList.add(zoteroRoam.config.params.theme),i.setAttribute("side-panel","hidden"),i.setAttribute("role","dialog"),i.style=e,document.createElement("div")),s=(n.classList.add("bp3-dialog-body"),document.createElement("div")),l=(s.classList.add("main-panel"),s.style="flex: 1 1 100%;",document.createElement("div")),c=(l.classList.add("side-panel"),l.style="flex: 1 0 0%;",document.createElement("div"));c.classList.add("side-panel-contents"),l.appendChild(c),n.appendChild(s),n.appendChild(l),i.appendChild(n),r.appendChild(i),o.appendChild(r),zoteroRoam.interface.portal.div.appendChild(o)},fillAuxiliaryOverlay(){let e=document.querySelector(".zotero-roam-auxiliary-overlay .bp3-dialog-body .main-panel"),t=document.querySelector(".zotero-roam-auxiliary-overlay .bp3-dialog-body .side-panel-contents"),a=document.createElement("div"),o=document.createElement("div"),d=(o.classList.add("bp3-input-group"),o.classList.add("header-content"),document.createElement("div")),m=(d.classList.add("header-left"),e.closest('[role="dialog"]').setAttribute("aria-labelledby","zr-related-dialogtitle"),document.createElement("div")),r=(m.classList.add("header-right"),document.createElement("div")),p=(r.classList.add("controls-top"),r.classList.add("zr-auxiliary"),r.innerHTML=`
              <button type="button" aria-label="Close" class="zotero-roam-overlay-close bp3-button bp3-minimal bp3-dialog-close-button">
              <span icon="small-cross" class="bp3-icon bp3-icon-small-cross"></span></button>
              `,m.appendChild(r),o.appendChild(d),o.appendChild(m),document.createElement("div")),u=(p.classList.add("rendered-div"),p.style="width:96%;margin:0 auto;",a.appendChild(o),a.appendChild(p),e.appendChild(a),document.createElement("div")),i=(u.classList.add("import-header"),u.innerHTML=`
              ${zoteroRoam.utils.renderBP3Button_group("Add to Zotero",{buttonClass:"bp3-minimal bp3-intent-primary",icon:"inheritance",buttonAttribute:'disabled role="add" style="font-weight:600;"'})}
              `,document.createElement("div")),g=(i.classList.add("import-options"),document.createElement("div")),b=(g.classList.add("options-library-list"),document.createElement("div")),n=(b.classList.add("options-collections-list"),document.createElement("div")),s=(n.classList.add("options-tags"),document.createElement("div")),l=(s.classList.add("options-tags-select"),s.classList.add("bp3-input-group"),s.classList.add("bp3-small"),document.createElement("span")),c=(l.classList.add("bp3-icon"),l.classList.add("bp3-icon-tag"),l.classList.add("bp3-intent-primary"),document.createElement("input")),y=(c.id="zotero-roam-tagselector_auxiliary",c.tabIndex="1",c.type="text",c.classList.add("zotero-roam-tags-autocomplete"),c.classList.add("bp3-input"),c.classList.add("bp3-fill"),c.setAttribute("autocomplete","off"),document.createElement("div"));y.classList.add("options-tags_selection"),y.setAttribute("data-tags","[]"),s.appendChild(l),s.appendChild(c),n.appendChild(s),n.appendChild(y),i.appendChild(g),i.appendChild(b),i.appendChild(n),t.setAttribute("zr-import","weblinks"),t.appendChild(u),t.appendChild(i),e.addEventListener("click",function(e){let a=e.target.closest("button");if(a)if(a.classList.contains("zotero-roam-citation-toggle-abstract")){let e=a.querySelector(".bp3-button-text"),t=a.closest(".zotero-roam-list-item").querySelector(".zotero-roam-citation-abstract");"none"==t.style.display?(t.style.display="block",e.innerHTML="Hide Abstract"):(t.style.display="none",e.innerHTML="Show Abstract")}else{var t,o;a.classList.contains("zotero-roam-add-to-graph")?(t=a.closest(".bp3-menu-item").getAttribute("label"),console.log("Importing metadata..."),zoteroRoam.handlers.importItemMetadata(title="@"+t,uid="",{popup:!0})):a.classList.contains("zotero-roam-list-item-go-to-page")&&(t=a.getAttribute("data-citekey"),(o=a.getAttribute("data-uid"))&&(console.log(`Navigating to @${t} (${o})`),zoteroRoam.interface.closeAuxiliaryOverlay(),roamAlphaAPI.ui.mainWindow.openPage({page:{uid:o}})))}else{let a=e.target.closest('input[type="checkbox"]');if(a&&"selectAll"==a.getAttribute("name")){let t=a.checked,e=Array.from(document.querySelectorAll('.zotero-roam-auxiliary-overlay [name="explo-weblink"]'));e.forEach(e=>{e.checked=t}),zoteroRoam.interface.triggerImport(type="weblinks")}else a&&"explo-weblink"==a.getAttribute("name")&&zoteroRoam.interface.triggerImport(type="weblinks")}})},fillSearchOverlay(e=zoteroRoam.interface.search.overlayClass){let t=document.querySelector(`.${e}-overlay .bp3-dialog-body .main-panel`),a=document.createElement("div"),o=(a.classList.add("bp3-input-group"),a.classList.add("header-content"),document.createElement("div")),r=(o.classList.add("header-right"),document.createElement("div")),i=(r.classList.add("controls-top"),r.classList.add("zr-auxiliary"),r.innerHTML=`
              <button type="button" aria-label="Close" class="zotero-roam-overlay-close bp3-button bp3-minimal bp3-dialog-close-button bp3-large">
              <span icon="small-cross" class="bp3-icon bp3-icon-small-cross"></span></button>
              `,o.appendChild(r),document.createElement("div")),n=(i.classList.add("header-bottom"),document.createElement("span")),s=(n.id="zr-library-search-dialogtitle",t.closest('[role="dialog"]').setAttribute("aria-labelledby","zr-library-search-dialogtitle"),n.classList.add("zr-search-scope"),n.innerHTML='Zotero library <span class="bp3-icon bp3-icon-chevron-right"></span>',document.createElement("input")),l=(s.id="zotero-roam-search-autocomplete",s.tabIndex="1",s.type="text",s.classList.add("bp3-input"),i.appendChild(n),i.appendChild(s),a.appendChild(o),a.appendChild(i),t.appendChild(a),document.createElement("div")),d=(l.id="zotero-roam-library-rendered",l.setAttribute("view","search"),document.createElement("div")),c=(d.id="zotero-roam-library-search-div",document.createElement("div")),m=(c.id="zotero-roam-search-selected-item",document.createElement("div")),p=(m.classList.add("selected-item-header"),document.createElement("div")),u=(p.classList.add("selected-item-body"),c.appendChild(m),c.appendChild(p),l.appendChild(d),l.appendChild(c),t.appendChild(l),document.createElement("div"));u.classList.add("bp3-dialog-footer-actions"),u.innerHTML=`
              <div>
                  <span class="zotero-roam-library-results-count zr-auxiliary"></span>
                  <label class="bp3-control bp3-switch bp3-text-small quick-copy-element">
                  <input id="zotero-roam-quick-copy-mode" type="checkbox">
                  <span class="bp3-control-indicator"></span>
                  Quick Copy
              </label>
              </div>
              <input class="bp3-input clipboard-copy-utility bp3-small" type="text" readonly style="opacity:0;">
              <span class="bp3-popover2-target" tabindex="0">
                  <button type="button" class="zotero-roam-update-data bp3-button bp3-minimal bp3-small">
                  <span icon="refresh" class="bp3-icon bp3-icon-refresh"></span>
                  <span class="bp3-button-text">Update Zotero data</span>
                  </button>
              </span>
              `,t.appendChild(u),zoteroRoam.interface.search.overlay=document.querySelector(`.${e}-overlay`),zoteroRoam.interface.search.input=document.querySelector("#zotero-roam-search-autocomplete"),zoteroRoam.interface.search.selectedItemDiv=document.querySelector("#zotero-roam-search-selected-item"),zoteroRoam.interface.search.closeButton=document.querySelector(`.${e}-overlay button.zotero-roam-overlay-close`),zoteroRoam.interface.search.updateButton=document.querySelector(`.${e}-overlay button.zotero-roam-update-data`)},fillCitationsOverlay(e=zoteroRoam.interface.citations.overlayClass){let t=document.querySelector(`.${e}-overlay .bp3-dialog-body .main-panel`),a=document.querySelector(`.${e}-overlay .bp3-dialog-body .side-panel-contents`),o=document.createElement("div"),d=(o.classList.add("bp3-input-group"),o.classList.add("header-content"),document.createElement("div")),r=(d.classList.add("header-left"),document.createElement("h5")),m=(r.id="zr-citations-search-dialogtitle",t.closest('[role="dialog"]').setAttribute("aria-labelledby","zr-citations-search-dialogtitle"),r.classList.add("panel-tt"),r.innerText="Citing Papers",d.appendChild(r),document.createElement("div")),i=(m.classList.add("header-right"),document.createElement("div")),p=(i.classList.add("controls-top"),i.classList.add("zr-auxiliary"),i.innerHTML=`
              <button type="button" aria-label="Close" class="zotero-roam-overlay-close bp3-button bp3-minimal bp3-dialog-close-button">
              <span icon="small-cross" class="bp3-icon bp3-icon-small-cross"></span></button>
              `,m.appendChild(i),document.createElement("div")),n=(p.classList.add("header-bottom"),document.createElement("input")),u=(n.id="zotero-roam-citations-autocomplete",n.tabIndex="1",n.type="text",n.classList.add("bp3-input"),n.setAttribute("aria-controls","zotero-roam-citations-pagination"),p.appendChild(n),o.appendChild(d),o.appendChild(m),o.appendChild(p),document.createElement("div")),g=(u.id="zotero-roam-citations-pagination",t.appendChild(o),t.appendChild(u),document.createElement("div")),s=(g.classList.add("import-header"),g.innerHTML=`
              ${zoteroRoam.utils.renderBP3Button_group("Cancel",{buttonClass:"bp3-minimal bp3-intent-warning",icon:"chevron-left",buttonAttribute:'role="cancel"'})}
              ${zoteroRoam.utils.renderBP3Button_group("Add to Zotero",{buttonClass:"bp3-minimal bp3-intent-primary",icon:"inheritance",buttonAttribute:'disabled role="add" style="font-weight:600;"'})}
              `,document.createElement("div")),b=(s.classList.add("import-options"),document.createElement("div")),y=(b.classList.add("options-library-list"),document.createElement("div")),h=(y.classList.add("options-collections-list"),document.createElement("div")),l=(h.classList.add("options-tags"),document.createElement("div")),f=(l.classList.add("options-tags-select"),l.classList.add("bp3-input-group"),l.classList.add("bp3-small"),document.createElement("span")),c=(f.classList.add("bp3-icon"),f.classList.add("bp3-icon-tag"),f.classList.add("bp3-intent-primary"),document.createElement("input")),z=(c.id="zotero-roam-tagselector_citations",c.tabIndex="1",c.type="text",c.classList.add("zotero-roam-tags-autocomplete"),c.classList.add("bp3-input"),c.classList.add("bp3-fill"),c.setAttribute("autocomplete","off"),document.createElement("div")),v=(z.classList.add("options-tags_selection"),z.setAttribute("data-tags","[]"),l.appendChild(f),l.appendChild(c),h.appendChild(l),h.appendChild(z),s.appendChild(b),s.appendChild(y),s.appendChild(h),document.createElement("h5")),k=(v.innerText="Selected Items",v.classList.add("import-selection-header"),document.createElement("div")),R=(k.classList.add("import-items"),k.classList.add("bp3-list-unstyled"),a.setAttribute("zr-import","citations"),a.appendChild(g),a.appendChild(s),a.appendChild(v),a.appendChild(k),document.createElement("div"));R.classList.add("bp3-dialog-footer-actions"),R.innerHTML=`
              <div class="bp3-button-group bp3-minimal">
                  ${zoteroRoam.utils.renderBP3Button_group(string="",{icon:"chevron-left",buttonClass:"zotero-roam-page-control",buttonAttribute:'goto="previous" pagination="citations" aria-controls="zotero-roam-citations-pagination"'})}
                  ${zoteroRoam.utils.renderBP3Button_group(string="",{icon:"chevron-right",buttonClass:"zotero-roam-page-control",buttonAttribute:'goto="next" pagination="citations" aria-controls="zotero-roam-citations-pagination"'})}
                  <span class="zotero-roam-citations-results-count zr-auxiliary"></span>
              </div>
              <input class="bp3-input clipboard-copy-utility" type="text" readonly style="opacity:0;">
              `,t.appendChild(R),zoteroRoam.interface.citations.overlay=document.querySelector(`.${e}-overlay`),zoteroRoam.interface.citations.input=document.querySelector("#zotero-roam-citations-autocomplete"),zoteroRoam.interface.citations.closeButton=document.querySelector(`.${e}-overlay button.zotero-roam-overlay-close`),u.addEventListener("click",function(e){let a=e.target.closest("button");if(a)if(a.classList.contains("zotero-roam-citation-copy-doi"))zoteroRoam.interface.citations.overlay.querySelector("input.clipboard-copy-utility").value=a.dataset.doi,zoteroRoam.interface.citations.overlay.querySelector("input.clipboard-copy-utility").select(),document.execCommand("copy");else if(a.classList.contains("zotero-roam-citation-toggle-abstract")){let e=a.querySelector(".bp3-button-text"),t=a.closest(".zotero-roam-citations-search_result").querySelector(".zotero-roam-citation-abstract");"none"==t.style.display?(t.style.display="block",e.innerHTML="Hide Abstract"):(t.style.display="none",e.innerHTML="Show Abstract")}else a.classList.contains("zotero-roam-citation-add-import")&&zoteroRoam.interface.triggerImport(type="citations",element=a.closest(".bp3-menu-item"))})},fillDashboardOverlay(){let e=document.querySelector(".zotero-roam-dashboard-overlay .main-panel"),t=[{name:"tag-manager",icon:"tag",title:"Tag Manager",description:'Rename, merge, and delete tags between <span data-tag-source="roam">Roam</span> and <span data-tag-source="zotero">Zotero</span>'}],a=document.createElement("div"),o=(a.classList.add("side-section"),document.createElement("div")),r=(o.classList.add("bp3-tabs"),o.classList.add("bp3-vertical"),document.createElement("ul")),i=(r.classList.add("bp3-tab-list"),r.setAttribute("role","tablist"),t.forEach((e,t)=>{r.innerHTML+=`
                  <li class="bp3-tab" role="tab" name="${e.name}" ${0==t?'aria-selected="true"':""}>
                      <span class="bp3-icon bp3-icon-${e.icon}"></span>
                      ${e.title}
                  </li>`}),o.appendChild(r),a.appendChild(o),document.createElement("div")),n=(i.classList.add("main-section"),t.forEach((e,t)=>{i.innerHTML+=`
                  <div class="bp3-tab-panel" role="tabpanel" name="${e.name}" ${0==t?"":'aria-hidden="true"'}>
                      <div class="zr-tab-panel-header">
                          <span class="zr-tab-panel-description zr-auxiliary">${e.description}</span>
                          <div class="zr-auxiliary">
                              <button type="button" aria-label="Close" class="zotero-roam-overlay-close bp3-button bp3-minimal bp3-dialog-close-button bp3-large">
                              <span icon="small-cross" class="bp3-icon bp3-icon-small-cross"></span></button>
                          </div>
                      </div>
                      <div class="zr-tab-panel-contents">
                      </div>
                  </div>
                  `}),e.appendChild(a),e.appendChild(i),document.querySelector('.zotero-roam-dashboard-overlay .bp3-tab-panel[name="tag-manager"] .zr-tab-panel-contents'));n.innerHTML+=`
              <div class="zr-loading-overlay bp3-dialog" style="display:none;">
              ${zoteroRoam.utils.renderBP3Spinner()}
              </div>
              <div class="zr-tab-panel-toolbar">
                  <div class="bp3-button-group bp3-minimal">
                      <span class="zr-datalist-sort_option">
                          ${zoteroRoam.utils.renderBP3_minimalradio(label="Most Used",{varName:"zr-tag-manager-sort",optValue:"usage",icon:"sort-desc",modifier:'checked="true"',labelClass:"zr-text-small"})}
                      </span>
                      <span class="zr-datalist-sort_option">
                          ${zoteroRoam.utils.renderBP3_minimalradio(label="Name",{varName:"zr-tag-manager-sort",optValue:"alphabetical",icon:"sort-alphabetical",labelClass:"zr-text-small"})}
                      </span>
                      <span class="zr-datalist-sort_option">
                          ${zoteroRoam.utils.renderBP3_minimalradio(label="In Roam",{varName:"zr-tag-manager-sort",optValue:"roam",icon:"star",labelClass:"zr-text-small"})}
                      </span>
                  </div>
              </div>
              </div>
              <div class="bp3-overlay zr-tab-panel-popover" overlay-visible="hidden" style="flex: 0 1 100%;position: relative;display:none;">
                  <div class="bp3-dialog-container bp3-overlay-content">
                      <div class="bp3-dialog ${zoteroRoam.config.params.theme||""}" role="dialog">
                          <div class="bp3-dialog-header"></div>
                          <div class="bp3-dialog-body"></div>
                          <div class="bp3-dialog-footer"></div>
                      </div>
                  </div>
              </div>
              <ul id="zr-tag-manager-pagination" class="zr-tab-panel-datalist bp3-menu" role="listbox">
              </ul>
              <div class="zr-tab-panel-datalist-footer">
                  <div class="bp3-button-group bp3-minimal">
                      ${zoteroRoam.utils.renderBP3Button_group(string="",{icon:"chevron-left",buttonClass:"zotero-roam-page-control",buttonAttribute:'goto="previous" pagination="tagManager" aria-controls="zr-tag-manager-pagination"'})}
                      ${zoteroRoam.utils.renderBP3Button_group(string="",{icon:"chevron-right",buttonClass:"zotero-roam-page-control",buttonAttribute:'goto="next" pagination="tagManager" aria-controls="zr-tag-manager-pagination"'})}
                      <span class="zotero-roam-tag-list-count zr-auxiliary"></span>
                  </div>
                  <span class="zr-tag-stats zr-auxiliary zr-text-small"></span>
              </div>
              `,e.addEventListener("click",o=>{let r=o.target.closest(".bp3-tab-panel");if(r){var i=r.getAttribute("name");if("tag-manager"==i)if(o.target.closest(".zr-tab-panel-popover")){let e=o.target.closest("button[zr-command]");e&&(zoteroRoam.handlers.modifySelectedTags(action=e.getAttribute("zr-command")),e.classList.add("bp3-disabled"),e.setAttribute("aria-disabled","true"))}else{let e=r.querySelector(".zr-tab-panel-popover"),t=("true"==e.getAttribute("overlay-visible")&&(e.querySelector(".bp3-dialog-header").innerHTML="",e.querySelector(".bp3-dialog-body").innerHTML="",e.querySelector(".bp3-dialog-footer").innerHTML="",e.style.display="none",e.setAttribute("overlay-visible","hidden")),o.target.closest(".zr-tab-panel-toolbar")),a=o.target.closest(".zr-datalist-item");if(t){i=Array.from(t.querySelectorAll(".zr-datalist-sort_option input")).find(e=>1==e.checked).value;zoteroRoam.tagManager.activeDisplay.by!=i&&zoteroRoam.utils.updateTagPagination(libPath=zoteroRoam.tagManager.activeDisplay.library.path,{by:i})}else if(a){let e=o.target.closest("button[zr-action]");e&&zoteroRoam.interface.showTagActionsPopover(tokens=[a.getAttribute("data-token")],action=e.getAttribute("zr-action"))}}}})},showTagActionsPopover(e,s="Edit"){let t=document.querySelector('.zotero-roam-dashboard-overlay .bp3-tab-panel[name="tag-manager"] .zr-tab-panel-popover'),l="0 0 48%",a="0 0 50%",o="Delete tags",r="danger",i="trash";"Delete"!=s&&(l="0 0 33%",a="0 0 35%",o="Modify tags",r="primary",i="arrow-right"),t.querySelector(".bp3-dialog-header").innerHTML=`
              <h4 style="flex:${a};">Roam</h4>
              <h4 style="flex:${a};">Zotero</h4>
              `,t.querySelector(".bp3-dialog-body").innerHTML=`
              ${e.map((t,a)=>{let e=zoteroRoam.tagManager.pagination.data.find(e=>e.token==t),o="";var r;let i="",n=(o=0<e.roam.length?e.roam.map(e=>zoteroRoam.utils.renderBP3_option(string=`<span class="zr-tag-name">${e.title}</span>`,type="checkbox",depth=0,{varName:"zr-tag-select_"+a,optValue:e.title,optClass:"zr-text-small",modifier:"Delete"==s?"":"checked",labelModifier:`data-tag-source="roam" data-uid="${e.uid}"`})).join("\n"):'<span class="zr-secondary zr-text-small" style="display:block;width:100%;text-align:center;">No tags in Roam</span>',e.zotero.reduce((e,t)=>e.has(t.tag)?e.set(t.tag,[...e.get(t.tag),t.meta.numItems]):e.set(t.tag,[t.meta.numItems]),new Map));return r=Array.from(n.keys()).map(e=>zoteroRoam.utils.renderBP3_option(`<span class="zr-tag-name">${e} <span class="zr-secondary zr-text-small">(${n.get(e).join(" + ")})</span></span>`,"checkbox",0,{varName:"zr-tag-select_"+a,optValue:e,optClass:"zr-text-small",modifier:"checked",labelModifier:'data-tag-source="zotero"'})).join("\n"),"Delete"!=s&&(i=`
                      <div class="bp3-input-group zr-tag-column_input" style="flex: 0 0 28%;">
                          <span class="bp3-icon bp3-icon-fork"></span>
                          <input type="text" class="bp3-input zr-text-small" name="zr-tag-rename_${a}" spellcheck="false" placeholder="Rename tag(s) as ..." ${0<e.roam.length?'value="'+e.roam[0].title+'"':""}" />
                      </div>
                      `),`
                  <div class="zr-tag-entry" data-entry-index="${a}">
                      <div class="zr-tag-column_roam" style="flex:${l};">
                          ${o}
                      </div>
                      <div class="zr-tag-column_zotero" style="flex:${l};">
                          ${r}
                      </div>
                      ${i}
                  </div>
                  `}).join("\n")}
              `,t.querySelector(".bp3-dialog-footer").innerHTML=`
              <div class="zr-tab-panel-popover-footer">
                  <div class="bp3-button-group bp3-minimal bp3-small">
                      ${zoteroRoam.utils.renderBP3Button_group(o,{buttonClass:"bp3-active bp3-intent-"+r,icon:i,buttonAttribute:`zr-command="${s}"`})}
                  </div>
              </div>
              `,t.style.display="block",t.setAttribute("overlay-visible","true")},async handleImportPanelClicks(a){let o=a.target.closest("[zr-import]");var r=o.getAttribute("zr-import");let t=a.target.closest("button[role]");if(null!==t)switch(t.getAttribute("role")){case"cancel":zoteroRoam.interface.clearImportPanel(action="close",r);break;case"add":t.setAttribute("disabled","");var i=await zoteroRoam.handlers.importSelectedItems(o);"citations"==r?(zoteroRoam.citations.activeImport.outcome=i,zoteroRoam.interface.renderImportResults(i)):"weblinks"==r&&(zoteroRoam.webImport.activeImport.outcome=i),t.classList.remove("bp3-intent-primary");let e=t.querySelector(".bp3-icon");e.classList.remove("bp3-icon-inheritance"),e.classList.add("bp3-icon-tick"),e.setAttribute("icon","tick"),t.querySelector(".bp3-button-text").innerText="Done",t.classList.add("bp3-intent-success"),t.removeAttribute("disabled"),t.setAttribute("role","done");break;case"done":zoteroRoam.interface.clearImportPanel(action="reset",r)}null!==a.target.closest('input[name="library"]')&&zoteroRoam.interface.selectImportLibrary(r);var e=a.target.closest(".options-tags_selection");if(null!==e){let e=a.target.closest(".bp3-tag-remove");if(null!==e){let t=e.closest(".bp3-tag");try{let e=o.querySelector(".options-tags_selection");e.dataset.tags=JSON.stringify(JSON.parse(e.dataset.tags).filter(e=>e!=t.dataset.tag)),t.remove()}catch(a){console.error(a)}}}if(null!==a.target.closest(".import-items")){let e=a.target.closest("button.selected_remove-button");if(null!==e){let t=e.closest(".import-items_selected");try{"citations"==r&&(zoteroRoam.citations.activeImport.items=zoteroRoam.citations.activeImport.items.filter(e=>e!=t.dataset.identifier),t.remove(),zoteroRoam.interface.citations.overlay.querySelector(".import-selection-header").innerText=`Selected Items (${zoteroRoam.citations.activeImport.items.length})`,0==zoteroRoam.citations.activeImport.items.length&&(zoteroRoam.interface.citations.overlay.querySelector('button[role="add"]').setAttribute("disabled",""),zoteroRoam.interface.citations.overlay.querySelector(".import-selection-header").innerText="Selected Items"))}catch(a){console.error(a)}}}},renderCitationsPagination(){let e=document.querySelector("#zotero-roam-citations-pagination"),t=e.querySelector("ul"),a=(null==t&&(t=document.createElement("ul"),t.classList.add("zotero-roam-citations-search-results-list"),t.classList.add("bp3-menu"),t.tabIndex="-1",t.setAttribute("role","listbox"),e.appendChild(t)),zoteroRoam.citations.pagination.getCurrentPageData());e.closest(".main-panel").querySelector(".zotero-roam-citations-results-count").innerHTML=`
              <strong>${zoteroRoam.citations.pagination.startIndex}-${zoteroRoam.citations.pagination.startIndex+a.length-1}</strong> / ${zoteroRoam.citations.pagination.data.length} ${zoteroRoam.citations.currentType}
              `,t.innerHTML=a.map(t=>{var a,e=`<span class="zotero-roam-search-item-title" style="display:block;">${t.title}</span>`,o=`<span class="zotero-roam-citation-origin zr-highlight-2">${t.authors+(t.year?" ("+t.year+")":"")}</span><span class="zr-secondary">${t.meta}</span>`;let r="";for(a of Object.keys(t.links)){let e=[];switch(a){case"scite":e.push(`<span class="zotero-roam-citation-link" service="scite"><a href="${t.links[a]}" target="_blank" class="zr-text-small">Scite</a></span>`);break;case"connectedPapers":e.push(`<span class="zotero-roam-citation-link" service="connected-papers"><a href="${t.links[a]}" target="_blank" class="zr-text-small">Connected Papers</a></span>`);break;case"semanticScholar":e.push(`<span class="zotero-roam-citation-link" service="semantic-scholar"><a href="${t.links[a]}" target="_blank" class="zr-text-small">Semantic Scholar</a></span>`);break;case"googleScholar":e.push(`<span class="zotero-roam-citation-link" service="google-scholar"><a href="${t.links[a]}" target="_blank" class="zr-text-small">Google Scholar</a></span>`)}r+=e.join(" - ")}let i=`
                  <span class="bp3-menu-item-label zotero-roam-search-item-key">
                  `;return t.inLibrary?i+=t.citekey:i+=`
                      <a href="${t.doi?"https://doi.org/"+t.doi:t.url}" target="_blank" class="bp3-text-muted zr-text-small zotero-roam-citation-identifier-link">${t.doi||"Semantic Scholar"}</a>
                      ${t.abstract?zoteroRoam.utils.renderBP3Button_group("Show Abstract",{buttonClass:"zotero-roam-citation-toggle-abstract zr-text-small bp3-minimal"}):""}
                      ${t.doi?zoteroRoam.utils.renderBP3Button_group("Copy DOI",{buttonClass:"zotero-roam-citation-copy-doi zr-text-small bp3-small bp3-minimal",buttonAttribute:'data-doi="'+t.doi+'"'}):""}
                      ${zoteroRoam.utils.renderBP3Button_group("Add to Zotero",{buttonClass:"zotero-roam-citation-add-import zr-text-small bp3-small bp3-minimal bp3-intent-primary",icon:"inheritance"})}
                      `,i+=`
                  </span>
                  `,`
                  <li class="zotero-roam-citations-search_result" ${t.inLibrary?'in-library="true"':""} data-intent=${t.intent?JSON.stringify(t.intent):""} ${t.isInfluential?"is-influential":""}>
                  <div class="bp3-menu-item">
                  <div class="bp3-text-overflow-ellipsis zotero-roam-citation-metadata">
                  ${e}
                  ${o}
                  <span class="zotero-roam-citation-links-list">
                  ${r}
                  </span>
                  </div>
                  ${i}
                  <span class="zotero-roam-citation-abstract" style="display:none;">${t.abstract||""}</span>
                  </div></li>
                  `}).join("")},setupContextMenus(t){window.addEventListener("click",e=>{t.forEach(e=>{zoteroRoam.interface[""+e].visible&&zoteroRoam.interface.toggleContextOverlay(e,command="hide")})}),t.forEach(e=>{zoteroRoam.interface[""+e].div.addEventListener("click",e=>{var t=zoteroRoam.interface.contextTarget,e=e.target.closest("li.zotero-roam-cm-option");if(e)switch(e.innerText){case"Add metadata":var a=t.parentElement.dataset.linkTitle,o=t.parentElement.dataset.linkUid;zoteroRoam.handlers.importItemMetadata(title=a,uid=o);break;case"Convert to citation":zoteroRoam.inPage.convertToCitekey(t);break;case"Check for citing papers":zoteroRoam.handlers.checkForSemantic_citations(t);break;case"View item information":zoteroRoam.interface.popItemInformation(t);break;case"Update Zotero data":zoteroRoam.extension.update();break;case"Search in library":zoteroRoam.interface.toggleSearchOverlay("show")}})})},toggleContextOverlay(e,t){zoteroRoam.interface[""+e].overlay.div.style.display="show"==t?"block":"none",zoteroRoam.interface[""+e].visible="show"==t},async toggleSearchOverlay(e,{focus:t=!0}={}){if(zoteroRoam.interface.search.overlay.style.display="show"===e?"block":"none","show"==e)console.log("Opening the Search Panel"),zoteroRoam.data.roamPages=new Map(zoteroRoam.utils.getRoamPages()),1==t&&(await zoteroRoam.utils.sleep(75),zoteroRoam.interface.search.input.focus()),document.querySelector(".zotero-roam-library-results-count").innerHTML="",zoteroRoam.interface.search.input.value="",document.getElementById("zotero-roam-library-rendered").removeAttribute("has-results"),zoteroRoam.interface.search.overlay.setAttribute("overlay-visible","true");else{zoteroRoam.interface.clearSelectedItem();try{zoteroRoam.librarySearch.autocomplete.close()}catch(e){}document.querySelector(".zotero-roam-library-results-count").innerHTML="",zoteroRoam.interface.search.input.value="",zoteroRoam.interface.search.overlay.querySelector("input.clipboard-copy-utility").value="",zoteroRoam.interface.search.overlay.setAttribute("overlay-visible","false")}},changePage(e,t){let a=("citations"==e?zoteroRoam.citations:zoteroRoam.tagManager).pagination;if(null!==a&&0<a.nbPages)switch(t){case"previous":a.previousPage();break;case"next":a.nextPage()}},popCitationsOverlay(e,t,a="citations"){zoteroRoam.citations.currentDOI=e,zoteroRoam.citations.currentCitekey=t,zoteroRoam.citations.currentType=a;let o=zoteroRoam.data.semantic.get(e)[""+a],r=new Map(zoteroRoam.data.items.filter(e=>e.data.DOI).map(e=>[zoteroRoam.utils.parseDOI(e.data.DOI),e.key]));o.forEach((e,t)=>{e.doi&&r.has(zoteroRoam.utils.parseDOI(e.doi))&&(o[t].inLibrary=!0,o[t].citekey=r.get(e.doi))}),zoteroRoam.citations.pagination=new zoteroRoam.Pagination({data:o,render:"zoteroRoam.interface.renderCitationsPagination"}),zoteroRoam.interface.renderCitationsPagination(),null==zoteroRoam.citations.autocomplete?zoteroRoam.citations.autocomplete=new autoComplete(zoteroRoam.config.citationsSearch):zoteroRoam.citations.autocomplete.init();e="citations"==a?"Citing":"Referenced by";let i=zoteroRoam.interface.citations.overlay.querySelector("h5.panel-tt");i.innerText=e+" @"+t,i.setAttribute("list-type",a),zoteroRoam.interface.citations.overlay.style.display="block",zoteroRoam.interface.citations.input.value="",zoteroRoam.interface.citations.overlay.querySelector("input.clipboard-copy-utility").value="",zoteroRoam.interface.citations.overlay.setAttribute("overlay-visible","true"),zoteroRoam.interface.citations.input.focus()},popRelatedDialog(e,t,o){let a=document.querySelector(".zotero-roam-auxiliary-overlay");var r=1<t.length?"s":"",r="added-on"==o?`item${r} added on`:"tagged-with"==o?`item${r} tagged with`:`abstract${r} mentioning`;a.querySelector(".main-panel .header-left").innerHTML=`
              <h5 id="zr-related-dialogtitle" class="panel-tt" list-type="${o}">${t.length} ${r} ${e}</h5>
              `;let i=new Map(zoteroRoam.utils.getAllRefPages()),n="added-on"==o?"timestamp":"meta",s=t.map(t=>{var e=zoteroRoam.data.items.find(e=>e.key==t),a=e.meta.parsedDate?`(${new Date(e.meta.parsedDate).getUTCFullYear()})`:"",o=e.meta.creatorSummary+" "||"",r=i.get("@"+t)||!1;return{abstract:e.data.abstractNote||"",key:t,meta:o+a,title:e.data.title||"",inGraph:r,added:e.data.dateAdded,itemType:e.data.itemType,timestamp:zoteroRoam.utils.makeTimestamp(e.data.dateAdded)}}).sort((e,t)=>e[n].toLowerCase()<t[n].toLowerCase()?-1:1);r=s.map(t=>{let a="";if(t.inGraph){let e="@"+t.key;a=zoteroRoam.utils.renderBP3ButtonGroup("Go to page",{buttonClass:"zotero-roam-list-item-go-to-page",divClass:"bp3-minimal zr-text-small bp3-small",icon:"symbol-circle",modifier:"bp3-intent-success",buttonModifier:`data-uid="${t.inGraph}" data-citekey="${e.slice(1)}"`})}else a=zoteroRoam.utils.renderBP3Button_group("Add to Roam",{icon:"minus",buttonClass:"bp3-minimal bp3-intent-warning zr-text-small bp3-small zotero-roam-add-to-graph"});return`
                  <li class="zotero-roam-list-item" in-graph="${!!t.inGraph}" data-item-type="${t.itemType}">
                  <div class="bp3-menu-item" label="${t.key}">
                      ${"added-on"==o?`<span class="bp3-menu-item-label zotero-roam-item-timestamp zr-text-small">${t.timestamp}</span>`:""}
                      <div class="bp3-fill zotero-roam-item-contents">
                          <span class="zotero-roam-search-item-title" style="white-space:normal;">${t.title}</span>
                          <span class="zr-highlight">${t.meta}</span>
                          <span class="zotero-roam-list-item-key zr-text-small zr-auxiliary">[${t.key}]</span>
                          ${t.abstract?zoteroRoam.utils.renderBP3Button_group("Show Abstract",{buttonClass:"zotero-roam-citation-toggle-abstract bp3-intent-primary bp3-minimal bp3-small"}):""}
                          <span class="zotero-roam-citation-abstract zr-text-small zr-auxiliary" style="display:none;">${t.abstract}</span>
                      </div>
                      <span class="zotero-roam-list-item-actions">
                          ${a}
                      </span>
                  </div>
                  </li>
                  `}).join("\n");a.querySelector(".main-panel .rendered-div").innerHTML=`
              <ul class="bp3-list-unstyled">
              ${r}
              </ul>
              `,a.style.display="block",a.setAttribute("overlay-visible","true")},fillWebImportDialog(e){let t=document.querySelector(".zotero-roam-auxiliary-overlay"),a=e.map((e,t)=>({abstract:e.data.abstractNote||"",creators:e.data.creators?zoteroRoam.formatting.getCreators(e,{creators_as:"string",brackets:!1,use_type:!1}):"",publication:e.data.publicationTitle||e.data.bookTitle||e.data.websiteTitle||"",title:e.data.title||"",itemType:e.data.itemType,clean_type:zoteroRoam.formatting.getItemType(e),url:e.query,item_index:t}));e=1<a.length?"s":"",t.querySelector(".main-panel .header-left").innerHTML=`
              ${zoteroRoam.utils.renderBP3_option(string=`<h5 class="panel-tt" list-type="weblinks">${a.length} linked resource${e}</h5>`,type="checkbox",depth=0,{varName:"selectAll"})}
              `,e=a.map(e=>`
                  <li class="zotero-roam-list-item zr-explo-list-item" data-item-type="${e.itemType}">
                      <div class="bp3-menu-item" label="link-${e.item_index}">
                          <span class="zr-explo-title">${zoteroRoam.utils.renderBP3_option(string=`<a target="_blank" href="${e.url}">${e.title}</a>`,type="checkbox",depth=0,{varName:"explo-weblink",optValue:""+e.item_index})}</span>
                          <div class="bp3-text-overflow-ellipsis bp3-fill zotero-roam-item-contents">
                              <span class="zr-explo-metadata">${e.clean_type}${e.creators?" | "+e.creators:""}</span>
                              ${e.publication?`<span class="zr-explo-publication zr-text-small bp3-text-disabled">${e.publication}</span>`:""}
                              <span class="zr-explo-abstract zr-text-small bp3-text-muted">${e.abstract}</span>
                          </div>
                      </div>
                  </li>
                  `).join("\n");t.querySelector(".main-panel .rendered-div").innerHTML=`
              <ul class="bp3-list-unstyled">
              ${e}
              </ul>
              `},closeAuxiliaryOverlay(){let e=document.querySelector(".zotero-roam-auxiliary-overlay");e.style.display="none",e.setAttribute("overlay-visible","false"),zoteroRoam.interface.clearImportPanel(action="close",type="weblinks")},closeCitationsOverlay(){zoteroRoam.interface.citations.overlay.style.display="none",zoteroRoam.interface.citations.input.value="",zoteroRoam.interface.citations.overlay.querySelector("input.clipboard-copy-utility").value="",zoteroRoam.interface.clearImportPanel(action="close",type="citations"),zoteroRoam.interface.citations.overlay.setAttribute("overlay-visible","false")},toggleDashboardOverlay(){let t=document.querySelector(".zotero-roam-dashboard-overlay");if("false"==t.getAttribute("overlay-visible"))t.setAttribute("overlay-visible","true"),t.style.display="block";else{let e=t.querySelector('.zr-tab-panel-popover[overlay-visible="true"]');e&&(e.querySelector(".bp3-dialog-body").innerHTML="",e.querySelector(".bp3-dialog-footer").innerHTML="",e.style.display="none",e.setAttribute("overlay-visible","hidden")),t.setAttribute("overlay-visible","false"),t.style.display="none"}},popContextOverlay(e,t){e.preventDefault();var a={left:e.pageX,top:e.pageY};return zoteroRoam.interface[""+t].position(a),zoteroRoam.interface.contextTarget=e.target,!1},async popContextMenu(e){zoteroRoam.interface.popContextOverlay(e,"contextMenu"),await zoteroRoam.utils.sleep(120);try{document.querySelector("body > .bp3-context-menu+.bp3-portal").style.display="none"}catch(e){}},popIconContextMenu(e){zoteroRoam.interface.popContextOverlay(e,"iconContextMenu")},popItemInformation(e){e=e.parentElement.dataset.linkTitle.replace("@","");zoteroRoam.interface.renderItemInPanel(e)},renderItemInPanel(e){let r=e.startsWith("@")?e:"@"+e,n=zoteroRoam.data.items.find(e=>e.key==r.slice(1)),m=n.meta.parsedDate?` (${new Date(n.meta.parsedDate).getUTCFullYear().toString()})`:"";e=0<n.data.creators.length?`<span class="zotero-roam-search-item-authors zr-highlight">${n.meta.creatorSummary||""}${m}</span>`:"";let t=n.data.publicationTitle||n.data.bookTitle||n.data.university||"",p=(t=2<t.length?`<span class="zr-secondary">${t}</span>`:"","");n.data.DOI?(l=zoteroRoam.utils.parseDOI(n.data.DOI))&&(p=`
                      <span class="item-weblink zr-secondary" style="display:block;">
                          <a href="https://doi.org/${l}" target="_blank">${l}</a>
                      </span>`):n.data.url&&(p=`
                  <span class="item-weblink zr-secondary" style="display:block;">
                      <a href="${n.data.url}" target="_blank">${n.data.url}</a>
                  </span>`);var a=n.data.creators.map(e=>e.name||[e.firstName,e.lastName].filter(Boolean).join(" ")),u=n.data.creators.map(e=>e.creatorType);let o="";if(0<a.length)for(o="<strong>Contributors : </strong>",i=0;i<a.length;i++){var g=zoteroRoam.utils.lookForPage(title=a[i]),g=1==g.present?zoteroRoam.utils.renderPageReference(title=a[i],uid=g.uid):zoteroRoam.utils.renderBP3Tag(string=a[i],{modifier:"bp3-intent-primary item-creator-tag"}),b=u[i]&&"author"!=u[i]?` (${u[i]}) `:" ";o=o+g+b}var s=n.data.tags.map(e=>e.tag);let y="";if(0<s.length)for(y="<strong>Tags : </strong>",i=0;i<s.length;i++){var h=1==zoteroRoam.utils.lookForPage(title=s[i]).present?zoteroRoam.utils.renderPageTag(title=s[i]):zoteroRoam.utils.renderBP3Tag(string=s[i]);y=y+h+" "}let f=zoteroRoam.formatting.getItemCollections(n),z="";if(f){z="<strong>Collections : </strong>";try{z+=f.map(e=>zoteroRoam.utils.renderBP3Tag(string=e.data.name,{modifier:"bp3-intent-success bp3-round",icon:"projects"})).join(" ")}catch(e){console.log(f),console.log(e),console.error("Something went wrong while getting the item's collections data")}}var l=zoteroRoam.utils.lookForPage(r),c=1==l.present?'<span class="bp3-icon bp3-icon-symbol-circle"></span>':'<span class="bp3-icon bp3-icon-minus"></span>';let v=document.querySelector(".selected-item-header"),k=(v.innerHTML=`
              <div class="item-basic-metadata">
                  <h4 class="item-title" tabindex="0">${n.data.title||""}</h4>
                  ${e}${t}${p}
                  </div>
              <div class="item-citekey-section" in-graph="${l.present||!1}">
                  <div class="bp3-fill citekey-element">${c}${r}</div>
                  <div class="bp3-button-group bp3-fill bp3-minimal copy-buttons">
                      <a class="bp3-button bp3-small bp3-intent-primary" format="citekey">Copy @citekey ${zoteroRoam.shortcuts.sequences.copyCitekey?zoteroRoam.shortcuts.makeSequenceText("copyCitekey"):""}</a>
                      <a class="bp3-button bp3-small bp3-intent-primary" format="citation">[Citation]([[@]]) ${zoteroRoam.shortcuts.sequences.copyCitation?zoteroRoam.shortcuts.makeSequenceText("copyCitation"):""}</a>
                      <a class="bp3-button bp3-small bp3-intent-primary" format="tag">#@ ${zoteroRoam.shortcuts.sequences.copyTag?zoteroRoam.shortcuts.makeSequenceText("copyTag"):""}</a>
                      <a class="bp3-button bp3-small bp3-intent-primary" format="page-reference">[[@]] ${zoteroRoam.shortcuts.sequences.copyPageRef?zoteroRoam.shortcuts.makeSequenceText("copyPageRef"):""}</a>
                  </div>
              </div>
              `,document.querySelector(".selected-item-body")),R="";n.data.DOI&&n.data.DOI.startsWith("10.")?(e="https://doi.org/"+n.data.DOI,R=zoteroRoam.utils.renderBP3Button_link(string="Open in browser",{linkClass:"bp3-minimal bp3-fill bp3-align-left item-open-in-browser",icon:"share",iconModifier:"bp3-intent-primary",target:e,linkAttribute:'target="_blank"'})):n.data.url&&(R=zoteroRoam.utils.renderBP3Button_link(string="Open in browser",{linkClass:"bp3-minimal bp3-fill bp3-align-left item-open-in-browser",icon:"share",iconModifier:"bp3-intent-primary",target:n.data.url,linkAttribute:'target="_blank"'}));c=1==l.present?`data-uid="${l.uid}"`:"disabled",e=zoteroRoam.shortcuts.sequences.goToItemPage?zoteroRoam.shortcuts.makeSequenceText("goToItemPage",pre=" "):"",e=zoteroRoam.utils.renderBP3ButtonGroup(string="Go to Roam page  "+e,{buttonClass:"item-go-to-page",divClass:"bp3-minimal bp3-fill bp3-align-left",icon:"arrow-right",modifier:"bp3-intent-primary",buttonModifier:c+` data-citekey="${r.slice(1)}"`}),c=1==l.present?`data-uid="${l.uid}"`:'data-uid=""',l=zoteroRoam.shortcuts.sequences.importMetadata?zoteroRoam.shortcuts.makeSequenceText("importMetadata",pre=" "):"",l=zoteroRoam.utils.renderBP3ButtonGroup(string="Import metadata  "+l,{buttonClass:"item-add-metadata",divClass:"bp3-minimal bp3-fill bp3-align-left",icon:"add",modifier:"bp3-intent-primary",buttonModifier:c+` data-citekey="${r.slice(1)}"`});let d=zoteroRoam.formatting.getItemChildren(n,{pdf_as:"raw",notes_as:"raw"}),x="";if(d.remoteChildren)x+="<p>This item has children, but they were not returned by the API data request. This might be due to a request for 'items/top' rather than 'items'.</p>";else try{var w,S=d.pdfItems?d.pdfItems.map(e=>{var t="group"==e.library.type?"groups/"+e.library.id:"library",t=["linked_file","imported_file","imported_url"].includes(e.data.linkMode)?`zotero://open-pdf/${t}/items/`+e.data.key:e.data.url,e=e.data.filename||e.data.title;return zoteroRoam.utils.renderBP3Button_link(string=e,{linkClass:"bp3-minimal item-pdf-link",icon:"paperclip",target:t,linkAttribute:'target="_blank"'})}).join(""):"No PDF attachments";x+=S,d.notes&&(w=zoteroRoam.shortcuts.sequences.toggleNotes?zoteroRoam.shortcuts.makeSequenceText("toggleNotes",pre=" "):"",x+=""+zoteroRoam.utils.renderBP3Button_group(string="Show Notes"+w,{buttonClass:"bp3-minimal bp3-align-left bp3-fill item-see-notes",icon:"comment"}),zoteroRoam.interface.search.overlay.querySelector(".side-panel-contents").innerHTML=`
                          <h4>Notes</h4>
                          <div class="item-rendered-notes">
                              ${d.notes.map(e=>e.data.note).join("<br>")}
                          </div>
                          `)}catch(e){console.log(d),console.log(pdfDiv),console.log(e),console.log("Something went wrong while getting the item's children data")}k.innerHTML=`
              <div class="item-additional-metadata">
                  <p class="item-abstract zr-text-small bp3-running-text">${n.data.abstractNote}</p>
                  <p class="item-creators">${o}</p>
                  <p class="item-tags">${y}</p>
                  <p class="item-collections">${z}</p>
              </div>
              <div class="item-actions">
                  <div class="bp3-card">
                      ${R}
                      ${e}
                      ${l}
                  </div>
                  <div class="item-pdf-notes">
                      ${x}
                  </div>
              </div>
              `,Array.from(document.querySelectorAll(".item-citekey-section .copy-buttons a.bp3-button[format]")).forEach(o=>{o.addEventListener("click",e=>{let t=zoteroRoam.interface.search.overlay.querySelector("input.clipboard-copy-utility");switch(o.getAttribute("format")){case"citekey":t.value=""+r;break;case"citation":var a=""+(n.meta.creatorSummary||"")+(m||"");t.value=`[${a}]([[${r}]])`;break;case"tag":t.value=`#[[${r}]]`;break;case"page-reference":t.value=`[[${r}]]`}t.select(),document.execCommand("copy")})});try{let t=document.querySelector("button.item-see-notes");t.addEventListener("click",function(){let e=t.querySelector(".bp3-button-text").innerHTML;switch(!0){case e.startsWith("Show"):zoteroRoam.interface.search.overlay.querySelector(".bp3-dialog").setAttribute("side-panel","visible"),t.querySelector(".bp3-button-text").innerHTML=e.replace("Show","Hide");break;case e.startsWith("Hide"):zoteroRoam.interface.search.overlay.querySelector(".bp3-dialog").setAttribute("side-panel","hidden"),t.querySelector(".bp3-button-text").innerHTML=e.replace("Hide","Show")}})}catch(e){}switch(document.querySelector("#zotero-roam-library-rendered").setAttribute("view","item"),zoteroRoam.interface.search.overlay.getAttribute("overlay-visible")){case"true":document.querySelector("h4.item-title").focus();break;case"false":zoteroRoam.interface.toggleSearchOverlay("show",{focus:!1})}},clearSelectedItem(){try{zoteroRoam.interface.search.selectedItemDiv.children.forEach(e=>{e.innerHTML=""})}catch(e){Array.from(zoteroRoam.interface.search.selectedItemDiv.children).forEach(e=>{e.innerHTML=""})}zoteroRoam.interface.search.overlay.querySelector(".side-panel-contents").innerHTML="","visible"==zoteroRoam.interface.search.overlay.querySelector(".bp3-dialog").getAttribute("side-panel")&&zoteroRoam.interface.search.overlay.querySelector(".bp3-dialog").setAttribute("side-panel","hidden"),document.querySelector("#zotero-roam-library-rendered").setAttribute("view","search")},checkEditingMode(){let e=document.querySelector("textarea.rm-block-input");e&&null==e.getAttribute("zotero-tribute")&&(document.querySelectorAll(".zotero-roam-tribute").forEach(e=>e.remove()),e.setAttribute("zotero-tribute","active"),new Tribute(zoteroRoam.config.tribute).attach(e),e.addEventListener("tribute-replaced",r=>{if("zotero"==r.detail.item.original.source){let e=document.querySelector("textarea.rm-block-input");var i=r.detail.context.mentionTriggerChar+r.detail.context.mentionText;let a=r.detail.context.mentionPosition,o=r.detail.item.original.value,t=r.target.defaultValue;r=zoteroRoam.utils.escapeRegExp(i),r=new RegExp(r,"g"),r=t.replaceAll(r,(e,t)=>t==a?o:e);zoteroRoam.interface.tributeTrigger=i,zoteroRoam.interface.tributeBlockTrigger=e,zoteroRoam.interface.tributeNewText=r;Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set.call(e,r);i=new Event("input",{bubbles:!0});e.dispatchEvent(i)}}))},triggerImport(e="citations",t=null){let a=document.querySelector(`[zr-import="${e}"]`);var o=("citations"==e?zoteroRoam.citations:zoteroRoam.webImport).activeImport,t=(null==o?(zoteroRoam.data.roamPages=new Map(zoteroRoam.utils.getRoamPages()),zoteroRoam.tagSelection["citations"==e?"cit_panel":"aux_panel"].init(),zoteroRoam.activeImport.libraries=zoteroRoam.utils.getLibraries(),zoteroRoam.interface.renderImportOptions(e)):"citations"==e&&a.querySelector('button[role="done"]')&&zoteroRoam.interface.clearImportPanel(action="reset",e),"citations"==e?zoteroRoam.interface.renderImportCitations(t):"weblinks"==e&&zoteroRoam.interface.renderImportWeblinks(),!!o&&0<o.items.length);t&&zoteroRoam.activeImport.currentLib?a.querySelector('button[role="add"]').removeAttribute("disabled"):a.querySelector('button[role="add"]').setAttribute("disabled","")},renderImportCitations(e){let t=document.querySelector('[zr-import="citations"]');var a=e.querySelector(".zotero-roam-citation-identifier-link").innerText,o=e.querySelector(".zotero-roam-search-item-title").innerText,r=e.querySelector(".zotero-roam-citation-origin").innerText;null==zoteroRoam.citations.activeImport?(zoteroRoam.citations.activeImport={items:[],outcome:null},zoteroRoam.interface.triggerImport(type="citations",e),t.closest(".bp3-dialog").setAttribute("side-panel","visible")):zoteroRoam.citations.activeImport.items.includes(a)||(zoteroRoam.citations.activeImport.items.push(a),t.querySelector(".import-items").innerHTML+=`
                      <li class="import-items_selected" data-identifier="${a}">
                      <div class="selected_info">
                      <span class="selected_title bp3-text-muted">${o}</span>
                      <span class="selected_origin">${r}</span>
                      </div>
                      <div class="selected_state">
                      ${zoteroRoam.utils.renderBP3Button_group(string="",{buttonClass:"bp3-small bp3-minimal bp3-intent-danger selected_remove-button",icon:"cross"})}
                      </div>
                      </li>
                      `,t.querySelector(".import-selection-header").innerText=`Selected Items (${zoteroRoam.citations.activeImport.items.length})`)},renderImportWeblinks(){if(null!=zoteroRoam.webImport.activeImport){let e=Array.from(document.querySelectorAll('[name="explo-weblink"]')).filter(e=>e.checked);zoteroRoam.webImport.activeImport.items=e.map(e=>zoteroRoam.webImport.activeImport.harvest[Number(e.getAttribute("value"))].data)}},renderImportOptions(e="citations"){let t=document.querySelector(`[zr-import="${e}"]`),a=zoteroRoam.activeImport.libraries;e=zoteroRoam.utils.renderBP3_list(a,"radio",{varName:"library",has_value:"path",has_string:"name",selectFirst:!0,active_if:"writeable"});let o="",r=a.find(e=>1==e.writeable);r&&(zoteroRoam.activeImport.currentLib=r,o=zoteroRoam.utils.renderBP3_list(r.collections.map(e=>({name:e.data.name,key:e.key,depth:e.depth})),"checkbox",{varName:"collections",has_value:"key",has_string:"name"})),t.querySelector(".options-library-list").innerHTML=e,t.querySelector(".options-collections-list").innerHTML=o},renderImportResults(i){zoteroRoam.citations.activeImport.items.forEach(t=>{let e=zoteroRoam.interface.citations.overlay.querySelector(`.import-items_selected[data-identifier="${t}"]`);var a=i.harvest.find(e=>e.query==t);switch(a.success){case null:e.querySelector(".selected_state").innerHTML=`<span icon="ban-circle" class="bp3-icon bp3-icon-ban-circle bp3-intent-danger" title="${a.error.name} : ${a.error.message}"></span>`;break;case!1:e.querySelector(".selected_state").innerHTML=`<span icon="error" class="bp3-icon bp3-icon-error bp3-intent-warning" title="${a.response.status}"></span>`;break;case!0:let t=a.data;var o=i.write;switch(o.success){case null:e.querySelector(".selected_state").innerHTML=`<span icon="ban-circle" class="bp3-icon bp3-icon-ban-circle bp3-intent-danger" title="${o.error.name} : ${o.error.message}"></span>`;break;case!1:e.querySelector(".selected_state").innerHTML=`<span icon="error" class="bp3-icon bp3-icon-error bp3-intent-warning" title="${o.response.status} : ${o.response.statusText}"></span>`;break;case!0:var r=Object.values(o.data.successful).find(e=>e.data.title==t.title&&e.data.url==t.url);r&&(e.querySelector(".selected_state").innerHTML=`<span icon="tick" class="bp3-icon bp3-icon-tick bp3-intent-success" title="${r.data.key}"></span>`)}}})},selectImportLibrary(e="citations"){let t=document.querySelector(`[zr-import="${e}"]`);var e=zoteroRoam.activeImport.currentLib.path;let a=Array.from(t.querySelectorAll('.options-library-list [name="library"]')).find(e=>1==e.checked).value;a!=e&&(zoteroRoam.activeImport.currentLib=zoteroRoam.activeImport.libraries.find(e=>e.path==a),e=zoteroRoam.utils.renderBP3_list(zoteroRoam.activeImport.currentLib.collections.map(e=>({name:e.data.name,key:e.key})),"checkbox",{varName:"collections",has_value:"key",has_string:"name"}),t.querySelector(".options-collections-list").innerHTML=e)},clearImportPanel(e="close",t="citations"){let a=document.querySelector(`[zr-import="${t}"]`);switch(e){case"close":a.closest(".bp3-dialog").setAttribute("side-panel","hidden"),"citations"==t?zoteroRoam.citations.activeImport=null:"weblinks"==t&&(zoteroRoam.webImport.activeImport=null),a.querySelector(".options-library-list").innerHTML="",a.querySelector(".options-collections-list").innerHTML="";break;case"reset":"citations"==t?(zoteroRoam.citations.activeImport.items=[],zoteroRoam.citations.activeImport.outcome=null):"weblinks"==t&&(Array.from(a.closest(".bp3-dialog").querySelectorAll('[name="explo-weblink"]')).forEach(e=>{e.checked=!1}),a.closest(".bp3-dialog").querySelectorAll('[name="selectAll"]').checked=!1,zoteroRoam.webImport.activeImport.items=[])}let o=a.querySelector('button[role="done"]');o&&(o.classList.remove("bp3-intent-success"),o.querySelector(".bp3-icon").classList.remove("bp3-icon-tick"),o.querySelector(".bp3-icon").classList.add("bp3-icon-inheritance"),o.querySelector(".bp3-icon").setAttribute("icon","inheritance"),o.querySelector(".bp3-button-text").innerText="Add to Zotero",o.classList.add("bp3-intent-primary"),o.setAttribute("role","add")),a.querySelector('button[role="add"]').setAttribute("disabled",""),a.querySelector(".zotero-roam-import-tags-list").value="",a.querySelector(".options-tags_selection").innerHTML="",a.querySelector(".options-tags_selection").dataset.tags="[]","citations"==t&&(a.querySelector(".import-selection-header").innerText="Selected Items",a.querySelector(".import-items").innerHTML="")}},zoteroRoam.extension={async load(){zoteroRoam.interface.icon.style="background-color: #fd9d0d63!important;";var e=await zoteroRoam.handlers.requestData(zoteroRoam.config.requests);if(!e.success)throw zoteroRoam.interface.icon.style="background-color:#f9a3a3 !important",zoteroRoam.interface.popToast(message="There was a problem with the Zotero data request. Please check your specification !",intent="danger"),new Error("The API request encountered a problem. Please check your request specification, and the console for any registered errors.");try{let t=[],e=(Array.from(new Set(zoteroRoam.config.requests.map(e=>e.apikey))).forEach(e=>{t.push(fetch("https://api.zotero.org/keys/"+e,{method:"GET",headers:{"Zotero-API-Version":3,"Zotero-API-Key":e}}))}),await Promise.all(t));e=await Promise.all(e.map(e=>e.json())),e=e.flat(1),zoteroRoam.data.keys=e}catch(e){console.error(e)}zoteroRoam.data.items=e.data.items,zoteroRoam.data.collections=e.data.collections,zoteroRoam.interface.icon.setAttribute("status","on"),zoteroRoam.inPage.checkReferences(),document.addEventListener("blur",zoteroRoam.inPage.checkReferences,!0),window.addEventListener("locationchange",zoteroRoam.inPage.checkReferences,!0),zoteroRoam.config.ref_checking=setInterval(zoteroRoam.inPage.checkReferences,1e3),zoteroRoam.utils.sleep(100),zoteroRoam.inPage.addPageMenus(wait=0),window.addEventListener("locationchange",zoteroRoam.inPage.addPageMenus,!0),zoteroRoam.config.page_checking=setInterval(function(){zoteroRoam.inPage.addPageMenus(wait=0)},1e3),zoteroRoam.config.userSettings.webimport&&(zoteroRoam.config.tag_checking=setInterval(function(){zoteroRoam.inPage.addWebImport()},1e3)),zoteroRoam.config.userSettings.autoupdate&&(zoteroRoam.config.auto_update=setInterval(function(){zoteroRoam.extension.update(popup=!1)},6e4)),zoteroRoam.config.userSettings.render_inline&&(zoteroRoam.config.render_inline=setInterval(function(){zoteroRoam.inPage.renderCitekeyRefs()},1e3)),null==zoteroRoam.librarySearch.autocomplete?zoteroRoam.librarySearch.autocomplete=new autoComplete(zoteroRoam.config.autoComplete):zoteroRoam.librarySearch.autocomplete.init(),1==zoteroRoam.config.params.autocomplete.enabled&&(zoteroRoam.config.editingObserver=new MutationObserver(zoteroRoam.interface.checkEditingMode),zoteroRoam.config.editingObserver.observe(document,{childList:!0,subtree:!0})),null==zoteroRoam.tagSelection.cit_panel?zoteroRoam.tagSelection.cit_panel=zoteroRoam.config.tagSelection(selector="#zotero-roam-tagselector_citations",index="cit_panel"):zoteroRoam.tagSelection.cit_panel.init(),null==zoteroRoam.tagSelection.aux_panel?zoteroRoam.tagSelection.aux_panel=zoteroRoam.config.tagSelection(selector="#zotero-roam-tagselector_auxiliary",index="aux_panel"):zoteroRoam.tagSelection.aux_panel.init(),zoteroRoam.interface.icon.addEventListener("contextmenu",zoteroRoam.interface.popIconContextMenu),window.addEventListener("keyup",zoteroRoam.shortcuts.verify),window.addEventListener("keydown",zoteroRoam.shortcuts.verify),roamAlphaAPI.ui.commandPalette.addCommand({label:"zoteroRoam : Open the search panel",callback:()=>{zoteroRoam.interface.toggleSearchOverlay("show")}}),zoteroRoam.smartblocks.registerCommands(),zoteroRoam.events.emit("ready",detail=zoteroRoam.data),zoteroRoam.interface.icon.style="background-color: #60f06042!important;",zoteroRoam.interface.popToast(message="Zotero data successfully loaded !",intent="success"),console.log("The results of the API request have been received ; you can check them by inspecting the value of the zoteroRoam.data object. Data import context menu should now be available.")},unload(){zoteroRoam.interface.icon.setAttribute("status","off"),zoteroRoam.data.items=[],zoteroRoam.data.collections=[],zoteroRoam.data.semantic.clear(),zoteroRoam.data.keys=[];for(lib of zoteroRoam.data.libraries.keys())zoteroRoam.data.libraries.get(lib).version="0";null!==zoteroRoam.librarySearch.autocomplete&&zoteroRoam.librarySearch.autocomplete.unInit(),null!==zoteroRoam.citations.autocomplete&&zoteroRoam.citations.autocomplete.unInit(),null!==zoteroRoam.tagSelection.cit_panel&&zoteroRoam.tagSelection.cit_panel.unInit(),null!==zoteroRoam.tagSelection.aux_panel&&zoteroRoam.tagSelection.aux_panel.unInit(),Array.from(document.querySelectorAll(".zotero-roam-page-div")).forEach(e=>e.remove());let e=document.querySelectorAll("ref-citekey");e.forEach(e=>{e.removeAttribute("data-zotero-bib"),e.querySelector(".rm-page-ref").removeEventListener("contextmenu",zoteroRoam.interface.popContextMenu)}),zoteroRoam.interface.icon.removeEventListener("contextmenu",zoteroRoam.interface.popIconContextMenu),document.removeEventListener("blur",zoteroRoam.inPage.checkReferences,!0),window.removeEventListener("locationchange",zoteroRoam.inPage.checkReferences,!0);try{clearInterval(zoteroRoam.config.ref_checking)}catch(e){}try{clearInterval(zoteroRoam.config.page_checking)}catch(e){}try{clearInterval(zoteroRoam.config.tag_checking)}catch(e){}try{clearInterval(zoteroRoam.config.auto_update)}catch(e){}try{clearInterval(zoteroRoam.config.render_inline)}catch(e){}zoteroRoam.inPage.renderCitekeyRefs();try{zoteroRoam.config.editingObserver.disconnect()}catch(e){}window.removeEventListener("keyup",zoteroRoam.shortcuts.verify),window.removeEventListener("keydown",zoteroRoam.shortcuts.verify),roamAlphaAPI.ui.commandPalette.removeCommand({label:"zoteroRoam : Open the search panel"}),zoteroRoam.interface.icon.removeAttribute("style"),zoteroRoam.interface.popToast(message="All Zotero data was cleared. Bye for now !",intent="success"),console.log("Data and request outputs have been removed")},toggle(){"off"==zoteroRoam.interface.icon.getAttribute("status")?zoteroRoam.extension.load():zoteroRoam.extension.unload()},async update(e="true",t=zoteroRoam.config.requests){zoteroRoam.interface.icon.style="background-color: #fd9d0d63!important;";var a,t=t.map(e=>{var t=zoteroRoam.data.libraries.get(e.library).version,{apikey:e,dataURI:a,params:o,name:r,library:i}=e;let n=new URLSearchParams(o);return n.set("since",t),{apikey:e,dataURI:a,params:n.toString(),name:r,library:i}});let o=await zoteroRoam.handlers.requestData(t,update=!0,collections=!0);1==o.success?(o.data.collections.forEach(t=>{var e=zoteroRoam.data.collections.findIndex(e=>e.key==t.key);-1==e?zoteroRoam.data.collections.push(t):zoteroRoam.data.collections[e]=t}),0==(a=o.data.items).length?e&&zoteroRoam.interface.popToast("No new items were found since the data was last loaded. Data on collections was refreshed.","primary"):(a=zoteroRoam.handlers.incorporateUpdates(a),zoteroRoam.inPage.checkCitekeys(update=!0),e?zoteroRoam.interface.popToast(`${a.new} new items and ${a.modified} modified items were added.`,"primary"):console.log(`${a.new} new items and ${a.modified} modified items were added.`)),zoteroRoam.interface.icon.style="background-color: #60f06042!important;"):e?zoteroRoam.interface.popToast("Something went wrong when updating the data. Check the console for any errors.","warning"):console.log("Something went wrong when updating the data. Check the console for any errors."),zoteroRoam.events.emit("update",{success:o.success,requests:t,data:o.data})}},zoteroRoam.inPage={addContextMenuListener(){for(var e=document.querySelectorAll(".ref-citekey"),t=0;t<e.length;t++){var a=e[t];a.dataset.zoteroBib||(zoteroRoam.data.items.find(e=>e.key==a.dataset.linkTitle.replace("@",""))?a.dataset.zoteroBib="inLibrary":a.dataset.zoteroBib="notFound"),"inLibrary"==a.dataset.zoteroBib&&a.querySelector(".rm-page-ref").addEventListener("contextmenu",zoteroRoam.interface.popContextMenu)}},checkReferences(e=!1){let t;setTimeout(function(){do{var e=document.getElementsByClassName("rm-page-ref");t=zoteroRoam.inPage.identifyCitekeys(e)}while(1==t)},300),zoteroRoam.inPage.checkCitekeys(e),zoteroRoam.inPage.addContextMenuListener()},identifyCitekeys(t){let a=!1;for(i=0;i<t.length;i++){let e=t[i].parentElement;void 0!==e.dataset.linkTitle&&e.dataset.linkTitle.startsWith("@")&&(a=!e.classList.contains("ref-citekey")&&(e.classList.add("ref-citekey"),!0))}return a},checkCitekeys(e=!1){let t=document.querySelectorAll(".ref-citekey"),a=0,o=0;t.forEach(t=>{if(t.dataset.zoteroBib)1==e&&"notFound"==t.dataset.zoteroBib&&(zoteroRoam.data.items.find(e=>e.key==t.dataset.linkTitle.replace("@",""))?(t.dataset.zoteroBib="inLibrary",a+=1):o+=1);else switch(t.dataset.zoteroBib=zoteroRoam.data.items.find(e=>e.key==t.dataset.linkTitle.replace("@",""))?"inLibrary":"notFound",t.dataset.zoteroBib){case"inLibrary":a+=1;break;case"notFound":o+=1}}),0<a|0<o&&console.log(`New matched citekeys: ${a}, New unmatched citekeys: `+o)},convertToCitekey(t){let r=zoteroRoam.data.items.find(e=>e.key==t.innerText.slice(1)),e=t.closest(".roam-block");var a=e.id.slice(-9),o=Array.from(e.querySelectorAll(".ref-citekey")).findIndex(e=>e==t.parentNode),i=window.roamAlphaAPI.q("[:find ?text :in $ ?uid :where[?b :block/uid ?uid][?b :block/string ?text]]",a)[0];if(0<i.length){let e=i[0];i=new RegExp(`(.*?(?:\\[\\[@.+?\\]\\].*?){${o}})(\\[\\[@.+?\\]\\])(.*)`,"g"),o=e.replace(i,(e,t,a,o)=>""+t+zoteroRoam.utils.formatItemReference(r,"citation")+o);window.roamAlphaAPI.updateBlock({block:{uid:a,string:o}})}},async addPageMenus(e=100){var n;zoteroRoam.utils.sleep(e);for(const s of Array.from(document.querySelectorAll("h1.rm-title-display")))if(!s.parentElement.querySelector(".zotero-roam-page-div")&&!s.parentElement.querySelector(".zotero-roam-page-related")){let i=(s.querySelector("span")?s.querySelector("span"):s).innerText;if(zoteroRoam.config.params.pageMenu.trigger(i))if(i.startsWith("@")){let t=i.slice(1);var a=zoteroRoam.data.items.find(e=>e.key==t);if(void 0!==a)zoteroRoam.inPage.renderCitekeyMenu(item=a,i=i,elem=s);else try{s.parentElement.querySelector(".zotero-roam-page-div").remove()}catch(e){}}else if(i.match(/(.+) ([0-9]+).{2}, ([0-9]{4})/g)){let t=zoteroRoam.utils.findSameDay(zoteroRoam.utils.readDNP(i));if(0<t.length){a=t.map(e=>e.key);let e=document.createElement("div");e.classList.add("zotero-roam-page-related"),e.classList.add("bp3-button-group"),e.classList.add("bp3-minimal"),e.classList.add("bp3-align-left"),e.classList.add("bp3-vertical"),e.innerHTML=zoteroRoam.utils.renderBP3Button_group(string=`${t.length} item${1<t.length?"s":""} added`,{icon:"calendar",buttonClass:"zotero-roam-page-added-on",buttonAttribute:`data-title="${i}" data-keys=`+JSON.stringify(a)}),s.insertAdjacentElement("afterend",e)}}else{let o=zoteroRoam.data.items.filter(e=>e.data.tags&&e.data.tags.map(e=>e.tag).includes(i)),r=zoteroRoam.data.items.filter(e=>e.data.abstractNote&&e.data.abstractNote.includes(i));if(0<o.length||0<r.length){let e=document.createElement("div"),t=(e.classList.add("zotero-roam-page-related"),e.classList.add("bp3-button-group"),e.classList.add("bp3-minimal"),e.classList.add("bp3-align-left"),e.classList.add("bp3-vertical"),"");0<o.length&&(n=o.map(e=>e.key),t=zoteroRoam.utils.renderBP3Button_group(o.length+" tagged item"+(1<o.length?"s":""),{icon:"manual",buttonClass:"zotero-roam-page-tagged-with",buttonAttribute:`data-title="${i}" data-keys=`+JSON.stringify(n)}));let a="";0<r.length&&(n=r.map(e=>e.key),a=zoteroRoam.utils.renderBP3Button_group(r.length+" abstract"+(1<r.length?"s":""),{icon:"manually-entered-data",buttonClass:"zotero-roam-page-abstract-mentions",buttonAttribute:`data-title="${i}" data-keys=`+JSON.stringify(n)})),e.innerHTML=`
                          ${t}
                          ${a}
                          `,s.insertAdjacentElement("afterend",e)}}}},makeSciteBadge(e,{layout:t="horizontal",showZero:a="true",showLabels:o="false",tooltip:r="bottom"}={}){let i=document.createElement("div");return i.classList.add("scite-badge"),i.setAttribute("data-doi",e),i.setAttribute("data-layout",t),i.setAttribute("data-show-zero",a),i.setAttribute("data-show-labels",o),i.setAttribute("data-tooltip-placement",r),i},async handleClicks(i){if(i.closest(".zotero-roam-page-div")){var n=i.closest(".zotero-roam-page-div");let e=n.dataset.title,t=n.dataset.uid,a=i.closest("button");if(a)if(a.classList.contains("zotero-roam-page-menu-add-metadata"))console.log(`Importing metadata to ${e} (${t})...`),zoteroRoam.handlers.importItemMetadata(e,t=t,{popup:!0});else if(a.classList.contains("zotero-roam-page-menu-import-notes"))console.log(`Adding notes to ${e} (${t})...`),zoteroRoam.handlers.addItemNotes(e=e,t=t);else if(a.classList.contains("zotero-roam-page-menu-view-item-info"))zoteroRoam.interface.renderItemInPanel(citekey=e);else if(a.classList.contains("zotero-roam-page-menu-backlinks-button")){let e=a.querySelector(".bp3-icon-caret-down"),t=a.parentElement.querySelector(".zotero-roam-page-menu-backlinks-list");Array.from(e.classList).includes("rm-caret-closed")&&t?(e.classList.replace("rm-caret-closed","rm-caret-open"),t.style.display="flex"):Array.from(e.classList).includes("rm-caret-open")&&(e.classList.replace("rm-caret-open","rm-caret-closed"),t.style.display="none")}else a.classList.contains("zotero-roam-page-menu-backlink-open-sidebar")?zoteroRoam.utils.addToSidebar(t=a.dataset.uid):a.classList.contains("zotero-roam-page-menu-backlink-add-sidebar")?(n=roamAlphaAPI.util.generateUID(),roamAlphaAPI.createPage({page:{title:a.dataset.title,uid:n}}),await zoteroRoam.handlers.importItemMetadata(e=a.dataset.title,t=n,{popup:!1}),zoteroRoam.utils.addToSidebar(t=n)):a.classList.contains("zotero-roam-page-menu-backlinks-total")?(n=a.getAttribute("data-doi"),s=a.getAttribute("data-citekey"),zoteroRoam.interface.popCitationsOverlay(n,s,type="citations")):a.classList.contains("zotero-roam-page-menu-references-total")&&(n=a.getAttribute("data-doi"),s=a.getAttribute("data-citekey"),zoteroRoam.interface.popCitationsOverlay(n,s,type="references"))}else if(i.closest(".zotero-roam-page-related")){let e=i.closest("button");e&&(n=e.dataset.title,s=JSON.parse(e.dataset.keys),e.classList.contains("zotero-roam-page-added-on")?zoteroRoam.interface.popRelatedDialog(n,s,type="added-on"):e.classList.contains("zotero-roam-page-tagged-with")?zoteroRoam.interface.popRelatedDialog(n,s,type="tagged-with"):e.classList.contains("zotero-roam-page-abstract-mentions")&&zoteroRoam.interface.popRelatedDialog(n,s,type="abstract-mention"))}else if(i.closest(".zotero-roam-explo-import")){let e=i.closest(".rm-block");n=e.querySelectorAll(".rm-block a:not(.rm-alias--page):not(.rm-alias--block)");let t=Array.from(n).map(e=>e.href),a=(zoteroRoam.webImport.currentBlock=e.querySelector(".rm-block-main .roam-block"),document.querySelector(".zotero-roam-auxiliary-overlay")),o=(a.querySelector(".main-panel .header-left").innerHTML=""+zoteroRoam.utils.renderBP3Spinner(),a.querySelector(".main-panel .rendered-div").innerHTML="",a.querySelector(".bp3-dialog").setAttribute("side-panel","visible"),zoteroRoam.interface.triggerImport(type="weblinks"),a.style.display="block",a.setAttribute("overlay-visible","true"),[]),r=(t.forEach(e=>{o.push(zoteroRoam.handlers.requestCitoid(query=e))}),await Promise.all(o));zoteroRoam.webImport.activeImport={items:null};var s=r.filter(e=>1==e.success);0<(zoteroRoam.webImport.activeImport.harvest=s).length?zoteroRoam.interface.fillWebImportDialog(s):a.querySelector(".main-panel .header-left").innerHTML="<p>No data successfully retrieved</p>"}},async renderCitekeyMenu(n,a,o){var s=a.slice(1),l=zoteroRoam.utils.parseDOI(n.data.DOI)||"",c=zoteroRoam.utils.lookForPage(a);let d=zoteroRoam.formatting.getItemChildren(n,{pdf_as:"raw",notes_as:"raw"}),m=zoteroRoam.config.params.pageMenu.defaults,p=o.parentElement.querySelector(".zotero-roam-page-div");if(null==p){p=document.createElement("div"),p.classList.add("zotero-roam-page-div"),p.setAttribute("data-uid",c.uid),p.setAttribute("data-title",a),p.innerHTML=l?`
                  <span class="zotero-roam-page-doi" data-doi="${l}">
                  <a href="https://doi.org/${l}" class="bp3-text-muted" target="_blank">${l}</a>
                  </span>
                  `:"",o.insertAdjacentElement("afterend",p);let e=o.parentElement.querySelector(".zotero-roam-page-menu");null==e&&(e=document.createElement("div"),e.classList.add("zotero-roam-page-menu"),e.classList.add("bp3-card"),zoteroRoam.config.params.theme&&e.classList.add(zoteroRoam.config.params.theme),p.appendChild(e));var g=m.includes("addMetadata")?zoteroRoam.utils.renderBP3Button_group(string="Add metadata",{buttonClass:"bp3-minimal zotero-roam-page-menu-add-metadata",icon:"add"}):"",b=m.includes("importNotes")&&d.notes?zoteroRoam.utils.renderBP3Button_group(string="Import notes",{buttonClass:"bp3-minimal zotero-roam-page-menu-import-notes",icon:"comment"}):"",y=m.includes("viewItemInfo")?zoteroRoam.utils.renderBP3Button_group(string="View item information",{buttonClass:"bp3-minimal zotero-roam-page-menu-view-item-info",icon:"info-sign"}):"",h=m.includes("openZoteroLocal")?zoteroRoam.utils.renderBP3Button_link(string="Open in Zotero",{linkClass:"bp3-minimal zotero-roam-page-menu-open-zotero-local",target:zoteroRoam.formatting.getLocalLink(n,{format:"target"}),linkAttribute:'target="_blank"',icon:"application"}):"",f=m.includes("openZoteroWeb")?zoteroRoam.utils.renderBP3Button_link(string="Open in Zotero [Web library]",{linkClass:"bp3-minimal zotero-roam-page-menu-open-zotero-web",target:zoteroRoam.formatting.getWebLink(n,{format:"target"}),linkAttribute:'target="_blank"',icon:"cloud"}):"",z=m.includes("pdfLinks")&&d.pdfItems?d.pdfItems.map(e=>{var t="group"==e.library.type?"groups/"+e.library.id:"library",t=["linked_file","imported_file","imported_url"].includes(e.data.linkMode)?`zotero://open-pdf/${t}/items/`+e.data.key:e.data.url,e=e.data.filename||e.data.title;return zoteroRoam.utils.renderBP3Button_link(string=e,{linkClass:"bp3-minimal zotero-roam-page-menu-pdf-link",icon:"paperclip",target:t,linkAttribute:'target="_blank"'})}).join(""):"";let t=[],r=(m.includes("connectedPapers")&&t.push(zoteroRoam.utils.renderBP3Button_link(string="Connected Papers",{icon:"layout",linkClass:"bp3-minimal bp3-intent-primary zotero-roam-page-menu-connected-papers",linkAttribute:'target="_blank"',target:"https://www.connectedpapers.com/"+(n.data.DOI?"api/redirect/doi/"+l:"search?q="+encodeURIComponent(n.data.title))})),m.includes("semanticScholar")&&t.push(l?zoteroRoam.utils.renderBP3Button_link(string="Semantic Scholar",{icon:"bookmark",linkClass:"bp3-minimal bp3-intent-primary zotero-roam-page-menu-semantic-scholar",linkAttribute:'target="_blank"',target:"https://api.semanticscholar.org/"+l}):""),m.includes("googleScholar")&&t.push(zoteroRoam.utils.renderBP3Button_link(string="Google Scholar",{icon:"learning",linkClass:"bp3-minimal bp3-intent-primary zotero-roam-page-menu-google-scholar",linkAttribute:'target="_blank"',target:"https://scholar.google.com/scholar?q="+(n.data.DOI?l:encodeURIComponent(n.data.title))})),""),i=null;try{if(m.includes("citingPapers")&&l&&(i=await zoteroRoam.handlers.getSemantic(l),i.data)){let o=i.citations.map(e=>zoteroRoam.utils.parseDOI(e.doi)).filter(Boolean);var u=i.references.map(e=>zoteroRoam.utils.parseDOI(e.doi)).filter(Boolean);let t=[...o,...u];if(0<t.length){let e=zoteroRoam.data.items.filter(e=>zoteroRoam.utils.parseDOI(e.data.DOI)),a=t.map(t=>e.find(e=>zoteroRoam.utils.parseDOI(e.data.DOI)==t)).filter(Boolean);a.forEach((e,t)=>{o.includes(e.data.DOI)?a[t].type="citing":a[t].type="cited"}),r="",r+=zoteroRoam.utils.renderBP3Button_group(string=`${0<i.references.length?i.references.length:"No"} references`,{buttonClass:"bp3-minimal bp3-intent-primary zotero-roam-page-menu-references-total",icon:"citation",buttonAttribute:`data-doi="${l}" data-citekey="${s}" aria-label="Show available references" `+(0<u.length?"":"disabled aria-disabled='true'")}),r+=zoteroRoam.utils.renderBP3Button_group(string=`${0<i.citations.length?i.citations.length:"No"} citing papers`,{buttonClass:"bp3-minimal bp3-intent-warning zotero-roam-page-menu-backlinks-total",icon:"chat",buttonAttribute:`data-doi="${l}" data-citekey="${s}" aria-label="Show available citing papers" `+(0<o.length?"":"disabled aria-disabled='true'")}),r+=zoteroRoam.utils.renderBP3Button_group(string=`${0<a.length?a.length:"No"} related library items`,{buttonClass:`${0<a.length?"":"bp3-disabled"} bp3-minimal zotero-roam-page-menu-backlinks-button`,icon:"caret-down bp3-icon-standard rm-caret rm-caret-closed",buttonAttribute:`aria-label="Show related items present in Zotero library" aria-controls="zr-backlinks-list-${s}" `+(0<a.length?"":"aria-disabled='true'")}),0<a.length&&(r+=`
                                      <ul id="zr-backlinks-list-${s}" class="zotero-roam-page-menu-backlinks-list bp3-list-unstyled" style="display:none;">
                                      ${zoteroRoam.inPage.renderBacklinksList_year(a,origin_year=n.meta.parsedDate?new Date(n.meta.parsedDate).getUTCFullYear():"")}
                                      </ul>
                                      `)}}}catch(e){console.log("Citations rendering error : "+e)}e.innerHTML=`
                  <div class="zotero-roam-page-menu-header">
                  <div class="zotero-roam-page-menu-actions bp3-button-group">
                  ${g}
                  ${b}
                  ${y}
                  ${h}
                  ${f}
                  ${z}
                  ${0==t.length?"":t.join("\n")}
                  </div>
                  </div>
                  <div class="zotero-roam-page-menu-citations" ${l?`data-doi="${l}"`:""}>
                  ${r}
                  </div>
                  `,m.includes("sciteBadge")&&n.data.DOI&&null==o.parentElement.querySelector(".scite-badge")&&(u=zoteroRoam.inPage.makeSciteBadge(doi=l),o.parentElement.querySelector(".zotero-roam-page-menu-header").appendChild(u),window.__SCITE.insertBadges()),zoteroRoam.events.emit("menu-ready",{title:a,item:n,doi:l,uid:c.uid,children:d,semantic:i,div:p,context:p.closest(".roam-article")?"main":"sidebar"})}},renderCitekeyRefs(){var o=document.querySelectorAll("span[data-link-title^='@']");for(i=0;i<o.length;i++){let e=o[i],t=e.getElementsByClassName("rm-page-ref")[0];var r,n=e.getAttribute("data-zotero-bib");let a=e.getAttribute("data-link-title").slice(1);"inLibrary"==n&&(r=zoteroRoam.data.items.find(e=>e.key==a))?t.textContent=zoteroRoam.utils.formatItemReference(r,"inline"):t.textContent!="@"+a&&(t.textContent="@"+a)}},renderBacklinksItem_year(e,t,a=null){var o="reference"==t?"zr-highlight":"zr-highlight-2",r="reference"==t?"bp3-intent-primary":"bp3-intent-warning";return a?`
                  <li class="related-item_listed" item-type="${t}" data-key="@${e.key}" data-item-type="${e.data.itemType}" data-item-year="${e.meta.parsedDate?new Date(e.meta.parsedDate).getUTCFullYear():""}" in-graph="true">
                      <div class="related_year">${e.meta.parsedDate?new Date(e.meta.parsedDate).getUTCFullYear():""}</div>
                      <div class="related_info">
                          <span class="zotero-roam-search-item-authors ${o}">${e.meta.creatorSummary||""}</span><span class="zr-secondary">${e.data.publicationTitle||e.data.bookTitle||""}</span>
                          <a class="zotero-roam-search-item-title" href="${window.location.hash.match(/#\/app\/([^\/]+)/g)[0]}/page/${a}">
                              ${e.data.title}
                          </a>
                      </div>
                      <div class="related_state">
                          ${zoteroRoam.utils.renderBP3Button_group(string="",{buttonClass:`bp3-minimal zr-text-small ${r} zotero-roam-page-menu-backlink-open-sidebar`,icon:"inheritance",buttonAttribute:`data-uid="${a}" title="Open in sidebar" aria-label="Open @${e.key} in the sidebar"`})}
                      </div>
                  </li>`:`
                  <li class="related-item_listed" item-type="${t}" data-key="@${e.key}" data-item-type="${e.data.itemType}" data-item-year="${e.meta.parsedDate?new Date(e.meta.parsedDate).getUTCFullYear():""}" in-graph="false">
                  <div class="related_year">${e.meta.parsedDate?new Date(e.meta.parsedDate).getUTCFullYear():""}</div>
                  <div class="related_info">
                      <span class="zotero-roam-search-item-authors ${o}">${e.meta.creatorSummary||""}</span><span class="zr-secondary">${e.data.publicationTitle||e.data.bookTitle||""}</span>
                      <span class="zotero-roam-search-item-title">${e.data.title}</span>
                  </div>
                  <div class="related_state">
                      ${zoteroRoam.utils.renderBP3Button_group(string="@"+e.key,{buttonClass:"bp3-minimal zr-text-small zotero-roam-page-menu-backlink-add-sidebar",icon:"plus",buttonAttribute:`data-title="@${e.key}" title="Add & open in sidebar" aria-label="Add & open @${e.key} in the sidebar"`})}
                  </div>
                  </li>`},renderBacklinksItem(e,t,a=null){var o="reference"==t?"citation":"chat",r="reference"==t?"zr-highlight":"zr-highlight-2";return a?`
                  <li class="related-item_listed" item-type="${t}" data-key="@${e.key}" in-graph="true">
                  <div class="related_info">
                  <a class="related_info-wrapper" href="${window.location.hash.match(/#\/app\/([^\/]+)/g)[0]}/page/${a}"><span><span class="bp3-icon bp3-icon-${o}"></span>${zoteroRoam.utils.formatItemReference(e,"zettlr_accent",{accent_class:r})}</span></a>
                  </div>
                  <div class="related_state">
                  ${zoteroRoam.utils.renderBP3Button_group(string="",{buttonClass:"bp3-minimal zotero-roam-page-menu-backlink-open-sidebar",icon:"inheritance",buttonAttribute:`data-uid="${a}" title="Open in sidebar"`})}
                  </div>
                  </li>`:`
                  <li class="related-item_listed" item-type="${t}" data-key="@${e.key}" in-graph="false">
                  <div class="related_info">
                  <span class="related_info-wrapper"><span class="bp3-icon bp3-icon-${o}"></span>${zoteroRoam.utils.formatItemReference(e,"zettlr_accent",{accent_class:r})}</span>
                  </div>
                  <div class="related_state">
                  ${zoteroRoam.utils.renderBP3Button_group(string="",{buttonClass:"bp3-minimal zotero-roam-page-menu-backlink-add-sidebar",icon:"add",buttonAttribute:`data-title="@${e.key}" title="Add & open in sidebar"`})}
                  </div>
                  </li>`},renderBacklinksList_year(e,t){let a=new Map(zoteroRoam.utils.getAllRefPages()),o=e.sort((e,t)=>{var a;return e.meta.parsedDate?!t.meta.parsedDate||(a=new Date(e.meta.parsedDate).getUTCFullYear()-new Date(t.meta.parsedDate).getUTCFullYear())<0||0==a&&e.meta.creatorSummary<t.meta.creatorSummary?-1:1:!t.meta.parsedDate&&e.meta.creatorSummary<t.meta.creatorSummary?-1:1}),r=o.filter(e=>"cited"==e.type).map(e=>{var t=a.get("@"+e.key)||null;return zoteroRoam.inPage.renderBacklinksItem_year(e,"reference",uid=t)}),i=o.filter(e=>"citing"==e.type).map(e=>{var t=a.get("@"+e.key)||null;return zoteroRoam.inPage.renderBacklinksItem_year(e,"citation",uid=t)});return`
              <ul class="related-sublist bp3-list-unstyled" list-type="references">
                  ${r.join("\n")}
              </ul>
              <span class="backlinks-list_divider">
                  <span class="bp3-tag bp3-minimal">${t}</span>
                  <hr>
              </span>
              <ul class="related-sublist bp3-list-unstyled" list-type="citations">
                  ${i.join("\n")}
              </ul>
              `},renderBacklinksList(e){let t=e.filter(e=>"citing"==e.type),a=e.filter(e=>"cited"==e.type),o=[],r=[],i=(0<a.length&&(o=a.sort((e,t)=>e.meta.creatorSummary<t.meta.creatorSummary?-1:1).map(e=>{var t=zoteroRoam.utils.lookForPage("@"+e.key).uid||null;return zoteroRoam.inPage.renderBacklinksItem(e,"reference",uid=t)})),0<t.length&&(r=t.sort((e,t)=>e.meta.creatorSummary<t.meta.creatorSummary?-1:1).map(e=>{var t=zoteroRoam.utils.lookForPage("@"+e.key).uid||null;return zoteroRoam.inPage.renderBacklinksItem(e,"citation",uid=t)})),[...o,...r]);e=Math.ceil(i.length/2);let n=[],s=[];return s=o.length>e?(n=o.slice(0,e),[...r,...o.slice(e)]):(n=i.slice(0,e),i.slice(e)),`
              <ul class="col-1-left bp3-list-unstyled">
              ${n.join("")}
              </ul>
              <ul class="col-2-right bp3-list-unstyled">
              ${s.join("")}
              </ul>
              `},addWebImport(){var e=zoteroRoam.config.params.webimport.tags;let t=e.constructor===Array?e:[e],o=document.createElement("button"),a=(o.setAttribute("type","button"),o.classList.add("bp3-button"),o.classList.add("bp3-minimal"),o.classList.add("zotero-roam-explo-import"),o.innerHTML='<span icon="geosearch" class="bp3-icon bp3-icon-geosearch"></span>',Array.from(document.querySelectorAll(".rm-block:not(.rm-block--ghost)")).filter(e=>zoteroRoam.utils.matchArrays(t,JSON.parse(e.getAttribute("data-page-links")))));a.forEach(e=>{var t=e.querySelectorAll(".rm-block a:not(.rm-alias--page):not(.rm-alias--block)");let a=e.firstChild;0<t.length?(e.setAttribute("data-zr-explo","true"),Array.from(a.classList).includes("zotero-roam-explo-import")||e.insertAdjacentElement("afterbegin",o.cloneNode(!0))):(e.setAttribute("data-zr-explo","false"),Array.from(a.classList).includes("zotero-roam-explo-import")&&a.remove())})}},zoteroRoam.formatting={getCreators(e,{creators_as:t="string",brackets:a=!0,use_type:o=!0}={}){let r=e.data.creators.map(e=>{var t=e.name?""+e.name:""+[e.firstName,e.lastName].filter(Boolean).join(" ");return{name:t,type:e.creatorType,inGraph:zoteroRoam.utils.lookForPage(t)}});switch(t){case"identity":return r;case"array":return r.map(e=>e.name);default:return(1==o?r.map(e=>{return(1==a?`[[${e.name}]]`:e.name)+("author"==e.type?"":` (${e.type})`)}):r.map(e=>1==a?`[[${e.name}]]`:e.name)).join(", ")}},async getItemBib(e,{include:t="bib",style:a="apa",linkwrap:o=0,locale:r="en-US"}={}){e=e.bib||await zoteroRoam.handlers.requestItemBib(e,{include:t,style:a,linkwrap:o,locale:r});return zoteroRoam.utils.formatBib(e)},getChildrenInDataset(t){var e=zoteroRoam.data.items.filter(e=>e.data.parentItem==t.data.key&e.library.id==t.library.id);return 0<e.length&&e},getItemChildren(t,{pdf_as:a="links",notes_as:e="formatted",split_char:o=zoteroRoam.config.params.notes.split_char}={}){let r={pdfItems:!1,notes:!1},i=[];var n=zoteroRoam.formatting.getChildrenInDataset(t);switch(n?i=n:0<t.meta.numChildren&&(r.remoteChildren=!0),a){case"raw":var s=i.filter(e=>"application/pdf"==e.data.contentType);r.pdfItems=0!=s.length&&s;break;case"identity":let e=i.filter(e=>"application/pdf"==e.data.contentType);r.pdfItems=0!=e.length&&e.map(e=>({title:e.data.title,key:e.key,link:zoteroRoam.utils.makePDFLinks(e)}));break;case"links":r.pdfItems=zoteroRoam.utils.makePDFLinks(i.filter(e=>"application/pdf"==e.data.contentType))}var l=i.filter(e=>"note"==e.data.itemType);switch(e){case"raw":r.notes=0!=l.length&&l;break;case"formatted":r.notes=0!=l.length&&zoteroRoam.handlers.formatNotes(notes=l,use=zoteroRoam.config.params.notes.use,o)}return r},getItemCollections(a){return 0<a.data.collections.length&&a.data.collections.map(t=>zoteroRoam.data.collections.find(e=>e.key==t&&e.library.id==a.library.id))},getItemRelated(t,{return_as:a="citekeys",brackets:o=!0}={}){if(t.data.relations&&t.data.relations["dc:relation"]){let e=t.data.relations["dc:relation"],n=(e.constructor===String&&(e=[e]),[]),s=/(users|groups)\/([^\/]+)\/items\/(.+)/g;return e.forEach(e=>{let[,t,a,o]=Array.from(e.matchAll(s))[0],r=(t=t.slice(0,-1),a=new Number(a),null);for(let e=0;e<zoteroRoam.data.items.length;e++){var i=zoteroRoam.data.items[e];if(i.library.type==t&&i.library.id==a&&i.data.key==o){r=i;break}}r&&n.push(r)}),"raw"!==a?o?n.map(e=>`[[@${e.key}]]`):n.map(e=>e.key):n}return[]},getItemType(e){let t=zoteroRoam.typemap[e.data.itemType]||e.data.itemType;return zoteroRoam.config.userSettings.typemap&&(t=zoteroRoam.config.userSettings.typemap[e.data.itemType]||t),t},getLocalLink(e,{format:t="markdown",text:a="Local library"}={}){var o=`zotero://select/${"group"==e.library.type?"groups/"+e.library.id:"library"}/items/`+e.data.key;switch(t){case"target":default:return o;case"markdown":return`[${a}](${o})`}},getWebLink(e,{format:t="markdown",text:a="Web library"}={}){var o=`https://www.zotero.org/${("user"==e.library.type?"users":"groups")+"/"+e.library.id}/items/`+e.data.key;switch(t){case"target":default:return o;case"markdown":return`[${a}](${o})`}},getTags(e){return e.data.tags.map(e=>"#[["+e.tag+"]]").join(", ")},getItemMetadata(e){let t=[],a=(e.data.title&&t.push("Title:: "+e.data.title),0<e.data.creators.length&&t.push("Author(s):: "+zoteroRoam.formatting.getCreators(e,{creators_as:"string",brackets:!0,use_type:!0})),e.data.abstractNote&&t.push("Abstract:: "+e.data.abstractNote),e.data.itemType&&t.push(`Type:: [[${zoteroRoam.formatting.getItemType(e)}]]`),t.push("Publication:: "+(e.data.publicationTitle||e.data.bookTitle||"")),e.data.url&&t.push("URL : "+e.data.url),e.data.dateAdded&&t.push("Date Added:: "+zoteroRoam.utils.makeDNP(e.data.dateAdded,{brackets:!0})),t.push(`Zotero links:: ${zoteroRoam.formatting.getLocalLink(e,{format:"markdown",text:"Local library"})}, `+zoteroRoam.formatting.getWebLink(e,{format:"markdown",text:"Local library"})),0<e.data.tags.length&&t.push("Tags:: "+zoteroRoam.formatting.getTags(e)),zoteroRoam.formatting.getItemChildren(e,{pdf_as:"links",notes_as:"formatted"}));if(a.pdfItems&&t.push("PDF links : "+a.pdfItems.join(", ")),a.notes){let e={string:"[[Notes]]",children:[]};e.children.push(...a.notes.flat(1)),t.push(e)}return t}},zoteroRoam.shortcuts={actions:{closeSearchPanel:{defaultShortcut:{Escape:!0},execute(){let e=document.querySelector('.bp3-overlay[overlay-visible="true"]')||!1;e&&(e.classList.contains(zoteroRoam.interface.search.overlayClass+"-overlay")?zoteroRoam.interface.toggleSearchOverlay("hide"):e.classList.contains(zoteroRoam.interface.citations.overlayClass+"-overlay")?zoteroRoam.interface.closeCitationsOverlay():e.classList.contains("zotero-roam-auxiliary-overlay")?zoteroRoam.interface.closeAuxiliaryOverlay():e.classList.contains("zotero-roam-dashboard-overlay")&&zoteroRoam.interface.toggleDashboardOverlay())}},toggleSearchPanel:{defaultShortcut:{altKey:!0,q:!0},execute(){var e;"true"==zoteroRoam.interface.citations.overlay.getAttribute("overlay-visible")?zoteroRoam.interface.closeCitationsOverlay():"true"==document.querySelector(".zotero-roam-auxiliary-overlay").getAttribute("overlay-visible")?zoteroRoam.interface.closeAuxiliaryOverlay():"true"==document.querySelector(".zotero-roam-dashboard-overlay").getAttribute("overlay-visible")?zoteroRoam.interface.toggleDashboardOverlay():(e="true"==zoteroRoam.interface.search.overlay.getAttribute("overlay-visible")?"hide":"show",zoteroRoam.interface.toggleSearchOverlay(e))}},toggleQuickCopy:{defaultShortcut:[],execute(){document.getElementById("zotero-roam-quick-copy-mode").click()}},importMetadata:{defaultShortcut:[],execute(){let e=document.querySelector("button.item-add-metadata");null!==e&&e.click()}},focusSearchBar:{defaultShortcut:[],execute(){let e=document.querySelector('.bp3-overlay[overlay-visible="true"]')||!1;e&&e.querySelector('input.bp3-input[type="text"]').focus()}},goToItemPage:{defaultShortcut:[],execute(){let e=document.querySelector("button.item-go-to-page");var t,a;e&&!e.disabled&&"true"==zoteroRoam.interface.search.overlay.getAttribute("overlay-visible")&&(t=e.getAttribute("data-uid"),a="@"+e.getAttribute("data-citekey"),console.log(`Navigating to ${a} (${t})`),roamAlphaAPI.ui.mainWindow.openPage({page:{uid:t}}))}},copyCitekey:{defaultShortcut:[],execute(){let e=document.querySelector('.item-citekey-section .copy-buttons a.bp3-button[format="citekey"]');null!==e&&e.click()}},copyCitation:{defaultShortcut:[],execute(){let e=document.querySelector('.item-citekey-section .copy-buttons a.bp3-button[format="citation"]');null!==e&&e.click()}},copyTag:{defaultShortcut:[],execute(){let e=document.querySelector('.item-citekey-section .copy-buttons a.bp3-button[format="tag"]');null!==e&&e.click()}},copyPageRef:{defaultShortcut:[],execute(){let e=document.querySelector('.item-citekey-section .copy-buttons a.bp3-button[format="page-reference"]');null!==e&&e.click()}},toggleNotes:{defaultShortcut:[],execute(){let e=document.querySelector('.zotero-roam-search-overlay[overlay-visible="true"] button.item-see-notes');null!==e&&e.click()}}},sequences:{},getSequences(t){let a=zoteroRoam.config.shortcuts.filter(e=>e.action==t);if(0==a.length)return!1;{let e=a.map(e=>{let t=[];for(key in e.template){var a;1==e.template[key]&&(a=key.endsWith("Key")?key.slice(0,-3):key,t.push(a))}return t});return e.map(e=>e.join("-")).join(" or ")}},generateSequences(){for(action in zoteroRoam.shortcuts.actions){var e=zoteroRoam.shortcuts.getSequences(action);e&&(zoteroRoam.shortcuts.sequences[action]=e)}},makeSequenceText(e,t="",a){return`${t}<span class="zotero-roam-sequence">${zoteroRoam.shortcuts.sequences[e]}</span>`},setup(){let a={},o=(Object.keys(zoteroRoam.shortcuts.actions).forEach(e=>{a[e]=zoteroRoam.shortcuts.actions[e].defaultShortcut}),{}),t=(zoteroRoam.config.userSettings.shortcuts?Object.keys(zoteroRoam.shortcuts.actions).forEach(e=>{var{[e]:t=a[e]}=zoteroRoam.config.userSettings.shortcuts;o[e]=t}):o=a,[]);for(k in o)o[k].constructor===Object?t.push({action:k,template:o[k]}):o[k].constructor===Array&&o[k].forEach(e=>{t.push({action:k,template:e})});t.forEach(e=>{zoteroRoam.config.shortcuts.push(new zoteroRoam.Shortcut(e))})},setupSequences(){zoteroRoam.shortcuts.generateSequences();let a=zoteroRoam.shortcuts.sequences.toggleSearchPanel?zoteroRoam.shortcuts.makeSequenceText("toggleSearchPanel",pre="Toggle panel with "):"",o=zoteroRoam.shortcuts.sequences.closeSearchPanel?zoteroRoam.shortcuts.makeSequenceText("closeSearchPanel",pre="Exit with "):"";if(0<a.length|0<o.length){let e=document.createElement("span"),t=(e.style="font-size:0.8em;margin:3px;",e.innerHTML=[a,o].filter(Boolean).join(" / ")+"  ",zoteroRoam.interface.search.overlay.querySelector(".controls-top"));if(t.insertBefore(e,zoteroRoam.interface.search.closeButton),0<o.length){let e=zoteroRoam.interface.citations.overlay.querySelector(".controls-top"),t=document.createElement("span"),a=(t.style="font-size:0.8em;margin:6px;",t.innerHTML=""+o,e.insertBefore(t,zoteroRoam.interface.citations.closeButton),document.querySelector(".zotero-roam-auxiliary-overlay .controls-top"));var r=t.cloneNode(!0);a.insertBefore(r,a.querySelector(".bp3-dialog-close-button"))}}r=zoteroRoam.shortcuts.sequences.toggleQuickCopy?zoteroRoam.shortcuts.makeSequenceText("toggleQuickCopy",pre=" "):"",0<r.length&&(zoteroRoam.interface.search.overlay.querySelector(".quick-copy-element").innerHTML+=r),r=zoteroRoam.shortcuts.sequences.focusSearchBar?zoteroRoam.shortcuts.makeSequenceText("focusSearchBar"):"";if(0<r.length){let t=document.createElement("span");t.classList.add("bp3-input-action"),t.style="height:30px;padding:5px;",t.innerHTML=""+r,Array.from(document.querySelectorAll(`#${zoteroRoam.interface.portal.id} input.bp3-input[type="text"]`)).forEach(e=>e.closest(".bp3-input-group").appendChild(t.cloneNode(!0)))}},verify(r){let i=r.key,n="keydown"==r.type,s=["altKey","ctrlKey","metaKey","shiftKey"];zoteroRoam.config.shortcuts=zoteroRoam.config.shortcuts.map(e=>{let{action:t,template:a,watcher:o}=e;return s.forEach(e=>{o[e]=r[e]}),a.hasOwnProperty(i)|a.hasOwnProperty(i.toLowerCase())&&(e=a.hasOwnProperty(i)?i:i.toLowerCase(),o[e]=n),{action:t,template:a,watcher:o}}),zoteroRoam.config.shortcuts.forEach(e=>{JSON.stringify(e.watcher)===JSON.stringify(e.template)&&zoteroRoam.shortcuts.actions[""+e.action].execute()})}},zoteroRoam.events={ready:{},"menu-ready":{},"metadata-added":{},"notes-added":{},update:{},write:{},emit(e,t={},a=document){e=new CustomEvent("zotero-roam:"+e,{bubbles:!0,cancelable:!0,detail:t});1==zoteroRoam.config.userSettings.logEvents&&console.log(e),a.dispatchEvent(e)},defaultHooks(){document.addEventListener("zotero-roam:metadata-added",e=>{let t=e.detail.title;var a=e.detail.uid;try{let e=document.querySelector(".item-in-graph"),t=(null!=e&&(e.innerHTML='<span class="bp3-icon-tick bp3-icon bp3-intent-success"></span><span> In the graph</span>'),document.querySelector(".item-go-to-page"));null!=t&&(t.setAttribute("data-uid",a),t.removeAttribute("disabled"))}catch(e){}try{let e=document.querySelector(`.zotero-roam-auxiliary-overlay .bp3-menu-item[label="${t.slice(1)}"]`);null!=e&&(e.setAttribute("in-graph","true"),e.querySelector(".zotero-roam-add-to-graph").remove(),e.innerHTML+=zoteroRoam.utils.renderBP3ButtonGroup("Go to page",{buttonClass:"zotero-roam-list-item-go-to-page",divClass:"bp3-minimal bp3-small",icon:"symbol-circle",modifier:"bp3-intent-success",buttonModifier:`data-uid="${a}" data-citekey="${t.slice(1)}"`}))}catch(e){}try{var o=Array.from(document.querySelectorAll(`.related-item_listed[data-key="${t}"][in-graph="false"]`));if(0<o.length)for(link of o)link.outerHTML=zoteroRoam.inPage.renderBacklinksItem(paper=e.detail.item,type=link.getAttribute("item-type"),uid=a)}catch(e){}}),document.addEventListener("zotero-roam:update",async function(t){var a=t.detail.data?t.detail.data.items:[];if(0<a.length){for(item of a){var o=zoteroRoam.utils.parseDOI(item.data.DOI),r=Array.from(document.querySelectorAll(".zotero-roam-page-added-on"));if(0<r.length){var i,n=zoteroRoam.utils.makeDNP(item.data.dateAdded,{brackets:!1});for(btn of r)if(btn.getAttribute("data-title")==n){let e=JSON.parse(btn.getAttribute("data-keys"));e.includes(item.key)||(e.includes(item.data.key)?btn.setAttribute("data-keys",JSON.stringify([...e.filter(e=>e!=item.data.key),item.key])):btn.setAttribute("data-keys",JSON.stringify([...e,item.key])),i=JSON.parse(btn.getAttribute("data-keys")).length,btn.querySelector(".bp3-button-text").innerText=i+` item${1==i?"":"s"} added`)}}r=Array.from(document.querySelectorAll(".zotero-roam-page-tagged-with"));if(0<r.length)for(btn of r){var s=btn.getAttribute("data-title");let e=JSON.parse(btn.getAttribute("data-keys"));item.data.tags&&item.data.tags.map(e=>e.tag).includes(s)&&(e.includes(item.key)||(e.includes(item.data.key)?btn.setAttribute("data-keys",JSON.stringify([...e.filter(e=>e!=item.data.key),item.key])):btn.setAttribute("data-keys",JSON.stringify([...e,item.key])),s=JSON.parse(btn.getAttribute("data-keys")).length,btn.querySelector(".bp3-button-text").innerText=s+" tagged item"+(1==s?"":"s")))}r=Array.from(document.querySelectorAll(".zotero-roam-page-abstract-mentions"));if(0<r.length)for(btn of r){var l=btn.getAttribute("data-title");let e=JSON.parse(btn.getAttribute("data-keys"));item.data.abstractNote&&item.data.abstractNote.includes(l)&&(e.includes(item.key)||(e.includes(item.data.key)?btn.setAttribute("data-keys",JSON.stringify([...e.filter(e=>e!=item.data.key),item.key])):btn.setAttribute("data-keys",JSON.stringify([...e,item.key])),l=JSON.parse(btn.getAttribute("data-keys")).length,btn.querySelector(".bp3-button-text").innerText=l+" abstract"+(1==l?"":"s")))}if(o&&zoteroRoam.config.params.pageMenu.defaults.includes("citingPapers"))for(menu of Array.from(document.querySelectorAll(".zotero-roam-page-menu-citations[data-doi]"))){var c=menu.dataset.doi;let e=await zoteroRoam.handlers.getSemantic(c);if(e.data){let r=e.citations.map(e=>zoteroRoam.utils.parseDOI(e.doi)).filter(Boolean);c=e.references.map(e=>zoteroRoam.utils.parseDOI(e.doi)).filter(Boolean);let i=[...r,...c];if(i.includes(o)){let e=zoteroRoam.data.items.filter(e=>zoteroRoam.utils.parseDOI(e.data.DOI)),a=i.map(t=>e.find(e=>zoteroRoam.utils.parseDOI(e.data.DOI)==t)).filter(Boolean),t=(a.forEach((e,t)=>{r.includes(e.data.DOI)?a[t].type="citing":a[t].type="cited"}),menu.querySelector(".zotero-roam-page-menu-backlinks-button")),o=(t.querySelector(".bp3-button-text").innerText=a.length+" related library items",t.classList.remove("bp3-disabled"),menu.querySelector(".zotero-roam-page-menu-backlinks-list"));o?o.innerHTML=""+zoteroRoam.inPage.renderBacklinksList(a):menu.innerHTML+=`
                                              <ul class="zotero-roam-page-menu-backlinks-list bp3-list-unstyled bp3-text-small" style="display:none;">
                                              ${zoteroRoam.inPage.renderBacklinksList(a)}
                                              </ul>
                                              `}}}}let e=document.querySelector('.zotero-roam-dashboard-overlay .zr-tab-panel-popover[overlay-visible="true"]');e&&(e.querySelector(".bp3-dialog-header").innerHTML="",e.querySelector(".bp3-dialog-body").innerHTML="",e.querySelector(".bp3-dialog-footer").innerHTML="",e.style.display="none",e.setAttribute("overlay-visible","hidden"));a=Array.from(new Set(t.detail.requests.map(e=>e.library)));zoteroRoam.utils.refreshTagLists(a)}}),document.addEventListener("zotero-roam:ready",e=>{zoteroRoam.utils.refreshTagLists(),zoteroRoam.utils.updateTagPagination(libPath=Array.from(zoteroRoam.data.libraries.keys())[0])})}},zoteroRoam.smartblocks={commands:{ZOTERORANDOMCITEKEY:{help:"Return one or more Zotero citekeys, with optional tag query",handler:e=>(e="1",t="")=>zoteroRoam.data.items.filter(e=>!["attachment","note","annotation"].includes(e.data.itemType)&&zoteroRoam.smartblocks.processQuery(t,e.data.tags.map(e=>e.tag))).map(e=>e.key).sort(()=>.5-Math.random()).slice(0,Number(e)||1)}},processQuery(e,t){let a=e.split(/([\|\&]?)([^\&\|\(\)]+|\(.+\))([\|\&]?)/).filter(Boolean);return a.includes("|")?zoteroRoam.smartblocks.eval_or(a.filter(e=>"|"!=e),t):zoteroRoam.smartblocks.eval_and(a.filter(e=>"&"!=e),t)},eval_and(t,a){let o=!0;for(let e=0;e<t.length&&1==o;e++)o=zoteroRoam.smartblocks.eval_term(t[e],a);return o},eval_or(t,a){let o=!1;for(let e=0;e<t.length&&0==o;e++)o=zoteroRoam.smartblocks.eval_term(t[e],a);return o},eval_term(e,t){var a;return e.startsWith("(")&&e.endsWith(")")?(a=e.slice(1,-1),zoteroRoam.smartblocks.processQuery(a,t)):e.startsWith("-")?(a=e.slice(1),!t.includes(a)):t.includes(e)},registerCommands(){Object.keys(zoteroRoam.smartblocks.commands).forEach(e=>{var{help:t,handler:a}=zoteroRoam.smartblocks.commands[""+e];window.roamjs?.extension?.smartblocks?.registerCommand({text:e,help:t,handler:a})})},async use_smartblock_metadata(e,t){let a=e;a.targetUid=t.uid,a.variables||(a.variables={}),Object.keys(t).forEach(e=>{a.variables[""+e]=t[""+e]});try{return await window.roamjs.extension.smartblocks.triggerSmartblock(a),{success:!0}}catch(e){return console.log(e),{success:!1}}}};export{zoteroRoam};