-
Notifications
You must be signed in to change notification settings - Fork 1
/
improved-print.min.js
22 lines (20 loc) · 2.58 KB
/
improved-print.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const CSS_SELECTORS={LINKS:`a[href]:not([data-no-improved-print])`,HIDDEN_CLASS:"improved-print--hidden"};class ImprovedPrint extends HTMLElement{static template(){const a=document.createElement("template");return a.innerHTML=`
<style>
:host {
display: inherit;
}
:host([${CSS_SELECTORS.HIDDEN_CLASS}]) {
display: none;
}
:host .${CSS_SELECTORS.HIDDEN_CLASS} {
display: none;
}
@media print {
:host .${CSS_SELECTORS.HIDDEN_CLASS},
:host ::slotted(.${CSS_SELECTORS.HIDDEN_CLASS}) {
display: inherit;
}
}
</style>
<slot></slot>
`,a}static createNavigationalList(){const a=document.createElement("nav");a.classList.add(CSS_SELECTORS.HIDDEN_CLASS);const b=document.createElement("ol");return b.setAttribute("role","list"),a.appendChild(b),{nav:a,list:b}}static createFootnote(b){const c=document.createElement("li"),d=document.createElement("a");return d.href=b,d.textContent=b,c.appendChild(d),c}constructor(){super(),this._shadowRoot=null,this._links=this._getLinks(),this._supElements=null,this._printObserver=window.matchMedia("print"),this._onPrint=this._onPrint.bind(this)}connectedCallback(){this.isConnected&&(this._setup(),this._addEventListeners())}disconnectedCallback(){this.isConnected||this._removeEventListeners()}_addEventListeners(){this._printObserver.addListener(this._onPrint)}_removeEventListeners(){this._printObserver.removeListener(this._onPrint)}_onPrint(a){a.matches?this._supElements.forEach(a=>a.hidden=!1):requestAnimationFrame(()=>{this._supElements.forEach(a=>a.hidden=!0)})}_setup(){const a=ImprovedPrint.template().content;this._shadowRoot=this.attachShadow({mode:"open"}),this._shadowRoot.appendChild(a),this._generateDOM()}_createFootnotes(a,b){b.forEach((b,c)=>{const d=ImprovedPrint.createFootnote(b.href),e=document.createElement("sup");e.textContent=`${c+1}`,e.classList.add(CSS_SELECTORS.HIDDEN_CLASS),e.inert=!0,e.hidden=!0,e.setAttribute("aria-hidden","true"),b.appendChild(e),a.appendChild(d)}),this._supElements=this._getSupElements()}_generateDOM(){if(this.links){const{nav:a,list:b}=ImprovedPrint.createNavigationalList();a.classList.add(CSS_SELECTORS.HIDDEN_CLASS),a.inert=!0,a.setAttribute("aria-hidden","true"),this._createFootnotes(b,this.links),this._shadowRoot.appendChild(a)}}_getLinks(){return this.querySelectorAll(CSS_SELECTORS.LINKS)}_getSupElements(){return this.querySelectorAll(`sup.${CSS_SELECTORS.HIDDEN_CLASS}`)}get links(){return this._links}}window.customElements.define("improved-print",ImprovedPrint);