UNPKG

bibcite

Version:
2 lines (1 loc) 15.1 kB
"use strict";function e(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function t(e,t){switch(e.compareDocumentPosition(t)){case Node.DOCUMENT_POSITION_FOLLOWING:return-1;case Node.DOCUMENT_POSITION_PRECEDING:return 1;default:return 0}}class i{constructor(e){this._length=0,this._used_keys=e}add(e){if(this._used_keys.has(e.key)){const t=this._used_keys.get(e.key);return t.citations.push(e),e.bibIndex=t.index,{need_ref_update:!1}}{this._length+=1;const t={index:this._length,citations:[e]};return this._used_keys.set(e.key,t),e.bibIndex=t.index,{need_ref_update:!0}}}remove(e){const t=this._used_keys.get(e.key).citations;if(t.length<=1)return this._used_keys.delete(e.key),{index:0,need_ref_update:!0};{const i=t.indexOf(e);return t.splice(i,1),{index:i,need_ref_update:!1}}}has(e){return this._used_keys.has(e)}get citations(){return Array.from(this._used_keys.values()).map((e=>e.citations)).flat(1)}get(){return this._used_keys}}class n extends i{constructor(e,t){super(e),this._key_order=t,this.sort_used_keys()}sort_used_keys(){const e=[...this._used_keys].sort((([e,t],[i,n])=>this._key_order.get(e)-this._key_order.get(i)));e.forEach((([e,t],i)=>{t.index=i,t.citations.forEach((e=>e.bibIndex=i))})),this._used_keys=new Map(e)}add(e){const t=super.add(e);return t.need_ref_update&&this.sort_used_keys(),t}remove(e){const t=super.remove(e);return t.need_ref_update&&this.sort_used_keys(),t}}class s extends i{constructor(e){super(e),this._safe_to_append_key=e=>!0,this.sort_used_keys()}sort_used_keys(){this._used_keys.forEach((e=>e.citations.sort(t).at(0)));const e=[...this._used_keys].sort((([e,i],[n,s])=>t(i.citations.at(0),s.citations.at(0))));e.forEach((([e,t],i)=>t.index=i)),this._length=e.length,0==this._length?this._safe_to_append_key=e=>!0:this._safe_to_append_key=i=>t(e.at(-1)[1].citations.at(0),i)<0,this._used_keys=new Map(e),this._used_keys.forEach((e=>e.citations.forEach((t=>t.bibIndex=e.index))))}add(e){const i=super.add(e).need_ref_update;return i&&(this._safe_to_append_key(e)?this._safe_to_append_key=i=>t(e,i)<0:this.sort_used_keys()),{need_ref_update:i}}remove(e){const t=super.remove(e).index;return 0==t&&this.sort_used_keys(),{index:t,need_ref_update:0==t}}}class r{constructor(e,t){this._reference_lists=[],this._bibOrder={comparison:t,inform_citations:!1},this.bib=e,"insertion"===this._bibOrder.comparison.name?this._cite_key_use=new s(new Map):this._bibOrder.inform_citations?this._cite_key_use=new n(new Map,new Map(Array.from(this._bib.keys()).map(((e,t)=>[e,t])))):this._cite_key_use=new i(new Map)}sort_and_hash(e,t){return new Map(e.sort(((e,i)=>t(e,i))).map((e=>[e.id,e])))}set sorting(e){this._bib=this.sort_and_hash(this.bib,e.comparison),"insertion"===e.comparison.name&&"insertion"!=this._bibOrder.comparison.name?this._cite_key_use=new s(this._cite_key_use.get()):e.inform_citations?this._cite_key_use=new n(this._cite_key_use.get(),new Map(Array.from(this._bib.keys()).map(((e,t)=>[e,t])))):this._cite_key_use=new i(this._cite_key_use.get()),this._bibOrder=e}registerCitation(e){if(this._cite_key_use.add(e).need_ref_update)for(const e of this._reference_lists)e.usedReferences=this.used_references();e.bibData=this._bib.get(e.key),console.log(`[Bibliography] Registered ${e.key}`)}unregisterCitation(e){if(this._cite_key_use.remove(e).need_ref_update)for(const e of this._reference_lists)e.usedReferences=this.used_references()}get citations(){return this._cite_key_use.citations}used_references(){return"insertion"===this._bibOrder.comparison.name?Array.from(this._cite_key_use.get()).map((([e,t])=>({index:t.index,csl_data:this._bib.get(e)}))):Array.from(this._bib).filter((([e,t])=>this._cite_key_use.has(e))).map((([e,t],i)=>({index:i,csl_data:t})))}registerReferenceList(e){this._reference_lists.push(e),e.usedReferences=this.used_references(),console.log("[Bibliography] Registered ReferenceList")}unregisterReferenceList(e){this._reference_lists=this._reference_lists.filter((t=>t!=e)),console.log("[Bibliography] Unregistered ReferenceList")}set bib(e){this._bib=this.sort_and_hash(e,this._bibOrder.comparison),console.log("[Bibliography] Sorted & Hashed CSL:",this._bib)}}function o(e){return function(e){switch(e.length){case 0:return"?";case 1:return e.at(0).family.slice(0,3).toUpperCase();default:return e.map((e=>e.family.at(0))).join("").toUpperCase()}}(e.author)+e.issued["date-parts"][0][0].toString().slice(-2)}function a(e){const t=e.map((e=>e["non-dropping-particle"]||" "+e.family));return t[0]+(t.length>1?" et al.":"")}function c(e,t){return`<tr style="vertical-align:top">\n <td>[${t}]</td>\n <td>${e}</td>\n </tr>\n `}function d(e){return`<strong>${e.title}</strong> ${function(e){if(e.DOI)return`<a href="https://doi.org/${e.DOI}">[DOI]</a>`;if(e.URL)return`<a href="${e.URL}>[${function(e){if(e.endsWith("pdf"))return"PDF";if(e.includes("arxiv"))return"ARXIV";if(e.endsWith("html"))return"HTML";if(e.match("doi.org/(.+)$"))return"DOI";return"link"}(e.URL)}]</a>`;return""}(e)}\n <br>\n <span>${_(e.author)}</span>\n <span>(${l(e.issued["date-parts"][0])})</span>\n <br>\n <span>${u(e)}\n `}function l(e){return e.map((e=>String(e))).join("-")}function h(e){return`<h2>References</h2>\n <table>\n ${e}\n </table>\n `}function _(e){if(!e)return"";if(1==e.length)return f(e.at(0));let t=e.map((e=>f(e)));return[t.slice(0,-1).join(", "),t.at(-1)].join(" and ")}function u(e){let t="";if(e["container-title"]){let i=[];e.volume&&i.push(`Volume: ${e.volume}`),e.issue&&i.push(`Issue: ${e.issue}`),e.locator&&console.log("locator"),t+="In: "+e["container-title"]+(i.length?" ["+i.join(", ")+"]":"")+"\n"}var i;return e["collection-title"]&&(t+="In: "+e["collection-title"]+"\n"),e.DOI?t+=`DOI: <a href="https://doi.org/${e.DOI}">${e.DOI}</a>\n`:e.ISBN?t+=`ISBN: ${e.ISBN}\n`:e.URL&&(t+=`URL: <a href="${e.URL}>${i=e.URL,i.replace(/^[a-z]+:\/\//i,"")}</a>`,t+=e.accessed?`(last accessed: ${e.accessed["date-parts"][0].map((e=>String(e))).join("-")})`:"",t+="\n"),t.trim().replace("\n","<br>")}function f(e){return(e.given?e.given+" ":"")+(e["non-dropping-particle"]?e["non-dropping-particle"]+" ":"")+(e["dropping-particle"]?e["dropping-particle"]+" ":"")+(e.family?e.family:"")+(e.suffix?" "+e.suffix:"").trim()||e.literal}const b={name:"alphabetic",order:{comparison:(e,t)=>o(e).localeCompare(o(t)),inform_citations:!1},identifier:o,enclosing:["[","]"],multiSeparator:";",bib_entry:d,metaBibEntry:c,metaReference:h};const p={name:"author-year",order:{comparison:function(e,t){const i=e.author[0],n=t.author[0];let s=i.family.localeCompare(n.family);return 0!=s?s:(s=i.given.localeCompare(n.given),0!=s?s:(s=e.issued["date-parts"][0]-t.issued["date-parts"][0],0!=s?s:e.title.localeCompare(t.title)))},inform_citations:!1},identifier:(e,t,i)=>{const n=String(e.issued["date-parts"][0][0]);return"text-cite"===i?n:a(e.author)+n},enclosing:["(",")"],multiSeparator:";",bib_entry:function(e){return`\n <span>${_(e.author)}</span>\n <span>(${l(e.issued["date-parts"][0])}).</span>\n `+u(e)},metaBibEntry:function(e){return`<p>${e}</p>`},metaReference:e=>`<h2>References</h2>${e}`},y={name:"numeric",order:{comparison:function(e,t){return 0},inform_citations:!0},enclosing:["[","]"],multiSeparator:",",identifier:(e,t)=>String(t),bib_entry:d,metaBibEntry:c,metaReference:h};let g=new Map;const m=b;function k(e){g.set(e.name,e)}k(y),k(b),k(p);class C extends HTMLElement{constructor(){super(),this.listeners={CitationAdded(t){return e(this,void 0,void 0,(function*(){console.log("[BibController] caught CitationAdded event");const e=yield this.bibliography,i=t.detail.element;i.myController=this,t.stopImmediatePropagation(),i.citeStyle=this.citeStyle,e.registerCitation(t.detail.element)}))},CitationRemoved(t){return e(this,void 0,void 0,(function*(){console.log("[BibController] caught CitationRemoved event");(yield this.bibliography).unregisterCitation(t.detail.element)}))},ReferenceAdded(t){return e(this,void 0,void 0,(function*(){console.log("[BibController] caught ReferenceAdded event");const e=yield this.bibliography,i=t.detail.element;i.myController=this,t.stopImmediatePropagation(),i.citeStyle=this.citeStyle,e.registerReferenceList(t.detail.element)}))},ReferenceRemoved(t){return e(this,void 0,void 0,(function*(){console.log("[BibController] caught ReferenceRemoved event");(yield this.bibliography).unregisterReferenceList(t.detail.element)}))}}}connectedCallback(){console.log("[BibController] connectedCallback"),this._scope=this.parentElement===document.head?document:this.parentElement;for(const[e,t]of Object.entries(this.listeners))console.log(`|- addEventListener: ${e}`),this._scope.addEventListener(e,t.bind(this))}disconnectedCallback(){console.log("[BibController] disconnectedCallback");for(const[e,t]of Object.entries(this.listeners))console.log(`removeEventListener: ${e}`),this._scope.removeEventListener(e,t.bind(this))}static get observedAttributes(){return["bib","citation-style"]}attributeChangedCallback(t,i,n){return e(this,void 0,void 0,(function*(){switch(console.log(`[BibController] attributeChangedCallback(${t}, ${i}, ${n})`),t){case"bib":this._bibliography?(yield this.bibliography).bib=yield this.csl_from_attribute(n):this.bibliography;break;case"citation-style":this.citeStyle=g.get(n)||m;break;default:console.error(`[BibController] attributeChangedCallback(${t}, ${i}, ${n})called with unknown attribute ${t}`)}}))}set innerHTML(e){console.log("[BibController] set innerHTML"),super.innerHTML=e,this.getAttribute("bib")||this.bibliography.then((t=>t.bib=JSON.parse(e)))}propagateCiteStyle(t){return e(this,void 0,void 0,(function*(){const e=yield this.bibliography;e.citations.forEach((e=>e.citeStyle=t)),e._reference_lists.forEach((e=>e.citeStyle=t))}))}set citeStyle(e){this._citeStyle=e,this.propagateCiteStyle(e)}get citeStyle(){return this._citeStyle||(this._citeStyle=g.get(this.getAttribute("citation-style"))||m),this._citeStyle}get bibliography(){return this._bibliography||(this._bibliography=this.csl_from_attribute(this.getAttribute("bib")).then((e=>new r(e,this.citeStyle.order.comparison)))),this._bibliography}csl_from_attribute(t){return e(this,void 0,void 0,(function*(){if(t){console.log("|- bib attribute present -> fetching");const e=yield fetch(t);return yield e.json()}return"loading"==document.readyState?(console.log("|- bib attribute missing -> waiting for innerHTML"),new Promise(((e,t)=>{document.addEventListener("DOMContentLoaded",(()=>e(this.innerHTML)))})).then(JSON.parse)):(console.log("|- bib attribute missing -> using innerHTML"),JSON.parse(this.innerHTML))}))}}const v=["text-cite","raw-cite","paren-cite"];function S(e){return t=e,v.includes(t)?e:(void 0===e?console.log('Missing Citation type, fallback to "paren-cite"'):console.error(`[Citation] Unknown Citation type ${e}, fallback to "paren-cite"`),"paren-cite");var t}function R(e){return 8==e.nodeType||3==e.nodeType&&function(e){return!/[^\t\n\r ]/.test(e.textContent)}(e)}function x(e){return(null==e?void 0:e.nodeType)===Node.ELEMENT_NODE}function E(e){const t=function(e){for(;e=e.previousSibling;)if(!R(e))return e;return null}(e);return x(t)&&t.tagName===e.tagName?t:null}function $(e){const t=function(e){for(;e=e.nextSibling;)if(!R(e))return e;return null}(e);return x(t)&&t.tagName===e.tagName?t:null}class w extends HTMLElement{constructor(){super()}set myController(e){this._myController=e}set bibIndex(e){this._bibIndex=e,this.sufficient_information()&&this.render()}set citeStyle(e){this._citeStyle=e,this.sufficient_information()&&this.render()}set bibData(e){this._bibData=e,this.sufficient_information()&&this.render()}sufficient_information(){return Boolean(this._citeStyle)&&Boolean(this._bibData)&&(Boolean(this._bibIndex)||!this._citeStyle.order.inform_citations)}get key(){return this.getAttribute("key")}get citeType(){return this._citeType||(this.citeType=this.getAttribute("type")),this._citeType}set citeType(e){this._citeType=S(e)}render_text_cite(){return`<a href=#${this.key}>`+a(this._bibData.author)+" "+this._citeStyle.enclosing[0]+this._citeStyle.identifier(this._bibData,this._bibIndex,this.citeType)+this._citeStyle.enclosing[1]+"</a>"}render_raw_cite(){return`<a href=#${this.key}>`+this._citeStyle.identifier(this._bibData,this._bibIndex,this.citeType)+"</a>"}render_paren_cite(){const e=this._adjBefore?"":this._citeStyle.enclosing[0],t=this._adjAfter?this._citeStyle.multiSeparator:this._citeStyle.enclosing[1];return e+this.render_raw_cite()+t}render(){this.innerHTML=this.pre_render()}pre_render(){switch(this.citeType){case"text-cite":return this.render_text_cite();case"raw-cite":return this.render_raw_cite();case"paren-cite":return this.render_paren_cite()}}set adjBefore(e){this._adjBefore=e,this.sufficient_information()&&this.render()}set adjAfter(e){this._adjAfter=e,this.sufficient_information()&&this.render()}connectedCallback(){this.adjBefore=E(this),this.adjAfter=$(this),this._adjBefore&&(this._adjBefore.adjAfter=this),this._adjAfter&&(this._adjAfter.adjBefore=this),this.key&&this.triggerCitationAdded(),this._connected=!0}disconnectedCallback(){this.key&&this.triggerCitationRemoved(),this._connected=!1,this._adjBefore&&(this._adjBefore.adjAfter=this._adjAfter),this._adjAfter&&(this._adjAfter.adjBefore=this._adjBefore)}triggerCitationAdded(){const e=new CustomEvent("CitationAdded",{bubbles:!0,detail:{element:this}});this.dispatchEvent(e)}triggerCitationRemoved(){const e=new CustomEvent("CitationRemoved",{bubbles:!1,detail:{element:this}});this._myController.dispatchEvent(e),this._bibIndex=void 0,this.removeAttribute("id")}static get observedAttributes(){return["key","type"]}attributeChangedCallback(e,t,i){console.log(`[Citation] attributeChangedCallback(${e}, ${t}, ${i})`),"key"===e?(t&&this.triggerCitationRemoved(),this._connected&&i&&this.triggerCitationAdded()):"type"===e&&(this.citeType=i,this.sufficient_information()&&this.render())}}class L extends HTMLElement{set myController(e){this._myController=e}connectedCallback(){const e=new CustomEvent("ReferenceAdded",{bubbles:!0,detail:{element:this}});this.dispatchEvent(e)}disconnectedCallback(){const e=new CustomEvent("ReferenceRemoved",{bubbles:!1,detail:{element:this}});this._myController.dispatchEvent(e)}set citeStyle(e){console.log("[Reference] set citeStyle"),this._citeStyle=e,this._usedReferences&&this.render()}render(){console.log("[Reference] rendering"),this.innerHTML=this._citeStyle.metaReference(this._usedReferences.map((e=>this._citeStyle.metaBibEntry(this._citeStyle.bib_entry(e.csl_data),this._citeStyle.identifier(e.csl_data,e.index,"raw-cite")))).join(""))}set usedReferences(e){console.log("[Reference] set usedReferences",e),this._usedReferences=e,this._citeStyle&&this.render()}}customElements.define("bib-config",C),customElements.define("bib-cite",w),customElements.define("bib-references",L);