diff --git a/main.js b/main.js index c523745..1570a27 100644 --- a/main.js +++ b/main.js @@ -227,7 +227,7 @@ end`},tu=function(){for(var t=[],e=0;e1||o.length===1&&n)&&this.enableMultiselect();for(var s=new Array(o.length),f=0,l=o.length;f1||o.length===1&&n)&&this.enableMultiselect();for(var a=new Array(o.length),s=0,f=o.length;sn)throw new Ju(r.length,n,this.getName());this.markAsDirty(),this.disableRichFormatting(),r?this.acroField.setValue(j.fromText(r)):this.acroField.removeValue()},e.prototype.getAlignment=function(){var r=this.acroField.getQuadding();return r===0?De.Left:r===1?De.Center:r===2?De.Right:De.Left},e.prototype.setAlignment=function(r){bt(r,"alignment",De),this.markAsDirty(),this.acroField.setQuadding(r)},e.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},e.prototype.setMaxLength=function(r){if(it(r,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),r===void 0)this.acroField.removeMaxLength();else{var n=this.getText();if(n&&n.length>r)throw new Qu(n.length,r,this.getName());this.acroField.setMaxLength(r)}},e.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},e.prototype.setImage=function(r){for(var n=this.getAlignment(),o=n===De.Center?wt.Center:n===De.Right?wt.Right:wt.Left,i=this.acroField.getWidgets(),a=0,s=i.length;aDm([...t,n],e)<=r-Pm}function km(t){let e=activeDocument.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(;e.nextNode();){let r=e.currentNode,n=(r.textContent??"").replace(/^\s+/,"");if(n!==r.textContent&&(r.textContent=n),n.length>0)break}}function Zo(t,e,r=!0){let n=activeDocument.createTreeWalker(t,NodeFilter.SHOW_TEXT),o=0,i=null,a=0;for(;n.nextNode();){let u=n.currentNode,d=u.textContent?.length??0;if(o+d>=e){i=u,a=e-o;break}o+=d}if(!i)return null;let s=activeDocument.createRange();s.selectNodeContents(t),s.setEnd(i,a);let f=activeDocument.createRange();f.selectNodeContents(t),f.setStart(i,a);let l=t.cloneNode(!1);l.appendChild(s.cloneContents());let c=t.cloneNode(!1);return c.appendChild(f.cloneContents()),r&&km(c),[l,c]}function Tm(t){let e=[],r=/\s+/g,n;for(;n=r.exec(t);)n.index>0&&n.index0){let f=0,l=o.length-1,c=-1;for(;f<=l;){let u=Math.floor((f+l)/2),d=Zo(t,o[u]);if(!d){l=u-1;continue}e(d[0])?(c=u,f=u+1):l=u-1}if(c>=0)return Zo(t,o[c]);if(!r)return null}let i=1,a=n.length-1,s=0;for(;i<=a;){let f=Math.floor((i+a)/2),l=Zo(t,f);if(!l){a=f-1;continue}e(l[0])?(s=f,i=f+1):a=f-1}return s>0?Zo(t,s):null}function Ms(t,e,r){let n=t.cloneNode(!1);t.tagName==="OL"&&r!==void 0&&r>1&&(n.start=r);for(let o of e)n.appendChild(o.cloneNode(!0));return n}function Am(t,e,r){let n=Array.from(t.children).filter(a=>a.tagName==="LI");if(n.length===0)return null;let o=t.tagName==="OL"?t.start??1:1,i=0;for(let a=0;a=n.length?null:[Ms(t,n.slice(0,i),o),Ms(t,n.slice(i),o+i)]}function Is(t,e){let r=t.cloneNode(!1),n=t.querySelector("caption");n&&r.appendChild(n.cloneNode(!0));let o=t.querySelector("colgroup");o&&r.appendChild(o.cloneNode(!0)),t.tHead&&r.appendChild(t.tHead.cloneNode(!0));let i=activeDocument.createElement("tbody");for(let a of e)i.appendChild(a.cloneNode(!0));return r.appendChild(i),r}function Rm(t,e,r){let n=t.tBodies[0],o=n?Array.from(n.rows):Array.from(t.rows).filter(a=>a.parentElement?.tagName!=="THEAD");if(o.length===0)return null;let i=0;for(let a=0;a=o.length?null:[Is(t,o.slice(0,i)),Is(t,o.slice(i))]}function Om(t){let e=[],r=0;for(let n of t)r+=n.length+1,e.push(r);return e}function Bm(t,e,r){let n=t.querySelector("code"),o=(n??t).textContent?.split(` `)??[];if(o.length>1&&o[o.length-1]===""&&o.pop(),o.length<2)return null;let i=Om(o),a=l=>{if(!n){let p=h=>{let b=t.cloneNode(!1);return b.textContent=h,b};return[p(o.slice(0,l).join(` `)),p(o.slice(l).join(` -`))]}let c=Zo(n,i[l-1],!1);if(!c)return null;let u=t.cloneNode(!1);u.appendChild(c[0]);let d=t.cloneNode(!1);return d.appendChild(c[1]),[u,d]},s=null,f=0;for(let l=1;l<=o.length;l++){let c=a(l);if(!c||!e(c[0]))break;s=c,f=l}if(f<=0){if(!r)return null;s=a(1),f=1}return f>=o.length||!s?null:s}function Nm(t){if(!Fm.has(t.tagName))return!1;for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE&&wm.has(e.tagName))return!1;return!0}function Mm(t,e,r){return Sm.has(t.tagName)?null:t.tagName==="PRE"?Bm(t,e,r):t.tagName==="TABLE"?Rm(t,e,r):t.tagName==="UL"||t.tagName==="OL"?Am(t,e,r):Nm(t)?Em(t,e,r):null}function ud(t,e,r,n){let o=activeDocument.createElement("div");o.setCssStyles({position:"fixed",top:"0",left:"-99999px",width:`${e}px`,visibility:"hidden",pointerEvents:"none",zIndex:"-1"});let i=o.attachShadow({mode:"open"}),a=new CSSStyleSheet;a.replaceSync(n),i.adoptedStyleSheets=[a];let s=activeDocument.createElement("div");s.className="mpdf-doc";for(let c of Array.from(t.children))s.appendChild(c.cloneNode(!0));i.appendChild(s);let f=activeDocument.createElement("div");f.className="mpdf-doc",f.setCssStyles({position:"absolute",top:"0",left:"0",width:`${e}px`,visibility:"hidden"}),i.appendChild(f),activeDocument.body.appendChild(o);let l=[];try{let c=[],u=Array.from(s.children),d=0;for(;d0?u[d]=x:d++;continue}if(c.length>0){l.push(c),c=[];continue}c.push(p.cloneNode(!0)),l.push(c),c=[],d++}c.length>0&&l.push(c)}finally{activeDocument.body.removeChild(o)}return l.length>0?l:[[]]}function Im(t,e,r){return(t&&t.trim()?t:"{{current}} / {{total}}").replace(/\{\{\s*current\s*\}\}/g,String(e)).replace(/\{\{\s*total\s*\}\}/g,String(r))}function dd(t,e){let r=t.length;return t.map((n,o)=>{let i=o+1,a=e.showHeaderOnFirstPage||o>0,s=e.showFooterOnFirstPage||o>0,f=e.showFooterOnFirstPage?e.pageNumberStart+o:e.pageNumberStart+(o-1),l=e.showFooterOnFirstPage?e.pageNumberStart+r-1:e.pageNumberStart+r-2,c=Im(e.pageNumberFormat,f,l),u="",d="",p="",h="",b="",F="";if(s&&(e.footerText&&(e.footerTextAlignment==="center"?p=e.footerText:e.footerTextAlignment==="left"?u=e.footerText:d=e.footerText),e.showPageNumbers)){let y=w=>w?w+" \u2014 "+c:c;e.pageNumberPosition==="center"?p=y(p):e.pageNumberPosition==="left"?u=y(u):d=y(d)}a&&e.headerText&&(e.headerAlignment==="center"?b=e.headerText:e.headerAlignment==="left"?h=e.headerText:F=e.headerText);let x=e.showHeader&&a&&!!(h||b||F||e.showHeaderBorder),m=e.showFooter&&s&&!!(u||d||p||e.showFooterBorder);return{pageNodes:n,pageNum:i,totalPages:r,pageShowsHeader:a,pageShowsFooter:s,hasHeader:x,hasFooter:m,headerLeft:h,headerCenter:b,headerRight:F,footerLeft:u,footerRight:d,footerCenter:p}})}function hd(t){let e=[];for(let r of t)for(let n of r.pageNodes){let o=/^H[1-6]$/.test(n.tagName)?[n]:[],i=Array.from(n.querySelectorAll("h1,h2,h3,h4,h5,h6"));for(let a of[...o,...i]){let s=parseInt(a.tagName[1],10),f=(a.textContent??"").trim();f&&e.push({title:f,level:s,page:r.pageNum})}}return e}async function pd(t,e){if(!e.length)return t;let r=await Ke.load(t),n=r.getPages(),o=r.context,i=e.length,a=new Array(i).fill(-1);for(let m=1;m=0;y--)if(e[y].level=0;y--)if(a[y]===a[m]){s[m]=y;break}for(let y=m+1;y=0&&(l[y]<0&&(l[y]=m),c[y]=m,u[y]++)}let d=o.nextRef(),p=e.map(()=>o.nextRef());for(let m=0;m=0?p[a[m]]:d),S.set(v.of("Dest"),w),s[m]>=0&&S.set(v.of("Prev"),p[s[m]]),f[m]>=0&&S.set(v.of("Next"),p[f[m]]),l[m]>=0&&(S.set(v.of("First"),p[l[m]]),S.set(v.of("Last"),p[c[m]]),S.set(v.of("Count"),z.of(-u[m]))),o.assign(p[m],S)}let h=-1,b=-1,F=0;for(let m=0;m`}function vd(t,e,r,n){if(!(!e&&!r&&!n))if(e){let o=activeDocument.createElement("span");o.className="mpdf-hf-center",o.textContent=e,t.appendChild(o)}else{let o=activeDocument.createElement("span");o.textContent=r,t.appendChild(o);let i=activeDocument.createElement("span");i.className="mpdf-hf-right",i.textContent=n,t.appendChild(i)}}function md(t,e,r){return!t&&!e&&!r?"":t?`${Mn(t)}`:`${Mn(e)}${Mn(r)}`}function jm(t,e){if(e)return e;let r=t.workspace.getActiveFile();if(r?.extension==="md")return r;let n=t.workspace.getMostRecentLeaf();return n?.view instanceof ze.MarkdownView?n.view.file??null:null}var Ji=class t extends ze.Modal{plugin;editorEl;previewEl;pageCountEl;noteTitleEl;renderBtn;exportBtn;loadingOverlayEl;renderComponent=new ze.Component;initialFile;currentFile=null;renderToken=0;layoutCache=null;renderDebounceTimer=null;constructor(e,r,n){super(e),this.plugin=r,this.initialFile=n??null}async onOpen(){this.plugin.activeModal=this,this.renderComponent.load(),this.modalEl.addClass("mpdf-modal"),this.buildUI(this.contentEl);let e=jm(this.app,this.initialFile);if(e){let r;try{r=await this.app.vault.read(e)}catch(n){let o=n instanceof Error?n.message:String(n);new ze.Notice(`Failed to read file "${e.basename}": ${o}`);return}if(!this.plugin.activeModal)return;this.currentFile=e,this.editorEl.value=r,this.noteTitleEl.textContent=e.basename,this.noteTitleEl.title=e.path,this.render(!0)}}onClose(){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.renderComponent.unload(),this.plugin.activeModal=null,this.currentFile=null,this.layoutCache=null}buildUI(e){let r=this.plugin.settings;this.buildTopbar(e.createEl("div",{cls:"mpdf-topbar"}),r);let n=e.createEl("div",{cls:"mpdf-main"}),o=n.createEl("div",{cls:"mpdf-editor-panel"});this.editorEl=o.createEl("textarea",{cls:"mpdf-editor"}),this.editorEl.placeholder=`Type or paste markdown here to preview and export as PDF. +`))]}let c=Zo(n,i[l-1],!1);if(!c)return null;let u=t.cloneNode(!1);u.appendChild(c[0]);let d=t.cloneNode(!1);return d.appendChild(c[1]),[u,d]},s=null,f=0;for(let l=1;l<=o.length;l++){let c=a(l);if(!c||!e(c[0]))break;s=c,f=l}if(f<=0){if(!r)return null;s=a(1),f=1}return f>=o.length||!s?null:s}function Nm(t){if(!Fm.has(t.tagName))return!1;for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE&&wm.has(e.tagName))return!1;return!0}function Mm(t,e,r){return Sm.has(t.tagName)?null:t.tagName==="PRE"?Bm(t,e,r):t.tagName==="TABLE"?Rm(t,e,r):t.tagName==="UL"||t.tagName==="OL"?Am(t,e,r):Nm(t)?Em(t,e,r):null}function ud(t,e,r,n){let o=activeDocument.createElement("div");o.setCssStyles({position:"fixed",top:"0",left:"-99999px",width:`${e}px`,visibility:"hidden",pointerEvents:"none",zIndex:"-1"});let i=o.attachShadow({mode:"open"}),a=new activeWindow.CSSStyleSheet;a.replaceSync(n),i.adoptedStyleSheets=[a];let s=activeDocument.createElement("div");s.className="mpdf-doc";for(let c of Array.from(t.children))s.appendChild(c.cloneNode(!0));i.appendChild(s);let f=activeDocument.createElement("div");f.className="mpdf-doc",f.setCssStyles({position:"absolute",top:"0",left:"0",width:`${e}px`,visibility:"hidden"}),i.appendChild(f),activeDocument.body.appendChild(o);let l=[];try{let c=[],u=Array.from(s.children),d=0;for(;d0?u[d]=x:d++;continue}if(c.length>0){l.push(c),c=[];continue}c.push(p.cloneNode(!0)),l.push(c),c=[],d++}c.length>0&&l.push(c)}finally{activeDocument.body.removeChild(o)}return l.length>0?l:[[]]}function Im(t,e,r){return(t&&t.trim()?t:"{{current}} / {{total}}").replace(/\{\{\s*current\s*\}\}/g,String(e)).replace(/\{\{\s*total\s*\}\}/g,String(r))}function dd(t,e){let r=t.length;return t.map((n,o)=>{let i=o+1,a=e.showHeaderOnFirstPage||o>0,s=e.showFooterOnFirstPage||o>0,f=e.showFooterOnFirstPage?e.pageNumberStart+o:e.pageNumberStart+(o-1),l=e.showFooterOnFirstPage?e.pageNumberStart+r-1:e.pageNumberStart+r-2,c=Im(e.pageNumberFormat,f,l),u="",d="",p="",h="",b="",F="";if(s&&(e.footerText&&(e.footerTextAlignment==="center"?p=e.footerText:e.footerTextAlignment==="left"?u=e.footerText:d=e.footerText),e.showPageNumbers)){let y=w=>w?w+" \u2014 "+c:c;e.pageNumberPosition==="center"?p=y(p):e.pageNumberPosition==="left"?u=y(u):d=y(d)}a&&e.headerText&&(e.headerAlignment==="center"?b=e.headerText:e.headerAlignment==="left"?h=e.headerText:F=e.headerText);let x=e.showHeader&&a&&!!(h||b||F||e.showHeaderBorder),m=e.showFooter&&s&&!!(u||d||p||e.showFooterBorder);return{pageNodes:n,pageNum:i,totalPages:r,pageShowsHeader:a,pageShowsFooter:s,hasHeader:x,hasFooter:m,headerLeft:h,headerCenter:b,headerRight:F,footerLeft:u,footerRight:d,footerCenter:p}})}function hd(t){let e=[];for(let r of t)for(let n of r.pageNodes){let o=/^H[1-6]$/.test(n.tagName)?[n]:[],i=Array.from(n.querySelectorAll("h1,h2,h3,h4,h5,h6"));for(let a of[...o,...i]){let s=parseInt(a.tagName[1],10),f=(a.textContent??"").trim();f&&e.push({title:f,level:s,page:r.pageNum})}}return e}async function pd(t,e){if(!e.length)return t;let r=await Ke.load(t),n=r.getPages(),o=r.context,i=e.length,a=new Array(i).fill(-1);for(let m=1;m=0;y--)if(e[y].level=0;y--)if(a[y]===a[m]){s[m]=y;break}for(let y=m+1;y=0&&(l[y]<0&&(l[y]=m),c[y]=m,u[y]++)}let d=o.nextRef(),p=e.map(()=>o.nextRef());for(let m=0;m=0?p[a[m]]:d),S.set(v.of("Dest"),w),s[m]>=0&&S.set(v.of("Prev"),p[s[m]]),f[m]>=0&&S.set(v.of("Next"),p[f[m]]),l[m]>=0&&(S.set(v.of("First"),p[l[m]]),S.set(v.of("Last"),p[c[m]]),S.set(v.of("Count"),z.of(-u[m]))),o.assign(p[m],S)}let h=-1,b=-1,F=0;for(let m=0;m`}function vd(t,e,r,n){if(!(!e&&!r&&!n))if(e){let o=activeDocument.createElement("span");o.className="mpdf-hf-center",o.textContent=e,t.appendChild(o)}else{let o=activeDocument.createElement("span");o.textContent=r,t.appendChild(o);let i=activeDocument.createElement("span");i.className="mpdf-hf-right",i.textContent=n,t.appendChild(i)}}function md(t,e,r){return!t&&!e&&!r?"":t?`${Mn(t)}`:`${Mn(e)}${Mn(r)}`}function jm(t,e){if(e)return e;let r=t.workspace.getActiveFile();if(r?.extension==="md")return r;let n=t.workspace.getMostRecentLeaf();return n?.view instanceof ze.MarkdownView?n.view.file??null:null}var Ji=class t extends ze.Modal{plugin;editorEl;previewEl;pageCountEl;noteTitleEl;renderBtn;exportBtn;loadingOverlayEl;renderComponent=new ze.Component;initialFile;currentFile=null;renderToken=0;layoutCache=null;renderDebounceTimer=null;constructor(e,r,n){super(e),this.plugin=r,this.initialFile=n??null}async onOpen(){this.plugin.activeModal=this,this.renderComponent.load(),this.modalEl.addClass("mpdf-modal"),this.buildUI(this.contentEl);let e=jm(this.app,this.initialFile);if(e){let r;try{r=await this.app.vault.read(e)}catch(n){let o=n instanceof Error?n.message:String(n);new ze.Notice(`Failed to read file "${e.basename}": ${o}`);return}if(!this.plugin.activeModal)return;this.currentFile=e,this.editorEl.value=r,this.noteTitleEl.textContent=e.basename,this.noteTitleEl.title=e.path,this.render(!0)}}onClose(){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.renderComponent.unload(),this.plugin.activeModal=null,this.currentFile=null,this.layoutCache=null}buildUI(e){let r=this.plugin.settings;this.buildTopbar(e.createEl("div",{cls:"mpdf-topbar"}),r);let n=e.createEl("div",{cls:"mpdf-main"}),o=n.createEl("div",{cls:"mpdf-editor-panel"});this.editorEl=o.createEl("textarea",{cls:"mpdf-editor"}),this.editorEl.placeholder=`Type or paste markdown here to preview and export as PDF. Tip: open this panel from a note's right-click menu, command palette, or keyboard shortcut to auto-load the active note. @@ -246,7 +246,7 @@ Markdown tables: |-------|-------| | Cell | Cell |`;let i=n.createEl("div",{cls:"mpdf-preview-container"});this.previewEl=i.createEl("div",{cls:"mpdf-preview"}),this.loadingOverlayEl=i.createEl("div",{cls:"mpdf-loading-overlay"}),this.loadingOverlayEl.createEl("div",{cls:"mpdf-spinner"}),this.loadingOverlayEl.createEl("span",{cls:"mpdf-loading-text",text:"Rendering\u2026"}),this.editorEl.addEventListener("keydown",a=>{a.key==="Enter"&&(a.ctrlKey||a.metaKey)&&(a.preventDefault(),this.render(!0))})}buildTopbar(e,r){let n=e.createEl("div",{cls:"mpdf-topbar-left"}),o=e.createEl("div",{cls:"mpdf-topbar-right"}),i=(w,S,D,T)=>{let C=n.createEl("div",{cls:"mpdf-ctrl"});C.createEl("span",{cls:"mpdf-ctrl-label",text:w});let E=C.createEl("select",{cls:"mpdf-select"});for(let[M,A]of Object.entries(S)){let R=E.createEl("option",{text:A,value:M});M===D&&(R.selected=!0)}E.addEventListener("change",()=>void T(E.value))},a={};Object.entries(It).forEach(([w,S])=>a[w]=S.name),i("Style",a,r.preset,async w=>{this.plugin.applyPreset(w),await this.plugin.saveSettingsAndRender()});let s={};Object.keys(mr).forEach(w=>s[w]=w),s.Custom="Custom";let f=n.createEl("div",{cls:"mpdf-ctrl"});f.createEl("span",{cls:"mpdf-ctrl-label",text:"Size"});let l=f.createEl("select",{cls:"mpdf-select"});for(let[w,S]of Object.entries(s)){let D=l.createEl("option",{text:S,value:w});w===r.pageSize&&(D.selected=!0)}let c=n.createEl("div",{cls:"mpdf-ctrl"});c.toggleClass("mpdf-is-hidden",r.pageSize!=="Custom");let u=(w,S)=>{c.createEl("span",{cls:"mpdf-ctrl-label",text:w});let D=c.createEl("input",{cls:"mpdf-custom-size-input"});return D.type="number",D.min="10",D.step="1",D.value=String(S),D},d=u("W",r.customPageWidth),p=u("H",r.customPageHeight);c.createEl("span",{cls:"mpdf-ctrl-label",text:"mm"}),l.addEventListener("change",()=>{this.plugin.settings.pageSize=l.value,c.toggleClass("mpdf-is-hidden",l.value!=="Custom"),this.plugin.saveSettingsAndRender()});let h=async()=>{this.plugin.settings.customPageWidth=Math.max(10,parseFloat(d.value)||210),this.plugin.settings.customPageHeight=Math.max(10,parseFloat(p.value)||297),await this.plugin.saveSettingsAndRender()};d.addEventListener("change",()=>void h()),p.addEventListener("change",()=>void h()),i("",{portrait:"Portrait",landscape:"Landscape"},r.orientation,async w=>{this.plugin.settings.orientation=w,await this.plugin.saveSettingsAndRender()});let b=n.createEl("div",{cls:"mpdf-ctrl"});b.createEl("span",{cls:"mpdf-ctrl-label",text:"Zoom"});let F=b.createEl("span",{cls:"mpdf-ctrl-label",text:Math.round(r.previewScale*100)+"%"}),x=b.createEl("input");x.type="range",x.min="0.35",x.max="1.0",x.step="0.05",x.value=String(r.previewScale),x.addClass("mpdf-zoom-slider"),x.addEventListener("input",()=>{let w=parseFloat(x.value);this.plugin.settings.previewScale=w,F.textContent=Math.round(w*100)+"%",this.plugin.saveSettings().then(()=>{this.renderPreviewOnly()})});let m=n.createEl("button",{cls:"mpdf-btn",text:"Insert Page Break"});m.title="Insert page break (///)",m.addEventListener("click",()=>this.insertAtCursor(` /// -`)),this.noteTitleEl=n.createEl("div",{cls:"mpdf-topbar-title",text:"\u2014"}),this.pageCountEl=o.createEl("span",{cls:"mpdf-page-count",text:"\u2014 pages"});let y=o.createEl("button",{cls:"mpdf-btn mpdf-btn-icon"});y.setAttr("aria-label","Open Advanced PDF Export settings"),(0,ze.setIcon)(y,"settings"),y.addEventListener("click",()=>{let w=this.app.setting;w?.open?.(),w?.openTabById?.("advanced-pdf-export")}),this.renderBtn=o.createEl("button",{cls:"mpdf-btn",text:"\u27F3 Render PDF"}),this.renderBtn.title="Render preview (Ctrl+Enter)",this.renderBtn.addEventListener("click",()=>this.render(!0)),this.exportBtn=o.createEl("button",{cls:"mpdf-btn mpdf-btn-primary",text:"\u2B07 Export PDF"}),this.exportBtn.addEventListener("click",()=>void this.exportPDF())}insertAtCursor(e){let r=this.editorEl,n=r.selectionStart,o=r.selectionEnd;r.value=r.value.slice(0,n)+e+r.value.slice(o),r.selectionStart=r.selectionEnd=n+e.length,r.focus()}render(e=!1){let r=++this.renderToken;this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.showLoading();let n=()=>this.doRender(r).catch(o=>{let i=o instanceof Error?o.message:String(o);console.error("[advanced-pdf-export] render error:",o),this.hideLoading(),new ze.Notice("Advanced PDF Export \u2014 render failed: "+i)});e?window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>void n())):this.renderDebounceTimer=window.setTimeout(()=>{this.renderDebounceTimer=null,window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>void n()))},150)}static insertAutoBreaks(e,r,n){if(!r&&!n)return e;let o=e.split(` +`)),this.noteTitleEl=n.createEl("div",{cls:"mpdf-topbar-title",text:"\u2014"}),this.pageCountEl=o.createEl("span",{cls:"mpdf-page-count",text:"\u2014 pages"});let y=o.createEl("button",{cls:"mpdf-btn mpdf-btn-icon"});y.setAttr("aria-label","Open Advanced PDF Export settings"),(0,ze.setIcon)(y,"settings"),y.addEventListener("click",()=>{let w=this.app.setting;w?.open?.(),w?.openTabById?.("advanced-pdf-export")}),this.renderBtn=o.createEl("button",{cls:"mpdf-btn",text:"\u27F3 Render PDF"}),this.renderBtn.title="Render preview (Ctrl+Enter)",this.renderBtn.addEventListener("click",()=>this.render(!0)),this.exportBtn=o.createEl("button",{cls:"mpdf-btn mpdf-btn-primary",text:"\u2B07 Export PDF"}),this.exportBtn.addEventListener("click",()=>void this.exportPDF())}insertAtCursor(e){let r=this.editorEl,n=r.selectionStart,o=r.selectionEnd;r.value=r.value.slice(0,n)+e+r.value.slice(o),r.selectionStart=r.selectionEnd=n+e.length,r.focus()}render(e=!1){let r=++this.renderToken;this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.showLoading();let n=()=>this.doRender(r).catch(o=>{let i=o instanceof Error?o.message:String(o);console.error("[advanced-pdf-export] render error:",o),this.hideLoading(),new ze.Notice("Advanced PDF Export \u2014 render failed: "+i)});e?activeWindow.requestAnimationFrame(()=>activeWindow.requestAnimationFrame(()=>void n())):this.renderDebounceTimer=window.setTimeout(()=>{this.renderDebounceTimer=null,activeWindow.requestAnimationFrame(()=>activeWindow.requestAnimationFrame(()=>void n()))},150)}static insertAutoBreaks(e,r,n){if(!r&&!n)return e;let o=e.split(` `),i=[],a=!1,s="";for(let f of o){if(a){let l=f.match(/^(`{3,}|~{3,})\s*$/);l&&l[1][0]===s[0]&&l[1].length>=s.length&&(a=!1,s="")}else{let l=f.match(/^(`{3,}|~{3,})/);l?(a=!0,s=l[1]):i.length>0&&(r&&/^# /.test(f)||n&&/^## /.test(f))&&i.push("///")}i.push(f)}return i.join(` `)}async doRender(e){let r=this.plugin.settings,n=Gs(this.editorEl.value);r.hideFrontmatter&&(n=Ks(n)),r.includeFilenameAsTitle&&this.currentFile&&(n=`# ${this.currentFile.basename} @@ -266,7 +266,7 @@ ${x}`:x,T=[];for(let E of y)T.push(...ud(E,h,b,D));let C=dd(T,r);this.layoutCach .mpdf-hf-center { flex: 1; text-align: center; } .mpdf-hf-right { margin-left: auto; } ${p} - `,D=new CSSStyleSheet;D.replaceSync(S);for(let T of n){let C=Math.round(o*r),E=Math.round(i*r),M=this.previewEl.createEl("div",{cls:"mpdf-page-wrap"});M.setCssStyles({width:`${C}px`,height:`${E}px`}),M.createEl("div",{cls:"mpdf-page-label",text:`Page ${T.pageNum} of ${T.totalPages}`}),w.push(M);let A=M.createEl("div",{cls:"mpdf-page-scale"});A.setCssStyles({width:`${C}px`,height:`${E}px`});let R=activeDocument.createElement("div");R.addClass("mpdf-shadow-host"),R.setCssStyles({width:`${o}px`,height:`${i}px`,transform:`scale(${r})`}),A.appendChild(R);let I=R.attachShadow({mode:"open"});if(I.adoptedStyleSheets=[D],m.backgroundImageEnabled&&m.backgroundImagePath){let oe=yr(this.app,m.backgroundImagePath);if(oe){let Fe=m.backgroundImageScope==="content-only",Ce=activeDocument.createElement("div"),Be=na(m.backgroundImageSize);Ce.setCssStyles({position:"absolute",...Fe?{top:`${a+c}px`,left:`${s}px`,width:`${u}px`,height:`${d}px`}:{inset:"0"},backgroundImage:`url('${oe}')`,backgroundRepeat:Be.repeat,backgroundSize:Be.size,backgroundPosition:"center",opacity:String(m.backgroundImageOpacity),pointerEvents:"none"}),I.appendChild(Ce)}}let N=T.pageShowsHeader,X=T.pageShowsFooter;if(N&&m.showHeader&&m.headerImagePath){let oe=yr(this.app,m.headerImagePath);if(oe){let Fe=activeDocument.createElement("div");Fe.setCssStyles({position:"absolute",top:`${a*.4}px`,left:`${m.headerImageMargin}px`,right:`${m.headerImageMargin}px`,height:`${c}px`,backgroundImage:`url('${oe}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),I.appendChild(Fe)}}if(T.hasHeader){let oe=activeDocument.createElement("div");oe.setCssStyles({position:"absolute",top:`${a*.4}px`,left:`${s}px`,right:`${f}px`,height:`${c}px`,display:"flex",alignItems:"center",fontSize:`${m.headerFontSize}px`,color:m.headerFontColor,fontFamily:h,whiteSpace:"nowrap",...m.showHeaderBorder?{borderBottom:`0.5px solid ${b}33`}:{}}),vd(oe,T.headerCenter,T.headerLeft,T.headerRight),I.appendChild(oe)}let L=activeDocument.createElement("div");L.className="mpdf-doc",x&&L.setAttribute("dir","rtl"),L.setCssStyles({position:"absolute",top:`${a+c}px`,left:`${s}px`,width:`${u}px`});for(let oe of T.pageNodes)L.appendChild(oe.cloneNode(!0));if(I.appendChild(L),L.querySelectorAll("a[href^='#']").forEach(oe=>{let Fe=decodeURIComponent((oe.getAttribute("href")??"").slice(1)),Ce=y.get(Fe);Ce!==void 0&&(oe.title=`Go to page ${Ce+1}`,oe.addEventListener("click",Be=>{Be.preventDefault(),w[Ce]?.scrollIntoView({behavior:"smooth",block:"start"})}))}),X&&m.showFooter&&m.footerImagePath){let oe=yr(this.app,m.footerImagePath);if(oe){let Fe=activeDocument.createElement("div");Fe.setCssStyles({position:"absolute",bottom:"0",left:`${m.footerImageMargin}px`,right:`${m.footerImageMargin}px`,height:`${l}px`,backgroundImage:`url('${oe}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),I.appendChild(Fe)}}if(T.hasFooter){let oe=activeDocument.createElement("div");oe.setCssStyles({position:"absolute",bottom:"0",left:"0",right:"0",height:`${l}px`,display:"flex",alignItems:"center",...m.showFooterBorder?{borderTop:`0.5px solid ${b}33`}:{},padding:`0 ${f}px 0 ${s}px`,fontSize:`${m.footerFontSize}px`,color:m.footerFontColor,fontFamily:h}),vd(oe,T.footerCenter,T.footerLeft,T.footerRight),I.appendChild(oe)}let ye=zm(m);ye&&I.appendChild(ye)}}async exportPDF(){let e=this.plugin.settings;this.exportBtn.disabled=!0,this.exportBtn.textContent="\u2B07 Exporting\u2026";let r=()=>{this.exportBtn.disabled=!1,this.exportBtn.textContent="\u2B07 Export PDF"};if(!this.layoutCache){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null);let R=++this.renderToken;this.showLoading();try{await this.doRender(R)}catch(I){let N=I instanceof Error?I.message:String(I);new ze.Notice("Advanced PDF Export \u2014 render failed: "+N),this.hideLoading(),r();return}}let n=this.layoutCache;if(!n||n.layouts.length===0){new ze.Notice("Nothing to export."),r();return}let{layouts:o,pw:i,ph:a,mTop:s,mLeft:f,mRight:l,footerH:c,headerH:u,contentW:d,contentH:p,docCSS:h,fontFamily:b,accentColor:F,pageBackground:x,isRTL:m}=n,y=Lm(e),w=e.showHeader&&e.headerImagePath?yr(this.app,e.headerImagePath):"",S=e.showFooter&&e.footerImagePath?yr(this.app,e.footerImagePath):"",D=e.backgroundImageEnabled&&e.backgroundImagePath?yr(this.app,e.backgroundImagePath):"",T=D?(()=>{let R=na(e.backgroundImageSize),I=e.backgroundImageScope==="content-only"?`top:${s+u}px;left:${f}px;width:${d}px;height:${p}px;`:"inset:0;",N=`background-image:url('${D}');background-size:${R.size};background-repeat:${R.repeat};background-position:center;opacity:${e.backgroundImageOpacity};pointer-events:none;`;return`
`})():"",C=o.map(R=>{let I=R.pageNodes.map(Be=>Be.outerHTML).join(` + `,D=new activeWindow.CSSStyleSheet;D.replaceSync(S);for(let T of n){let C=Math.round(o*r),E=Math.round(i*r),M=this.previewEl.createEl("div",{cls:"mpdf-page-wrap"});M.setCssStyles({width:`${C}px`,height:`${E}px`}),M.createEl("div",{cls:"mpdf-page-label",text:`Page ${T.pageNum} of ${T.totalPages}`}),w.push(M);let A=M.createEl("div",{cls:"mpdf-page-scale"});A.setCssStyles({width:`${C}px`,height:`${E}px`});let R=activeDocument.createElement("div");R.addClass("mpdf-shadow-host"),R.setCssStyles({width:`${o}px`,height:`${i}px`,transform:`scale(${r})`}),A.appendChild(R);let I=R.attachShadow({mode:"open"});if(I.adoptedStyleSheets=[D],m.backgroundImageEnabled&&m.backgroundImagePath){let oe=yr(this.app,m.backgroundImagePath);if(oe){let Fe=m.backgroundImageScope==="content-only",Ce=activeDocument.createElement("div"),Be=na(m.backgroundImageSize);Ce.setCssStyles({position:"absolute",...Fe?{top:`${a+c}px`,left:`${s}px`,width:`${u}px`,height:`${d}px`}:{inset:"0"},backgroundImage:`url('${oe}')`,backgroundRepeat:Be.repeat,backgroundSize:Be.size,backgroundPosition:"center",opacity:String(m.backgroundImageOpacity),pointerEvents:"none"}),I.appendChild(Ce)}}let N=T.pageShowsHeader,X=T.pageShowsFooter;if(N&&m.showHeader&&m.headerImagePath){let oe=yr(this.app,m.headerImagePath);if(oe){let Fe=activeDocument.createElement("div");Fe.setCssStyles({position:"absolute",top:`${a*.4}px`,left:`${m.headerImageMargin}px`,right:`${m.headerImageMargin}px`,height:`${c}px`,backgroundImage:`url('${oe}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),I.appendChild(Fe)}}if(T.hasHeader){let oe=activeDocument.createElement("div");oe.setCssStyles({position:"absolute",top:`${a*.4}px`,left:`${s}px`,right:`${f}px`,height:`${c}px`,display:"flex",alignItems:"center",fontSize:`${m.headerFontSize}px`,color:m.headerFontColor,fontFamily:h,whiteSpace:"nowrap",...m.showHeaderBorder?{borderBottom:`0.5px solid ${b}33`}:{}}),vd(oe,T.headerCenter,T.headerLeft,T.headerRight),I.appendChild(oe)}let L=activeDocument.createElement("div");L.className="mpdf-doc",x&&L.setAttribute("dir","rtl"),L.setCssStyles({position:"absolute",top:`${a+c}px`,left:`${s}px`,width:`${u}px`});for(let oe of T.pageNodes)L.appendChild(oe.cloneNode(!0));if(I.appendChild(L),L.querySelectorAll("a[href^='#']").forEach(oe=>{let Fe=decodeURIComponent((oe.getAttribute("href")??"").slice(1)),Ce=y.get(Fe);Ce!==void 0&&(oe.title=`Go to page ${Ce+1}`,oe.addEventListener("click",Be=>{Be.preventDefault(),w[Ce]?.scrollIntoView({behavior:"smooth",block:"start"})}))}),X&&m.showFooter&&m.footerImagePath){let oe=yr(this.app,m.footerImagePath);if(oe){let Fe=activeDocument.createElement("div");Fe.setCssStyles({position:"absolute",bottom:"0",left:`${m.footerImageMargin}px`,right:`${m.footerImageMargin}px`,height:`${l}px`,backgroundImage:`url('${oe}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),I.appendChild(Fe)}}if(T.hasFooter){let oe=activeDocument.createElement("div");oe.setCssStyles({position:"absolute",bottom:"0",left:"0",right:"0",height:`${l}px`,display:"flex",alignItems:"center",...m.showFooterBorder?{borderTop:`0.5px solid ${b}33`}:{},padding:`0 ${f}px 0 ${s}px`,fontSize:`${m.footerFontSize}px`,color:m.footerFontColor,fontFamily:h}),vd(oe,T.footerCenter,T.footerLeft,T.footerRight),I.appendChild(oe)}let ye=zm(m);ye&&I.appendChild(ye)}}async exportPDF(){let e=this.plugin.settings;this.exportBtn.disabled=!0,this.exportBtn.textContent="\u2B07 Exporting\u2026";let r=()=>{this.exportBtn.disabled=!1,this.exportBtn.textContent="\u2B07 Export PDF"};if(!this.layoutCache){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null);let R=++this.renderToken;this.showLoading();try{await this.doRender(R)}catch(I){let N=I instanceof Error?I.message:String(I);new ze.Notice("Advanced PDF Export \u2014 render failed: "+N),this.hideLoading(),r();return}}let n=this.layoutCache;if(!n||n.layouts.length===0){new ze.Notice("Nothing to export."),r();return}let{layouts:o,pw:i,ph:a,mTop:s,mLeft:f,mRight:l,footerH:c,headerH:u,contentW:d,contentH:p,docCSS:h,fontFamily:b,accentColor:F,pageBackground:x,isRTL:m}=n,y=Lm(e),w=e.showHeader&&e.headerImagePath?yr(this.app,e.headerImagePath):"",S=e.showFooter&&e.footerImagePath?yr(this.app,e.footerImagePath):"",D=e.backgroundImageEnabled&&e.backgroundImagePath?yr(this.app,e.backgroundImagePath):"",T=D?(()=>{let R=na(e.backgroundImageSize),I=e.backgroundImageScope==="content-only"?`top:${s+u}px;left:${f}px;width:${d}px;height:${p}px;`:"inset:0;",N=`background-image:url('${D}');background-size:${R.size};background-repeat:${R.repeat};background-position:center;opacity:${e.backgroundImageOpacity};pointer-events:none;`;return`
`})():"",C=o.map(R=>{let I=R.pageNodes.map(Be=>Be.outerHTML).join(` `),N=R.hasHeader,X=e.showHeaderBorder?`border-bottom:0.5px solid ${F}33;`:"",te=N?`
${md(R.headerCenter,R.headerLeft,R.headerRight)}
`:"",L=R.hasFooter,ue=e.showFooterBorder?`border-top:0.5px solid ${F}33;`:"",ye=L?`
${md(R.footerCenter,R.footerLeft,R.footerRight)}
`:"",oe=`
${I}
`,Fe=R.pageShowsHeader&&w?`
`:"",Ce=R.pageShowsFooter&&S?`
`:"";return`
${T}${Fe}${te}${oe}${Ce}${ye}${y}
`});await In();let E=await qs(),M=` *, *::before, *::after { box-sizing: border-box; } @page { size: ${i}px ${a}px; margin: 0; } diff --git a/src/export-modal.ts b/src/export-modal.ts index a9bba12..aa43aa9 100644 --- a/src/export-modal.ts +++ b/src/export-modal.ts @@ -433,11 +433,11 @@ export class PDFExportModal extends Modal { if (immediate) { // Double rAF: ensures the spinner paints before synchronous pagination blocks the thread. - window.requestAnimationFrame(() => window.requestAnimationFrame(() => void safeDo())); + activeWindow.requestAnimationFrame(() => activeWindow.requestAnimationFrame(() => void safeDo())); } else { this.renderDebounceTimer = window.setTimeout(() => { this.renderDebounceTimer = null; - window.requestAnimationFrame(() => window.requestAnimationFrame(() => void safeDo())); + activeWindow.requestAnimationFrame(() => activeWindow.requestAnimationFrame(() => void safeDo())); }, 150); } } @@ -601,7 +601,7 @@ export class PDFExportModal extends Modal { .mpdf-hf-right { margin-left: auto; } ${docCSS} `; - const pageSheet = new CSSStyleSheet(); + const pageSheet = new (activeWindow as unknown as typeof window).CSSStyleSheet(); pageSheet.replaceSync(shadowCSS); for (const layout of layouts) { diff --git a/src/paginator.ts b/src/paginator.ts index 235a094..be61fa6 100644 --- a/src/paginator.ts +++ b/src/paginator.ts @@ -375,7 +375,7 @@ export function paginateEl( const sandboxShadow = sandboxHost.attachShadow({ mode: "open" }); - const sandboxSheet = new CSSStyleSheet(); + const sandboxSheet = new (activeWindow as unknown as typeof window).CSSStyleSheet(); sandboxSheet.replaceSync(docCSS); sandboxShadow.adoptedStyleSheets = [sandboxSheet];