From fb44654bdd5c47a6f8224725dd316e36baa06f07 Mon Sep 17 00:00:00 2001 From: Human Date: Wed, 3 Jun 2026 01:48:22 -0700 Subject: [PATCH] 0.82.4: faster big lists (lazy rendering), import refinements, navigation polish --- main.js | 133 ++++++------ manifest.json | 2 +- package.json | 2 +- pnpm-lock.yaml | 443 ++++++++++++++++++++++++++++++++++++++++ pnpm-workspace.yaml | 6 + release-notes/0.82.4.md | 51 +++++ src/frontmatter-sync.ts | 5 +- src/import-service.ts | 156 ++++++++++---- src/main.ts | 111 ++++++++-- src/notifications.ts | 9 +- src/perf.ts | 60 ++++++ src/settings.ts | 31 ++- src/stash-package.ts | 6 +- src/tree-index.ts | 19 +- src/types.ts | 24 ++- src/view.ts | 177 +++++++++++++--- 16 files changed, 1069 insertions(+), 166 deletions(-) create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 release-notes/0.82.4.md create mode 100644 src/perf.ts diff --git a/main.js b/main.js index 881dd4d..b2088c8 100644 --- a/main.js +++ b/main.js @@ -1,98 +1,99 @@ -"use strict";var Di=Object.create;var De=Object.defineProperty;var Pi=Object.getOwnPropertyDescriptor;var Mi=Object.getOwnPropertyNames;var _i=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var Xt=(g,h)=>()=>(g&&(h=g(g=0)),h);var Ni=(g,h)=>()=>(h||g((h={exports:{}}).exports,h),h.exports),Pe=(g,h)=>{for(var t in h)De(g,t,{get:h[t],enumerable:!0})},Vs=(g,h,t,e)=>{if(h&&typeof h=="object"||typeof h=="function")for(let s of Mi(h))!Li.call(g,s)&&s!==t&&De(g,s,{get:()=>h[s],enumerable:!(e=Pi(h,s))||e.enumerable});return g};var Oi=(g,h,t)=>(t=g!=null?Di(_i(g)):{},Vs(h||!g||!g.__esModule?De(t,"default",{value:g,enumerable:!0}):t,g)),$i=g=>Vs(De({},"__esModule",{value:!0}),g);function bs(g){return Array.isArray(g)?g.filter(h=>typeof h=="string"):typeof g=="string"?g.split(/[,\s]+/).filter(Boolean):[]}function Vt(g,h){let t=h.replace(/^#/,"");return bs(g?.tags).some(e=>e.replace(/^#/,"")===t)}function Ss(g,h){let t=h.replace(/^#/,""),e=bs(g.tags);e.some(s=>s.replace(/^#/,"")===t)||e.push(t),g.tags=e}function ks(g,h){let t=h.replace(/^#/,""),e=bs(g.tags).filter(s=>s.replace(/^#/,"")!==t);e.length?g.tags=e:delete g.tags}function Ys(g){return g.split("/").some(h=>h==="_archive"||h===".archive")}function qs(g){let h=g.match(/\.([^./]+)$/);return!!h&&Ri.has(h[1].toLowerCase())}function Ks(g,h){if(!Array.isArray(h))return!1;for(let t of h){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(g))return!0}catch{}else if(g===e||g.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function Zs(g,h){let t=g.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=h.toLowerCase();return t.every(s=>e.includes(s))}function pe(g){if(typeof g!="string")return null;let h=g.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=h.split("|"),s=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!s)return null;let i=s[2],n=(e??"").trim()||s[1].replace(/-/g," ").trim();return{id:i,name:n}}function ue(g){let h=g?.assignedTo,t=Array.isArray(h)?h:h!=null?[h]:[],e=[];for(let s of t){let i=pe(s);i&&e.push(i)}return e}var mt,$t,Ut,R,Rt,Me,Ri,Tt=Xt(()=>{"use strict";mt="stashpad-view",$t="stashpad-panels",Ut="stashpad-detail",R="__root__";Rt=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy"],Me=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);Ri=new Set(["edtz"])});function Bi(g,h){return g>12?g>=24?0:g:h==="am"?g===12?0:g:g===12?12:g+12}function Le(g,h){g.addClass("stashpad-when-pop-time");let t=h.seedPeriod,e=g.createDiv({cls:"stashpad-when-time-display"}),s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(h.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(h.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),r=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});r.type="button";let o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"PM"});o.type="button";let a=()=>{r.toggleClass("is-active",t==="am"),o.toggleClass("is-active",t==="pm")};a(),r.addEventListener("mousedown",k=>k.preventDefault()),o.addEventListener("mousedown",k=>k.preventDefault()),r.addEventListener("click",k=>{k.preventDefault(),t="am",a()}),o.addEventListener("click",k=>{k.preventDefault(),t="pm",a()});let l=s;s.addEventListener("focus",()=>{l=s,s.select()}),i.addEventListener("focus",()=>{l=i,i.select()});let c=()=>{let C=(parseInt(s.value||"0",10)||0)>12;r.toggleClass("is-disabled",C),o.toggleClass("is-disabled",C),r.disabled=C,o.disabled=C},p=k=>{let C=k.value.replace(/\D/g,"").slice(0,2);if(C===""){k.value="",k===s&&c();return}let I=parseInt(C,10);k===s?I>24&&(I=24):I>59&&(I=59),k.value=String(I),k===s&&c()};for(let k of[s,i])k.addEventListener("input",()=>p(k));c();let u=()=>{let k=parseInt(s.value||"12",10)||12,C=parseInt(i.value||"0",10)||0,I=k>12;h.onFinalize({hours24:Bi(k,t),minutes:C,raw:{hh:k,mm:C,period:t,is24:I}}),h.close()};h.setOnEnter?.(u);let d=[s,i,r,o],f=(k,C)=>{let I=d.indexOf(k);if(I===-1)return;let E=(I+C+d.length)%d.length;d[E].focus()},m=k=>{k.addEventListener("keydown",C=>{C.key==="Enter"?(C.preventDefault(),C.stopPropagation(),u()):C.key==="Escape"?(C.preventDefault(),C.stopPropagation(),h.close()):C.key==="Tab"&&(C.preventDefault(),C.stopPropagation(),f(k,C.shiftKey?-1:1))})},v=g.createDiv({cls:"stashpad-when-time-pad"}),y=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],b=null;for(let k of y){let C=v.createEl("button",{cls:"stashpad-when-time-padbtn"});C.type="button",k==="backspace"?(0,Qs.setIcon)(C,"delete"):k==="insert"?(C.setText("OK"),b=C):C.setText(k),k==="insert"&&C.addClass("is-go"),C.addEventListener("mousedown",I=>I.preventDefault()),C.addEventListener("click",I=>{if(I.preventDefault(),k==="insert"){u();return}if(k==="backspace"){l.value=l.value.slice(0,-1),p(l),l.focus();return}let E=l.selectionStart===0&&l.selectionEnd===l.value.length&&l.value.length>0,D=2,H=E||l.value.length>=D?k:l.value+k;l.value=H,p(l),l.focus(),l.setSelectionRange(l.value.length,l.value.length),l===s&&l.value.length>=D&&(i.focus(),i.select())})}b&&d.push(b);for(let k of d)m(k);s.focus(),s.select()}function ti(g){let{hh:h,mm:t,period:e,is24:s}=g.raw;return s?`${h}:${String(t).padStart(2,"0")}`:`${h}:${String(t).padStart(2,"0")}${e}`}var Qs,Ts=Xt(()=>{"use strict";Qs=require("obsidian")});var Ne={};Pe(Ne,{newId:()=>yt});function yt(g=6){let h="",t=new Uint8Array(g);crypto.getRandomValues(t);for(let e=0;e{"use strict";ei="abcdefghijkmnpqrstuvwxyz23456789"});var be={};Pe(be,{AssignModal:()=>ge,ColorPickerModal:()=>Zt,ConfirmDeleteModal:()=>te,ConfirmModal:()=>It,CustomColorModal:()=>Oe,DueDatePickerModal:()=>ve,ImportDupChoiceModal:()=>we,ImportLogModal:()=>Cs,LogModal:()=>Qt,NotificationHistoryModal:()=>ye,SplitNoteModal:()=>me,buildAssigneePicker:()=>Fs});function Fs(g,h){let t=[...h.initial],e=h.knownAuthors,s=g.createDiv({cls:"stashpad-assign"});s.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let i=s.createDiv({cls:"stashpad-assign-chips"}),n=s.createDiv({cls:"stashpad-assign-input-wrap"}),r=n.createEl("input",{type:"text",cls:"stashpad-assign-input",attr:{placeholder:"Add a person \u2014 type a name\u2026"}}),o=n.createDiv({cls:"stashpad-assign-suggest"});o.style.display="none";let a=()=>h.onChange([...t]),l=()=>{i.empty(),t.length===0&&i.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let u of t){let d=i.createSpan({cls:"stashpad-assign-chip"});d.createSpan({cls:"stashpad-assign-chip-name",text:u.name});let f=d.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});f.title=`Remove ${u.name}`,f.onclick=()=>{t=t.filter(m=>m.id!==u.id),a(),l()}}},c=u=>{u.name.trim()&&(t.some(d=>d.id===u.id)||t.push(u),r.value="",o.style.display="none",a(),l(),r.focus())},p=()=>{let u=r.value.trim();o.empty();let d=new Set(t.map(v=>v.id)),m=e.filter(v=>!d.has(v.id)&&Zs(u,v.name)).slice(0,6).map(v=>({label:v.name,onPick:()=>c(v)}));if(u&&!e.some(v=>v.name.toLowerCase()===u.toLowerCase())&&m.push({label:`Create \u201C${u}\u201D`,onPick:()=>c({id:yt(6),name:u})}),m.length===0){o.style.display="none";return}o.style.display="";for(let v of m){let y=o.createDiv({cls:"stashpad-assign-suggest-item",text:v.label});y.onmousedown=b=>{b.preventDefault(),v.onPick()}}};r.addEventListener("input",p),r.addEventListener("focus",p),r.addEventListener("keydown",u=>{if(u.key==="Enter"){u.preventDefault();let d=o.querySelector(".stashpad-assign-suggest-item");d&&d.dispatchEvent(new MouseEvent("mousedown"))}else u.key==="Escape"&&o.style.display!=="none"&&(u.stopPropagation(),o.style.display="none")}),r.addEventListener("blur",()=>{window.setTimeout(()=>{o.style.display="none"},120)}),l()}var ht,qt,Qt,te,me,Oe,fe,Zt,It,ge,ve,Kt,ye,Cs,we,Bt=Xt(()=>{"use strict";ht=require("obsidian");Ts();Tt();Pt();qt=class qt extends ht.Modal{constructor(t,e,s){super(t);this.text=e;this.jsonlPath=s;this.events=[];this.visible=[];this.shownCount=0;this.typeFilter=null;this.listEl=null;this.footerEl=null;this.countEl=null;this.filterSelEl=null}onOpen(){this.contentEl.empty(),this.titleEl.setText("Stashpad log"),this.modalEl.addClass("stashpad-log-modal"),this.events=[];for(let a of this.text.trim().split(/\r?\n/))if(a)try{this.events.push(JSON.parse(a))}catch{}this.events.reverse();let t=this.contentEl.createDiv({cls:"stashpad-log-toolbar"});this.countEl=t.createSpan({cls:"stashpad-log-count"}),this.updateCount(),this.filterSelEl=t.createEl("select",{cls:"stashpad-log-type-filter"}),this.filterSelEl.onchange=()=>this.setTypeFilter(this.filterSelEl.value||null),this.refreshTypeFilter();let e=t.createEl("button",{text:"Reveal JSONL"});e.onclick=()=>this.shellAct("reveal");let s=t.createEl("button",{text:"Open in default app"});s.onclick=()=>this.shellAct("open");let i=t.createEl("button",{text:"Copy raw JSONL"}),n=null;i.onclick=async()=>{await navigator.clipboard.writeText(this.text),i.setText("Copied"),n!=null&&window.clearTimeout(n),n=window.setTimeout(()=>{i.setText("Copy raw JSONL"),n=null},1500)};let r=t.createEl("button",{text:"Export copy"});r.onclick=()=>this.exportCopy();let o=t.createEl("button",{cls:"mod-warning",text:"Clear log"});o.onclick=()=>this.clearLog(),this.listEl=this.contentEl.createDiv({cls:"stashpad-log-list"}),this.refreshList(),this.footerEl=this.contentEl.createDiv({cls:"stashpad-log-footer"}),this.renderFooter()}refreshList(){if(this.listEl){if(this.visible=this.typeFilter?this.events.filter(t=>t.type===this.typeFilter):this.events.slice(),this.shownCount=0,this.listEl.empty(),!this.visible.length){this.listEl.createDiv({cls:"stashpad-log-empty",text:this.typeFilter?`No "${this.typeFilter}" events.`:"No events yet."}),this.updateCount();return}this.appendMore(qt.PAGE)}}setTypeFilter(t){(this.typeFilter??null)!==(t??null)&&(this.typeFilter=t,this.refreshList(),this.renderFooter())}refreshTypeFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.events)e.set(n.type,(e.get(n.type)??0)+1);let s=[...e.entries()].sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])),i=t.createEl("option",{text:`All types (${this.events.length})`});i.value="";for(let[n,r]of s){let o=t.createEl("option",{text:`${n} (${r})`});o.value=n}this.typeFilter&&!e.has(this.typeFilter)&&(this.typeFilter=null),t.value=this.typeFilter??""}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.typeFilter?`${t} ${this.typeFilter} event${t===1?"":"s"}`:`${t} event${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let s=this.shownCount;s{this.appendMore(qt.PAGE),this.renderFooter()},t>qt.PAGE){let s=this.footerEl.createEl("button",{text:`Load all (${t})`});s.onclick=()=>{this.appendMore(t),this.renderFooter()}}}shellAct(t){try{let e=this.app.vault.adapter.getFullPath?.(this.jsonlPath);if(!e)throw new Error("no full path");let{shell:s}=window.require("electron");t==="reveal"?s.showItemInFolder(e):s.openPath(e)}catch(e){new ht.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,ht.moment)().format("YYYY-MM-DD_HHmmss"),e=this.jsonlPath.replace(/\/[^/]+$/,"")||"",s=e?`${e}/${t}-log.jsonl`:`${t}-log.jsonl`;return await this.app.vault.adapter.write(s,this.text),new ht.Notice(`Exported log \u2192 ${s}`),s}catch(t){return new ht.Notice(`Export failed: ${t.message}`),null}}clearLog(){new It(this.app,"Clear log?","A timestamped copy will be saved alongside the active log before it's truncated.","Export & clear",async t=>{if(!(!t||!await this.exportCopy())){try{await this.app.vault.adapter.write(this.jsonlPath,"")}catch(s){new ht.Notice(`Clear failed: ${s.message}`);return}this.text="",this.events=[],this.typeFilter=null,this.shownCount=0,this.refreshTypeFilter(),this.refreshList(),this.footerEl&&this.footerEl.empty(),new ht.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let s=(0,ht.moment)(t.ts).isValid()?(0,ht.moment)(t.ts).format("YYYY-MM-DD HH:mm:ss"):t.ts,i=document.createElement("span");i.className="stashpad-log-ts",i.textContent=s,e.appendChild(i);let n=document.createElement("span");n.className="stashpad-log-type",n.textContent=t.type,e.appendChild(n);let r=document.createElement("span");r.className="stashpad-log-author",r.textContent=t.author?t.author:"\u2014",t.author||r.classList.add("is-empty"),e.appendChild(r);let o=document.createElement("span");return o.className="stashpad-log-msg",o.textContent=this.describe(t),e.appendChild(o),e}describe(t){let e=t.payload??{};switch(t.type){case"create":return`Created "${e.path??t.id}" under ${e.parent??"?"}`;case"delete":{let s=Array.isArray(e.attachmentsRemoved)?e.attachmentsRemoved.length:0,i=e.mergedInto?` (merged into ${e.mergedInto})`:"";return`Deleted ${t.id}${i}${s?` \u2014 also removed ${s} attachment${s===1?"":"s"}`:""}`}case"missing":return`Missing: ${e.lastPath??t.id}`;case"parent_change":{let s=e.reason?` (${e.reason})`:"";return`Moved ${t.id} from ${e.from??"null"} \u2192 ${e.to??"null"}${s}`}case"rename":return`Renamed ${e.from??"?"} \u2192 ${e.to??"?"}`;case"reorder":{let s=e.count??1,i=e.dir??"?",n=e.parent??t.id??"?";return`Reordered ${s} note${s===1?"":"s"} (${i}) under ${n}`}case"complete":{let s=e.count??1,i=e.undo?" (undo)":e.redo?" (redo)":"";return`Marked ${s} note${s===1?"":"s"} complete${i}`}case"uncomplete":{let s=e.count??1,i=e.undo?" (undo)":e.redo?" (redo)":"";return`Unmarked ${s} note${s===1?"":"s"}${i}`}case"stash_export":{let s=e.noteCount??"?";return`Exported ${s} note${s===1?"":"s"} \u2192 ${e.path??"?"}`}case"stash_import":{let s=e.noteCount??"?",i=[];e.attachmentsWritten&&i.push(`${e.attachmentsWritten} attachment${e.attachmentsWritten===1?"":"s"}`),e.collisionsRenamed&&i.push(`${e.collisionsRenamed} renamed`);let n=i.length?` (${i.join(", ")})`:"";return`Imported ${s} note${s===1?"":"s"} from ${e.from??"?"} \u2192 ${e.into??"?"}${n}`}case"attachment_add":return`Added attachment ${e.path??t.id}`;case"attachment_remove":return`Removed attachment ${e.path??t.id}`;case"palette_color_add":return`Added palette color ${e.color??t.id}`;case"palette_color_remove":return`Removed palette color ${e.color??t.id}`;default:return JSON.stringify(e)}}onClose(){this.contentEl.empty()}};qt.PAGE=100;Qt=qt,te=class extends ht.Modal{constructor(t,e,s,i,n,r){super(t);this.noteTitle=e;this.descendantCount=s;this.attachmentCount=i;this.offerAttachmentDelete=n;this.onChoose=r}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText(`Delete "${this.noteTitle}"?`);let t=[];this.descendantCount>0&&t.push(`${this.descendantCount} descendant note${this.descendantCount===1?"":"s"} will also be deleted.`),this.attachmentCount>0&&t.push(`${this.attachmentCount} attachment${this.attachmentCount===1?"":"s"} found across these notes.`),this.contentEl.createEl("p",{text:t.join(" ")});let e=this.offerAttachmentDelete&&this.attachmentCount>0;if(this.offerAttachmentDelete&&this.attachmentCount>0){let r=this.contentEl.createEl("label",{cls:"stashpad-modal-check"}),o=r.createEl("input",{type:"checkbox"});o.checked=e,o.onchange=()=>{e=o.checked},r.createSpan({text:" Also delete attachments"})}let s=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=s.createEl("button",{text:"Cancel"});i.onclick=()=>this.close();let n=s.createEl("button",{cls:"mod-warning",text:"Delete"});n.onclick=()=>{this.close(),this.onChoose(e)}}onClose(){this.contentEl.empty()}},me=class extends ht.Modal{constructor(t,e,s,i){super(t);this.body=e;this.onSplitAtLine=s;this.onSplitAtChar=i;this.mode="line";this.cursorTextarea=null;this.lines=e.replace(/\r\n/g,` +"use strict";var Ni=Object.create;var Oe=Object.defineProperty;var Oi=Object.getOwnPropertyDescriptor;var $i=Object.getOwnPropertyNames;var Ri=Object.getPrototypeOf,Bi=Object.prototype.hasOwnProperty;var ee=(g,d)=>()=>(g&&(d=g(g=0)),d);var Hi=(g,d)=>()=>(d||g((d={exports:{}}).exports,d),d.exports),$e=(g,d)=>{for(var t in d)Oe(g,t,{get:d[t],enumerable:!0})},Gs=(g,d,t,e)=>{if(d&&typeof d=="object"||typeof d=="function")for(let s of $i(d))!Bi.call(g,s)&&s!==t&&Oe(g,s,{get:()=>d[s],enumerable:!(e=Oi(d,s))||e.enumerable});return g};var zi=(g,d,t)=>(t=g!=null?Ni(Ri(g)):{},Gs(d||!g||!g.__esModule?Oe(t,"default",{value:g,enumerable:!0}):t,g)),Wi=g=>Gs(Oe({},"__esModule",{value:!0}),g);function Cs(g){return Array.isArray(g)?g.filter(d=>typeof d=="string"):typeof g=="string"?g.split(/[,\s]+/).filter(Boolean):[]}function Yt(g,d){let t=d.replace(/^#/,"");return Cs(g?.tags).some(e=>e.replace(/^#/,"")===t)}function Fs(g,d){let t=d.replace(/^#/,""),e=Cs(g.tags);e.some(s=>s.replace(/^#/,"")===t)||e.push(t),g.tags=e}function xs(g,d){let t=d.replace(/^#/,""),e=Cs(g.tags).filter(s=>s.replace(/^#/,"")!==t);e.length?g.tags=e:delete g.tags}function ye(g){return g.split("/").some(d=>ve.has(d))}function Js(g){return g.split("/").some(d=>d==="_archive"||d===".archive")}function qt(g){let d=(g??"").trim();return!d||/^\[\[.*\]\]$/.test(d)?d:`[[${d}]]`}function se(g){let d=(g??"").trim(),t=d.match(/^\[\[(.*)\]\]$/);return t&&(d=t[1]),d.split("|")[0].split("#")[0].split("^")[0].trim()}function Xs(g){let d=g.match(/\.([^./]+)$/);return!!d&&ji.has(d[1].toLowerCase())}function Qs(g,d){if(!Array.isArray(d))return!1;for(let t of d){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(g))return!0}catch{}else if(g===e||g.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function ti(g,d){let t=g.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=d.toLowerCase();return t.every(s=>e.includes(s))}function we(g){if(typeof g!="string")return null;let d=g.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=d.split("|"),s=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!s)return null;let i=s[2],n=(e??"").trim()||s[1].replace(/-/g," ").trim();return{id:i,name:n}}function be(g){let d=g?.assignedTo,t=Array.isArray(d)?d:d!=null?[d]:[],e=[];for(let s of t){let i=we(s);i&&e.push(i)}return e}var mt,Rt,Vt,R,Bt,ve,ji,Tt=ee(()=>{"use strict";mt="stashpad-view",Rt="stashpad-panels",Vt="stashpad-detail",R="__root__";Bt=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy"],ve=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);ji=new Set(["edtz"])});function Ui(g,d){return g>12?g>=24?0:g:d==="am"?g===12?0:g:g===12?12:g+12}function Be(g,d){g.addClass("stashpad-when-pop-time");let t=d.seedPeriod,e=g.createDiv({cls:"stashpad-when-time-display"}),s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(d.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(d.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),r=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});r.type="button";let a=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"PM"});a.type="button";let o=()=>{r.toggleClass("is-active",t==="am"),a.toggleClass("is-active",t==="pm")};o(),r.addEventListener("mousedown",k=>k.preventDefault()),a.addEventListener("mousedown",k=>k.preventDefault()),r.addEventListener("click",k=>{k.preventDefault(),t="am",o()}),a.addEventListener("click",k=>{k.preventDefault(),t="pm",o()});let l=s;s.addEventListener("focus",()=>{l=s,s.select()}),i.addEventListener("focus",()=>{l=i,i.select()});let c=()=>{let T=(parseInt(s.value||"0",10)||0)>12;r.toggleClass("is-disabled",T),a.toggleClass("is-disabled",T),r.disabled=T,a.disabled=T},p=k=>{let T=k.value.replace(/\D/g,"").slice(0,2);if(T===""){k.value="",k===s&&c();return}let I=parseInt(T,10);k===s?I>24&&(I=24):I>59&&(I=59),k.value=String(I),k===s&&c()};for(let k of[s,i])k.addEventListener("input",()=>p(k));c();let u=()=>{let k=parseInt(s.value||"12",10)||12,T=parseInt(i.value||"0",10)||0,I=k>12;d.onFinalize({hours24:Ui(k,t),minutes:T,raw:{hh:k,mm:T,period:t,is24:I}}),d.close()};d.setOnEnter?.(u);let h=[s,i,r,a],f=(k,T)=>{let I=h.indexOf(k);if(I===-1)return;let E=(I+T+h.length)%h.length;h[E].focus()},m=k=>{k.addEventListener("keydown",T=>{T.key==="Enter"?(T.preventDefault(),T.stopPropagation(),u()):T.key==="Escape"?(T.preventDefault(),T.stopPropagation(),d.close()):T.key==="Tab"&&(T.preventDefault(),T.stopPropagation(),f(k,T.shiftKey?-1:1))})},v=g.createDiv({cls:"stashpad-when-time-pad"}),y=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],b=null;for(let k of y){let T=v.createEl("button",{cls:"stashpad-when-time-padbtn"});T.type="button",k==="backspace"?(0,ni.setIcon)(T,"delete"):k==="insert"?(T.setText("OK"),b=T):T.setText(k),k==="insert"&&T.addClass("is-go"),T.addEventListener("mousedown",I=>I.preventDefault()),T.addEventListener("click",I=>{if(I.preventDefault(),k==="insert"){u();return}if(k==="backspace"){l.value=l.value.slice(0,-1),p(l),l.focus();return}let E=l.selectionStart===0&&l.selectionEnd===l.value.length&&l.value.length>0,D=2,H=E||l.value.length>=D?k:l.value+k;l.value=H,p(l),l.focus(),l.setSelectionRange(l.value.length,l.value.length),l===s&&l.value.length>=D&&(i.focus(),i.select())})}b&&h.push(b);for(let k of h)m(k);s.focus(),s.select()}function ri(g){let{hh:d,mm:t,period:e,is24:s}=g.raw;return s?`${d}:${String(t).padStart(2,"0")}`:`${d}:${String(t).padStart(2,"0")}${e}`}var ni,Es=ee(()=>{"use strict";ni=require("obsidian")});var He={};$e(He,{newId:()=>yt});function yt(g=6){let d="",t=new Uint8Array(g);crypto.getRandomValues(t);for(let e=0;e{"use strict";ai="abcdefghijkmnpqrstuvwxyz23456789"});var Ee={};$e(Ee,{AssignModal:()=>Te,ColorPickerModal:()=>Jt,ConfirmDeleteModal:()=>ne,ConfirmModal:()=>At,CustomColorModal:()=>ze,DueDatePickerModal:()=>Ce,ImportDupChoiceModal:()=>xe,ImportLogModal:()=>Is,LogModal:()=>ie,NotificationHistoryModal:()=>Fe,SplitNoteModal:()=>ke,buildAssigneePicker:()=>As});function As(g,d){let t=[...d.initial],e=d.knownAuthors,s=g.createDiv({cls:"stashpad-assign"});s.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let i=s.createDiv({cls:"stashpad-assign-chips"}),n=s.createDiv({cls:"stashpad-assign-input-wrap"}),r=n.createEl("input",{type:"text",cls:"stashpad-assign-input",attr:{placeholder:"Add a person \u2014 type a name\u2026"}}),a=n.createDiv({cls:"stashpad-assign-suggest"});a.style.display="none";let o=()=>d.onChange([...t]),l=()=>{i.empty(),t.length===0&&i.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let u of t){let h=i.createSpan({cls:"stashpad-assign-chip"});h.createSpan({cls:"stashpad-assign-chip-name",text:u.name});let f=h.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});f.title=`Remove ${u.name}`,f.onclick=()=>{t=t.filter(m=>m.id!==u.id),o(),l()}}},c=u=>{u.name.trim()&&(t.some(h=>h.id===u.id)||t.push(u),r.value="",a.style.display="none",o(),l(),r.focus())},p=()=>{let u=r.value.trim();a.empty();let h=new Set(t.map(v=>v.id)),m=e.filter(v=>!h.has(v.id)&&ti(u,v.name)).slice(0,6).map(v=>({label:v.name,onPick:()=>c(v)}));if(u&&!e.some(v=>v.name.toLowerCase()===u.toLowerCase())&&m.push({label:`Create \u201C${u}\u201D`,onPick:()=>c({id:yt(6),name:u})}),m.length===0){a.style.display="none";return}a.style.display="";for(let v of m){let y=a.createDiv({cls:"stashpad-assign-suggest-item",text:v.label});y.onmousedown=b=>{b.preventDefault(),v.onPick()}}};r.addEventListener("input",p),r.addEventListener("focus",p),r.addEventListener("keydown",u=>{if(u.key==="Enter"){u.preventDefault();let h=a.querySelector(".stashpad-assign-suggest-item");h&&h.dispatchEvent(new MouseEvent("mousedown"))}else u.key==="Escape"&&a.style.display!=="none"&&(u.stopPropagation(),a.style.display="none")}),r.addEventListener("blur",()=>{window.setTimeout(()=>{a.style.display="none"},120)}),l()}var ht,Zt,ie,ne,ke,ze,Se,Jt,At,Te,Ce,Gt,Fe,Is,xe,Ht=ee(()=>{"use strict";ht=require("obsidian");Es();Tt();Mt();Zt=class Zt extends ht.Modal{constructor(t,e,s){super(t);this.text=e;this.jsonlPath=s;this.events=[];this.visible=[];this.shownCount=0;this.typeFilter=null;this.listEl=null;this.footerEl=null;this.countEl=null;this.filterSelEl=null}onOpen(){this.contentEl.empty(),this.titleEl.setText("Stashpad log"),this.modalEl.addClass("stashpad-log-modal"),this.events=[];for(let o of this.text.trim().split(/\r?\n/))if(o)try{this.events.push(JSON.parse(o))}catch{}this.events.reverse();let t=this.contentEl.createDiv({cls:"stashpad-log-toolbar"});this.countEl=t.createSpan({cls:"stashpad-log-count"}),this.updateCount(),this.filterSelEl=t.createEl("select",{cls:"stashpad-log-type-filter"}),this.filterSelEl.onchange=()=>this.setTypeFilter(this.filterSelEl.value||null),this.refreshTypeFilter();let e=t.createEl("button",{text:"Reveal JSONL"});e.onclick=()=>this.shellAct("reveal");let s=t.createEl("button",{text:"Open in default app"});s.onclick=()=>this.shellAct("open");let i=t.createEl("button",{text:"Copy raw JSONL"}),n=null;i.onclick=async()=>{await navigator.clipboard.writeText(this.text),i.setText("Copied"),n!=null&&window.clearTimeout(n),n=window.setTimeout(()=>{i.setText("Copy raw JSONL"),n=null},1500)};let r=t.createEl("button",{text:"Export copy"});r.onclick=()=>this.exportCopy();let a=t.createEl("button",{cls:"mod-warning",text:"Clear log"});a.onclick=()=>this.clearLog(),this.listEl=this.contentEl.createDiv({cls:"stashpad-log-list"}),this.refreshList(),this.footerEl=this.contentEl.createDiv({cls:"stashpad-log-footer"}),this.renderFooter()}refreshList(){if(this.listEl){if(this.visible=this.typeFilter?this.events.filter(t=>t.type===this.typeFilter):this.events.slice(),this.shownCount=0,this.listEl.empty(),!this.visible.length){this.listEl.createDiv({cls:"stashpad-log-empty",text:this.typeFilter?`No "${this.typeFilter}" events.`:"No events yet."}),this.updateCount();return}this.appendMore(Zt.PAGE)}}setTypeFilter(t){(this.typeFilter??null)!==(t??null)&&(this.typeFilter=t,this.refreshList(),this.renderFooter())}refreshTypeFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.events)e.set(n.type,(e.get(n.type)??0)+1);let s=[...e.entries()].sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])),i=t.createEl("option",{text:`All types (${this.events.length})`});i.value="";for(let[n,r]of s){let a=t.createEl("option",{text:`${n} (${r})`});a.value=n}this.typeFilter&&!e.has(this.typeFilter)&&(this.typeFilter=null),t.value=this.typeFilter??""}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.typeFilter?`${t} ${this.typeFilter} event${t===1?"":"s"}`:`${t} event${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let s=this.shownCount;s{this.appendMore(Zt.PAGE),this.renderFooter()},t>Zt.PAGE){let s=this.footerEl.createEl("button",{text:`Load all (${t})`});s.onclick=()=>{this.appendMore(t),this.renderFooter()}}}shellAct(t){try{let e=this.app.vault.adapter.getFullPath?.(this.jsonlPath);if(!e)throw new Error("no full path");let{shell:s}=window.require("electron");t==="reveal"?s.showItemInFolder(e):s.openPath(e)}catch(e){new ht.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,ht.moment)().format("YYYY-MM-DD_HHmmss"),e=this.jsonlPath.replace(/\/[^/]+$/,"")||"",s=e?`${e}/${t}-log.jsonl`:`${t}-log.jsonl`;return await this.app.vault.adapter.write(s,this.text),new ht.Notice(`Exported log \u2192 ${s}`),s}catch(t){return new ht.Notice(`Export failed: ${t.message}`),null}}clearLog(){new At(this.app,"Clear log?","A timestamped copy will be saved alongside the active log before it's truncated.","Export & clear",async t=>{if(!(!t||!await this.exportCopy())){try{await this.app.vault.adapter.write(this.jsonlPath,"")}catch(s){new ht.Notice(`Clear failed: ${s.message}`);return}this.text="",this.events=[],this.typeFilter=null,this.shownCount=0,this.refreshTypeFilter(),this.refreshList(),this.footerEl&&this.footerEl.empty(),new ht.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let s=(0,ht.moment)(t.ts).isValid()?(0,ht.moment)(t.ts).format("YYYY-MM-DD HH:mm:ss"):t.ts,i=document.createElement("span");i.className="stashpad-log-ts",i.textContent=s,e.appendChild(i);let n=document.createElement("span");n.className="stashpad-log-type",n.textContent=t.type,e.appendChild(n);let r=document.createElement("span");r.className="stashpad-log-author",r.textContent=t.author?t.author:"\u2014",t.author||r.classList.add("is-empty"),e.appendChild(r);let a=document.createElement("span");return a.className="stashpad-log-msg",a.textContent=this.describe(t),e.appendChild(a),e}describe(t){let e=t.payload??{};switch(t.type){case"create":return`Created "${e.path??t.id}" under ${e.parent??"?"}`;case"delete":{let s=Array.isArray(e.attachmentsRemoved)?e.attachmentsRemoved.length:0,i=e.mergedInto?` (merged into ${e.mergedInto})`:"";return`Deleted ${t.id}${i}${s?` \u2014 also removed ${s} attachment${s===1?"":"s"}`:""}`}case"missing":return`Missing: ${e.lastPath??t.id}`;case"parent_change":{let s=e.reason?` (${e.reason})`:"";return`Moved ${t.id} from ${e.from??"null"} \u2192 ${e.to??"null"}${s}`}case"rename":return`Renamed ${e.from??"?"} \u2192 ${e.to??"?"}`;case"reorder":{let s=e.count??1,i=e.dir??"?",n=e.parent??t.id??"?";return`Reordered ${s} note${s===1?"":"s"} (${i}) under ${n}`}case"complete":{let s=e.count??1,i=e.undo?" (undo)":e.redo?" (redo)":"";return`Marked ${s} note${s===1?"":"s"} complete${i}`}case"uncomplete":{let s=e.count??1,i=e.undo?" (undo)":e.redo?" (redo)":"";return`Unmarked ${s} note${s===1?"":"s"}${i}`}case"stash_export":{let s=e.noteCount??"?";return`Exported ${s} note${s===1?"":"s"} \u2192 ${e.path??"?"}`}case"stash_import":{let s=e.noteCount??"?",i=[];e.attachmentsWritten&&i.push(`${e.attachmentsWritten} attachment${e.attachmentsWritten===1?"":"s"}`),e.collisionsRenamed&&i.push(`${e.collisionsRenamed} renamed`);let n=i.length?` (${i.join(", ")})`:"";return`Imported ${s} note${s===1?"":"s"} from ${e.from??"?"} \u2192 ${e.into??"?"}${n}`}case"attachment_add":return`Added attachment ${e.path??t.id}`;case"attachment_remove":return`Removed attachment ${e.path??t.id}`;case"palette_color_add":return`Added palette color ${e.color??t.id}`;case"palette_color_remove":return`Removed palette color ${e.color??t.id}`;default:return JSON.stringify(e)}}onClose(){this.contentEl.empty()}};Zt.PAGE=100;ie=Zt,ne=class extends ht.Modal{constructor(t,e,s,i,n,r){super(t);this.noteTitle=e;this.descendantCount=s;this.attachmentCount=i;this.offerAttachmentDelete=n;this.onChoose=r}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText(`Delete "${this.noteTitle}"?`);let t=[];this.descendantCount>0&&t.push(`${this.descendantCount} descendant note${this.descendantCount===1?"":"s"} will also be deleted.`),this.attachmentCount>0&&t.push(`${this.attachmentCount} attachment${this.attachmentCount===1?"":"s"} found across these notes.`),this.contentEl.createEl("p",{text:t.join(" ")});let e=this.offerAttachmentDelete&&this.attachmentCount>0;if(this.offerAttachmentDelete&&this.attachmentCount>0){let r=this.contentEl.createEl("label",{cls:"stashpad-modal-check"}),a=r.createEl("input",{type:"checkbox"});a.checked=e,a.onchange=()=>{e=a.checked},r.createSpan({text:" Also delete attachments"})}let s=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=s.createEl("button",{text:"Cancel"});i.onclick=()=>this.close();let n=s.createEl("button",{cls:"mod-warning",text:"Delete"});n.onclick=()=>{this.close(),this.onChoose(e)}}onClose(){this.contentEl.empty()}},ke=class extends ht.Modal{constructor(t,e,s,i){super(t);this.body=e;this.onSplitAtLine=s;this.onSplitAtChar=i;this.mode="line";this.cursorTextarea=null;this.lines=e.replace(/\r\n/g,` `).split(` -`),this.lineCursorIdx=Math.max(1,Math.min(this.lines.length-1,Math.floor(this.lines.length/2))),this.lines.length<2&&(this.mode="cursor")}onOpen(){this.titleEl.setText("Split note"),this.modalEl.addClass("stashpad-split-modal"),this.render(),this.scope.register([],"Tab",t=>{this.lines.length<2||(t.preventDefault(),this.mode=this.mode==="line"?"cursor":"line",this.render())}),this.scope.register([],"Enter",t=>{this.mode==="line"&&(t.preventDefault(),this.commitLine())}),this.scope.register(["Mod"],"Enter",t=>{this.mode==="cursor"&&(t.preventDefault(),this.commitCursor())}),this.scope.register([],"ArrowUp",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.max(1,this.lineCursorIdx-1),this.render())}),this.scope.register([],"ArrowDown",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.min(this.lines.length-1,this.lineCursorIdx+1),this.render())})}commitLine(){let t=this.lineCursorIdx;this.close(),this.onSplitAtLine(t)}commitCursor(){let t=this.cursorTextarea;if(!t)return;let e=t.selectionStart;if(e<=0||e>=t.value.length){new ht.Notice("Move the cursor inside the text \u2014 neither end can be empty.");return}this.close(),this.onSplitAtChar(e)}render(){this.contentEl.empty();let t=this.contentEl.createDiv({cls:"stashpad-split-toggle-bar"});if(this.lines.length>=2){let n=t.createEl("button",{text:"Line split",cls:"stashpad-split-mode-btn"});this.mode==="line"&&n.addClass("is-active"),n.onclick=()=>{this.mode="line",this.render()}}let e=t.createEl("button",{text:"Cursor split",cls:"stashpad-split-mode-btn"});this.mode==="cursor"&&e.addClass("is-active"),e.onclick=()=>{this.mode="cursor",this.render()};let s=t.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});s.onmousedown=n=>n.preventDefault(),s.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let i=this.contentEl.createDiv({cls:"stashpad-split-help"});ht.Platform.isMobile?i.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):i.setText(this.mode==="line"?"\u2191/\u2193 pick split line \xB7 Enter or Split confirm \xB7 Tab \u2192 cursor mode \xB7 Esc cancel \xB7 Children stay with the first part":"Click or arrow to position cursor \xB7 Mod+Enter or Split confirm \xB7 Tab \u2192 line mode \xB7 Esc cancel \xB7 Children stay with the first part")}renderLineMode(){let t=this.contentEl.createDiv({cls:"stashpad-split-list"});for(let e=0;e{let i=Math.max(1,Math.min(this.lines.length-1,e));i!==this.lineCursorIdx&&(this.lineCursorIdx=i,this.render())}}}renderCursorMode(){let e=this.contentEl.createDiv({cls:"stashpad-split-cursor-wrap"}).createEl("textarea",{cls:"stashpad-split-cursor-ta"});e.value=this.body,e.readOnly=!1,this.cursorTextarea=e;let s=parseFloat(getComputedStyle(e).lineHeight)||22,i=ht.Platform.isMobile?3:12,n=2,r=()=>{e.style.height="auto";let o=Math.min(e.scrollHeight,s*i+16);e.style.height=`${Math.max(o,s*n+16)}px`};requestAnimationFrame(()=>{r();let o=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(o,o)}),e.addEventListener("input",r)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},Oe=class extends ht.Modal{constructor(t,e,s){super(t);this.onResult=s;this.delivered=!1;this.value=e&&/^#[0-9a-f]{6}$/i.test(e)?e:"#888888"}onOpen(){this.contentEl.empty(),this.titleEl.setText("Custom color"),this.modalEl.addClass("stashpad-custom-color-modal");let t=this.contentEl.createDiv({cls:"stashpad-custom-color-row"}),e=t.createDiv({cls:"stashpad-custom-color-preview"});e.style.background=this.value;let s=t.createEl("input",{type:"color"});s.value=this.value,s.addClass("stashpad-custom-color-wheel"),e.onclick=()=>s.click();let i=t.createEl("input",{type:"text"});i.addClass("stashpad-custom-color-hex"),i.placeholder="#RRGGBB",i.value=this.value,i.maxLength=7;let n=c=>{let p=c.startsWith("#")?c:"#"+c;/^#[0-9a-f]{6}$/i.test(p)&&(this.value=p,e.style.background=p,s.value=p,i.value!==p&&(i.value=p))};s.oninput=()=>n(s.value),i.oninput=()=>n(i.value);let r=this.contentEl.createDiv({cls:"stashpad-color-footer"}),o=r.createEl("button",{text:"Cancel"});o.onclick=()=>{this.delivered=!0,this.close()};let a=r.createEl("button",{cls:"mod-cta",text:"Save"});a.title="Apply this color to the selection (without adding to your palette).",a.onclick=()=>this.commit({addToPalette:!1});let l=r.createEl("button",{cls:"mod-cta",text:"Add to palette"});l.title="Apply and save this color so it appears as a tile next time.",l.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",c=>{c.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",c=>{c.preventDefault(),this.commit({addToPalette:!0})}),requestAnimationFrame(()=>i.focus())}commit(t){this.delivered=!0,this.close(),this.onResult(this.value,t)}onClose(){this.delivered||(this.delivered=!0,this.onResult(this.value,{addToPalette:!1})),this.contentEl.empty()}},fe=class fe extends ht.Modal{constructor(t,e,s,i,n){super(t);this.currentColor=e;this.customPalette=s;this.onPick=i;this.onDeleteCustom=n;this.focusIdx=-1;this.items=[]}onOpen(){this.contentEl.empty(),this.titleEl.setText("Pick a color"),this.modalEl.addClass("stashpad-color-modal");let t=this.contentEl.createDiv({cls:"stashpad-color-grid"});this.items=[];let e=t.createDiv({cls:"stashpad-color-tile stashpad-color-none"});e.title="No color",e.onclick=()=>this.activate(0),this.items.push({kind:"none",color:null,el:e});let s=[...fe.DEFAULT_PALETTE,...this.customPalette];for(let o of s){let a=t.createDiv({cls:"stashpad-color-tile"});a.style.background=o,a.title=o;let l=!fe.DEFAULT_PALETTE.some(p=>p.toLowerCase()===o.toLowerCase()),c=this.items.length;if(a.onclick=()=>this.activate(c),l&&this.onDeleteCustom){let p=a.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});p.title="Remove from palette",p.onclick=u=>{u.stopPropagation(),this.handleDelete(o)}}this.items.push({kind:l?"custom":"preset",color:o,el:a})}let i=t.createDiv({cls:"stashpad-color-tile stashpad-color-add"});i.title="Custom color\u2026";let n=this.items.length;i.onclick=()=>this.activate(n),this.items.push({kind:"add",color:null,el:i});let r=this.items.findIndex(o=>this.currentColor===null?o.kind==="none":this.currentColor?o.color!==null&&o.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=r>=0?r:0,this.refreshActive(),this.scope.register([],"ArrowRight",o=>{o.preventDefault(),this.moveFocus(1)}),this.scope.register([],"ArrowLeft",o=>{o.preventDefault(),this.moveFocus(-1)}),this.scope.register([],"ArrowDown",o=>{o.preventDefault(),this.moveFocus(this.columns())}),this.scope.register([],"ArrowUp",o=>{o.preventDefault(),this.moveFocus(-this.columns())}),this.scope.register([],"Enter",o=>{o.preventDefault(),this.activate(this.focusIdx)}),requestAnimationFrame(()=>this.modalEl.focus())}activate(t){if(t<0||t>=this.items.length)return;this.focusIdx=t,this.refreshActive();let e=this.items[t];if(e.kind==="add"){this.close(),new Oe(this.app,this.currentColor,(s,i)=>{this.onPick(s,i)}).open();return}this.close(),this.onPick(e.color,{addToPalette:!1})}columns(){if(!this.items.length)return 1;let t=this.items[0].el.parentElement;if(!t)return 1;let e=t.getBoundingClientRect(),s=this.items[0].el.getBoundingClientRect();if(s.width<=0)return 1;let i=s.top,n=0;for(let r of this.items){let o=r.el.getBoundingClientRect();if(Math.abs(o.top-i)<1)n++;else break}return Math.max(1,n)}async handleDelete(t){if(this.onDeleteCustom)try{let e=await this.onDeleteCustom(t);this.customPalette=Array.isArray(e)?e:this.customPalette.filter(s=>s.toLowerCase()!==t.toLowerCase()),this.onOpen()}catch(e){console.warn("Stashpad: palette delete failed",e)}}moveFocus(t){if(!this.items.length)return;let e=Math.max(0,Math.min(this.items.length-1,this.focusIdx+t));this.focusIdx=e,this.refreshActive()}refreshActive(){for(let t=0;t{this.didChoose=!0,this.close(),this.onChoose(!1)};let i=e.createEl("button",{cls:"mod-cta",text:this.confirmText});i.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!0)},requestAnimationFrame(()=>i.focus())}onClose(){this.contentEl.empty(),this.didChoose||(this.didChoose=!0,this.onChoose(!1))}};ge=class extends ht.Modal{constructor(t,e,s){super(t);this.opts=e;this.onPick=s;this.didChoose=!1;this.assignees=[];this.assignees=[...e.currentAssignees]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Assign task");let t=this.contentEl.createDiv({cls:"stashpad-due-picker"});Fs(t,{knownAuthors:this.opts.knownAuthors,initial:this.assignees,onChange:n=>{this.assignees=n}});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=e.createEl("button",{text:"Cancel"});s.onclick=()=>{this.didChoose=!0,this.close()};let i=e.createEl("button",{cls:"mod-cta",text:"Save"});i.onclick=()=>{this.didChoose=!0,this.close(),this.onPick(this.assignees)}}onClose(){this.contentEl.empty(),this.didChoose}},ve=class extends ht.Modal{constructor(t,e,s,i={}){super(t);this.current=e;this.onPick=s;this.opts=i;this.didChoose=!1;this.assignees=[];this.tinyClosePopover=null;this.assignees=[...i.currentAssignees??[]]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Set due date");let t=null;if(this.current){let v=Date.parse(this.current);Number.isNaN(v)||(t=new Date(v))}let e=this.contentEl.createDiv({cls:"stashpad-due-picker"}),s=e.createDiv({cls:"stashpad-due-fields"}),i=s.createDiv({cls:"stashpad-due-field"}),n=i.createSpan({cls:"stashpad-due-field-icon"});(0,ht.setIcon)(n,"calendar");let r=i.createEl("input",{type:"date",cls:"stashpad-due-date"}),o=s.createDiv({cls:"stashpad-due-field"}),a=o.createSpan({cls:"stashpad-due-field-icon"});(0,ht.setIcon)(a,"clock");let l=o.createEl("input",{type:"time",cls:"stashpad-due-time"});n.onclick=()=>{try{r.showPicker?.()}catch{}},a.onclick=()=>this.openTimeNumpad(a,l),t&&(r.value=this.toDateValue(t),l.value=this.toTimeValue(t)),this.renderAssignSection(e);let c=e.createDiv({cls:"stashpad-due-grid"}),p=(v,y)=>{let b=c.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:v});b.onclick=()=>{let k=y();r.value=this.toDateValue(k),l.value||(l.value=this.toTimeValue(k))}},u=v=>(v.setHours(9,0,0,0),v);p("Today",()=>u(this.startOfTodayLocal())),p("Tomorrow",()=>{let v=this.startOfTodayLocal();return v.setDate(v.getDate()+1),u(v)}),p("Next week",()=>{let v=this.startOfTodayLocal();return v.setDate(v.getDate()+7),u(v)});let d=c.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});d.onclick=()=>{r.value="",l.value="",r.focus()};let f=c.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});f.onclick=()=>{this.didChoose=!0,this.close()};let m=c.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});m.onclick=()=>{if(!r.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[v,y,b]=r.value.split("-").map(E=>parseInt(E,10)),k=9,C=0;if(l.value){let[E,D]=l.value.split(":").map(H=>parseInt(H,10));k=E,C=D}let I=new Date(v,y-1,b,k,C,0,0);this.didChoose=!0,this.close(),this.onPick({iso:I.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>r.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){Fs(t,{knownAuthors:this.opts.knownAuthors??[],initial:this.assignees,onChange:e=>{this.assignees=e}})}openTimeNumpad(t,e){this.tinyClosePopover?.();let s=9,i=0;if(e.value){let[d,f]=e.value.split(":").map(m=>parseInt(m,10));Number.isFinite(d)&&(s=d),Number.isFinite(f)&&(i=f)}else{let d=new Date;s=d.getHours(),i=d.getMinutes()}let n=s>=12?"pm":"am",r=s===0?12:s>12?s-12:s,o=document.body.createDiv({cls:"stashpad-when-popover stashpad-due-time-pop"});o.style.position="fixed",o.style.zIndex="9999";let a=null,l=()=>{o.remove(),document.removeEventListener("mousedown",c,!0),document.removeEventListener("keydown",p,!0),this.tinyClosePopover===l&&(this.tinyClosePopover=null)},c=d=>{!o.contains(d.target)&&d.target!==t&&!t.contains(d.target)&&l()},p=d=>{d.key==="Escape"?(d.preventDefault(),d.stopPropagation(),l()):d.key==="Enter"&&a&&(d.preventDefault(),d.stopPropagation(),a())};this.tinyClosePopover=l,Le(o,{seedH:r,seedM:i,seedPeriod:n,close:l,setOnEnter:d=>{a=d},onFinalize:d=>{e.value=`${String(d.hours24).padStart(2,"0")}:${String(d.minutes).padStart(2,"0")}`}});let u=t.getBoundingClientRect();o.style.left=`${Math.max(8,Math.min(u.left,window.innerWidth-220))}px`,o.style.top=`${u.bottom+4}px`,setTimeout(()=>{document.addEventListener("mousedown",c,!0),document.addEventListener("keydown",p,!0)},0)}startOfTodayLocal(){let t=new Date;return t.setHours(0,0,0,0),t}toDateValue(t){let e=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${e}-${s}-${i}`}toTimeValue(t){let e=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0");return`${e}:${s}`}},Kt=class Kt extends ht.Modal{constructor(t,e,s,i=null,n){super(t);this.service=e;this.openLog=s;this.currentAuthorId=i;this.getNoteAuthorIds=n;this.records=[];this.visible=[];this.shownCount=0;this.categoryFilter=null;this.listEl=null;this.footerEl=null;this.countEl=null;this.filterSelEl=null;this.unsubscribe=null;this.authorFilter="all";this.authorSelEl=null}onOpen(){this.contentEl.empty(),this.titleEl.setText("Stashpad notification history"),this.modalEl.addClass("stashpad-log-modal"),this.modalEl.addClass("stashpad-notif-history-modal"),this.records=this.service.recent();let t=this.contentEl.createDiv({cls:"stashpad-log-toolbar"});if(this.countEl=t.createSpan({cls:"stashpad-log-count"}),this.updateCount(),this.filterSelEl=t.createEl("select",{cls:"stashpad-log-type-filter"}),this.filterSelEl.onchange=()=>this.setCategoryFilter(this.filterSelEl.value||null),this.refreshCategoryFilter(),this.authorSelEl=t.createEl("select",{cls:"stashpad-log-type-filter stashpad-notif-author-filter"}),this.authorSelEl.onchange=()=>this.setAuthorFilter(this.authorSelEl.value||"all"),this.refreshAuthorFilter(),this.openLog){let s=t.createEl("button",{text:"Open log"});s.title="Open the per-folder Stashpad log for the most recent notification's folder.",s.onclick=()=>{let i=this.records.find(n=>!!n.folder);this.openLog?.(i?.folder)}}let e=t.createEl("button",{cls:"mod-warning",text:"Clear history"});e.onclick=()=>{new It(this.app,"Clear notification history?",`This will permanently remove all ${this.records.length} stored notifications from the history. The current toasts on screen are unaffected. This can't be undone.`,"Clear history",s=>{s&&this.service.clearHistory()}).open()},this.listEl=this.contentEl.createDiv({cls:"stashpad-log-list"}),this.refreshList(),this.footerEl=this.contentEl.createDiv({cls:"stashpad-log-footer"}),this.renderFooter(),this.unsubscribe=this.service.onChange(()=>{this.records=this.service.recent(),this.refreshCategoryFilter(),this.refreshAuthorFilter(),this.refreshList(),this.renderFooter()})}setAuthorFilter(t){this.authorFilter!==t&&(this.authorFilter=t,this.refreshList(),this.renderFooter())}refreshAuthorFilter(){if(!this.authorSelEl)return;let t=this.authorSelEl;t.empty(),t.createEl("option",{text:"All authors"}).value="all",this.currentAuthorId&&(t.createEl("option",{text:"Me"}).value="me"),t.createEl("option",{text:"Cross-author"}).value="cross";let e=new Set;for(let i of this.records)i.authorId&&i.authorId!==this.currentAuthorId&&e.add(i.authorId);if(e.size>0){let i=t.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});i.disabled=!0;for(let n of[...e].sort())t.createEl("option",{text:n}).value=n}new Set(["all","cross",...this.currentAuthorId?["me"]:[],...e]).has(this.authorFilter)||(this.authorFilter="all"),t.value=this.authorFilter}isCrossAuthor(t){let e=t.authorId??null;if(!e)return!1;for(let s of t.affectedAuthorIds??[])if(s&&s!==e)return!0;if(!this.getNoteAuthorIds)return!1;for(let s of t.affectedIds){let i=this.getNoteAuthorIds(s);for(let n of i)if(n&&n!==e)return!0}return!1}onClose(){this.unsubscribe?.(),this.unsubscribe=null,this.contentEl.empty()}setCategoryFilter(t){(this.categoryFilter??null)!==(t??null)&&(this.categoryFilter=t,this.refreshList(),this.renderFooter())}refreshCategoryFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.records)e.set(n.category,(e.get(n.category)??0)+1);let s=[...e.entries()].sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])),i=t.createEl("option",{text:`All categories (${this.records.length})`});i.value="";for(let[n,r]of s){let o=t.createEl("option",{text:`${n} (${r})`});o.value=n}this.categoryFilter&&!e.has(this.categoryFilter)&&(this.categoryFilter=null),t.value=this.categoryFilter??""}refreshList(){if(this.listEl){if(this.visible=this.records.filter(t=>{if(this.categoryFilter&&t.category!==this.categoryFilter)return!1;switch(this.authorFilter){case"all":return!0;case"me":return!!this.currentAuthorId&&t.authorId===this.currentAuthorId;case"cross":return this.isCrossAuthor(t);default:return t.authorId===this.authorFilter}}),this.shownCount=0,this.listEl.empty(),!this.visible.length){this.listEl.createDiv({cls:"stashpad-log-empty",text:this.categoryFilter?`No "${this.categoryFilter}" notifications.`:"No notifications yet."}),this.updateCount();return}this.appendMore(Kt.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let s=this.shownCount;s0){let l=s.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let c of e.actionLabels){let p=l.createSpan({cls:"stashpad-notif-action-chip"});p.setText(c),p.title="Action button was shown on the original toast (handler not retained)."}}}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.categoryFilter?`${t} ${this.categoryFilter} notification${t===1?"":"s"}`:`${t} notification${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}renderFooter(){if(!this.footerEl)return;this.footerEl.empty();let t=this.visible.length-this.shownCount;if(t<=0)return;let e=this.footerEl.createEl("button",{text:`Load ${Math.min(Kt.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Kt.PAGE),this.renderFooter()},t>Kt.PAGE){let s=this.footerEl.createEl("button",{text:`Load all (${t})`});s.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Kt.PAGE=100;ye=Kt,Cs=class extends ht.Modal{constructor(t,e){super(t);this.entries=e}onOpen(){if(this.contentEl.empty(),this.titleEl.setText("Stashpad import log"),this.entries.length===0){this.contentEl.createDiv({cls:"stashpad-log-empty",text:"Nothing imported yet."});return}let t=this.contentEl.createDiv({cls:"stashpad-import-log-list"});for(let e of this.entries){let s=t.createDiv({cls:"stashpad-import-log-row"}),i=(0,ht.moment)(e.ts).format("YYYY-MM-DD HH:mm");s.createSpan({cls:"stashpad-import-log-when",text:i});let n=e.kind==="folder"?"folder":e.kind==="md"?"note":"file";s.createSpan({cls:`stashpad-import-log-kind is-${e.kind}`,text:n}),s.createSpan({cls:"stashpad-import-log-name",text:e.originalName});let r=[e.folder.split("/").pop()||e.folder];e.notePaths.length>1&&r.push(`${e.notePaths.length} notes`),s.createSpan({cls:"stashpad-import-log-meta",text:r.join(" \xB7 ")})}}onClose(){this.contentEl.empty()}},we=class extends ht.Modal{constructor(t,e,s){super(t);this.message=e;this.onChoose=s;this.chose=!1}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Possible duplicate import");let t=this.contentEl.createDiv({cls:"stashpad-confirm-body"});for(let r of this.message.split(` -`))t.createDiv({cls:"stashpad-confirm-line",text:r});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=e.createEl("button",{text:"Skip duplicates"});s.onclick=()=>{this.chose=!0,this.close(),this.onChoose("skip")};let i=e.createEl("button",{text:"Replace existing"});i.onclick=()=>{this.chose=!0,this.close(),this.onChoose("replace")};let n=e.createEl("button",{cls:"mod-cta",text:"Import anyway"});n.onclick=()=>{this.chose=!0,this.close(),this.onChoose("anyway")}}onClose(){this.chose||this.onChoose("skip"),this.contentEl.empty()}}});function Ft(g,h=Mt){let t=h instanceof Set?h:new Set(h.map(r=>r.toLowerCase())),e=(g.split(/\r?\n/).find(r=>r.trim().length>0)??"").trim();if(!e)return"Untitled";let i=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(r=>r&&!t.has(r.toLowerCase())).map(r=>r.length>=2&&/^[A-Z0-9]+$/.test(r)?r:r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()),n="";for(let r of i){let o=n?`${n}-${r}`:r;if(o.length>50)break;n=o}return n||"Untitled"}function xt(g,h){return`${g}-${h}.md`}function ee(g){let h=g.match(/-([a-z0-9]{4,12})$/);return h?h[1]:null}var Mt,se=Xt(()=>{"use strict";Mt=["a","an","the","and","or","but","if","then","else","of","in","on","at","to","for","with","by","from","as","is","are","was","were","be","been","being","i","you","he","she","it","we","they","this","that","these","those","my","your","our","their","do","does","did","so","just","very","really","im"]});var We={};Pe(We,{JdBuildConfirmModal:()=>ke,buildJdIndexNotes:()=>Es,buildJdIndexPreview:()=>He,buildJdPreviewNotice:()=>ze,scanForJdNotes:()=>ie});function xs(g,h){if(/^\d+-\d+$/.test(g))return null;if(g.includes(".")){let e=g.split(".").slice(0,-1).join(".");return h.has(e)?e:xs(e,h)}if(/^\d+$/.test(g)){let t=parseInt(g,10);for(let e of h){let s=e.match(/^(\d+)-(\d+)$/);if(!s)continue;let i=parseInt(s[1],10),n=parseInt(s[2],10);if(t>=i&&t<=n)return e}return null}return null}function ie(g,h,t){let e=g.vault.getMarkdownFiles(),s=zi(e,t),i=t.jdIndexIncludeStashpadFolders===!0,n=i?new Set:new Set(h.discoverStashpadFolders()),r=d=>i?!1:Array.from(n).some(f=>d===f||d.startsWith(f+"/")),o=[],a=[],l=[];for(let d of s){let f=d.parent?.path?.replace(/\/+$/,"")??"";if(r(f)){l.push(d);continue}let m=d.basename.match(si);m?o.push({prefix:m[1],segments:m[1].split("."),title:m[2],file:d,folder:null}):a.push(d)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",p=d=>{let f=d.path.replace(/\/+$/,"");if(!(c&&f&&f!==c&&!f.startsWith(c+"/"))){if(f&&!r(f)){let m=d.name.match(si);m&&o.push({prefix:m[1],segments:m[1].split("."),title:m[2],file:null,folder:d})}}for(let m of d.children)m instanceof kt.TFolder&&p(m)};p(g.vault.getRoot());let u=t.jdIndexSort??"natural";return o.sort((d,f)=>Wi(d,f,u)),{indexed:o,nonIndex:a,skippedStashpadNotes:l}}async function He(g,h,t){let e=Is(t.jdIndexStashpadFolder??"");if(!e)return{...ie(g,h,t),previewPath:null,error:"no-dest"};let s=ie(g,h,t),i=Hi(g,e);if(!i)return{...s,previewPath:null,error:"no-home"};let n=ji(s.indexed,s.nonIndex,s.skippedStashpadNotes),o=(await g.vault.read(i)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),a=o?`${o[0]}${n}`:n;return await g.vault.modify(i,a),{...s,previewPath:i.path}}function Hi(g,h){let t=g.vault.getAbstractFileByPath(h);if(!(t instanceof kt.TFolder))return null;for(let e of t.children){if(!(e instanceof kt.TFile)||e.extension!=="md")continue;if((g.metadataCache.getFileCache(e)?.frontmatter??{}).id===R)return e}return null}async function Es(g,h,t){let e=Is(t.jdIndexStashpadFolder??"");if(!e)return{created:0,updated:0,skipped:0,destFolder:"",error:"no-dest"};if(!new Set(h.discoverStashpadFolders()).has(e))return{created:0,updated:0,skipped:0,destFolder:e,error:"dest-not-stashpad"};let i=ie(g,h,t),n=new Map;for(let v of i.indexed)n.set(v.prefix,v);for(let v of i.indexed)if(v.prefix.includes("."))for(let y=1;y{a.push(v);for(let y of o.get(v)??[])l(y)};for(let v of r)l(v);let c=new Map,p=g.vault.getAbstractFileByPath(e);if(p instanceof kt.TFolder)for(let v of p.children){if(!(v instanceof kt.TFile)||v.extension!=="md")continue;let y=g.metadataCache.getFileCache(v)?.frontmatter??{};typeof y.jdPrefix=="string"&&c.set(y.jdPrefix,v)}let u=new Map,d=0,f=0,m=0;for(let v of a){let y=n.get(v)??null,b=xs(v,new Set(n.keys())),k=b?u.get(b)??R:R,C=y?`${v} ${y.title}`:v,I=y?.file?`[[${y.file.basename}]]`:"",E=I?`${I} -`:`${C} -`,D=c.get(v);if(D){try{let H=null;await g.fileManager.processFrontMatter(D,_=>{_.jdPrefix=v,k&&(_.parent=k),(!_.id||typeof _.id!="string")&&(_.id=yt()),_.created||(_.created=new Date().toISOString()),_.attachments||(_.attachments=[]),H=_.id});let A=(await g.vault.read(D)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),S=A?`${A[0]}${E}`:E;await g.vault.modify(D,S),H&&u.set(v,H),f++}catch(H){console.error("[stashpad] buildJdIndexNotes: update failed",H),m++}continue}try{let H=yt();u.set(v,H);let T=Ft(C,t.slugStopWords),A=xt(T,H),S=`${e}/${A}`,_=["---",`id: ${H}`,`parent: ${k}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${v}"`,"---",""].join(` -`);await g.vault.create(S,_+E),d++}catch(H){console.error("[stashpad] buildJdIndexNotes: create failed for",v,H),m++}}return{created:d,updated:f,skipped:m,destFolder:e}}function Is(g){return(g||"").trim().replace(/^\/+|\/+$/g,"")}function zi(g,h){if((h.jdIndexScope??"vault")==="vault")return g;let t=Is(h.jdIndexScopeFolder??"");return t?g.filter(e=>{let s=e.parent?.path?.replace(/\/+$/,"")??"";return s===t||s.startsWith(t+"/")}):g}function Wi(g,h,t){if(t==="created"){let e=g.file.stat?.ctime??0,s=h.file.stat?.ctime??0;if(e!==s)return e-s}return ni(g.segments,h.segments)}function ii(g,h){let t=g.match(/^(\d+)-(\d+)$/),e=h.match(/^(\d+)-(\d+)$/),s=t?[t[1]]:g.split("."),i=e?[e[1]]:h.split(".");return ni(s,i)}function ni(g,h){let t=Math.min(g.length,h.length);for(let e=0;e{i.set(r,o);for(let a of e.get(r)??[])n(a,o+1)};for(let r of s)n(r,0);return{roots:s,childrenOf:e,depthOf:i}}function ji(g,h,t){let e=[],s=i=>"#".repeat(Math.min(i+1,6));if(e.push("# Indexed"),e.push(""),g.length===0){let i=t.length>0?`_No notes matched. ${t.length} note${t.length===1?" was":"s were"} excluded because they live inside a Stashpad folder \u2014 toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder if you want them included._`:"_No notes matched the JD-prefix convention. Check Scope and Designated folder in Settings \u2192 JD Index Builder._";e.push(i)}else{let i=new Map;for(let l of g)i.set(l.prefix,l);for(let l of g)if(l.prefix.includes("."))for(let c=1;c{let c=i.get(l),p=o.get(l)??0,u=" ".repeat(p),d=s(p),f=c?.folder?` ${c.title} _(folder)_`:(c?.file,"");c?.file?e.push(`${u}- ${d} [[${c.file.basename}|${c.prefix} ${c.title}]]`):c?.folder?e.push(`${u}- ${d} ${c.prefix}${f}`):e.push(`${u}- ${d} ${l}`);for(let m of r.get(l)??[])a(m)};for(let l of n)a(l)}if(h.length>0){e.push(""),e.push(`# Non-indexed (${h.length})`),e.push(""),e.push("_These notes don't match the JD-prefix convention. Rename them to ` ` and re-run to include them._"),e.push("");for(let i of h)e.push(`- # [[${i.basename}]] \xB7 \`${i.path}\``)}if(t.length>0){let i=new Map;for(let r of t){let o=r.parent?.path?.replace(/\/+$/,"")??"";i.set(o,(i.get(o)??0)+1)}let n=Array.from(i.entries()).sort((r,o)=>r[0].localeCompare(o[0]));e.push(""),e.push(`# Excluded folders (${n.length})`),e.push(""),e.push(`_Stashpad folders are excluded by default so the index doesn't reference itself. Toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder to include them._`),e.push("");for(let[r,o]of n)e.push(`- # All ${o} file${o===1?"":"s"} in \`${r||"(vault root)"}\``)}return e.join(` +`),this.lineCursorIdx=Math.max(1,Math.min(this.lines.length-1,Math.floor(this.lines.length/2))),this.lines.length<2&&(this.mode="cursor")}onOpen(){this.titleEl.setText("Split note"),this.modalEl.addClass("stashpad-split-modal"),this.render(),this.scope.register([],"Tab",t=>{this.lines.length<2||(t.preventDefault(),this.mode=this.mode==="line"?"cursor":"line",this.render())}),this.scope.register([],"Enter",t=>{this.mode==="line"&&(t.preventDefault(),this.commitLine())}),this.scope.register(["Mod"],"Enter",t=>{this.mode==="cursor"&&(t.preventDefault(),this.commitCursor())}),this.scope.register([],"ArrowUp",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.max(1,this.lineCursorIdx-1),this.render())}),this.scope.register([],"ArrowDown",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.min(this.lines.length-1,this.lineCursorIdx+1),this.render())})}commitLine(){let t=this.lineCursorIdx;this.close(),this.onSplitAtLine(t)}commitCursor(){let t=this.cursorTextarea;if(!t)return;let e=t.selectionStart;if(e<=0||e>=t.value.length){new ht.Notice("Move the cursor inside the text \u2014 neither end can be empty.");return}this.close(),this.onSplitAtChar(e)}render(){this.contentEl.empty();let t=this.contentEl.createDiv({cls:"stashpad-split-toggle-bar"});if(this.lines.length>=2){let n=t.createEl("button",{text:"Line split",cls:"stashpad-split-mode-btn"});this.mode==="line"&&n.addClass("is-active"),n.onclick=()=>{this.mode="line",this.render()}}let e=t.createEl("button",{text:"Cursor split",cls:"stashpad-split-mode-btn"});this.mode==="cursor"&&e.addClass("is-active"),e.onclick=()=>{this.mode="cursor",this.render()};let s=t.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});s.onmousedown=n=>n.preventDefault(),s.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let i=this.contentEl.createDiv({cls:"stashpad-split-help"});ht.Platform.isMobile?i.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):i.setText(this.mode==="line"?"\u2191/\u2193 pick split line \xB7 Enter or Split confirm \xB7 Tab \u2192 cursor mode \xB7 Esc cancel \xB7 Children stay with the first part":"Click or arrow to position cursor \xB7 Mod+Enter or Split confirm \xB7 Tab \u2192 line mode \xB7 Esc cancel \xB7 Children stay with the first part")}renderLineMode(){let t=this.contentEl.createDiv({cls:"stashpad-split-list"});for(let e=0;e<this.lines.length;e++){e===this.lineCursorIdx&&t.createDiv({cls:"stashpad-split-divider",text:"\u2500\u2500 split here \u2500\u2500"});let s=t.createDiv({cls:"stashpad-split-line"});s.createSpan({cls:"stashpad-split-lineno",text:String(e+1)}),s.createSpan({cls:"stashpad-split-text",text:this.lines[e]||" "}),s.onclick=()=>{let i=Math.max(1,Math.min(this.lines.length-1,e));i!==this.lineCursorIdx&&(this.lineCursorIdx=i,this.render())}}}renderCursorMode(){let e=this.contentEl.createDiv({cls:"stashpad-split-cursor-wrap"}).createEl("textarea",{cls:"stashpad-split-cursor-ta"});e.value=this.body,e.readOnly=!1,this.cursorTextarea=e;let s=parseFloat(getComputedStyle(e).lineHeight)||22,i=ht.Platform.isMobile?3:12,n=2,r=()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,s*i+16);e.style.height=`${Math.max(a,s*n+16)}px`};requestAnimationFrame(()=>{r();let a=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(a,a)}),e.addEventListener("input",r)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},ze=class extends ht.Modal{constructor(t,e,s){super(t);this.onResult=s;this.delivered=!1;this.value=e&&/^#[0-9a-f]{6}$/i.test(e)?e:"#888888"}onOpen(){this.contentEl.empty(),this.titleEl.setText("Custom color"),this.modalEl.addClass("stashpad-custom-color-modal");let t=this.contentEl.createDiv({cls:"stashpad-custom-color-row"}),e=t.createDiv({cls:"stashpad-custom-color-preview"});e.style.background=this.value;let s=t.createEl("input",{type:"color"});s.value=this.value,s.addClass("stashpad-custom-color-wheel"),e.onclick=()=>s.click();let i=t.createEl("input",{type:"text"});i.addClass("stashpad-custom-color-hex"),i.placeholder="#RRGGBB",i.value=this.value,i.maxLength=7;let n=c=>{let p=c.startsWith("#")?c:"#"+c;/^#[0-9a-f]{6}$/i.test(p)&&(this.value=p,e.style.background=p,s.value=p,i.value!==p&&(i.value=p))};s.oninput=()=>n(s.value),i.oninput=()=>n(i.value);let r=this.contentEl.createDiv({cls:"stashpad-color-footer"}),a=r.createEl("button",{text:"Cancel"});a.onclick=()=>{this.delivered=!0,this.close()};let o=r.createEl("button",{cls:"mod-cta",text:"Save"});o.title="Apply this color to the selection (without adding to your palette).",o.onclick=()=>this.commit({addToPalette:!1});let l=r.createEl("button",{cls:"mod-cta",text:"Add to palette"});l.title="Apply and save this color so it appears as a tile next time.",l.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",c=>{c.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",c=>{c.preventDefault(),this.commit({addToPalette:!0})}),requestAnimationFrame(()=>i.focus())}commit(t){this.delivered=!0,this.close(),this.onResult(this.value,t)}onClose(){this.delivered||(this.delivered=!0,this.onResult(this.value,{addToPalette:!1})),this.contentEl.empty()}},Se=class Se extends ht.Modal{constructor(t,e,s,i,n){super(t);this.currentColor=e;this.customPalette=s;this.onPick=i;this.onDeleteCustom=n;this.focusIdx=-1;this.items=[]}onOpen(){this.contentEl.empty(),this.titleEl.setText("Pick a color"),this.modalEl.addClass("stashpad-color-modal");let t=this.contentEl.createDiv({cls:"stashpad-color-grid"});this.items=[];let e=t.createDiv({cls:"stashpad-color-tile stashpad-color-none"});e.title="No color",e.onclick=()=>this.activate(0),this.items.push({kind:"none",color:null,el:e});let s=[...Se.DEFAULT_PALETTE,...this.customPalette];for(let a of s){let o=t.createDiv({cls:"stashpad-color-tile"});o.style.background=a,o.title=a;let l=!Se.DEFAULT_PALETTE.some(p=>p.toLowerCase()===a.toLowerCase()),c=this.items.length;if(o.onclick=()=>this.activate(c),l&&this.onDeleteCustom){let p=o.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});p.title="Remove from palette",p.onclick=u=>{u.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:l?"custom":"preset",color:a,el:o})}let i=t.createDiv({cls:"stashpad-color-tile stashpad-color-add"});i.title="Custom color\u2026";let n=this.items.length;i.onclick=()=>this.activate(n),this.items.push({kind:"add",color:null,el:i});let r=this.items.findIndex(a=>this.currentColor===null?a.kind==="none":this.currentColor?a.color!==null&&a.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=r>=0?r:0,this.refreshActive(),this.scope.register([],"ArrowRight",a=>{a.preventDefault(),this.moveFocus(1)}),this.scope.register([],"ArrowLeft",a=>{a.preventDefault(),this.moveFocus(-1)}),this.scope.register([],"ArrowDown",a=>{a.preventDefault(),this.moveFocus(this.columns())}),this.scope.register([],"ArrowUp",a=>{a.preventDefault(),this.moveFocus(-this.columns())}),this.scope.register([],"Enter",a=>{a.preventDefault(),this.activate(this.focusIdx)}),requestAnimationFrame(()=>this.modalEl.focus())}activate(t){if(t<0||t>=this.items.length)return;this.focusIdx=t,this.refreshActive();let e=this.items[t];if(e.kind==="add"){this.close(),new ze(this.app,this.currentColor,(s,i)=>{this.onPick(s,i)}).open();return}this.close(),this.onPick(e.color,{addToPalette:!1})}columns(){if(!this.items.length)return 1;let t=this.items[0].el.parentElement;if(!t)return 1;let e=t.getBoundingClientRect(),s=this.items[0].el.getBoundingClientRect();if(s.width<=0)return 1;let i=s.top,n=0;for(let r of this.items){let a=r.el.getBoundingClientRect();if(Math.abs(a.top-i)<1)n++;else break}return Math.max(1,n)}async handleDelete(t){if(this.onDeleteCustom)try{let e=await this.onDeleteCustom(t);this.customPalette=Array.isArray(e)?e:this.customPalette.filter(s=>s.toLowerCase()!==t.toLowerCase()),this.onOpen()}catch(e){console.warn("Stashpad: palette delete failed",e)}}moveFocus(t){if(!this.items.length)return;let e=Math.max(0,Math.min(this.items.length-1,this.focusIdx+t));this.focusIdx=e,this.refreshActive()}refreshActive(){for(let t=0;t<this.items.length;t++)this.items[t].el.toggleClass("is-active",t===this.focusIdx)}onClose(){this.contentEl.empty()}};Se.DEFAULT_PALETTE=["#E07A78","#E08A47","#E0A744","#B0CC6E","#6BC07A","#5BA9CE","#9B82C9","#C57AB5","#D75AA8"];Jt=Se,At=class extends ht.Modal{constructor(t,e,s,i,n){super(t);this.titleText=e;this.message=s;this.confirmText=i;this.onChoose=n;this.didChoose=!1}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText(this.titleText);let t=this.contentEl.createDiv({cls:"stashpad-confirm-body"});for(let n of this.message.split(` +`))t.createDiv({cls:"stashpad-confirm-line",text:n});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=e.createEl("button",{text:"Cancel"});s.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!1)};let i=e.createEl("button",{cls:"mod-cta",text:this.confirmText});i.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!0)},requestAnimationFrame(()=>i.focus())}onClose(){this.contentEl.empty(),this.didChoose||(this.didChoose=!0,this.onChoose(!1))}};Te=class extends ht.Modal{constructor(t,e,s){super(t);this.opts=e;this.onPick=s;this.didChoose=!1;this.assignees=[];this.assignees=[...e.currentAssignees]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Assign task");let t=this.contentEl.createDiv({cls:"stashpad-due-picker"});As(t,{knownAuthors:this.opts.knownAuthors,initial:this.assignees,onChange:n=>{this.assignees=n}});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=e.createEl("button",{text:"Cancel"});s.onclick=()=>{this.didChoose=!0,this.close()};let i=e.createEl("button",{cls:"mod-cta",text:"Save"});i.onclick=()=>{this.didChoose=!0,this.close(),this.onPick(this.assignees)}}onClose(){this.contentEl.empty(),this.didChoose}},Ce=class extends ht.Modal{constructor(t,e,s,i={}){super(t);this.current=e;this.onPick=s;this.opts=i;this.didChoose=!1;this.assignees=[];this.tinyClosePopover=null;this.assignees=[...i.currentAssignees??[]]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Set due date");let t=null;if(this.current){let v=Date.parse(this.current);Number.isNaN(v)||(t=new Date(v))}let e=this.contentEl.createDiv({cls:"stashpad-due-picker"}),s=e.createDiv({cls:"stashpad-due-fields"}),i=s.createDiv({cls:"stashpad-due-field"}),n=i.createSpan({cls:"stashpad-due-field-icon"});(0,ht.setIcon)(n,"calendar");let r=i.createEl("input",{type:"date",cls:"stashpad-due-date"}),a=s.createDiv({cls:"stashpad-due-field"}),o=a.createSpan({cls:"stashpad-due-field-icon"});(0,ht.setIcon)(o,"clock");let l=a.createEl("input",{type:"time",cls:"stashpad-due-time"});n.onclick=()=>{try{r.showPicker?.()}catch{}},o.onclick=()=>this.openTimeNumpad(o,l),t&&(r.value=this.toDateValue(t),l.value=this.toTimeValue(t)),this.renderAssignSection(e);let c=e.createDiv({cls:"stashpad-due-grid"}),p=(v,y)=>{let b=c.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:v});b.onclick=()=>{let k=y();r.value=this.toDateValue(k),l.value||(l.value=this.toTimeValue(k))}},u=v=>(v.setHours(9,0,0,0),v);p("Today",()=>u(this.startOfTodayLocal())),p("Tomorrow",()=>{let v=this.startOfTodayLocal();return v.setDate(v.getDate()+1),u(v)}),p("Next week",()=>{let v=this.startOfTodayLocal();return v.setDate(v.getDate()+7),u(v)});let h=c.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});h.onclick=()=>{r.value="",l.value="",r.focus()};let f=c.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});f.onclick=()=>{this.didChoose=!0,this.close()};let m=c.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});m.onclick=()=>{if(!r.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[v,y,b]=r.value.split("-").map(E=>parseInt(E,10)),k=9,T=0;if(l.value){let[E,D]=l.value.split(":").map(H=>parseInt(H,10));k=E,T=D}let I=new Date(v,y-1,b,k,T,0,0);this.didChoose=!0,this.close(),this.onPick({iso:I.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>r.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){As(t,{knownAuthors:this.opts.knownAuthors??[],initial:this.assignees,onChange:e=>{this.assignees=e}})}openTimeNumpad(t,e){this.tinyClosePopover?.();let s=9,i=0;if(e.value){let[h,f]=e.value.split(":").map(m=>parseInt(m,10));Number.isFinite(h)&&(s=h),Number.isFinite(f)&&(i=f)}else{let h=new Date;s=h.getHours(),i=h.getMinutes()}let n=s>=12?"pm":"am",r=s===0?12:s>12?s-12:s,a=document.body.createDiv({cls:"stashpad-when-popover stashpad-due-time-pop"});a.style.position="fixed",a.style.zIndex="9999";let o=null,l=()=>{a.remove(),document.removeEventListener("mousedown",c,!0),document.removeEventListener("keydown",p,!0),this.tinyClosePopover===l&&(this.tinyClosePopover=null)},c=h=>{!a.contains(h.target)&&h.target!==t&&!t.contains(h.target)&&l()},p=h=>{h.key==="Escape"?(h.preventDefault(),h.stopPropagation(),l()):h.key==="Enter"&&o&&(h.preventDefault(),h.stopPropagation(),o())};this.tinyClosePopover=l,Be(a,{seedH:r,seedM:i,seedPeriod:n,close:l,setOnEnter:h=>{o=h},onFinalize:h=>{e.value=`${String(h.hours24).padStart(2,"0")}:${String(h.minutes).padStart(2,"0")}`}});let u=t.getBoundingClientRect();a.style.left=`${Math.max(8,Math.min(u.left,window.innerWidth-220))}px`,a.style.top=`${u.bottom+4}px`,setTimeout(()=>{document.addEventListener("mousedown",c,!0),document.addEventListener("keydown",p,!0)},0)}startOfTodayLocal(){let t=new Date;return t.setHours(0,0,0,0),t}toDateValue(t){let e=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${e}-${s}-${i}`}toTimeValue(t){let e=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0");return`${e}:${s}`}},Gt=class Gt extends ht.Modal{constructor(t,e,s,i=null,n){super(t);this.service=e;this.openLog=s;this.currentAuthorId=i;this.getNoteAuthorIds=n;this.records=[];this.visible=[];this.shownCount=0;this.categoryFilter=null;this.listEl=null;this.footerEl=null;this.countEl=null;this.filterSelEl=null;this.unsubscribe=null;this.authorFilter="all";this.authorSelEl=null}onOpen(){this.contentEl.empty(),this.titleEl.setText("Stashpad notification history"),this.modalEl.addClass("stashpad-log-modal"),this.modalEl.addClass("stashpad-notif-history-modal"),this.records=this.service.recent();let t=this.contentEl.createDiv({cls:"stashpad-log-toolbar"});if(this.countEl=t.createSpan({cls:"stashpad-log-count"}),this.updateCount(),this.filterSelEl=t.createEl("select",{cls:"stashpad-log-type-filter"}),this.filterSelEl.onchange=()=>this.setCategoryFilter(this.filterSelEl.value||null),this.refreshCategoryFilter(),this.authorSelEl=t.createEl("select",{cls:"stashpad-log-type-filter stashpad-notif-author-filter"}),this.authorSelEl.onchange=()=>this.setAuthorFilter(this.authorSelEl.value||"all"),this.refreshAuthorFilter(),this.openLog){let s=t.createEl("button",{text:"Open log"});s.title="Open the per-folder Stashpad log for the most recent notification's folder.",s.onclick=()=>{let i=this.records.find(n=>!!n.folder);this.openLog?.(i?.folder)}}let e=t.createEl("button",{cls:"mod-warning",text:"Clear history"});e.onclick=()=>{new At(this.app,"Clear notification history?",`This will permanently remove all ${this.records.length} stored notifications from the history. The current toasts on screen are unaffected. This can't be undone.`,"Clear history",s=>{s&&this.service.clearHistory()}).open()},this.listEl=this.contentEl.createDiv({cls:"stashpad-log-list"}),this.refreshList(),this.footerEl=this.contentEl.createDiv({cls:"stashpad-log-footer"}),this.renderFooter(),this.unsubscribe=this.service.onChange(()=>{this.records=this.service.recent(),this.refreshCategoryFilter(),this.refreshAuthorFilter(),this.refreshList(),this.renderFooter()})}setAuthorFilter(t){this.authorFilter!==t&&(this.authorFilter=t,this.refreshList(),this.renderFooter())}refreshAuthorFilter(){if(!this.authorSelEl)return;let t=this.authorSelEl;t.empty(),t.createEl("option",{text:"All authors"}).value="all",this.currentAuthorId&&(t.createEl("option",{text:"Me"}).value="me"),t.createEl("option",{text:"Cross-author"}).value="cross";let e=new Set;for(let i of this.records)i.authorId&&i.authorId!==this.currentAuthorId&&e.add(i.authorId);if(e.size>0){let i=t.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});i.disabled=!0;for(let n of[...e].sort())t.createEl("option",{text:n}).value=n}new Set(["all","cross",...this.currentAuthorId?["me"]:[],...e]).has(this.authorFilter)||(this.authorFilter="all"),t.value=this.authorFilter}isCrossAuthor(t){let e=t.authorId??null;if(!e)return!1;for(let s of t.affectedAuthorIds??[])if(s&&s!==e)return!0;if(!this.getNoteAuthorIds)return!1;for(let s of t.affectedIds){let i=this.getNoteAuthorIds(s);for(let n of i)if(n&&n!==e)return!0}return!1}onClose(){this.unsubscribe?.(),this.unsubscribe=null,this.contentEl.empty()}setCategoryFilter(t){(this.categoryFilter??null)!==(t??null)&&(this.categoryFilter=t,this.refreshList(),this.renderFooter())}refreshCategoryFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.records)e.set(n.category,(e.get(n.category)??0)+1);let s=[...e.entries()].sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])),i=t.createEl("option",{text:`All categories (${this.records.length})`});i.value="";for(let[n,r]of s){let a=t.createEl("option",{text:`${n} (${r})`});a.value=n}this.categoryFilter&&!e.has(this.categoryFilter)&&(this.categoryFilter=null),t.value=this.categoryFilter??""}refreshList(){if(this.listEl){if(this.visible=this.records.filter(t=>{if(this.categoryFilter&&t.category!==this.categoryFilter)return!1;switch(this.authorFilter){case"all":return!0;case"me":return!!this.currentAuthorId&&t.authorId===this.currentAuthorId;case"cross":return this.isCrossAuthor(t);default:return t.authorId===this.authorFilter}}),this.shownCount=0,this.listEl.empty(),!this.visible.length){this.listEl.createDiv({cls:"stashpad-log-empty",text:this.categoryFilter?`No "${this.categoryFilter}" notifications.`:"No notifications yet."}),this.updateCount();return}this.appendMore(Gt.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let s=this.shownCount;s<e;s++)this.renderRow(this.listEl,this.visible[s]);this.shownCount=e,this.updateCount()}renderRow(t,e){let s=t.createDiv({cls:`stashpad-notif-row stashpad-notif-row-${e.kind}`}),i=s.createDiv({cls:"stashpad-notif-meta"}),n=i.createSpan({cls:"stashpad-notif-time"}),r=(0,ht.moment)(e.ts);if(n.setText(r.fromNow()),n.title=r.format("YYYY-MM-DD HH:mm:ss"),i.createSpan({cls:`stashpad-notif-cat stashpad-notif-cat-${e.category}`}).setText(e.category),s.createDiv({cls:"stashpad-notif-msg"}).setText(e.message),e.actionLabels.length>0){let l=s.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let c of e.actionLabels){let p=l.createSpan({cls:"stashpad-notif-action-chip"});p.setText(c),p.title="Action button was shown on the original toast (handler not retained)."}}}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.categoryFilter?`${t} ${this.categoryFilter} notification${t===1?"":"s"}`:`${t} notification${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}renderFooter(){if(!this.footerEl)return;this.footerEl.empty();let t=this.visible.length-this.shownCount;if(t<=0)return;let e=this.footerEl.createEl("button",{text:`Load ${Math.min(Gt.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Gt.PAGE),this.renderFooter()},t>Gt.PAGE){let s=this.footerEl.createEl("button",{text:`Load all (${t})`});s.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Gt.PAGE=100;Fe=Gt,Is=class extends ht.Modal{constructor(t,e){super(t);this.entries=e}onOpen(){if(this.contentEl.empty(),this.titleEl.setText("Stashpad import log"),this.entries.length===0){this.contentEl.createDiv({cls:"stashpad-log-empty",text:"Nothing imported yet."});return}let t=this.contentEl.createDiv({cls:"stashpad-import-log-list"});for(let e of this.entries){let s=t.createDiv({cls:"stashpad-import-log-row"}),i=(0,ht.moment)(e.ts).format("YYYY-MM-DD HH:mm");s.createSpan({cls:"stashpad-import-log-when",text:i});let n=e.kind==="folder"?"folder":e.kind==="md"?"note":"file";s.createSpan({cls:`stashpad-import-log-kind is-${e.kind}`,text:n}),s.createSpan({cls:"stashpad-import-log-name",text:e.originalName});let r=[e.folder.split("/").pop()||e.folder];e.notePaths.length>1&&r.push(`${e.notePaths.length} notes`),s.createSpan({cls:"stashpad-import-log-meta",text:r.join(" \xB7 ")})}}onClose(){this.contentEl.empty()}},xe=class extends ht.Modal{constructor(t,e,s){super(t);this.message=e;this.onChoose=s;this.chose=!1}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Possible duplicate import");let t=this.contentEl.createDiv({cls:"stashpad-confirm-body"});for(let r of this.message.split(` +`))t.createDiv({cls:"stashpad-confirm-line",text:r});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=e.createEl("button",{text:"Skip duplicates"});s.onclick=()=>{this.chose=!0,this.close(),this.onChoose("skip")};let i=e.createEl("button",{text:"Replace existing"});i.onclick=()=>{this.chose=!0,this.close(),this.onChoose("replace")};let n=e.createEl("button",{cls:"mod-cta",text:"Import anyway"});n.onclick=()=>{this.chose=!0,this.close(),this.onChoose("anyway")}}onClose(){this.chose||this.onChoose("skip"),this.contentEl.empty()}}});function Ft(g,d=_t){let t=d instanceof Set?d:new Set(d.map(r=>r.toLowerCase())),e=(g.split(/\r?\n/).find(r=>r.trim().length>0)??"").trim();if(!e)return"Untitled";let i=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(r=>r&&!t.has(r.toLowerCase())).map(r=>r.length>=2&&/^[A-Z0-9]+$/.test(r)?r:r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()),n="";for(let r of i){let a=n?`${n}-${r}`:r;if(a.length>50)break;n=a}return n||"Untitled"}function xt(g,d){return`${g}-${d}.md`}function re(g){let d=g.match(/-([a-z0-9]{4,12})$/);return d?d[1]:null}var _t,ae=ee(()=>{"use strict";_t=["a","an","the","and","or","but","if","then","else","of","in","on","at","to","for","with","by","from","as","is","are","was","were","be","been","being","i","you","he","she","it","we","they","this","that","these","those","my","your","our","their","do","does","did","so","just","very","really","im"]});var qe={};$e(qe,{JdBuildConfirmModal:()=>Ae,buildJdIndexNotes:()=>Ps,buildJdIndexPreview:()=>Ve,buildJdPreviewNotice:()=>Ye,scanForJdNotes:()=>oe});function Ds(g,d){if(/^\d+-\d+$/.test(g))return null;if(g.includes(".")){let e=g.split(".").slice(0,-1).join(".");return d.has(e)?e:Ds(e,d)}if(/^\d+$/.test(g)){let t=parseInt(g,10);for(let e of d){let s=e.match(/^(\d+)-(\d+)$/);if(!s)continue;let i=parseInt(s[1],10),n=parseInt(s[2],10);if(t>=i&&t<=n)return e}return null}return null}function oe(g,d,t){let e=g.vault.getMarkdownFiles(),s=Yi(e,t),i=t.jdIndexIncludeStashpadFolders===!0,n=i?new Set:new Set(d.discoverStashpadFolders()),r=h=>i?!1:Array.from(n).some(f=>h===f||h.startsWith(f+"/")),a=[],o=[],l=[];for(let h of s){let f=h.parent?.path?.replace(/\/+$/,"")??"";if(r(f)){l.push(h);continue}let m=h.basename.match(oi);m?a.push({prefix:m[1],segments:m[1].split("."),title:m[2],file:h,folder:null}):o.push(h)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",p=h=>{let f=h.path.replace(/\/+$/,"");if(!(c&&f&&f!==c&&!f.startsWith(c+"/"))){if(f&&!r(f)){let m=h.name.match(oi);m&&a.push({prefix:m[1],segments:m[1].split("."),title:m[2],file:null,folder:h})}}for(let m of h.children)m instanceof kt.TFolder&&p(m)};p(g.vault.getRoot());let u=t.jdIndexSort??"natural";return a.sort((h,f)=>qi(h,f,u)),{indexed:a,nonIndex:o,skippedStashpadNotes:l}}async function Ve(g,d,t){let e=Ms(t.jdIndexStashpadFolder??"");if(!e)return{...oe(g,d,t),previewPath:null,error:"no-dest"};let s=oe(g,d,t),i=Vi(g,e);if(!i)return{...s,previewPath:null,error:"no-home"};let n=Ki(s.indexed,s.nonIndex,s.skippedStashpadNotes),a=(await g.vault.read(i)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),o=a?`${a[0]}${n}`:n;return await g.vault.modify(i,o),{...s,previewPath:i.path}}function Vi(g,d){let t=g.vault.getAbstractFileByPath(d);if(!(t instanceof kt.TFolder))return null;for(let e of t.children){if(!(e instanceof kt.TFile)||e.extension!=="md")continue;if((g.metadataCache.getFileCache(e)?.frontmatter??{}).id===R)return e}return null}async function Ps(g,d,t){let e=Ms(t.jdIndexStashpadFolder??"");if(!e)return{created:0,updated:0,skipped:0,destFolder:"",error:"no-dest"};if(!new Set(d.discoverStashpadFolders()).has(e))return{created:0,updated:0,skipped:0,destFolder:e,error:"dest-not-stashpad"};let i=oe(g,d,t),n=new Map;for(let v of i.indexed)n.set(v.prefix,v);for(let v of i.indexed)if(v.prefix.includes("."))for(let y=1;y<v.segments.length;y++){let b=v.segments.slice(0,y).join(".");n.has(b)||n.set(b,null)}let{roots:r,childrenOf:a}=di(n),o=[],l=v=>{o.push(v);for(let y of a.get(v)??[])l(y)};for(let v of r)l(v);let c=new Map,p=g.vault.getAbstractFileByPath(e);if(p instanceof kt.TFolder)for(let v of p.children){if(!(v instanceof kt.TFile)||v.extension!=="md")continue;let y=g.metadataCache.getFileCache(v)?.frontmatter??{};typeof y.jdPrefix=="string"&&c.set(y.jdPrefix,v)}let u=new Map,h=0,f=0,m=0;for(let v of o){let y=n.get(v)??null,b=Ds(v,new Set(n.keys())),k=b?u.get(b)??R:R,T=y?`${v} ${y.title}`:v,I=y?.file?`[[${y.file.basename}]]`:"",E=I?`${I} +`:`${T} +`,D=c.get(v);if(D){try{let H=null;await g.fileManager.processFrontMatter(D,_=>{_.jdPrefix=v,k&&(_.parent=k),(!_.id||typeof _.id!="string")&&(_.id=yt()),_.created||(_.created=new Date().toISOString()),_.attachments||(_.attachments=[]),H=_.id});let A=(await g.vault.read(D)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),S=A?`${A[0]}${E}`:E;await g.vault.modify(D,S),H&&u.set(v,H),f++}catch(H){console.error("[stashpad] buildJdIndexNotes: update failed",H),m++}continue}try{let H=yt();u.set(v,H);let C=Ft(T,t.slugStopWords),A=xt(C,H),S=`${e}/${A}`,_=["---",`id: ${H}`,`parent: ${k}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${v}"`,"---",""].join(` +`);await g.vault.create(S,_+E),h++}catch(H){console.error("[stashpad] buildJdIndexNotes: create failed for",v,H),m++}}return{created:h,updated:f,skipped:m,destFolder:e}}function Ms(g){return(g||"").trim().replace(/^\/+|\/+$/g,"")}function Yi(g,d){if((d.jdIndexScope??"vault")==="vault")return g;let t=Ms(d.jdIndexScopeFolder??"");return t?g.filter(e=>{let s=e.parent?.path?.replace(/\/+$/,"")??"";return s===t||s.startsWith(t+"/")}):g}function qi(g,d,t){if(t==="created"){let e=g.file.stat?.ctime??0,s=d.file.stat?.ctime??0;if(e!==s)return e-s}return ci(g.segments,d.segments)}function li(g,d){let t=g.match(/^(\d+)-(\d+)$/),e=d.match(/^(\d+)-(\d+)$/),s=t?[t[1]]:g.split("."),i=e?[e[1]]:d.split(".");return ci(s,i)}function ci(g,d){let t=Math.min(g.length,d.length);for(let e=0;e<t;e++){let s=g[e],i=d[e],n=/^\d+$/.test(s),r=/^\d+$/.test(i);if(n&&r){let a=parseInt(s,10)-parseInt(i,10);if(a!==0)return a}else{if(n&&!r)return-1;if(!n&&r)return 1;{let a=s.localeCompare(i,void 0,{numeric:!0,sensitivity:"base"});if(a!==0)return a}}}return g.length-d.length}function di(g){let d=new Set(g.keys()),t=new Map,e=new Map;for(let r of d){let a=Ds(r,d);if(t.set(r,a),a!==null){let o=e.get(a)??[];o.push(r),e.set(a,o)}}let s=[];for(let r of d)t.get(r)===null&&s.push(r);s.sort(li);for(let r of e.values())r.sort(li);let i=new Map,n=(r,a)=>{i.set(r,a);for(let o of e.get(r)??[])n(o,a+1)};for(let r of s)n(r,0);return{roots:s,childrenOf:e,depthOf:i}}function Ki(g,d,t){let e=[],s=i=>"#".repeat(Math.min(i+1,6));if(e.push("# Indexed"),e.push(""),g.length===0){let i=t.length>0?`_No notes matched. ${t.length} note${t.length===1?" was":"s were"} excluded because they live inside a Stashpad folder \u2014 toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder if you want them included._`:"_No notes matched the JD-prefix convention. Check Scope and Designated folder in Settings \u2192 JD Index Builder._";e.push(i)}else{let i=new Map;for(let l of g)i.set(l.prefix,l);for(let l of g)if(l.prefix.includes("."))for(let c=1;c<l.segments.length;c++){let p=l.segments.slice(0,c).join(".");i.has(p)||i.set(p,null)}let{roots:n,childrenOf:r,depthOf:a}=di(i),o=l=>{let c=i.get(l),p=a.get(l)??0,u=" ".repeat(p),h=s(p),f=c?.folder?` ${c.title} _(folder)_`:(c?.file,"");c?.file?e.push(`${u}- ${h} [[${c.file.basename}|${c.prefix} ${c.title}]]`):c?.folder?e.push(`${u}- ${h} ${c.prefix}${f}`):e.push(`${u}- ${h} ${l}`);for(let m of r.get(l)??[])o(m)};for(let l of n)o(l)}if(d.length>0){e.push(""),e.push(`# Non-indexed (${d.length})`),e.push(""),e.push("_These notes don't match the JD-prefix convention. Rename them to `<prefix> <title>` and re-run to include them._"),e.push("");for(let i of d)e.push(`- # [[${i.basename}]] \xB7 \`${i.path}\``)}if(t.length>0){let i=new Map;for(let r of t){let a=r.parent?.path?.replace(/\/+$/,"")??"";i.set(a,(i.get(a)??0)+1)}let n=Array.from(i.entries()).sort((r,a)=>r[0].localeCompare(a[0]));e.push(""),e.push(`# Excluded folders (${n.length})`),e.push(""),e.push(`_Stashpad folders are excluded by default so the index doesn't reference itself. Toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder to include them._`),e.push("");for(let[r,a]of n)e.push(`- # All ${a} file${a===1?"":"s"} in \`${r||"(vault root)"}\``)}return e.join(` `)+` -`}function ze(g,h){let t=document.createDocumentFragment(),e=t.createEl("div",{text:"Home note updated"});e.style.fontWeight="600",e.style.marginBottom="6px";let s=t.createEl("ul");s.style.margin="0 0 8px 0",s.style.paddingLeft="18px",s.createEl("li",{text:`${h.indexed.length} indexed`}),s.createEl("li",{text:`${h.nonIndex.length+h.skippedStashpadNotes.length} excluded`});let i=t.createEl("button",{text:"Open",cls:"mod-cta"});i.style.padding="2px 10px",i.style.fontSize="var(--font-ui-smaller)";let n;return i.onclick=async r=>{if(r.stopPropagation(),h.previewPath){let o=g.vault.getAbstractFileByPath(h.previewPath);o instanceof kt.TFile&&await g.workspace.getLeaf("tab").openFile(o)}n?.hide()},n=new kt.Notice(t,0),n}var kt,si,ke,Te=Xt(()=>{"use strict";kt=require("obsidian");Pt();se();Tt();si=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;ke=class extends kt.Modal{constructor(t,e,s,i,n){super(t);this.plugin=e;this.settings=s;this.indexedCount=i;this.onBuild=n;this.LARGE_BUILD=50;this.previewRan=!1;this.previewPath=null}onOpen(){let{contentEl:t,titleEl:e}=this,s=!this.settings.jdIndexHasBuilt,i=this.indexedCount>this.LARGE_BUILD;e.setText(s?"Build JD index \u2014 first time?":"Build JD index");let n=this.settings.jdIndexStashpadFolder,r=t.createEl("p"),o=`${this.indexedCount} note${this.indexedCount===1?"":"s"}`;s?(r.appendText(`Stashpad is about to create ${o} (plus synthetic parents as needed) inside "`),r.createEl("code",{text:n}),r.appendText('". Existing notes with the same '),r.createEl("code",{text:"jdPrefix"}),r.appendText(" are updated, never deleted \u2014 but if the prefix detection picks up notes you didn't mean to index, you'll end up with a lot of unwanted notes."),t.createEl("p").setText("Running Preview first writes a single Markdown file showing exactly what would be built (and what wouldn't), so you can sanity-check before committing.")):i?(r.appendText(`You're about to create ${this.indexedCount} notes in "`),r.createEl("code",{text:n}),r.appendText(`". That's a big batch \u2014 if anything looks off, Preview the single-file output first.`)):(r.appendText('Build the JD index into "'),r.createEl("code",{text:n}),r.appendText(`"? Stashpad will create / update ${o}. Existing notes with matching `),r.createEl("code",{text:"jdPrefix"}),r.appendText(" are updated in place.")),this.previewRan&&this.previewPath&&t.createEl("p",{cls:"setting-item-description"}).setText(`\u2713 Preview written to home note (${this.previewPath}). Open it before building if you haven't.`);let a=new kt.Setting(t);(s||i)&&a.addButton(l=>{l.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),l.setCta(),l.onClick(async()=>{try{let c=await He(this.app,this.plugin,this.settings);if(c.error==="no-dest"){new kt.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(c.error==="no-home"){new kt.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first.`,7e3),this.close();return}this.previewRan=!0,this.previewPath=c.previewPath,ze(this.app,c),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(c){new kt.Notice(`Preview failed: ${c?.message??c}`,8e3)}})}),a.addButton(l=>{l.setButtonText(s?"Build anyway":"Build"),!s&&!i&&l.setCta(),l.onClick(async()=>{this.close(),await this.onBuild()})}),a.addButton(l=>{l.setButtonText("Cancel"),l.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});var yi=Ni((vi,Rs)=>{(function(g){typeof vi=="object"&&typeof Rs<"u"?Rs.exports=g():typeof define=="function"&&define.amd?define([],g):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=g()})(function(){return function g(h,t,e){function s(r,o){if(!t[r]){if(!h[r]){var a=typeof require=="function"&&require;if(!o&&a)return a(r,!0);if(i)return i(r,!0);var l=new Error("Cannot find module '"+r+"'");throw l.code="MODULE_NOT_FOUND",l}var c=t[r]={exports:{}};h[r][0].call(c.exports,function(p){var u=h[r][1][p];return s(u||p)},c,c.exports,g,h,t,e)}return t[r].exports}for(var i=typeof require=="function"&&require,n=0;n<e.length;n++)s(e[n]);return s}({1:[function(g,h,t){"use strict";var e=g("./utils"),s=g("./support"),i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var r,o,a,l,c,p,u,d=[],f=0,m=n.length,v=m,y=e.getTypeOf(n)!=="string";f<n.length;)v=m-f,a=y?(r=n[f++],o=f<m?n[f++]:0,f<m?n[f++]:0):(r=n.charCodeAt(f++),o=f<m?n.charCodeAt(f++):0,f<m?n.charCodeAt(f++):0),l=r>>2,c=(3&r)<<4|o>>4,p=1<v?(15&o)<<2|a>>6:64,u=2<v?63&a:64,d.push(i.charAt(l)+i.charAt(c)+i.charAt(p)+i.charAt(u));return d.join("")},t.decode=function(n){var r,o,a,l,c,p,u=0,d=0,f="data:";if(n.substr(0,f.length)===f)throw new Error("Invalid base64 input, it looks like a data url.");var m,v=3*(n=n.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(n.charAt(n.length-1)===i.charAt(64)&&v--,n.charAt(n.length-2)===i.charAt(64)&&v--,v%1!=0)throw new Error("Invalid base64 input, bad content length.");for(m=s.uint8array?new Uint8Array(0|v):new Array(0|v);u<n.length;)r=i.indexOf(n.charAt(u++))<<2|(l=i.indexOf(n.charAt(u++)))>>4,o=(15&l)<<4|(c=i.indexOf(n.charAt(u++)))>>2,a=(3&c)<<6|(p=i.indexOf(n.charAt(u++))),m[d++]=r,c!==64&&(m[d++]=o),p!==64&&(m[d++]=a);return m}},{"./support":30,"./utils":32}],2:[function(g,h,t){"use strict";var e=g("./external"),s=g("./stream/DataWorker"),i=g("./stream/Crc32Probe"),n=g("./stream/DataLengthProbe");function r(o,a,l,c,p){this.compressedSize=o,this.uncompressedSize=a,this.crc32=l,this.compression=c,this.compressedContent=p}r.prototype={getContentWorker:function(){var o=new s(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),a=this;return o.on("end",function(){if(this.streamInfo.data_length!==a.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),o},getCompressedWorker:function(){return new s(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},r.createWorkerFrom=function(o,a,l){return o.pipe(new i).pipe(new n("uncompressedSize")).pipe(a.compressWorker(l)).pipe(new n("compressedSize")).withStreamInfo("compression",a)},h.exports=r},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(g,h,t){"use strict";var e=g("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=g("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(g,h,t){"use strict";var e=g("./utils"),s=function(){for(var i,n=[],r=0;r<256;r++){i=r;for(var o=0;o<8;o++)i=1&i?3988292384^i>>>1:i>>>1;n[r]=i}return n}();h.exports=function(i,n){return i!==void 0&&i.length?e.getTypeOf(i)!=="string"?function(r,o,a,l){var c=s,p=l+a;r^=-1;for(var u=l;u<p;u++)r=r>>>8^c[255&(r^o[u])];return-1^r}(0|n,i,i.length,0):function(r,o,a,l){var c=s,p=l+a;r^=-1;for(var u=l;u<p;u++)r=r>>>8^c[255&(r^o.charCodeAt(u))];return-1^r}(0|n,i,i.length,0):0}},{"./utils":32}],5:[function(g,h,t){"use strict";t.base64=!1,t.binary=!1,t.dir=!1,t.createFolders=!0,t.date=null,t.compression=null,t.compressionOptions=null,t.comment=null,t.unixPermissions=null,t.dosPermissions=null},{}],6:[function(g,h,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:g("lie"),h.exports={Promise:e}},{lie:37}],7:[function(g,h,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",s=g("pako"),i=g("./utils"),n=g("./stream/GenericWorker"),r=e?"uint8array":"array";function o(a,l){n.call(this,"FlateWorker/"+a),this._pako=null,this._pakoAction=a,this._pakoOptions=l,this.meta={}}t.magic="\b\0",i.inherits(o,n),o.prototype.processChunk=function(a){this.meta=a.meta,this._pako===null&&this._createPako(),this._pako.push(i.transformTo(r,a.data),!1)},o.prototype.flush=function(){n.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},o.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this._pako=null},o.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var a=this;this._pako.onData=function(l){a.push({data:l,meta:a.meta})}},t.compressWorker=function(a){return new o("Deflate",a)},t.uncompressWorker=function(){return new o("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(g,h,t){"use strict";function e(c,p){var u,d="";for(u=0;u<p;u++)d+=String.fromCharCode(255&c),c>>>=8;return d}function s(c,p,u,d,f,m){var v,y,b=c.file,k=c.compression,C=m!==r.utf8encode,I=i.transformTo("string",m(b.name)),E=i.transformTo("string",r.utf8encode(b.name)),D=b.comment,H=i.transformTo("string",m(D)),T=i.transformTo("string",r.utf8encode(D)),A=E.length!==b.name.length,S=T.length!==D.length,_="",J="",U="",z=b.dir,W=b.date,Q={crc32:0,compressedSize:0,uncompressedSize:0};p&&!u||(Q.crc32=c.crc32,Q.compressedSize=c.compressedSize,Q.uncompressedSize=c.uncompressedSize);var N=0;p&&(N|=8),C||!A&&!S||(N|=2048);var P=0,X=0;z&&(P|=16),f==="UNIX"?(X=798,P|=function(Y,ct){var pt=Y;return Y||(pt=ct?16893:33204),(65535&pt)<<16}(b.unixPermissions,z)):(X=20,P|=function(Y){return 63&(Y||0)}(b.dosPermissions)),v=W.getUTCHours(),v<<=6,v|=W.getUTCMinutes(),v<<=5,v|=W.getUTCSeconds()/2,y=W.getUTCFullYear()-1980,y<<=4,y|=W.getUTCMonth()+1,y<<=5,y|=W.getUTCDate(),A&&(J=e(1,1)+e(o(I),4)+E,_+="up"+e(J.length,2)+J),S&&(U=e(1,1)+e(o(H),4)+T,_+="uc"+e(U.length,2)+U);var q="";return q+=` -\0`,q+=e(N,2),q+=k.magic,q+=e(v,2),q+=e(y,2),q+=e(Q.crc32,4),q+=e(Q.compressedSize,4),q+=e(Q.uncompressedSize,4),q+=e(I.length,2),q+=e(_.length,2),{fileRecord:a.LOCAL_FILE_HEADER+q+I+_,dirRecord:a.CENTRAL_FILE_HEADER+e(X,2)+q+e(H.length,2)+"\0\0\0\0"+e(P,4)+e(d,4)+I+_+H}}var i=g("../utils"),n=g("../stream/GenericWorker"),r=g("../utf8"),o=g("../crc32"),a=g("../signature");function l(c,p,u,d){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=p,this.zipPlatform=u,this.encodeFileName=d,this.streamFiles=c,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}i.inherits(l,n),l.prototype.push=function(c){var p=c.meta.percent||0,u=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(c):(this.bytesWritten+=c.data.length,n.prototype.push.call(this,{data:c.data,meta:{currentFile:this.currentFile,percent:u?(p+100*(u-d-1))/u:100}}))},l.prototype.openedSource=function(c){this.currentSourceOffset=this.bytesWritten,this.currentFile=c.file.name;var p=this.streamFiles&&!c.file.dir;if(p){var u=s(c,p,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:u.fileRecord,meta:{percent:0}})}else this.accumulate=!0},l.prototype.closedSource=function(c){this.accumulate=!1;var p=this.streamFiles&&!c.file.dir,u=s(c,p,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(u.dirRecord),p)this.push({data:function(d){return a.DATA_DESCRIPTOR+e(d.crc32,4)+e(d.compressedSize,4)+e(d.uncompressedSize,4)}(c),meta:{percent:100}});else for(this.push({data:u.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},l.prototype.flush=function(){for(var c=this.bytesWritten,p=0;p<this.dirRecords.length;p++)this.push({data:this.dirRecords[p],meta:{percent:100}});var u=this.bytesWritten-c,d=function(f,m,v,y,b){var k=i.transformTo("string",b(y));return a.CENTRAL_DIRECTORY_END+"\0\0\0\0"+e(f,2)+e(f,2)+e(m,4)+e(v,4)+e(k.length,2)+k}(this.dirRecords.length,u,c,this.zipComment,this.encodeFileName);this.push({data:d,meta:{percent:100}})},l.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},l.prototype.registerPrevious=function(c){this._sources.push(c);var p=this;return c.on("data",function(u){p.processChunk(u)}),c.on("end",function(){p.closedSource(p.previous.streamInfo),p._sources.length?p.prepareNextSource():p.end()}),c.on("error",function(u){p.error(u)}),this},l.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},l.prototype.error=function(c){var p=this._sources;if(!n.prototype.error.call(this,c))return!1;for(var u=0;u<p.length;u++)try{p[u].error(c)}catch{}return!0},l.prototype.lock=function(){n.prototype.lock.call(this);for(var c=this._sources,p=0;p<c.length;p++)c[p].lock()},h.exports=l},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(g,h,t){"use strict";var e=g("../compressions"),s=g("./ZipFileWorker");t.generateWorker=function(i,n,r){var o=new s(n.streamFiles,r,n.platform,n.encodeFileName),a=0;try{i.forEach(function(l,c){a++;var p=function(m,v){var y=m||v,b=e[y];if(!b)throw new Error(y+" is not a valid compression method !");return b}(c.options.compression,n.compression),u=c.options.compressionOptions||n.compressionOptions||{},d=c.dir,f=c.date;c._compressWorker(p,u).withStreamInfo("file",{name:l,dir:d,date:f,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(o)}),o.entriesCount=a}catch(l){o.error(l)}return o}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(g,h,t){"use strict";function e(){if(!(this instanceof e))return new e;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var s=new e;for(var i in this)typeof this[i]!="function"&&(s[i]=this[i]);return s}}(e.prototype=g("./object")).loadAsync=g("./load"),e.support=g("./support"),e.defaults=g("./defaults"),e.version="3.10.1",e.loadAsync=function(s,i){return new e().loadAsync(s,i)},e.external=g("./external"),h.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(g,h,t){"use strict";var e=g("./utils"),s=g("./external"),i=g("./utf8"),n=g("./zipEntries"),r=g("./stream/Crc32Probe"),o=g("./nodejsUtils");function a(l){return new s.Promise(function(c,p){var u=l.decompressed.getContentWorker().pipe(new r);u.on("error",function(d){p(d)}).on("end",function(){u.streamInfo.crc32!==l.decompressed.crc32?p(new Error("Corrupted zip : CRC32 mismatch")):c()}).resume()})}h.exports=function(l,c){var p=this;return c=e.extend(c||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:i.utf8decode}),o.isNode&&o.isStream(l)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):e.prepareContent("the loaded zip file",l,!0,c.optimizedBinaryString,c.base64).then(function(u){var d=new n(c);return d.load(u),d}).then(function(u){var d=[s.Promise.resolve(u)],f=u.files;if(c.checkCRC32)for(var m=0;m<f.length;m++)d.push(a(f[m]));return s.Promise.all(d)}).then(function(u){for(var d=u.shift(),f=d.files,m=0;m<f.length;m++){var v=f[m],y=v.fileNameStr,b=e.resolve(v.fileNameStr);p.file(b,v.decompressed,{binary:!0,optimizedBinaryString:!0,date:v.date,dir:v.dir,comment:v.fileCommentStr.length?v.fileCommentStr:null,unixPermissions:v.unixPermissions,dosPermissions:v.dosPermissions,createFolders:c.createFolders}),v.dir||(p.file(b).unsafeOriginalName=y)}return d.zipComment.length&&(p.comment=d.zipComment),p})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(g,h,t){"use strict";var e=g("../utils"),s=g("../stream/GenericWorker");function i(n,r){s.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(r)}e.inherits(i,s),i.prototype._bindStream=function(n){var r=this;(this._stream=n).pause(),n.on("data",function(o){r.push({data:o,meta:{percent:0}})}).on("error",function(o){r.isPaused?this.generatedError=o:r.error(o)}).on("end",function(){r.isPaused?r._upstreamEnded=!0:r.end()})},i.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},i.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},h.exports=i},{"../stream/GenericWorker":28,"../utils":32}],13:[function(g,h,t){"use strict";var e=g("readable-stream").Readable;function s(i,n,r){e.call(this,n),this._helper=i;var o=this;i.on("data",function(a,l){o.push(a)||o._helper.pause(),r&&r(l)}).on("error",function(a){o.emit("error",a)}).on("end",function(){o.push(null)})}g("../utils").inherits(s,e),s.prototype._read=function(){this._helper.resume()},h.exports=s},{"../utils":32,"readable-stream":16}],14:[function(g,h,t){"use strict";h.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,s){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,s);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,s)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var s=new Buffer(e);return s.fill(0),s},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}}},{}],15:[function(g,h,t){"use strict";function e(b,k,C){var I,E=i.getTypeOf(k),D=i.extend(C||{},o);D.date=D.date||new Date,D.compression!==null&&(D.compression=D.compression.toUpperCase()),typeof D.unixPermissions=="string"&&(D.unixPermissions=parseInt(D.unixPermissions,8)),D.unixPermissions&&16384&D.unixPermissions&&(D.dir=!0),D.dosPermissions&&16&D.dosPermissions&&(D.dir=!0),D.dir&&(b=f(b)),D.createFolders&&(I=d(b))&&m.call(this,I,!0);var H=E==="string"&&D.binary===!1&&D.base64===!1;C&&C.binary!==void 0||(D.binary=!H),(k instanceof a&&k.uncompressedSize===0||D.dir||!k||k.length===0)&&(D.base64=!1,D.binary=!0,k="",D.compression="STORE",E="string");var T=null;T=k instanceof a||k instanceof n?k:p.isNode&&p.isStream(k)?new u(b,k):i.prepareContent(b,k,D.binary,D.optimizedBinaryString,D.base64);var A=new l(b,T,D);this.files[b]=A}var s=g("./utf8"),i=g("./utils"),n=g("./stream/GenericWorker"),r=g("./stream/StreamHelper"),o=g("./defaults"),a=g("./compressedObject"),l=g("./zipObject"),c=g("./generate"),p=g("./nodejsUtils"),u=g("./nodejs/NodejsStreamInputAdapter"),d=function(b){b.slice(-1)==="/"&&(b=b.substring(0,b.length-1));var k=b.lastIndexOf("/");return 0<k?b.substring(0,k):""},f=function(b){return b.slice(-1)!=="/"&&(b+="/"),b},m=function(b,k){return k=k!==void 0?k:o.createFolders,b=f(b),this.files[b]||e.call(this,b,null,{dir:!0,createFolders:k}),this.files[b]};function v(b){return Object.prototype.toString.call(b)==="[object RegExp]"}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(b){var k,C,I;for(k in this.files)I=this.files[k],(C=k.slice(this.root.length,k.length))&&k.slice(0,this.root.length)===this.root&&b(C,I)},filter:function(b){var k=[];return this.forEach(function(C,I){b(C,I)&&k.push(I)}),k},file:function(b,k,C){if(arguments.length!==1)return b=this.root+b,e.call(this,b,k,C),this;if(v(b)){var I=b;return this.filter(function(D,H){return!H.dir&&I.test(D)})}var E=this.files[this.root+b];return E&&!E.dir?E:null},folder:function(b){if(!b)return this;if(v(b))return this.filter(function(E,D){return D.dir&&b.test(E)});var k=this.root+b,C=m.call(this,k),I=this.clone();return I.root=C.name,I},remove:function(b){b=this.root+b;var k=this.files[b];if(k||(b.slice(-1)!=="/"&&(b+="/"),k=this.files[b]),k&&!k.dir)delete this.files[b];else for(var C=this.filter(function(E,D){return D.name.slice(0,b.length)===b}),I=0;I<C.length;I++)delete this.files[C[I].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(b){var k,C={};try{if((C=i.extend(b||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=C.type.toLowerCase(),C.compression=C.compression.toUpperCase(),C.type==="binarystring"&&(C.type="string"),!C.type)throw new Error("No output type specified.");i.checkSupport(C.type),C.platform!=="darwin"&&C.platform!=="freebsd"&&C.platform!=="linux"&&C.platform!=="sunos"||(C.platform="UNIX"),C.platform==="win32"&&(C.platform="DOS");var I=C.comment||this.comment||"";k=c.generateWorker(this,C,I)}catch(E){(k=new n("error")).error(E)}return new r(k,C.type||"string",C.mimeType)},generateAsync:function(b,k){return this.generateInternalStream(b).accumulate(k)},generateNodeStream:function(b,k){return(b=b||{}).type||(b.type="nodebuffer"),this.generateInternalStream(b).toNodejsStream(k)}};h.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(g,h,t){"use strict";h.exports=g("stream")},{stream:void 0}],17:[function(g,h,t){"use strict";var e=g("./DataReader");function s(i){e.call(this,i);for(var n=0;n<this.data.length;n++)i[n]=255&i[n]}g("../utils").inherits(s,e),s.prototype.byteAt=function(i){return this.data[this.zero+i]},s.prototype.lastIndexOfSignature=function(i){for(var n=i.charCodeAt(0),r=i.charCodeAt(1),o=i.charCodeAt(2),a=i.charCodeAt(3),l=this.length-4;0<=l;--l)if(this.data[l]===n&&this.data[l+1]===r&&this.data[l+2]===o&&this.data[l+3]===a)return l-this.zero;return-1},s.prototype.readAndCheckSignature=function(i){var n=i.charCodeAt(0),r=i.charCodeAt(1),o=i.charCodeAt(2),a=i.charCodeAt(3),l=this.readData(4);return n===l[0]&&r===l[1]&&o===l[2]&&a===l[3]},s.prototype.readData=function(i){if(this.checkOffset(i),i===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,n},h.exports=s},{"../utils":32,"./DataReader":18}],18:[function(g,h,t){"use strict";var e=g("../utils");function s(i){this.data=i,this.length=i.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(i){this.checkIndex(this.index+i)},checkIndex:function(i){if(this.length<this.zero+i||i<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+i+"). Corrupted zip ?")},setIndex:function(i){this.checkIndex(i),this.index=i},skip:function(i){this.setIndex(this.index+i)},byteAt:function(){},readInt:function(i){var n,r=0;for(this.checkOffset(i),n=this.index+i-1;n>=this.index;n--)r=(r<<8)+this.byteAt(n);return this.index+=i,r},readString:function(i){return e.transformTo("string",this.readData(i))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var i=this.readInt(4);return new Date(Date.UTC(1980+(i>>25&127),(i>>21&15)-1,i>>16&31,i>>11&31,i>>5&63,(31&i)<<1))}},h.exports=s},{"../utils":32}],19:[function(g,h,t){"use strict";var e=g("./Uint8ArrayReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.readData=function(i){this.checkOffset(i);var n=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,n},h.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(g,h,t){"use strict";var e=g("./DataReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.byteAt=function(i){return this.data.charCodeAt(this.zero+i)},s.prototype.lastIndexOfSignature=function(i){return this.data.lastIndexOf(i)-this.zero},s.prototype.readAndCheckSignature=function(i){return i===this.readData(4)},s.prototype.readData=function(i){this.checkOffset(i);var n=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,n},h.exports=s},{"../utils":32,"./DataReader":18}],21:[function(g,h,t){"use strict";var e=g("./ArrayReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.readData=function(i){if(this.checkOffset(i),i===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+i);return this.index+=i,n},h.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(g,h,t){"use strict";var e=g("../utils"),s=g("../support"),i=g("./ArrayReader"),n=g("./StringReader"),r=g("./NodeBufferReader"),o=g("./Uint8ArrayReader");h.exports=function(a){var l=e.getTypeOf(a);return e.checkSupport(l),l!=="string"||s.uint8array?l==="nodebuffer"?new r(a):s.uint8array?new o(e.transformTo("uint8array",a)):new i(e.transformTo("array",a)):new n(a)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(g,h,t){"use strict";t.LOCAL_FILE_HEADER="PK",t.CENTRAL_FILE_HEADER="PK",t.CENTRAL_DIRECTORY_END="PK",t.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",t.ZIP64_CENTRAL_DIRECTORY_END="PK",t.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(g,h,t){"use strict";var e=g("./GenericWorker"),s=g("../utils");function i(n){e.call(this,"ConvertWorker to "+n),this.destType=n}s.inherits(i,e),i.prototype.processChunk=function(n){this.push({data:s.transformTo(this.destType,n.data),meta:n.meta})},h.exports=i},{"../utils":32,"./GenericWorker":28}],25:[function(g,h,t){"use strict";var e=g("./GenericWorker"),s=g("../crc32");function i(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}g("../utils").inherits(i,e),i.prototype.processChunk=function(n){this.streamInfo.crc32=s(n.data,this.streamInfo.crc32||0),this.push(n)},h.exports=i},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(g,h,t){"use strict";var e=g("../utils"),s=g("./GenericWorker");function i(n){s.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}e.inherits(i,s),i.prototype.processChunk=function(n){if(n){var r=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=r+n.data.length}s.prototype.processChunk.call(this,n)},h.exports=i},{"../utils":32,"./GenericWorker":28}],27:[function(g,h,t){"use strict";var e=g("../utils"),s=g("./GenericWorker");function i(n){s.call(this,"DataWorker");var r=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(o){r.dataIsReady=!0,r.data=o,r.max=o&&o.length||0,r.type=e.getTypeOf(o),r.isPaused||r._tickAndRepeat()},function(o){r.error(o)})}e.inherits(i,s),i.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},i.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},i.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},i.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,r=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":n=this.data.substring(this.index,r);break;case"uint8array":n=this.data.subarray(this.index,r);break;case"array":case"nodebuffer":n=this.data.slice(this.index,r)}return this.index=r,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},h.exports=i},{"../utils":32,"./GenericWorker":28}],28:[function(g,h,t){"use strict";function e(s){this.name=s||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}e.prototype={push:function(s){this.emit("data",s)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(s){this.emit("error",s)}return!0},error:function(s){return!this.isFinished&&(this.isPaused?this.generatedError=s:(this.isFinished=!0,this.emit("error",s),this.previous&&this.previous.error(s),this.cleanUp()),!0)},on:function(s,i){return this._listeners[s].push(i),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(s,i){if(this._listeners[s])for(var n=0;n<this._listeners[s].length;n++)this._listeners[s][n].call(this,i)},pipe:function(s){return s.registerPrevious(this)},registerPrevious:function(s){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=s.streamInfo,this.mergeStreamInfo(),this.previous=s;var i=this;return s.on("data",function(n){i.processChunk(n)}),s.on("end",function(){i.end()}),s.on("error",function(n){i.error(n)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var s=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),s=!0),this.previous&&this.previous.resume(),!s},flush:function(){},processChunk:function(s){this.push(s)},withStreamInfo:function(s,i){return this.extraStreamInfo[s]=i,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var s in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,s)&&(this.streamInfo[s]=this.extraStreamInfo[s])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var s="Worker "+this.name;return this.previous?this.previous+" -> "+s:s}},h.exports=e},{}],29:[function(g,h,t){"use strict";var e=g("../utils"),s=g("./ConvertWorker"),i=g("./GenericWorker"),n=g("../base64"),r=g("../support"),o=g("../external"),a=null;if(r.nodestream)try{a=g("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(p,u){return new o.Promise(function(d,f){var m=[],v=p._internalType,y=p._outputType,b=p._mimeType;p.on("data",function(k,C){m.push(k),u&&u(C)}).on("error",function(k){m=[],f(k)}).on("end",function(){try{var k=function(C,I,E){switch(C){case"blob":return e.newBlob(e.transformTo("arraybuffer",I),E);case"base64":return n.encode(I);default:return e.transformTo(C,I)}}(y,function(C,I){var E,D=0,H=null,T=0;for(E=0;E<I.length;E++)T+=I[E].length;switch(C){case"string":return I.join("");case"array":return Array.prototype.concat.apply([],I);case"uint8array":for(H=new Uint8Array(T),E=0;E<I.length;E++)H.set(I[E],D),D+=I[E].length;return H;case"nodebuffer":return Buffer.concat(I);default:throw new Error("concat : unsupported type '"+C+"'")}}(v,m),b);d(k)}catch(C){f(C)}m=[]}).resume()})}function c(p,u,d){var f=u;switch(u){case"blob":case"arraybuffer":f="uint8array";break;case"base64":f="string"}try{this._internalType=f,this._outputType=u,this._mimeType=d,e.checkSupport(f),this._worker=p.pipe(new s(f)),p.lock()}catch(m){this._worker=new i("error"),this._worker.error(m)}}c.prototype={accumulate:function(p){return l(this,p)},on:function(p,u){var d=this;return p==="data"?this._worker.on(p,function(f){u.call(d,f.data,f.meta)}):this._worker.on(p,function(){e.delay(u,arguments,d)}),this},resume:function(){return e.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(p){if(e.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new a(this,{objectMode:this._outputType!=="nodebuffer"},p)}},h.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(g,h,t){"use strict";if(t.base64=!0,t.array=!0,t.string=!0,t.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",t.nodebuffer=typeof Buffer<"u",t.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")t.blob=!1;else{var e=new ArrayBuffer(0);try{t.blob=new Blob([e],{type:"application/zip"}).size===0}catch{try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(e),t.blob=s.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!g("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(g,h,t){"use strict";for(var e=g("./utils"),s=g("./support"),i=g("./nodejsUtils"),n=g("./stream/GenericWorker"),r=new Array(256),o=0;o<256;o++)r[o]=252<=o?6:248<=o?5:240<=o?4:224<=o?3:192<=o?2:1;r[254]=r[254]=1;function a(){n.call(this,"utf-8 decode"),this.leftOver=null}function l(){n.call(this,"utf-8 encode")}t.utf8encode=function(c){return s.nodebuffer?i.newBufferFrom(c,"utf-8"):function(p){var u,d,f,m,v,y=p.length,b=0;for(m=0;m<y;m++)(64512&(d=p.charCodeAt(m)))==55296&&m+1<y&&(64512&(f=p.charCodeAt(m+1)))==56320&&(d=65536+(d-55296<<10)+(f-56320),m++),b+=d<128?1:d<2048?2:d<65536?3:4;for(u=s.uint8array?new Uint8Array(b):new Array(b),m=v=0;v<b;m++)(64512&(d=p.charCodeAt(m)))==55296&&m+1<y&&(64512&(f=p.charCodeAt(m+1)))==56320&&(d=65536+(d-55296<<10)+(f-56320),m++),d<128?u[v++]=d:(d<2048?u[v++]=192|d>>>6:(d<65536?u[v++]=224|d>>>12:(u[v++]=240|d>>>18,u[v++]=128|d>>>12&63),u[v++]=128|d>>>6&63),u[v++]=128|63&d);return u}(c)},t.utf8decode=function(c){return s.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(p){var u,d,f,m,v=p.length,y=new Array(2*v);for(u=d=0;u<v;)if((f=p[u++])<128)y[d++]=f;else if(4<(m=r[f]))y[d++]=65533,u+=m-1;else{for(f&=m===2?31:m===3?15:7;1<m&&u<v;)f=f<<6|63&p[u++],m--;1<m?y[d++]=65533:f<65536?y[d++]=f:(f-=65536,y[d++]=55296|f>>10&1023,y[d++]=56320|1023&f)}return y.length!==d&&(y.subarray?y=y.subarray(0,d):y.length=d),e.applyFromCharCode(y)}(c=e.transformTo(s.uint8array?"uint8array":"array",c))},e.inherits(a,n),a.prototype.processChunk=function(c){var p=e.transformTo(s.uint8array?"uint8array":"array",c.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var u=p;(p=new Uint8Array(u.length+this.leftOver.length)).set(this.leftOver,0),p.set(u,this.leftOver.length)}else p=this.leftOver.concat(p);this.leftOver=null}var d=function(m,v){var y;for((v=v||m.length)>m.length&&(v=m.length),y=v-1;0<=y&&(192&m[y])==128;)y--;return y<0||y===0?v:y+r[m[y]]>v?y:v}(p),f=p;d!==p.length&&(s.uint8array?(f=p.subarray(0,d),this.leftOver=p.subarray(d,p.length)):(f=p.slice(0,d),this.leftOver=p.slice(d,p.length))),this.push({data:t.utf8decode(f),meta:c.meta})},a.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=a,e.inherits(l,n),l.prototype.processChunk=function(c){this.push({data:t.utf8encode(c.data),meta:c.meta})},t.Utf8EncodeWorker=l},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(g,h,t){"use strict";var e=g("./support"),s=g("./base64"),i=g("./nodejsUtils"),n=g("./external");function r(u){return u}function o(u,d){for(var f=0;f<u.length;++f)d[f]=255&u.charCodeAt(f);return d}g("setimmediate"),t.newBlob=function(u,d){t.checkSupport("blob");try{return new Blob([u],{type:d})}catch{try{var f=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return f.append(u),f.getBlob(d)}catch{throw new Error("Bug : can't construct the Blob.")}}};var a={stringifyByChunk:function(u,d,f){var m=[],v=0,y=u.length;if(y<=f)return String.fromCharCode.apply(null,u);for(;v<y;)d==="array"||d==="nodebuffer"?m.push(String.fromCharCode.apply(null,u.slice(v,Math.min(v+f,y)))):m.push(String.fromCharCode.apply(null,u.subarray(v,Math.min(v+f,y)))),v+=f;return m.join("")},stringifyByChar:function(u){for(var d="",f=0;f<u.length;f++)d+=String.fromCharCode(u[f]);return d},applyCanBeUsed:{uint8array:function(){try{return e.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}}(),nodebuffer:function(){try{return e.nodebuffer&&String.fromCharCode.apply(null,i.allocBuffer(1)).length===1}catch{return!1}}()}};function l(u){var d=65536,f=t.getTypeOf(u),m=!0;if(f==="uint8array"?m=a.applyCanBeUsed.uint8array:f==="nodebuffer"&&(m=a.applyCanBeUsed.nodebuffer),m)for(;1<d;)try{return a.stringifyByChunk(u,f,d)}catch{d=Math.floor(d/2)}return a.stringifyByChar(u)}function c(u,d){for(var f=0;f<u.length;f++)d[f]=u[f];return d}t.applyFromCharCode=l;var p={};p.string={string:r,array:function(u){return o(u,new Array(u.length))},arraybuffer:function(u){return p.string.uint8array(u).buffer},uint8array:function(u){return o(u,new Uint8Array(u.length))},nodebuffer:function(u){return o(u,i.allocBuffer(u.length))}},p.array={string:l,array:r,arraybuffer:function(u){return new Uint8Array(u).buffer},uint8array:function(u){return new Uint8Array(u)},nodebuffer:function(u){return i.newBufferFrom(u)}},p.arraybuffer={string:function(u){return l(new Uint8Array(u))},array:function(u){return c(new Uint8Array(u),new Array(u.byteLength))},arraybuffer:r,uint8array:function(u){return new Uint8Array(u)},nodebuffer:function(u){return i.newBufferFrom(new Uint8Array(u))}},p.uint8array={string:l,array:function(u){return c(u,new Array(u.length))},arraybuffer:function(u){return u.buffer},uint8array:r,nodebuffer:function(u){return i.newBufferFrom(u)}},p.nodebuffer={string:l,array:function(u){return c(u,new Array(u.length))},arraybuffer:function(u){return p.nodebuffer.uint8array(u).buffer},uint8array:function(u){return c(u,new Uint8Array(u.length))},nodebuffer:r},t.transformTo=function(u,d){if(d=d||"",!u)return d;t.checkSupport(u);var f=t.getTypeOf(d);return p[f][u](d)},t.resolve=function(u){for(var d=u.split("/"),f=[],m=0;m<d.length;m++){var v=d[m];v==="."||v===""&&m!==0&&m!==d.length-1||(v===".."?f.pop():f.push(v))}return f.join("/")},t.getTypeOf=function(u){return typeof u=="string"?"string":Object.prototype.toString.call(u)==="[object Array]"?"array":e.nodebuffer&&i.isBuffer(u)?"nodebuffer":e.uint8array&&u instanceof Uint8Array?"uint8array":e.arraybuffer&&u instanceof ArrayBuffer?"arraybuffer":void 0},t.checkSupport=function(u){if(!e[u.toLowerCase()])throw new Error(u+" is not supported by this platform")},t.MAX_VALUE_16BITS=65535,t.MAX_VALUE_32BITS=-1,t.pretty=function(u){var d,f,m="";for(f=0;f<(u||"").length;f++)m+="\\x"+((d=u.charCodeAt(f))<16?"0":"")+d.toString(16).toUpperCase();return m},t.delay=function(u,d,f){setImmediate(function(){u.apply(f||null,d||[])})},t.inherits=function(u,d){function f(){}f.prototype=d.prototype,u.prototype=new f},t.extend=function(){var u,d,f={};for(u=0;u<arguments.length;u++)for(d in arguments[u])Object.prototype.hasOwnProperty.call(arguments[u],d)&&f[d]===void 0&&(f[d]=arguments[u][d]);return f},t.prepareContent=function(u,d,f,m,v){return n.Promise.resolve(d).then(function(y){return e.blob&&(y instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(y))!==-1)&&typeof FileReader<"u"?new n.Promise(function(b,k){var C=new FileReader;C.onload=function(I){b(I.target.result)},C.onerror=function(I){k(I.target.error)},C.readAsArrayBuffer(y)}):y}).then(function(y){var b=t.getTypeOf(y);return b?(b==="arraybuffer"?y=t.transformTo("uint8array",y):b==="string"&&(v?y=s.decode(y):f&&m!==!0&&(y=function(k){return o(k,e.uint8array?new Uint8Array(k.length):new Array(k.length))}(y))),y):n.Promise.reject(new Error("Can't read the data of '"+u+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(g,h,t){"use strict";var e=g("./reader/readerFor"),s=g("./utils"),i=g("./signature"),n=g("./zipEntry"),r=g("./support");function o(a){this.files=[],this.loadOptions=a}o.prototype={checkSignature:function(a){if(!this.reader.readAndCheckSignature(a)){this.reader.index-=4;var l=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(l)+", expected "+s.pretty(a)+")")}},isSignature:function(a,l){var c=this.reader.index;this.reader.setIndex(a);var p=this.reader.readString(4)===l;return this.reader.setIndex(c),p},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var a=this.reader.readData(this.zipCommentLength),l=r.uint8array?"uint8array":"array",c=s.transformTo(l,a);this.zipComment=this.loadOptions.decodeFileName(c)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,l,c,p=this.zip64EndOfCentralSize-44;0<p;)a=this.reader.readInt(2),l=this.reader.readInt(4),c=this.reader.readData(l),this.zip64ExtensibleData[a]={id:a,length:l,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,l;for(a=0;a<this.files.length;a++)l=this.files[a],this.reader.setIndex(l.localHeaderOffset),this.checkSignature(i.LOCAL_FILE_HEADER),l.readLocalPart(this.reader),l.handleUTF8(),l.processAttributes()},readCentralDir:function(){var a;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(i.CENTRAL_FILE_HEADER);)(a=new n({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(a);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var a=this.reader.lastIndexOfSignature(i.CENTRAL_DIRECTORY_END);if(a<0)throw this.isSignature(0,i.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(a);var l=a;if(this.checkSignature(i.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(a=this.reader.lastIndexOfSignature(i.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(a),this.checkSignature(i.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,i.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(i.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(i.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var c=this.centralDirOffset+this.centralDirSize;this.zip64&&(c+=20,c+=12+this.zip64EndOfCentralSize);var p=l-c;if(0<p)this.isSignature(l,i.CENTRAL_FILE_HEADER)||(this.reader.zero=p);else if(p<0)throw new Error("Corrupted zip: missing "+Math.abs(p)+" bytes.")},prepareReader:function(a){this.reader=e(a)},load:function(a){this.prepareReader(a),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},h.exports=o},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(g,h,t){"use strict";var e=g("./reader/readerFor"),s=g("./utils"),i=g("./compressedObject"),n=g("./crc32"),r=g("./utf8"),o=g("./compressions"),a=g("./support");function l(c,p){this.options=c,this.loadOptions=p}l.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(c){var p,u;if(c.skip(22),this.fileNameLength=c.readInt(2),u=c.readInt(2),this.fileName=c.readData(this.fileNameLength),c.skip(u),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((p=function(d){for(var f in o)if(Object.prototype.hasOwnProperty.call(o,f)&&o[f].magic===d)return o[f];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new i(this.compressedSize,this.uncompressedSize,this.crc32,p,c.readData(this.compressedSize))},readCentralPart:function(c){this.versionMadeBy=c.readInt(2),c.skip(2),this.bitFlag=c.readInt(2),this.compressionMethod=c.readString(2),this.date=c.readDate(),this.crc32=c.readInt(4),this.compressedSize=c.readInt(4),this.uncompressedSize=c.readInt(4);var p=c.readInt(2);if(this.extraFieldsLength=c.readInt(2),this.fileCommentLength=c.readInt(2),this.diskNumberStart=c.readInt(2),this.internalFileAttributes=c.readInt(2),this.externalFileAttributes=c.readInt(4),this.localHeaderOffset=c.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");c.skip(p),this.readExtraFields(c),this.parseZIP64ExtraField(c),this.fileComment=c.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var c=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),c==0&&(this.dosPermissions=63&this.externalFileAttributes),c==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var c=e(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=c.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=c.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=c.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=c.readInt(4))}},readExtraFields:function(c){var p,u,d,f=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<f;)p=c.readInt(2),u=c.readInt(2),d=c.readData(u),this.extraFields[p]={id:p,length:u,value:d};c.setIndex(f)},handleUTF8:function(){var c=a.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=r.utf8decode(this.fileName),this.fileCommentStr=r.utf8decode(this.fileComment);else{var p=this.findExtraFieldUnicodePath();if(p!==null)this.fileNameStr=p;else{var u=s.transformTo(c,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(u)}var d=this.findExtraFieldUnicodeComment();if(d!==null)this.fileCommentStr=d;else{var f=s.transformTo(c,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(f)}}},findExtraFieldUnicodePath:function(){var c=this.extraFields[28789];if(c){var p=e(c.value);return p.readInt(1)!==1||n(this.fileName)!==p.readInt(4)?null:r.utf8decode(p.readData(c.length-5))}return null},findExtraFieldUnicodeComment:function(){var c=this.extraFields[25461];if(c){var p=e(c.value);return p.readInt(1)!==1||n(this.fileComment)!==p.readInt(4)?null:r.utf8decode(p.readData(c.length-5))}return null}},h.exports=l},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(g,h,t){"use strict";function e(p,u,d){this.name=p,this.dir=d.dir,this.date=d.date,this.comment=d.comment,this.unixPermissions=d.unixPermissions,this.dosPermissions=d.dosPermissions,this._data=u,this._dataBinary=d.binary,this.options={compression:d.compression,compressionOptions:d.compressionOptions}}var s=g("./stream/StreamHelper"),i=g("./stream/DataWorker"),n=g("./utf8"),r=g("./compressedObject"),o=g("./stream/GenericWorker");e.prototype={internalStream:function(p){var u=null,d="string";try{if(!p)throw new Error("No output type specified.");var f=(d=p.toLowerCase())==="string"||d==="text";d!=="binarystring"&&d!=="text"||(d="string"),u=this._decompressWorker();var m=!this._dataBinary;m&&!f&&(u=u.pipe(new n.Utf8EncodeWorker)),!m&&f&&(u=u.pipe(new n.Utf8DecodeWorker))}catch(v){(u=new o("error")).error(v)}return new s(u,d,"")},async:function(p,u){return this.internalStream(p).accumulate(u)},nodeStream:function(p,u){return this.internalStream(p||"nodebuffer").toNodejsStream(u)},_compressWorker:function(p,u){if(this._data instanceof r&&this._data.compression.magic===p.magic)return this._data.getCompressedWorker();var d=this._decompressWorker();return this._dataBinary||(d=d.pipe(new n.Utf8EncodeWorker)),r.createWorkerFrom(d,p,u)},_decompressWorker:function(){return this._data instanceof r?this._data.getContentWorker():this._data instanceof o?this._data:new i(this._data)}};for(var a=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],l=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},c=0;c<a.length;c++)e.prototype[a[c]]=l;h.exports=e},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(g,h,t){(function(e){"use strict";var s,i,n=e.MutationObserver||e.WebKitMutationObserver;if(n){var r=0,o=new n(p),a=e.document.createTextNode("");o.observe(a,{characterData:!0}),s=function(){a.data=r=++r%2}}else if(e.setImmediate||e.MessageChannel===void 0)s="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var u=e.document.createElement("script");u.onreadystatechange=function(){p(),u.onreadystatechange=null,u.parentNode.removeChild(u),u=null},e.document.documentElement.appendChild(u)}:function(){setTimeout(p,0)};else{var l=new e.MessageChannel;l.port1.onmessage=p,s=function(){l.port2.postMessage(0)}}var c=[];function p(){var u,d;i=!0;for(var f=c.length;f;){for(d=c,c=[],u=-1;++u<f;)d[u]();f=c.length}i=!1}h.exports=function(u){c.push(u)!==1||i||s()}}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(g,h,t){"use strict";var e=g("immediate");function s(){}var i={},n=["REJECTED"],r=["FULFILLED"],o=["PENDING"];function a(f){if(typeof f!="function")throw new TypeError("resolver must be a function");this.state=o,this.queue=[],this.outcome=void 0,f!==s&&u(this,f)}function l(f,m,v){this.promise=f,typeof m=="function"&&(this.onFulfilled=m,this.callFulfilled=this.otherCallFulfilled),typeof v=="function"&&(this.onRejected=v,this.callRejected=this.otherCallRejected)}function c(f,m,v){e(function(){var y;try{y=m(v)}catch(b){return i.reject(f,b)}y===f?i.reject(f,new TypeError("Cannot resolve promise with itself")):i.resolve(f,y)})}function p(f){var m=f&&f.then;if(f&&(typeof f=="object"||typeof f=="function")&&typeof m=="function")return function(){m.apply(f,arguments)}}function u(f,m){var v=!1;function y(C){v||(v=!0,i.reject(f,C))}function b(C){v||(v=!0,i.resolve(f,C))}var k=d(function(){m(b,y)});k.status==="error"&&y(k.value)}function d(f,m){var v={};try{v.value=f(m),v.status="success"}catch(y){v.status="error",v.value=y}return v}(h.exports=a).prototype.finally=function(f){if(typeof f!="function")return this;var m=this.constructor;return this.then(function(v){return m.resolve(f()).then(function(){return v})},function(v){return m.resolve(f()).then(function(){throw v})})},a.prototype.catch=function(f){return this.then(null,f)},a.prototype.then=function(f,m){if(typeof f!="function"&&this.state===r||typeof m!="function"&&this.state===n)return this;var v=new this.constructor(s);return this.state!==o?c(v,this.state===r?f:m,this.outcome):this.queue.push(new l(v,f,m)),v},l.prototype.callFulfilled=function(f){i.resolve(this.promise,f)},l.prototype.otherCallFulfilled=function(f){c(this.promise,this.onFulfilled,f)},l.prototype.callRejected=function(f){i.reject(this.promise,f)},l.prototype.otherCallRejected=function(f){c(this.promise,this.onRejected,f)},i.resolve=function(f,m){var v=d(p,m);if(v.status==="error")return i.reject(f,v.value);var y=v.value;if(y)u(f,y);else{f.state=r,f.outcome=m;for(var b=-1,k=f.queue.length;++b<k;)f.queue[b].callFulfilled(m)}return f},i.reject=function(f,m){f.state=n,f.outcome=m;for(var v=-1,y=f.queue.length;++v<y;)f.queue[v].callRejected(m);return f},a.resolve=function(f){return f instanceof this?f:i.resolve(new this(s),f)},a.reject=function(f){var m=new this(s);return i.reject(m,f)},a.all=function(f){var m=this;if(Object.prototype.toString.call(f)!=="[object Array]")return this.reject(new TypeError("must be an array"));var v=f.length,y=!1;if(!v)return this.resolve([]);for(var b=new Array(v),k=0,C=-1,I=new this(s);++C<v;)E(f[C],C);return I;function E(D,H){m.resolve(D).then(function(T){b[H]=T,++k!==v||y||(y=!0,i.resolve(I,b))},function(T){y||(y=!0,i.reject(I,T))})}},a.race=function(f){var m=this;if(Object.prototype.toString.call(f)!=="[object Array]")return this.reject(new TypeError("must be an array"));var v=f.length,y=!1;if(!v)return this.resolve([]);for(var b=-1,k=new this(s);++b<v;)C=f[b],m.resolve(C).then(function(I){y||(y=!0,i.resolve(k,I))},function(I){y||(y=!0,i.reject(k,I))});var C;return k}},{immediate:36}],38:[function(g,h,t){"use strict";var e={};(0,g("./lib/utils/common").assign)(e,g("./lib/deflate"),g("./lib/inflate"),g("./lib/zlib/constants")),h.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(g,h,t){"use strict";var e=g("./zlib/deflate"),s=g("./utils/common"),i=g("./utils/strings"),n=g("./zlib/messages"),r=g("./zlib/zstream"),o=Object.prototype.toString,a=0,l=-1,c=0,p=8;function u(f){if(!(this instanceof u))return new u(f);this.options=s.assign({level:l,method:p,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},f||{});var m=this.options;m.raw&&0<m.windowBits?m.windowBits=-m.windowBits:m.gzip&&0<m.windowBits&&m.windowBits<16&&(m.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new r,this.strm.avail_out=0;var v=e.deflateInit2(this.strm,m.level,m.method,m.windowBits,m.memLevel,m.strategy);if(v!==a)throw new Error(n[v]);if(m.header&&e.deflateSetHeader(this.strm,m.header),m.dictionary){var y;if(y=typeof m.dictionary=="string"?i.string2buf(m.dictionary):o.call(m.dictionary)==="[object ArrayBuffer]"?new Uint8Array(m.dictionary):m.dictionary,(v=e.deflateSetDictionary(this.strm,y))!==a)throw new Error(n[v]);this._dict_set=!0}}function d(f,m){var v=new u(m);if(v.push(f,!0),v.err)throw v.msg||n[v.err];return v.result}u.prototype.push=function(f,m){var v,y,b=this.strm,k=this.options.chunkSize;if(this.ended)return!1;y=m===~~m?m:m===!0?4:0,typeof f=="string"?b.input=i.string2buf(f):o.call(f)==="[object ArrayBuffer]"?b.input=new Uint8Array(f):b.input=f,b.next_in=0,b.avail_in=b.input.length;do{if(b.avail_out===0&&(b.output=new s.Buf8(k),b.next_out=0,b.avail_out=k),(v=e.deflate(b,y))!==1&&v!==a)return this.onEnd(v),!(this.ended=!0);b.avail_out!==0&&(b.avail_in!==0||y!==4&&y!==2)||(this.options.to==="string"?this.onData(i.buf2binstring(s.shrinkBuf(b.output,b.next_out))):this.onData(s.shrinkBuf(b.output,b.next_out)))}while((0<b.avail_in||b.avail_out===0)&&v!==1);return y===4?(v=e.deflateEnd(this.strm),this.onEnd(v),this.ended=!0,v===a):y!==2||(this.onEnd(a),!(b.avail_out=0))},u.prototype.onData=function(f){this.chunks.push(f)},u.prototype.onEnd=function(f){f===a&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=f,this.msg=this.strm.msg},t.Deflate=u,t.deflate=d,t.deflateRaw=function(f,m){return(m=m||{}).raw=!0,d(f,m)},t.gzip=function(f,m){return(m=m||{}).gzip=!0,d(f,m)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(g,h,t){"use strict";var e=g("./zlib/inflate"),s=g("./utils/common"),i=g("./utils/strings"),n=g("./zlib/constants"),r=g("./zlib/messages"),o=g("./zlib/zstream"),a=g("./zlib/gzheader"),l=Object.prototype.toString;function c(u){if(!(this instanceof c))return new c(u);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},u||{});var d=this.options;d.raw&&0<=d.windowBits&&d.windowBits<16&&(d.windowBits=-d.windowBits,d.windowBits===0&&(d.windowBits=-15)),!(0<=d.windowBits&&d.windowBits<16)||u&&u.windowBits||(d.windowBits+=32),15<d.windowBits&&d.windowBits<48&&!(15&d.windowBits)&&(d.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var f=e.inflateInit2(this.strm,d.windowBits);if(f!==n.Z_OK)throw new Error(r[f]);this.header=new a,e.inflateGetHeader(this.strm,this.header)}function p(u,d){var f=new c(d);if(f.push(u,!0),f.err)throw f.msg||r[f.err];return f.result}c.prototype.push=function(u,d){var f,m,v,y,b,k,C=this.strm,I=this.options.chunkSize,E=this.options.dictionary,D=!1;if(this.ended)return!1;m=d===~~d?d:d===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof u=="string"?C.input=i.binstring2buf(u):l.call(u)==="[object ArrayBuffer]"?C.input=new Uint8Array(u):C.input=u,C.next_in=0,C.avail_in=C.input.length;do{if(C.avail_out===0&&(C.output=new s.Buf8(I),C.next_out=0,C.avail_out=I),(f=e.inflate(C,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&E&&(k=typeof E=="string"?i.string2buf(E):l.call(E)==="[object ArrayBuffer]"?new Uint8Array(E):E,f=e.inflateSetDictionary(this.strm,k)),f===n.Z_BUF_ERROR&&D===!0&&(f=n.Z_OK,D=!1),f!==n.Z_STREAM_END&&f!==n.Z_OK)return this.onEnd(f),!(this.ended=!0);C.next_out&&(C.avail_out!==0&&f!==n.Z_STREAM_END&&(C.avail_in!==0||m!==n.Z_FINISH&&m!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(v=i.utf8border(C.output,C.next_out),y=C.next_out-v,b=i.buf2string(C.output,v),C.next_out=y,C.avail_out=I-y,y&&s.arraySet(C.output,C.output,v,y,0),this.onData(b)):this.onData(s.shrinkBuf(C.output,C.next_out)))),C.avail_in===0&&C.avail_out===0&&(D=!0)}while((0<C.avail_in||C.avail_out===0)&&f!==n.Z_STREAM_END);return f===n.Z_STREAM_END&&(m=n.Z_FINISH),m===n.Z_FINISH?(f=e.inflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===n.Z_OK):m!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(C.avail_out=0))},c.prototype.onData=function(u){this.chunks.push(u)},c.prototype.onEnd=function(u){u===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=u,this.msg=this.strm.msg},t.Inflate=c,t.inflate=p,t.inflateRaw=function(u,d){return(d=d||{}).raw=!0,p(u,d)},t.ungzip=p},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(g,h,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";t.assign=function(n){for(var r=Array.prototype.slice.call(arguments,1);r.length;){var o=r.shift();if(o){if(typeof o!="object")throw new TypeError(o+"must be non-object");for(var a in o)o.hasOwnProperty(a)&&(n[a]=o[a])}}return n},t.shrinkBuf=function(n,r){return n.length===r?n:n.subarray?n.subarray(0,r):(n.length=r,n)};var s={arraySet:function(n,r,o,a,l){if(r.subarray&&n.subarray)n.set(r.subarray(o,o+a),l);else for(var c=0;c<a;c++)n[l+c]=r[o+c]},flattenChunks:function(n){var r,o,a,l,c,p;for(r=a=0,o=n.length;r<o;r++)a+=n[r].length;for(p=new Uint8Array(a),r=l=0,o=n.length;r<o;r++)c=n[r],p.set(c,l),l+=c.length;return p}},i={arraySet:function(n,r,o,a,l){for(var c=0;c<a;c++)n[l+c]=r[o+c]},flattenChunks:function(n){return[].concat.apply([],n)}};t.setTyped=function(n){n?(t.Buf8=Uint8Array,t.Buf16=Uint16Array,t.Buf32=Int32Array,t.assign(t,s)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,i))},t.setTyped(e)},{}],42:[function(g,h,t){"use strict";var e=g("./common"),s=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch{s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{i=!1}for(var n=new e.Buf8(256),r=0;r<256;r++)n[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function o(a,l){if(l<65537&&(a.subarray&&i||!a.subarray&&s))return String.fromCharCode.apply(null,e.shrinkBuf(a,l));for(var c="",p=0;p<l;p++)c+=String.fromCharCode(a[p]);return c}n[254]=n[254]=1,t.string2buf=function(a){var l,c,p,u,d,f=a.length,m=0;for(u=0;u<f;u++)(64512&(c=a.charCodeAt(u)))==55296&&u+1<f&&(64512&(p=a.charCodeAt(u+1)))==56320&&(c=65536+(c-55296<<10)+(p-56320),u++),m+=c<128?1:c<2048?2:c<65536?3:4;for(l=new e.Buf8(m),u=d=0;d<m;u++)(64512&(c=a.charCodeAt(u)))==55296&&u+1<f&&(64512&(p=a.charCodeAt(u+1)))==56320&&(c=65536+(c-55296<<10)+(p-56320),u++),c<128?l[d++]=c:(c<2048?l[d++]=192|c>>>6:(c<65536?l[d++]=224|c>>>12:(l[d++]=240|c>>>18,l[d++]=128|c>>>12&63),l[d++]=128|c>>>6&63),l[d++]=128|63&c);return l},t.buf2binstring=function(a){return o(a,a.length)},t.binstring2buf=function(a){for(var l=new e.Buf8(a.length),c=0,p=l.length;c<p;c++)l[c]=a.charCodeAt(c);return l},t.buf2string=function(a,l){var c,p,u,d,f=l||a.length,m=new Array(2*f);for(c=p=0;c<f;)if((u=a[c++])<128)m[p++]=u;else if(4<(d=n[u]))m[p++]=65533,c+=d-1;else{for(u&=d===2?31:d===3?15:7;1<d&&c<f;)u=u<<6|63&a[c++],d--;1<d?m[p++]=65533:u<65536?m[p++]=u:(u-=65536,m[p++]=55296|u>>10&1023,m[p++]=56320|1023&u)}return o(m,p)},t.utf8border=function(a,l){var c;for((l=l||a.length)>a.length&&(l=a.length),c=l-1;0<=c&&(192&a[c])==128;)c--;return c<0||c===0?l:c+n[a[c]]>l?c:l}},{"./common":41}],43:[function(g,h,t){"use strict";h.exports=function(e,s,i,n){for(var r=65535&e|0,o=e>>>16&65535|0,a=0;i!==0;){for(i-=a=2e3<i?2e3:i;o=o+(r=r+s[n++]|0)|0,--a;);r%=65521,o%=65521}return r|o<<16|0}},{}],44:[function(g,h,t){"use strict";h.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(g,h,t){"use strict";var e=function(){for(var s,i=[],n=0;n<256;n++){s=n;for(var r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;i[n]=s}return i}();h.exports=function(s,i,n,r){var o=e,a=r+n;s^=-1;for(var l=r;l<a;l++)s=s>>>8^o[255&(s^i[l])];return-1^s}},{}],46:[function(g,h,t){"use strict";var e,s=g("../utils/common"),i=g("./trees"),n=g("./adler32"),r=g("./crc32"),o=g("./messages"),a=0,l=4,c=0,p=-2,u=-1,d=4,f=2,m=8,v=9,y=286,b=30,k=19,C=2*y+1,I=15,E=3,D=258,H=D+E+1,T=42,A=113,S=1,_=2,J=3,U=4;function z(w,B){return w.msg=o[B],B}function W(w){return(w<<1)-(4<w?9:0)}function Q(w){for(var B=w.length;0<=--B;)w[B]=0}function N(w){var B=w.state,$=B.pending;$>w.avail_out&&($=w.avail_out),$!==0&&(s.arraySet(w.output,B.pending_buf,B.pending_out,$,w.next_out),w.next_out+=$,B.pending_out+=$,w.total_out+=$,w.avail_out-=$,B.pending-=$,B.pending===0&&(B.pending_out=0))}function P(w,B){i._tr_flush_block(w,0<=w.block_start?w.block_start:-1,w.strstart-w.block_start,B),w.block_start=w.strstart,N(w.strm)}function X(w,B){w.pending_buf[w.pending++]=B}function q(w,B){w.pending_buf[w.pending++]=B>>>8&255,w.pending_buf[w.pending++]=255&B}function Y(w,B){var $,x,F=w.max_chain_length,M=w.strstart,j=w.prev_length,V=w.nice_match,L=w.strstart>w.w_size-H?w.strstart-(w.w_size-H):0,K=w.window,tt=w.w_mask,Z=w.prev,st=w.strstart+D,ut=K[M+j-1],lt=K[M+j];w.prev_length>=w.good_match&&(F>>=2),V>w.lookahead&&(V=w.lookahead);do if(K[($=B)+j]===lt&&K[$+j-1]===ut&&K[$]===K[M]&&K[++$]===K[M+1]){M+=2,$++;do;while(K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&M<st);if(x=D-(st-M),M=st-D,j<x){if(w.match_start=B,V<=(j=x))break;ut=K[M+j-1],lt=K[M+j]}}while((B=Z[B&tt])>L&&--F!=0);return j<=w.lookahead?j:w.lookahead}function ct(w){var B,$,x,F,M,j,V,L,K,tt,Z=w.w_size;do{if(F=w.window_size-w.lookahead-w.strstart,w.strstart>=Z+(Z-H)){for(s.arraySet(w.window,w.window,Z,Z,0),w.match_start-=Z,w.strstart-=Z,w.block_start-=Z,B=$=w.hash_size;x=w.head[--B],w.head[B]=Z<=x?x-Z:0,--$;);for(B=$=Z;x=w.prev[--B],w.prev[B]=Z<=x?x-Z:0,--$;);F+=Z}if(w.strm.avail_in===0)break;if(j=w.strm,V=w.window,L=w.strstart+w.lookahead,K=F,tt=void 0,tt=j.avail_in,K<tt&&(tt=K),$=tt===0?0:(j.avail_in-=tt,s.arraySet(V,j.input,j.next_in,tt,L),j.state.wrap===1?j.adler=n(j.adler,V,tt,L):j.state.wrap===2&&(j.adler=r(j.adler,V,tt,L)),j.next_in+=tt,j.total_in+=tt,tt),w.lookahead+=$,w.lookahead+w.insert>=E)for(M=w.strstart-w.insert,w.ins_h=w.window[M],w.ins_h=(w.ins_h<<w.hash_shift^w.window[M+1])&w.hash_mask;w.insert&&(w.ins_h=(w.ins_h<<w.hash_shift^w.window[M+E-1])&w.hash_mask,w.prev[M&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=M,M++,w.insert--,!(w.lookahead+w.insert<E)););}while(w.lookahead<H&&w.strm.avail_in!==0)}function pt(w,B){for(var $,x;;){if(w.lookahead<H){if(ct(w),w.lookahead<H&&B===a)return S;if(w.lookahead===0)break}if($=0,w.lookahead>=E&&(w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+E-1])&w.hash_mask,$=w.prev[w.strstart&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=w.strstart),$!==0&&w.strstart-$<=w.w_size-H&&(w.match_length=Y(w,$)),w.match_length>=E)if(x=i._tr_tally(w,w.strstart-w.match_start,w.match_length-E),w.lookahead-=w.match_length,w.match_length<=w.max_lazy_match&&w.lookahead>=E){for(w.match_length--;w.strstart++,w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+E-1])&w.hash_mask,$=w.prev[w.strstart&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=w.strstart,--w.match_length!=0;);w.strstart++}else w.strstart+=w.match_length,w.match_length=0,w.ins_h=w.window[w.strstart],w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+1])&w.hash_mask;else x=i._tr_tally(w,0,w.window[w.strstart]),w.lookahead--,w.strstart++;if(x&&(P(w,!1),w.strm.avail_out===0))return S}return w.insert=w.strstart<E-1?w.strstart:E-1,B===l?(P(w,!0),w.strm.avail_out===0?J:U):w.last_lit&&(P(w,!1),w.strm.avail_out===0)?S:_}function nt(w,B){for(var $,x,F;;){if(w.lookahead<H){if(ct(w),w.lookahead<H&&B===a)return S;if(w.lookahead===0)break}if($=0,w.lookahead>=E&&(w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+E-1])&w.hash_mask,$=w.prev[w.strstart&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=w.strstart),w.prev_length=w.match_length,w.prev_match=w.match_start,w.match_length=E-1,$!==0&&w.prev_length<w.max_lazy_match&&w.strstart-$<=w.w_size-H&&(w.match_length=Y(w,$),w.match_length<=5&&(w.strategy===1||w.match_length===E&&4096<w.strstart-w.match_start)&&(w.match_length=E-1)),w.prev_length>=E&&w.match_length<=w.prev_length){for(F=w.strstart+w.lookahead-E,x=i._tr_tally(w,w.strstart-1-w.prev_match,w.prev_length-E),w.lookahead-=w.prev_length-1,w.prev_length-=2;++w.strstart<=F&&(w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+E-1])&w.hash_mask,$=w.prev[w.strstart&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=w.strstart),--w.prev_length!=0;);if(w.match_available=0,w.match_length=E-1,w.strstart++,x&&(P(w,!1),w.strm.avail_out===0))return S}else if(w.match_available){if((x=i._tr_tally(w,0,w.window[w.strstart-1]))&&P(w,!1),w.strstart++,w.lookahead--,w.strm.avail_out===0)return S}else w.match_available=1,w.strstart++,w.lookahead--}return w.match_available&&(x=i._tr_tally(w,0,w.window[w.strstart-1]),w.match_available=0),w.insert=w.strstart<E-1?w.strstart:E-1,B===l?(P(w,!0),w.strm.avail_out===0?J:U):w.last_lit&&(P(w,!1),w.strm.avail_out===0)?S:_}function rt(w,B,$,x,F){this.good_length=w,this.max_lazy=B,this.nice_length=$,this.max_chain=x,this.func=F}function at(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=m,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*C),this.dyn_dtree=new s.Buf16(2*(2*b+1)),this.bl_tree=new s.Buf16(2*(2*k+1)),Q(this.dyn_ltree),Q(this.dyn_dtree),Q(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(I+1),this.heap=new s.Buf16(2*y+1),Q(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*y+1),Q(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function it(w){var B;return w&&w.state?(w.total_in=w.total_out=0,w.data_type=f,(B=w.state).pending=0,B.pending_out=0,B.wrap<0&&(B.wrap=-B.wrap),B.status=B.wrap?T:A,w.adler=B.wrap===2?0:1,B.last_flush=a,i._tr_init(B),c):z(w,p)}function gt(w){var B=it(w);return B===c&&function($){$.window_size=2*$.w_size,Q($.head),$.max_lazy_match=e[$.level].max_lazy,$.good_match=e[$.level].good_length,$.nice_match=e[$.level].nice_length,$.max_chain_length=e[$.level].max_chain,$.strstart=0,$.block_start=0,$.lookahead=0,$.insert=0,$.match_length=$.prev_length=E-1,$.match_available=0,$.ins_h=0}(w.state),B}function ft(w,B,$,x,F,M){if(!w)return p;var j=1;if(B===u&&(B=6),x<0?(j=0,x=-x):15<x&&(j=2,x-=16),F<1||v<F||$!==m||x<8||15<x||B<0||9<B||M<0||d<M)return z(w,p);x===8&&(x=9);var V=new at;return(w.state=V).strm=w,V.wrap=j,V.gzhead=null,V.w_bits=x,V.w_size=1<<V.w_bits,V.w_mask=V.w_size-1,V.hash_bits=F+7,V.hash_size=1<<V.hash_bits,V.hash_mask=V.hash_size-1,V.hash_shift=~~((V.hash_bits+E-1)/E),V.window=new s.Buf8(2*V.w_size),V.head=new s.Buf16(V.hash_size),V.prev=new s.Buf16(V.w_size),V.lit_bufsize=1<<F+6,V.pending_buf_size=4*V.lit_bufsize,V.pending_buf=new s.Buf8(V.pending_buf_size),V.d_buf=1*V.lit_bufsize,V.l_buf=3*V.lit_bufsize,V.level=B,V.strategy=M,V.method=$,gt(w)}e=[new rt(0,0,0,0,function(w,B){var $=65535;for($>w.pending_buf_size-5&&($=w.pending_buf_size-5);;){if(w.lookahead<=1){if(ct(w),w.lookahead===0&&B===a)return S;if(w.lookahead===0)break}w.strstart+=w.lookahead,w.lookahead=0;var x=w.block_start+$;if((w.strstart===0||w.strstart>=x)&&(w.lookahead=w.strstart-x,w.strstart=x,P(w,!1),w.strm.avail_out===0)||w.strstart-w.block_start>=w.w_size-H&&(P(w,!1),w.strm.avail_out===0))return S}return w.insert=0,B===l?(P(w,!0),w.strm.avail_out===0?J:U):(w.strstart>w.block_start&&(P(w,!1),w.strm.avail_out),S)}),new rt(4,4,8,4,pt),new rt(4,5,16,8,pt),new rt(4,6,32,32,pt),new rt(4,4,16,16,nt),new rt(8,16,32,32,nt),new rt(8,16,128,128,nt),new rt(8,32,128,256,nt),new rt(32,128,258,1024,nt),new rt(32,258,258,4096,nt)],t.deflateInit=function(w,B){return ft(w,B,m,15,8,0)},t.deflateInit2=ft,t.deflateReset=gt,t.deflateResetKeep=it,t.deflateSetHeader=function(w,B){return w&&w.state?w.state.wrap!==2?p:(w.state.gzhead=B,c):p},t.deflate=function(w,B){var $,x,F,M;if(!w||!w.state||5<B||B<0)return w?z(w,p):p;if(x=w.state,!w.output||!w.input&&w.avail_in!==0||x.status===666&&B!==l)return z(w,w.avail_out===0?-5:p);if(x.strm=w,$=x.last_flush,x.last_flush=B,x.status===T)if(x.wrap===2)w.adler=0,X(x,31),X(x,139),X(x,8),x.gzhead?(X(x,(x.gzhead.text?1:0)+(x.gzhead.hcrc?2:0)+(x.gzhead.extra?4:0)+(x.gzhead.name?8:0)+(x.gzhead.comment?16:0)),X(x,255&x.gzhead.time),X(x,x.gzhead.time>>8&255),X(x,x.gzhead.time>>16&255),X(x,x.gzhead.time>>24&255),X(x,x.level===9?2:2<=x.strategy||x.level<2?4:0),X(x,255&x.gzhead.os),x.gzhead.extra&&x.gzhead.extra.length&&(X(x,255&x.gzhead.extra.length),X(x,x.gzhead.extra.length>>8&255)),x.gzhead.hcrc&&(w.adler=r(w.adler,x.pending_buf,x.pending,0)),x.gzindex=0,x.status=69):(X(x,0),X(x,0),X(x,0),X(x,0),X(x,0),X(x,x.level===9?2:2<=x.strategy||x.level<2?4:0),X(x,3),x.status=A);else{var j=m+(x.w_bits-8<<4)<<8;j|=(2<=x.strategy||x.level<2?0:x.level<6?1:x.level===6?2:3)<<6,x.strstart!==0&&(j|=32),j+=31-j%31,x.status=A,q(x,j),x.strstart!==0&&(q(x,w.adler>>>16),q(x,65535&w.adler)),w.adler=1}if(x.status===69)if(x.gzhead.extra){for(F=x.pending;x.gzindex<(65535&x.gzhead.extra.length)&&(x.pending!==x.pending_buf_size||(x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),N(w),F=x.pending,x.pending!==x.pending_buf_size));)X(x,255&x.gzhead.extra[x.gzindex]),x.gzindex++;x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),x.gzindex===x.gzhead.extra.length&&(x.gzindex=0,x.status=73)}else x.status=73;if(x.status===73)if(x.gzhead.name){F=x.pending;do{if(x.pending===x.pending_buf_size&&(x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),N(w),F=x.pending,x.pending===x.pending_buf_size)){M=1;break}M=x.gzindex<x.gzhead.name.length?255&x.gzhead.name.charCodeAt(x.gzindex++):0,X(x,M)}while(M!==0);x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),M===0&&(x.gzindex=0,x.status=91)}else x.status=91;if(x.status===91)if(x.gzhead.comment){F=x.pending;do{if(x.pending===x.pending_buf_size&&(x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),N(w),F=x.pending,x.pending===x.pending_buf_size)){M=1;break}M=x.gzindex<x.gzhead.comment.length?255&x.gzhead.comment.charCodeAt(x.gzindex++):0,X(x,M)}while(M!==0);x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),M===0&&(x.status=103)}else x.status=103;if(x.status===103&&(x.gzhead.hcrc?(x.pending+2>x.pending_buf_size&&N(w),x.pending+2<=x.pending_buf_size&&(X(x,255&w.adler),X(x,w.adler>>8&255),w.adler=0,x.status=A)):x.status=A),x.pending!==0){if(N(w),w.avail_out===0)return x.last_flush=-1,c}else if(w.avail_in===0&&W(B)<=W($)&&B!==l)return z(w,-5);if(x.status===666&&w.avail_in!==0)return z(w,-5);if(w.avail_in!==0||x.lookahead!==0||B!==a&&x.status!==666){var V=x.strategy===2?function(L,K){for(var tt;;){if(L.lookahead===0&&(ct(L),L.lookahead===0)){if(K===a)return S;break}if(L.match_length=0,tt=i._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++,tt&&(P(L,!1),L.strm.avail_out===0))return S}return L.insert=0,K===l?(P(L,!0),L.strm.avail_out===0?J:U):L.last_lit&&(P(L,!1),L.strm.avail_out===0)?S:_}(x,B):x.strategy===3?function(L,K){for(var tt,Z,st,ut,lt=L.window;;){if(L.lookahead<=D){if(ct(L),L.lookahead<=D&&K===a)return S;if(L.lookahead===0)break}if(L.match_length=0,L.lookahead>=E&&0<L.strstart&&(Z=lt[st=L.strstart-1])===lt[++st]&&Z===lt[++st]&&Z===lt[++st]){ut=L.strstart+D;do;while(Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&st<ut);L.match_length=D-(ut-st),L.match_length>L.lookahead&&(L.match_length=L.lookahead)}if(L.match_length>=E?(tt=i._tr_tally(L,1,L.match_length-E),L.lookahead-=L.match_length,L.strstart+=L.match_length,L.match_length=0):(tt=i._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++),tt&&(P(L,!1),L.strm.avail_out===0))return S}return L.insert=0,K===l?(P(L,!0),L.strm.avail_out===0?J:U):L.last_lit&&(P(L,!1),L.strm.avail_out===0)?S:_}(x,B):e[x.level].func(x,B);if(V!==J&&V!==U||(x.status=666),V===S||V===J)return w.avail_out===0&&(x.last_flush=-1),c;if(V===_&&(B===1?i._tr_align(x):B!==5&&(i._tr_stored_block(x,0,0,!1),B===3&&(Q(x.head),x.lookahead===0&&(x.strstart=0,x.block_start=0,x.insert=0))),N(w),w.avail_out===0))return x.last_flush=-1,c}return B!==l?c:x.wrap<=0?1:(x.wrap===2?(X(x,255&w.adler),X(x,w.adler>>8&255),X(x,w.adler>>16&255),X(x,w.adler>>24&255),X(x,255&w.total_in),X(x,w.total_in>>8&255),X(x,w.total_in>>16&255),X(x,w.total_in>>24&255)):(q(x,w.adler>>>16),q(x,65535&w.adler)),N(w),0<x.wrap&&(x.wrap=-x.wrap),x.pending!==0?c:1)},t.deflateEnd=function(w){var B;return w&&w.state?(B=w.state.status)!==T&&B!==69&&B!==73&&B!==91&&B!==103&&B!==A&&B!==666?z(w,p):(w.state=null,B===A?z(w,-3):c):p},t.deflateSetDictionary=function(w,B){var $,x,F,M,j,V,L,K,tt=B.length;if(!w||!w.state||(M=($=w.state).wrap)===2||M===1&&$.status!==T||$.lookahead)return p;for(M===1&&(w.adler=n(w.adler,B,tt,0)),$.wrap=0,tt>=$.w_size&&(M===0&&(Q($.head),$.strstart=0,$.block_start=0,$.insert=0),K=new s.Buf8($.w_size),s.arraySet(K,B,tt-$.w_size,$.w_size,0),B=K,tt=$.w_size),j=w.avail_in,V=w.next_in,L=w.input,w.avail_in=tt,w.next_in=0,w.input=B,ct($);$.lookahead>=E;){for(x=$.strstart,F=$.lookahead-(E-1);$.ins_h=($.ins_h<<$.hash_shift^$.window[x+E-1])&$.hash_mask,$.prev[x&$.w_mask]=$.head[$.ins_h],$.head[$.ins_h]=x,x++,--F;);$.strstart=x,$.lookahead=E-1,ct($)}return $.strstart+=$.lookahead,$.block_start=$.strstart,$.insert=$.lookahead,$.lookahead=0,$.match_length=$.prev_length=E-1,$.match_available=0,w.next_in=V,w.input=L,w.avail_in=j,$.wrap=M,c},t.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(g,h,t){"use strict";h.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(g,h,t){"use strict";h.exports=function(e,s){var i,n,r,o,a,l,c,p,u,d,f,m,v,y,b,k,C,I,E,D,H,T,A,S,_;i=e.state,n=e.next_in,S=e.input,r=n+(e.avail_in-5),o=e.next_out,_=e.output,a=o-(s-e.avail_out),l=o+(e.avail_out-257),c=i.dmax,p=i.wsize,u=i.whave,d=i.wnext,f=i.window,m=i.hold,v=i.bits,y=i.lencode,b=i.distcode,k=(1<<i.lenbits)-1,C=(1<<i.distbits)-1;t:do{v<15&&(m+=S[n++]<<v,v+=8,m+=S[n++]<<v,v+=8),I=y[m&k];e:for(;;){if(m>>>=E=I>>>24,v-=E,(E=I>>>16&255)===0)_[o++]=65535&I;else{if(!(16&E)){if(!(64&E)){I=y[(65535&I)+(m&(1<<E)-1)];continue e}if(32&E){i.mode=12;break t}e.msg="invalid literal/length code",i.mode=30;break t}D=65535&I,(E&=15)&&(v<E&&(m+=S[n++]<<v,v+=8),D+=m&(1<<E)-1,m>>>=E,v-=E),v<15&&(m+=S[n++]<<v,v+=8,m+=S[n++]<<v,v+=8),I=b[m&C];s:for(;;){if(m>>>=E=I>>>24,v-=E,!(16&(E=I>>>16&255))){if(!(64&E)){I=b[(65535&I)+(m&(1<<E)-1)];continue s}e.msg="invalid distance code",i.mode=30;break t}if(H=65535&I,v<(E&=15)&&(m+=S[n++]<<v,(v+=8)<E&&(m+=S[n++]<<v,v+=8)),c<(H+=m&(1<<E)-1)){e.msg="invalid distance too far back",i.mode=30;break t}if(m>>>=E,v-=E,(E=o-a)<H){if(u<(E=H-E)&&i.sane){e.msg="invalid distance too far back",i.mode=30;break t}if(A=f,(T=0)===d){if(T+=p-E,E<D){for(D-=E;_[o++]=f[T++],--E;);T=o-H,A=_}}else if(d<E){if(T+=p+d-E,(E-=d)<D){for(D-=E;_[o++]=f[T++],--E;);if(T=0,d<D){for(D-=E=d;_[o++]=f[T++],--E;);T=o-H,A=_}}}else if(T+=d-E,E<D){for(D-=E;_[o++]=f[T++],--E;);T=o-H,A=_}for(;2<D;)_[o++]=A[T++],_[o++]=A[T++],_[o++]=A[T++],D-=3;D&&(_[o++]=A[T++],1<D&&(_[o++]=A[T++]))}else{for(T=o-H;_[o++]=_[T++],_[o++]=_[T++],_[o++]=_[T++],2<(D-=3););D&&(_[o++]=_[T++],1<D&&(_[o++]=_[T++]))}break}}break}}while(n<r&&o<l);n-=D=v>>3,m&=(1<<(v-=D<<3))-1,e.next_in=n,e.next_out=o,e.avail_in=n<r?r-n+5:5-(n-r),e.avail_out=o<l?l-o+257:257-(o-l),i.hold=m,i.bits=v}},{}],49:[function(g,h,t){"use strict";var e=g("../utils/common"),s=g("./adler32"),i=g("./crc32"),n=g("./inffast"),r=g("./inftrees"),o=1,a=2,l=0,c=-2,p=1,u=852,d=592;function f(T){return(T>>>24&255)+(T>>>8&65280)+((65280&T)<<8)+((255&T)<<24)}function m(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new e.Buf16(320),this.work=new e.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(T){var A;return T&&T.state?(A=T.state,T.total_in=T.total_out=A.total=0,T.msg="",A.wrap&&(T.adler=1&A.wrap),A.mode=p,A.last=0,A.havedict=0,A.dmax=32768,A.head=null,A.hold=0,A.bits=0,A.lencode=A.lendyn=new e.Buf32(u),A.distcode=A.distdyn=new e.Buf32(d),A.sane=1,A.back=-1,l):c}function y(T){var A;return T&&T.state?((A=T.state).wsize=0,A.whave=0,A.wnext=0,v(T)):c}function b(T,A){var S,_;return T&&T.state?(_=T.state,A<0?(S=0,A=-A):(S=1+(A>>4),A<48&&(A&=15)),A&&(A<8||15<A)?c:(_.window!==null&&_.wbits!==A&&(_.window=null),_.wrap=S,_.wbits=A,y(T))):c}function k(T,A){var S,_;return T?(_=new m,(T.state=_).window=null,(S=b(T,A))!==l&&(T.state=null),S):c}var C,I,E=!0;function D(T){if(E){var A;for(C=new e.Buf32(512),I=new e.Buf32(32),A=0;A<144;)T.lens[A++]=8;for(;A<256;)T.lens[A++]=9;for(;A<280;)T.lens[A++]=7;for(;A<288;)T.lens[A++]=8;for(r(o,T.lens,0,288,C,0,T.work,{bits:9}),A=0;A<32;)T.lens[A++]=5;r(a,T.lens,0,32,I,0,T.work,{bits:5}),E=!1}T.lencode=C,T.lenbits=9,T.distcode=I,T.distbits=5}function H(T,A,S,_){var J,U=T.state;return U.window===null&&(U.wsize=1<<U.wbits,U.wnext=0,U.whave=0,U.window=new e.Buf8(U.wsize)),_>=U.wsize?(e.arraySet(U.window,A,S-U.wsize,U.wsize,0),U.wnext=0,U.whave=U.wsize):(_<(J=U.wsize-U.wnext)&&(J=_),e.arraySet(U.window,A,S-_,J,U.wnext),(_-=J)?(e.arraySet(U.window,A,S-_,_,0),U.wnext=_,U.whave=U.wsize):(U.wnext+=J,U.wnext===U.wsize&&(U.wnext=0),U.whave<U.wsize&&(U.whave+=J))),0}t.inflateReset=y,t.inflateReset2=b,t.inflateResetKeep=v,t.inflateInit=function(T){return k(T,15)},t.inflateInit2=k,t.inflate=function(T,A){var S,_,J,U,z,W,Q,N,P,X,q,Y,ct,pt,nt,rt,at,it,gt,ft,w,B,$,x,F=0,M=new e.Buf8(4),j=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!T||!T.state||!T.output||!T.input&&T.avail_in!==0)return c;(S=T.state).mode===12&&(S.mode=13),z=T.next_out,J=T.output,Q=T.avail_out,U=T.next_in,_=T.input,W=T.avail_in,N=S.hold,P=S.bits,X=W,q=Q,B=l;t:for(;;)switch(S.mode){case p:if(S.wrap===0){S.mode=13;break}for(;P<16;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(2&S.wrap&&N===35615){M[S.check=0]=255&N,M[1]=N>>>8&255,S.check=i(S.check,M,2,0),P=N=0,S.mode=2;break}if(S.flags=0,S.head&&(S.head.done=!1),!(1&S.wrap)||(((255&N)<<8)+(N>>8))%31){T.msg="incorrect header check",S.mode=30;break}if((15&N)!=8){T.msg="unknown compression method",S.mode=30;break}if(P-=4,w=8+(15&(N>>>=4)),S.wbits===0)S.wbits=w;else if(w>S.wbits){T.msg="invalid window size",S.mode=30;break}S.dmax=1<<w,T.adler=S.check=1,S.mode=512&N?10:12,P=N=0;break;case 2:for(;P<16;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(S.flags=N,(255&S.flags)!=8){T.msg="unknown compression method",S.mode=30;break}if(57344&S.flags){T.msg="unknown header flags set",S.mode=30;break}S.head&&(S.head.text=N>>8&1),512&S.flags&&(M[0]=255&N,M[1]=N>>>8&255,S.check=i(S.check,M,2,0)),P=N=0,S.mode=3;case 3:for(;P<32;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}S.head&&(S.head.time=N),512&S.flags&&(M[0]=255&N,M[1]=N>>>8&255,M[2]=N>>>16&255,M[3]=N>>>24&255,S.check=i(S.check,M,4,0)),P=N=0,S.mode=4;case 4:for(;P<16;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}S.head&&(S.head.xflags=255&N,S.head.os=N>>8),512&S.flags&&(M[0]=255&N,M[1]=N>>>8&255,S.check=i(S.check,M,2,0)),P=N=0,S.mode=5;case 5:if(1024&S.flags){for(;P<16;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}S.length=N,S.head&&(S.head.extra_len=N),512&S.flags&&(M[0]=255&N,M[1]=N>>>8&255,S.check=i(S.check,M,2,0)),P=N=0}else S.head&&(S.head.extra=null);S.mode=6;case 6:if(1024&S.flags&&(W<(Y=S.length)&&(Y=W),Y&&(S.head&&(w=S.head.extra_len-S.length,S.head.extra||(S.head.extra=new Array(S.head.extra_len)),e.arraySet(S.head.extra,_,U,Y,w)),512&S.flags&&(S.check=i(S.check,_,Y,U)),W-=Y,U+=Y,S.length-=Y),S.length))break t;S.length=0,S.mode=7;case 7:if(2048&S.flags){if(W===0)break t;for(Y=0;w=_[U+Y++],S.head&&w&&S.length<65536&&(S.head.name+=String.fromCharCode(w)),w&&Y<W;);if(512&S.flags&&(S.check=i(S.check,_,Y,U)),W-=Y,U+=Y,w)break t}else S.head&&(S.head.name=null);S.length=0,S.mode=8;case 8:if(4096&S.flags){if(W===0)break t;for(Y=0;w=_[U+Y++],S.head&&w&&S.length<65536&&(S.head.comment+=String.fromCharCode(w)),w&&Y<W;);if(512&S.flags&&(S.check=i(S.check,_,Y,U)),W-=Y,U+=Y,w)break t}else S.head&&(S.head.comment=null);S.mode=9;case 9:if(512&S.flags){for(;P<16;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(N!==(65535&S.check)){T.msg="header crc mismatch",S.mode=30;break}P=N=0}S.head&&(S.head.hcrc=S.flags>>9&1,S.head.done=!0),T.adler=S.check=0,S.mode=12;break;case 10:for(;P<32;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}T.adler=S.check=f(N),P=N=0,S.mode=11;case 11:if(S.havedict===0)return T.next_out=z,T.avail_out=Q,T.next_in=U,T.avail_in=W,S.hold=N,S.bits=P,2;T.adler=S.check=1,S.mode=12;case 12:if(A===5||A===6)break t;case 13:if(S.last){N>>>=7&P,P-=7&P,S.mode=27;break}for(;P<3;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}switch(S.last=1&N,P-=1,3&(N>>>=1)){case 0:S.mode=14;break;case 1:if(D(S),S.mode=20,A!==6)break;N>>>=2,P-=2;break t;case 2:S.mode=17;break;case 3:T.msg="invalid block type",S.mode=30}N>>>=2,P-=2;break;case 14:for(N>>>=7&P,P-=7&P;P<32;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if((65535&N)!=(N>>>16^65535)){T.msg="invalid stored block lengths",S.mode=30;break}if(S.length=65535&N,P=N=0,S.mode=15,A===6)break t;case 15:S.mode=16;case 16:if(Y=S.length){if(W<Y&&(Y=W),Q<Y&&(Y=Q),Y===0)break t;e.arraySet(J,_,U,Y,z),W-=Y,U+=Y,Q-=Y,z+=Y,S.length-=Y;break}S.mode=12;break;case 17:for(;P<14;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(S.nlen=257+(31&N),N>>>=5,P-=5,S.ndist=1+(31&N),N>>>=5,P-=5,S.ncode=4+(15&N),N>>>=4,P-=4,286<S.nlen||30<S.ndist){T.msg="too many length or distance symbols",S.mode=30;break}S.have=0,S.mode=18;case 18:for(;S.have<S.ncode;){for(;P<3;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}S.lens[j[S.have++]]=7&N,N>>>=3,P-=3}for(;S.have<19;)S.lens[j[S.have++]]=0;if(S.lencode=S.lendyn,S.lenbits=7,$={bits:S.lenbits},B=r(0,S.lens,0,19,S.lencode,0,S.work,$),S.lenbits=$.bits,B){T.msg="invalid code lengths set",S.mode=30;break}S.have=0,S.mode=19;case 19:for(;S.have<S.nlen+S.ndist;){for(;rt=(F=S.lencode[N&(1<<S.lenbits)-1])>>>16&255,at=65535&F,!((nt=F>>>24)<=P);){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(at<16)N>>>=nt,P-=nt,S.lens[S.have++]=at;else{if(at===16){for(x=nt+2;P<x;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(N>>>=nt,P-=nt,S.have===0){T.msg="invalid bit length repeat",S.mode=30;break}w=S.lens[S.have-1],Y=3+(3&N),N>>>=2,P-=2}else if(at===17){for(x=nt+3;P<x;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}P-=nt,w=0,Y=3+(7&(N>>>=nt)),N>>>=3,P-=3}else{for(x=nt+7;P<x;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}P-=nt,w=0,Y=11+(127&(N>>>=nt)),N>>>=7,P-=7}if(S.have+Y>S.nlen+S.ndist){T.msg="invalid bit length repeat",S.mode=30;break}for(;Y--;)S.lens[S.have++]=w}}if(S.mode===30)break;if(S.lens[256]===0){T.msg="invalid code -- missing end-of-block",S.mode=30;break}if(S.lenbits=9,$={bits:S.lenbits},B=r(o,S.lens,0,S.nlen,S.lencode,0,S.work,$),S.lenbits=$.bits,B){T.msg="invalid literal/lengths set",S.mode=30;break}if(S.distbits=6,S.distcode=S.distdyn,$={bits:S.distbits},B=r(a,S.lens,S.nlen,S.ndist,S.distcode,0,S.work,$),S.distbits=$.bits,B){T.msg="invalid distances set",S.mode=30;break}if(S.mode=20,A===6)break t;case 20:S.mode=21;case 21:if(6<=W&&258<=Q){T.next_out=z,T.avail_out=Q,T.next_in=U,T.avail_in=W,S.hold=N,S.bits=P,n(T,q),z=T.next_out,J=T.output,Q=T.avail_out,U=T.next_in,_=T.input,W=T.avail_in,N=S.hold,P=S.bits,S.mode===12&&(S.back=-1);break}for(S.back=0;rt=(F=S.lencode[N&(1<<S.lenbits)-1])>>>16&255,at=65535&F,!((nt=F>>>24)<=P);){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(rt&&!(240&rt)){for(it=nt,gt=rt,ft=at;rt=(F=S.lencode[ft+((N&(1<<it+gt)-1)>>it)])>>>16&255,at=65535&F,!(it+(nt=F>>>24)<=P);){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}N>>>=it,P-=it,S.back+=it}if(N>>>=nt,P-=nt,S.back+=nt,S.length=at,rt===0){S.mode=26;break}if(32&rt){S.back=-1,S.mode=12;break}if(64&rt){T.msg="invalid literal/length code",S.mode=30;break}S.extra=15&rt,S.mode=22;case 22:if(S.extra){for(x=S.extra;P<x;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}S.length+=N&(1<<S.extra)-1,N>>>=S.extra,P-=S.extra,S.back+=S.extra}S.was=S.length,S.mode=23;case 23:for(;rt=(F=S.distcode[N&(1<<S.distbits)-1])>>>16&255,at=65535&F,!((nt=F>>>24)<=P);){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(!(240&rt)){for(it=nt,gt=rt,ft=at;rt=(F=S.distcode[ft+((N&(1<<it+gt)-1)>>it)])>>>16&255,at=65535&F,!(it+(nt=F>>>24)<=P);){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}N>>>=it,P-=it,S.back+=it}if(N>>>=nt,P-=nt,S.back+=nt,64&rt){T.msg="invalid distance code",S.mode=30;break}S.offset=at,S.extra=15&rt,S.mode=24;case 24:if(S.extra){for(x=S.extra;P<x;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}S.offset+=N&(1<<S.extra)-1,N>>>=S.extra,P-=S.extra,S.back+=S.extra}if(S.offset>S.dmax){T.msg="invalid distance too far back",S.mode=30;break}S.mode=25;case 25:if(Q===0)break t;if(Y=q-Q,S.offset>Y){if((Y=S.offset-Y)>S.whave&&S.sane){T.msg="invalid distance too far back",S.mode=30;break}ct=Y>S.wnext?(Y-=S.wnext,S.wsize-Y):S.wnext-Y,Y>S.length&&(Y=S.length),pt=S.window}else pt=J,ct=z-S.offset,Y=S.length;for(Q<Y&&(Y=Q),Q-=Y,S.length-=Y;J[z++]=pt[ct++],--Y;);S.length===0&&(S.mode=21);break;case 26:if(Q===0)break t;J[z++]=S.length,Q--,S.mode=21;break;case 27:if(S.wrap){for(;P<32;){if(W===0)break t;W--,N|=_[U++]<<P,P+=8}if(q-=Q,T.total_out+=q,S.total+=q,q&&(T.adler=S.check=S.flags?i(S.check,J,q,z-q):s(S.check,J,q,z-q)),q=Q,(S.flags?N:f(N))!==S.check){T.msg="incorrect data check",S.mode=30;break}P=N=0}S.mode=28;case 28:if(S.wrap&&S.flags){for(;P<32;){if(W===0)break t;W--,N+=_[U++]<<P,P+=8}if(N!==(4294967295&S.total)){T.msg="incorrect length check",S.mode=30;break}P=N=0}S.mode=29;case 29:B=1;break t;case 30:B=-3;break t;case 31:return-4;case 32:default:return c}return T.next_out=z,T.avail_out=Q,T.next_in=U,T.avail_in=W,S.hold=N,S.bits=P,(S.wsize||q!==T.avail_out&&S.mode<30&&(S.mode<27||A!==4))&&H(T,T.output,T.next_out,q-T.avail_out)?(S.mode=31,-4):(X-=T.avail_in,q-=T.avail_out,T.total_in+=X,T.total_out+=q,S.total+=q,S.wrap&&q&&(T.adler=S.check=S.flags?i(S.check,J,q,T.next_out-q):s(S.check,J,q,T.next_out-q)),T.data_type=S.bits+(S.last?64:0)+(S.mode===12?128:0)+(S.mode===20||S.mode===15?256:0),(X==0&&q===0||A===4)&&B===l&&(B=-5),B)},t.inflateEnd=function(T){if(!T||!T.state)return c;var A=T.state;return A.window&&(A.window=null),T.state=null,l},t.inflateGetHeader=function(T,A){var S;return T&&T.state&&2&(S=T.state).wrap?((S.head=A).done=!1,l):c},t.inflateSetDictionary=function(T,A){var S,_=A.length;return T&&T.state?(S=T.state).wrap!==0&&S.mode!==11?c:S.mode===11&&s(1,A,_,0)!==S.check?-3:H(T,A,_,_)?(S.mode=31,-4):(S.havedict=1,l):c},t.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(g,h,t){"use strict";var e=g("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],i=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],r=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];h.exports=function(o,a,l,c,p,u,d,f){var m,v,y,b,k,C,I,E,D,H=f.bits,T=0,A=0,S=0,_=0,J=0,U=0,z=0,W=0,Q=0,N=0,P=null,X=0,q=new e.Buf16(16),Y=new e.Buf16(16),ct=null,pt=0;for(T=0;T<=15;T++)q[T]=0;for(A=0;A<c;A++)q[a[l+A]]++;for(J=H,_=15;1<=_&&q[_]===0;_--);if(_<J&&(J=_),_===0)return p[u++]=20971520,p[u++]=20971520,f.bits=1,0;for(S=1;S<_&&q[S]===0;S++);for(J<S&&(J=S),T=W=1;T<=15;T++)if(W<<=1,(W-=q[T])<0)return-1;if(0<W&&(o===0||_!==1))return-1;for(Y[1]=0,T=1;T<15;T++)Y[T+1]=Y[T]+q[T];for(A=0;A<c;A++)a[l+A]!==0&&(d[Y[a[l+A]]++]=A);if(C=o===0?(P=ct=d,19):o===1?(P=s,X-=257,ct=i,pt-=257,256):(P=n,ct=r,-1),T=S,k=u,z=A=N=0,y=-1,b=(Q=1<<(U=J))-1,o===1&&852<Q||o===2&&592<Q)return 1;for(;;){for(I=T-z,D=d[A]<C?(E=0,d[A]):d[A]>C?(E=ct[pt+d[A]],P[X+d[A]]):(E=96,0),m=1<<T-z,S=v=1<<U;p[k+(N>>z)+(v-=m)]=I<<24|E<<16|D|0,v!==0;);for(m=1<<T-1;N&m;)m>>=1;if(m!==0?(N&=m-1,N+=m):N=0,A++,--q[T]==0){if(T===_)break;T=a[l+d[A]]}if(J<T&&(N&b)!==y){for(z===0&&(z=J),k+=S,W=1<<(U=T-z);U+z<_&&!((W-=q[U+z])<=0);)U++,W<<=1;if(Q+=1<<U,o===1&&852<Q||o===2&&592<Q)return 1;p[y=N&b]=J<<24|U<<16|k-u|0}}return N!==0&&(p[k+N]=T-z<<24|64<<16|0),f.bits=J,0}},{"../utils/common":41}],51:[function(g,h,t){"use strict";h.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(g,h,t){"use strict";var e=g("../utils/common"),s=0,i=1;function n(F){for(var M=F.length;0<=--M;)F[M]=0}var r=0,o=29,a=256,l=a+1+o,c=30,p=19,u=2*l+1,d=15,f=16,m=7,v=256,y=16,b=17,k=18,C=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],I=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],E=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],D=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],H=new Array(2*(l+2));n(H);var T=new Array(2*c);n(T);var A=new Array(512);n(A);var S=new Array(256);n(S);var _=new Array(o);n(_);var J,U,z,W=new Array(c);function Q(F,M,j,V,L){this.static_tree=F,this.extra_bits=M,this.extra_base=j,this.elems=V,this.max_length=L,this.has_stree=F&&F.length}function N(F,M){this.dyn_tree=F,this.max_code=0,this.stat_desc=M}function P(F){return F<256?A[F]:A[256+(F>>>7)]}function X(F,M){F.pending_buf[F.pending++]=255&M,F.pending_buf[F.pending++]=M>>>8&255}function q(F,M,j){F.bi_valid>f-j?(F.bi_buf|=M<<F.bi_valid&65535,X(F,F.bi_buf),F.bi_buf=M>>f-F.bi_valid,F.bi_valid+=j-f):(F.bi_buf|=M<<F.bi_valid&65535,F.bi_valid+=j)}function Y(F,M,j){q(F,j[2*M],j[2*M+1])}function ct(F,M){for(var j=0;j|=1&F,F>>>=1,j<<=1,0<--M;);return j>>>1}function pt(F,M,j){var V,L,K=new Array(d+1),tt=0;for(V=1;V<=d;V++)K[V]=tt=tt+j[V-1]<<1;for(L=0;L<=M;L++){var Z=F[2*L+1];Z!==0&&(F[2*L]=ct(K[Z]++,Z))}}function nt(F){var M;for(M=0;M<l;M++)F.dyn_ltree[2*M]=0;for(M=0;M<c;M++)F.dyn_dtree[2*M]=0;for(M=0;M<p;M++)F.bl_tree[2*M]=0;F.dyn_ltree[2*v]=1,F.opt_len=F.static_len=0,F.last_lit=F.matches=0}function rt(F){8<F.bi_valid?X(F,F.bi_buf):0<F.bi_valid&&(F.pending_buf[F.pending++]=F.bi_buf),F.bi_buf=0,F.bi_valid=0}function at(F,M,j,V){var L=2*M,K=2*j;return F[L]<F[K]||F[L]===F[K]&&V[M]<=V[j]}function it(F,M,j){for(var V=F.heap[j],L=j<<1;L<=F.heap_len&&(L<F.heap_len&&at(M,F.heap[L+1],F.heap[L],F.depth)&&L++,!at(M,V,F.heap[L],F.depth));)F.heap[j]=F.heap[L],j=L,L<<=1;F.heap[j]=V}function gt(F,M,j){var V,L,K,tt,Z=0;if(F.last_lit!==0)for(;V=F.pending_buf[F.d_buf+2*Z]<<8|F.pending_buf[F.d_buf+2*Z+1],L=F.pending_buf[F.l_buf+Z],Z++,V===0?Y(F,L,M):(Y(F,(K=S[L])+a+1,M),(tt=C[K])!==0&&q(F,L-=_[K],tt),Y(F,K=P(--V),j),(tt=I[K])!==0&&q(F,V-=W[K],tt)),Z<F.last_lit;);Y(F,v,M)}function ft(F,M){var j,V,L,K=M.dyn_tree,tt=M.stat_desc.static_tree,Z=M.stat_desc.has_stree,st=M.stat_desc.elems,ut=-1;for(F.heap_len=0,F.heap_max=u,j=0;j<st;j++)K[2*j]!==0?(F.heap[++F.heap_len]=ut=j,F.depth[j]=0):K[2*j+1]=0;for(;F.heap_len<2;)K[2*(L=F.heap[++F.heap_len]=ut<2?++ut:0)]=1,F.depth[L]=0,F.opt_len--,Z&&(F.static_len-=tt[2*L+1]);for(M.max_code=ut,j=F.heap_len>>1;1<=j;j--)it(F,K,j);for(L=st;j=F.heap[1],F.heap[1]=F.heap[F.heap_len--],it(F,K,1),V=F.heap[1],F.heap[--F.heap_max]=j,F.heap[--F.heap_max]=V,K[2*L]=K[2*j]+K[2*V],F.depth[L]=(F.depth[j]>=F.depth[V]?F.depth[j]:F.depth[V])+1,K[2*j+1]=K[2*V+1]=L,F.heap[1]=L++,it(F,K,1),2<=F.heap_len;);F.heap[--F.heap_max]=F.heap[1],function(lt,Et){var ce,Dt,de,vt,Ie,ws,_t=Et.dyn_tree,js=Et.max_code,Ei=Et.stat_desc.static_tree,Ii=Et.stat_desc.has_stree,Ai=Et.stat_desc.extra_bits,Us=Et.stat_desc.extra_base,he=Et.stat_desc.max_length,Ae=0;for(vt=0;vt<=d;vt++)lt.bl_count[vt]=0;for(_t[2*lt.heap[lt.heap_max]+1]=0,ce=lt.heap_max+1;ce<u;ce++)he<(vt=_t[2*_t[2*(Dt=lt.heap[ce])+1]+1]+1)&&(vt=he,Ae++),_t[2*Dt+1]=vt,js<Dt||(lt.bl_count[vt]++,Ie=0,Us<=Dt&&(Ie=Ai[Dt-Us]),ws=_t[2*Dt],lt.opt_len+=ws*(vt+Ie),Ii&&(lt.static_len+=ws*(Ei[2*Dt+1]+Ie)));if(Ae!==0){do{for(vt=he-1;lt.bl_count[vt]===0;)vt--;lt.bl_count[vt]--,lt.bl_count[vt+1]+=2,lt.bl_count[he]--,Ae-=2}while(0<Ae);for(vt=he;vt!==0;vt--)for(Dt=lt.bl_count[vt];Dt!==0;)js<(de=lt.heap[--ce])||(_t[2*de+1]!==vt&&(lt.opt_len+=(vt-_t[2*de+1])*_t[2*de],_t[2*de+1]=vt),Dt--)}}(F,M),pt(K,ut,F.bl_count)}function w(F,M,j){var V,L,K=-1,tt=M[1],Z=0,st=7,ut=4;for(tt===0&&(st=138,ut=3),M[2*(j+1)+1]=65535,V=0;V<=j;V++)L=tt,tt=M[2*(V+1)+1],++Z<st&&L===tt||(Z<ut?F.bl_tree[2*L]+=Z:L!==0?(L!==K&&F.bl_tree[2*L]++,F.bl_tree[2*y]++):Z<=10?F.bl_tree[2*b]++:F.bl_tree[2*k]++,K=L,ut=(Z=0)===tt?(st=138,3):L===tt?(st=6,3):(st=7,4))}function B(F,M,j){var V,L,K=-1,tt=M[1],Z=0,st=7,ut=4;for(tt===0&&(st=138,ut=3),V=0;V<=j;V++)if(L=tt,tt=M[2*(V+1)+1],!(++Z<st&&L===tt)){if(Z<ut)for(;Y(F,L,F.bl_tree),--Z!=0;);else L!==0?(L!==K&&(Y(F,L,F.bl_tree),Z--),Y(F,y,F.bl_tree),q(F,Z-3,2)):Z<=10?(Y(F,b,F.bl_tree),q(F,Z-3,3)):(Y(F,k,F.bl_tree),q(F,Z-11,7));K=L,ut=(Z=0)===tt?(st=138,3):L===tt?(st=6,3):(st=7,4)}}n(W);var $=!1;function x(F,M,j,V){q(F,(r<<1)+(V?1:0),3),function(L,K,tt,Z){rt(L),Z&&(X(L,tt),X(L,~tt)),e.arraySet(L.pending_buf,L.window,K,tt,L.pending),L.pending+=tt}(F,M,j,!0)}t._tr_init=function(F){$||(function(){var M,j,V,L,K,tt=new Array(d+1);for(L=V=0;L<o-1;L++)for(_[L]=V,M=0;M<1<<C[L];M++)S[V++]=L;for(S[V-1]=L,L=K=0;L<16;L++)for(W[L]=K,M=0;M<1<<I[L];M++)A[K++]=L;for(K>>=7;L<c;L++)for(W[L]=K<<7,M=0;M<1<<I[L]-7;M++)A[256+K++]=L;for(j=0;j<=d;j++)tt[j]=0;for(M=0;M<=143;)H[2*M+1]=8,M++,tt[8]++;for(;M<=255;)H[2*M+1]=9,M++,tt[9]++;for(;M<=279;)H[2*M+1]=7,M++,tt[7]++;for(;M<=287;)H[2*M+1]=8,M++,tt[8]++;for(pt(H,l+1,tt),M=0;M<c;M++)T[2*M+1]=5,T[2*M]=ct(M,5);J=new Q(H,C,a+1,l,d),U=new Q(T,I,0,c,d),z=new Q(new Array(0),E,0,p,m)}(),$=!0),F.l_desc=new N(F.dyn_ltree,J),F.d_desc=new N(F.dyn_dtree,U),F.bl_desc=new N(F.bl_tree,z),F.bi_buf=0,F.bi_valid=0,nt(F)},t._tr_stored_block=x,t._tr_flush_block=function(F,M,j,V){var L,K,tt=0;0<F.level?(F.strm.data_type===2&&(F.strm.data_type=function(Z){var st,ut=4093624447;for(st=0;st<=31;st++,ut>>>=1)if(1&ut&&Z.dyn_ltree[2*st]!==0)return s;if(Z.dyn_ltree[18]!==0||Z.dyn_ltree[20]!==0||Z.dyn_ltree[26]!==0)return i;for(st=32;st<a;st++)if(Z.dyn_ltree[2*st]!==0)return i;return s}(F)),ft(F,F.l_desc),ft(F,F.d_desc),tt=function(Z){var st;for(w(Z,Z.dyn_ltree,Z.l_desc.max_code),w(Z,Z.dyn_dtree,Z.d_desc.max_code),ft(Z,Z.bl_desc),st=p-1;3<=st&&Z.bl_tree[2*D[st]+1]===0;st--);return Z.opt_len+=3*(st+1)+5+5+4,st}(F),L=F.opt_len+3+7>>>3,(K=F.static_len+3+7>>>3)<=L&&(L=K)):L=K=j+5,j+4<=L&&M!==-1?x(F,M,j,V):F.strategy===4||K===L?(q(F,2+(V?1:0),3),gt(F,H,T)):(q(F,4+(V?1:0),3),function(Z,st,ut,lt){var Et;for(q(Z,st-257,5),q(Z,ut-1,5),q(Z,lt-4,4),Et=0;Et<lt;Et++)q(Z,Z.bl_tree[2*D[Et]+1],3);B(Z,Z.dyn_ltree,st-1),B(Z,Z.dyn_dtree,ut-1)}(F,F.l_desc.max_code+1,F.d_desc.max_code+1,tt+1),gt(F,F.dyn_ltree,F.dyn_dtree)),nt(F),V&&rt(F)},t._tr_tally=function(F,M,j){return F.pending_buf[F.d_buf+2*F.last_lit]=M>>>8&255,F.pending_buf[F.d_buf+2*F.last_lit+1]=255&M,F.pending_buf[F.l_buf+F.last_lit]=255&j,F.last_lit++,M===0?F.dyn_ltree[2*j]++:(F.matches++,M--,F.dyn_ltree[2*(S[j]+a+1)]++,F.dyn_dtree[2*P(M)]++),F.last_lit===F.lit_bufsize-1},t._tr_align=function(F){q(F,2,3),Y(F,v,H),function(M){M.bi_valid===16?(X(M,M.bi_buf),M.bi_buf=0,M.bi_valid=0):8<=M.bi_valid&&(M.pending_buf[M.pending++]=255&M.bi_buf,M.bi_buf>>=8,M.bi_valid-=8)}(F)}},{"../utils/common":41}],53:[function(g,h,t){"use strict";h.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(g,h,t){(function(e){(function(s,i){"use strict";if(!s.setImmediate){var n,r,o,a,l=1,c={},p=!1,u=s.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(s);d=d&&d.setTimeout?d:s,n={}.toString.call(s.process)==="[object process]"?function(y){process.nextTick(function(){m(y)})}:function(){if(s.postMessage&&!s.importScripts){var y=!0,b=s.onmessage;return s.onmessage=function(){y=!1},s.postMessage("","*"),s.onmessage=b,y}}()?(a="setImmediate$"+Math.random()+"$",s.addEventListener?s.addEventListener("message",v,!1):s.attachEvent("onmessage",v),function(y){s.postMessage(a+y,"*")}):s.MessageChannel?((o=new MessageChannel).port1.onmessage=function(y){m(y.data)},function(y){o.port2.postMessage(y)}):u&&"onreadystatechange"in u.createElement("script")?(r=u.documentElement,function(y){var b=u.createElement("script");b.onreadystatechange=function(){m(y),b.onreadystatechange=null,r.removeChild(b),b=null},r.appendChild(b)}):function(y){setTimeout(m,0,y)},d.setImmediate=function(y){typeof y!="function"&&(y=new Function(""+y));for(var b=new Array(arguments.length-1),k=0;k<b.length;k++)b[k]=arguments[k+1];var C={callback:y,args:b};return c[l]=C,n(l),l++},d.clearImmediate=f}function f(y){delete c[y]}function m(y){if(p)setTimeout(m,0,y);else{var b=c[y];if(b){p=!0;try{(function(k){var C=k.callback,I=k.args;switch(I.length){case 0:C();break;case 1:C(I[0]);break;case 2:C(I[0],I[1]);break;case 3:C(I[0],I[1],I[2]);break;default:C.apply(i,I)}})(b)}finally{f(y),p=!1}}}}function v(y){y.source===s&&typeof y.data=="string"&&y.data.indexOf(a)===0&&m(+y.data.slice(a.length))}})(typeof self>"u"?e===void 0?this:e:self)}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})});var dn={};Pe(dn,{default:()=>ys});module.exports=$i(dn);var et=require("obsidian");Tt();var Ct=require("obsidian");var wt=require("obsidian");Tt();function _e(g){let h=(g.dateDisplayTimezone||"").trim();return h?{timeZone:h}:{}}function Lt(g,h){try{return new Intl.DateTimeFormat(void 0,h).format(new Date(g))}catch{let{timeZone:t,...e}=h;return new Intl.DateTimeFormat(void 0,e).format(new Date(g))}}function Yt(g,h){let t=_e(h);switch(h.dateDisplayFormat??"locale"){case"iso":return Xs(g,h,!0);case"us":return Lt(g,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Lt(g,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Lt(g,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Lt(g,{...t,dateStyle:"medium",timeStyle:"short"})}}function Gs(g,h){let t=_e(h);switch(h.dateDisplayFormat??"locale"){case"iso":return Xs(g,h,!1);case"us":return Lt(g,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Lt(g,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Lt(g,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,s=new Date(g).getFullYear()===e.getFullYear();return Lt(g,s?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Js(g,h){let t=_e(h),e=h.dateDisplayFormat==="iso"||h.dateDisplayFormat==="eu";return Lt(g,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Xs(g,h,t){let e=_e(h),s=new Intl.DateTimeFormat("en-CA",{...e,year:"numeric",month:"2-digit",day:"2-digit",...t?{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}:{}}).formatToParts(new Date(g)),i=r=>s.find(o=>o.type===r)?.value??"",n=`${i("year")}-${i("month")}-${i("day")}`;return t?`${n} ${i("hour")}:${i("minute")}`:n}function $e(g,h,t){let e=g.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(h>99?"99+":String(h))}var Se={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},Re=class extends wt.ItemView{constructor(t,e){super(t);this.plugin=e;this.activePanel="pinned";this.taskFilter="all";this.taskAssignFilter="all";this.expanded=new Set;this.renderTimer=null;this.sharedAuthorFilter="all";this.sharedContribOnly=!1}setActivePanel(t){this.activePanel=t,this.containerEl.isConnected&&this.render()}getViewType(){return $t}getDisplayText(){return"Stashpad panels"}getIcon(){return"panel-left"}async onOpen(){this.render(),this.registerEvent(this.app.metadataCache.on("changed",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("rename",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("delete",()=>this.scheduleRender())),this.registerEvent(this.app.workspace.on("active-leaf-change",t=>{t&&t.view.getViewType()===mt&&this.scheduleRender()}))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},80))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-panels-root");let e=t.createDiv({cls:"stashpad-panels-globals"}),s=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,wt.setIcon)(s.createSpan({cls:"stashpad-panels-global-btn-icon"}),"search"),s.createSpan({cls:"stashpad-panels-global-btn-text",text:"Search"}),s.onclick=()=>this.openSearchFromPanel();let i=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,wt.setIcon)(i.createSpan({cls:"stashpad-panels-global-btn-icon"}),"folder-tree"),i.createSpan({cls:"stashpad-panels-global-btn-text",text:"Folder Switcher"}),i.onclick=()=>this.plugin.openFolderPicker();let n=e.createDiv({cls:"stashpad-panels-globals-row"}),r=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,wt.setIcon)(r.createSpan({cls:"stashpad-panels-global-btn-icon"}),"scroll-text"),r.createSpan({cls:"stashpad-panels-global-btn-text",text:"Log"}),r.onclick=()=>this.openLogFromPanel();let o=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,wt.setIcon)(o.createSpan({cls:"stashpad-panels-global-btn-icon"}),"bell"),o.createSpan({cls:"stashpad-panels-global-btn-text",text:"Notifications"}),o.onclick=()=>this.openNotificationsFromPanel();let a=t.createDiv({cls:"stashpad-panels-bar"});for(let c of Object.keys(Se)){let p=Se[c],u=a.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,wt.setIcon)(u.createSpan({cls:"stashpad-panels-bar-btn-icon"}),p.icon),u.createSpan({cls:"stashpad-panels-bar-btn-text",text:p.label}),this.activePanel===c&&u.addClass("is-active"),u.onclick=()=>{this.activePanel!==c&&(this.activePanel=c,this.render())}}let l=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(l):this.activePanel==="shared"?this.renderSharedPanel(l):this.activePanel==="tasks"&&this.renderTasksPanel(l)}renderPinnedPanel(t){let e=t.createDiv({cls:"stashpad-panel-pinned"}),s=e.createEl("button",{cls:"stashpad-pinned-row stashpad-pinned-home"}),i=s.createSpan({cls:"stashpad-pinned-icon"});(0,wt.setIcon)(i,"home"),s.createSpan({cls:"stashpad-pinned-label",text:"Home"}),s.onclick=()=>this.openHomeFromPanel();let n=this.plugin.settings.pinnedNotes??[];if(n.length===0){e.createDiv({cls:"stashpad-pinned-empty"}).setText("No pinned notes yet \u2014 right-click a note and choose \u201CPin to sidebar.\u201D");return}let r=new Map;n.forEach((l,c)=>{let p=r.get(l.folder);p||(p=[],r.set(l.folder,p)),p.push({pin:l,idx:c})});let o=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,a=Array.from(r.keys());o&&r.has(o)&&(a.splice(a.indexOf(o),1),a.unshift(o));for(let l of a){let c=l.split("/").pop()||l,p=e.createDiv({cls:"stashpad-pinned-group-header"});l===o&&p.addClass("is-active-folder"),p.createSpan({cls:"stashpad-pinned-group-name",text:c});let u=r.get(l)??[];for(let{pin:d,idx:f}of u)this.renderPinnedRow(e,d,f)}}renderPinnedRow(t,e,s){let i=this.findFileFor(e);if(!i)return;let n=this.app.metadataCache.getFileCache(i)?.frontmatter??{},r=this.titleFromFile(i),o=typeof n.color=="string"?n.color:null,a=n.completed===!0,l=this.childrenOf(e.folder,e.id).length,c=l>0,p=this.expanded.has(`${e.folder}|${e.id}`),u=t.createDiv({cls:"stashpad-pinned-row"});o&&u.addClass("has-color"),a&&u.addClass("is-completed"),u.draggable=!0,u.dataset.pinIdx=String(s),u.addEventListener("dragstart",y=>{y.dataTransfer?.setData("text/plain",String(s)),y.dataTransfer&&(y.dataTransfer.effectAllowed="move"),u.addClass("is-dragging")}),u.addEventListener("dragend",()=>u.removeClass("is-dragging")),u.addEventListener("dragover",y=>{y.preventDefault(),y.dataTransfer&&(y.dataTransfer.dropEffect="move");let b=u.getBoundingClientRect(),k=y.clientY-b.top<b.height/2;u.toggleClass("drop-before",k),u.toggleClass("drop-after",!k)}),u.addEventListener("dragleave",()=>{u.removeClass("drop-before"),u.removeClass("drop-after")}),u.addEventListener("drop",y=>{y.preventDefault(),u.removeClass("drop-before"),u.removeClass("drop-after");let b=parseInt(y.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(b)||b===s)return;let k=u.getBoundingClientRect(),C=y.clientY-k.top<k.height/2;this.reorderPin(b,C?s:s+1)});let d=u.createSpan({cls:"stashpad-pinned-toggle"});c&&($e(d,l,p),d.onclick=y=>{y.stopPropagation();let b=`${e.folder}|${e.id}`;this.expanded.has(b)?this.expanded.delete(b):this.expanded.add(b),this.render()});let f=u.createSpan({cls:"stashpad-pinned-icon"});(0,wt.setIcon)(f,c?"folder-tree":"file-text"),o&&(f.style.color=o);let m=u.createSpan({cls:"stashpad-pinned-label",text:r});m.onclick=()=>this.openPinFromPanel(e);let v=e.folder.split("/").pop()||e.folder;if(u.createSpan({cls:"stashpad-pinned-folder",text:v}),u.oncontextmenu=y=>{y.preventDefault();let b=new wt.Menu;b.addItem(k=>k.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),b.showAtMouseEvent(y)},c&&p){let y=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(y,e.folder,e.id,1)}}async reorderPin(t,e){let s=(this.plugin.settings.pinnedNotes??[]).slice();if(t<0||t>=s.length)return;let[i]=s.splice(t,1),n=e>t?e-1:e;s.splice(Math.max(0,Math.min(n,s.length)),0,i),this.plugin.settings.pinnedNotes=s,await this.plugin.saveSettings(),this.render()}renderPinnedSubtree(t,e,s,i){let n=this.childrenOf(e,s);for(let r of n){let o=this.app.metadataCache.getFileCache(r)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a)continue;let l=typeof o.color=="string"?o.color:null,c=o.completed===!0,p=this.childrenOf(e,a).length,u=p>0,d=this.expanded.has(`${e}|${a}`),f=t.createDiv({cls:"stashpad-pinned-subrow"});c&&f.addClass("is-completed"),f.style.paddingLeft=`${i*16}px`;let m=f.createSpan({cls:"stashpad-pinned-toggle"});u&&($e(m,p,d),m.onclick=b=>{b.stopPropagation();let k=`${e}|${a}`;this.expanded.has(k)?this.expanded.delete(k):this.expanded.add(k),this.render()});let v=f.createSpan({cls:"stashpad-pinned-icon"});(0,wt.setIcon)(v,"file-text"),l&&(v.style.color=l);let y=f.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(r)});y.onclick=()=>this.openPinFromPanel({folder:e,id:a}),u&&d&&this.renderPinnedSubtree(t,e,a,i+1)}}findFileFor(t){for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==t.folder)continue;if(this.app.metadataCache.getFileCache(e)?.frontmatter?.id===t.id)return e}return null}childrenOf(t,e){let s=[];for(let i of this.app.vault.getMarkdownFiles()){if((i.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let r=this.app.metadataCache.getFileCache(i)?.frontmatter;if(!r||typeof r.id!="string")continue;let o=r.parent;if(o===e||e===R&&(o==null||o===R)){if(r.id===R)continue;s.push(i)}}return s.sort((i,n)=>{let r=this.app.metadataCache.getFileCache(i)?.frontmatter,o=this.app.metadataCache.getFileCache(n)?.frontmatter,a=r?.created??"",l=o?.created??"";return a.localeCompare(l)}),s}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}async openSearchFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.openSearchModal=="function"&&t.openSearchModal()}async openLogFromPanel(){let t=this.app.vault.adapter,e=this.plugin.pluginPrivatePath("log.jsonl");if(!await t.exists(e)){new wt.Notice("No log yet \u2014 make some changes first.");return}let s=await t.read(e),{LogModal:i}=await Promise.resolve().then(()=>(Bt(),be));new i(this.app,s,e).open()}openNotificationsFromPanel(){this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")}async openHomeFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.navigateTo=="function"&&t.navigateTo(R)}async openPinFromPanel(t){await this.plugin.activateViewForFolder(t.folder);let e=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();e&&typeof e.navigateTo=="function"&&e.navigateTo(t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===mt)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let s=this.app.workspace.getLeavesOfType(mt);return s.length>0?(this.app.workspace.revealLeaf(s[0]),s[0].view):(await this.plugin.activateView({reveal:!0}),this.findActiveStashpad())}findActiveStashpad(){let t=this.app.workspace.activeLeaf;return t&&t.view.getViewType()===mt?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),s=(this.plugin.settings.authorId??"").trim();if(!s){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let i=this.collectSharedNotes(s),n=new Map;for(let c of i){let p=c.authorId;p&&!n.has(p)&&n.set(p,c.authorDisplay||p)}let r=e.createDiv({cls:"stashpad-shared-filters"}),o=(c,p,u)=>{let d=r.createEl("button",{cls:"stashpad-shared-chip",text:c});return p&&d.addClass("is-active"),d.onclick=u,d};if(o("All",this.sharedAuthorFilter==="all",()=>{this.sharedAuthorFilter="all",this.render()}),o("Mine",this.sharedAuthorFilter==="mine",()=>{this.sharedAuthorFilter="mine",this.render()}),o("Others",this.sharedAuthorFilter==="others",()=>{this.sharedAuthorFilter="others",this.render()}),n.size>1){let c=r.createEl("select",{cls:"stashpad-shared-author-select"}),p=c.createEl("option",{text:"Any author"});p.value="__any__";for(let[d,f]of n){let m=c.createEl("option",{text:f});m.value=d}let u=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;c.value=u,c.onchange=()=>{let d=c.value;d==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=d,this.render()}}let a=r.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&a.addClass("is-active"),a.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let l=i.filter(c=>{if(this.sharedContribOnly&&c.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return c.authorId===s;case"others":return c.authorId!==s;default:return c.authorId===this.sharedAuthorFilter}});if(l.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let c of l){let p=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),u=p.createSpan({cls:"stashpad-pinned-icon"});(0,wt.setIcon)(u,"users"),c.color&&(u.style.color=c.color);let d=p.createSpan({cls:"stashpad-pinned-label",text:c.title});d.onclick=()=>this.openSharedFromPanel(c.folder,c.id);let f=c.folder.split("/").pop()||c.folder;p.createSpan({cls:"stashpad-pinned-folder",text:f}),c.authorDisplay&&p.createSpan({cls:"stashpad-shared-meta"}).setText(c.authorId===s?`you \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:`by ${c.authorDisplay}${c.contributorCount>0?` \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:""}`)}}collectSharedNotes(t){let e=this.plugin.discoverStashpadFolders(),s=new Set(e),i=new Map;for(let r of this.app.vault.getMarkdownFiles()){let o=r.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(o))continue;let a=this.app.metadataCache.getFileCache(r)?.frontmatter??{};a.id===R&&i.set(o,this.extractAuthorId(a.author))}let n=[];for(let r of this.app.vault.getMarkdownFiles()){let o=r.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(o)||o.endsWith("/_authors")||r.path.includes("/_authors/"))continue;let a=this.app.metadataCache.getFileCache(r)?.frontmatter??{};if(typeof a.id!="string"||a.id===R)continue;let l=this.extractAuthorId(a.author),c=Array.isArray(a.contributors)?a.contributors.filter(b=>typeof b=="string"):[],p=i.get(o)??null;if(!(c.length>0||p===t&&(l!==null&&l!==t)))continue;let v=this.titleFromFile(r),y=typeof a.color=="string"?a.color:null;n.push({file:r,folder:o,id:a.id,title:v,color:y,authorId:l,authorDisplay:this.extractAuthorDisplay(a.author)||(l??""),contributorCount:c.length})}return n.sort((r,o)=>{let a=this.app.metadataCache.getFileCache(r.file)?.frontmatter??{},l=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},c=a.modified??a.created??"";return(l.modified??l.created??"").localeCompare(c)}),n}extractAuthorId(t){if(typeof t!="string")return null;let e=t.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return e?e[1]:null}extractAuthorDisplay(t){if(typeof t!="string")return"";let e=t.match(/\|([^\]]+)\]\]/);if(e)return e[1].trim();let s=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return s?s[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.activateViewForFolder(t);let s=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();s&&typeof s.navigateTo=="function"&&s.navigateTo(e)}renderTasksPanel(t){let e=t.createDiv({cls:"stashpad-panel-tasks"}),s=this.collectTasks();if(s.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks yet \u2014 press H on a note to mark it a task, or D to give it a due date.");return}let i=(this.plugin.settings.authorId??"").trim(),n=T=>!!i&&T.assignedTo.some(A=>A.id===i),r=T=>{let A=this.taskAssignFilter;if(A.startsWith("person:")){let S=A.slice(7);return T.assignedTo.some(_=>_.id===S)}switch(A){case"mine":return n(T);case"others":return T.assignedTo.length>0&&!n(T);case"byme":return!!i&&T.assignedBy?.id===i;case"unassigned":return T.assignedTo.length===0;default:return!0}},o=new Map;for(let T of s){for(let A of T.assignedTo)A.id!==i&&o.set(A.id,A.name);T.assignedBy&&T.assignedBy.id!==i&&o.set(T.assignedBy.id,T.assignedBy.name)}let a=[...o.entries()].map(([T,A])=>({id:T,name:A})).sort((T,A)=>T.name.localeCompare(A.name)),l=e.createDiv({cls:"stashpad-task-assign-bar"});l.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let c=l.createEl("select",{cls:"stashpad-task-assign-select"}),p=T=>{let A={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return T.startsWith("person:")?o.get(T.slice(7))??"Person":A[T]??T},u=T=>{let A=c.createEl("option",{text:p(T),value:T});this.taskAssignFilter===T&&(A.selected=!0)};for(let T of["all","mine","others","byme","unassigned"])u(T);if(a.length>0){let T=c.createEl("optgroup");T.setAttr("label","By person");for(let A of a){let S=T.createEl("option",{text:A.name,value:`person:${A.id}`});this.taskAssignFilter===`person:${A.id}`&&(S.selected=!0)}}c.onchange=()=>{this.taskAssignFilter=c.value,this.render()};let d=s.filter(r);if(d.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`No tasks match "${p(this.taskAssignFilter)}".`);return}let f=new Date;f.setHours(0,0,0,0);let m=f.getTime(),v=m+24*60*60*1e3,y={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let T of d){if(T.completed){y.completed.push(T);continue}if(T.due==null){y.nodate.push(T);continue}T.due<m?y.overdue.push(T):T.due<v?y.today.push(T):y.upcoming.push(T)}let b=(T,A)=>T.due==null&&A.due==null?T.title.localeCompare(A.title):T.due==null?1:A.due==null?-1:T.due-A.due,k=[{key:"overdue",label:"Overdue",icon:"alert-circle"},{key:"today",label:"Due today",icon:"calendar-clock"},{key:"upcoming",label:"Upcoming",icon:"calendar"},{key:"nodate",label:"No date",icon:"inbox"},{key:"completed",label:"Completed",icon:"check-circle-2"}],C=e.createDiv({cls:"stashpad-task-filters"}),I=d.length,E=(T,A,S)=>{let _=C.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===T&&_.addClass("is-active"),_.createSpan({cls:"stashpad-task-filter-label",text:A}),_.createSpan({cls:"stashpad-task-filter-count",text:String(S)}),_.onclick=()=>{this.taskFilter=T,this.render()}};E("all","All",I),E("overdue","Overdue",y.overdue.length),E("today","Today",y.today.length),E("upcoming","Upcoming",y.upcoming.length),E("nodate","No date",y.nodate.length),E("completed","Done",y.completed.length);let D=this.taskFilter==="all"?k:k.filter(T=>T.key===this.taskFilter),H=!1;for(let T of D){let A=y[T.key];if(A.length!==0){if(H=!0,A.sort(T.key==="completed"?(S,_)=>b(_,S):b),this.taskFilter==="all"){let S=e.createDiv({cls:`stashpad-task-section-header is-${T.key}`});(0,wt.setIcon)(S.createSpan({cls:"stashpad-task-section-icon"}),T.icon),S.createSpan({cls:"stashpad-task-section-name",text:T.label}),S.createSpan({cls:"stashpad-task-section-count",text:String(A.length)})}for(let S of A)this.renderTaskRow(e,S,T.key==="today")}}if(!H&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${D[0]?.label??this.taskFilter}".`);return}H||e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks to show.")}renderTaskRow(t,e,s){let i=t.createDiv({cls:"stashpad-pinned-row stashpad-task-row"});e.color&&i.addClass("has-color"),e.completed&&i.addClass("is-completed");let n=i.createSpan({cls:"stashpad-pinned-icon stashpad-task-checkbox"});(0,wt.setIcon)(n,e.completed?"check-square":"square"),e.color&&(n.style.color=e.color),n.title=e.completed?"Mark not done":"Mark done",n.onclick=o=>{o.stopPropagation(),this.toggleTaskCompleted(e)};let r=i.createSpan({cls:"stashpad-pinned-label",text:e.title});if(r.onclick=()=>this.openTaskFromPanel(e.folder,e.id),i.createSpan({cls:"stashpad-task-folder",text:e.folder.split("/").pop()||e.folder}),e.due!=null){let o=i.createSpan({cls:"stashpad-task-due",text:this.formatDueShort(e.due,s)});e.due<Date.now()&&!e.completed&&o.addClass("is-overdue")}else e.dueRaw&&i.createSpan({cls:"stashpad-task-due",text:e.dueRaw});if(e.assignedTo.length>0){let o=(this.plugin.settings.authorId??"").trim(),a=i.createSpan({cls:"stashpad-task-assignees"});for(let l of e.assignedTo){let c=a.createSpan({cls:"stashpad-task-assignee"});o&&l.id===o&&c.addClass("is-me"),c.setText(this.initials(l.name)),c.title=o&&l.id===o?`${l.name} (you)`:l.name}}i.oncontextmenu=o=>{o.preventDefault();let a=new wt.Menu;a.addItem(l=>l.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),a.showAtMouseEvent(o)}}formatDueShort(t,e){return e?Js(t,this.plugin.settings):Gs(t,this.plugin.settings)}async openTaskFromPanel(t,e){await this.plugin.activateViewForFolder(t);let s=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();s&&typeof s.navigateTo=="function"&&s.navigateTo(e)}async toggleTaskCompleted(t){try{await this.app.fileManager.processFrontMatter(t.file,e=>{e.completed=e.completed!==!0})}catch(e){new wt.Notice(`Couldn't update task: ${e.message}`);return}this.scheduleRender()}initials(t){let e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[e.length-1][0]).toUpperCase()}collectTasks(){let t=this.plugin.discoverStashpadFolders(),e=new Set(t),s=[];for(let i of this.app.vault.getMarkdownFiles()){let n=i.parent?.path?.replace(/\/+$/,"")??"";if(!e.has(n))continue;let r=this.app.metadataCache.getFileCache(i)?.frontmatter??{},o=typeof r.id=="string"?r.id:null;if(!o||o===R)continue;let a=r.completed===!0,l=Vt(r,"task")||r.task===!0||r.completed!==void 0,c=typeof r.due=="string"||typeof r.due=="number"?String(r.due):null,p=null;if(c){let u=Date.parse(c);Number.isNaN(u)||(p=u)}!l&&!a&&p==null&&!c||s.push({file:i,folder:n,id:o,title:this.titleFromFile(i),task:l,completed:a,due:p,dueRaw:c,color:typeof r.color=="string"?r.color:null,assignedTo:ue(r),assignedBy:pe(r.assignedBy)})}return s}};async function Be(g){let h=g.workspace.getLeavesOfType($t);if(h.length>0){g.workspace.revealLeaf(h[0]);return}let t=g.workspace.getLeftLeaf(!1);if(!t){new wt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:$t,active:!0}),g.workspace.revealLeaf(t)}var pi=require("obsidian");Tt();var G=require("obsidian");Te();var je=require("obsidian");Tt();var ne=class extends je.AbstractInputSuggest{constructor(t,e){super(t,e);this.inputEl=e}getSuggestions(t){let e=t.toLowerCase().split(/\s+/).filter(Boolean),s=r=>e.every(o=>r.toLowerCase().includes(o)),i=[],n=r=>{if(!(r.path!=="/"&&Me.has(r.name))){r.path!=="/"&&s(r.path)&&i.push(r);for(let o of r.children)o instanceof je.TFolder&&n(o)}};return n(this.app.vault.getRoot()),i.slice(0,100)}renderSuggestion(t,e){e.setText(t.path)}selectSuggestion(t){this.setValue(t.path),this.inputEl.dispatchEvent(new Event("input",{bubbles:!0})),this.close()}};Tt();Bt();var Ve=require("obsidian"),As={create:{label:"Create",desc:"Confirmations after a new note is created."},edit:{label:"Edit",desc:"Edit-related toasts (currently rare)."},delete:{label:"Delete",desc:"Confirmations after deleting one or more notes."},move:{label:"Move",desc:"After reparenting or moving notes between folders."},merge:{label:"Merge",desc:"After combining multiple notes into one."},split:{label:"Split",desc:"After splitting a note in two."},clone:{label:"Clone",desc:"After duplicating notes or subtrees."},complete:{label:"Complete",desc:"When a note is marked complete."},uncomplete:{label:"Uncomplete",desc:"When a note's complete mark is removed."},export:{label:"Export",desc:".stash exports \u2014 success + the action buttons."},import:{label:"Import",desc:".stash imports (both manual and the drop-folder auto-import)."},attachment:{label:"Attachment",desc:"Attachment add / remove notifications."},color:{label:"Color",desc:"Per-note color changes."},reorder:{label:"Reorder",desc:"Drag-reorder and keyboard moveUp/Down/Top/Bottom."},multiplayer:{label:"Multiplayer",desc:"Cross-author activity (someone else touched your notes or vice versa)."},system:{label:"System",desc:"Plumbing toasts: backfill progress, integrity warnings, errors not tied to a verb."}},Ui={info:4e3,success:4e3,warning:6e3,error:1e4},ai=5e3,Ue=class{constructor(h){this.app=h;this.history=[];this.nextId=1;this.historyLimit=ai;this.changeListeners=new Set;this.muted=new Set;this.defaultAuthorId=null}setDefaultAuthorId(h){this.defaultAuthorId=h||null}show(h){let t=h.kind??"info",e=h.category??"system",s={id:this.nextId++,ts:Date.now(),message:h.message,kind:t,category:e,authorId:h.authorId??this.defaultAuthorId??void 0,affectedIds:h.affectedIds?h.affectedIds.slice():[],affectedPaths:h.affectedPaths?h.affectedPaths.slice():[],affectedAuthorIds:h.affectedAuthorIds?h.affectedAuthorIds.slice():[],folder:h.folder,actionLabels:(h.actions??[]).map(r=>r.label)};if(this.pushHistory(s),this.muted.has(e))return null;let i=this.buildContent(h,t),n=h.duration??Ui[t];return new Ve.Notice(i,n)}onChange(h){return this.changeListeners.add(h),()=>this.changeListeners.delete(h)}recent(){return this.history.slice().reverse()}clearHistory(){this.history=[],this.emit()}setMuted(h,t){t?this.muted.add(h):this.muted.delete(h)}isMuted(h){return this.muted.has(h)}loadMutedFromList(h){this.muted=new Set(h)}mutedList(){return Array.from(this.muted)}loadHistory(h){let t=this.applyLimit(h.slice());this.history=t;let e=0;for(let s of t)s.id>e&&(e=s.id);this.nextId=Math.max(this.nextId,e+1),this.emit()}setHistoryLimit(h){this.historyLimit=Number.isFinite(h)?h:ai,this.history=this.applyLimit(this.history),this.emit()}applyLimit(h){return this.historyLimit<=0||h.length<=this.historyLimit?h:h.slice(h.length-this.historyLimit)}pushHistory(h){this.history.push(h),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let h of this.changeListeners)try{h()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(h,t){let e=document.createDocumentFragment(),s=document.createElement("div");s.className=`stashpad-notice stashpad-notice-${t}`;let i=document.createElement("div");i.className="stashpad-notice-message";let n=h.message.split(/(`[^`\n]+`)/);for(let r of n)if(r.length>1&&r.startsWith("`")&&r.endsWith("`")){let o=document.createElement("code");o.textContent=r.slice(1,-1),i.appendChild(o)}else r.length>0&&i.appendChild(document.createTextNode(r));if(s.appendChild(i),h.actions&&h.actions.length>0){let r=document.createElement("div");r.className="stashpad-notice-actions";for(let o of h.actions){let a=document.createElement("button");a.className="stashpad-notice-action",a.textContent=o.label,a.addEventListener("click",l=>{if(l.stopPropagation(),Promise.resolve().then(()=>o.onClick()).catch(c=>console.warn("[Stashpad] notification action failed",c)),!o.keepOpen){let c=a.closest(".notice");c&&c.parentElement&&c.parentElement.removeChild(c)}}),r.appendChild(a)}s.appendChild(r)}return e.appendChild(s),e}};function Ye(g,h,t){let e=g.vault.getAbstractFileByPath(h);if(!(e instanceof Ve.TFile))return[];let s=[{label:"Reveal",keepOpen:!0,onClick:()=>{let i=g.workspace.getLeavesOfType("file-explorer")[0];if(!i)return;g.workspace.revealLeaf(i),i.view?.revealInFolder?.(e)}}];return t||s.push({label:"Show in Finder",keepOpen:!0,onClick:()=>{try{let i=window.require?.("electron")?.shell,r=g.vault.adapter?.getFullPath?.(h);r&&i?.showItemInFolder&&i.showItemInFolder(r)}catch(i){console.warn("[Stashpad] showItemInFolder failed",i)}}}),s}var Ds=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function Ps(g){if(!g)return"(none)";let h=g.replace(/\bMod\b/g,Ds?"Cmd":"Ctrl");return Ds&&(h=h.replace(/\bAlt\b/g,"Option")),h}function oi(g,h,t={allowSingleKey:!0}){let e=g.placeholder,s=g.value;g.placeholder="Press a key\u2026 (Backspace to cancel)",g.value="",g.classList.add("is-recording");let i=!1,n=()=>{g.placeholder=e,g.classList.remove("is-recording"),i||(g.value=s),g.removeEventListener("keydown",r,!0),g.removeEventListener("blur",o)},r=a=>{if(a.key==="Control"||a.key==="Shift"||a.key==="Alt"||a.key==="Meta"||a.key==="OS")return;let l=!!a.code&&(/^Key[A-Z]$/.test(a.code)||/^Digit\d$/.test(a.code));if((a.key==="Dead"||a.key==="Process"||a.key==="Unidentified")&&!l)return;if(a.preventDefault(),a.stopPropagation(),a.key==="Backspace"&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.shiftKey){n();return}let c=[];Ds?(a.metaKey&&c.push("Mod"),a.ctrlKey&&c.push("Ctrl")):a.ctrlKey&&c.push("Mod"),a.altKey&&c.push("Alt"),a.shiftKey&&c.push("Shift");let p=Vi(a.key,a.code);if(!p||c.length===0&&!t.allowSingleKey)return;c.push(p);let u=c.join("+");i=!0,n(),h(u)},o=()=>n();return g.addEventListener("keydown",r,!0),g.addEventListener("blur",o),n}function Vi(g,h){if(!g)return"";if(h){let t=/^Key([A-Z])$/.exec(h);if(t)return t[1];let e=/^Digit(\d)$/.exec(h);if(e)return e[1]}return g.length===1?g.toUpperCase():g}se();Pt();var Ce=null,qe=new Set;function Ke(g){if(Ce!==g){Ce=g;for(let h of qe)h()}}function Nt(){return Ce}function li(g){if(Ce===g){Ce=null;for(let h of qe)h()}}function ci(g){return qe.add(g),()=>qe.delete(g)}var Fe=[{id:"move",label:"Move (picker)",desc:"Open a fuzzy picker to choose the new parent.",defaultPrimary:"M"},{id:"pickMove",label:"Move (in-list)",desc:"Highlight a note in the list with arrows; Enter sets it as parent.",defaultPrimary:"O"},{id:"merge",label:"Merge",desc:"Concatenate selected notes into the oldest one.",defaultPrimary:"&"},{id:"copy",label:"Copy",desc:"Copy selected note bodies to clipboard.",defaultPrimary:"C"},{id:"copyTree",label:"Copy tree",desc:"Copy the focused note + all descendants, indented.",defaultPrimary:"Y"},{id:"openEditor",label:"Open in editor",desc:"Open the cursor row (or focused note) in a regular Obsidian markdown tab.",defaultPrimary:"E"},{id:"openTab",label:"Open in new Stashpad tab",desc:"Open the cursor row (or focused note) in a new Stashpad tab focused on it.",defaultPrimary:"T"},{id:"split",label:"Split note",desc:"Split the cursor row (or focused note) into two notes at a chosen line.",defaultPrimary:"S"},{id:"copyOutline",label:"Copy as outline",desc:"Copy selection (or cursor row) as a nested ![[embed]] outline.",defaultPrimary:"L"},{id:"toggleSplit",label:"Toggle split-on-newlines",desc:"Default: Mod+/",defaultPrimary:"Mod+/"},{id:"pickDestination",label:"Pick destination",desc:"Default: Mod+D",defaultPrimary:"Mod+D"},{id:"search",label:"Search notes",desc:"Default: Mod+F",defaultPrimary:"Mod+F"},{id:"searchInParent",label:"Search in current parent",desc:"Default: Mod+Alt+F (Mod+Shift+F is taken by Obsidian's global search).",defaultPrimary:"Mod+Alt+F"},{id:"delete",label:"Delete selection",desc:"Default: Mod+Backspace",defaultPrimary:"Mod+Backspace"},{id:"undo",label:"Undo",desc:"Default: Mod+Z (Stashpad-only \u2014 won't fire while typing in the composer).",defaultPrimary:"Mod+Z"},{id:"redo",label:"Redo",desc:"Default: Mod+Shift+Z",defaultPrimary:"Mod+Shift+Z"},{id:"toggleComplete",label:"Toggle complete (strikethrough)",desc:"Default: Mod+Enter \u2014 marks selected/focused notes as complete.",defaultPrimary:"Mod+Enter"},{id:"moveUp",label:"Move note up",desc:"Default: Mod+ArrowUp",defaultPrimary:"Mod+ArrowUp"},{id:"moveDown",label:"Move note down",desc:"Default: Mod+ArrowDown",defaultPrimary:"Mod+ArrowDown"},{id:"moveToTop",label:"Move note to top",desc:"Default: Mod+Shift+ArrowUp",defaultPrimary:"Mod+Shift+ArrowUp"},{id:"moveToBottom",label:"Move note to bottom",desc:"Default: Mod+Shift+ArrowDown",defaultPrimary:"Mod+Shift+ArrowDown"},{id:"outdent",label:"Outdent (move to grandparent)",desc:"Default: Mod+[ \u2014 re-parents the selection one level up.",defaultPrimary:"Mod+["},{id:"setColor",label:"Set note color",desc:"Default: Shift+: \u2014 open the color picker for the selection.",defaultPrimary:"Shift+:"},{id:"clone",label:"Clone (duplicate / copy) selection",desc:"Default: Mod+Shift+D \u2014 clone selected notes (with their subtrees) as siblings.",defaultPrimary:"Mod+Shift+D"},{id:"insertTemplate",label:"Insert template (clone an existing note)",desc:"Pick any note in this Stashpad; clone it (with subtree + attachments) into the current view, retimestamped.",defaultPrimary:""},{id:"toggleExpand",label:"Show more / show less (expand toggle)",desc:"Default: Shift+? \u2014 toggle the clamp on the cursor row (or every selected row).",defaultPrimary:"Shift+?"},{id:"exportStash",label:"Export selection to .stash",desc:"Export the selected subtree(s) as a .stash bundle (notes + attachments).",defaultPrimary:""},{id:"importStash",label:"Import .stash file",desc:"Open the .stash bundle picker and import its notes into this Stashpad.",defaultPrimary:""},{id:"pickFolder",label:"Open / switch / create Stashpad folder",desc:"Default: Mod+S \u2014 opens the unified folder picker (reveal, switch, create, convert).",defaultPrimary:"Mod+S"},{id:"cloneStashpadTab",label:"Clone (duplicate / copy) this Stashpad tab",desc:'Open a second tab on the same folder + focus, mirroring the "copy" button in the focused-header actions.',defaultPrimary:""},{id:"selectAll",label:"Select all notes in view",desc:"Default: Mod+A \u2014 adds every visible row to the selection.",defaultPrimary:"Mod+A"},{id:"copyCodeBlock",label:"Copy code from codeblock",desc:"Default: { \u2014 copy the contents of the cursor row's first codeblock (or pick one when multiple exist).",defaultPrimary:"{"},{id:"swapWithParent",label:"Swap with parent (ouroboros)",desc:"Promote the cursor row above its current parent; the parent slides under it (carrying its other children). No default \u2014 bind in this tab.",defaultPrimary:""},{id:"togglePin",label:"Pin / unpin selected note",desc:"Default: P \u2014 toggle the sidebar pin state of the cursor row (or focused note).",defaultPrimary:"P"},{id:"toggleTask",label:"Toggle task (todo)",desc:"Default: H \u2014 mark the selection (or cursor row) as a task / todo, or clear it. Tasks appear in the Tasks panel.",defaultPrimary:"H"},{id:"setDue",label:"Set due date\u2026",desc:"Default: D \u2014 open a date+time picker to set (or clear) the due date on the selection. Setting a due date also marks the note as a task.",defaultPrimary:"D"}];function _s(){let g={};for(let h of Fe)g[h.id]={primary:h.defaultPrimary,secondary:"",preferRight:!1};return g}var Ht={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!0,inheritObsidianExclusions:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,pinnedNotes:[],hideMobileToolbarInStashpad:!0,slugStopWords:[],searchIncludedFolders:[],searchExcludedFolders:[],shortcuts:{move:"M",pickMove:"O",merge:"&",copy:"C",copyTree:"Y",openEditor:"E",openTab:"T",split:"S",copyOutline:"L"},mod:{toggleSplit:"Mod+/",pickDestination:"Mod+D",search:"Mod+F",delete:"Mod+Backspace",undo:"Mod+Z",redo:"Mod+Shift+Z",toggleComplete:"Mod+Enter",moveUp:"Mod+ArrowUp",moveDown:"Mod+ArrowDown",moveToTop:"Mod+Shift+ArrowUp",moveToBottom:"Mod+Shift+ArrowDown",outdent:"Mod+[",setColor:"Shift+:"},customPalette:[],colorAliases:{},noteTemplates:{},authorName:"",authorId:"",authorRole:"",authorDepartment:"",showAuthor:!0,showContributors:!0,showLastEdit:!0,viewModes:{},includeAttachmentsInEverything:{},hideChildlessNotes:{},hideCompletedNotes:{},attachmentsOnlyNotes:{},mutedNotificationCategories:[],notificationHistoryLimit:5e3,autoNavOnMoveIn:!1,autoNavOnMoveOut:!1,autoExpandCursorRow:!1,autoOpenDetailPanel:!1,doubleClickToFocus:!0,dateDisplayFormat:"locale",dateDisplayTimezone:"",jdIndexScope:"vault",jdIndexScopeFolder:"",jdIndexStashpadFolder:"",jdIndexFile:"Index",jdIndexIncludeStashpadFolders:!1,jdIndexSort:"natural",jdIndexHasBuilt:!1,drafts:{},lastSubmitted:{},bindings:_s()},di=JSON.parse(JSON.stringify(Ht)),Ms=new Set;function bt(){return di}function Ls(g){di=g;for(let h of Ms)h()}function hi(g){return Ms.add(g),()=>Ms.delete(g)}function Je(g){try{let h=g.internalPlugins?.plugins?.templates;if(!h?.enabled)return null;let t=h.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var Ze=[{id:"general",label:"General"},{id:"diagnostics",label:"Diagnostics"},{id:"authorship",label:"Authorship"},{id:"templates",label:"Templates"},{id:"jdindex",label:"JD Index"},{id:"hotkeys",label:"Hotkeys"}],Ge=class extends G.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e;this.activeTab="general";this.searchQuery=""}openToTab(t){this.activeTab=t,this.searchQuery="",this.containerEl?.isShown?.()!==!1&&this.display()}focusSearchInput(){let t=this.containerEl?.querySelector(".stashpad-settings-search-input");t&&(t.focus(),t.setSelectionRange(t.value.length,t.value.length))}display(){let{containerEl:t}=this;t.empty(),t.addClass("stashpad-settings-tabbed"),t.createEl("h2",{text:"Stashpad",cls:"stashpad-settings-title"});let s=t.createDiv({cls:"stashpad-settings-search-wrap"}).createEl("input",{type:"text",placeholder:"Search settings\u2026",cls:"stashpad-settings-search-input"});s.value=this.searchQuery;let i=this.searchQuery.trim().length>0,n=t.createDiv({cls:"stashpad-settings-tabs"});i&&n.addClass("is-search-mode");for(let a of Ze){let l=n.createEl("button",{cls:"stashpad-settings-tab",text:a.label});!i&&this.activeTab===a.id&&l.addClass("is-active"),l.onclick=()=>{this.searchQuery="",this.activeTab=a.id,this.display()}}let r=t.createDiv({cls:"stashpad-settings-body"});if(i){for(let a of Ze){let l=r.createDiv({cls:"stashpad-settings-search-group"});l.createEl("h3",{text:a.label,cls:"stashpad-settings-search-group-header"});let c=l.createDiv();this.renderTabContent(c,a.id)}this.applySearchFilter(r)}else this.renderTabContent(r,this.activeTab);let o=i;s.oninput=()=>{this.searchQuery=s.value;let a=this.searchQuery.trim().length>0;if(a!==o){let l=s.selectionStart??s.value.length;this.display();let c=t.querySelector(".stashpad-settings-search-input");c&&(c.focus(),c.setSelectionRange(l,l));return}a&&this.applySearchFilter(r)},this.searchQuery&&setTimeout(()=>{s.focus(),s.setSelectionRange(s.value.length,s.value.length)},0)}applySearchFilter(t){let e=this.searchQuery.trim().toLowerCase();if(!e)return;let s=e.split(/\s+/).filter(Boolean),i=r=>s.every(o=>r.includes(o));t.querySelectorAll(".setting-item").forEach(r=>{let o=r.querySelector(".setting-item-name")?.textContent?.toLowerCase()??"",a=r.querySelector(".setting-item-description")?.textContent?.toLowerCase()??"";r.style.display=i(`${o} ${a}`)?"":"none"}),t.querySelectorAll(".stashpad-settings-search-group").forEach(r=>{let o=Array.from(r.querySelectorAll(".setting-item")).some(a=>a.style.display!=="none");r.style.display=o?"":"none"})}renderTabContent(t,e){switch(e){case"general":this.renderGeneralTab(t);break;case"diagnostics":this.renderDiagnosticsTab(t);break;case"authorship":this.renderAuthorshipSection(t);break;case"templates":this.renderTemplatesTab(t);break;case"jdindex":this.renderJdIndexSection(t);break;case"hotkeys":this.renderHotkeysTab(t);break}}renderDiagnosticsTab(t){new G.Setting(t).setName("Open log file").setDesc("Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.").addButton(r=>r.setButtonText("Open log").onClick(async()=>{let o=this.app.vault.adapter,a=this.plugin.pluginPrivatePath("log.jsonl");if(!await o.exists(a)){new G.Notice("No log yet \u2014 make some changes first.");return}let l=await o.read(a);new Qt(this.app,l,a).open()})),new G.Setting(t).setName("Notification history limit").setDesc("Maximum number of notifications kept in the persistent history. Set to 0 for unlimited (the file size grows with usage; expect a few hundred KB per ~5000 entries). Default: 5000.").addText(r=>r.setValue(String(this.plugin.settings.notificationHistoryLimit??5e3)).setPlaceholder("5000").onChange(async o=>{let a=parseInt(o,10);Number.isFinite(a)&&(this.plugin.settings.notificationHistoryLimit=a,this.plugin.notifications.setHistoryLimit(a),await this.plugin.saveSettings())}));let e=t.createEl("details",{cls:"stashpad-notif-mute-details"});e.createEl("summary",{text:"Mute notification categories"}),e.createDiv({cls:"stashpad-notif-mute-help"}).setText("Muted categories don't pop toasts but still appear in the history panel so you can review what was suppressed.");let i=new Set(this.plugin.settings.mutedNotificationCategories??[]),n=Object.keys(As);for(let r of n){let o=As[r];new G.Setting(e).setName(o.label).setDesc(o.desc).addToggle(a=>a.setValue(!i.has(r)).onChange(async l=>{let c=!l;c?i.add(r):i.delete(r),this.plugin.settings.mutedNotificationCategories=Array.from(i),this.plugin.notifications.setMuted(r,c),await this.plugin.saveSettings()}))}new G.Setting(t).setName("Notification history").setDesc("Browse the last 200 toasts. Filter by category. Live-updates as new notifications arrive. Muted categories still appear here so you can review what was suppressed.").addButton(r=>r.setButtonText("View notification history").onClick(()=>{new ye(this.app,this.plugin.notifications,async o=>{let a=this.app.vault.adapter,l=this.plugin.pluginPrivatePath("log.jsonl");if(!await a.exists(l)){new G.Notice("No log yet \u2014 make some changes first.");return}let c=await a.read(l);new Qt(this.app,c,l).open()},this.plugin.settings.authorId||null,o=>this.plugin.lookupNoteAuthorIds(o)).open()}))}renderGeneralTab(t){new G.Setting(t).setName("Stashpad notes folder").setDesc("Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.").addText(i=>{new ne(this.app,i.inputEl),i.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async n=>{let r=(n||"").trim().replace(/^\/+|\/+$/g,"")||Ht.folder,o=r.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(l=>(l??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(o)){new G.Notice(`"${r}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=r,await this.plugin.saveSettings()})}),new G.Setting(t).setName("Auto-import dropped files").setDesc("When on, any file you drop directly into a Stashpad folder is imported automatically: markdown becomes a note (the original is archived to .archive); other files move to _attachments with a note that links to them. Large drops ask for confirmation first.").addToggle(i=>i.setValue(this.plugin.settings.autoImport).onChange(async n=>{this.plugin.settings.autoImport=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Inherit Obsidian's excluded files").setDesc("Also hide files matching Obsidian's \u201CExcluded files\u201D list (Settings \u2192 Files & Links) from Stashpad's link autocomplete and file surfaces \u2014 so you manage exclusions in one place. Plugin-internal formats like .edtz are always excluded regardless.").addToggle(i=>i.setValue(this.plugin.settings.inheritObsidianExclusions).onChange(async n=>{this.plugin.settings.inheritObsidianExclusions=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Dedicated import subfolder (optional)").setDesc("Optional. A subfolder (relative to each Stashpad folder) where dropped .stash files auto-import. Leave blank to just drop files into the Stashpad folder itself (recommended). Suggested name: _imports.").addText(i=>i.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports (leave blank to use the folder root)").onChange(async n=>{this.plugin.settings.importDropFolder=(n||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})),new G.Setting(t).setName("Stash export subfolder").setDesc("Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.").addText(i=>i.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async n=>{let r=(n||"").trim().replace(/^\/+|\/+$/g,"")||Ht.exportFolder;this.plugin.settings.exportFolder=r,await this.plugin.saveSettings()})),new G.Setting(t).setName("Rebootstrap existing Stashpad folders").setDesc("Walk every folder that has a home note: ensure infrastructure (_imports, _exports, drafts file), backfill the redundant parentLink + children frontmatter fields, AND rename any note whose filename slug no longer matches its body's first line. Safe to run anytime; skip-if-equal means already-synced notes are no-op writes.").addButton(i=>i.setButtonText("Rebootstrap now").onClick(async()=>{i.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:n,fmChecked:r,fmWritten:o,slugsRenamed:a,authors:l,imported:c}=await this.plugin.rebootstrapAllFolders(),p=[];p.push(`rebootstrapped ${n.length} folder${n.length===1?"":"s"}`),c>0&&p.push(`imported ${c} loose file${c===1?"":"s"}`),o>0?p.push(`updated frontmatter on ${o} of ${r} notes`):r>0&&p.push(`frontmatter already in sync (${r} notes checked)`),a>0&&p.push(`renamed ${a} note${a===1?"":"s"} to match body`),l>0&&p.push(`rebuilt author registry (${l} author${l===1?"":"s"})`),new G.Notice(`Stashpad: ${p.join("; ")}.`)}catch(n){new G.Notice(`Stashpad: rebootstrap failed (${n.message})`)}finally{i.setDisabled(!1).setButtonText("Rebootstrap now")}})),new G.Setting(t).setName("Use Templates plugin date/time formats").setDesc("When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.").addToggle(i=>i.setValue(this.plugin.settings.useTemplatesFormat).onChange(async n=>{this.plugin.settings.useTemplatesFormat=n,await this.plugin.saveSettings()}));let e=Je(this.app);t.createDiv({cls:"setting-item-description stashpad-settings-note"}).setText(e?`Templates plugin: date = "${e.dateFormat}", time = "${e.timeFormat}"`:"Templates plugin not enabled.");{let i=null,n=()=>{if(!i)return;let r=Date.now(),o=Yt(r,this.plugin.settings);i.setText(`Sample: ${o}`)};new G.Setting(t).setName("Date display format").setDesc("How due dates and created/modified times are shown in the Tasks and detail panels.").addDropdown(r=>{r.addOption("locale","Locale, short (Mar 5, 9:00 AM)"),r.addOption("long","Locale, long (Thursday, March 5\u2026)"),r.addOption("iso","ISO (2026-03-05 09:00)"),r.addOption("us","US (3/5/2026, 9:00 AM)"),r.addOption("eu","EU (5/3/2026, 09:00)"),r.setValue(this.plugin.settings.dateDisplayFormat??"locale"),r.onChange(async o=>{this.plugin.settings.dateDisplayFormat=o,await this.plugin.saveSettings(),n()})}),new G.Setting(t).setName("Display timezone").setDesc("IANA timezone name (e.g. America/New_York, Europe/London, Asia/Kolkata). Leave blank to use your system timezone.").addText(r=>{r.setPlaceholder("(system timezone)"),r.setValue(this.plugin.settings.dateDisplayTimezone??""),r.onChange(async o=>{this.plugin.settings.dateDisplayTimezone=(o||"").trim(),await this.plugin.saveSettings(),n()})}),i=t.createDiv({cls:"setting-item-description stashpad-settings-note"}),n()}new G.Setting(t).setName("Navigate into parent after moving a note IN").setDesc("When you move a note onto another note via the in-list move picker (drag-onto-sibling), automatically drill into the new parent so you can see the moved note in its new home. Off = stay focused where you were.").addToggle(i=>i.setValue(this.plugin.settings.autoNavOnMoveIn).onChange(async n=>{this.plugin.settings.autoNavOnMoveIn=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Navigate to destination after moving a note OUT").setDesc("When you outdent a note, move it via the cross-parent picker, or send it to Home, automatically drill into the destination parent. Off = stay focused where you were.").addToggle(i=>i.setValue(this.plugin.settings.autoNavOnMoveOut).onChange(async n=>{this.plugin.settings.autoNavOnMoveOut=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Double-click a note to open it").setDesc("Double-click (or double-tap on mobile) a note in the list to focus/open it \u2014 the same as pressing \u2192 or clicking the enter arrow. Single click still just selects. On by default.").addToggle(i=>i.setValue(this.plugin.settings.doubleClickToFocus).onChange(async n=>{this.plugin.settings.doubleClickToFocus=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Auto-open the detail panel").setDesc("Open the right-sidebar Stashpad detail panel automatically whenever a Stashpad view becomes active. The panel shows the cursored note's body, metadata, and children. Off = open manually via ribbon or command palette.").addToggle(i=>i.setValue(this.plugin.settings.autoOpenDetailPanel).onChange(async n=>{this.plugin.settings.autoOpenDetailPanel=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Expand the cursor row's body automatically").setDesc("As you arrow-key through the list, the row under the cursor temporarily un-clamps to show its full body. Moving away re-collapses it. Doesn't affect the persistent 'Show more' state \u2014 this is a transient view-only effect.").addToggle(i=>i.setValue(this.plugin.settings.autoExpandCursorRow).onChange(async n=>{this.plugin.settings.autoExpandCursorRow=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Confirm cross-parent drag-and-drop").setDesc("When dragging notes onto a note that has a different parent, ask before re-parenting (turn off to allow direct moves).").addToggle(i=>i.setValue(this.plugin.settings.confirmCrossParentDrag).onChange(async n=>{this.plugin.settings.confirmCrossParentDrag=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Confirm bulk deletes").setDesc("Warn before deletes that affect more than one note \u2014 multi-selection delete OR deleting a note that has descendants. A single childless note with no attachments never prompts. Off = those deletes apply immediately (undo still recovers everything).").addToggle(i=>i.setValue(this.plugin.settings.confirmBulkDelete).onChange(async n=>{this.plugin.settings.confirmBulkDelete=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Offer to delete attachments with note").setDesc(`When a note references attachments, the delete modal includes an "Also delete attachments" checkbox so orphaned files don't pile up in your vault. Attachments are detected from both ![[\u2026]] embeds in the body and the frontmatter attachments: list. Off = attachments are always preserved on delete (no checkbox shown), and a single childless note with attachments deletes silently.`).addToggle(i=>i.setValue(this.plugin.settings.confirmAttachmentDelete).onChange(async n=>{this.plugin.settings.confirmAttachmentDelete=n,await this.plugin.saveSettings()}));{let i=null,n=(this.plugin.settings.slugStopWords?.length?this.plugin.settings.slugStopWords:Mt).join(` -`);new G.Setting(t).setName("Slug stop-words").setDesc("Words removed from auto-generated note titles (filenames). One per line.").addTextArea(r=>{r.setValue(n),i=r.inputEl,i.rows=6,i.style.fontFamily="var(--font-monospace)",r.onChange(async o=>{let a=(o||"").split(/\r?\n/).map(l=>l.trim().toLowerCase()).filter(Boolean);this.plugin.settings.slugStopWords=a,await this.plugin.saveSettings()})}).addExtraButton(r=>r.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...Mt],i&&(i.value=Mt.join(` -`)),await this.plugin.saveSettings()}))}{let i=this.plugin.discoverStashpadFolders();if(new G.Setting(t).setName("Cross-Stashpad search scope").setDesc("Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations \u2014 their notes just don't appear in search results from elsewhere."),i.length===0)t.createEl("p",{cls:"setting-item-description"}).setText('No Stashpads found in this vault yet. A Stashpad is just a folder that contains a Stashpad-shaped note (frontmatter has both `id` and `parent`). Easiest way: open Stashpad (ribbon icon or command "Reveal or open Stashpad") \u2014 it auto-creates the default folder on first use. Or create one below.');else{let r=t.createDiv({cls:"stashpad-folder-list"});for(let o of i)this.renderFolderScopeRow(r,o)}let n=null;new G.Setting(t).setName("Create a new Stashpad").setDesc("Type a vault-relative folder path. The folder is created (with intermediates) and seeded with a Home note so Stashpad recognizes it.").addText(r=>{r.setPlaceholder("my-stashpad"),n=r.inputEl}).addButton(r=>r.setButtonText("Create").setCta().onClick(async()=>{let o=(n?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!o){new G.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(o),new G.Notice(`Created Stashpad "${o}".`),n&&(n.value=""),await this.plugin.waitForStashpadFolder(o,2e3),this.display()}catch(a){new G.Notice(`Couldn't create: ${a.message}`)}}))}new G.Setting(t).setName("Autofocus composer after sending").setDesc("After Enter-submitting a note, return focus to the composer so you can keep typing. Off keeps focus in the list \u2014 useful if you want arrow keys to work without an extra click.").addToggle(i=>i.setValue(this.plugin.settings.autofocusComposerAfterSend).onChange(async n=>{this.plugin.settings.autofocusComposerAfterSend=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Open in new window \u2014 duplicate tab").setDesc("ON: the new-window button (in the time-filter row) duplicates the current Stashpad tab \u2014 original stays open in the main window. OFF: the leaf is MOVED to the new window, closing the original tab.").addToggle(i=>i.setValue(this.plugin.settings.popoutDuplicates).onChange(async n=>{this.plugin.settings.popoutDuplicates=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Prefix timestamps when copying").setDesc("Include each note's timestamp before its body when copying with C or Y.").addToggle(i=>i.setValue(this.plugin.settings.prefixTimestampsOnCopy).onChange(async n=>{this.plugin.settings.prefixTimestampsOnCopy=n,await this.plugin.saveSettings()}))}renderTemplatesTab(t){this.renderColorAliasesSection(t),this.renderNoteTemplatesSection(t)}renderHotkeysTab(t){t.createEl("p",{cls:"setting-item-description",text:"Each command has up to two slots. Click a slot and press a key (or chord) to bind it; press Backspace (delete on Mac) to cancel without binding; or click \u2715 to clear an existing binding. When both slots are set, the pill on the right decides which one is active."});for(let e of Fe)this.renderBindingRow(t,e)}renderJdIndexSection(t){let e=t.createEl("h3",{text:"JD Index Builder"});e.id="stashpad-jd-index-section";let s=t.createEl("p",{cls:"setting-item-description"});s.innerHTML="Builds a Johnny-Decimal-style index inside a designated Stashpad folder. Two commands:<br/><strong>Preview</strong> overwrites the designated folder’s HOME note body with the would-be hierarchy + everything that didn’t match. Frontmatter is preserved; everything below it is replaced.<br/><strong>Build</strong> creates an actual hierarchy of Stashpad notes (one per prefix), with child\u2192parent relationships matching the dotted segments.<br/>Matches strict prefixes only: all-digits (<code>10 Life</code>) or alphanumeric-with-dots (<code>1.2 Family</code>, <code>animal.duck.yellow Eggs</code>). Mixed schemes sort numbers first, then alphabetically.";let i=this.plugin.discoverStashpadFolders();new G.Setting(t).setName("Scope").setDesc("Scan the whole vault, or restrict to a single folder + its descendants.").addDropdown(a=>{a.addOption("vault","Entire vault"),a.addOption("folder","Single folder"),a.setValue(this.plugin.settings.jdIndexScope??"vault"),a.onChange(async l=>{this.plugin.settings.jdIndexScope=l==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new G.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(a=>{new ne(this.app,a.inputEl),a.setPlaceholder("Path/To/Folder"),a.setValue(this.plugin.settings.jdIndexScopeFolder??""),a.onChange(async l=>{this.plugin.settings.jdIndexScopeFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new G.Setting(t).setName("Include Stashpad folders in scan").setDesc("By default, notes inside any known Stashpad folder are excluded \u2014 the index destination shouldn't index itself, and other Stashpad folders are usually already organized. Toggle on if you want them included anyway.").addToggle(a=>{a.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),a.onChange(async l=>{this.plugin.settings.jdIndexIncludeStashpadFolders=l,await this.plugin.saveSettings(),this.display()})}),new G.Setting(t).setName("Designated Stashpad folder for Index").setDesc("Required. Must be a Stashpad folder. The index hierarchy is built here. New notes are created; nothing is deleted.").addText(a=>{new ne(this.app,a.inputEl),a.setPlaceholder(i[0]??"(pick a Stashpad folder)"),a.setValue(this.plugin.settings.jdIndexStashpadFolder??""),a.onChange(async l=>{this.plugin.settings.jdIndexStashpadFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new G.Setting(t).setName("Sort").setDesc("Order of entries within the same depth. Natural: numbers first then alphabetical (recommended). Created: by source file's creation time \u2014 handy when prefixes are word-only and don't carry ordering.").addDropdown(a=>{a.addOption("natural","Natural (numeric \u2192 alphabetical)"),a.addOption("created","By creation time"),a.setValue(this.plugin.settings.jdIndexSort??"natural"),a.onChange(async l=>{this.plugin.settings.jdIndexSort=l==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=ie(this.app,this.plugin,this.plugin.settings),r=t.createEl("p",{cls:"setting-item-description"}),o=n.skippedStashpadNotes.length>0?` (${n.skippedStashpadNotes.length} Stashpad-folder note${n.skippedStashpadNotes.length===1?"":"s"} excluded by default)`:"";r.setText(`Preview: ${n.indexed.length} note${n.indexed.length===1?"":"s"} would be indexed, ${n.nonIndex.length} would NOT be indexed${o}.`),new G.Setting(t).setName("Actions").setDesc("Preview aggressively overwrites the designated folder's HOME note body (frontmatter preserved). Build creates Stashpad notes (existing notes with the same jdPrefix are updated, not duplicated).").addButton(a=>{a.setButtonText("Preview"),a.setTooltip("Overwrites the designated Stashpad folder's HOME note body with the preview."),a.onClick(async()=>{try{let l=await He(this.app,this.plugin,this.plugin.settings);if(l.error==="no-dest"){new G.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(l.error==="no-home"){new G.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}ze(this.app,l),this.display()}catch(l){console.error("[stashpad] preview failed",l),new G.Notice(`Preview failed: ${l?.message??l}`,8e3)}})}).addButton(a=>{a.setButtonText("Build Stashpad notes"),a.setCta(),a.setTooltip("Create the Stashpad-note hierarchy. Existing notes with matching jdPrefix are updated."),a.onClick(()=>{if(!(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new G.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new ke(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let p=await Es(this.app,this.plugin,this.plugin.settings);if(p.error==="no-dest"){new G.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(p.error==="dest-not-stashpad"){new G.Notice(`"${p.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder (or create one first).`,7e3);return}this.plugin.settings.jdIndexHasBuilt=!0,await this.plugin.saveSettings(),new G.Notice(`Built: ${p.created} created, ${p.updated} updated, ${p.skipped} skipped \u2192 ${p.destFolder}`,6e3),this.display()}catch(p){console.error("[stashpad] build failed",p),new G.Notice(`Build failed: ${p?.message??p}`,8e3)}}).open()})}).addButton(a=>{a.setButtonText("Reveal in Finder"),a.setTooltip("Open the designated Stashpad folder in your OS file browser."),a.onClick(async()=>{let l=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!l){new G.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(l)){new G.Notice(`Folder "${l}" doesn't exist yet.`,5e3);return}try{let p=this.app.vault.adapter.basePath;if(p){let{shell:u}=window.require?.("electron")??{},d=`${p}/${l}`;u?.openPath?.(d)}else new G.Notice("Reveal in file system not supported on this platform.",4e3)}catch(p){new G.Notice(`Couldn't open folder: ${p?.message??p}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new G.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let s=(()=>{let r=Nt()?.noteFolder;return r&&e.includes(r)?r:e[0]})();new G.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(r=>{for(let o of e)r.addOption(o,o);r.setValue(s),r.onChange(o=>{s=o,n()})}),t.createEl("p",{cls:"setting-item-description",text:"Give each per-note color a friendly name. Filters and pickers display the alias instead of the hex code; the underlying color stays the same. The same hex in two Stashpads can have different aliases."});let i=t.createDiv({cls:"stashpad-color-aliases-list"}),n=()=>{i.empty();let r=this.plugin.collectColorsInFolder(s),o=new Map(r.map(p=>[p.hex,p.count])),a=this.plugin.settings.colorAliases?.[s.replace(/\/+$/,"")]??{},l=new Set([...o.keys(),...Object.keys(a)]);if(l.size===0){i.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${s}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let c=[...l].map(p=>({hex:p,count:o.get(p)??0}));c.sort((p,u)=>u.count-p.count||p.hex.localeCompare(u.hex));for(let p of c)this.renderColorAliasRow(i,s,p.hex,p.count,n)};n()}renderAuthorshipSection(t){t.createEl("h3",{text:"Authorship"}),t.createEl("p",{cls:"setting-item-description",text:"Stamp each new note with your name. If the vault is later shared (e.g. a coworker opens it with --config pointing at their own settings folder), every modification automatically tracks contributors on top of the original author. Names link to per-user pages in <stashpad>/_authors/."}),new G.Setting(t).setName("Author name").setDesc("Your display name. Used in the note footer + as the author/contributor link target. Leave blank to opt out (notes won't be stamped).").addText(s=>{s.setValue(this.plugin.settings.authorName).onChange(async i=>{this.plugin.settings.authorName=i.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=yt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new G.Setting(t).setName("Author id (auto-assigned)").setDesc("Stable id appended to your name on links so coworkers with the same name don't collide. Generated once and shouldn't change. If you really need to reset it, clear and retype your author name above.").addText(s=>{s.setValue(this.plugin.settings.authorId).setDisabled(!0)}),new G.Setting(t).setName("Title / role").setDesc('Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").').addText(s=>{s.setValue(this.plugin.settings.authorRole).onChange(async i=>{this.plugin.settings.authorRole=i.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new G.Setting(t).setName("Department / team").setDesc('Optional. Shown on your author page (e.g. "Engineering", "Growth").').addText(s=>{s.setValue(this.plugin.settings.authorDepartment).onChange(async i=>{this.plugin.settings.authorDepartment=i.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new G.Setting(t).setName("Show author in note footer").addToggle(s=>s.setValue(this.plugin.settings.showAuthor).onChange(async i=>{this.plugin.settings.showAuthor=i,await this.plugin.saveSettings()})),new G.Setting(t).setName("Show contributors in note footer").addToggle(s=>s.setValue(this.plugin.settings.showContributors).onChange(async i=>{this.plugin.settings.showContributors=i,await this.plugin.saveSettings()})),new G.Setting(t).setName("Show last edit time in note footer").addToggle(s=>s.setValue(this.plugin.settings.showLastEdit).onChange(async i=>{this.plugin.settings.showLastEdit=i,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){t.createEl("h4",{text:"Folders you've worked in"});let s=t.createDiv({cls:"stashpad-authored-folders-list"});for(let i of e){let n=s.createDiv({cls:"stashpad-authored-folder-row"}),r=n.createEl("a",{cls:"stashpad-authored-folder-link",text:i.folder});r.onclick=a=>{a.preventDefault(),this.plugin.activateViewForFolder(i.folder)};let o=[];i.authored>0&&o.push(`authored ${i.authored}`),i.contributed>0&&o.push(`contributed to ${i.contributed}`),n.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${o.join(", ")}`})}}this.renderKnownAuthorsSection(t)}renderKnownAuthorsSection(t){t.createEl("h4",{text:"Known authors (registry)"}),t.createEl("div",{cls:"setting-item-description",text:"A rebuildable cache of every author Stashpad has seen, with rename history. Not a source of truth \u2014 the author id stored in each note is authoritative. Use it to recover deleted author pages or audit name changes."}),new G.Setting(t).setName("Registry maintenance").setDesc("Rebuild scans the whole vault to reconstruct the list. Restore regenerates any deleted author pages across every Stashpad folder.").addButton(i=>i.setButtonText("Rebuild").onClick(async()=>{i.setDisabled(!0).setButtonText("Rebuilding\u2026");try{let n=await this.plugin.rebuildAuthorRegistry();new G.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new G.Notice(`Rebuild failed: ${n.message}`)}i.setDisabled(!1).setButtonText("Rebuild"),this.display()})).addButton(i=>i.setButtonText("Restore missing pages").onClick(async()=>{i.setDisabled(!0).setButtonText("Restoring\u2026");try{let n=await this.plugin.restoreMissingAuthorStubs();new G.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new G.Notice(`Restore failed: ${n.message}`)}i.setDisabled(!1).setButtonText("Restore missing pages")}));let e=this.plugin.authorRegistry.all();if(e.length===0){t.createEl("div",{cls:"setting-item-description",text:"No authors recorded yet. Rebuild to scan the vault."});return}let s=t.createDiv({cls:"stashpad-known-authors-list"});for(let i of e){let n=s.createDiv({cls:"stashpad-known-author-row"}),r=n.createDiv({cls:"stashpad-known-author-main"});r.createSpan({cls:"stashpad-known-author-name",text:i.name||"(unnamed)"});let o=[];if(i.role&&o.push(i.role),i.department&&o.push(i.department),o.push(`id ${i.id}`),r.createSpan({cls:"stashpad-known-author-meta",text:` \xB7 ${o.join(" \xB7 ")}`}),i.renames&&i.renames.length>0){let a=n.createDiv({cls:"stashpad-known-author-history"}),l=i.renames.map(c=>`${c.from} \u2192 ${c.to}`).join(", ");a.setText(`Renamed: ${l}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;new G.Setting(t).setName("Note templates per Stashpad").setDesc("Pick a markdown file to use as the default template for new notes in each Stashpad. The template's frontmatter becomes the new note's frontmatter (id/parent/created/attachments are always set by Stashpad). If the body contains {{body}}, that's where the user-typed body goes; otherwise the user body is followed by the template body.");let s=t.createDiv({cls:"stashpad-note-templates-list"}),i=n=>{let r=n.replace(/\/+$/,""),o=s.createDiv({cls:"stashpad-note-template-row"});o.createSpan({cls:"stashpad-note-template-folder"}).setText(n);let l=o.createDiv({cls:"stashpad-note-template-input-wrap"}),c=l.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});c.value=(this.plugin.settings.noteTemplates??{})[r]??"";let p=l.createDiv({cls:"stashpad-note-template-suggest"});p.style.display="none";let u=o.createDiv({cls:"stashpad-note-template-warn"});u.style.display="none";let d=()=>this.app.vault.getMarkdownFiles().map(y=>y.path).filter(y=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(y)).sort(),f=()=>{p.empty();let y=c.value.trim().toLowerCase().split(/\s+/).filter(Boolean),b=C=>{let I=C.toLowerCase();return y.every(E=>I.includes(E))},k=d().filter(C=>b(C)).slice(0,12);if(k.length===0){p.style.display="none";return}p.style.display="";for(let C of k)p.createDiv({cls:"stashpad-note-template-suggest-item",text:C}).addEventListener("mousedown",async E=>{E.preventDefault(),c.value=C,await m(),p.style.display="none"})},m=async()=>{let y=c.value.trim(),b={...this.plugin.settings.noteTemplates??{}};y?b[r]=y:delete b[r],this.plugin.settings.noteTemplates=b,await this.plugin.saveSettings(),v()},v=()=>{u.empty(),u.style.display="none";let y=c.value.trim();if(!y)return;let b=this.app.vault.getAbstractFileByPath(y);if(!b||b.extension!=="md"){u.style.display="",u.setText(`\u26A0 "${y}" is not a markdown file in this vault.`);return}let k=this.app.metadataCache.getFileCache(b)?.frontmatter??{},I=Rt.filter(E=>{let D=k[E];return!(D==null||typeof D=="string"&&D.trim()===""||Array.isArray(D)&&D.length===0)});I.length!==0&&(u.style.display="",u.setText(`\u26A0 Template defines ${I.join(", ")} \u2014 Stashpad always sets ${I.length===1?"this":"these"} on new notes, so the template value${I.length===1?"":"s"} will be ignored.`))};c.addEventListener("focus",f),c.addEventListener("input",f),c.addEventListener("blur",()=>{setTimeout(()=>{p.style.display="none"},150)}),c.addEventListener("change",()=>{m()}),v()};for(let n of e)i(n)}renderColorAliasRow(t,e,s,i,n){let r=t.createDiv({cls:"stashpad-color-alias-row"});i===0&&r.addClass("is-unused");let o=r.createSpan({cls:"stashpad-color-alias-swatch"});o.style.background=s,o.title="Click to bulk-recolor every note of this color in this Stashpad",o.onclick=()=>{let p=this.plugin.settings.customPalette??[];new Zt(this.app,s,p,async u=>{if((u??null)===null&&i===0){await this.plugin.setColorAlias(e,s,""),n();return}if(u&&u.toLowerCase()===s){n();return}let d=await this.plugin.recolorAllInFolder(e,s,u??null);if(d>0)new G.Notice(`Recolored ${d} note${d===1?"":"s"}.`);else if(i===0){let f=this.plugin.getColorAlias(e,s);f&&(await this.plugin.setColorAlias(e,s,""),u&&await this.plugin.setColorAlias(e,u,f))}n()},async u=>{let d=(this.plugin.settings.customPalette??[]).filter(f=>f.toLowerCase()!==u.toLowerCase());return this.plugin.settings.customPalette=d,await this.plugin.saveSettings(),d}).open()};let a=r.createDiv({cls:"stashpad-color-alias-meta"});a.createSpan({cls:"stashpad-color-alias-hex",text:s}),a.createSpan({cls:"stashpad-color-alias-count",text:i===0?"\xB7 unused":`\xB7 ${i} note${i===1?"":"s"}`});let l=r.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});l.value=this.plugin.getColorAlias(e,s)??"",l.onchange=async()=>{await this.plugin.setColorAlias(e,s,l.value),!l.value.trim()&&i===0&&n()};let c=r.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});l.value||(c.style.visibility="hidden"),c.onclick=async()=>{await this.plugin.setColorAlias(e,s,""),i===0?n():(l.value="",c.style.visibility="hidden")}}renderFolderScopeRow(t,e){let s=t.createDiv({cls:"stashpad-folder-row"});s.createSpan({cls:"stashpad-folder-row-label",text:e});let i=s.createSpan({cls:"stashpad-folder-row-state"}),n=s.createDiv({cls:"stashpad-binding-pill"});n.setAttribute("role","switch"),n.setAttribute("tabindex","0");let r=n.createDiv({cls:"stashpad-binding-pill-knob"}),o=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),a=()=>{let c=o();n.toggleClass("is-right",c),n.setAttribute("aria-checked",String(c)),r.setText(c?"X":"\u2713"),i.setText(c?"Excluded":"Included"),i.toggleClass("is-excluded",c),n.title=c?"Excluded \u2014 notes here won't appear in cross-Stashpad search. Click to include.":"Included \u2014 notes here appear in cross-Stashpad search. Click to exclude."},l=async()=>{let c=new Set(this.plugin.settings.searchExcludedFolders??[]);c.has(e)?c.delete(e):c.add(e),this.plugin.settings.searchExcludedFolders=[...c].sort(),a(),await this.plugin.saveSettings()};n.onclick=()=>void l(),n.onkeydown=c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())},a()}renderBindingRow(t,e){let s=new G.Setting(t).setName(e.label).setDesc(e.desc),i=()=>this.plugin.settings.bindings[e.id],n,r,o=()=>{},a=f=>{let m=s.controlEl.createDiv({cls:"stashpad-binding-slot"}),v=m.createEl("input",{type:"text"});v.readOnly=!0,v.placeholder="Click & press a key",v.value=Ps(i()[f]),v.classList.add("stashpad-binding-input");let y=()=>{v.size=Math.max(3,v.value.length||v.placeholder.length)};y(),v.onclick=()=>{oi(v,async k=>{this.plugin.settings.bindings[e.id][f]=k,v.value=Ps(k),y(),await this.plugin.saveSettings(),o()})};let b=m.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});return b.title="Clear this slot",b.onclick=async()=>{this.plugin.settings.bindings[e.id][f]="",v.value="",y(),await this.plugin.saveSettings(),o()},v};n=a("primary"),r=a("secondary");let l=s.controlEl.createDiv({cls:"stashpad-binding-pill"});l.setAttribute("role","switch"),l.setAttribute("tabindex","0");let c=l.createDiv({cls:"stashpad-binding-pill-knob"}),p=s.controlEl.createDiv({cls:"stashpad-binding-useboth"}),u=p.createEl("input",{type:"checkbox"});u.title="Use both bindings simultaneously (overrides the L/R toggle)",p.createSpan({text:"Use both"}),u.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=u.checked,await this.plugin.saveSettings(),o()},o=()=>{let f=i(),m=!!(f.primary&&f.secondary);u.checked=!!f.useBoth,u.disabled=!m,p.toggleClass("is-disabled",!m);let v=!!f.useBoth&&m;l.toggleClass("is-disabled",!m||v),l.toggleClass("is-right",f.preferRight),l.setAttribute("aria-checked",String(f.preferRight)),l.setAttribute("aria-disabled",String(!m||v)),c.setText(f.preferRight?"R":"L"),l.title=m?v?'Overridden by "Use both"':f.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let d=async()=>{let f=i();!f.primary||!f.secondary||(this.plugin.settings.bindings[e.id].preferRight=!f.preferRight,o(),await this.plugin.saveSettings())};l.onclick=()=>void d(),l.onkeydown=f=>{(f.key===" "||f.key==="Enter")&&(f.preventDefault(),d())},o()}};var re=class{constructor(h,t){this.app=h;this.ta=t;this.popupEl=null;this.items=[];this.activeIdx=0;this.state=null;this.fileIndex=[];this.tagIndex=[];this.indexBuilt=!1;this.vaultListeners=[];this.scope=null;this.onInput=()=>{let h=this.detectTrigger();if(!h){this.close();return}this.openFor(h)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=h=>{h.key==="Escape"&&(!this.state||!this.items.length||(h.preventDefault(),h.stopPropagation(),h.stopImmediatePropagation(),this.close()))};this.onKeyDown=h=>{!this.state||!this.items.length||(h.key==="ArrowDown"?(h.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):h.key==="ArrowUp"?(h.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):h.key==="Enter"||h.key==="Tab"?(h.preventDefault(),h.stopPropagation(),this.commit()):h.key==="Escape"&&(h.preventDefault(),h.stopPropagation(),h.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let h=this.ta.ownerDocument??document;h.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>h.removeEventListener("keydown",this.onDocEscape,!0)),this.buildIndex();let t=()=>{this.indexBuilt=!1},e=this.app.vault;e.on("create",t),e.on("delete",t),e.on("rename",t),this.vaultListeners.push(()=>e.off("create",t),()=>e.off("delete",t),()=>e.off("rename",t))}isOpen(){return!!this.state&&this.items.length>0}detach(){this.close(),this.ta.removeEventListener("input",this.onInput),this.ta.removeEventListener("keydown",this.onKeyDown,!0),this.ta.removeEventListener("blur",this.onBlur);for(let h of this.vaultListeners)h();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;let h=bt().inheritObsidianExclusions,t=h?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(s=>!Ys(s.path)&&!qs(s.path)&&!(h&&Ks(s.path,t))).map(s=>{let i=s.extension==="md",n=i?s.basename:s.name,r=i?s.basename:s.name;return{label:n,lower:n.toLowerCase(),insertText:r,file:s}});let e=this.app.metadataCache.getTags?.()??{};this.tagIndex=Object.keys(e).sort((s,i)=>(e[i]||0)-(e[s]||0)),this.indexBuilt=!0}detectTrigger(){let h=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=h.slice(0,t),s=e.match(/\[\[([^\]\[\n]*)$/);if(s){let n=s[1];return{kind:"link",query:n,replaceStart:t-n.length-2,replaceEnd:t}}let i=e.match(/(^|\s)#([A-Za-z0-9_/\-]+)$/);if(i){let n=i[2];return{kind:"tag",query:n,replaceStart:t-n.length-1,replaceEnd:t}}return null}buildItems(h){this.buildIndex();let t=h.query.toLowerCase().trim(),e=t?t.split(/\s+/).filter(Boolean):[],s=i=>{if(!e.length)return!0;for(let n of e)if(!i.includes(n))return!1;return!0};return h.kind==="link"?this.fileIndex.filter(n=>s(n.lower)).slice(0,50).map(n=>({label:n.label,insert:`[[${n.insertText}]]`,subtitle:n.file.path})):this.tagIndex.filter(n=>s(n.toLowerCase())).slice(0,30).map(n=>({label:n,insert:n,subtitle:""}))}openFor(h){if(this.state=h,this.items=this.buildItems(h),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let h=new pi.Scope(this.app.scope);h.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=h,this.app.keymap?.pushScope(h)}popScope(){if(this.scope){try{this.app.keymap?.popScope(this.scope)}catch{}this.scope=null}}renderPopup(){if(!this.popupEl){let t=this.ta.ownerDocument??document;this.popupEl=t.body.createDiv({cls:"stashpad-composer-suggest"}),this.popupEl.tabIndex=-1,this.popupEl.addEventListener("mousedown",e=>e.preventDefault())}let h=this.popupEl;h.empty();for(let t=0;t<this.items.length;t++){let e=this.items[t],s=h.createDiv({cls:"stashpad-composer-suggest-row"});t===this.activeIdx&&s.addClass("is-active"),s.createSpan({cls:"stashpad-composer-suggest-label",text:e.label}),e.subtitle&&s.createSpan({cls:"stashpad-composer-suggest-sub",text:e.subtitle}),s.onmousedown=i=>{i.preventDefault(),this.activeIdx=t,this.commit()}}this.position()}refreshActive(){if(!this.popupEl)return;let h=this.popupEl.children;for(let e=0;e<h.length;e++)h[e].toggleClass("is-active",e===this.activeIdx);let t=h[this.activeIdx];t&&t.scrollIntoView({block:"nearest"})}position(){if(!this.popupEl)return;let h=this.ta.getBoundingClientRect(),t=this.popupEl.offsetHeight||200,e=h.top-t-4,s=h.left;this.popupEl.style.left=`${Math.max(8,s)}px`,this.popupEl.style.top=`${Math.max(8,e)}px`,this.popupEl.style.minWidth=`${Math.min(360,h.width)}px`}commit(){if(!this.state||!this.items.length)return;let h=this.items[this.activeIdx];if(!h)return;let t=this.ta.value.slice(0,this.state.replaceStart),e=this.ta.value.slice(this.state.replaceEnd),s=h.insert;this.ta.value=t+s+e;let i=t.length+s.length;this.ta.setSelectionRange(i,i),this.ta.dispatchEvent(new Event("input",{bubbles:!0})),this.close(),this.ta.focus()}close(){this.popupEl&&(this.popupEl.remove(),this.popupEl=null),this.state=null,this.items=[],this.activeIdx=0,this.popScope()}};Tt();var Xe=class extends Ct.ItemView{constructor(t,e){super(t);this.plugin=e;this.displayedPath=null;this.unsubscribeSelection=null;this.renderTimer=null;this.expanded=new Set;this.composerAutocomplete=null;this.composerInputEl=null;this.composerDraft="";this.composerDraftForId=null;this.displayedId=null;this.unsubscribeContent=null}getViewType(){return Ut}getDisplayText(){return"Stashpad detail"}getIcon(){return"panel-right"}async onOpen(){this.render(),this.unsubscribeSelection=this.plugin.onStashpadSelectionChange(()=>{this.displayedId=null,this.scheduleRender()}),this.unsubscribeContent=this.plugin.onStashpadContentChange(()=>this.scheduleRender()),this.registerEvent(this.app.workspace.on("active-leaf-change",t=>{!t||t===this.leaf||t.view?.getViewType?.()===mt&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("modify",t=>{this.displayedPath&&t.path===this.displayedPath&&this.scheduleRender()})),this.registerEvent(this.app.metadataCache.on("changed",t=>{this.displayedPath&&t.path===this.displayedPath&&this.scheduleRender()}))}async onClose(){this.unsubscribeSelection?.(),this.unsubscribeSelection=null,this.unsubscribeContent?.(),this.unsubscribeContent=null,this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,this.renderTimer!=null&&(window.clearTimeout(this.renderTimer),this.renderTimer=null)}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},60))}resolveDisplayed(){if(this.displayedId){let e=this.plugin.lastActiveStashpadLeaf?.view;if(e?.getViewType?.()===mt&&e.tree?.get){let s=e.tree.get(this.displayedId);if(s?.file)return{folder:e.noteFolder,id:this.displayedId,file:s.file}}this.displayedId=null}let t=this.plugin.getActiveStashpadSelection();return t&&(this.displayedId=t.id),t}async render(){let t=this.contentEl,e=!!this.composerInputEl&&document.activeElement===this.composerInputEl,s=this.composerInputEl?.selectionStart??null;this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,t.empty(),t.addClass("stashpad-detail-root");let i=this.resolveDisplayed();if(!i){this.displayedPath=null;let d=t.createDiv({cls:"stashpad-detail-empty"});(0,Ct.setIcon)(d.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),d.createSpan({cls:"stashpad-detail-empty-text",text:"No Stashpad note selected. Cursor or click a note in a Stashpad list to inspect it here."});return}let n=i.file;this.displayedPath=n.path;let r=this.app.metadataCache.getFileCache(n)?.frontmatter??{},o=t.createDiv({cls:"stashpad-detail-scroll"}),a=o.createDiv({cls:"stashpad-detail-header"}),l=a.createDiv({cls:"stashpad-detail-titlerow"});l.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let c=l.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,Ct.setIcon)(c,"arrow-up-right"),c.title="Open this note in a new Stashpad tab",c.onclick=()=>{this.openInStashpad(i.folder,i.id)};let p=a.createDiv({cls:"stashpad-detail-metarow"});if(i.folder&&p.createSpan({cls:"stashpad-detail-meta-chip",text:i.folder.split("/").pop()||i.folder}),typeof r.color=="string"&&r.color){let d=p.createSpan({cls:"stashpad-detail-meta-color"});d.style.background=r.color,d.title=r.color}if(r.completed===!0&&p.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof r.due=="string"||typeof r.due=="number"){let d=Date.parse(String(r.due)),f=Number.isNaN(d)?String(r.due):Yt(d,this.plugin.settings);p.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${f}`})}if(Array.isArray(r.tags))for(let d of r.tags.filter(f=>typeof f=="string"))p.createSpan({cls:"stashpad-detail-meta-tag",text:`#${d.replace(/^#/,"")}`});let u=o.createDiv({cls:"stashpad-detail-body"});try{let d=await this.app.vault.cachedRead(n),f=this.stripFrontmatter(d);await Ct.MarkdownRenderer.render(this.app,f,u,n.path,this)}catch(d){u.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${d.message}`})}if(this.renderFooterMeta(o,n,r,i),this.renderChildren(o,i.folder,i.id),this.renderComposer(t,i),e&&this.composerInputEl&&(this.composerInputEl.focus(),s!=null)){let d=Math.min(s,this.composerInputEl.value.length);try{this.composerInputEl.setSelectionRange(d,d)}catch{}}}renderComposer(t,e){let s=t.createDiv({cls:"stashpad-detail-composer"}),i=s.createEl("textarea",{cls:"stashpad-detail-composer-input",attr:{placeholder:"Add a child note\u2026",rows:"2"}});this.composerInputEl=i,this.composerDraftForId===e.id?i.value=this.composerDraft:(this.composerDraft="",this.composerDraftForId=e.id),i.addEventListener("input",()=>{this.composerDraft=i.value,this.composerDraftForId=e.id}),i.addEventListener("keydown",r=>{if(r.key==="Enter"&&!r.shiftKey&&!r.isComposing){if(this.composerAutocomplete?.isOpen?.())return;r.preventDefault(),this.submitComposer(e)}});let n=s.createEl("button",{cls:"stashpad-detail-composer-send",attr:{"aria-label":"Add child note"}});(0,Ct.setIcon)(n.createSpan({cls:"stashpad-detail-composer-send-icon"}),"plus"),n.createSpan({cls:"stashpad-detail-composer-send-text",text:"Add child note"}),n.title="Add child note (Enter)",n.onclick=()=>void this.submitComposer(e),this.composerAutocomplete=new re(this.app,i),this.composerAutocomplete.attach()}async submitComposer(t){let e=(this.composerInputEl?.value??"").trim();if(!e)return;let s=this.plugin.lastActiveStashpadLeaf?.view;if(!s||s.getViewType?.()!==mt||typeof s.createNoteUnder!="function"){new Ct.Notice("Open a Stashpad view to add notes.");return}try{await s.createNoteUnder(e,t.id)}catch(i){new Ct.Notice(`Couldn't add note: ${i.message}`);return}this.composerDraft="",this.composerDraftForId=t.id,this.composerInputEl&&(this.composerInputEl.value=""),await this.render(),setTimeout(()=>this.composerInputEl?.focus(),0)}renderChildren(t,e,s){let i=this.plugin.lastActiveStashpadLeaf?.view;if(!i||i.getViewType?.()!==mt)return;let n=i.tree;if(!n?.getChildren)return;let r=n.getChildren(s);if(!r||r.length===0)return;let o=t.createDiv({cls:"stashpad-detail-children"});o.createDiv({cls:"stashpad-detail-children-header",text:`Children (${r.length})`});let a=o.createDiv({cls:"stashpad-detail-children-list"});for(let l of r)l.file&&this.renderDetailChildRow(a,i,n,e,l,0)}renderDetailChildRow(t,e,s,i,n,r){if(!n.file)return;let o=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},a=typeof o.color=="string"?o.color:null,l=o.completed===!0,c=s.getChildren(n.id),p=c.length>0,u=`${i}|${n.id}`,d=this.expanded.has(u),f=t.createDiv({cls:"stashpad-detail-child-row"});l&&f.addClass("is-completed"),r>0&&(f.style.paddingLeft=`${r*16}px`),f.draggable=!0,f.dataset.id=n.id,f.addEventListener("dragstart",k=>{k.dataTransfer?.setData("text/plain",n.id),k.dataTransfer&&(k.dataTransfer.effectAllowed="move"),f.addClass("is-dragging")}),f.addEventListener("dragend",()=>f.removeClass("is-dragging")),f.addEventListener("dragover",k=>{k.preventDefault(),k.dataTransfer&&(k.dataTransfer.dropEffect="move");let C=f.getBoundingClientRect(),I=k.clientY-C.top<C.height/2;f.toggleClass("drop-before",I),f.toggleClass("drop-after",!I)}),f.addEventListener("dragleave",()=>{f.removeClass("drop-before"),f.removeClass("drop-after")}),f.addEventListener("drop",k=>{k.preventDefault(),f.removeClass("drop-before"),f.removeClass("drop-after");let C=k.dataTransfer?.getData("text/plain");if(!C||C===n.id)return;let I=f.getBoundingClientRect(),E=k.clientY-I.top<I.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([C],n.id,E?"before":"after")}),f.oncontextmenu=k=>{k.preventDefault();let C=s.get(n.id);C&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(k,C)};let m=f.createSpan({cls:"stashpad-detail-child-toggle"});if(p&&($e(m,c.length,d),m.onclick=k=>{k.stopPropagation(),this.expanded.has(u)?this.expanded.delete(u):this.expanded.add(u),this.render()}),Vt(o,"task")||o.task===!0||o.completed!==void 0){let k=f.createSpan({cls:"stashpad-detail-child-checkbox"});(0,Ct.setIcon)(k,l?"check-square":"square"),k.title=l?"Mark not done":"Mark done",k.addEventListener("mousedown",C=>C.stopPropagation()),k.addEventListener("dblclick",C=>{C.preventDefault(),C.stopPropagation()}),k.onclick=C=>{C.preventDefault(),C.stopPropagation();let I=s.get(n.id);I&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(I)}}let y=f.createSpan({cls:"stashpad-detail-child-icon"});(0,Ct.setIcon)(y,p?"folder-tree":"file-text"),a&&(y.style.color=a);let b=f.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(b.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},p&&d)for(let k of c)this.renderDetailChildRow(t,e,s,i,k,r+1)}renderFooterMeta(t,e,s,i){let n=t.createDiv({cls:"stashpad-detail-footer-meta"}),r=[];if(typeof s.author=="string"&&s.author&&r.push({label:"Author",value:this.stripWikiLink(s.author)}),Array.isArray(s.contributors)){let o=s.contributors.filter(a=>typeof a=="string").map(a=>this.stripWikiLink(a));o.length>0&&r.push({label:"Contributors",value:o.join(", ")})}if(typeof s.modified=="string"&&r.push({label:"Modified",value:this.formatTime(s.modified)}),typeof s.created=="string"&&r.push({label:"Created",value:this.formatTime(s.created)}),r.push({label:"Path",value:e.path}),r.push({label:"ID",value:i.id}),r.length===0){n.remove();return}for(let o of r){let a=n.createDiv({cls:"stashpad-detail-meta-line"});a.createSpan({cls:"stashpad-detail-meta-key",text:o.label}),a.createSpan({cls:"stashpad-detail-meta-val",text:o.value})}}titleFor(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")}stripFrontmatter(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` ----`,3);return e<0?t:t.slice(e+4).replace(/^\n+/,"")}stripWikiLink(t){let e=t.match(/^\[\[(.+?)(?:\|(.+))?\]\]$/);return e?e[2]??(e[1].split("/").pop()??e[1]).replace(/\.md$/,""):t}formatTime(t){let e=Date.parse(t);return Number.isFinite(e)?Yt(e,this.plugin.settings):t}async openInStashpad(t,e){try{await this.plugin.activateViewForFolder(t);let s=this.plugin.lastActiveStashpadLeaf?.view;s?.navigateTo&&e!==R&&s.navigateTo(e)}catch(s){new Ct.Notice(`Couldn't open: ${s.message}`)}}};async function Qe(g){let h=g.workspace.getLeavesOfType(Ut);if(h.length>0){g.workspace.revealLeaf(h[0]);return}let t=g.workspace.getRightLeaf(!1);if(!t){new Ct.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:Ut,active:!0}),g.workspace.revealLeaf(t)}var O=require("obsidian");Tt();var zt=require("obsidian");Tt();function Yi(g,h){let t=g.vault.getAbstractFileByPath(h);if(!(t instanceof zt.TFolder))return[];let e=[],s=[t];for(;s.length;){let i=s.pop();for(let n of i.children)n instanceof zt.TFile?n.extension==="md"&&e.push(n):n instanceof zt.TFolder&&(Me.has(n.name)||s.push(n))}return e}var ts=class{constructor(h){this.app=h;this.nodes=new Map;this.byPath=new Map;this.listeners=new Set;this.orderProvider=null;this.synthetic=new Map;this.coalesceTimer=null;this.nodes.set(R,{id:R,parent:null,children:[],file:null,created:""})}setOrderProvider(h){this.orderProvider=h}onChange(h){return this.listeners.add(h),()=>this.listeners.delete(h)}emit(){for(let h of this.listeners)h()}rebuild(h){h!==void 0&&(this.currentFolder=h);let t=this.currentFolder,e=this.byPath,s=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(R,{id:R,parent:null,children:[],file:null,created:""});let i=t?Yi(this.app,t):this.app.vault.getMarkdownFiles();for(let n of i){let r=this.app.metadataCache.getFileCache(n)?.frontmatter,o=r?.id;if(!o){let l=e.get(n.path),c=l?s.get(l):void 0,p=this.synthetic.get(n.path),u=c??p;u&&(this.nodes.set(u.id,{...u,children:[],file:n}),this.byPath.set(n.path,u.id));continue}if(this.synthetic.delete(n.path),o===R){let l=this.nodes.get(R);l.file=n,l.created=r?.created??"",this.byPath.set(n.path,R);continue}let a=r?.parent??null;a===o&&(a=null),this.nodes.set(o,{id:o,parent:a??R,children:[],file:n,created:r?.created??""}),this.byPath.set(n.path,o)}for(let n of this.nodes.values()){if(n.id===R)continue;let r=n.parent??R;(this.nodes.get(r)??this.nodes.get(R)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((r,o)=>{let a=this.nodes.get(r),l=this.nodes.get(o);return(a.created||"").localeCompare(l.created||"")}),this.orderProvider){let r=this.orderProvider(n.id);if(r.length>0){let o=new Map;r.forEach((a,l)=>o.set(a,l)),n.children.sort((a,l)=>{let c=o.has(a)?o.get(a):1/0,p=o.has(l)?o.get(l):1/0;return c===p?0:c-p})}}this.emit()}insertSynthetic(h){if(!h.file)return;let t=h.file.path;this.synthetic.set(t,h),this.nodes.set(h.id,h),this.byPath.set(t,h.id);let e=h.parent??R,s=this.nodes.get(e);s&&!s.children.includes(h.id)&&s.children.push(h.id),this.emit()}get(h){return this.nodes.get(h)}getRoot(){return this.nodes.get(R)}getChildren(h){let t=this.nodes.get(h);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let h=0;for(let t of this.nodes.values())t.file&&h++;return h}pathTo(h){let t=[],e=new Set,s=this.nodes.get(h);for(;s&&s.id!==R&&!e.has(s.id);)e.add(s.id),t.unshift(s),s=s.parent?this.nodes.get(s.parent):void 0;return t}idForPath(h){return this.byPath.get(h)}snapshot(){let h={};for(let t of this.nodes.values())t.id===R||!t.file||(h[t.id]={parent:t.parent===R?null:t.parent,path:t.file.path});return h}hookMetadataCache(h){let t=a=>{let l=this.currentFolder;return l?typeof a!="string"?!1:a===l||a.startsWith(l+"/"):!0},e=!1,s=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),h())},16))},i=a=>{a instanceof zt.TFile&&t(a.path)&&a.extension==="md"&&this.applyChange(a)&&s()},n=a=>{a instanceof zt.TFile&&t(a.path)&&a.extension==="md"&&this.applyChange(a)&&s()},r=a=>{let l=a?.path;typeof l=="string"&&t(l)&&this.applyDelete(l)&&s()},o=(a,l)=>{if(!(a instanceof zt.TFile))return;let c=typeof l=="string"?l:null;!t(a.path)&&!t(c)||this.applyRename(a,c??"")&&s()};return this.app.metadataCache.on("changed",i),this.app.vault.on("create",n),this.app.vault.on("delete",r),this.app.vault.on("rename",o),()=>{this.app.metadataCache.off("changed",i),this.app.vault.off("create",n),this.app.vault.off("delete",r),this.app.vault.off("rename",o),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}applyChange(h){let t=this.app.metadataCache.getFileCache(h)?.frontmatter,e=t?.id,s=this.byPath.get(h.path);if(!e){if(s){let l=this.nodes.get(s);if(l&&l.file!==h)return l.file=h,!0}return!1}if(this.synthetic.delete(h.path),e===R){let l=this.nodes.get(R),c=t?.created??"",p=!1;return l.file!==h&&(l.file=h,p=!0),l.created!==c&&(l.created=c,p=!0),this.byPath.get(h.path)!==R&&(this.byPath.set(h.path,R),p=!0),p}let i=t?.parent??R,n=t?.created??"";if(!(i===R||this.nodes.has(i)))return this.rebuild(),!0;if(s&&s!==e)return this.rebuild(),!0;let o=this.nodes.get(e);if(!o){let l={id:e,parent:i,children:[],file:h,created:n};return this.nodes.set(e,l),this.byPath.set(h.path,e),this.attachToParent(l),this.resortChildrenOf(i),!0}let a=!1;if(o.file!==h&&(o.file=h,a=!0),o.created!==n&&(o.created=n,this.resortChildrenOf(o.parent??R),a=!0),o.parent!==i){let l=o.parent??R;this.detachFromParent(o),o.parent=i,this.attachToParent(o),this.resortChildrenOf(l),this.resortChildrenOf(i),a=!0}return a}applyDelete(h){let t=this.byPath.get(h);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(h),this.synthetic.delete(h),!0;this.detachFromParent(e);let s=this.nodes.get(R);for(let i of e.children){let n=this.nodes.get(i);n&&(n.parent=R,s.children.includes(i)||s.children.push(i))}return e.children.length>0&&this.resortChildrenOf(R),this.nodes.delete(t),this.byPath.delete(h),this.synthetic.delete(h),!0}applyRename(h,t){let e=this.currentFolder,s=!e||t===e||t.startsWith(e+"/"),i=!e||h.path===e||h.path.startsWith(e+"/");if(!s&&!i)return!1;if(s&&!i)return this.applyDelete(t);if(!s&&i)return this.applyChange(h);let n=this.byPath.get(t);if(!n)return this.applyChange(h);this.byPath.delete(t),this.byPath.set(h.path,n);let r=this.nodes.get(n);return r&&(r.file=h),!0}detachFromParent(h){let t=this.nodes.get(h.parent??R);if(!t)return;let e=t.children.indexOf(h.id);e>=0&&t.children.splice(e,1)}attachToParent(h){let t=this.nodes.get(h.parent??R);t||(t=this.nodes.get(R)),t.children.includes(h.id)||t.children.push(h.id)}resortChildrenOf(h){let t=this.nodes.get(h);if(t&&(t.children.sort((e,s)=>{let i=this.nodes.get(e),n=this.nodes.get(s);return(i.created||"").localeCompare(n.created||"")}),this.orderProvider)){let e=this.orderProvider(h);if(e.length>0){let s=new Map;e.forEach((i,n)=>s.set(i,n)),t.children.sort((i,n)=>{let r=s.has(i)?s.get(i):1/0,o=s.has(n)?s.get(n):1/0;return r===o?0:r-o})}}}};var ui=".stashpad-order.json",es=class{constructor(h){this.app=h;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(h){if(this.cache.has(h))return this.cache.get(h);let t=`${h}/${ui}`,e=this.app.vault.adapter,s={};try{if(await e.exists(t)){let i=await e.read(t),n=JSON.parse(i);if(n&&typeof n=="object"&&!Array.isArray(n))for(let[r,o]of Object.entries(n))Array.isArray(o)&&o.every(a=>typeof a=="string")&&(s[r]=o)}}catch(i){console.warn("Stashpad: order load failed",i)}return this.cache.set(h,s),s}async save(h){this.scheduleWrite(h)}async flush(h){let t=this.pendingTimers.get(h);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(h)),await this.writeNow(h)}scheduleWrite(h){let t=this.pendingTimers.get(h);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(h),this.writeNow(h)},150);this.pendingTimers.set(h,e)}async writeNow(h){let e=(this.writeInFlight.get(h)??Promise.resolve()).then(()=>this.doWrite(h));this.writeInFlight.set(h,e);try{await e}finally{this.writeInFlight.get(h)===e&&this.writeInFlight.delete(h)}}async doWrite(h){let t=this.cache.get(h)??{},e={};for(let[n,r]of Object.entries(t))r.length>0&&(e[n]=r);this.cache.set(h,e);let s=`${h}/${ui}`,i=this.app.vault.adapter;try{if(Object.keys(e).length===0)try{await i.remove(s)}catch{}else await i.write(s,JSON.stringify(e,null,2))}catch(n){console.warn("Stashpad: order save failed",n)}}getOrder(h,t){return this.cache.get(h)?.[t]?.slice()??[]}setOrder(h,t,e){let s=this.cache.get(h)??{};s[t]=e.slice(),this.cache.set(h,s)}appendChild(h,t,e){let s=this.cache.get(h)??{},i=s[t]??[];i.includes(e)||i.push(e),s[t]=i,this.cache.set(h,s)}removeChild(h,t){let e=this.cache.get(h);if(e)for(let s of Object.values(e)){let i=s.indexOf(t);i>=0&&s.splice(i,1)}}invalidate(h){this.cache.delete(h)}};var xe={manual:"Manual","created-asc":"Created \u2014 oldest first","created-desc":"Created \u2014 newest first","modified-asc":"Modified \u2014 oldest first","modified-desc":"Modified \u2014 newest first","title-az":"Title \u2014 A\u2192Z","title-za":"Title \u2014 Z\u2192A"},Ns=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],qi=new Set(Ns),fi=".stashpad-sort.json",ss=class{constructor(h){this.app=h;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(h){if(this.cache.has(h))return this.cache.get(h);let t=`${h}/${fi}`,e=this.app.vault.adapter,s={};try{if(await e.exists(t)){let i=JSON.parse(await e.read(t));if(i&&typeof i=="object"&&!Array.isArray(i))for(let[n,r]of Object.entries(i))typeof r=="string"&&qi.has(r)&&(s[n]=r)}}catch(i){console.warn("Stashpad: sort load failed",i)}return this.cache.set(h,s),s}async save(h){this.scheduleWrite(h)}async flush(h){let t=this.pendingTimers.get(h);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(h)),await this.writeNow(h)}scheduleWrite(h){let t=this.pendingTimers.get(h);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(h),this.writeNow(h)},150);this.pendingTimers.set(h,e)}async writeNow(h){let e=(this.writeInFlight.get(h)??Promise.resolve()).then(()=>this.doWrite(h));this.writeInFlight.set(h,e);try{await e}finally{this.writeInFlight.get(h)===e&&this.writeInFlight.delete(h)}}async doWrite(h){let t=this.cache.get(h)??{},e=`${h}/${fi}`,s=this.app.vault.adapter;try{if(Object.keys(t).length===0)try{await s.remove(e)}catch{}else await s.write(e,JSON.stringify(t,null,2))}catch(i){console.warn("Stashpad: sort save failed",i)}}getMode(h,t){return this.cache.get(h)?.[t]??"manual"}setMode(h,t,e){let s=this.cache.get(h)??{};e==="manual"?delete s[t]:s[t]=e,this.cache.set(h,s)}removeParent(h,t){let e=this.cache.get(h);e&&delete e[t]}invalidate(h){this.cache.delete(h)}};Tt();var Wt="parentLink",ae="children";var rs=class rs{constructor(h,t){this.app=h;this.getTree=t;this.pending=new Set;this.timer=null;this.activityListeners=new Set;this.errorListeners=new Set}onActivity(h){return this.activityListeners.add(h),()=>this.activityListeners.delete(h)}emitActivity(){let h=this.pending.size;for(let t of this.activityListeners)try{t(h)}catch(e){console.warn("[Stashpad] fmSync activity listener failed",e)}}schedule(h){if(!h)return;let t=this.pending.size;this.pending.add(h),this.pending.size!==t&&this.emitActivity(),this.kick()}scheduleParentChange(h,t,e){this.schedule(h),t&&this.schedule(t),this.schedule(e)}scheduleSubtree(h){let t=this.getTree(),e=s=>{this.schedule(s);for(let i of t.getChildren(s))e(i.id)};e(h)}scheduleParentOfDeleted(h){h&&this.schedule(h)}async flush(){for(this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null);this.pending.size>0;){let h=this.pending.values().next().value;if(h===void 0)break;this.pending.delete(h),this.emitActivity(),await this.syncOne(h)}}pendingCount(){return this.pending.size}onError(h){return this.errorListeners.add(h),()=>this.errorListeners.delete(h)}emitError(h,t){for(let e of this.errorListeners)try{e(h,t)}catch(s){console.warn("[Stashpad] fmSync error listener failed",s)}}reset(){this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null),this.pending.clear()}kick(){this.timer!=null||this.pending.size===0||(this.timer=window.setTimeout(()=>this.tick(),rs.PACING_MS))}async tick(){this.timer=null;let h=this.pending.values().next().value;if(h!==void 0){this.pending.delete(h),this.emitActivity();try{await this.syncOne(h)}catch(t){console.warn("[Stashpad] frontmatter sync tick failed",t)}this.pending.size>0&&this.kick()}}wouldWrite(h){let e=this.getTree().get(h);if(!e||!e.file)return!1;let s=this.computeParentLink(e),i=this.computeChildrenLinks(e),n=this.app.metadataCache.getFileCache(e.file)?.frontmatter,r=n&&typeof n[Wt]=="string"?n[Wt]:null,o=n?.[ae],a=Array.isArray(o)?o.filter(l=>typeof l=="string"):[];if((r??null)!==(s??null)||a.length!==i.length)return!0;for(let l=0;l<a.length;l++)if(a[l]!==i[l])return!0;return!1}async syncOne(h){let e=this.getTree().get(h);if(!e||!e.file||!this.wouldWrite(h))return;let s=this.computeParentLink(e),i=this.computeChildrenLinks(e);try{await this.app.fileManager.processFrontMatter(e.file,n=>{s?n[Wt]=s:delete n[Wt],i.length>0?n[ae]=i:delete n[ae]})}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(h){if(h.id===R)return null;let t=this.getTree();if(!h.parent||h.parent===R){let s=t.getRoot();return s&&s.id!==h.id&&s.file?is(s.file.path):null}let e=t.get(h.parent);return e?.file?is(e.file.path):null}computeChildrenLinks(h){return this.getTree().getChildren(h.id).filter(e=>!!e.file).map(e=>is(e.file.path))}};rs.PACING_MS=100;var ns=rs;async function mi(g,h){let t=h.endsWith("/")?h:h+"/",e=new Map,s=new Map;for(let l of g.vault.getMarkdownFiles()){if(l.path!==h&&!l.path.startsWith(t))continue;let c=g.metadataCache.getFileCache(l)?.frontmatter,p=typeof c?.id=="string"?c.id:null;if(!p)continue;let u=typeof c?.parent=="string"?c.parent:R;e.set(p,{file:l,id:p,parent:u});let d=s.get(u)??[];d.push(p),s.set(u,d)}let i=l=>is(l.file.path),n=l=>{if(l.id===R)return null;if(l.parent===R||!l.parent){let p=e.get(R);return p?i(p):null}let c=e.get(l.parent);return c?i(c):null},r=l=>{let c=s.get(l.id)??[],p=[];for(let u of c){let d=e.get(u);d&&p.push(i(d))}return p},o=0,a=0;for(let l of e.values()){o+=1;let c=n(l),p=r(l),u=g.metadataCache.getFileCache(l.file)?.frontmatter,d=u&&typeof u[Wt]=="string"?u[Wt]:null,f=u?.[ae],m=Array.isArray(f)?f.filter(b=>typeof b=="string"):[],v=(d??null)===(c??null),y=m.length===p.length&&m.every((b,k)=>b===p[k]);if(!(v&&y))try{await g.fileManager.processFrontMatter(l.file,b=>{c?b[Wt]=c:delete b[Wt],p.length>0?b[ae]=p:delete b[ae]}),a+=1,await new Promise(b=>setTimeout(b,50))}catch(b){console.warn("[Stashpad] rebootstrap fm sync failed",l.file.path,b)}}return{checked:o,written:a}}function is(g){return`[[${g.replace(/\.md$/i,"")}]]`}Pt();se();var as=class{constructor(h,t){this.tree=h;this.log=t}async sweep(h){let t=await this.log.readState(),e=this.tree.snapshot(),s=n=>{if(!h)return!0;let r=h.replace(/\/+$/,"");return n===r||n.startsWith(r+"/")};for(let[n,r]of Object.entries(e)){let o=t[n];o?o.parent!==r.parent?await this.log.append({type:"parent_change",id:n,payload:{from:o.parent,to:r.parent}}):o.path!==r.path&&await this.log.append({type:"rename",id:n,payload:{from:o.path,to:r.path}}):await this.log.append({type:"create",id:n,payload:{path:r.path,parent:r.parent}})}for(let[n,r]of Object.entries(t))!e[n]&&s(r.path)&&await this.log.append({type:"missing",id:n,payload:{lastPath:r.path}});let i={};for(let[n,r]of Object.entries(t))s(r.path)||(i[n]=r);for(let[n,r]of Object.entries(e))i[n]=r;await this.log.writeState(i)}};var dt=require("obsidian");Tt();Ts();function Os(g){let h=g.trim().toLowerCase();if(!h)return null;let t=Date.now(),e=f=>(0,dt.moment)(f).startOf("day").valueOf(),s=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,i=0,n=!1,r=h,o=s.exec(h);if(o&&(o[3]||o[2])){let f=parseInt(o[1],10),m=o[2]?parseInt(o[2],10):0,v=o[3];v==="pm"&&f<12&&(f+=12),v==="am"&&f===12&&(f=0),f>=0&&f<24&&m>=0&&m<60&&(i=(f*3600+m*60)*1e3,n=!0,r=h.replace(o[0]," ").replace(/\s+/g," ").trim())}let a=f=>n?f+i:f;if(r===""||r==="today")return a(e(t));if(r==="yesterday")return a(e(t)-864e5);if(r==="tomorrow")return a(e(t)+864e5);let l=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],c=["sun","mon","tue","wed","thu","fri","sat"],p=l.indexOf(r)>=0?l.indexOf(r):c.indexOf(r);if(p>=0){let f=(0,dt.moment)().startOf("day"),v=(f.day()-p+7)%7;return a(f.subtract(v,"days").valueOf())}let u=/^(\d+)\s*([dwmy])$/.exec(r);if(u){let f=parseInt(u[1],10),m={d:"days",w:"weeks",m:"months",y:"years"}[u[2]];return a((0,dt.moment)().subtract(f,m).startOf("day").valueOf())}let d=(0,dt.moment)(r,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return d.isValid()?a(d.startOf("day").valueOf()):null}function gi(g){let h={text:[],filters:{}},t=(g||"").trim();if(!t)return h;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,s=t,i;for(;(i=e.exec(t))!=null;){let n=i[1].toLowerCase(),r=(i[2]!==void 0?i[2]:i[3]??"").trim();if(r){if(n==="in")h.filters.in=r.toLowerCase();else if(n==="before"){let o=Os(r);o!=null&&(h.filters.before=o)}else if(n==="after"){let o=Os(r);o!=null&&(h.filters.after=o)}else if(n==="on"){let o=Os(r);if(o!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(r))h.filters.on={start:o-6e4,end:o+6e4};else{let l=(0,dt.moment)(o).startOf("day").valueOf();h.filters.on={start:l,end:l+864e5}}}s=s.replace(i[0]," ")}}for(let n of s.split(/\s+/))n&&h.text.push(n.toLowerCase());return h}var Ot=class g extends dt.SuggestModal{constructor(t,e,s,i){super(t);this.tree=e;this.titleFn=s;this.opts=i;this.notes=[];this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(i.placeholder??(i.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}onClose(){for(;this.pendingCleanups.length>0;){let t=this.pendingCleanups.pop();try{t&&t()}catch{}}}loadAll(){let t=(s,i)=>{let n=this.tree.get(s);n?.file&&s!==R?this.notes.push({node:n,title:`${" ".repeat(i)}${this.titleFn(n)}`,body:""}):n?.file&&s===R&&this.notes.push({node:n,title:"Home",body:""});for(let r of this.tree.getChildren(s))t(r.id,i+1)},e=this.tree.getRoot();e.file&&this.notes.push({node:e,title:"Home",body:""});for(let s of this.tree.getChildren(R))t(s.id,1);for(let s of this.notes)s.node?.file&&this.app.vault.cachedRead(s.node.file).then(i=>{s.body=this.stripFm(i)});if(this.opts.crossFolderNotes){let s=this.opts.crossFolderNotes();for(let i of s)this.notes.push({node:null,title:i.title,body:i.body,cross:i});for(let i of this.notes)!i.cross||i.body||i.cross.file&&this.app.vault.cachedRead(i.cross.file).then(n=>{i.body=this.stripFm(n)})}}createdMsFor(t){if(t.node?.created){let e=Date.parse(t.node.created);if(!Number.isNaN(e))return e}return t.cross?.file?.stat?.ctime!=null?t.cross.file.stat.ctime:null}stripFm(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` ----`,3);return e===-1?t:t.slice(e+4).replace(/^\r?\n/,"")}getSuggestions(t){let e=t.trim().toLowerCase(),s=gi(t),i=s.text;console.log("[Stashpad] search query parsed",{query:t,text:s.text,filters:s.filters});let n=y=>{if(!i.length)return!0;for(let b of i)if(!y.includes(b))return!1;return!0},r=null,o=null;if(s.filters.in){let y=s.filters.in.split(/\s+/).filter(Boolean);r=new Set,o=new Map;let b=I=>y.every(E=>I.toLowerCase().includes(E)),k=I=>{if(!r.has(I)){r.add(I);for(let E of this.tree.getChildren(I))k(E.id)}};for(let I of this.notes)!I.node||I.cross||b(I.title)&&k(I.node.id);let C=new Map;for(let I of this.notes){if(!I.cross)continue;let E=C.get(I.cross.folder)??[];E.push(I),C.set(I.cross.folder,E)}for(let[I,E]of C){let D=new Map;for(let A of E){let S=A.cross?.parentId??null;if(!S)continue;let _=D.get(S)??[];_.push(A.cross.id),D.set(S,_)}let H=new Set;o.set(I,H);let T=A=>{if(!H.has(A)){H.add(A);for(let S of D.get(A)??[])T(S)}};for(let A of E)b(A.title)&&T(A.cross.id)}}let a=y=>{let b=s.filters;if(r||o)if(y.cross){let k=o?.get(y.cross.folder);if(!k||!k.has(y.cross.id))return!1}else if(y.node){if(!r||!r.has(y.node.id))return!1}else return!1;if(b.before||b.after||b.on){let k=this.createdMsFor(y);if(k==null||b.before!=null&&k>=b.before||b.after!=null&&k<=b.after||b.on&&(k<b.on.start||k>=b.on.end))return!1}return!0},l=y=>n(y.toLowerCase()),c=this.notes.filter(y=>!y.cross),p=this.notes.filter(y=>y.cross),u=(y,b)=>({id:y.cross?`cross:${y.cross.id}`:y.node.id,label:y.title,node:y.node,kind:"note",bodyPreview:this.previewFromBody(y.body,b),matchLine:b,crossFolder:y.cross?.folder,crossFile:y.cross?.file}),d=y=>{let b=[];for(let k of y)if(a(k))if(this.opts.mode==="search"){if(!e){b.push(u(k,-1));continue}let C=n(k.title.toLowerCase()),I=k.body.split(/\r?\n/),E=[];for(let H=0;H<I.length;H++)l(I[H])&&E.push(H);let D=E.length>0||n(k.body.toLowerCase());if(!C&&!D)continue;if(E.length===0)b.push(u(k,-1));else{let H=[],T=-100;for(let S of E)S-T>5&&H.push(S),T=S;let A=5;for(let S of H.slice(0,A))b.push(u(k,S))}}else{if(e&&!n(k.title.toLowerCase())&&!n(k.body.toLowerCase()))continue;b.push(u(k,-1))}return b},f=d(c),m=[...f];if(this.opts.mode==="search"?e?!0:f.length<10:!!e){let y=d(p);this.opts.mode==="search"&&!e&&(m.length=Math.min(m.length,50)),m.push(...y)}if(this.opts.folderResults){let y=this.opts.folderResults(),b=!e||y.some(k=>{let C=k.split("/").pop()??k;return n(`${k.toLowerCase()} ${C.toLowerCase()}`)});if(y.length>0&&b){let k={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};Object.keys(s.filters).length>0?m.push(k):m.unshift(k)}}return this.opts.allowCreate&&e&&!m.some(y=>y.label.trim().toLowerCase()===e)&&m.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),m}previewFromBody(t,e){let s=t.split(/\r?\n/);if(e<0)return s.filter(o=>o.trim().length>0).slice(0,3).join(` +`}function Ye(g,d){let t=document.createDocumentFragment(),e=t.createEl("div",{text:"Home note updated"});e.style.fontWeight="600",e.style.marginBottom="6px";let s=t.createEl("ul");s.style.margin="0 0 8px 0",s.style.paddingLeft="18px",s.createEl("li",{text:`${d.indexed.length} indexed`}),s.createEl("li",{text:`${d.nonIndex.length+d.skippedStashpadNotes.length} excluded`});let i=t.createEl("button",{text:"Open",cls:"mod-cta"});i.style.padding="2px 10px",i.style.fontSize="var(--font-ui-smaller)";let n;return i.onclick=async r=>{if(r.stopPropagation(),d.previewPath){let a=g.vault.getAbstractFileByPath(d.previewPath);a instanceof kt.TFile&&await g.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new kt.Notice(t,0),n}var kt,oi,Ae,De=ee(()=>{"use strict";kt=require("obsidian");Mt();ae();Tt();oi=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Ae=class extends kt.Modal{constructor(t,e,s,i,n){super(t);this.plugin=e;this.settings=s;this.indexedCount=i;this.onBuild=n;this.LARGE_BUILD=50;this.previewRan=!1;this.previewPath=null}onOpen(){let{contentEl:t,titleEl:e}=this,s=!this.settings.jdIndexHasBuilt,i=this.indexedCount>this.LARGE_BUILD;e.setText(s?"Build JD index \u2014 first time?":"Build JD index");let n=this.settings.jdIndexStashpadFolder,r=t.createEl("p"),a=`${this.indexedCount} note${this.indexedCount===1?"":"s"}`;s?(r.appendText(`Stashpad is about to create ${a} (plus synthetic parents as needed) inside "`),r.createEl("code",{text:n}),r.appendText('". Existing notes with the same '),r.createEl("code",{text:"jdPrefix"}),r.appendText(" are updated, never deleted \u2014 but if the prefix detection picks up notes you didn't mean to index, you'll end up with a lot of unwanted notes."),t.createEl("p").setText("Running Preview first writes a single Markdown file showing exactly what would be built (and what wouldn't), so you can sanity-check before committing.")):i?(r.appendText(`You're about to create ${this.indexedCount} notes in "`),r.createEl("code",{text:n}),r.appendText(`". That's a big batch \u2014 if anything looks off, Preview the single-file output first.`)):(r.appendText('Build the JD index into "'),r.createEl("code",{text:n}),r.appendText(`"? Stashpad will create / update ${a}. Existing notes with matching `),r.createEl("code",{text:"jdPrefix"}),r.appendText(" are updated in place.")),this.previewRan&&this.previewPath&&t.createEl("p",{cls:"setting-item-description"}).setText(`\u2713 Preview written to home note (${this.previewPath}). Open it before building if you haven't.`);let o=new kt.Setting(t);(s||i)&&o.addButton(l=>{l.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),l.setCta(),l.onClick(async()=>{try{let c=await Ve(this.app,this.plugin,this.settings);if(c.error==="no-dest"){new kt.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(c.error==="no-home"){new kt.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first.`,7e3),this.close();return}this.previewRan=!0,this.previewPath=c.previewPath,Ye(this.app,c),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(c){new kt.Notice(`Preview failed: ${c?.message??c}`,8e3)}})}),o.addButton(l=>{l.setButtonText(s?"Build anyway":"Build"),!s&&!i&&l.setCta(),l.onClick(async()=>{this.close(),await this.onBuild()})}),o.addButton(l=>{l.setButtonText("Cancel"),l.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});var Ti=Hi((ki,js)=>{(function(g){typeof ki=="object"&&typeof js<"u"?js.exports=g():typeof define=="function"&&define.amd?define([],g):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=g()})(function(){return function g(d,t,e){function s(r,a){if(!t[r]){if(!d[r]){var o=typeof require=="function"&&require;if(!a&&o)return o(r,!0);if(i)return i(r,!0);var l=new Error("Cannot find module '"+r+"'");throw l.code="MODULE_NOT_FOUND",l}var c=t[r]={exports:{}};d[r][0].call(c.exports,function(p){var u=d[r][1][p];return s(u||p)},c,c.exports,g,d,t,e)}return t[r].exports}for(var i=typeof require=="function"&&require,n=0;n<e.length;n++)s(e[n]);return s}({1:[function(g,d,t){"use strict";var e=g("./utils"),s=g("./support"),i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var r,a,o,l,c,p,u,h=[],f=0,m=n.length,v=m,y=e.getTypeOf(n)!=="string";f<n.length;)v=m-f,o=y?(r=n[f++],a=f<m?n[f++]:0,f<m?n[f++]:0):(r=n.charCodeAt(f++),a=f<m?n.charCodeAt(f++):0,f<m?n.charCodeAt(f++):0),l=r>>2,c=(3&r)<<4|a>>4,p=1<v?(15&a)<<2|o>>6:64,u=2<v?63&o:64,h.push(i.charAt(l)+i.charAt(c)+i.charAt(p)+i.charAt(u));return h.join("")},t.decode=function(n){var r,a,o,l,c,p,u=0,h=0,f="data:";if(n.substr(0,f.length)===f)throw new Error("Invalid base64 input, it looks like a data url.");var m,v=3*(n=n.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(n.charAt(n.length-1)===i.charAt(64)&&v--,n.charAt(n.length-2)===i.charAt(64)&&v--,v%1!=0)throw new Error("Invalid base64 input, bad content length.");for(m=s.uint8array?new Uint8Array(0|v):new Array(0|v);u<n.length;)r=i.indexOf(n.charAt(u++))<<2|(l=i.indexOf(n.charAt(u++)))>>4,a=(15&l)<<4|(c=i.indexOf(n.charAt(u++)))>>2,o=(3&c)<<6|(p=i.indexOf(n.charAt(u++))),m[h++]=r,c!==64&&(m[h++]=a),p!==64&&(m[h++]=o);return m}},{"./support":30,"./utils":32}],2:[function(g,d,t){"use strict";var e=g("./external"),s=g("./stream/DataWorker"),i=g("./stream/Crc32Probe"),n=g("./stream/DataLengthProbe");function r(a,o,l,c,p){this.compressedSize=a,this.uncompressedSize=o,this.crc32=l,this.compression=c,this.compressedContent=p}r.prototype={getContentWorker:function(){var a=new s(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),o=this;return a.on("end",function(){if(this.streamInfo.data_length!==o.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new s(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},r.createWorkerFrom=function(a,o,l){return a.pipe(new i).pipe(new n("uncompressedSize")).pipe(o.compressWorker(l)).pipe(new n("compressedSize")).withStreamInfo("compression",o)},d.exports=r},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(g,d,t){"use strict";var e=g("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=g("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(g,d,t){"use strict";var e=g("./utils"),s=function(){for(var i,n=[],r=0;r<256;r++){i=r;for(var a=0;a<8;a++)i=1&i?3988292384^i>>>1:i>>>1;n[r]=i}return n}();d.exports=function(i,n){return i!==void 0&&i.length?e.getTypeOf(i)!=="string"?function(r,a,o,l){var c=s,p=l+o;r^=-1;for(var u=l;u<p;u++)r=r>>>8^c[255&(r^a[u])];return-1^r}(0|n,i,i.length,0):function(r,a,o,l){var c=s,p=l+o;r^=-1;for(var u=l;u<p;u++)r=r>>>8^c[255&(r^a.charCodeAt(u))];return-1^r}(0|n,i,i.length,0):0}},{"./utils":32}],5:[function(g,d,t){"use strict";t.base64=!1,t.binary=!1,t.dir=!1,t.createFolders=!0,t.date=null,t.compression=null,t.compressionOptions=null,t.comment=null,t.unixPermissions=null,t.dosPermissions=null},{}],6:[function(g,d,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:g("lie"),d.exports={Promise:e}},{lie:37}],7:[function(g,d,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",s=g("pako"),i=g("./utils"),n=g("./stream/GenericWorker"),r=e?"uint8array":"array";function a(o,l){n.call(this,"FlateWorker/"+o),this._pako=null,this._pakoAction=o,this._pakoOptions=l,this.meta={}}t.magic="\b\0",i.inherits(a,n),a.prototype.processChunk=function(o){this.meta=o.meta,this._pako===null&&this._createPako(),this._pako.push(i.transformTo(r,o.data),!1)},a.prototype.flush=function(){n.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},a.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this._pako=null},a.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var o=this;this._pako.onData=function(l){o.push({data:l,meta:o.meta})}},t.compressWorker=function(o){return new a("Deflate",o)},t.uncompressWorker=function(){return new a("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(g,d,t){"use strict";function e(c,p){var u,h="";for(u=0;u<p;u++)h+=String.fromCharCode(255&c),c>>>=8;return h}function s(c,p,u,h,f,m){var v,y,b=c.file,k=c.compression,T=m!==r.utf8encode,I=i.transformTo("string",m(b.name)),E=i.transformTo("string",r.utf8encode(b.name)),D=b.comment,H=i.transformTo("string",m(D)),C=i.transformTo("string",r.utf8encode(D)),A=E.length!==b.name.length,S=C.length!==D.length,_="",J="",U="",z=b.dir,W=b.date,Q={crc32:0,compressedSize:0,uncompressedSize:0};p&&!u||(Q.crc32=c.crc32,Q.compressedSize=c.compressedSize,Q.uncompressedSize=c.uncompressedSize);var L=0;p&&(L|=8),T||!A&&!S||(L|=2048);var P=0,X=0;z&&(P|=16),f==="UNIX"?(X=798,P|=function(Y,ct){var pt=Y;return Y||(pt=ct?16893:33204),(65535&pt)<<16}(b.unixPermissions,z)):(X=20,P|=function(Y){return 63&(Y||0)}(b.dosPermissions)),v=W.getUTCHours(),v<<=6,v|=W.getUTCMinutes(),v<<=5,v|=W.getUTCSeconds()/2,y=W.getUTCFullYear()-1980,y<<=4,y|=W.getUTCMonth()+1,y<<=5,y|=W.getUTCDate(),A&&(J=e(1,1)+e(a(I),4)+E,_+="up"+e(J.length,2)+J),S&&(U=e(1,1)+e(a(H),4)+C,_+="uc"+e(U.length,2)+U);var q="";return q+=` +\0`,q+=e(L,2),q+=k.magic,q+=e(v,2),q+=e(y,2),q+=e(Q.crc32,4),q+=e(Q.compressedSize,4),q+=e(Q.uncompressedSize,4),q+=e(I.length,2),q+=e(_.length,2),{fileRecord:o.LOCAL_FILE_HEADER+q+I+_,dirRecord:o.CENTRAL_FILE_HEADER+e(X,2)+q+e(H.length,2)+"\0\0\0\0"+e(P,4)+e(h,4)+I+_+H}}var i=g("../utils"),n=g("../stream/GenericWorker"),r=g("../utf8"),a=g("../crc32"),o=g("../signature");function l(c,p,u,h){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=p,this.zipPlatform=u,this.encodeFileName=h,this.streamFiles=c,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}i.inherits(l,n),l.prototype.push=function(c){var p=c.meta.percent||0,u=this.entriesCount,h=this._sources.length;this.accumulate?this.contentBuffer.push(c):(this.bytesWritten+=c.data.length,n.prototype.push.call(this,{data:c.data,meta:{currentFile:this.currentFile,percent:u?(p+100*(u-h-1))/u:100}}))},l.prototype.openedSource=function(c){this.currentSourceOffset=this.bytesWritten,this.currentFile=c.file.name;var p=this.streamFiles&&!c.file.dir;if(p){var u=s(c,p,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:u.fileRecord,meta:{percent:0}})}else this.accumulate=!0},l.prototype.closedSource=function(c){this.accumulate=!1;var p=this.streamFiles&&!c.file.dir,u=s(c,p,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(u.dirRecord),p)this.push({data:function(h){return o.DATA_DESCRIPTOR+e(h.crc32,4)+e(h.compressedSize,4)+e(h.uncompressedSize,4)}(c),meta:{percent:100}});else for(this.push({data:u.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},l.prototype.flush=function(){for(var c=this.bytesWritten,p=0;p<this.dirRecords.length;p++)this.push({data:this.dirRecords[p],meta:{percent:100}});var u=this.bytesWritten-c,h=function(f,m,v,y,b){var k=i.transformTo("string",b(y));return o.CENTRAL_DIRECTORY_END+"\0\0\0\0"+e(f,2)+e(f,2)+e(m,4)+e(v,4)+e(k.length,2)+k}(this.dirRecords.length,u,c,this.zipComment,this.encodeFileName);this.push({data:h,meta:{percent:100}})},l.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},l.prototype.registerPrevious=function(c){this._sources.push(c);var p=this;return c.on("data",function(u){p.processChunk(u)}),c.on("end",function(){p.closedSource(p.previous.streamInfo),p._sources.length?p.prepareNextSource():p.end()}),c.on("error",function(u){p.error(u)}),this},l.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},l.prototype.error=function(c){var p=this._sources;if(!n.prototype.error.call(this,c))return!1;for(var u=0;u<p.length;u++)try{p[u].error(c)}catch{}return!0},l.prototype.lock=function(){n.prototype.lock.call(this);for(var c=this._sources,p=0;p<c.length;p++)c[p].lock()},d.exports=l},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(g,d,t){"use strict";var e=g("../compressions"),s=g("./ZipFileWorker");t.generateWorker=function(i,n,r){var a=new s(n.streamFiles,r,n.platform,n.encodeFileName),o=0;try{i.forEach(function(l,c){o++;var p=function(m,v){var y=m||v,b=e[y];if(!b)throw new Error(y+" is not a valid compression method !");return b}(c.options.compression,n.compression),u=c.options.compressionOptions||n.compressionOptions||{},h=c.dir,f=c.date;c._compressWorker(p,u).withStreamInfo("file",{name:l,dir:h,date:f,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(a)}),a.entriesCount=o}catch(l){a.error(l)}return a}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(g,d,t){"use strict";function e(){if(!(this instanceof e))return new e;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var s=new e;for(var i in this)typeof this[i]!="function"&&(s[i]=this[i]);return s}}(e.prototype=g("./object")).loadAsync=g("./load"),e.support=g("./support"),e.defaults=g("./defaults"),e.version="3.10.1",e.loadAsync=function(s,i){return new e().loadAsync(s,i)},e.external=g("./external"),d.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(g,d,t){"use strict";var e=g("./utils"),s=g("./external"),i=g("./utf8"),n=g("./zipEntries"),r=g("./stream/Crc32Probe"),a=g("./nodejsUtils");function o(l){return new s.Promise(function(c,p){var u=l.decompressed.getContentWorker().pipe(new r);u.on("error",function(h){p(h)}).on("end",function(){u.streamInfo.crc32!==l.decompressed.crc32?p(new Error("Corrupted zip : CRC32 mismatch")):c()}).resume()})}d.exports=function(l,c){var p=this;return c=e.extend(c||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:i.utf8decode}),a.isNode&&a.isStream(l)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):e.prepareContent("the loaded zip file",l,!0,c.optimizedBinaryString,c.base64).then(function(u){var h=new n(c);return h.load(u),h}).then(function(u){var h=[s.Promise.resolve(u)],f=u.files;if(c.checkCRC32)for(var m=0;m<f.length;m++)h.push(o(f[m]));return s.Promise.all(h)}).then(function(u){for(var h=u.shift(),f=h.files,m=0;m<f.length;m++){var v=f[m],y=v.fileNameStr,b=e.resolve(v.fileNameStr);p.file(b,v.decompressed,{binary:!0,optimizedBinaryString:!0,date:v.date,dir:v.dir,comment:v.fileCommentStr.length?v.fileCommentStr:null,unixPermissions:v.unixPermissions,dosPermissions:v.dosPermissions,createFolders:c.createFolders}),v.dir||(p.file(b).unsafeOriginalName=y)}return h.zipComment.length&&(p.comment=h.zipComment),p})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(g,d,t){"use strict";var e=g("../utils"),s=g("../stream/GenericWorker");function i(n,r){s.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(r)}e.inherits(i,s),i.prototype._bindStream=function(n){var r=this;(this._stream=n).pause(),n.on("data",function(a){r.push({data:a,meta:{percent:0}})}).on("error",function(a){r.isPaused?this.generatedError=a:r.error(a)}).on("end",function(){r.isPaused?r._upstreamEnded=!0:r.end()})},i.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},i.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},d.exports=i},{"../stream/GenericWorker":28,"../utils":32}],13:[function(g,d,t){"use strict";var e=g("readable-stream").Readable;function s(i,n,r){e.call(this,n),this._helper=i;var a=this;i.on("data",function(o,l){a.push(o)||a._helper.pause(),r&&r(l)}).on("error",function(o){a.emit("error",o)}).on("end",function(){a.push(null)})}g("../utils").inherits(s,e),s.prototype._read=function(){this._helper.resume()},d.exports=s},{"../utils":32,"readable-stream":16}],14:[function(g,d,t){"use strict";d.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,s){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,s);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,s)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var s=new Buffer(e);return s.fill(0),s},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}}},{}],15:[function(g,d,t){"use strict";function e(b,k,T){var I,E=i.getTypeOf(k),D=i.extend(T||{},a);D.date=D.date||new Date,D.compression!==null&&(D.compression=D.compression.toUpperCase()),typeof D.unixPermissions=="string"&&(D.unixPermissions=parseInt(D.unixPermissions,8)),D.unixPermissions&&16384&D.unixPermissions&&(D.dir=!0),D.dosPermissions&&16&D.dosPermissions&&(D.dir=!0),D.dir&&(b=f(b)),D.createFolders&&(I=h(b))&&m.call(this,I,!0);var H=E==="string"&&D.binary===!1&&D.base64===!1;T&&T.binary!==void 0||(D.binary=!H),(k instanceof o&&k.uncompressedSize===0||D.dir||!k||k.length===0)&&(D.base64=!1,D.binary=!0,k="",D.compression="STORE",E="string");var C=null;C=k instanceof o||k instanceof n?k:p.isNode&&p.isStream(k)?new u(b,k):i.prepareContent(b,k,D.binary,D.optimizedBinaryString,D.base64);var A=new l(b,C,D);this.files[b]=A}var s=g("./utf8"),i=g("./utils"),n=g("./stream/GenericWorker"),r=g("./stream/StreamHelper"),a=g("./defaults"),o=g("./compressedObject"),l=g("./zipObject"),c=g("./generate"),p=g("./nodejsUtils"),u=g("./nodejs/NodejsStreamInputAdapter"),h=function(b){b.slice(-1)==="/"&&(b=b.substring(0,b.length-1));var k=b.lastIndexOf("/");return 0<k?b.substring(0,k):""},f=function(b){return b.slice(-1)!=="/"&&(b+="/"),b},m=function(b,k){return k=k!==void 0?k:a.createFolders,b=f(b),this.files[b]||e.call(this,b,null,{dir:!0,createFolders:k}),this.files[b]};function v(b){return Object.prototype.toString.call(b)==="[object RegExp]"}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(b){var k,T,I;for(k in this.files)I=this.files[k],(T=k.slice(this.root.length,k.length))&&k.slice(0,this.root.length)===this.root&&b(T,I)},filter:function(b){var k=[];return this.forEach(function(T,I){b(T,I)&&k.push(I)}),k},file:function(b,k,T){if(arguments.length!==1)return b=this.root+b,e.call(this,b,k,T),this;if(v(b)){var I=b;return this.filter(function(D,H){return!H.dir&&I.test(D)})}var E=this.files[this.root+b];return E&&!E.dir?E:null},folder:function(b){if(!b)return this;if(v(b))return this.filter(function(E,D){return D.dir&&b.test(E)});var k=this.root+b,T=m.call(this,k),I=this.clone();return I.root=T.name,I},remove:function(b){b=this.root+b;var k=this.files[b];if(k||(b.slice(-1)!=="/"&&(b+="/"),k=this.files[b]),k&&!k.dir)delete this.files[b];else for(var T=this.filter(function(E,D){return D.name.slice(0,b.length)===b}),I=0;I<T.length;I++)delete this.files[T[I].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(b){var k,T={};try{if((T=i.extend(b||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=T.type.toLowerCase(),T.compression=T.compression.toUpperCase(),T.type==="binarystring"&&(T.type="string"),!T.type)throw new Error("No output type specified.");i.checkSupport(T.type),T.platform!=="darwin"&&T.platform!=="freebsd"&&T.platform!=="linux"&&T.platform!=="sunos"||(T.platform="UNIX"),T.platform==="win32"&&(T.platform="DOS");var I=T.comment||this.comment||"";k=c.generateWorker(this,T,I)}catch(E){(k=new n("error")).error(E)}return new r(k,T.type||"string",T.mimeType)},generateAsync:function(b,k){return this.generateInternalStream(b).accumulate(k)},generateNodeStream:function(b,k){return(b=b||{}).type||(b.type="nodebuffer"),this.generateInternalStream(b).toNodejsStream(k)}};d.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(g,d,t){"use strict";d.exports=g("stream")},{stream:void 0}],17:[function(g,d,t){"use strict";var e=g("./DataReader");function s(i){e.call(this,i);for(var n=0;n<this.data.length;n++)i[n]=255&i[n]}g("../utils").inherits(s,e),s.prototype.byteAt=function(i){return this.data[this.zero+i]},s.prototype.lastIndexOfSignature=function(i){for(var n=i.charCodeAt(0),r=i.charCodeAt(1),a=i.charCodeAt(2),o=i.charCodeAt(3),l=this.length-4;0<=l;--l)if(this.data[l]===n&&this.data[l+1]===r&&this.data[l+2]===a&&this.data[l+3]===o)return l-this.zero;return-1},s.prototype.readAndCheckSignature=function(i){var n=i.charCodeAt(0),r=i.charCodeAt(1),a=i.charCodeAt(2),o=i.charCodeAt(3),l=this.readData(4);return n===l[0]&&r===l[1]&&a===l[2]&&o===l[3]},s.prototype.readData=function(i){if(this.checkOffset(i),i===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,n},d.exports=s},{"../utils":32,"./DataReader":18}],18:[function(g,d,t){"use strict";var e=g("../utils");function s(i){this.data=i,this.length=i.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(i){this.checkIndex(this.index+i)},checkIndex:function(i){if(this.length<this.zero+i||i<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+i+"). Corrupted zip ?")},setIndex:function(i){this.checkIndex(i),this.index=i},skip:function(i){this.setIndex(this.index+i)},byteAt:function(){},readInt:function(i){var n,r=0;for(this.checkOffset(i),n=this.index+i-1;n>=this.index;n--)r=(r<<8)+this.byteAt(n);return this.index+=i,r},readString:function(i){return e.transformTo("string",this.readData(i))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var i=this.readInt(4);return new Date(Date.UTC(1980+(i>>25&127),(i>>21&15)-1,i>>16&31,i>>11&31,i>>5&63,(31&i)<<1))}},d.exports=s},{"../utils":32}],19:[function(g,d,t){"use strict";var e=g("./Uint8ArrayReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.readData=function(i){this.checkOffset(i);var n=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,n},d.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(g,d,t){"use strict";var e=g("./DataReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.byteAt=function(i){return this.data.charCodeAt(this.zero+i)},s.prototype.lastIndexOfSignature=function(i){return this.data.lastIndexOf(i)-this.zero},s.prototype.readAndCheckSignature=function(i){return i===this.readData(4)},s.prototype.readData=function(i){this.checkOffset(i);var n=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,n},d.exports=s},{"../utils":32,"./DataReader":18}],21:[function(g,d,t){"use strict";var e=g("./ArrayReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.readData=function(i){if(this.checkOffset(i),i===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+i);return this.index+=i,n},d.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(g,d,t){"use strict";var e=g("../utils"),s=g("../support"),i=g("./ArrayReader"),n=g("./StringReader"),r=g("./NodeBufferReader"),a=g("./Uint8ArrayReader");d.exports=function(o){var l=e.getTypeOf(o);return e.checkSupport(l),l!=="string"||s.uint8array?l==="nodebuffer"?new r(o):s.uint8array?new a(e.transformTo("uint8array",o)):new i(e.transformTo("array",o)):new n(o)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(g,d,t){"use strict";t.LOCAL_FILE_HEADER="PK",t.CENTRAL_FILE_HEADER="PK",t.CENTRAL_DIRECTORY_END="PK",t.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",t.ZIP64_CENTRAL_DIRECTORY_END="PK",t.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(g,d,t){"use strict";var e=g("./GenericWorker"),s=g("../utils");function i(n){e.call(this,"ConvertWorker to "+n),this.destType=n}s.inherits(i,e),i.prototype.processChunk=function(n){this.push({data:s.transformTo(this.destType,n.data),meta:n.meta})},d.exports=i},{"../utils":32,"./GenericWorker":28}],25:[function(g,d,t){"use strict";var e=g("./GenericWorker"),s=g("../crc32");function i(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}g("../utils").inherits(i,e),i.prototype.processChunk=function(n){this.streamInfo.crc32=s(n.data,this.streamInfo.crc32||0),this.push(n)},d.exports=i},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(g,d,t){"use strict";var e=g("../utils"),s=g("./GenericWorker");function i(n){s.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}e.inherits(i,s),i.prototype.processChunk=function(n){if(n){var r=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=r+n.data.length}s.prototype.processChunk.call(this,n)},d.exports=i},{"../utils":32,"./GenericWorker":28}],27:[function(g,d,t){"use strict";var e=g("../utils"),s=g("./GenericWorker");function i(n){s.call(this,"DataWorker");var r=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(a){r.dataIsReady=!0,r.data=a,r.max=a&&a.length||0,r.type=e.getTypeOf(a),r.isPaused||r._tickAndRepeat()},function(a){r.error(a)})}e.inherits(i,s),i.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},i.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},i.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},i.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,r=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":n=this.data.substring(this.index,r);break;case"uint8array":n=this.data.subarray(this.index,r);break;case"array":case"nodebuffer":n=this.data.slice(this.index,r)}return this.index=r,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},d.exports=i},{"../utils":32,"./GenericWorker":28}],28:[function(g,d,t){"use strict";function e(s){this.name=s||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}e.prototype={push:function(s){this.emit("data",s)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(s){this.emit("error",s)}return!0},error:function(s){return!this.isFinished&&(this.isPaused?this.generatedError=s:(this.isFinished=!0,this.emit("error",s),this.previous&&this.previous.error(s),this.cleanUp()),!0)},on:function(s,i){return this._listeners[s].push(i),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(s,i){if(this._listeners[s])for(var n=0;n<this._listeners[s].length;n++)this._listeners[s][n].call(this,i)},pipe:function(s){return s.registerPrevious(this)},registerPrevious:function(s){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=s.streamInfo,this.mergeStreamInfo(),this.previous=s;var i=this;return s.on("data",function(n){i.processChunk(n)}),s.on("end",function(){i.end()}),s.on("error",function(n){i.error(n)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var s=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),s=!0),this.previous&&this.previous.resume(),!s},flush:function(){},processChunk:function(s){this.push(s)},withStreamInfo:function(s,i){return this.extraStreamInfo[s]=i,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var s in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,s)&&(this.streamInfo[s]=this.extraStreamInfo[s])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var s="Worker "+this.name;return this.previous?this.previous+" -> "+s:s}},d.exports=e},{}],29:[function(g,d,t){"use strict";var e=g("../utils"),s=g("./ConvertWorker"),i=g("./GenericWorker"),n=g("../base64"),r=g("../support"),a=g("../external"),o=null;if(r.nodestream)try{o=g("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(p,u){return new a.Promise(function(h,f){var m=[],v=p._internalType,y=p._outputType,b=p._mimeType;p.on("data",function(k,T){m.push(k),u&&u(T)}).on("error",function(k){m=[],f(k)}).on("end",function(){try{var k=function(T,I,E){switch(T){case"blob":return e.newBlob(e.transformTo("arraybuffer",I),E);case"base64":return n.encode(I);default:return e.transformTo(T,I)}}(y,function(T,I){var E,D=0,H=null,C=0;for(E=0;E<I.length;E++)C+=I[E].length;switch(T){case"string":return I.join("");case"array":return Array.prototype.concat.apply([],I);case"uint8array":for(H=new Uint8Array(C),E=0;E<I.length;E++)H.set(I[E],D),D+=I[E].length;return H;case"nodebuffer":return Buffer.concat(I);default:throw new Error("concat : unsupported type '"+T+"'")}}(v,m),b);h(k)}catch(T){f(T)}m=[]}).resume()})}function c(p,u,h){var f=u;switch(u){case"blob":case"arraybuffer":f="uint8array";break;case"base64":f="string"}try{this._internalType=f,this._outputType=u,this._mimeType=h,e.checkSupport(f),this._worker=p.pipe(new s(f)),p.lock()}catch(m){this._worker=new i("error"),this._worker.error(m)}}c.prototype={accumulate:function(p){return l(this,p)},on:function(p,u){var h=this;return p==="data"?this._worker.on(p,function(f){u.call(h,f.data,f.meta)}):this._worker.on(p,function(){e.delay(u,arguments,h)}),this},resume:function(){return e.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(p){if(e.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new o(this,{objectMode:this._outputType!=="nodebuffer"},p)}},d.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(g,d,t){"use strict";if(t.base64=!0,t.array=!0,t.string=!0,t.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",t.nodebuffer=typeof Buffer<"u",t.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")t.blob=!1;else{var e=new ArrayBuffer(0);try{t.blob=new Blob([e],{type:"application/zip"}).size===0}catch{try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(e),t.blob=s.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!g("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(g,d,t){"use strict";for(var e=g("./utils"),s=g("./support"),i=g("./nodejsUtils"),n=g("./stream/GenericWorker"),r=new Array(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;r[254]=r[254]=1;function o(){n.call(this,"utf-8 decode"),this.leftOver=null}function l(){n.call(this,"utf-8 encode")}t.utf8encode=function(c){return s.nodebuffer?i.newBufferFrom(c,"utf-8"):function(p){var u,h,f,m,v,y=p.length,b=0;for(m=0;m<y;m++)(64512&(h=p.charCodeAt(m)))==55296&&m+1<y&&(64512&(f=p.charCodeAt(m+1)))==56320&&(h=65536+(h-55296<<10)+(f-56320),m++),b+=h<128?1:h<2048?2:h<65536?3:4;for(u=s.uint8array?new Uint8Array(b):new Array(b),m=v=0;v<b;m++)(64512&(h=p.charCodeAt(m)))==55296&&m+1<y&&(64512&(f=p.charCodeAt(m+1)))==56320&&(h=65536+(h-55296<<10)+(f-56320),m++),h<128?u[v++]=h:(h<2048?u[v++]=192|h>>>6:(h<65536?u[v++]=224|h>>>12:(u[v++]=240|h>>>18,u[v++]=128|h>>>12&63),u[v++]=128|h>>>6&63),u[v++]=128|63&h);return u}(c)},t.utf8decode=function(c){return s.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(p){var u,h,f,m,v=p.length,y=new Array(2*v);for(u=h=0;u<v;)if((f=p[u++])<128)y[h++]=f;else if(4<(m=r[f]))y[h++]=65533,u+=m-1;else{for(f&=m===2?31:m===3?15:7;1<m&&u<v;)f=f<<6|63&p[u++],m--;1<m?y[h++]=65533:f<65536?y[h++]=f:(f-=65536,y[h++]=55296|f>>10&1023,y[h++]=56320|1023&f)}return y.length!==h&&(y.subarray?y=y.subarray(0,h):y.length=h),e.applyFromCharCode(y)}(c=e.transformTo(s.uint8array?"uint8array":"array",c))},e.inherits(o,n),o.prototype.processChunk=function(c){var p=e.transformTo(s.uint8array?"uint8array":"array",c.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var u=p;(p=new Uint8Array(u.length+this.leftOver.length)).set(this.leftOver,0),p.set(u,this.leftOver.length)}else p=this.leftOver.concat(p);this.leftOver=null}var h=function(m,v){var y;for((v=v||m.length)>m.length&&(v=m.length),y=v-1;0<=y&&(192&m[y])==128;)y--;return y<0||y===0?v:y+r[m[y]]>v?y:v}(p),f=p;h!==p.length&&(s.uint8array?(f=p.subarray(0,h),this.leftOver=p.subarray(h,p.length)):(f=p.slice(0,h),this.leftOver=p.slice(h,p.length))),this.push({data:t.utf8decode(f),meta:c.meta})},o.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=o,e.inherits(l,n),l.prototype.processChunk=function(c){this.push({data:t.utf8encode(c.data),meta:c.meta})},t.Utf8EncodeWorker=l},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(g,d,t){"use strict";var e=g("./support"),s=g("./base64"),i=g("./nodejsUtils"),n=g("./external");function r(u){return u}function a(u,h){for(var f=0;f<u.length;++f)h[f]=255&u.charCodeAt(f);return h}g("setimmediate"),t.newBlob=function(u,h){t.checkSupport("blob");try{return new Blob([u],{type:h})}catch{try{var f=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return f.append(u),f.getBlob(h)}catch{throw new Error("Bug : can't construct the Blob.")}}};var o={stringifyByChunk:function(u,h,f){var m=[],v=0,y=u.length;if(y<=f)return String.fromCharCode.apply(null,u);for(;v<y;)h==="array"||h==="nodebuffer"?m.push(String.fromCharCode.apply(null,u.slice(v,Math.min(v+f,y)))):m.push(String.fromCharCode.apply(null,u.subarray(v,Math.min(v+f,y)))),v+=f;return m.join("")},stringifyByChar:function(u){for(var h="",f=0;f<u.length;f++)h+=String.fromCharCode(u[f]);return h},applyCanBeUsed:{uint8array:function(){try{return e.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}}(),nodebuffer:function(){try{return e.nodebuffer&&String.fromCharCode.apply(null,i.allocBuffer(1)).length===1}catch{return!1}}()}};function l(u){var h=65536,f=t.getTypeOf(u),m=!0;if(f==="uint8array"?m=o.applyCanBeUsed.uint8array:f==="nodebuffer"&&(m=o.applyCanBeUsed.nodebuffer),m)for(;1<h;)try{return o.stringifyByChunk(u,f,h)}catch{h=Math.floor(h/2)}return o.stringifyByChar(u)}function c(u,h){for(var f=0;f<u.length;f++)h[f]=u[f];return h}t.applyFromCharCode=l;var p={};p.string={string:r,array:function(u){return a(u,new Array(u.length))},arraybuffer:function(u){return p.string.uint8array(u).buffer},uint8array:function(u){return a(u,new Uint8Array(u.length))},nodebuffer:function(u){return a(u,i.allocBuffer(u.length))}},p.array={string:l,array:r,arraybuffer:function(u){return new Uint8Array(u).buffer},uint8array:function(u){return new Uint8Array(u)},nodebuffer:function(u){return i.newBufferFrom(u)}},p.arraybuffer={string:function(u){return l(new Uint8Array(u))},array:function(u){return c(new Uint8Array(u),new Array(u.byteLength))},arraybuffer:r,uint8array:function(u){return new Uint8Array(u)},nodebuffer:function(u){return i.newBufferFrom(new Uint8Array(u))}},p.uint8array={string:l,array:function(u){return c(u,new Array(u.length))},arraybuffer:function(u){return u.buffer},uint8array:r,nodebuffer:function(u){return i.newBufferFrom(u)}},p.nodebuffer={string:l,array:function(u){return c(u,new Array(u.length))},arraybuffer:function(u){return p.nodebuffer.uint8array(u).buffer},uint8array:function(u){return c(u,new Uint8Array(u.length))},nodebuffer:r},t.transformTo=function(u,h){if(h=h||"",!u)return h;t.checkSupport(u);var f=t.getTypeOf(h);return p[f][u](h)},t.resolve=function(u){for(var h=u.split("/"),f=[],m=0;m<h.length;m++){var v=h[m];v==="."||v===""&&m!==0&&m!==h.length-1||(v===".."?f.pop():f.push(v))}return f.join("/")},t.getTypeOf=function(u){return typeof u=="string"?"string":Object.prototype.toString.call(u)==="[object Array]"?"array":e.nodebuffer&&i.isBuffer(u)?"nodebuffer":e.uint8array&&u instanceof Uint8Array?"uint8array":e.arraybuffer&&u instanceof ArrayBuffer?"arraybuffer":void 0},t.checkSupport=function(u){if(!e[u.toLowerCase()])throw new Error(u+" is not supported by this platform")},t.MAX_VALUE_16BITS=65535,t.MAX_VALUE_32BITS=-1,t.pretty=function(u){var h,f,m="";for(f=0;f<(u||"").length;f++)m+="\\x"+((h=u.charCodeAt(f))<16?"0":"")+h.toString(16).toUpperCase();return m},t.delay=function(u,h,f){setImmediate(function(){u.apply(f||null,h||[])})},t.inherits=function(u,h){function f(){}f.prototype=h.prototype,u.prototype=new f},t.extend=function(){var u,h,f={};for(u=0;u<arguments.length;u++)for(h in arguments[u])Object.prototype.hasOwnProperty.call(arguments[u],h)&&f[h]===void 0&&(f[h]=arguments[u][h]);return f},t.prepareContent=function(u,h,f,m,v){return n.Promise.resolve(h).then(function(y){return e.blob&&(y instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(y))!==-1)&&typeof FileReader<"u"?new n.Promise(function(b,k){var T=new FileReader;T.onload=function(I){b(I.target.result)},T.onerror=function(I){k(I.target.error)},T.readAsArrayBuffer(y)}):y}).then(function(y){var b=t.getTypeOf(y);return b?(b==="arraybuffer"?y=t.transformTo("uint8array",y):b==="string"&&(v?y=s.decode(y):f&&m!==!0&&(y=function(k){return a(k,e.uint8array?new Uint8Array(k.length):new Array(k.length))}(y))),y):n.Promise.reject(new Error("Can't read the data of '"+u+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(g,d,t){"use strict";var e=g("./reader/readerFor"),s=g("./utils"),i=g("./signature"),n=g("./zipEntry"),r=g("./support");function a(o){this.files=[],this.loadOptions=o}a.prototype={checkSignature:function(o){if(!this.reader.readAndCheckSignature(o)){this.reader.index-=4;var l=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(l)+", expected "+s.pretty(o)+")")}},isSignature:function(o,l){var c=this.reader.index;this.reader.setIndex(o);var p=this.reader.readString(4)===l;return this.reader.setIndex(c),p},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var o=this.reader.readData(this.zipCommentLength),l=r.uint8array?"uint8array":"array",c=s.transformTo(l,o);this.zipComment=this.loadOptions.decodeFileName(c)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var o,l,c,p=this.zip64EndOfCentralSize-44;0<p;)o=this.reader.readInt(2),l=this.reader.readInt(4),c=this.reader.readData(l),this.zip64ExtensibleData[o]={id:o,length:l,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var o,l;for(o=0;o<this.files.length;o++)l=this.files[o],this.reader.setIndex(l.localHeaderOffset),this.checkSignature(i.LOCAL_FILE_HEADER),l.readLocalPart(this.reader),l.handleUTF8(),l.processAttributes()},readCentralDir:function(){var o;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(i.CENTRAL_FILE_HEADER);)(o=new n({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(o);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var o=this.reader.lastIndexOfSignature(i.CENTRAL_DIRECTORY_END);if(o<0)throw this.isSignature(0,i.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(o);var l=o;if(this.checkSignature(i.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(o=this.reader.lastIndexOfSignature(i.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(o),this.checkSignature(i.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,i.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(i.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(i.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var c=this.centralDirOffset+this.centralDirSize;this.zip64&&(c+=20,c+=12+this.zip64EndOfCentralSize);var p=l-c;if(0<p)this.isSignature(l,i.CENTRAL_FILE_HEADER)||(this.reader.zero=p);else if(p<0)throw new Error("Corrupted zip: missing "+Math.abs(p)+" bytes.")},prepareReader:function(o){this.reader=e(o)},load:function(o){this.prepareReader(o),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},d.exports=a},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(g,d,t){"use strict";var e=g("./reader/readerFor"),s=g("./utils"),i=g("./compressedObject"),n=g("./crc32"),r=g("./utf8"),a=g("./compressions"),o=g("./support");function l(c,p){this.options=c,this.loadOptions=p}l.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(c){var p,u;if(c.skip(22),this.fileNameLength=c.readInt(2),u=c.readInt(2),this.fileName=c.readData(this.fileNameLength),c.skip(u),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((p=function(h){for(var f in a)if(Object.prototype.hasOwnProperty.call(a,f)&&a[f].magic===h)return a[f];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new i(this.compressedSize,this.uncompressedSize,this.crc32,p,c.readData(this.compressedSize))},readCentralPart:function(c){this.versionMadeBy=c.readInt(2),c.skip(2),this.bitFlag=c.readInt(2),this.compressionMethod=c.readString(2),this.date=c.readDate(),this.crc32=c.readInt(4),this.compressedSize=c.readInt(4),this.uncompressedSize=c.readInt(4);var p=c.readInt(2);if(this.extraFieldsLength=c.readInt(2),this.fileCommentLength=c.readInt(2),this.diskNumberStart=c.readInt(2),this.internalFileAttributes=c.readInt(2),this.externalFileAttributes=c.readInt(4),this.localHeaderOffset=c.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");c.skip(p),this.readExtraFields(c),this.parseZIP64ExtraField(c),this.fileComment=c.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var c=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),c==0&&(this.dosPermissions=63&this.externalFileAttributes),c==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var c=e(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=c.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=c.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=c.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=c.readInt(4))}},readExtraFields:function(c){var p,u,h,f=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<f;)p=c.readInt(2),u=c.readInt(2),h=c.readData(u),this.extraFields[p]={id:p,length:u,value:h};c.setIndex(f)},handleUTF8:function(){var c=o.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=r.utf8decode(this.fileName),this.fileCommentStr=r.utf8decode(this.fileComment);else{var p=this.findExtraFieldUnicodePath();if(p!==null)this.fileNameStr=p;else{var u=s.transformTo(c,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(u)}var h=this.findExtraFieldUnicodeComment();if(h!==null)this.fileCommentStr=h;else{var f=s.transformTo(c,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(f)}}},findExtraFieldUnicodePath:function(){var c=this.extraFields[28789];if(c){var p=e(c.value);return p.readInt(1)!==1||n(this.fileName)!==p.readInt(4)?null:r.utf8decode(p.readData(c.length-5))}return null},findExtraFieldUnicodeComment:function(){var c=this.extraFields[25461];if(c){var p=e(c.value);return p.readInt(1)!==1||n(this.fileComment)!==p.readInt(4)?null:r.utf8decode(p.readData(c.length-5))}return null}},d.exports=l},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(g,d,t){"use strict";function e(p,u,h){this.name=p,this.dir=h.dir,this.date=h.date,this.comment=h.comment,this.unixPermissions=h.unixPermissions,this.dosPermissions=h.dosPermissions,this._data=u,this._dataBinary=h.binary,this.options={compression:h.compression,compressionOptions:h.compressionOptions}}var s=g("./stream/StreamHelper"),i=g("./stream/DataWorker"),n=g("./utf8"),r=g("./compressedObject"),a=g("./stream/GenericWorker");e.prototype={internalStream:function(p){var u=null,h="string";try{if(!p)throw new Error("No output type specified.");var f=(h=p.toLowerCase())==="string"||h==="text";h!=="binarystring"&&h!=="text"||(h="string"),u=this._decompressWorker();var m=!this._dataBinary;m&&!f&&(u=u.pipe(new n.Utf8EncodeWorker)),!m&&f&&(u=u.pipe(new n.Utf8DecodeWorker))}catch(v){(u=new a("error")).error(v)}return new s(u,h,"")},async:function(p,u){return this.internalStream(p).accumulate(u)},nodeStream:function(p,u){return this.internalStream(p||"nodebuffer").toNodejsStream(u)},_compressWorker:function(p,u){if(this._data instanceof r&&this._data.compression.magic===p.magic)return this._data.getCompressedWorker();var h=this._decompressWorker();return this._dataBinary||(h=h.pipe(new n.Utf8EncodeWorker)),r.createWorkerFrom(h,p,u)},_decompressWorker:function(){return this._data instanceof r?this._data.getContentWorker():this._data instanceof a?this._data:new i(this._data)}};for(var o=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],l=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},c=0;c<o.length;c++)e.prototype[o[c]]=l;d.exports=e},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(g,d,t){(function(e){"use strict";var s,i,n=e.MutationObserver||e.WebKitMutationObserver;if(n){var r=0,a=new n(p),o=e.document.createTextNode("");a.observe(o,{characterData:!0}),s=function(){o.data=r=++r%2}}else if(e.setImmediate||e.MessageChannel===void 0)s="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var u=e.document.createElement("script");u.onreadystatechange=function(){p(),u.onreadystatechange=null,u.parentNode.removeChild(u),u=null},e.document.documentElement.appendChild(u)}:function(){setTimeout(p,0)};else{var l=new e.MessageChannel;l.port1.onmessage=p,s=function(){l.port2.postMessage(0)}}var c=[];function p(){var u,h;i=!0;for(var f=c.length;f;){for(h=c,c=[],u=-1;++u<f;)h[u]();f=c.length}i=!1}d.exports=function(u){c.push(u)!==1||i||s()}}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(g,d,t){"use strict";var e=g("immediate");function s(){}var i={},n=["REJECTED"],r=["FULFILLED"],a=["PENDING"];function o(f){if(typeof f!="function")throw new TypeError("resolver must be a function");this.state=a,this.queue=[],this.outcome=void 0,f!==s&&u(this,f)}function l(f,m,v){this.promise=f,typeof m=="function"&&(this.onFulfilled=m,this.callFulfilled=this.otherCallFulfilled),typeof v=="function"&&(this.onRejected=v,this.callRejected=this.otherCallRejected)}function c(f,m,v){e(function(){var y;try{y=m(v)}catch(b){return i.reject(f,b)}y===f?i.reject(f,new TypeError("Cannot resolve promise with itself")):i.resolve(f,y)})}function p(f){var m=f&&f.then;if(f&&(typeof f=="object"||typeof f=="function")&&typeof m=="function")return function(){m.apply(f,arguments)}}function u(f,m){var v=!1;function y(T){v||(v=!0,i.reject(f,T))}function b(T){v||(v=!0,i.resolve(f,T))}var k=h(function(){m(b,y)});k.status==="error"&&y(k.value)}function h(f,m){var v={};try{v.value=f(m),v.status="success"}catch(y){v.status="error",v.value=y}return v}(d.exports=o).prototype.finally=function(f){if(typeof f!="function")return this;var m=this.constructor;return this.then(function(v){return m.resolve(f()).then(function(){return v})},function(v){return m.resolve(f()).then(function(){throw v})})},o.prototype.catch=function(f){return this.then(null,f)},o.prototype.then=function(f,m){if(typeof f!="function"&&this.state===r||typeof m!="function"&&this.state===n)return this;var v=new this.constructor(s);return this.state!==a?c(v,this.state===r?f:m,this.outcome):this.queue.push(new l(v,f,m)),v},l.prototype.callFulfilled=function(f){i.resolve(this.promise,f)},l.prototype.otherCallFulfilled=function(f){c(this.promise,this.onFulfilled,f)},l.prototype.callRejected=function(f){i.reject(this.promise,f)},l.prototype.otherCallRejected=function(f){c(this.promise,this.onRejected,f)},i.resolve=function(f,m){var v=h(p,m);if(v.status==="error")return i.reject(f,v.value);var y=v.value;if(y)u(f,y);else{f.state=r,f.outcome=m;for(var b=-1,k=f.queue.length;++b<k;)f.queue[b].callFulfilled(m)}return f},i.reject=function(f,m){f.state=n,f.outcome=m;for(var v=-1,y=f.queue.length;++v<y;)f.queue[v].callRejected(m);return f},o.resolve=function(f){return f instanceof this?f:i.resolve(new this(s),f)},o.reject=function(f){var m=new this(s);return i.reject(m,f)},o.all=function(f){var m=this;if(Object.prototype.toString.call(f)!=="[object Array]")return this.reject(new TypeError("must be an array"));var v=f.length,y=!1;if(!v)return this.resolve([]);for(var b=new Array(v),k=0,T=-1,I=new this(s);++T<v;)E(f[T],T);return I;function E(D,H){m.resolve(D).then(function(C){b[H]=C,++k!==v||y||(y=!0,i.resolve(I,b))},function(C){y||(y=!0,i.reject(I,C))})}},o.race=function(f){var m=this;if(Object.prototype.toString.call(f)!=="[object Array]")return this.reject(new TypeError("must be an array"));var v=f.length,y=!1;if(!v)return this.resolve([]);for(var b=-1,k=new this(s);++b<v;)T=f[b],m.resolve(T).then(function(I){y||(y=!0,i.resolve(k,I))},function(I){y||(y=!0,i.reject(k,I))});var T;return k}},{immediate:36}],38:[function(g,d,t){"use strict";var e={};(0,g("./lib/utils/common").assign)(e,g("./lib/deflate"),g("./lib/inflate"),g("./lib/zlib/constants")),d.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(g,d,t){"use strict";var e=g("./zlib/deflate"),s=g("./utils/common"),i=g("./utils/strings"),n=g("./zlib/messages"),r=g("./zlib/zstream"),a=Object.prototype.toString,o=0,l=-1,c=0,p=8;function u(f){if(!(this instanceof u))return new u(f);this.options=s.assign({level:l,method:p,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},f||{});var m=this.options;m.raw&&0<m.windowBits?m.windowBits=-m.windowBits:m.gzip&&0<m.windowBits&&m.windowBits<16&&(m.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new r,this.strm.avail_out=0;var v=e.deflateInit2(this.strm,m.level,m.method,m.windowBits,m.memLevel,m.strategy);if(v!==o)throw new Error(n[v]);if(m.header&&e.deflateSetHeader(this.strm,m.header),m.dictionary){var y;if(y=typeof m.dictionary=="string"?i.string2buf(m.dictionary):a.call(m.dictionary)==="[object ArrayBuffer]"?new Uint8Array(m.dictionary):m.dictionary,(v=e.deflateSetDictionary(this.strm,y))!==o)throw new Error(n[v]);this._dict_set=!0}}function h(f,m){var v=new u(m);if(v.push(f,!0),v.err)throw v.msg||n[v.err];return v.result}u.prototype.push=function(f,m){var v,y,b=this.strm,k=this.options.chunkSize;if(this.ended)return!1;y=m===~~m?m:m===!0?4:0,typeof f=="string"?b.input=i.string2buf(f):a.call(f)==="[object ArrayBuffer]"?b.input=new Uint8Array(f):b.input=f,b.next_in=0,b.avail_in=b.input.length;do{if(b.avail_out===0&&(b.output=new s.Buf8(k),b.next_out=0,b.avail_out=k),(v=e.deflate(b,y))!==1&&v!==o)return this.onEnd(v),!(this.ended=!0);b.avail_out!==0&&(b.avail_in!==0||y!==4&&y!==2)||(this.options.to==="string"?this.onData(i.buf2binstring(s.shrinkBuf(b.output,b.next_out))):this.onData(s.shrinkBuf(b.output,b.next_out)))}while((0<b.avail_in||b.avail_out===0)&&v!==1);return y===4?(v=e.deflateEnd(this.strm),this.onEnd(v),this.ended=!0,v===o):y!==2||(this.onEnd(o),!(b.avail_out=0))},u.prototype.onData=function(f){this.chunks.push(f)},u.prototype.onEnd=function(f){f===o&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=f,this.msg=this.strm.msg},t.Deflate=u,t.deflate=h,t.deflateRaw=function(f,m){return(m=m||{}).raw=!0,h(f,m)},t.gzip=function(f,m){return(m=m||{}).gzip=!0,h(f,m)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(g,d,t){"use strict";var e=g("./zlib/inflate"),s=g("./utils/common"),i=g("./utils/strings"),n=g("./zlib/constants"),r=g("./zlib/messages"),a=g("./zlib/zstream"),o=g("./zlib/gzheader"),l=Object.prototype.toString;function c(u){if(!(this instanceof c))return new c(u);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},u||{});var h=this.options;h.raw&&0<=h.windowBits&&h.windowBits<16&&(h.windowBits=-h.windowBits,h.windowBits===0&&(h.windowBits=-15)),!(0<=h.windowBits&&h.windowBits<16)||u&&u.windowBits||(h.windowBits+=32),15<h.windowBits&&h.windowBits<48&&!(15&h.windowBits)&&(h.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var f=e.inflateInit2(this.strm,h.windowBits);if(f!==n.Z_OK)throw new Error(r[f]);this.header=new o,e.inflateGetHeader(this.strm,this.header)}function p(u,h){var f=new c(h);if(f.push(u,!0),f.err)throw f.msg||r[f.err];return f.result}c.prototype.push=function(u,h){var f,m,v,y,b,k,T=this.strm,I=this.options.chunkSize,E=this.options.dictionary,D=!1;if(this.ended)return!1;m=h===~~h?h:h===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof u=="string"?T.input=i.binstring2buf(u):l.call(u)==="[object ArrayBuffer]"?T.input=new Uint8Array(u):T.input=u,T.next_in=0,T.avail_in=T.input.length;do{if(T.avail_out===0&&(T.output=new s.Buf8(I),T.next_out=0,T.avail_out=I),(f=e.inflate(T,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&E&&(k=typeof E=="string"?i.string2buf(E):l.call(E)==="[object ArrayBuffer]"?new Uint8Array(E):E,f=e.inflateSetDictionary(this.strm,k)),f===n.Z_BUF_ERROR&&D===!0&&(f=n.Z_OK,D=!1),f!==n.Z_STREAM_END&&f!==n.Z_OK)return this.onEnd(f),!(this.ended=!0);T.next_out&&(T.avail_out!==0&&f!==n.Z_STREAM_END&&(T.avail_in!==0||m!==n.Z_FINISH&&m!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(v=i.utf8border(T.output,T.next_out),y=T.next_out-v,b=i.buf2string(T.output,v),T.next_out=y,T.avail_out=I-y,y&&s.arraySet(T.output,T.output,v,y,0),this.onData(b)):this.onData(s.shrinkBuf(T.output,T.next_out)))),T.avail_in===0&&T.avail_out===0&&(D=!0)}while((0<T.avail_in||T.avail_out===0)&&f!==n.Z_STREAM_END);return f===n.Z_STREAM_END&&(m=n.Z_FINISH),m===n.Z_FINISH?(f=e.inflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===n.Z_OK):m!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(T.avail_out=0))},c.prototype.onData=function(u){this.chunks.push(u)},c.prototype.onEnd=function(u){u===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=u,this.msg=this.strm.msg},t.Inflate=c,t.inflate=p,t.inflateRaw=function(u,h){return(h=h||{}).raw=!0,p(u,h)},t.ungzip=p},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(g,d,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";t.assign=function(n){for(var r=Array.prototype.slice.call(arguments,1);r.length;){var a=r.shift();if(a){if(typeof a!="object")throw new TypeError(a+"must be non-object");for(var o in a)a.hasOwnProperty(o)&&(n[o]=a[o])}}return n},t.shrinkBuf=function(n,r){return n.length===r?n:n.subarray?n.subarray(0,r):(n.length=r,n)};var s={arraySet:function(n,r,a,o,l){if(r.subarray&&n.subarray)n.set(r.subarray(a,a+o),l);else for(var c=0;c<o;c++)n[l+c]=r[a+c]},flattenChunks:function(n){var r,a,o,l,c,p;for(r=o=0,a=n.length;r<a;r++)o+=n[r].length;for(p=new Uint8Array(o),r=l=0,a=n.length;r<a;r++)c=n[r],p.set(c,l),l+=c.length;return p}},i={arraySet:function(n,r,a,o,l){for(var c=0;c<o;c++)n[l+c]=r[a+c]},flattenChunks:function(n){return[].concat.apply([],n)}};t.setTyped=function(n){n?(t.Buf8=Uint8Array,t.Buf16=Uint16Array,t.Buf32=Int32Array,t.assign(t,s)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,i))},t.setTyped(e)},{}],42:[function(g,d,t){"use strict";var e=g("./common"),s=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch{s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{i=!1}for(var n=new e.Buf8(256),r=0;r<256;r++)n[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function a(o,l){if(l<65537&&(o.subarray&&i||!o.subarray&&s))return String.fromCharCode.apply(null,e.shrinkBuf(o,l));for(var c="",p=0;p<l;p++)c+=String.fromCharCode(o[p]);return c}n[254]=n[254]=1,t.string2buf=function(o){var l,c,p,u,h,f=o.length,m=0;for(u=0;u<f;u++)(64512&(c=o.charCodeAt(u)))==55296&&u+1<f&&(64512&(p=o.charCodeAt(u+1)))==56320&&(c=65536+(c-55296<<10)+(p-56320),u++),m+=c<128?1:c<2048?2:c<65536?3:4;for(l=new e.Buf8(m),u=h=0;h<m;u++)(64512&(c=o.charCodeAt(u)))==55296&&u+1<f&&(64512&(p=o.charCodeAt(u+1)))==56320&&(c=65536+(c-55296<<10)+(p-56320),u++),c<128?l[h++]=c:(c<2048?l[h++]=192|c>>>6:(c<65536?l[h++]=224|c>>>12:(l[h++]=240|c>>>18,l[h++]=128|c>>>12&63),l[h++]=128|c>>>6&63),l[h++]=128|63&c);return l},t.buf2binstring=function(o){return a(o,o.length)},t.binstring2buf=function(o){for(var l=new e.Buf8(o.length),c=0,p=l.length;c<p;c++)l[c]=o.charCodeAt(c);return l},t.buf2string=function(o,l){var c,p,u,h,f=l||o.length,m=new Array(2*f);for(c=p=0;c<f;)if((u=o[c++])<128)m[p++]=u;else if(4<(h=n[u]))m[p++]=65533,c+=h-1;else{for(u&=h===2?31:h===3?15:7;1<h&&c<f;)u=u<<6|63&o[c++],h--;1<h?m[p++]=65533:u<65536?m[p++]=u:(u-=65536,m[p++]=55296|u>>10&1023,m[p++]=56320|1023&u)}return a(m,p)},t.utf8border=function(o,l){var c;for((l=l||o.length)>o.length&&(l=o.length),c=l-1;0<=c&&(192&o[c])==128;)c--;return c<0||c===0?l:c+n[o[c]]>l?c:l}},{"./common":41}],43:[function(g,d,t){"use strict";d.exports=function(e,s,i,n){for(var r=65535&e|0,a=e>>>16&65535|0,o=0;i!==0;){for(i-=o=2e3<i?2e3:i;a=a+(r=r+s[n++]|0)|0,--o;);r%=65521,a%=65521}return r|a<<16|0}},{}],44:[function(g,d,t){"use strict";d.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(g,d,t){"use strict";var e=function(){for(var s,i=[],n=0;n<256;n++){s=n;for(var r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;i[n]=s}return i}();d.exports=function(s,i,n,r){var a=e,o=r+n;s^=-1;for(var l=r;l<o;l++)s=s>>>8^a[255&(s^i[l])];return-1^s}},{}],46:[function(g,d,t){"use strict";var e,s=g("../utils/common"),i=g("./trees"),n=g("./adler32"),r=g("./crc32"),a=g("./messages"),o=0,l=4,c=0,p=-2,u=-1,h=4,f=2,m=8,v=9,y=286,b=30,k=19,T=2*y+1,I=15,E=3,D=258,H=D+E+1,C=42,A=113,S=1,_=2,J=3,U=4;function z(w,B){return w.msg=a[B],B}function W(w){return(w<<1)-(4<w?9:0)}function Q(w){for(var B=w.length;0<=--B;)w[B]=0}function L(w){var B=w.state,$=B.pending;$>w.avail_out&&($=w.avail_out),$!==0&&(s.arraySet(w.output,B.pending_buf,B.pending_out,$,w.next_out),w.next_out+=$,B.pending_out+=$,w.total_out+=$,w.avail_out-=$,B.pending-=$,B.pending===0&&(B.pending_out=0))}function P(w,B){i._tr_flush_block(w,0<=w.block_start?w.block_start:-1,w.strstart-w.block_start,B),w.block_start=w.strstart,L(w.strm)}function X(w,B){w.pending_buf[w.pending++]=B}function q(w,B){w.pending_buf[w.pending++]=B>>>8&255,w.pending_buf[w.pending++]=255&B}function Y(w,B){var $,x,F=w.max_chain_length,M=w.strstart,j=w.prev_length,V=w.nice_match,N=w.strstart>w.w_size-H?w.strstart-(w.w_size-H):0,K=w.window,tt=w.w_mask,Z=w.prev,st=w.strstart+D,ut=K[M+j-1],lt=K[M+j];w.prev_length>=w.good_match&&(F>>=2),V>w.lookahead&&(V=w.lookahead);do if(K[($=B)+j]===lt&&K[$+j-1]===ut&&K[$]===K[M]&&K[++$]===K[M+1]){M+=2,$++;do;while(K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&K[++M]===K[++$]&&M<st);if(x=D-(st-M),M=st-D,j<x){if(w.match_start=B,V<=(j=x))break;ut=K[M+j-1],lt=K[M+j]}}while((B=Z[B&tt])>N&&--F!=0);return j<=w.lookahead?j:w.lookahead}function ct(w){var B,$,x,F,M,j,V,N,K,tt,Z=w.w_size;do{if(F=w.window_size-w.lookahead-w.strstart,w.strstart>=Z+(Z-H)){for(s.arraySet(w.window,w.window,Z,Z,0),w.match_start-=Z,w.strstart-=Z,w.block_start-=Z,B=$=w.hash_size;x=w.head[--B],w.head[B]=Z<=x?x-Z:0,--$;);for(B=$=Z;x=w.prev[--B],w.prev[B]=Z<=x?x-Z:0,--$;);F+=Z}if(w.strm.avail_in===0)break;if(j=w.strm,V=w.window,N=w.strstart+w.lookahead,K=F,tt=void 0,tt=j.avail_in,K<tt&&(tt=K),$=tt===0?0:(j.avail_in-=tt,s.arraySet(V,j.input,j.next_in,tt,N),j.state.wrap===1?j.adler=n(j.adler,V,tt,N):j.state.wrap===2&&(j.adler=r(j.adler,V,tt,N)),j.next_in+=tt,j.total_in+=tt,tt),w.lookahead+=$,w.lookahead+w.insert>=E)for(M=w.strstart-w.insert,w.ins_h=w.window[M],w.ins_h=(w.ins_h<<w.hash_shift^w.window[M+1])&w.hash_mask;w.insert&&(w.ins_h=(w.ins_h<<w.hash_shift^w.window[M+E-1])&w.hash_mask,w.prev[M&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=M,M++,w.insert--,!(w.lookahead+w.insert<E)););}while(w.lookahead<H&&w.strm.avail_in!==0)}function pt(w,B){for(var $,x;;){if(w.lookahead<H){if(ct(w),w.lookahead<H&&B===o)return S;if(w.lookahead===0)break}if($=0,w.lookahead>=E&&(w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+E-1])&w.hash_mask,$=w.prev[w.strstart&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=w.strstart),$!==0&&w.strstart-$<=w.w_size-H&&(w.match_length=Y(w,$)),w.match_length>=E)if(x=i._tr_tally(w,w.strstart-w.match_start,w.match_length-E),w.lookahead-=w.match_length,w.match_length<=w.max_lazy_match&&w.lookahead>=E){for(w.match_length--;w.strstart++,w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+E-1])&w.hash_mask,$=w.prev[w.strstart&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=w.strstart,--w.match_length!=0;);w.strstart++}else w.strstart+=w.match_length,w.match_length=0,w.ins_h=w.window[w.strstart],w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+1])&w.hash_mask;else x=i._tr_tally(w,0,w.window[w.strstart]),w.lookahead--,w.strstart++;if(x&&(P(w,!1),w.strm.avail_out===0))return S}return w.insert=w.strstart<E-1?w.strstart:E-1,B===l?(P(w,!0),w.strm.avail_out===0?J:U):w.last_lit&&(P(w,!1),w.strm.avail_out===0)?S:_}function nt(w,B){for(var $,x,F;;){if(w.lookahead<H){if(ct(w),w.lookahead<H&&B===o)return S;if(w.lookahead===0)break}if($=0,w.lookahead>=E&&(w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+E-1])&w.hash_mask,$=w.prev[w.strstart&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=w.strstart),w.prev_length=w.match_length,w.prev_match=w.match_start,w.match_length=E-1,$!==0&&w.prev_length<w.max_lazy_match&&w.strstart-$<=w.w_size-H&&(w.match_length=Y(w,$),w.match_length<=5&&(w.strategy===1||w.match_length===E&&4096<w.strstart-w.match_start)&&(w.match_length=E-1)),w.prev_length>=E&&w.match_length<=w.prev_length){for(F=w.strstart+w.lookahead-E,x=i._tr_tally(w,w.strstart-1-w.prev_match,w.prev_length-E),w.lookahead-=w.prev_length-1,w.prev_length-=2;++w.strstart<=F&&(w.ins_h=(w.ins_h<<w.hash_shift^w.window[w.strstart+E-1])&w.hash_mask,$=w.prev[w.strstart&w.w_mask]=w.head[w.ins_h],w.head[w.ins_h]=w.strstart),--w.prev_length!=0;);if(w.match_available=0,w.match_length=E-1,w.strstart++,x&&(P(w,!1),w.strm.avail_out===0))return S}else if(w.match_available){if((x=i._tr_tally(w,0,w.window[w.strstart-1]))&&P(w,!1),w.strstart++,w.lookahead--,w.strm.avail_out===0)return S}else w.match_available=1,w.strstart++,w.lookahead--}return w.match_available&&(x=i._tr_tally(w,0,w.window[w.strstart-1]),w.match_available=0),w.insert=w.strstart<E-1?w.strstart:E-1,B===l?(P(w,!0),w.strm.avail_out===0?J:U):w.last_lit&&(P(w,!1),w.strm.avail_out===0)?S:_}function rt(w,B,$,x,F){this.good_length=w,this.max_lazy=B,this.nice_length=$,this.max_chain=x,this.func=F}function ot(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=m,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*T),this.dyn_dtree=new s.Buf16(2*(2*b+1)),this.bl_tree=new s.Buf16(2*(2*k+1)),Q(this.dyn_ltree),Q(this.dyn_dtree),Q(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(I+1),this.heap=new s.Buf16(2*y+1),Q(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*y+1),Q(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function it(w){var B;return w&&w.state?(w.total_in=w.total_out=0,w.data_type=f,(B=w.state).pending=0,B.pending_out=0,B.wrap<0&&(B.wrap=-B.wrap),B.status=B.wrap?C:A,w.adler=B.wrap===2?0:1,B.last_flush=o,i._tr_init(B),c):z(w,p)}function gt(w){var B=it(w);return B===c&&function($){$.window_size=2*$.w_size,Q($.head),$.max_lazy_match=e[$.level].max_lazy,$.good_match=e[$.level].good_length,$.nice_match=e[$.level].nice_length,$.max_chain_length=e[$.level].max_chain,$.strstart=0,$.block_start=0,$.lookahead=0,$.insert=0,$.match_length=$.prev_length=E-1,$.match_available=0,$.ins_h=0}(w.state),B}function ft(w,B,$,x,F,M){if(!w)return p;var j=1;if(B===u&&(B=6),x<0?(j=0,x=-x):15<x&&(j=2,x-=16),F<1||v<F||$!==m||x<8||15<x||B<0||9<B||M<0||h<M)return z(w,p);x===8&&(x=9);var V=new ot;return(w.state=V).strm=w,V.wrap=j,V.gzhead=null,V.w_bits=x,V.w_size=1<<V.w_bits,V.w_mask=V.w_size-1,V.hash_bits=F+7,V.hash_size=1<<V.hash_bits,V.hash_mask=V.hash_size-1,V.hash_shift=~~((V.hash_bits+E-1)/E),V.window=new s.Buf8(2*V.w_size),V.head=new s.Buf16(V.hash_size),V.prev=new s.Buf16(V.w_size),V.lit_bufsize=1<<F+6,V.pending_buf_size=4*V.lit_bufsize,V.pending_buf=new s.Buf8(V.pending_buf_size),V.d_buf=1*V.lit_bufsize,V.l_buf=3*V.lit_bufsize,V.level=B,V.strategy=M,V.method=$,gt(w)}e=[new rt(0,0,0,0,function(w,B){var $=65535;for($>w.pending_buf_size-5&&($=w.pending_buf_size-5);;){if(w.lookahead<=1){if(ct(w),w.lookahead===0&&B===o)return S;if(w.lookahead===0)break}w.strstart+=w.lookahead,w.lookahead=0;var x=w.block_start+$;if((w.strstart===0||w.strstart>=x)&&(w.lookahead=w.strstart-x,w.strstart=x,P(w,!1),w.strm.avail_out===0)||w.strstart-w.block_start>=w.w_size-H&&(P(w,!1),w.strm.avail_out===0))return S}return w.insert=0,B===l?(P(w,!0),w.strm.avail_out===0?J:U):(w.strstart>w.block_start&&(P(w,!1),w.strm.avail_out),S)}),new rt(4,4,8,4,pt),new rt(4,5,16,8,pt),new rt(4,6,32,32,pt),new rt(4,4,16,16,nt),new rt(8,16,32,32,nt),new rt(8,16,128,128,nt),new rt(8,32,128,256,nt),new rt(32,128,258,1024,nt),new rt(32,258,258,4096,nt)],t.deflateInit=function(w,B){return ft(w,B,m,15,8,0)},t.deflateInit2=ft,t.deflateReset=gt,t.deflateResetKeep=it,t.deflateSetHeader=function(w,B){return w&&w.state?w.state.wrap!==2?p:(w.state.gzhead=B,c):p},t.deflate=function(w,B){var $,x,F,M;if(!w||!w.state||5<B||B<0)return w?z(w,p):p;if(x=w.state,!w.output||!w.input&&w.avail_in!==0||x.status===666&&B!==l)return z(w,w.avail_out===0?-5:p);if(x.strm=w,$=x.last_flush,x.last_flush=B,x.status===C)if(x.wrap===2)w.adler=0,X(x,31),X(x,139),X(x,8),x.gzhead?(X(x,(x.gzhead.text?1:0)+(x.gzhead.hcrc?2:0)+(x.gzhead.extra?4:0)+(x.gzhead.name?8:0)+(x.gzhead.comment?16:0)),X(x,255&x.gzhead.time),X(x,x.gzhead.time>>8&255),X(x,x.gzhead.time>>16&255),X(x,x.gzhead.time>>24&255),X(x,x.level===9?2:2<=x.strategy||x.level<2?4:0),X(x,255&x.gzhead.os),x.gzhead.extra&&x.gzhead.extra.length&&(X(x,255&x.gzhead.extra.length),X(x,x.gzhead.extra.length>>8&255)),x.gzhead.hcrc&&(w.adler=r(w.adler,x.pending_buf,x.pending,0)),x.gzindex=0,x.status=69):(X(x,0),X(x,0),X(x,0),X(x,0),X(x,0),X(x,x.level===9?2:2<=x.strategy||x.level<2?4:0),X(x,3),x.status=A);else{var j=m+(x.w_bits-8<<4)<<8;j|=(2<=x.strategy||x.level<2?0:x.level<6?1:x.level===6?2:3)<<6,x.strstart!==0&&(j|=32),j+=31-j%31,x.status=A,q(x,j),x.strstart!==0&&(q(x,w.adler>>>16),q(x,65535&w.adler)),w.adler=1}if(x.status===69)if(x.gzhead.extra){for(F=x.pending;x.gzindex<(65535&x.gzhead.extra.length)&&(x.pending!==x.pending_buf_size||(x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),L(w),F=x.pending,x.pending!==x.pending_buf_size));)X(x,255&x.gzhead.extra[x.gzindex]),x.gzindex++;x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),x.gzindex===x.gzhead.extra.length&&(x.gzindex=0,x.status=73)}else x.status=73;if(x.status===73)if(x.gzhead.name){F=x.pending;do{if(x.pending===x.pending_buf_size&&(x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),L(w),F=x.pending,x.pending===x.pending_buf_size)){M=1;break}M=x.gzindex<x.gzhead.name.length?255&x.gzhead.name.charCodeAt(x.gzindex++):0,X(x,M)}while(M!==0);x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),M===0&&(x.gzindex=0,x.status=91)}else x.status=91;if(x.status===91)if(x.gzhead.comment){F=x.pending;do{if(x.pending===x.pending_buf_size&&(x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),L(w),F=x.pending,x.pending===x.pending_buf_size)){M=1;break}M=x.gzindex<x.gzhead.comment.length?255&x.gzhead.comment.charCodeAt(x.gzindex++):0,X(x,M)}while(M!==0);x.gzhead.hcrc&&x.pending>F&&(w.adler=r(w.adler,x.pending_buf,x.pending-F,F)),M===0&&(x.status=103)}else x.status=103;if(x.status===103&&(x.gzhead.hcrc?(x.pending+2>x.pending_buf_size&&L(w),x.pending+2<=x.pending_buf_size&&(X(x,255&w.adler),X(x,w.adler>>8&255),w.adler=0,x.status=A)):x.status=A),x.pending!==0){if(L(w),w.avail_out===0)return x.last_flush=-1,c}else if(w.avail_in===0&&W(B)<=W($)&&B!==l)return z(w,-5);if(x.status===666&&w.avail_in!==0)return z(w,-5);if(w.avail_in!==0||x.lookahead!==0||B!==o&&x.status!==666){var V=x.strategy===2?function(N,K){for(var tt;;){if(N.lookahead===0&&(ct(N),N.lookahead===0)){if(K===o)return S;break}if(N.match_length=0,tt=i._tr_tally(N,0,N.window[N.strstart]),N.lookahead--,N.strstart++,tt&&(P(N,!1),N.strm.avail_out===0))return S}return N.insert=0,K===l?(P(N,!0),N.strm.avail_out===0?J:U):N.last_lit&&(P(N,!1),N.strm.avail_out===0)?S:_}(x,B):x.strategy===3?function(N,K){for(var tt,Z,st,ut,lt=N.window;;){if(N.lookahead<=D){if(ct(N),N.lookahead<=D&&K===o)return S;if(N.lookahead===0)break}if(N.match_length=0,N.lookahead>=E&&0<N.strstart&&(Z=lt[st=N.strstart-1])===lt[++st]&&Z===lt[++st]&&Z===lt[++st]){ut=N.strstart+D;do;while(Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&Z===lt[++st]&&st<ut);N.match_length=D-(ut-st),N.match_length>N.lookahead&&(N.match_length=N.lookahead)}if(N.match_length>=E?(tt=i._tr_tally(N,1,N.match_length-E),N.lookahead-=N.match_length,N.strstart+=N.match_length,N.match_length=0):(tt=i._tr_tally(N,0,N.window[N.strstart]),N.lookahead--,N.strstart++),tt&&(P(N,!1),N.strm.avail_out===0))return S}return N.insert=0,K===l?(P(N,!0),N.strm.avail_out===0?J:U):N.last_lit&&(P(N,!1),N.strm.avail_out===0)?S:_}(x,B):e[x.level].func(x,B);if(V!==J&&V!==U||(x.status=666),V===S||V===J)return w.avail_out===0&&(x.last_flush=-1),c;if(V===_&&(B===1?i._tr_align(x):B!==5&&(i._tr_stored_block(x,0,0,!1),B===3&&(Q(x.head),x.lookahead===0&&(x.strstart=0,x.block_start=0,x.insert=0))),L(w),w.avail_out===0))return x.last_flush=-1,c}return B!==l?c:x.wrap<=0?1:(x.wrap===2?(X(x,255&w.adler),X(x,w.adler>>8&255),X(x,w.adler>>16&255),X(x,w.adler>>24&255),X(x,255&w.total_in),X(x,w.total_in>>8&255),X(x,w.total_in>>16&255),X(x,w.total_in>>24&255)):(q(x,w.adler>>>16),q(x,65535&w.adler)),L(w),0<x.wrap&&(x.wrap=-x.wrap),x.pending!==0?c:1)},t.deflateEnd=function(w){var B;return w&&w.state?(B=w.state.status)!==C&&B!==69&&B!==73&&B!==91&&B!==103&&B!==A&&B!==666?z(w,p):(w.state=null,B===A?z(w,-3):c):p},t.deflateSetDictionary=function(w,B){var $,x,F,M,j,V,N,K,tt=B.length;if(!w||!w.state||(M=($=w.state).wrap)===2||M===1&&$.status!==C||$.lookahead)return p;for(M===1&&(w.adler=n(w.adler,B,tt,0)),$.wrap=0,tt>=$.w_size&&(M===0&&(Q($.head),$.strstart=0,$.block_start=0,$.insert=0),K=new s.Buf8($.w_size),s.arraySet(K,B,tt-$.w_size,$.w_size,0),B=K,tt=$.w_size),j=w.avail_in,V=w.next_in,N=w.input,w.avail_in=tt,w.next_in=0,w.input=B,ct($);$.lookahead>=E;){for(x=$.strstart,F=$.lookahead-(E-1);$.ins_h=($.ins_h<<$.hash_shift^$.window[x+E-1])&$.hash_mask,$.prev[x&$.w_mask]=$.head[$.ins_h],$.head[$.ins_h]=x,x++,--F;);$.strstart=x,$.lookahead=E-1,ct($)}return $.strstart+=$.lookahead,$.block_start=$.strstart,$.insert=$.lookahead,$.lookahead=0,$.match_length=$.prev_length=E-1,$.match_available=0,w.next_in=V,w.input=N,w.avail_in=j,$.wrap=M,c},t.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(g,d,t){"use strict";d.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(g,d,t){"use strict";d.exports=function(e,s){var i,n,r,a,o,l,c,p,u,h,f,m,v,y,b,k,T,I,E,D,H,C,A,S,_;i=e.state,n=e.next_in,S=e.input,r=n+(e.avail_in-5),a=e.next_out,_=e.output,o=a-(s-e.avail_out),l=a+(e.avail_out-257),c=i.dmax,p=i.wsize,u=i.whave,h=i.wnext,f=i.window,m=i.hold,v=i.bits,y=i.lencode,b=i.distcode,k=(1<<i.lenbits)-1,T=(1<<i.distbits)-1;t:do{v<15&&(m+=S[n++]<<v,v+=8,m+=S[n++]<<v,v+=8),I=y[m&k];e:for(;;){if(m>>>=E=I>>>24,v-=E,(E=I>>>16&255)===0)_[a++]=65535&I;else{if(!(16&E)){if(!(64&E)){I=y[(65535&I)+(m&(1<<E)-1)];continue e}if(32&E){i.mode=12;break t}e.msg="invalid literal/length code",i.mode=30;break t}D=65535&I,(E&=15)&&(v<E&&(m+=S[n++]<<v,v+=8),D+=m&(1<<E)-1,m>>>=E,v-=E),v<15&&(m+=S[n++]<<v,v+=8,m+=S[n++]<<v,v+=8),I=b[m&T];s:for(;;){if(m>>>=E=I>>>24,v-=E,!(16&(E=I>>>16&255))){if(!(64&E)){I=b[(65535&I)+(m&(1<<E)-1)];continue s}e.msg="invalid distance code",i.mode=30;break t}if(H=65535&I,v<(E&=15)&&(m+=S[n++]<<v,(v+=8)<E&&(m+=S[n++]<<v,v+=8)),c<(H+=m&(1<<E)-1)){e.msg="invalid distance too far back",i.mode=30;break t}if(m>>>=E,v-=E,(E=a-o)<H){if(u<(E=H-E)&&i.sane){e.msg="invalid distance too far back",i.mode=30;break t}if(A=f,(C=0)===h){if(C+=p-E,E<D){for(D-=E;_[a++]=f[C++],--E;);C=a-H,A=_}}else if(h<E){if(C+=p+h-E,(E-=h)<D){for(D-=E;_[a++]=f[C++],--E;);if(C=0,h<D){for(D-=E=h;_[a++]=f[C++],--E;);C=a-H,A=_}}}else if(C+=h-E,E<D){for(D-=E;_[a++]=f[C++],--E;);C=a-H,A=_}for(;2<D;)_[a++]=A[C++],_[a++]=A[C++],_[a++]=A[C++],D-=3;D&&(_[a++]=A[C++],1<D&&(_[a++]=A[C++]))}else{for(C=a-H;_[a++]=_[C++],_[a++]=_[C++],_[a++]=_[C++],2<(D-=3););D&&(_[a++]=_[C++],1<D&&(_[a++]=_[C++]))}break}}break}}while(n<r&&a<l);n-=D=v>>3,m&=(1<<(v-=D<<3))-1,e.next_in=n,e.next_out=a,e.avail_in=n<r?r-n+5:5-(n-r),e.avail_out=a<l?l-a+257:257-(a-l),i.hold=m,i.bits=v}},{}],49:[function(g,d,t){"use strict";var e=g("../utils/common"),s=g("./adler32"),i=g("./crc32"),n=g("./inffast"),r=g("./inftrees"),a=1,o=2,l=0,c=-2,p=1,u=852,h=592;function f(C){return(C>>>24&255)+(C>>>8&65280)+((65280&C)<<8)+((255&C)<<24)}function m(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new e.Buf16(320),this.work=new e.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(C){var A;return C&&C.state?(A=C.state,C.total_in=C.total_out=A.total=0,C.msg="",A.wrap&&(C.adler=1&A.wrap),A.mode=p,A.last=0,A.havedict=0,A.dmax=32768,A.head=null,A.hold=0,A.bits=0,A.lencode=A.lendyn=new e.Buf32(u),A.distcode=A.distdyn=new e.Buf32(h),A.sane=1,A.back=-1,l):c}function y(C){var A;return C&&C.state?((A=C.state).wsize=0,A.whave=0,A.wnext=0,v(C)):c}function b(C,A){var S,_;return C&&C.state?(_=C.state,A<0?(S=0,A=-A):(S=1+(A>>4),A<48&&(A&=15)),A&&(A<8||15<A)?c:(_.window!==null&&_.wbits!==A&&(_.window=null),_.wrap=S,_.wbits=A,y(C))):c}function k(C,A){var S,_;return C?(_=new m,(C.state=_).window=null,(S=b(C,A))!==l&&(C.state=null),S):c}var T,I,E=!0;function D(C){if(E){var A;for(T=new e.Buf32(512),I=new e.Buf32(32),A=0;A<144;)C.lens[A++]=8;for(;A<256;)C.lens[A++]=9;for(;A<280;)C.lens[A++]=7;for(;A<288;)C.lens[A++]=8;for(r(a,C.lens,0,288,T,0,C.work,{bits:9}),A=0;A<32;)C.lens[A++]=5;r(o,C.lens,0,32,I,0,C.work,{bits:5}),E=!1}C.lencode=T,C.lenbits=9,C.distcode=I,C.distbits=5}function H(C,A,S,_){var J,U=C.state;return U.window===null&&(U.wsize=1<<U.wbits,U.wnext=0,U.whave=0,U.window=new e.Buf8(U.wsize)),_>=U.wsize?(e.arraySet(U.window,A,S-U.wsize,U.wsize,0),U.wnext=0,U.whave=U.wsize):(_<(J=U.wsize-U.wnext)&&(J=_),e.arraySet(U.window,A,S-_,J,U.wnext),(_-=J)?(e.arraySet(U.window,A,S-_,_,0),U.wnext=_,U.whave=U.wsize):(U.wnext+=J,U.wnext===U.wsize&&(U.wnext=0),U.whave<U.wsize&&(U.whave+=J))),0}t.inflateReset=y,t.inflateReset2=b,t.inflateResetKeep=v,t.inflateInit=function(C){return k(C,15)},t.inflateInit2=k,t.inflate=function(C,A){var S,_,J,U,z,W,Q,L,P,X,q,Y,ct,pt,nt,rt,ot,it,gt,ft,w,B,$,x,F=0,M=new e.Buf8(4),j=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!C||!C.state||!C.output||!C.input&&C.avail_in!==0)return c;(S=C.state).mode===12&&(S.mode=13),z=C.next_out,J=C.output,Q=C.avail_out,U=C.next_in,_=C.input,W=C.avail_in,L=S.hold,P=S.bits,X=W,q=Q,B=l;t:for(;;)switch(S.mode){case p:if(S.wrap===0){S.mode=13;break}for(;P<16;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(2&S.wrap&&L===35615){M[S.check=0]=255&L,M[1]=L>>>8&255,S.check=i(S.check,M,2,0),P=L=0,S.mode=2;break}if(S.flags=0,S.head&&(S.head.done=!1),!(1&S.wrap)||(((255&L)<<8)+(L>>8))%31){C.msg="incorrect header check",S.mode=30;break}if((15&L)!=8){C.msg="unknown compression method",S.mode=30;break}if(P-=4,w=8+(15&(L>>>=4)),S.wbits===0)S.wbits=w;else if(w>S.wbits){C.msg="invalid window size",S.mode=30;break}S.dmax=1<<w,C.adler=S.check=1,S.mode=512&L?10:12,P=L=0;break;case 2:for(;P<16;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(S.flags=L,(255&S.flags)!=8){C.msg="unknown compression method",S.mode=30;break}if(57344&S.flags){C.msg="unknown header flags set",S.mode=30;break}S.head&&(S.head.text=L>>8&1),512&S.flags&&(M[0]=255&L,M[1]=L>>>8&255,S.check=i(S.check,M,2,0)),P=L=0,S.mode=3;case 3:for(;P<32;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}S.head&&(S.head.time=L),512&S.flags&&(M[0]=255&L,M[1]=L>>>8&255,M[2]=L>>>16&255,M[3]=L>>>24&255,S.check=i(S.check,M,4,0)),P=L=0,S.mode=4;case 4:for(;P<16;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}S.head&&(S.head.xflags=255&L,S.head.os=L>>8),512&S.flags&&(M[0]=255&L,M[1]=L>>>8&255,S.check=i(S.check,M,2,0)),P=L=0,S.mode=5;case 5:if(1024&S.flags){for(;P<16;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}S.length=L,S.head&&(S.head.extra_len=L),512&S.flags&&(M[0]=255&L,M[1]=L>>>8&255,S.check=i(S.check,M,2,0)),P=L=0}else S.head&&(S.head.extra=null);S.mode=6;case 6:if(1024&S.flags&&(W<(Y=S.length)&&(Y=W),Y&&(S.head&&(w=S.head.extra_len-S.length,S.head.extra||(S.head.extra=new Array(S.head.extra_len)),e.arraySet(S.head.extra,_,U,Y,w)),512&S.flags&&(S.check=i(S.check,_,Y,U)),W-=Y,U+=Y,S.length-=Y),S.length))break t;S.length=0,S.mode=7;case 7:if(2048&S.flags){if(W===0)break t;for(Y=0;w=_[U+Y++],S.head&&w&&S.length<65536&&(S.head.name+=String.fromCharCode(w)),w&&Y<W;);if(512&S.flags&&(S.check=i(S.check,_,Y,U)),W-=Y,U+=Y,w)break t}else S.head&&(S.head.name=null);S.length=0,S.mode=8;case 8:if(4096&S.flags){if(W===0)break t;for(Y=0;w=_[U+Y++],S.head&&w&&S.length<65536&&(S.head.comment+=String.fromCharCode(w)),w&&Y<W;);if(512&S.flags&&(S.check=i(S.check,_,Y,U)),W-=Y,U+=Y,w)break t}else S.head&&(S.head.comment=null);S.mode=9;case 9:if(512&S.flags){for(;P<16;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(L!==(65535&S.check)){C.msg="header crc mismatch",S.mode=30;break}P=L=0}S.head&&(S.head.hcrc=S.flags>>9&1,S.head.done=!0),C.adler=S.check=0,S.mode=12;break;case 10:for(;P<32;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}C.adler=S.check=f(L),P=L=0,S.mode=11;case 11:if(S.havedict===0)return C.next_out=z,C.avail_out=Q,C.next_in=U,C.avail_in=W,S.hold=L,S.bits=P,2;C.adler=S.check=1,S.mode=12;case 12:if(A===5||A===6)break t;case 13:if(S.last){L>>>=7&P,P-=7&P,S.mode=27;break}for(;P<3;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}switch(S.last=1&L,P-=1,3&(L>>>=1)){case 0:S.mode=14;break;case 1:if(D(S),S.mode=20,A!==6)break;L>>>=2,P-=2;break t;case 2:S.mode=17;break;case 3:C.msg="invalid block type",S.mode=30}L>>>=2,P-=2;break;case 14:for(L>>>=7&P,P-=7&P;P<32;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if((65535&L)!=(L>>>16^65535)){C.msg="invalid stored block lengths",S.mode=30;break}if(S.length=65535&L,P=L=0,S.mode=15,A===6)break t;case 15:S.mode=16;case 16:if(Y=S.length){if(W<Y&&(Y=W),Q<Y&&(Y=Q),Y===0)break t;e.arraySet(J,_,U,Y,z),W-=Y,U+=Y,Q-=Y,z+=Y,S.length-=Y;break}S.mode=12;break;case 17:for(;P<14;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(S.nlen=257+(31&L),L>>>=5,P-=5,S.ndist=1+(31&L),L>>>=5,P-=5,S.ncode=4+(15&L),L>>>=4,P-=4,286<S.nlen||30<S.ndist){C.msg="too many length or distance symbols",S.mode=30;break}S.have=0,S.mode=18;case 18:for(;S.have<S.ncode;){for(;P<3;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}S.lens[j[S.have++]]=7&L,L>>>=3,P-=3}for(;S.have<19;)S.lens[j[S.have++]]=0;if(S.lencode=S.lendyn,S.lenbits=7,$={bits:S.lenbits},B=r(0,S.lens,0,19,S.lencode,0,S.work,$),S.lenbits=$.bits,B){C.msg="invalid code lengths set",S.mode=30;break}S.have=0,S.mode=19;case 19:for(;S.have<S.nlen+S.ndist;){for(;rt=(F=S.lencode[L&(1<<S.lenbits)-1])>>>16&255,ot=65535&F,!((nt=F>>>24)<=P);){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(ot<16)L>>>=nt,P-=nt,S.lens[S.have++]=ot;else{if(ot===16){for(x=nt+2;P<x;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(L>>>=nt,P-=nt,S.have===0){C.msg="invalid bit length repeat",S.mode=30;break}w=S.lens[S.have-1],Y=3+(3&L),L>>>=2,P-=2}else if(ot===17){for(x=nt+3;P<x;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}P-=nt,w=0,Y=3+(7&(L>>>=nt)),L>>>=3,P-=3}else{for(x=nt+7;P<x;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}P-=nt,w=0,Y=11+(127&(L>>>=nt)),L>>>=7,P-=7}if(S.have+Y>S.nlen+S.ndist){C.msg="invalid bit length repeat",S.mode=30;break}for(;Y--;)S.lens[S.have++]=w}}if(S.mode===30)break;if(S.lens[256]===0){C.msg="invalid code -- missing end-of-block",S.mode=30;break}if(S.lenbits=9,$={bits:S.lenbits},B=r(a,S.lens,0,S.nlen,S.lencode,0,S.work,$),S.lenbits=$.bits,B){C.msg="invalid literal/lengths set",S.mode=30;break}if(S.distbits=6,S.distcode=S.distdyn,$={bits:S.distbits},B=r(o,S.lens,S.nlen,S.ndist,S.distcode,0,S.work,$),S.distbits=$.bits,B){C.msg="invalid distances set",S.mode=30;break}if(S.mode=20,A===6)break t;case 20:S.mode=21;case 21:if(6<=W&&258<=Q){C.next_out=z,C.avail_out=Q,C.next_in=U,C.avail_in=W,S.hold=L,S.bits=P,n(C,q),z=C.next_out,J=C.output,Q=C.avail_out,U=C.next_in,_=C.input,W=C.avail_in,L=S.hold,P=S.bits,S.mode===12&&(S.back=-1);break}for(S.back=0;rt=(F=S.lencode[L&(1<<S.lenbits)-1])>>>16&255,ot=65535&F,!((nt=F>>>24)<=P);){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(rt&&!(240&rt)){for(it=nt,gt=rt,ft=ot;rt=(F=S.lencode[ft+((L&(1<<it+gt)-1)>>it)])>>>16&255,ot=65535&F,!(it+(nt=F>>>24)<=P);){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}L>>>=it,P-=it,S.back+=it}if(L>>>=nt,P-=nt,S.back+=nt,S.length=ot,rt===0){S.mode=26;break}if(32&rt){S.back=-1,S.mode=12;break}if(64&rt){C.msg="invalid literal/length code",S.mode=30;break}S.extra=15&rt,S.mode=22;case 22:if(S.extra){for(x=S.extra;P<x;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}S.length+=L&(1<<S.extra)-1,L>>>=S.extra,P-=S.extra,S.back+=S.extra}S.was=S.length,S.mode=23;case 23:for(;rt=(F=S.distcode[L&(1<<S.distbits)-1])>>>16&255,ot=65535&F,!((nt=F>>>24)<=P);){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(!(240&rt)){for(it=nt,gt=rt,ft=ot;rt=(F=S.distcode[ft+((L&(1<<it+gt)-1)>>it)])>>>16&255,ot=65535&F,!(it+(nt=F>>>24)<=P);){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}L>>>=it,P-=it,S.back+=it}if(L>>>=nt,P-=nt,S.back+=nt,64&rt){C.msg="invalid distance code",S.mode=30;break}S.offset=ot,S.extra=15&rt,S.mode=24;case 24:if(S.extra){for(x=S.extra;P<x;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}S.offset+=L&(1<<S.extra)-1,L>>>=S.extra,P-=S.extra,S.back+=S.extra}if(S.offset>S.dmax){C.msg="invalid distance too far back",S.mode=30;break}S.mode=25;case 25:if(Q===0)break t;if(Y=q-Q,S.offset>Y){if((Y=S.offset-Y)>S.whave&&S.sane){C.msg="invalid distance too far back",S.mode=30;break}ct=Y>S.wnext?(Y-=S.wnext,S.wsize-Y):S.wnext-Y,Y>S.length&&(Y=S.length),pt=S.window}else pt=J,ct=z-S.offset,Y=S.length;for(Q<Y&&(Y=Q),Q-=Y,S.length-=Y;J[z++]=pt[ct++],--Y;);S.length===0&&(S.mode=21);break;case 26:if(Q===0)break t;J[z++]=S.length,Q--,S.mode=21;break;case 27:if(S.wrap){for(;P<32;){if(W===0)break t;W--,L|=_[U++]<<P,P+=8}if(q-=Q,C.total_out+=q,S.total+=q,q&&(C.adler=S.check=S.flags?i(S.check,J,q,z-q):s(S.check,J,q,z-q)),q=Q,(S.flags?L:f(L))!==S.check){C.msg="incorrect data check",S.mode=30;break}P=L=0}S.mode=28;case 28:if(S.wrap&&S.flags){for(;P<32;){if(W===0)break t;W--,L+=_[U++]<<P,P+=8}if(L!==(4294967295&S.total)){C.msg="incorrect length check",S.mode=30;break}P=L=0}S.mode=29;case 29:B=1;break t;case 30:B=-3;break t;case 31:return-4;case 32:default:return c}return C.next_out=z,C.avail_out=Q,C.next_in=U,C.avail_in=W,S.hold=L,S.bits=P,(S.wsize||q!==C.avail_out&&S.mode<30&&(S.mode<27||A!==4))&&H(C,C.output,C.next_out,q-C.avail_out)?(S.mode=31,-4):(X-=C.avail_in,q-=C.avail_out,C.total_in+=X,C.total_out+=q,S.total+=q,S.wrap&&q&&(C.adler=S.check=S.flags?i(S.check,J,q,C.next_out-q):s(S.check,J,q,C.next_out-q)),C.data_type=S.bits+(S.last?64:0)+(S.mode===12?128:0)+(S.mode===20||S.mode===15?256:0),(X==0&&q===0||A===4)&&B===l&&(B=-5),B)},t.inflateEnd=function(C){if(!C||!C.state)return c;var A=C.state;return A.window&&(A.window=null),C.state=null,l},t.inflateGetHeader=function(C,A){var S;return C&&C.state&&2&(S=C.state).wrap?((S.head=A).done=!1,l):c},t.inflateSetDictionary=function(C,A){var S,_=A.length;return C&&C.state?(S=C.state).wrap!==0&&S.mode!==11?c:S.mode===11&&s(1,A,_,0)!==S.check?-3:H(C,A,_,_)?(S.mode=31,-4):(S.havedict=1,l):c},t.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(g,d,t){"use strict";var e=g("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],i=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],r=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];d.exports=function(a,o,l,c,p,u,h,f){var m,v,y,b,k,T,I,E,D,H=f.bits,C=0,A=0,S=0,_=0,J=0,U=0,z=0,W=0,Q=0,L=0,P=null,X=0,q=new e.Buf16(16),Y=new e.Buf16(16),ct=null,pt=0;for(C=0;C<=15;C++)q[C]=0;for(A=0;A<c;A++)q[o[l+A]]++;for(J=H,_=15;1<=_&&q[_]===0;_--);if(_<J&&(J=_),_===0)return p[u++]=20971520,p[u++]=20971520,f.bits=1,0;for(S=1;S<_&&q[S]===0;S++);for(J<S&&(J=S),C=W=1;C<=15;C++)if(W<<=1,(W-=q[C])<0)return-1;if(0<W&&(a===0||_!==1))return-1;for(Y[1]=0,C=1;C<15;C++)Y[C+1]=Y[C]+q[C];for(A=0;A<c;A++)o[l+A]!==0&&(h[Y[o[l+A]]++]=A);if(T=a===0?(P=ct=h,19):a===1?(P=s,X-=257,ct=i,pt-=257,256):(P=n,ct=r,-1),C=S,k=u,z=A=L=0,y=-1,b=(Q=1<<(U=J))-1,a===1&&852<Q||a===2&&592<Q)return 1;for(;;){for(I=C-z,D=h[A]<T?(E=0,h[A]):h[A]>T?(E=ct[pt+h[A]],P[X+h[A]]):(E=96,0),m=1<<C-z,S=v=1<<U;p[k+(L>>z)+(v-=m)]=I<<24|E<<16|D|0,v!==0;);for(m=1<<C-1;L&m;)m>>=1;if(m!==0?(L&=m-1,L+=m):L=0,A++,--q[C]==0){if(C===_)break;C=o[l+h[A]]}if(J<C&&(L&b)!==y){for(z===0&&(z=J),k+=S,W=1<<(U=C-z);U+z<_&&!((W-=q[U+z])<=0);)U++,W<<=1;if(Q+=1<<U,a===1&&852<Q||a===2&&592<Q)return 1;p[y=L&b]=J<<24|U<<16|k-u|0}}return L!==0&&(p[k+L]=C-z<<24|64<<16|0),f.bits=J,0}},{"../utils/common":41}],51:[function(g,d,t){"use strict";d.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(g,d,t){"use strict";var e=g("../utils/common"),s=0,i=1;function n(F){for(var M=F.length;0<=--M;)F[M]=0}var r=0,a=29,o=256,l=o+1+a,c=30,p=19,u=2*l+1,h=15,f=16,m=7,v=256,y=16,b=17,k=18,T=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],I=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],E=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],D=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],H=new Array(2*(l+2));n(H);var C=new Array(2*c);n(C);var A=new Array(512);n(A);var S=new Array(256);n(S);var _=new Array(a);n(_);var J,U,z,W=new Array(c);function Q(F,M,j,V,N){this.static_tree=F,this.extra_bits=M,this.extra_base=j,this.elems=V,this.max_length=N,this.has_stree=F&&F.length}function L(F,M){this.dyn_tree=F,this.max_code=0,this.stat_desc=M}function P(F){return F<256?A[F]:A[256+(F>>>7)]}function X(F,M){F.pending_buf[F.pending++]=255&M,F.pending_buf[F.pending++]=M>>>8&255}function q(F,M,j){F.bi_valid>f-j?(F.bi_buf|=M<<F.bi_valid&65535,X(F,F.bi_buf),F.bi_buf=M>>f-F.bi_valid,F.bi_valid+=j-f):(F.bi_buf|=M<<F.bi_valid&65535,F.bi_valid+=j)}function Y(F,M,j){q(F,j[2*M],j[2*M+1])}function ct(F,M){for(var j=0;j|=1&F,F>>>=1,j<<=1,0<--M;);return j>>>1}function pt(F,M,j){var V,N,K=new Array(h+1),tt=0;for(V=1;V<=h;V++)K[V]=tt=tt+j[V-1]<<1;for(N=0;N<=M;N++){var Z=F[2*N+1];Z!==0&&(F[2*N]=ct(K[Z]++,Z))}}function nt(F){var M;for(M=0;M<l;M++)F.dyn_ltree[2*M]=0;for(M=0;M<c;M++)F.dyn_dtree[2*M]=0;for(M=0;M<p;M++)F.bl_tree[2*M]=0;F.dyn_ltree[2*v]=1,F.opt_len=F.static_len=0,F.last_lit=F.matches=0}function rt(F){8<F.bi_valid?X(F,F.bi_buf):0<F.bi_valid&&(F.pending_buf[F.pending++]=F.bi_buf),F.bi_buf=0,F.bi_valid=0}function ot(F,M,j,V){var N=2*M,K=2*j;return F[N]<F[K]||F[N]===F[K]&&V[M]<=V[j]}function it(F,M,j){for(var V=F.heap[j],N=j<<1;N<=F.heap_len&&(N<F.heap_len&&ot(M,F.heap[N+1],F.heap[N],F.depth)&&N++,!ot(M,V,F.heap[N],F.depth));)F.heap[j]=F.heap[N],j=N,N<<=1;F.heap[j]=V}function gt(F,M,j){var V,N,K,tt,Z=0;if(F.last_lit!==0)for(;V=F.pending_buf[F.d_buf+2*Z]<<8|F.pending_buf[F.d_buf+2*Z+1],N=F.pending_buf[F.l_buf+Z],Z++,V===0?Y(F,N,M):(Y(F,(K=S[N])+o+1,M),(tt=T[K])!==0&&q(F,N-=_[K],tt),Y(F,K=P(--V),j),(tt=I[K])!==0&&q(F,V-=W[K],tt)),Z<F.last_lit;);Y(F,v,M)}function ft(F,M){var j,V,N,K=M.dyn_tree,tt=M.stat_desc.static_tree,Z=M.stat_desc.has_stree,st=M.stat_desc.elems,ut=-1;for(F.heap_len=0,F.heap_max=u,j=0;j<st;j++)K[2*j]!==0?(F.heap[++F.heap_len]=ut=j,F.depth[j]=0):K[2*j+1]=0;for(;F.heap_len<2;)K[2*(N=F.heap[++F.heap_len]=ut<2?++ut:0)]=1,F.depth[N]=0,F.opt_len--,Z&&(F.static_len-=tt[2*N+1]);for(M.max_code=ut,j=F.heap_len>>1;1<=j;j--)it(F,K,j);for(N=st;j=F.heap[1],F.heap[1]=F.heap[F.heap_len--],it(F,K,1),V=F.heap[1],F.heap[--F.heap_max]=j,F.heap[--F.heap_max]=V,K[2*N]=K[2*j]+K[2*V],F.depth[N]=(F.depth[j]>=F.depth[V]?F.depth[j]:F.depth[V])+1,K[2*j+1]=K[2*V+1]=N,F.heap[1]=N++,it(F,K,1),2<=F.heap_len;);F.heap[--F.heap_max]=F.heap[1],function(lt,It){var fe,Pt,me,vt,Le,Ts,Lt=It.dyn_tree,Ks=It.max_code,Mi=It.stat_desc.static_tree,_i=It.stat_desc.has_stree,Li=It.stat_desc.extra_bits,Zs=It.stat_desc.extra_base,ge=It.stat_desc.max_length,Ne=0;for(vt=0;vt<=h;vt++)lt.bl_count[vt]=0;for(Lt[2*lt.heap[lt.heap_max]+1]=0,fe=lt.heap_max+1;fe<u;fe++)ge<(vt=Lt[2*Lt[2*(Pt=lt.heap[fe])+1]+1]+1)&&(vt=ge,Ne++),Lt[2*Pt+1]=vt,Ks<Pt||(lt.bl_count[vt]++,Le=0,Zs<=Pt&&(Le=Li[Pt-Zs]),Ts=Lt[2*Pt],lt.opt_len+=Ts*(vt+Le),_i&&(lt.static_len+=Ts*(Mi[2*Pt+1]+Le)));if(Ne!==0){do{for(vt=ge-1;lt.bl_count[vt]===0;)vt--;lt.bl_count[vt]--,lt.bl_count[vt+1]+=2,lt.bl_count[ge]--,Ne-=2}while(0<Ne);for(vt=ge;vt!==0;vt--)for(Pt=lt.bl_count[vt];Pt!==0;)Ks<(me=lt.heap[--fe])||(Lt[2*me+1]!==vt&&(lt.opt_len+=(vt-Lt[2*me+1])*Lt[2*me],Lt[2*me+1]=vt),Pt--)}}(F,M),pt(K,ut,F.bl_count)}function w(F,M,j){var V,N,K=-1,tt=M[1],Z=0,st=7,ut=4;for(tt===0&&(st=138,ut=3),M[2*(j+1)+1]=65535,V=0;V<=j;V++)N=tt,tt=M[2*(V+1)+1],++Z<st&&N===tt||(Z<ut?F.bl_tree[2*N]+=Z:N!==0?(N!==K&&F.bl_tree[2*N]++,F.bl_tree[2*y]++):Z<=10?F.bl_tree[2*b]++:F.bl_tree[2*k]++,K=N,ut=(Z=0)===tt?(st=138,3):N===tt?(st=6,3):(st=7,4))}function B(F,M,j){var V,N,K=-1,tt=M[1],Z=0,st=7,ut=4;for(tt===0&&(st=138,ut=3),V=0;V<=j;V++)if(N=tt,tt=M[2*(V+1)+1],!(++Z<st&&N===tt)){if(Z<ut)for(;Y(F,N,F.bl_tree),--Z!=0;);else N!==0?(N!==K&&(Y(F,N,F.bl_tree),Z--),Y(F,y,F.bl_tree),q(F,Z-3,2)):Z<=10?(Y(F,b,F.bl_tree),q(F,Z-3,3)):(Y(F,k,F.bl_tree),q(F,Z-11,7));K=N,ut=(Z=0)===tt?(st=138,3):N===tt?(st=6,3):(st=7,4)}}n(W);var $=!1;function x(F,M,j,V){q(F,(r<<1)+(V?1:0),3),function(N,K,tt,Z){rt(N),Z&&(X(N,tt),X(N,~tt)),e.arraySet(N.pending_buf,N.window,K,tt,N.pending),N.pending+=tt}(F,M,j,!0)}t._tr_init=function(F){$||(function(){var M,j,V,N,K,tt=new Array(h+1);for(N=V=0;N<a-1;N++)for(_[N]=V,M=0;M<1<<T[N];M++)S[V++]=N;for(S[V-1]=N,N=K=0;N<16;N++)for(W[N]=K,M=0;M<1<<I[N];M++)A[K++]=N;for(K>>=7;N<c;N++)for(W[N]=K<<7,M=0;M<1<<I[N]-7;M++)A[256+K++]=N;for(j=0;j<=h;j++)tt[j]=0;for(M=0;M<=143;)H[2*M+1]=8,M++,tt[8]++;for(;M<=255;)H[2*M+1]=9,M++,tt[9]++;for(;M<=279;)H[2*M+1]=7,M++,tt[7]++;for(;M<=287;)H[2*M+1]=8,M++,tt[8]++;for(pt(H,l+1,tt),M=0;M<c;M++)C[2*M+1]=5,C[2*M]=ct(M,5);J=new Q(H,T,o+1,l,h),U=new Q(C,I,0,c,h),z=new Q(new Array(0),E,0,p,m)}(),$=!0),F.l_desc=new L(F.dyn_ltree,J),F.d_desc=new L(F.dyn_dtree,U),F.bl_desc=new L(F.bl_tree,z),F.bi_buf=0,F.bi_valid=0,nt(F)},t._tr_stored_block=x,t._tr_flush_block=function(F,M,j,V){var N,K,tt=0;0<F.level?(F.strm.data_type===2&&(F.strm.data_type=function(Z){var st,ut=4093624447;for(st=0;st<=31;st++,ut>>>=1)if(1&ut&&Z.dyn_ltree[2*st]!==0)return s;if(Z.dyn_ltree[18]!==0||Z.dyn_ltree[20]!==0||Z.dyn_ltree[26]!==0)return i;for(st=32;st<o;st++)if(Z.dyn_ltree[2*st]!==0)return i;return s}(F)),ft(F,F.l_desc),ft(F,F.d_desc),tt=function(Z){var st;for(w(Z,Z.dyn_ltree,Z.l_desc.max_code),w(Z,Z.dyn_dtree,Z.d_desc.max_code),ft(Z,Z.bl_desc),st=p-1;3<=st&&Z.bl_tree[2*D[st]+1]===0;st--);return Z.opt_len+=3*(st+1)+5+5+4,st}(F),N=F.opt_len+3+7>>>3,(K=F.static_len+3+7>>>3)<=N&&(N=K)):N=K=j+5,j+4<=N&&M!==-1?x(F,M,j,V):F.strategy===4||K===N?(q(F,2+(V?1:0),3),gt(F,H,C)):(q(F,4+(V?1:0),3),function(Z,st,ut,lt){var It;for(q(Z,st-257,5),q(Z,ut-1,5),q(Z,lt-4,4),It=0;It<lt;It++)q(Z,Z.bl_tree[2*D[It]+1],3);B(Z,Z.dyn_ltree,st-1),B(Z,Z.dyn_dtree,ut-1)}(F,F.l_desc.max_code+1,F.d_desc.max_code+1,tt+1),gt(F,F.dyn_ltree,F.dyn_dtree)),nt(F),V&&rt(F)},t._tr_tally=function(F,M,j){return F.pending_buf[F.d_buf+2*F.last_lit]=M>>>8&255,F.pending_buf[F.d_buf+2*F.last_lit+1]=255&M,F.pending_buf[F.l_buf+F.last_lit]=255&j,F.last_lit++,M===0?F.dyn_ltree[2*j]++:(F.matches++,M--,F.dyn_ltree[2*(S[j]+o+1)]++,F.dyn_dtree[2*P(M)]++),F.last_lit===F.lit_bufsize-1},t._tr_align=function(F){q(F,2,3),Y(F,v,H),function(M){M.bi_valid===16?(X(M,M.bi_buf),M.bi_buf=0,M.bi_valid=0):8<=M.bi_valid&&(M.pending_buf[M.pending++]=255&M.bi_buf,M.bi_buf>>=8,M.bi_valid-=8)}(F)}},{"../utils/common":41}],53:[function(g,d,t){"use strict";d.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(g,d,t){(function(e){(function(s,i){"use strict";if(!s.setImmediate){var n,r,a,o,l=1,c={},p=!1,u=s.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(s);h=h&&h.setTimeout?h:s,n={}.toString.call(s.process)==="[object process]"?function(y){process.nextTick(function(){m(y)})}:function(){if(s.postMessage&&!s.importScripts){var y=!0,b=s.onmessage;return s.onmessage=function(){y=!1},s.postMessage("","*"),s.onmessage=b,y}}()?(o="setImmediate$"+Math.random()+"$",s.addEventListener?s.addEventListener("message",v,!1):s.attachEvent("onmessage",v),function(y){s.postMessage(o+y,"*")}):s.MessageChannel?((a=new MessageChannel).port1.onmessage=function(y){m(y.data)},function(y){a.port2.postMessage(y)}):u&&"onreadystatechange"in u.createElement("script")?(r=u.documentElement,function(y){var b=u.createElement("script");b.onreadystatechange=function(){m(y),b.onreadystatechange=null,r.removeChild(b),b=null},r.appendChild(b)}):function(y){setTimeout(m,0,y)},h.setImmediate=function(y){typeof y!="function"&&(y=new Function(""+y));for(var b=new Array(arguments.length-1),k=0;k<b.length;k++)b[k]=arguments[k+1];var T={callback:y,args:b};return c[l]=T,n(l),l++},h.clearImmediate=f}function f(y){delete c[y]}function m(y){if(p)setTimeout(m,0,y);else{var b=c[y];if(b){p=!0;try{(function(k){var T=k.callback,I=k.args;switch(I.length){case 0:T();break;case 1:T(I[0]);break;case 2:T(I[0],I[1]);break;case 3:T(I[0],I[1],I[2]);break;default:T.apply(i,I)}})(b)}finally{f(y),p=!1}}}}function v(y){y.source===s&&typeof y.data=="string"&&y.data.indexOf(o)===0&&m(+y.data.slice(o.length))}})(typeof self>"u"?e===void 0?this:e:self)}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})});var gn={};$e(gn,{default:()=>ks});module.exports=Wi(gn);var et=require("obsidian");Tt();var Ct=require("obsidian");var wt=require("obsidian");Tt();function Re(g){let d=(g.dateDisplayTimezone||"").trim();return d?{timeZone:d}:{}}function Nt(g,d){try{return new Intl.DateTimeFormat(void 0,d).format(new Date(g))}catch{let{timeZone:t,...e}=d;return new Intl.DateTimeFormat(void 0,e).format(new Date(g))}}function Kt(g,d){let t=Re(d);switch(d.dateDisplayFormat??"locale"){case"iso":return ii(g,d,!0);case"us":return Nt(g,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Nt(g,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Nt(g,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Nt(g,{...t,dateStyle:"medium",timeStyle:"short"})}}function ei(g,d){let t=Re(d);switch(d.dateDisplayFormat??"locale"){case"iso":return ii(g,d,!1);case"us":return Nt(g,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Nt(g,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Nt(g,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,s=new Date(g).getFullYear()===e.getFullYear();return Nt(g,s?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function si(g,d){let t=Re(d),e=d.dateDisplayFormat==="iso"||d.dateDisplayFormat==="eu";return Nt(g,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function ii(g,d,t){let e=Re(d),s=new Intl.DateTimeFormat("en-CA",{...e,year:"numeric",month:"2-digit",day:"2-digit",...t?{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}:{}}).formatToParts(new Date(g)),i=r=>s.find(a=>a.type===r)?.value??"",n=`${i("year")}-${i("month")}-${i("day")}`;return t?`${n} ${i("hour")}:${i("minute")}`:n}function We(g,d,t){let e=g.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(d>99?"99+":String(d))}var Ie={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},je=class extends wt.ItemView{constructor(t,e){super(t);this.plugin=e;this.activePanel="pinned";this.taskFilter="all";this.taskAssignFilter="all";this.expanded=new Set;this.renderTimer=null;this.sharedAuthorFilter="all";this.sharedContribOnly=!1}setActivePanel(t){this.activePanel=t,this.containerEl.isConnected&&this.render()}getViewType(){return Rt}getDisplayText(){return"Stashpad panels"}getIcon(){return"panel-left"}async onOpen(){this.render(),this.registerEvent(this.app.metadataCache.on("changed",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("rename",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("delete",()=>this.scheduleRender())),this.registerEvent(this.app.workspace.on("active-leaf-change",t=>{t&&t.view.getViewType()===mt&&this.scheduleRender()}))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},80))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-panels-root");let e=t.createDiv({cls:"stashpad-panels-globals"}),s=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,wt.setIcon)(s.createSpan({cls:"stashpad-panels-global-btn-icon"}),"search"),s.createSpan({cls:"stashpad-panels-global-btn-text",text:"Search"}),s.onclick=()=>this.openSearchFromPanel();let i=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,wt.setIcon)(i.createSpan({cls:"stashpad-panels-global-btn-icon"}),"folder-tree"),i.createSpan({cls:"stashpad-panels-global-btn-text",text:"Folder Switcher"}),i.onclick=()=>this.plugin.openFolderPicker();let n=e.createDiv({cls:"stashpad-panels-globals-row"}),r=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,wt.setIcon)(r.createSpan({cls:"stashpad-panels-global-btn-icon"}),"scroll-text"),r.createSpan({cls:"stashpad-panels-global-btn-text",text:"Log"}),r.onclick=()=>this.openLogFromPanel();let a=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,wt.setIcon)(a.createSpan({cls:"stashpad-panels-global-btn-icon"}),"bell"),a.createSpan({cls:"stashpad-panels-global-btn-text",text:"Notifications"}),a.onclick=()=>this.openNotificationsFromPanel();let o=t.createDiv({cls:"stashpad-panels-bar"});for(let c of Object.keys(Ie)){let p=Ie[c],u=o.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,wt.setIcon)(u.createSpan({cls:"stashpad-panels-bar-btn-icon"}),p.icon),u.createSpan({cls:"stashpad-panels-bar-btn-text",text:p.label}),this.activePanel===c&&u.addClass("is-active"),u.onclick=()=>{this.activePanel!==c&&(this.activePanel=c,this.render())}}let l=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(l):this.activePanel==="shared"?this.renderSharedPanel(l):this.activePanel==="tasks"&&this.renderTasksPanel(l)}renderPinnedPanel(t){let e=t.createDiv({cls:"stashpad-panel-pinned"}),s=e.createEl("button",{cls:"stashpad-pinned-row stashpad-pinned-home"}),i=s.createSpan({cls:"stashpad-pinned-icon"});(0,wt.setIcon)(i,"home"),s.createSpan({cls:"stashpad-pinned-label",text:"Home"}),s.onclick=()=>this.openHomeFromPanel();let n=this.plugin.settings.pinnedNotes??[];if(n.length===0){e.createDiv({cls:"stashpad-pinned-empty"}).setText("No pinned notes yet \u2014 right-click a note and choose \u201CPin to sidebar.\u201D");return}let r=new Map;n.forEach((l,c)=>{let p=r.get(l.folder);p||(p=[],r.set(l.folder,p)),p.push({pin:l,idx:c})});let a=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,o=Array.from(r.keys());a&&r.has(a)&&(o.splice(o.indexOf(a),1),o.unshift(a));for(let l of o){let c=l.split("/").pop()||l,p=e.createDiv({cls:"stashpad-pinned-group-header"});l===a&&p.addClass("is-active-folder"),p.createSpan({cls:"stashpad-pinned-group-name",text:c});let u=r.get(l)??[];for(let{pin:h,idx:f}of u)this.renderPinnedRow(e,h,f)}}renderPinnedRow(t,e,s){let i=this.findFileFor(e);if(!i)return;let n=this.app.metadataCache.getFileCache(i)?.frontmatter??{},r=this.titleFromFile(i),a=typeof n.color=="string"?n.color:null,o=n.completed===!0,l=this.childrenOf(e.folder,e.id).length,c=l>0,p=this.expanded.has(`${e.folder}|${e.id}`),u=t.createDiv({cls:"stashpad-pinned-row"});a&&u.addClass("has-color"),o&&u.addClass("is-completed"),u.draggable=!0,u.dataset.pinIdx=String(s),u.addEventListener("dragstart",y=>{y.dataTransfer?.setData("text/plain",String(s)),y.dataTransfer&&(y.dataTransfer.effectAllowed="move"),u.addClass("is-dragging")}),u.addEventListener("dragend",()=>u.removeClass("is-dragging")),u.addEventListener("dragover",y=>{y.preventDefault(),y.dataTransfer&&(y.dataTransfer.dropEffect="move");let b=u.getBoundingClientRect(),k=y.clientY-b.top<b.height/2;u.toggleClass("drop-before",k),u.toggleClass("drop-after",!k)}),u.addEventListener("dragleave",()=>{u.removeClass("drop-before"),u.removeClass("drop-after")}),u.addEventListener("drop",y=>{y.preventDefault(),u.removeClass("drop-before"),u.removeClass("drop-after");let b=parseInt(y.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(b)||b===s)return;let k=u.getBoundingClientRect(),T=y.clientY-k.top<k.height/2;this.reorderPin(b,T?s:s+1)});let h=u.createSpan({cls:"stashpad-pinned-toggle"});c&&(We(h,l,p),h.onclick=y=>{y.stopPropagation();let b=`${e.folder}|${e.id}`;this.expanded.has(b)?this.expanded.delete(b):this.expanded.add(b),this.render()});let f=u.createSpan({cls:"stashpad-pinned-icon"});(0,wt.setIcon)(f,c?"folder-tree":"file-text"),a&&(f.style.color=a);let m=u.createSpan({cls:"stashpad-pinned-label",text:r});m.onclick=()=>this.openPinFromPanel(e);let v=e.folder.split("/").pop()||e.folder;if(u.createSpan({cls:"stashpad-pinned-folder",text:v}),u.oncontextmenu=y=>{y.preventDefault();let b=new wt.Menu;b.addItem(k=>k.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),b.showAtMouseEvent(y)},c&&p){let y=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(y,e.folder,e.id,1)}}async reorderPin(t,e){let s=(this.plugin.settings.pinnedNotes??[]).slice();if(t<0||t>=s.length)return;let[i]=s.splice(t,1),n=e>t?e-1:e;s.splice(Math.max(0,Math.min(n,s.length)),0,i),this.plugin.settings.pinnedNotes=s,await this.plugin.saveSettings(),this.render()}renderPinnedSubtree(t,e,s,i){let n=this.childrenOf(e,s);for(let r of n){let a=this.app.metadataCache.getFileCache(r)?.frontmatter??{},o=typeof a.id=="string"?a.id:null;if(!o)continue;let l=typeof a.color=="string"?a.color:null,c=a.completed===!0,p=this.childrenOf(e,o).length,u=p>0,h=this.expanded.has(`${e}|${o}`),f=t.createDiv({cls:"stashpad-pinned-subrow"});c&&f.addClass("is-completed"),f.style.paddingLeft=`${i*16}px`;let m=f.createSpan({cls:"stashpad-pinned-toggle"});u&&(We(m,p,h),m.onclick=b=>{b.stopPropagation();let k=`${e}|${o}`;this.expanded.has(k)?this.expanded.delete(k):this.expanded.add(k),this.render()});let v=f.createSpan({cls:"stashpad-pinned-icon"});(0,wt.setIcon)(v,"file-text"),l&&(v.style.color=l);let y=f.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(r)});y.onclick=()=>this.openPinFromPanel({folder:e,id:o}),u&&h&&this.renderPinnedSubtree(t,e,o,i+1)}}findFileFor(t){for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==t.folder)continue;if(this.app.metadataCache.getFileCache(e)?.frontmatter?.id===t.id)return e}return null}childrenOf(t,e){let s=[];for(let i of this.app.vault.getMarkdownFiles()){if((i.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let r=this.app.metadataCache.getFileCache(i)?.frontmatter;if(!r||typeof r.id!="string")continue;let a=r.parent;if(a===e||e===R&&(a==null||a===R)){if(r.id===R)continue;s.push(i)}}return s.sort((i,n)=>{let r=this.app.metadataCache.getFileCache(i)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,o=r?.created??"",l=a?.created??"";return o.localeCompare(l)}),s}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}async openSearchFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.openSearchModal=="function"&&t.openSearchModal()}async openLogFromPanel(){let t=this.app.vault.adapter,e=this.plugin.pluginPrivatePath("log.jsonl");if(!await t.exists(e)){new wt.Notice("No log yet \u2014 make some changes first.");return}let s=await t.read(e),{LogModal:i}=await Promise.resolve().then(()=>(Ht(),Ee));new i(this.app,s,e).open()}openNotificationsFromPanel(){this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")}async openHomeFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.navigateTo=="function"&&t.navigateTo(R)}async openPinFromPanel(t){await this.plugin.activateViewForFolder(t.folder);let e=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();e&&typeof e.navigateTo=="function"&&e.navigateTo(t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===mt)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let s=this.app.workspace.getLeavesOfType(mt);return s.length>0?(this.app.workspace.revealLeaf(s[0]),s[0].view):(await this.plugin.activateView({reveal:!0}),this.findActiveStashpad())}findActiveStashpad(){let t=this.app.workspace.activeLeaf;return t&&t.view.getViewType()===mt?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),s=(this.plugin.settings.authorId??"").trim();if(!s){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let i=this.collectSharedNotes(s),n=new Map;for(let c of i){let p=c.authorId;p&&!n.has(p)&&n.set(p,c.authorDisplay||p)}let r=e.createDiv({cls:"stashpad-shared-filters"}),a=(c,p,u)=>{let h=r.createEl("button",{cls:"stashpad-shared-chip",text:c});return p&&h.addClass("is-active"),h.onclick=u,h};if(a("All",this.sharedAuthorFilter==="all",()=>{this.sharedAuthorFilter="all",this.render()}),a("Mine",this.sharedAuthorFilter==="mine",()=>{this.sharedAuthorFilter="mine",this.render()}),a("Others",this.sharedAuthorFilter==="others",()=>{this.sharedAuthorFilter="others",this.render()}),n.size>1){let c=r.createEl("select",{cls:"stashpad-shared-author-select"}),p=c.createEl("option",{text:"Any author"});p.value="__any__";for(let[h,f]of n){let m=c.createEl("option",{text:f});m.value=h}let u=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;c.value=u,c.onchange=()=>{let h=c.value;h==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=h,this.render()}}let o=r.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&o.addClass("is-active"),o.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let l=i.filter(c=>{if(this.sharedContribOnly&&c.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return c.authorId===s;case"others":return c.authorId!==s;default:return c.authorId===this.sharedAuthorFilter}});if(l.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let c of l){let p=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),u=p.createSpan({cls:"stashpad-pinned-icon"});(0,wt.setIcon)(u,"users"),c.color&&(u.style.color=c.color);let h=p.createSpan({cls:"stashpad-pinned-label",text:c.title});h.onclick=()=>this.openSharedFromPanel(c.folder,c.id);let f=c.folder.split("/").pop()||c.folder;p.createSpan({cls:"stashpad-pinned-folder",text:f}),c.authorDisplay&&p.createSpan({cls:"stashpad-shared-meta"}).setText(c.authorId===s?`you \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:`by ${c.authorDisplay}${c.contributorCount>0?` \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:""}`)}}collectSharedNotes(t){let e=this.plugin.discoverStashpadFolders(),s=new Set(e),i=new Map;for(let r of this.app.vault.getMarkdownFiles()){let a=r.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(a))continue;let o=this.app.metadataCache.getFileCache(r)?.frontmatter??{};o.id===R&&i.set(a,this.extractAuthorId(o.author))}let n=[];for(let r of this.app.vault.getMarkdownFiles()){let a=r.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(a)||a.endsWith("/_authors")||r.path.includes("/_authors/"))continue;let o=this.app.metadataCache.getFileCache(r)?.frontmatter??{};if(typeof o.id!="string"||o.id===R)continue;let l=this.extractAuthorId(o.author),c=Array.isArray(o.contributors)?o.contributors.filter(b=>typeof b=="string"):[],p=i.get(a)??null;if(!(c.length>0||p===t&&(l!==null&&l!==t)))continue;let v=this.titleFromFile(r),y=typeof o.color=="string"?o.color:null;n.push({file:r,folder:a,id:o.id,title:v,color:y,authorId:l,authorDisplay:this.extractAuthorDisplay(o.author)||(l??""),contributorCount:c.length})}return n.sort((r,a)=>{let o=this.app.metadataCache.getFileCache(r.file)?.frontmatter??{},l=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},c=o.modified??o.created??"";return(l.modified??l.created??"").localeCompare(c)}),n}extractAuthorId(t){if(typeof t!="string")return null;let e=t.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return e?e[1]:null}extractAuthorDisplay(t){if(typeof t!="string")return"";let e=t.match(/\|([^\]]+)\]\]/);if(e)return e[1].trim();let s=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return s?s[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.activateViewForFolder(t);let s=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();s&&typeof s.navigateTo=="function"&&s.navigateTo(e)}renderTasksPanel(t){let e=t.createDiv({cls:"stashpad-panel-tasks"}),s=this.collectTasks();if(s.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks yet \u2014 press H on a note to mark it a task, or D to give it a due date.");return}let i=(this.plugin.settings.authorId??"").trim(),n=C=>!!i&&C.assignedTo.some(A=>A.id===i),r=C=>{let A=this.taskAssignFilter;if(A.startsWith("person:")){let S=A.slice(7);return C.assignedTo.some(_=>_.id===S)}switch(A){case"mine":return n(C);case"others":return C.assignedTo.length>0&&!n(C);case"byme":return!!i&&C.assignedBy?.id===i;case"unassigned":return C.assignedTo.length===0;default:return!0}},a=new Map;for(let C of s){for(let A of C.assignedTo)A.id!==i&&a.set(A.id,A.name);C.assignedBy&&C.assignedBy.id!==i&&a.set(C.assignedBy.id,C.assignedBy.name)}let o=[...a.entries()].map(([C,A])=>({id:C,name:A})).sort((C,A)=>C.name.localeCompare(A.name)),l=e.createDiv({cls:"stashpad-task-assign-bar"});l.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let c=l.createEl("select",{cls:"stashpad-task-assign-select"}),p=C=>{let A={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return C.startsWith("person:")?a.get(C.slice(7))??"Person":A[C]??C},u=C=>{let A=c.createEl("option",{text:p(C),value:C});this.taskAssignFilter===C&&(A.selected=!0)};for(let C of["all","mine","others","byme","unassigned"])u(C);if(o.length>0){let C=c.createEl("optgroup");C.setAttr("label","By person");for(let A of o){let S=C.createEl("option",{text:A.name,value:`person:${A.id}`});this.taskAssignFilter===`person:${A.id}`&&(S.selected=!0)}}c.onchange=()=>{this.taskAssignFilter=c.value,this.render()};let h=s.filter(r);if(h.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`No tasks match "${p(this.taskAssignFilter)}".`);return}let f=new Date;f.setHours(0,0,0,0);let m=f.getTime(),v=m+24*60*60*1e3,y={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let C of h){if(C.completed){y.completed.push(C);continue}if(C.due==null){y.nodate.push(C);continue}C.due<m?y.overdue.push(C):C.due<v?y.today.push(C):y.upcoming.push(C)}let b=(C,A)=>C.due==null&&A.due==null?C.title.localeCompare(A.title):C.due==null?1:A.due==null?-1:C.due-A.due,k=[{key:"overdue",label:"Overdue",icon:"alert-circle"},{key:"today",label:"Due today",icon:"calendar-clock"},{key:"upcoming",label:"Upcoming",icon:"calendar"},{key:"nodate",label:"No date",icon:"inbox"},{key:"completed",label:"Completed",icon:"check-circle-2"}],T=e.createDiv({cls:"stashpad-task-filters"}),I=h.length,E=(C,A,S)=>{let _=T.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===C&&_.addClass("is-active"),_.createSpan({cls:"stashpad-task-filter-label",text:A}),_.createSpan({cls:"stashpad-task-filter-count",text:String(S)}),_.onclick=()=>{this.taskFilter=C,this.render()}};E("all","All",I),E("overdue","Overdue",y.overdue.length),E("today","Today",y.today.length),E("upcoming","Upcoming",y.upcoming.length),E("nodate","No date",y.nodate.length),E("completed","Done",y.completed.length);let D=this.taskFilter==="all"?k:k.filter(C=>C.key===this.taskFilter),H=!1;for(let C of D){let A=y[C.key];if(A.length!==0){if(H=!0,A.sort(C.key==="completed"?(S,_)=>b(_,S):b),this.taskFilter==="all"){let S=e.createDiv({cls:`stashpad-task-section-header is-${C.key}`});(0,wt.setIcon)(S.createSpan({cls:"stashpad-task-section-icon"}),C.icon),S.createSpan({cls:"stashpad-task-section-name",text:C.label}),S.createSpan({cls:"stashpad-task-section-count",text:String(A.length)})}for(let S of A)this.renderTaskRow(e,S,C.key==="today")}}if(!H&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${D[0]?.label??this.taskFilter}".`);return}H||e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks to show.")}renderTaskRow(t,e,s){let i=t.createDiv({cls:"stashpad-pinned-row stashpad-task-row"});e.color&&i.addClass("has-color"),e.completed&&i.addClass("is-completed");let n=i.createSpan({cls:"stashpad-pinned-icon stashpad-task-checkbox"});(0,wt.setIcon)(n,e.completed?"check-square":"square"),e.color&&(n.style.color=e.color),n.title=e.completed?"Mark not done":"Mark done",n.onclick=a=>{a.stopPropagation(),this.toggleTaskCompleted(e)};let r=i.createSpan({cls:"stashpad-pinned-label",text:e.title});if(r.onclick=()=>this.openTaskFromPanel(e.folder,e.id),i.createSpan({cls:"stashpad-task-folder",text:e.folder.split("/").pop()||e.folder}),e.due!=null){let a=i.createSpan({cls:"stashpad-task-due",text:this.formatDueShort(e.due,s)});e.due<Date.now()&&!e.completed&&a.addClass("is-overdue")}else e.dueRaw&&i.createSpan({cls:"stashpad-task-due",text:e.dueRaw});if(e.assignedTo.length>0){let a=(this.plugin.settings.authorId??"").trim(),o=i.createSpan({cls:"stashpad-task-assignees"});for(let l of e.assignedTo){let c=o.createSpan({cls:"stashpad-task-assignee"});a&&l.id===a&&c.addClass("is-me"),c.setText(this.initials(l.name)),c.title=a&&l.id===a?`${l.name} (you)`:l.name}}i.oncontextmenu=a=>{a.preventDefault();let o=new wt.Menu;o.addItem(l=>l.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),o.showAtMouseEvent(a)}}formatDueShort(t,e){return e?si(t,this.plugin.settings):ei(t,this.plugin.settings)}async openTaskFromPanel(t,e){await this.plugin.activateViewForFolder(t);let s=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();s&&typeof s.navigateTo=="function"&&s.navigateTo(e)}async toggleTaskCompleted(t){try{await this.app.fileManager.processFrontMatter(t.file,e=>{e.completed=e.completed!==!0})}catch(e){new wt.Notice(`Couldn't update task: ${e.message}`);return}this.scheduleRender()}initials(t){let e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[e.length-1][0]).toUpperCase()}collectTasks(){let t=this.plugin.discoverStashpadFolders(),e=new Set(t),s=[];for(let i of this.app.vault.getMarkdownFiles()){let n=i.parent?.path?.replace(/\/+$/,"")??"";if(!e.has(n))continue;let r=this.app.metadataCache.getFileCache(i)?.frontmatter??{},a=typeof r.id=="string"?r.id:null;if(!a||a===R)continue;let o=r.completed===!0,l=Yt(r,"task")||r.task===!0||r.completed!==void 0,c=typeof r.due=="string"||typeof r.due=="number"?String(r.due):null,p=null;if(c){let u=Date.parse(c);Number.isNaN(u)||(p=u)}!l&&!o&&p==null&&!c||s.push({file:i,folder:n,id:a,title:this.titleFromFile(i),task:l,completed:o,due:p,dueRaw:c,color:typeof r.color=="string"?r.color:null,assignedTo:be(r),assignedBy:we(r.assignedBy)})}return s}};async function Ue(g){let d=g.workspace.getLeavesOfType(Rt);if(d.length>0){g.workspace.revealLeaf(d[0]);return}let t=g.workspace.getLeftLeaf(!1);if(!t){new wt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:Rt,active:!0}),g.workspace.revealLeaf(t)}var vi=require("obsidian");Tt();var G=require("obsidian");De();var Ke=require("obsidian");Tt();var le=class extends Ke.AbstractInputSuggest{constructor(t,e){super(t,e);this.inputEl=e}getSuggestions(t){let e=t.toLowerCase().split(/\s+/).filter(Boolean),s=r=>e.every(a=>r.toLowerCase().includes(a)),i=[],n=r=>{if(!(r.path!=="/"&&ve.has(r.name))){r.path!=="/"&&s(r.path)&&i.push(r);for(let a of r.children)a instanceof Ke.TFolder&&n(a)}};return n(this.app.vault.getRoot()),i.slice(0,100)}renderSuggestion(t,e){e.setText(t.path)}selectSuggestion(t){this.setValue(t.path),this.inputEl.dispatchEvent(new Event("input",{bubbles:!0})),this.close()}};Tt();Ht();var Xt=require("obsidian"),_s={create:{label:"Create",desc:"Confirmations after a new note is created."},edit:{label:"Edit",desc:"Edit-related toasts (currently rare)."},delete:{label:"Delete",desc:"Confirmations after deleting one or more notes."},move:{label:"Move",desc:"After reparenting or moving notes between folders."},merge:{label:"Merge",desc:"After combining multiple notes into one."},split:{label:"Split",desc:"After splitting a note in two."},clone:{label:"Clone",desc:"After duplicating notes or subtrees."},complete:{label:"Complete",desc:"When a note is marked complete."},uncomplete:{label:"Uncomplete",desc:"When a note's complete mark is removed."},export:{label:"Export",desc:".stash exports \u2014 success + the action buttons."},import:{label:"Import",desc:".stash imports (both manual and the drop-folder auto-import)."},attachment:{label:"Attachment",desc:"Attachment add / remove notifications."},color:{label:"Color",desc:"Per-note color changes."},reorder:{label:"Reorder",desc:"Drag-reorder and keyboard moveUp/Down/Top/Bottom."},multiplayer:{label:"Multiplayer",desc:"Cross-author activity (someone else touched your notes or vice versa)."},system:{label:"System",desc:"Plumbing toasts: backfill progress, integrity warnings, errors not tied to a verb."}},Zi={info:4e3,success:4e3,warning:6e3,error:1e4},hi=5e3,Ze=class{constructor(d){this.app=d;this.history=[];this.nextId=1;this.historyLimit=hi;this.changeListeners=new Set;this.muted=new Set;this.defaultAuthorId=null}setDefaultAuthorId(d){this.defaultAuthorId=d||null}show(d){let t=d.kind??"info",e=d.category??"system",s={id:this.nextId++,ts:Date.now(),message:d.message,kind:t,category:e,authorId:d.authorId??this.defaultAuthorId??void 0,affectedIds:d.affectedIds?d.affectedIds.slice():[],affectedPaths:d.affectedPaths?d.affectedPaths.slice():[],affectedAuthorIds:d.affectedAuthorIds?d.affectedAuthorIds.slice():[],folder:d.folder,actionLabels:(d.actions??[]).map(r=>r.label)};if(this.pushHistory(s),this.muted.has(e))return null;let i=this.buildContent(d,t),n=d.duration??Zi[t];return new Xt.Notice(i,n)}onChange(d){return this.changeListeners.add(d),()=>this.changeListeners.delete(d)}recent(){return this.history.slice().reverse()}clearHistory(){this.history=[],this.emit()}setMuted(d,t){t?this.muted.add(d):this.muted.delete(d)}isMuted(d){return this.muted.has(d)}loadMutedFromList(d){this.muted=new Set(d)}mutedList(){return Array.from(this.muted)}loadHistory(d){let t=this.applyLimit(d.slice());this.history=t;let e=0;for(let s of t)s.id>e&&(e=s.id);this.nextId=Math.max(this.nextId,e+1),this.emit()}setHistoryLimit(d){this.historyLimit=Number.isFinite(d)?d:hi,this.history=this.applyLimit(this.history),this.emit()}applyLimit(d){return this.historyLimit<=0||d.length<=this.historyLimit?d:d.slice(d.length-this.historyLimit)}pushHistory(d){this.history.push(d),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let d of this.changeListeners)try{d()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(d,t){let e=document.createDocumentFragment(),s=document.createElement("div");s.className=`stashpad-notice stashpad-notice-${t}`;let i=document.createElement("div");i.className="stashpad-notice-message";let n=d.message.split(/(`[^`\n]+`)/);for(let r of n)if(r.length>1&&r.startsWith("`")&&r.endsWith("`")){let a=document.createElement("code");a.textContent=r.slice(1,-1),i.appendChild(a)}else r.length>0&&i.appendChild(document.createTextNode(r));if(s.appendChild(i),d.actions&&d.actions.length>0){let r=document.createElement("div");r.className="stashpad-notice-actions";for(let a of d.actions){let o=document.createElement("button");o.className="stashpad-notice-action",o.textContent=a.label,o.addEventListener("click",l=>{if(l.stopPropagation(),Promise.resolve().then(()=>a.onClick()).catch(c=>console.warn("[Stashpad] notification action failed",c)),!a.keepOpen){let c=o.closest(".notice");c&&c.parentElement&&c.parentElement.removeChild(c)}}),r.appendChild(o)}s.appendChild(r)}return e.appendChild(s),e}};function Ge(g,d,t){let e=g.vault.getAbstractFileByPath(d);if(!(e instanceof Xt.TFile))return[];let s=[{label:"Reveal",keepOpen:!0,onClick:()=>{let i=g.workspace.getLeavesOfType("file-explorer")[0];if(!i)return;g.workspace.revealLeaf(i),i.view?.revealInFolder?.(e)}}];if(!t){let i=Xt.Platform.isMacOS?"Finder":Xt.Platform.isWin?"File Explorer":"file manager";s.push({label:`Show in ${i}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=g.vault.adapter?.getFullPath?.(d);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return s}var Ls=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function Ns(g){if(!g)return"(none)";let d=g.replace(/\bMod\b/g,Ls?"Cmd":"Ctrl");return Ls&&(d=d.replace(/\bAlt\b/g,"Option")),d}function pi(g,d,t={allowSingleKey:!0}){let e=g.placeholder,s=g.value;g.placeholder="Press a key\u2026 (Backspace to cancel)",g.value="",g.classList.add("is-recording");let i=!1,n=()=>{g.placeholder=e,g.classList.remove("is-recording"),i||(g.value=s),g.removeEventListener("keydown",r,!0),g.removeEventListener("blur",a)},r=o=>{if(o.key==="Control"||o.key==="Shift"||o.key==="Alt"||o.key==="Meta"||o.key==="OS")return;let l=!!o.code&&(/^Key[A-Z]$/.test(o.code)||/^Digit\d$/.test(o.code));if((o.key==="Dead"||o.key==="Process"||o.key==="Unidentified")&&!l)return;if(o.preventDefault(),o.stopPropagation(),o.key==="Backspace"&&!o.metaKey&&!o.ctrlKey&&!o.altKey&&!o.shiftKey){n();return}let c=[];Ls?(o.metaKey&&c.push("Mod"),o.ctrlKey&&c.push("Ctrl")):o.ctrlKey&&c.push("Mod"),o.altKey&&c.push("Alt"),o.shiftKey&&c.push("Shift");let p=Gi(o.key,o.code);if(!p||c.length===0&&!t.allowSingleKey)return;c.push(p);let u=c.join("+");i=!0,n(),d(u)},a=()=>n();return g.addEventListener("keydown",r,!0),g.addEventListener("blur",a),n}function Gi(g,d){if(!g)return"";if(d){let t=/^Key([A-Z])$/.exec(d);if(t)return t[1];let e=/^Digit(\d)$/.exec(d);if(e)return e[1]}return g.length===1?g.toUpperCase():g}ae();Mt();var Pe=null,Je=new Set;function Xe(g){if(Pe!==g){Pe=g;for(let d of Je)d()}}function Ot(){return Pe}function ui(g){if(Pe===g){Pe=null;for(let d of Je)d()}}function fi(g){return Je.add(g),()=>Je.delete(g)}function Ji(){return G.Platform.isMacOS?"Finder":G.Platform.isWin?"File Explorer":"file manager"}var Me=[{id:"move",label:"Move (picker)",desc:"Open a fuzzy picker to choose the new parent.",defaultPrimary:"M"},{id:"pickMove",label:"Move (in-list)",desc:"Highlight a note in the list with arrows; Enter sets it as parent.",defaultPrimary:"O"},{id:"merge",label:"Merge",desc:"Concatenate selected notes into the oldest one.",defaultPrimary:"&"},{id:"copy",label:"Copy",desc:"Copy selected note bodies to clipboard.",defaultPrimary:"C"},{id:"copyTree",label:"Copy tree",desc:"Copy the focused note + all descendants, indented.",defaultPrimary:"Y"},{id:"openEditor",label:"Open in editor",desc:"Open the cursor row (or focused note) in a regular Obsidian markdown tab.",defaultPrimary:"E"},{id:"openTab",label:"Open in new Stashpad tab",desc:"Open the cursor row (or focused note) in a new Stashpad tab focused on it.",defaultPrimary:"T"},{id:"split",label:"Split note",desc:"Split the cursor row (or focused note) into two notes at a chosen line.",defaultPrimary:"S"},{id:"copyOutline",label:"Copy as outline",desc:"Copy selection (or cursor row) as a nested ![[embed]] outline.",defaultPrimary:"L"},{id:"toggleSplit",label:"Toggle split-on-newlines",desc:"Default: Mod+/",defaultPrimary:"Mod+/"},{id:"pickDestination",label:"Pick destination",desc:"Default: Mod+D",defaultPrimary:"Mod+D"},{id:"search",label:"Search notes",desc:"Default: Mod+F",defaultPrimary:"Mod+F"},{id:"searchInParent",label:"Search in current parent",desc:"Default: Mod+Alt+F (Mod+Shift+F is taken by Obsidian's global search).",defaultPrimary:"Mod+Alt+F"},{id:"delete",label:"Delete selection",desc:"Default: Mod+Backspace",defaultPrimary:"Mod+Backspace"},{id:"undo",label:"Undo",desc:"Default: Mod+Z (Stashpad-only \u2014 won't fire while typing in the composer).",defaultPrimary:"Mod+Z"},{id:"redo",label:"Redo",desc:"Default: Mod+Shift+Z",defaultPrimary:"Mod+Shift+Z"},{id:"toggleComplete",label:"Toggle complete (strikethrough)",desc:"Default: Mod+Enter \u2014 marks selected/focused notes as complete.",defaultPrimary:"Mod+Enter"},{id:"moveUp",label:"Move note up",desc:"Default: Mod+ArrowUp",defaultPrimary:"Mod+ArrowUp"},{id:"moveDown",label:"Move note down",desc:"Default: Mod+ArrowDown",defaultPrimary:"Mod+ArrowDown"},{id:"moveToTop",label:"Move note to top",desc:"Default: Mod+Shift+ArrowUp",defaultPrimary:"Mod+Shift+ArrowUp"},{id:"moveToBottom",label:"Move note to bottom",desc:"Default: Mod+Shift+ArrowDown",defaultPrimary:"Mod+Shift+ArrowDown"},{id:"outdent",label:"Outdent (move to grandparent)",desc:"Default: Mod+[ \u2014 re-parents the selection one level up.",defaultPrimary:"Mod+["},{id:"setColor",label:"Set note color",desc:"Default: Shift+: \u2014 open the color picker for the selection.",defaultPrimary:"Shift+:"},{id:"clone",label:"Clone (duplicate / copy) selection",desc:"Default: Mod+Shift+D \u2014 clone selected notes (with their subtrees) as siblings.",defaultPrimary:"Mod+Shift+D"},{id:"insertTemplate",label:"Insert template (clone an existing note)",desc:"Pick any note in this Stashpad; clone it (with subtree + attachments) into the current view, retimestamped.",defaultPrimary:""},{id:"toggleExpand",label:"Show more / show less (expand toggle)",desc:"Default: Shift+? \u2014 toggle the clamp on the cursor row (or every selected row).",defaultPrimary:"Shift+?"},{id:"exportStash",label:"Export selection to .stash",desc:"Export the selected subtree(s) as a .stash bundle (notes + attachments).",defaultPrimary:""},{id:"importStash",label:"Import .stash file",desc:"Open the .stash bundle picker and import its notes into this Stashpad.",defaultPrimary:""},{id:"pickFolder",label:"Open / switch / create Stashpad folder",desc:"Default: Mod+S \u2014 opens the unified folder picker (reveal, switch, create, convert).",defaultPrimary:"Mod+S"},{id:"cloneStashpadTab",label:"Clone (duplicate / copy) this Stashpad tab",desc:'Open a second tab on the same folder + focus, mirroring the "copy" button in the focused-header actions.',defaultPrimary:""},{id:"selectAll",label:"Select all notes in view",desc:"Default: Mod+A \u2014 adds every visible row to the selection.",defaultPrimary:"Mod+A"},{id:"copyCodeBlock",label:"Copy code from codeblock",desc:"Default: { \u2014 copy the contents of the cursor row's first codeblock (or pick one when multiple exist).",defaultPrimary:"{"},{id:"swapWithParent",label:"Swap with parent (ouroboros)",desc:"Promote the cursor row above its current parent; the parent slides under it (carrying its other children). No default \u2014 bind in this tab.",defaultPrimary:""},{id:"togglePin",label:"Pin / unpin selected note",desc:"Default: P \u2014 toggle the sidebar pin state of the cursor row (or focused note).",defaultPrimary:"P"},{id:"toggleTask",label:"Toggle task (todo)",desc:"Default: H \u2014 mark the selection (or cursor row) as a task / todo, or clear it. Tasks appear in the Tasks panel.",defaultPrimary:"H"},{id:"setDue",label:"Set due date\u2026",desc:"Default: D \u2014 open a date+time picker to set (or clear) the due date on the selection. Setting a due date also marks the note as a task.",defaultPrimary:"D"},{id:"jumpToTop",label:"Jump to top of list",desc:"Default: Home \u2014 move the cursor to the first note in the current list.",defaultPrimary:"Home"},{id:"jumpToBottom",label:"Jump to bottom of list",desc:"Default: End \u2014 move the cursor to the last note in the current list.",defaultPrimary:"End"}];function $s(){let g={};for(let d of Me)g[d.id]={primary:d.defaultPrimary,secondary:"",preferRight:!1};return g}var zt={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,enablePerfProfiling:!1,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,pinnedNotes:[],hideMobileToolbarInStashpad:!0,slugStopWords:[],searchIncludedFolders:[],searchExcludedFolders:[],shortcuts:{move:"M",pickMove:"O",merge:"&",copy:"C",copyTree:"Y",openEditor:"E",openTab:"T",split:"S",copyOutline:"L"},mod:{toggleSplit:"Mod+/",pickDestination:"Mod+D",search:"Mod+F",delete:"Mod+Backspace",undo:"Mod+Z",redo:"Mod+Shift+Z",toggleComplete:"Mod+Enter",moveUp:"Mod+ArrowUp",moveDown:"Mod+ArrowDown",moveToTop:"Mod+Shift+ArrowUp",moveToBottom:"Mod+Shift+ArrowDown",outdent:"Mod+[",setColor:"Shift+:"},customPalette:[],colorAliases:{},noteTemplates:{},authorName:"",authorId:"",authorRole:"",authorDepartment:"",showAuthor:!0,showContributors:!0,showLastEdit:!0,viewModes:{},includeAttachmentsInEverything:{},hideChildlessNotes:{},hideCompletedNotes:{},attachmentsOnlyNotes:{},mutedNotificationCategories:[],notificationHistoryLimit:5e3,autoNavOnMoveIn:!1,autoNavOnMoveOut:!1,autoExpandCursorRow:!1,autoOpenDetailPanel:!1,doubleClickToFocus:!0,dateDisplayFormat:"locale",dateDisplayTimezone:"",jdIndexScope:"vault",jdIndexScopeFolder:"",jdIndexStashpadFolder:"",jdIndexFile:"Index",jdIndexIncludeStashpadFolders:!1,jdIndexSort:"natural",jdIndexHasBuilt:!1,drafts:{},lastSubmitted:{},bindings:$s()},mi=JSON.parse(JSON.stringify(zt)),Os=new Set;function St(){return mi}function Rs(g){mi=g;for(let d of Os)d()}function gi(g){return Os.add(g),()=>Os.delete(g)}function es(g){try{let d=g.internalPlugins?.plugins?.templates;if(!d?.enabled)return null;let t=d.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var Qe=[{id:"general",label:"General"},{id:"diagnostics",label:"Diagnostics"},{id:"authorship",label:"Authorship"},{id:"templates",label:"Templates"},{id:"jdindex",label:"JD Index"},{id:"hotkeys",label:"Hotkeys"}],ts=class extends G.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e;this.activeTab="general";this.searchQuery=""}openToTab(t){this.activeTab=t,this.searchQuery="",this.containerEl?.isShown?.()!==!1&&this.display()}focusSearchInput(){let t=this.containerEl?.querySelector(".stashpad-settings-search-input");t&&(t.focus(),t.setSelectionRange(t.value.length,t.value.length))}display(){let{containerEl:t}=this;t.empty(),t.addClass("stashpad-settings-tabbed"),t.createEl("h2",{text:"Stashpad",cls:"stashpad-settings-title"});let s=t.createDiv({cls:"stashpad-settings-search-wrap"}).createEl("input",{type:"text",placeholder:"Search settings\u2026",cls:"stashpad-settings-search-input"});s.value=this.searchQuery;let i=this.searchQuery.trim().length>0,n=t.createDiv({cls:"stashpad-settings-tabs"});i&&n.addClass("is-search-mode");for(let o of Qe){let l=n.createEl("button",{cls:"stashpad-settings-tab",text:o.label});!i&&this.activeTab===o.id&&l.addClass("is-active"),l.onclick=()=>{this.searchQuery="",this.activeTab=o.id,this.display()}}let r=t.createDiv({cls:"stashpad-settings-body"});if(i){for(let o of Qe){let l=r.createDiv({cls:"stashpad-settings-search-group"});l.createEl("h3",{text:o.label,cls:"stashpad-settings-search-group-header"});let c=l.createDiv();this.renderTabContent(c,o.id)}this.applySearchFilter(r)}else this.renderTabContent(r,this.activeTab);let a=i;s.oninput=()=>{this.searchQuery=s.value;let o=this.searchQuery.trim().length>0;if(o!==a){let l=s.selectionStart??s.value.length;this.display();let c=t.querySelector(".stashpad-settings-search-input");c&&(c.focus(),c.setSelectionRange(l,l));return}o&&this.applySearchFilter(r)},this.searchQuery&&setTimeout(()=>{s.focus(),s.setSelectionRange(s.value.length,s.value.length)},0)}applySearchFilter(t){let e=this.searchQuery.trim().toLowerCase();if(!e)return;let s=e.split(/\s+/).filter(Boolean),i=r=>s.every(a=>r.includes(a));t.querySelectorAll(".setting-item").forEach(r=>{let a=r.querySelector(".setting-item-name")?.textContent?.toLowerCase()??"",o=r.querySelector(".setting-item-description")?.textContent?.toLowerCase()??"";r.style.display=i(`${a} ${o}`)?"":"none"}),t.querySelectorAll(".stashpad-settings-search-group").forEach(r=>{let a=Array.from(r.querySelectorAll(".setting-item")).some(o=>o.style.display!=="none");r.style.display=a?"":"none"})}renderTabContent(t,e){switch(e){case"general":this.renderGeneralTab(t);break;case"diagnostics":this.renderDiagnosticsTab(t);break;case"authorship":this.renderAuthorshipSection(t);break;case"templates":this.renderTemplatesTab(t);break;case"jdindex":this.renderJdIndexSection(t);break;case"hotkeys":this.renderHotkeysTab(t);break}}renderDiagnosticsTab(t){new G.Setting(t).setName("Performance profiling").setDesc("Record timing for list rendering, body reads, and file writes. Turn on, use Stashpad normally (especially the slow operations), then run \u201CDump performance profile\u201D from the command palette and share the result. Off = zero overhead.").addToggle(r=>r.setValue(this.plugin.settings.enablePerfProfiling).onChange(async a=>{this.plugin.settings.enablePerfProfiling=a,await this.plugin.saveSettings()})),new G.Setting(t).setName("Open log file").setDesc("Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.").addButton(r=>r.setButtonText("Open log").onClick(async()=>{let a=this.app.vault.adapter,o=this.plugin.pluginPrivatePath("log.jsonl");if(!await a.exists(o)){new G.Notice("No log yet \u2014 make some changes first.");return}let l=await a.read(o);new ie(this.app,l,o).open()})),new G.Setting(t).setName("Notification history limit").setDesc("Maximum number of notifications kept in the persistent history. Set to 0 for unlimited (the file size grows with usage; expect a few hundred KB per ~5000 entries). Default: 5000.").addText(r=>r.setValue(String(this.plugin.settings.notificationHistoryLimit??5e3)).setPlaceholder("5000").onChange(async a=>{let o=parseInt(a,10);Number.isFinite(o)&&(this.plugin.settings.notificationHistoryLimit=o,this.plugin.notifications.setHistoryLimit(o),await this.plugin.saveSettings())}));let e=t.createEl("details",{cls:"stashpad-notif-mute-details"});e.createEl("summary",{text:"Mute notification categories"}),e.createDiv({cls:"stashpad-notif-mute-help"}).setText("Muted categories don't pop toasts but still appear in the history panel so you can review what was suppressed.");let i=new Set(this.plugin.settings.mutedNotificationCategories??[]),n=Object.keys(_s);for(let r of n){let a=_s[r];new G.Setting(e).setName(a.label).setDesc(a.desc).addToggle(o=>o.setValue(!i.has(r)).onChange(async l=>{let c=!l;c?i.add(r):i.delete(r),this.plugin.settings.mutedNotificationCategories=Array.from(i),this.plugin.notifications.setMuted(r,c),await this.plugin.saveSettings()}))}new G.Setting(t).setName("Notification history").setDesc("Browse the last 200 toasts. Filter by category. Live-updates as new notifications arrive. Muted categories still appear here so you can review what was suppressed.").addButton(r=>r.setButtonText("View notification history").onClick(()=>{new Fe(this.app,this.plugin.notifications,async a=>{let o=this.app.vault.adapter,l=this.plugin.pluginPrivatePath("log.jsonl");if(!await o.exists(l)){new G.Notice("No log yet \u2014 make some changes first.");return}let c=await o.read(l);new ie(this.app,c,l).open()},this.plugin.settings.authorId||null,a=>this.plugin.lookupNoteAuthorIds(a)).open()}))}renderGeneralTab(t){new G.Setting(t).setName("Stashpad notes folder").setDesc("Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.").addText(i=>{new le(this.app,i.inputEl),i.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async n=>{let r=(n||"").trim().replace(/^\/+|\/+$/g,"")||zt.folder,a=r.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(l=>(l??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(a)){new G.Notice(`"${r}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=r,await this.plugin.saveSettings()})}),new G.Setting(t).setName("Auto-import dropped files").setDesc("When on, any file you drop directly into a Stashpad folder is imported automatically: markdown becomes a note (the original is archived to .archive); other files move to _attachments with a note that links to them. Large drops ask for confirmation first.").addToggle(i=>i.setValue(this.plugin.settings.autoImport).onChange(async n=>{this.plugin.settings.autoImport=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Inherit Obsidian's excluded files").setDesc("Also hide files matching Obsidian's \u201CExcluded files\u201D list (Settings \u2192 Files & Links) from Stashpad's link autocomplete and file surfaces \u2014 so you manage exclusions in one place. Plugin-internal formats like .edtz are always excluded regardless.").addToggle(i=>i.setValue(this.plugin.settings.inheritObsidianExclusions).onChange(async n=>{this.plugin.settings.inheritObsidianExclusions=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Dedicated import subfolder (optional)").setDesc("Optional. A subfolder (relative to each Stashpad folder) where dropped .stash files auto-import. Leave blank to just drop files into the Stashpad folder itself (recommended). Suggested name: _imports.").addText(i=>i.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports (leave blank to use the folder root)").onChange(async n=>{this.plugin.settings.importDropFolder=(n||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})),new G.Setting(t).setName("Stash export subfolder").setDesc("Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.").addText(i=>i.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async n=>{let r=(n||"").trim().replace(/^\/+|\/+$/g,"")||zt.exportFolder;this.plugin.settings.exportFolder=r,await this.plugin.saveSettings()})),new G.Setting(t).setName("Rebootstrap existing Stashpad folders").setDesc("Walk every folder that has a home note: ensure infrastructure (_imports, _exports, drafts file), backfill the redundant parentLink + children frontmatter fields, AND rename any note whose filename slug no longer matches its body's first line. Safe to run anytime; skip-if-equal means already-synced notes are no-op writes.").addButton(i=>i.setButtonText("Rebootstrap now").onClick(async()=>{i.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:n,fmChecked:r,fmWritten:a,slugsRenamed:o,authors:l,imported:c,attachmentsLinked:p}=await this.plugin.rebootstrapAllFolders(),u=[];u.push(`rebootstrapped ${n.length} folder${n.length===1?"":"s"}`),c>0&&u.push(`imported ${c} loose file${c===1?"":"s"}`),p>0&&u.push(`linked attachments on ${p} note${p===1?"":"s"}`),a>0?u.push(`updated frontmatter on ${a} of ${r} notes`):r>0&&u.push(`frontmatter already in sync (${r} notes checked)`),o>0&&u.push(`renamed ${o} note${o===1?"":"s"} to match body`),l>0&&u.push(`rebuilt author registry (${l} author${l===1?"":"s"})`),new G.Notice(`Stashpad: ${u.join("; ")}.`)}catch(n){new G.Notice(`Stashpad: rebootstrap failed (${n.message})`)}finally{i.setDisabled(!1).setButtonText("Rebootstrap now")}})),new G.Setting(t).setName("Use Templates plugin date/time formats").setDesc("When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.").addToggle(i=>i.setValue(this.plugin.settings.useTemplatesFormat).onChange(async n=>{this.plugin.settings.useTemplatesFormat=n,await this.plugin.saveSettings()}));let e=es(this.app);t.createDiv({cls:"setting-item-description stashpad-settings-note"}).setText(e?`Templates plugin: date = "${e.dateFormat}", time = "${e.timeFormat}"`:"Templates plugin not enabled.");{let i=null,n=()=>{if(!i)return;let r=Date.now(),a=Kt(r,this.plugin.settings);i.setText(`Sample: ${a}`)};new G.Setting(t).setName("Date display format").setDesc("How due dates and created/modified times are shown in the Tasks and detail panels.").addDropdown(r=>{r.addOption("locale","Locale, short (Mar 5, 9:00 AM)"),r.addOption("long","Locale, long (Thursday, March 5\u2026)"),r.addOption("iso","ISO (2026-03-05 09:00)"),r.addOption("us","US (3/5/2026, 9:00 AM)"),r.addOption("eu","EU (5/3/2026, 09:00)"),r.setValue(this.plugin.settings.dateDisplayFormat??"locale"),r.onChange(async a=>{this.plugin.settings.dateDisplayFormat=a,await this.plugin.saveSettings(),n()})}),new G.Setting(t).setName("Display timezone").setDesc("IANA timezone name (e.g. America/New_York, Europe/London, Asia/Kolkata). Leave blank to use your system timezone.").addText(r=>{r.setPlaceholder("(system timezone)"),r.setValue(this.plugin.settings.dateDisplayTimezone??""),r.onChange(async a=>{this.plugin.settings.dateDisplayTimezone=(a||"").trim(),await this.plugin.saveSettings(),n()})}),i=t.createDiv({cls:"setting-item-description stashpad-settings-note"}),n()}new G.Setting(t).setName("Navigate into parent after moving a note IN").setDesc("When you move a note onto another note via the in-list move picker (drag-onto-sibling), automatically drill into the new parent so you can see the moved note in its new home. Off = stay focused where you were.").addToggle(i=>i.setValue(this.plugin.settings.autoNavOnMoveIn).onChange(async n=>{this.plugin.settings.autoNavOnMoveIn=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Navigate to destination after moving a note OUT").setDesc("When you outdent a note, move it via the cross-parent picker, or send it to Home, automatically drill into the destination parent. Off = stay focused where you were.").addToggle(i=>i.setValue(this.plugin.settings.autoNavOnMoveOut).onChange(async n=>{this.plugin.settings.autoNavOnMoveOut=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Double-click a note to open it").setDesc("Double-click (or double-tap on mobile) a note in the list to focus/open it \u2014 the same as pressing \u2192 or clicking the enter arrow. Single click still just selects. On by default.").addToggle(i=>i.setValue(this.plugin.settings.doubleClickToFocus).onChange(async n=>{this.plugin.settings.doubleClickToFocus=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Auto-open the detail panel").setDesc("Open the right-sidebar Stashpad detail panel automatically whenever a Stashpad view becomes active. The panel shows the cursored note's body, metadata, and children. Off = open manually via ribbon or command palette.").addToggle(i=>i.setValue(this.plugin.settings.autoOpenDetailPanel).onChange(async n=>{this.plugin.settings.autoOpenDetailPanel=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Expand the cursor row's body automatically").setDesc("As you arrow-key through the list, the row under the cursor temporarily un-clamps to show its full body. Moving away re-collapses it. Doesn't affect the persistent 'Show more' state \u2014 this is a transient view-only effect.").addToggle(i=>i.setValue(this.plugin.settings.autoExpandCursorRow).onChange(async n=>{this.plugin.settings.autoExpandCursorRow=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Confirm cross-parent drag-and-drop").setDesc("When dragging notes onto a note that has a different parent, ask before re-parenting (turn off to allow direct moves).").addToggle(i=>i.setValue(this.plugin.settings.confirmCrossParentDrag).onChange(async n=>{this.plugin.settings.confirmCrossParentDrag=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Confirm bulk deletes").setDesc("Warn before deletes that affect more than one note \u2014 multi-selection delete OR deleting a note that has descendants. A single childless note with no attachments never prompts. Off = those deletes apply immediately (undo still recovers everything).").addToggle(i=>i.setValue(this.plugin.settings.confirmBulkDelete).onChange(async n=>{this.plugin.settings.confirmBulkDelete=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Offer to delete attachments with note").setDesc(`When a note references attachments, the delete modal includes an "Also delete attachments" checkbox so orphaned files don't pile up in your vault. Attachments are detected from both ![[\u2026]] embeds in the body and the frontmatter attachments: list. Off = attachments are always preserved on delete (no checkbox shown), and a single childless note with attachments deletes silently.`).addToggle(i=>i.setValue(this.plugin.settings.confirmAttachmentDelete).onChange(async n=>{this.plugin.settings.confirmAttachmentDelete=n,await this.plugin.saveSettings()}));{let i=null,n=(this.plugin.settings.slugStopWords?.length?this.plugin.settings.slugStopWords:_t).join(` +`);new G.Setting(t).setName("Slug stop-words").setDesc("Words removed from auto-generated note titles (filenames). One per line.").addTextArea(r=>{r.setValue(n),i=r.inputEl,i.rows=6,i.style.fontFamily="var(--font-monospace)",r.onChange(async a=>{let o=(a||"").split(/\r?\n/).map(l=>l.trim().toLowerCase()).filter(Boolean);this.plugin.settings.slugStopWords=o,await this.plugin.saveSettings()})}).addExtraButton(r=>r.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[..._t],i&&(i.value=_t.join(` +`)),await this.plugin.saveSettings()}))}{let i=this.plugin.discoverStashpadFolders();if(new G.Setting(t).setName("Cross-Stashpad search scope").setDesc("Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations \u2014 their notes just don't appear in search results from elsewhere."),i.length===0)t.createEl("p",{cls:"setting-item-description"}).setText('No Stashpads found in this vault yet. A Stashpad is just a folder that contains a Stashpad-shaped note (frontmatter has both `id` and `parent`). Easiest way: open Stashpad (ribbon icon or command "Reveal or open Stashpad") \u2014 it auto-creates the default folder on first use. Or create one below.');else{let r=t.createDiv({cls:"stashpad-folder-list"});for(let a of i)this.renderFolderScopeRow(r,a)}let n=null;new G.Setting(t).setName("Create a new Stashpad").setDesc("Type a vault-relative folder path. The folder is created (with intermediates) and seeded with a Home note so Stashpad recognizes it.").addText(r=>{r.setPlaceholder("my-stashpad"),n=r.inputEl}).addButton(r=>r.setButtonText("Create").setCta().onClick(async()=>{let a=(n?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!a){new G.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(a),new G.Notice(`Created Stashpad "${a}".`),n&&(n.value=""),await this.plugin.waitForStashpadFolder(a,2e3),this.display()}catch(o){new G.Notice(`Couldn't create: ${o.message}`)}}))}new G.Setting(t).setName("Autofocus composer after sending").setDesc("After Enter-submitting a note, return focus to the composer so you can keep typing. Off keeps focus in the list \u2014 useful if you want arrow keys to work without an extra click.").addToggle(i=>i.setValue(this.plugin.settings.autofocusComposerAfterSend).onChange(async n=>{this.plugin.settings.autofocusComposerAfterSend=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Open in new window \u2014 duplicate tab").setDesc("ON: the new-window button (in the time-filter row) duplicates the current Stashpad tab \u2014 original stays open in the main window. OFF: the leaf is MOVED to the new window, closing the original tab.").addToggle(i=>i.setValue(this.plugin.settings.popoutDuplicates).onChange(async n=>{this.plugin.settings.popoutDuplicates=n,await this.plugin.saveSettings()})),new G.Setting(t).setName("Prefix timestamps when copying").setDesc("Include each note's timestamp before its body when copying with C or Y.").addToggle(i=>i.setValue(this.plugin.settings.prefixTimestampsOnCopy).onChange(async n=>{this.plugin.settings.prefixTimestampsOnCopy=n,await this.plugin.saveSettings()}))}renderTemplatesTab(t){this.renderColorAliasesSection(t),this.renderNoteTemplatesSection(t)}renderHotkeysTab(t){t.createEl("p",{cls:"setting-item-description",text:"Each command has up to two slots. Click a slot and press a key (or chord) to bind it; press Backspace (delete on Mac) to cancel without binding; or click \u2715 to clear an existing binding. When both slots are set, the pill on the right decides which one is active."});for(let e of Me)this.renderBindingRow(t,e)}renderJdIndexSection(t){let e=t.createEl("h3",{text:"JD Index Builder"});e.id="stashpad-jd-index-section";let s=t.createEl("p",{cls:"setting-item-description"});s.innerHTML="Builds a Johnny-Decimal-style index inside a designated Stashpad folder. Two commands:<br/><strong>Preview</strong> overwrites the designated folder’s HOME note body with the would-be hierarchy + everything that didn’t match. Frontmatter is preserved; everything below it is replaced.<br/><strong>Build</strong> creates an actual hierarchy of Stashpad notes (one per prefix), with child\u2192parent relationships matching the dotted segments.<br/>Matches strict prefixes only: all-digits (<code>10 Life</code>) or alphanumeric-with-dots (<code>1.2 Family</code>, <code>animal.duck.yellow Eggs</code>). Mixed schemes sort numbers first, then alphabetically.";let i=this.plugin.discoverStashpadFolders();new G.Setting(t).setName("Scope").setDesc("Scan the whole vault, or restrict to a single folder + its descendants.").addDropdown(o=>{o.addOption("vault","Entire vault"),o.addOption("folder","Single folder"),o.setValue(this.plugin.settings.jdIndexScope??"vault"),o.onChange(async l=>{this.plugin.settings.jdIndexScope=l==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new G.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(o=>{new le(this.app,o.inputEl),o.setPlaceholder("Path/To/Folder"),o.setValue(this.plugin.settings.jdIndexScopeFolder??""),o.onChange(async l=>{this.plugin.settings.jdIndexScopeFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new G.Setting(t).setName("Include Stashpad folders in scan").setDesc("By default, notes inside any known Stashpad folder are excluded \u2014 the index destination shouldn't index itself, and other Stashpad folders are usually already organized. Toggle on if you want them included anyway.").addToggle(o=>{o.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),o.onChange(async l=>{this.plugin.settings.jdIndexIncludeStashpadFolders=l,await this.plugin.saveSettings(),this.display()})}),new G.Setting(t).setName("Designated Stashpad folder for Index").setDesc("Required. Must be a Stashpad folder. The index hierarchy is built here. New notes are created; nothing is deleted.").addText(o=>{new le(this.app,o.inputEl),o.setPlaceholder(i[0]??"(pick a Stashpad folder)"),o.setValue(this.plugin.settings.jdIndexStashpadFolder??""),o.onChange(async l=>{this.plugin.settings.jdIndexStashpadFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new G.Setting(t).setName("Sort").setDesc("Order of entries within the same depth. Natural: numbers first then alphabetical (recommended). Created: by source file's creation time \u2014 handy when prefixes are word-only and don't carry ordering.").addDropdown(o=>{o.addOption("natural","Natural (numeric \u2192 alphabetical)"),o.addOption("created","By creation time"),o.setValue(this.plugin.settings.jdIndexSort??"natural"),o.onChange(async l=>{this.plugin.settings.jdIndexSort=l==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=oe(this.app,this.plugin,this.plugin.settings),r=t.createEl("p",{cls:"setting-item-description"}),a=n.skippedStashpadNotes.length>0?` (${n.skippedStashpadNotes.length} Stashpad-folder note${n.skippedStashpadNotes.length===1?"":"s"} excluded by default)`:"";r.setText(`Preview: ${n.indexed.length} note${n.indexed.length===1?"":"s"} would be indexed, ${n.nonIndex.length} would NOT be indexed${a}.`),new G.Setting(t).setName("Actions").setDesc("Preview aggressively overwrites the designated folder's HOME note body (frontmatter preserved). Build creates Stashpad notes (existing notes with the same jdPrefix are updated, not duplicated).").addButton(o=>{o.setButtonText("Preview"),o.setTooltip("Overwrites the designated Stashpad folder's HOME note body with the preview."),o.onClick(async()=>{try{let l=await Ve(this.app,this.plugin,this.plugin.settings);if(l.error==="no-dest"){new G.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(l.error==="no-home"){new G.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}Ye(this.app,l),this.display()}catch(l){console.error("[stashpad] preview failed",l),new G.Notice(`Preview failed: ${l?.message??l}`,8e3)}})}).addButton(o=>{o.setButtonText("Build Stashpad notes"),o.setCta(),o.setTooltip("Create the Stashpad-note hierarchy. Existing notes with matching jdPrefix are updated."),o.onClick(()=>{if(!(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new G.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new Ae(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let p=await Ps(this.app,this.plugin,this.plugin.settings);if(p.error==="no-dest"){new G.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(p.error==="dest-not-stashpad"){new G.Notice(`"${p.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder (or create one first).`,7e3);return}this.plugin.settings.jdIndexHasBuilt=!0,await this.plugin.saveSettings(),new G.Notice(`Built: ${p.created} created, ${p.updated} updated, ${p.skipped} skipped \u2192 ${p.destFolder}`,6e3),this.display()}catch(p){console.error("[stashpad] build failed",p),new G.Notice(`Build failed: ${p?.message??p}`,8e3)}}).open()})}).addButton(o=>{o.setButtonText(`Reveal in ${Ji()}`),o.setTooltip("Open the designated Stashpad folder in your OS file browser."),o.onClick(async()=>{let l=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!l){new G.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(l)){new G.Notice(`Folder "${l}" doesn't exist yet.`,5e3);return}try{let p=this.app.vault.adapter.basePath;if(p){let{shell:u}=window.require?.("electron")??{},h=`${p}/${l}`;u?.openPath?.(h)}else new G.Notice("Reveal in file system not supported on this platform.",4e3)}catch(p){new G.Notice(`Couldn't open folder: ${p?.message??p}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new G.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let s=(()=>{let r=Ot()?.noteFolder;return r&&e.includes(r)?r:e[0]})();new G.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(r=>{for(let a of e)r.addOption(a,a);r.setValue(s),r.onChange(a=>{s=a,n()})}),t.createEl("p",{cls:"setting-item-description",text:"Give each per-note color a friendly name. Filters and pickers display the alias instead of the hex code; the underlying color stays the same. The same hex in two Stashpads can have different aliases."});let i=t.createDiv({cls:"stashpad-color-aliases-list"}),n=()=>{i.empty();let r=this.plugin.collectColorsInFolder(s),a=new Map(r.map(p=>[p.hex,p.count])),o=this.plugin.settings.colorAliases?.[s.replace(/\/+$/,"")]??{},l=new Set([...a.keys(),...Object.keys(o)]);if(l.size===0){i.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${s}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let c=[...l].map(p=>({hex:p,count:a.get(p)??0}));c.sort((p,u)=>u.count-p.count||p.hex.localeCompare(u.hex));for(let p of c)this.renderColorAliasRow(i,s,p.hex,p.count,n)};n()}renderAuthorshipSection(t){t.createEl("h3",{text:"Authorship"}),t.createEl("p",{cls:"setting-item-description",text:"Stamp each new note with your name. If the vault is later shared (e.g. a coworker opens it with --config pointing at their own settings folder), every modification automatically tracks contributors on top of the original author. Names link to per-user pages in <stashpad>/_authors/."}),new G.Setting(t).setName("Author name").setDesc("Your display name. Used in the note footer + as the author/contributor link target. Leave blank to opt out (notes won't be stamped).").addText(s=>{s.setValue(this.plugin.settings.authorName).onChange(async i=>{this.plugin.settings.authorName=i.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=yt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new G.Setting(t).setName("Author id (auto-assigned)").setDesc("Stable id appended to your name on links so coworkers with the same name don't collide. Generated once and shouldn't change. If you really need to reset it, clear and retype your author name above.").addText(s=>{s.setValue(this.plugin.settings.authorId).setDisabled(!0)}),new G.Setting(t).setName("Title / role").setDesc('Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").').addText(s=>{s.setValue(this.plugin.settings.authorRole).onChange(async i=>{this.plugin.settings.authorRole=i.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new G.Setting(t).setName("Department / team").setDesc('Optional. Shown on your author page (e.g. "Engineering", "Growth").').addText(s=>{s.setValue(this.plugin.settings.authorDepartment).onChange(async i=>{this.plugin.settings.authorDepartment=i.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new G.Setting(t).setName("Show author in note footer").addToggle(s=>s.setValue(this.plugin.settings.showAuthor).onChange(async i=>{this.plugin.settings.showAuthor=i,await this.plugin.saveSettings()})),new G.Setting(t).setName("Show contributors in note footer").addToggle(s=>s.setValue(this.plugin.settings.showContributors).onChange(async i=>{this.plugin.settings.showContributors=i,await this.plugin.saveSettings()})),new G.Setting(t).setName("Show last edit time in note footer").addToggle(s=>s.setValue(this.plugin.settings.showLastEdit).onChange(async i=>{this.plugin.settings.showLastEdit=i,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){t.createEl("h4",{text:"Folders you've worked in"});let s=t.createDiv({cls:"stashpad-authored-folders-list"});for(let i of e){let n=s.createDiv({cls:"stashpad-authored-folder-row"}),r=n.createEl("a",{cls:"stashpad-authored-folder-link",text:i.folder});r.onclick=o=>{o.preventDefault(),this.plugin.activateViewForFolder(i.folder)};let a=[];i.authored>0&&a.push(`authored ${i.authored}`),i.contributed>0&&a.push(`contributed to ${i.contributed}`),n.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${a.join(", ")}`})}}this.renderKnownAuthorsSection(t)}renderKnownAuthorsSection(t){t.createEl("h4",{text:"Known authors (registry)"}),t.createEl("div",{cls:"setting-item-description",text:"A rebuildable cache of every author Stashpad has seen, with rename history. Not a source of truth \u2014 the author id stored in each note is authoritative. Use it to recover deleted author pages or audit name changes."}),new G.Setting(t).setName("Registry maintenance").setDesc("Rebuild scans the whole vault to reconstruct the list. Restore regenerates any deleted author pages across every Stashpad folder.").addButton(i=>i.setButtonText("Rebuild").onClick(async()=>{i.setDisabled(!0).setButtonText("Rebuilding\u2026");try{let n=await this.plugin.rebuildAuthorRegistry();new G.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new G.Notice(`Rebuild failed: ${n.message}`)}i.setDisabled(!1).setButtonText("Rebuild"),this.display()})).addButton(i=>i.setButtonText("Restore missing pages").onClick(async()=>{i.setDisabled(!0).setButtonText("Restoring\u2026");try{let n=await this.plugin.restoreMissingAuthorStubs();new G.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new G.Notice(`Restore failed: ${n.message}`)}i.setDisabled(!1).setButtonText("Restore missing pages")}));let e=this.plugin.authorRegistry.all();if(e.length===0){t.createEl("div",{cls:"setting-item-description",text:"No authors recorded yet. Rebuild to scan the vault."});return}let s=t.createDiv({cls:"stashpad-known-authors-list"});for(let i of e){let n=s.createDiv({cls:"stashpad-known-author-row"}),r=n.createDiv({cls:"stashpad-known-author-main"});r.createSpan({cls:"stashpad-known-author-name",text:i.name||"(unnamed)"});let a=[];if(i.role&&a.push(i.role),i.department&&a.push(i.department),a.push(`id ${i.id}`),r.createSpan({cls:"stashpad-known-author-meta",text:` \xB7 ${a.join(" \xB7 ")}`}),i.renames&&i.renames.length>0){let o=n.createDiv({cls:"stashpad-known-author-history"}),l=i.renames.map(c=>`${c.from} \u2192 ${c.to}`).join(", ");o.setText(`Renamed: ${l}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;new G.Setting(t).setName("Note templates per Stashpad").setDesc("Pick a markdown file to use as the default template for new notes in each Stashpad. The template's frontmatter becomes the new note's frontmatter (id/parent/created/attachments are always set by Stashpad). If the body contains {{body}}, that's where the user-typed body goes; otherwise the user body is followed by the template body.");let s=t.createDiv({cls:"stashpad-note-templates-list"}),i=n=>{let r=n.replace(/\/+$/,""),a=s.createDiv({cls:"stashpad-note-template-row"});a.createSpan({cls:"stashpad-note-template-folder"}).setText(n);let l=a.createDiv({cls:"stashpad-note-template-input-wrap"}),c=l.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});c.value=(this.plugin.settings.noteTemplates??{})[r]??"";let p=l.createDiv({cls:"stashpad-note-template-suggest"});p.style.display="none";let u=a.createDiv({cls:"stashpad-note-template-warn"});u.style.display="none";let h=()=>this.app.vault.getMarkdownFiles().map(y=>y.path).filter(y=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(y)).sort(),f=()=>{p.empty();let y=c.value.trim().toLowerCase().split(/\s+/).filter(Boolean),b=T=>{let I=T.toLowerCase();return y.every(E=>I.includes(E))},k=h().filter(T=>b(T)).slice(0,12);if(k.length===0){p.style.display="none";return}p.style.display="";for(let T of k)p.createDiv({cls:"stashpad-note-template-suggest-item",text:T}).addEventListener("mousedown",async E=>{E.preventDefault(),c.value=T,await m(),p.style.display="none"})},m=async()=>{let y=c.value.trim(),b={...this.plugin.settings.noteTemplates??{}};y?b[r]=y:delete b[r],this.plugin.settings.noteTemplates=b,await this.plugin.saveSettings(),v()},v=()=>{u.empty(),u.style.display="none";let y=c.value.trim();if(!y)return;let b=this.app.vault.getAbstractFileByPath(y);if(!b||b.extension!=="md"){u.style.display="",u.setText(`\u26A0 "${y}" is not a markdown file in this vault.`);return}let k=this.app.metadataCache.getFileCache(b)?.frontmatter??{},I=Bt.filter(E=>{let D=k[E];return!(D==null||typeof D=="string"&&D.trim()===""||Array.isArray(D)&&D.length===0)});I.length!==0&&(u.style.display="",u.setText(`\u26A0 Template defines ${I.join(", ")} \u2014 Stashpad always sets ${I.length===1?"this":"these"} on new notes, so the template value${I.length===1?"":"s"} will be ignored.`))};c.addEventListener("focus",f),c.addEventListener("input",f),c.addEventListener("blur",()=>{setTimeout(()=>{p.style.display="none"},150)}),c.addEventListener("change",()=>{m()}),v()};for(let n of e)i(n)}renderColorAliasRow(t,e,s,i,n){let r=t.createDiv({cls:"stashpad-color-alias-row"});i===0&&r.addClass("is-unused");let a=r.createSpan({cls:"stashpad-color-alias-swatch"});a.style.background=s,a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let p=this.plugin.settings.customPalette??[];new Jt(this.app,s,p,async u=>{if((u??null)===null&&i===0){await this.plugin.setColorAlias(e,s,""),n();return}if(u&&u.toLowerCase()===s){n();return}let h=await this.plugin.recolorAllInFolder(e,s,u??null);if(h>0)new G.Notice(`Recolored ${h} note${h===1?"":"s"}.`);else if(i===0){let f=this.plugin.getColorAlias(e,s);f&&(await this.plugin.setColorAlias(e,s,""),u&&await this.plugin.setColorAlias(e,u,f))}n()},async u=>{let h=(this.plugin.settings.customPalette??[]).filter(f=>f.toLowerCase()!==u.toLowerCase());return this.plugin.settings.customPalette=h,await this.plugin.saveSettings(),h}).open()};let o=r.createDiv({cls:"stashpad-color-alias-meta"});o.createSpan({cls:"stashpad-color-alias-hex",text:s}),o.createSpan({cls:"stashpad-color-alias-count",text:i===0?"\xB7 unused":`\xB7 ${i} note${i===1?"":"s"}`});let l=r.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});l.value=this.plugin.getColorAlias(e,s)??"",l.onchange=async()=>{await this.plugin.setColorAlias(e,s,l.value),!l.value.trim()&&i===0&&n()};let c=r.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});l.value||(c.style.visibility="hidden"),c.onclick=async()=>{await this.plugin.setColorAlias(e,s,""),i===0?n():(l.value="",c.style.visibility="hidden")}}renderFolderScopeRow(t,e){let s=t.createDiv({cls:"stashpad-folder-row"});s.createSpan({cls:"stashpad-folder-row-label",text:e});let i=s.createSpan({cls:"stashpad-folder-row-state"}),n=s.createDiv({cls:"stashpad-binding-pill"});n.setAttribute("role","switch"),n.setAttribute("tabindex","0");let r=n.createDiv({cls:"stashpad-binding-pill-knob"}),a=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),o=()=>{let c=a();n.toggleClass("is-right",c),n.setAttribute("aria-checked",String(c)),r.setText(c?"X":"\u2713"),i.setText(c?"Excluded":"Included"),i.toggleClass("is-excluded",c),n.title=c?"Excluded \u2014 notes here won't appear in cross-Stashpad search. Click to include.":"Included \u2014 notes here appear in cross-Stashpad search. Click to exclude."},l=async()=>{let c=new Set(this.plugin.settings.searchExcludedFolders??[]);c.has(e)?c.delete(e):c.add(e),this.plugin.settings.searchExcludedFolders=[...c].sort(),o(),await this.plugin.saveSettings()};n.onclick=()=>void l(),n.onkeydown=c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())},o()}renderBindingRow(t,e){let s=new G.Setting(t).setName(e.label).setDesc(e.desc),i=()=>this.plugin.settings.bindings[e.id],n,r,a=()=>{},o=f=>{let m=s.controlEl.createDiv({cls:"stashpad-binding-slot"}),v=m.createEl("input",{type:"text"});v.readOnly=!0,v.placeholder="Click & press a key",v.value=Ns(i()[f]),v.classList.add("stashpad-binding-input");let y=()=>{v.size=Math.max(3,v.value.length||v.placeholder.length)};y(),v.onclick=()=>{pi(v,async k=>{this.plugin.settings.bindings[e.id][f]=k,v.value=Ns(k),y(),await this.plugin.saveSettings(),a()})};let b=m.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});return b.title="Clear this slot",b.onclick=async()=>{this.plugin.settings.bindings[e.id][f]="",v.value="",y(),await this.plugin.saveSettings(),a()},v};n=o("primary"),r=o("secondary");let l=s.controlEl.createDiv({cls:"stashpad-binding-pill"});l.setAttribute("role","switch"),l.setAttribute("tabindex","0");let c=l.createDiv({cls:"stashpad-binding-pill-knob"}),p=s.controlEl.createDiv({cls:"stashpad-binding-useboth"}),u=p.createEl("input",{type:"checkbox"});u.title="Use both bindings simultaneously (overrides the L/R toggle)",p.createSpan({text:"Use both"}),u.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=u.checked,await this.plugin.saveSettings(),a()},a=()=>{let f=i(),m=!!(f.primary&&f.secondary);u.checked=!!f.useBoth,u.disabled=!m,p.toggleClass("is-disabled",!m);let v=!!f.useBoth&&m;l.toggleClass("is-disabled",!m||v),l.toggleClass("is-right",f.preferRight),l.setAttribute("aria-checked",String(f.preferRight)),l.setAttribute("aria-disabled",String(!m||v)),c.setText(f.preferRight?"R":"L"),l.title=m?v?'Overridden by "Use both"':f.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let h=async()=>{let f=i();!f.primary||!f.secondary||(this.plugin.settings.bindings[e.id].preferRight=!f.preferRight,a(),await this.plugin.saveSettings())};l.onclick=()=>void h(),l.onkeydown=f=>{(f.key===" "||f.key==="Enter")&&(f.preventDefault(),h())},a()}};var ce=class{constructor(d,t){this.app=d;this.ta=t;this.popupEl=null;this.items=[];this.activeIdx=0;this.state=null;this.fileIndex=[];this.tagIndex=[];this.indexBuilt=!1;this.vaultListeners=[];this.scope=null;this.onInput=()=>{let d=this.detectTrigger();if(!d){this.close();return}this.openFor(d)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=d=>{d.key==="Escape"&&(!this.state||!this.items.length||(d.preventDefault(),d.stopPropagation(),d.stopImmediatePropagation(),this.close()))};this.onKeyDown=d=>{!this.state||!this.items.length||(d.key==="ArrowDown"?(d.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):d.key==="ArrowUp"?(d.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):d.key==="Enter"||d.key==="Tab"?(d.preventDefault(),d.stopPropagation(),this.commit()):d.key==="Escape"&&(d.preventDefault(),d.stopPropagation(),d.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let d=this.ta.ownerDocument??document;d.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>d.removeEventListener("keydown",this.onDocEscape,!0)),this.buildIndex();let t=()=>{this.indexBuilt=!1},e=this.app.vault;e.on("create",t),e.on("delete",t),e.on("rename",t),this.vaultListeners.push(()=>e.off("create",t),()=>e.off("delete",t),()=>e.off("rename",t))}isOpen(){return!!this.state&&this.items.length>0}detach(){this.close(),this.ta.removeEventListener("input",this.onInput),this.ta.removeEventListener("keydown",this.onKeyDown,!0),this.ta.removeEventListener("blur",this.onBlur);for(let d of this.vaultListeners)d();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;let d=St().inheritObsidianExclusions,t=d?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(s=>!Js(s.path)&&!Xs(s.path)&&!(d&&Qs(s.path,t))).map(s=>{let i=s.extension==="md",n=i?s.basename:s.name,r=i?s.basename:s.name;return{label:n,lower:n.toLowerCase(),insertText:r,file:s}});let e=this.app.metadataCache.getTags?.()??{};this.tagIndex=Object.keys(e).sort((s,i)=>(e[i]||0)-(e[s]||0)),this.indexBuilt=!0}detectTrigger(){let d=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=d.slice(0,t),s=e.match(/\[\[([^\]\[\n]*)$/);if(s){let n=s[1];return{kind:"link",query:n,replaceStart:t-n.length-2,replaceEnd:t}}let i=e.match(/(^|\s)#([A-Za-z0-9_/\-]+)$/);if(i){let n=i[2];return{kind:"tag",query:n,replaceStart:t-n.length-1,replaceEnd:t}}return null}buildItems(d){this.buildIndex();let t=d.query.toLowerCase().trim(),e=t?t.split(/\s+/).filter(Boolean):[],s=i=>{if(!e.length)return!0;for(let n of e)if(!i.includes(n))return!1;return!0};return d.kind==="link"?this.fileIndex.filter(n=>s(n.lower)).slice(0,50).map(n=>({label:n.label,insert:`[[${n.insertText}]]`,subtitle:n.file.path})):this.tagIndex.filter(n=>s(n.toLowerCase())).slice(0,30).map(n=>({label:n,insert:n,subtitle:""}))}openFor(d){if(this.state=d,this.items=this.buildItems(d),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let d=new vi.Scope(this.app.scope);d.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=d,this.app.keymap?.pushScope(d)}popScope(){if(this.scope){try{this.app.keymap?.popScope(this.scope)}catch{}this.scope=null}}renderPopup(){if(!this.popupEl){let t=this.ta.ownerDocument??document;this.popupEl=t.body.createDiv({cls:"stashpad-composer-suggest"}),this.popupEl.tabIndex=-1,this.popupEl.addEventListener("mousedown",e=>e.preventDefault())}let d=this.popupEl;d.empty();for(let t=0;t<this.items.length;t++){let e=this.items[t],s=d.createDiv({cls:"stashpad-composer-suggest-row"});t===this.activeIdx&&s.addClass("is-active"),s.createSpan({cls:"stashpad-composer-suggest-label",text:e.label}),e.subtitle&&s.createSpan({cls:"stashpad-composer-suggest-sub",text:e.subtitle}),s.onmousedown=i=>{i.preventDefault(),this.activeIdx=t,this.commit()}}this.position()}refreshActive(){if(!this.popupEl)return;let d=this.popupEl.children;for(let e=0;e<d.length;e++)d[e].toggleClass("is-active",e===this.activeIdx);let t=d[this.activeIdx];t&&t.scrollIntoView({block:"nearest"})}position(){if(!this.popupEl)return;let d=this.ta.getBoundingClientRect(),t=this.popupEl.offsetHeight||200,e=d.top-t-4,s=d.left;this.popupEl.style.left=`${Math.max(8,s)}px`,this.popupEl.style.top=`${Math.max(8,e)}px`,this.popupEl.style.minWidth=`${Math.min(360,d.width)}px`}commit(){if(!this.state||!this.items.length)return;let d=this.items[this.activeIdx];if(!d)return;let t=this.ta.value.slice(0,this.state.replaceStart),e=this.ta.value.slice(this.state.replaceEnd),s=d.insert;this.ta.value=t+s+e;let i=t.length+s.length;this.ta.setSelectionRange(i,i),this.ta.dispatchEvent(new Event("input",{bubbles:!0})),this.close(),this.ta.focus()}close(){this.popupEl&&(this.popupEl.remove(),this.popupEl=null),this.state=null,this.items=[],this.activeIdx=0,this.popScope()}};Tt();var ss=class extends Ct.ItemView{constructor(t,e){super(t);this.plugin=e;this.displayedPath=null;this.unsubscribeSelection=null;this.renderTimer=null;this.expanded=new Set;this.composerAutocomplete=null;this.composerInputEl=null;this.composerDraft="";this.composerDraftForId=null;this.displayedId=null;this.unsubscribeContent=null}getViewType(){return Vt}getDisplayText(){return"Stashpad detail"}getIcon(){return"panel-right"}async onOpen(){this.render(),this.unsubscribeSelection=this.plugin.onStashpadSelectionChange(()=>{this.displayedId=null,this.scheduleRender()}),this.unsubscribeContent=this.plugin.onStashpadContentChange(()=>this.scheduleRender()),this.registerEvent(this.app.workspace.on("active-leaf-change",t=>{!t||t===this.leaf||t.view?.getViewType?.()===mt&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("modify",t=>{this.displayedPath&&t.path===this.displayedPath&&this.scheduleRender()})),this.registerEvent(this.app.metadataCache.on("changed",t=>{this.displayedPath&&t.path===this.displayedPath&&this.scheduleRender()}))}async onClose(){this.unsubscribeSelection?.(),this.unsubscribeSelection=null,this.unsubscribeContent?.(),this.unsubscribeContent=null,this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,this.renderTimer!=null&&(window.clearTimeout(this.renderTimer),this.renderTimer=null)}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},60))}resolveDisplayed(){if(this.displayedId){let e=this.plugin.lastActiveStashpadLeaf?.view;if(e?.getViewType?.()===mt&&e.tree?.get){let s=e.tree.get(this.displayedId);if(s?.file)return{folder:e.noteFolder,id:this.displayedId,file:s.file}}this.displayedId=null}let t=this.plugin.getActiveStashpadSelection();return t&&(this.displayedId=t.id),t}async render(){let t=this.contentEl,e=!!this.composerInputEl&&document.activeElement===this.composerInputEl,s=this.composerInputEl?.selectionStart??null;this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,t.empty(),t.addClass("stashpad-detail-root");let i=this.resolveDisplayed();if(!i){this.displayedPath=null;let h=t.createDiv({cls:"stashpad-detail-empty"});(0,Ct.setIcon)(h.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),h.createSpan({cls:"stashpad-detail-empty-text",text:"No Stashpad note selected. Cursor or click a note in a Stashpad list to inspect it here."});return}let n=i.file;this.displayedPath=n.path;let r=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=t.createDiv({cls:"stashpad-detail-scroll"}),o=a.createDiv({cls:"stashpad-detail-header"}),l=o.createDiv({cls:"stashpad-detail-titlerow"});l.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let c=l.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,Ct.setIcon)(c,"arrow-up-right"),c.title="Open this note in a new Stashpad tab",c.onclick=()=>{this.openInStashpad(i.folder,i.id)};let p=o.createDiv({cls:"stashpad-detail-metarow"});if(i.folder&&p.createSpan({cls:"stashpad-detail-meta-chip",text:i.folder.split("/").pop()||i.folder}),typeof r.color=="string"&&r.color){let h=p.createSpan({cls:"stashpad-detail-meta-color"});h.style.background=r.color,h.title=r.color}if(r.completed===!0&&p.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof r.due=="string"||typeof r.due=="number"){let h=Date.parse(String(r.due)),f=Number.isNaN(h)?String(r.due):Kt(h,this.plugin.settings);p.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${f}`})}if(Array.isArray(r.tags))for(let h of r.tags.filter(f=>typeof f=="string"))p.createSpan({cls:"stashpad-detail-meta-tag",text:`#${h.replace(/^#/,"")}`});let u=a.createDiv({cls:"stashpad-detail-body"});try{let h=await this.app.vault.cachedRead(n),f=this.stripFrontmatter(h);await Ct.MarkdownRenderer.render(this.app,f,u,n.path,this)}catch(h){u.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${h.message}`})}if(this.renderFooterMeta(a,n,r,i),this.renderChildren(a,i.folder,i.id),this.renderComposer(t,i),e&&this.composerInputEl&&(this.composerInputEl.focus(),s!=null)){let h=Math.min(s,this.composerInputEl.value.length);try{this.composerInputEl.setSelectionRange(h,h)}catch{}}}renderComposer(t,e){let s=t.createDiv({cls:"stashpad-detail-composer"}),i=s.createEl("textarea",{cls:"stashpad-detail-composer-input",attr:{placeholder:"Add a child note\u2026",rows:"2"}});this.composerInputEl=i,this.composerDraftForId===e.id?i.value=this.composerDraft:(this.composerDraft="",this.composerDraftForId=e.id),i.addEventListener("input",()=>{this.composerDraft=i.value,this.composerDraftForId=e.id}),i.addEventListener("keydown",r=>{if(r.key==="Enter"&&!r.shiftKey&&!r.isComposing){if(this.composerAutocomplete?.isOpen?.())return;r.preventDefault(),this.submitComposer(e)}});let n=s.createEl("button",{cls:"stashpad-detail-composer-send",attr:{"aria-label":"Add child note"}});(0,Ct.setIcon)(n.createSpan({cls:"stashpad-detail-composer-send-icon"}),"plus"),n.createSpan({cls:"stashpad-detail-composer-send-text",text:"Add child note"}),n.title="Add child note (Enter)",n.onclick=()=>void this.submitComposer(e),this.composerAutocomplete=new ce(this.app,i),this.composerAutocomplete.attach()}async submitComposer(t){let e=(this.composerInputEl?.value??"").trim();if(!e)return;let s=this.plugin.lastActiveStashpadLeaf?.view;if(!s||s.getViewType?.()!==mt||typeof s.createNoteUnder!="function"){new Ct.Notice("Open a Stashpad view to add notes.");return}try{await s.createNoteUnder(e,t.id)}catch(i){new Ct.Notice(`Couldn't add note: ${i.message}`);return}this.composerDraft="",this.composerDraftForId=t.id,this.composerInputEl&&(this.composerInputEl.value=""),await this.render(),setTimeout(()=>this.composerInputEl?.focus(),0)}renderChildren(t,e,s){let i=this.plugin.lastActiveStashpadLeaf?.view;if(!i||i.getViewType?.()!==mt)return;let n=i.tree;if(!n?.getChildren)return;let r=n.getChildren(s);if(!r||r.length===0)return;let a=t.createDiv({cls:"stashpad-detail-children"});a.createDiv({cls:"stashpad-detail-children-header",text:`Children (${r.length})`});let o=a.createDiv({cls:"stashpad-detail-children-list"});for(let l of r)l.file&&this.renderDetailChildRow(o,i,n,e,l,0)}renderDetailChildRow(t,e,s,i,n,r){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},o=typeof a.color=="string"?a.color:null,l=a.completed===!0,c=s.getChildren(n.id),p=c.length>0,u=`${i}|${n.id}`,h=this.expanded.has(u),f=t.createDiv({cls:"stashpad-detail-child-row"});l&&f.addClass("is-completed"),r>0&&(f.style.paddingLeft=`${r*16}px`),f.draggable=!0,f.dataset.id=n.id,f.addEventListener("dragstart",k=>{k.dataTransfer?.setData("text/plain",n.id),k.dataTransfer&&(k.dataTransfer.effectAllowed="move"),f.addClass("is-dragging")}),f.addEventListener("dragend",()=>f.removeClass("is-dragging")),f.addEventListener("dragover",k=>{k.preventDefault(),k.dataTransfer&&(k.dataTransfer.dropEffect="move");let T=f.getBoundingClientRect(),I=k.clientY-T.top<T.height/2;f.toggleClass("drop-before",I),f.toggleClass("drop-after",!I)}),f.addEventListener("dragleave",()=>{f.removeClass("drop-before"),f.removeClass("drop-after")}),f.addEventListener("drop",k=>{k.preventDefault(),f.removeClass("drop-before"),f.removeClass("drop-after");let T=k.dataTransfer?.getData("text/plain");if(!T||T===n.id)return;let I=f.getBoundingClientRect(),E=k.clientY-I.top<I.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([T],n.id,E?"before":"after")}),f.oncontextmenu=k=>{k.preventDefault();let T=s.get(n.id);T&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(k,T)};let m=f.createSpan({cls:"stashpad-detail-child-toggle"});if(p&&(We(m,c.length,h),m.onclick=k=>{k.stopPropagation(),this.expanded.has(u)?this.expanded.delete(u):this.expanded.add(u),this.render()}),Yt(a,"task")||a.task===!0||a.completed!==void 0){let k=f.createSpan({cls:"stashpad-detail-child-checkbox"});(0,Ct.setIcon)(k,l?"check-square":"square"),k.title=l?"Mark not done":"Mark done",k.addEventListener("mousedown",T=>T.stopPropagation()),k.addEventListener("dblclick",T=>{T.preventDefault(),T.stopPropagation()}),k.onclick=T=>{T.preventDefault(),T.stopPropagation();let I=s.get(n.id);I&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(I)}}let y=f.createSpan({cls:"stashpad-detail-child-icon"});(0,Ct.setIcon)(y,p?"folder-tree":"file-text"),o&&(y.style.color=o);let b=f.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(b.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},p&&h)for(let k of c)this.renderDetailChildRow(t,e,s,i,k,r+1)}renderFooterMeta(t,e,s,i){let n=t.createDiv({cls:"stashpad-detail-footer-meta"}),r=[];if(typeof s.author=="string"&&s.author&&r.push({label:"Author",value:this.stripWikiLink(s.author)}),Array.isArray(s.contributors)){let a=s.contributors.filter(o=>typeof o=="string").map(o=>this.stripWikiLink(o));a.length>0&&r.push({label:"Contributors",value:a.join(", ")})}if(typeof s.modified=="string"&&r.push({label:"Modified",value:this.formatTime(s.modified)}),typeof s.created=="string"&&r.push({label:"Created",value:this.formatTime(s.created)}),r.push({label:"Path",value:e.path}),r.push({label:"ID",value:i.id}),r.length===0){n.remove();return}for(let a of r){let o=n.createDiv({cls:"stashpad-detail-meta-line"});o.createSpan({cls:"stashpad-detail-meta-key",text:a.label}),o.createSpan({cls:"stashpad-detail-meta-val",text:a.value})}}titleFor(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")}stripFrontmatter(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` +---`,3);return e<0?t:t.slice(e+4).replace(/^\n+/,"")}stripWikiLink(t){let e=t.match(/^\[\[(.+?)(?:\|(.+))?\]\]$/);return e?e[2]??(e[1].split("/").pop()??e[1]).replace(/\.md$/,""):t}formatTime(t){let e=Date.parse(t);return Number.isFinite(e)?Kt(e,this.plugin.settings):t}async openInStashpad(t,e){try{await this.plugin.activateViewForFolder(t);let s=this.plugin.lastActiveStashpadLeaf?.view;s?.navigateTo&&e!==R&&s.navigateTo(e)}catch(s){new Ct.Notice(`Couldn't open: ${s.message}`)}}};async function is(g){let d=g.workspace.getLeavesOfType(Vt);if(d.length>0){g.workspace.revealLeaf(d[0]);return}let t=g.workspace.getRightLeaf(!1);if(!t){new Ct.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:Vt,active:!0}),g.workspace.revealLeaf(t)}var O=require("obsidian");Tt();var Wt=require("obsidian");Tt();function Xi(g,d){let t=g.vault.getAbstractFileByPath(d);if(!(t instanceof Wt.TFolder))return[];let e=[],s=[t];for(;s.length;){let i=s.pop();for(let n of i.children)n instanceof Wt.TFile?n.extension==="md"&&e.push(n):n instanceof Wt.TFolder&&(ve.has(n.name)||s.push(n))}return e}var ns=class{constructor(d){this.app=d;this.nodes=new Map;this.byPath=new Map;this.listeners=new Set;this.orderProvider=null;this.synthetic=new Map;this.coalesceTimer=null;this.nodes.set(R,{id:R,parent:null,children:[],file:null,created:""})}setOrderProvider(d){this.orderProvider=d}onChange(d){return this.listeners.add(d),()=>this.listeners.delete(d)}emit(){for(let d of this.listeners)d()}rebuild(d){d!==void 0&&(this.currentFolder=d);let t=this.currentFolder,e=this.byPath,s=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(R,{id:R,parent:null,children:[],file:null,created:""});let i=t?Xi(this.app,t):this.app.vault.getMarkdownFiles();for(let n of i){let r=this.app.metadataCache.getFileCache(n)?.frontmatter,a=r?.id;if(!a){let l=e.get(n.path),c=l?s.get(l):void 0,p=this.synthetic.get(n.path),u=c??p;u&&(this.nodes.set(u.id,{...u,children:[],file:n}),this.byPath.set(n.path,u.id));continue}if(this.synthetic.delete(n.path),a===R){let l=this.nodes.get(R);l.file=n,l.created=r?.created??"",this.byPath.set(n.path,R);continue}let o=r?.parent??null;o===a&&(o=null),this.nodes.set(a,{id:a,parent:o??R,children:[],file:n,created:r?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===R)continue;let r=n.parent??R;(this.nodes.get(r)??this.nodes.get(R)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((r,a)=>{let o=this.nodes.get(r),l=this.nodes.get(a);return(o.created||"").localeCompare(l.created||"")}),this.orderProvider){let r=this.orderProvider(n.id);if(r.length>0){let a=new Map;r.forEach((o,l)=>a.set(o,l)),n.children.sort((o,l)=>{let c=a.has(o)?a.get(o):1/0,p=a.has(l)?a.get(l):1/0;return c===p?0:c-p})}}this.emit()}insertSynthetic(d){if(!d.file)return;let t=d.file.path;this.synthetic.set(t,d),this.nodes.set(d.id,d),this.byPath.set(t,d.id);let e=d.parent??R,s=this.nodes.get(e);s&&!s.children.includes(d.id)&&s.children.push(d.id),this.emit()}get(d){return this.nodes.get(d)}getRoot(){return this.nodes.get(R)}getChildren(d){let t=this.nodes.get(d);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let d=0;for(let t of this.nodes.values())t.file&&d++;return d}pathTo(d){let t=[],e=new Set,s=this.nodes.get(d);for(;s&&s.id!==R&&!e.has(s.id);)e.add(s.id),t.unshift(s),s=s.parent?this.nodes.get(s.parent):void 0;return t}idForPath(d){return this.byPath.get(d)}snapshot(){let d={};for(let t of this.nodes.values())t.id===R||!t.file||(d[t.id]={parent:t.parent===R?null:t.parent,path:t.file.path});return d}hookMetadataCache(d){let t=o=>{let l=this.currentFolder;return l?typeof o!="string"?!1:o===l||o.startsWith(l+"/"):!0},e=!1,s=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),d())},16))},i=o=>{o instanceof Wt.TFile&&t(o.path)&&o.extension==="md"&&this.applyChange(o)&&s()},n=o=>{o instanceof Wt.TFile&&t(o.path)&&o.extension==="md"&&this.applyChange(o)&&s()},r=o=>{let l=o?.path;typeof l=="string"&&t(l)&&this.applyDelete(l)&&s()},a=(o,l)=>{if(!(o instanceof Wt.TFile))return;let c=typeof l=="string"?l:null;!t(o.path)&&!t(c)||this.applyRename(o,c??"")&&s()};return this.app.metadataCache.on("changed",i),this.app.vault.on("create",n),this.app.vault.on("delete",r),this.app.vault.on("rename",a),()=>{this.app.metadataCache.off("changed",i),this.app.vault.off("create",n),this.app.vault.off("delete",r),this.app.vault.off("rename",a),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}applyChange(d){if(ye(d.path))return this.byPath.has(d.path)?this.applyDelete(d.path):!1;let t=this.app.metadataCache.getFileCache(d)?.frontmatter,e=t?.id,s=this.byPath.get(d.path);if(!e){if(s){let l=this.nodes.get(s);if(l&&l.file!==d)return l.file=d,!0}return!1}if(this.synthetic.delete(d.path),e===R){let l=this.nodes.get(R),c=t?.created??"",p=!1;return l.file!==d&&(l.file=d,p=!0),l.created!==c&&(l.created=c,p=!0),this.byPath.get(d.path)!==R&&(this.byPath.set(d.path,R),p=!0),p}let i=t?.parent??R,n=t?.created??"";if(!(i===R||this.nodes.has(i)))return this.rebuild(),!0;if(s&&s!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let l={id:e,parent:i,children:[],file:d,created:n};return this.nodes.set(e,l),this.byPath.set(d.path,e),this.attachToParent(l),this.resortChildrenOf(i),!0}let o=!1;if(a.file!==d&&(a.file=d,o=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??R),o=!0),a.parent!==i){let l=a.parent??R;this.detachFromParent(a),a.parent=i,this.attachToParent(a),this.resortChildrenOf(l),this.resortChildrenOf(i),o=!0}return o}applyDelete(d){let t=this.byPath.get(d);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(d),this.synthetic.delete(d),!0;this.detachFromParent(e);let s=this.nodes.get(R);for(let i of e.children){let n=this.nodes.get(i);n&&(n.parent=R,s.children.includes(i)||s.children.push(i))}return e.children.length>0&&this.resortChildrenOf(R),this.nodes.delete(t),this.byPath.delete(d),this.synthetic.delete(d),!0}applyRename(d,t){let e=this.currentFolder,s=!e||t===e||t.startsWith(e+"/"),i=!e||d.path===e||d.path.startsWith(e+"/");if(!s&&!i)return!1;if(s&&!i)return this.applyDelete(t);if(!s&&i)return this.applyChange(d);if(ye(d.path))return this.byPath.has(t)?this.applyDelete(t):!1;let n=this.byPath.get(t);if(!n)return this.applyChange(d);this.byPath.delete(t),this.byPath.set(d.path,n);let r=this.nodes.get(n);return r&&(r.file=d),!0}detachFromParent(d){let t=this.nodes.get(d.parent??R);if(!t)return;let e=t.children.indexOf(d.id);e>=0&&t.children.splice(e,1)}attachToParent(d){let t=this.nodes.get(d.parent??R);t||(t=this.nodes.get(R)),t.children.includes(d.id)||t.children.push(d.id)}resortChildrenOf(d){let t=this.nodes.get(d);if(t&&(t.children.sort((e,s)=>{let i=this.nodes.get(e),n=this.nodes.get(s);return(i.created||"").localeCompare(n.created||"")}),this.orderProvider)){let e=this.orderProvider(d);if(e.length>0){let s=new Map;e.forEach((i,n)=>s.set(i,n)),t.children.sort((i,n)=>{let r=s.has(i)?s.get(i):1/0,a=s.has(n)?s.get(n):1/0;return r===a?0:r-a})}}}};var Bs=class{constructor(){this.enabled=!1;this.buckets=new Map}record(d,t){if(!this.enabled)return;let e=this.buckets.get(d);e||(e={count:0,total:0,max:0},this.buckets.set(d,e)),e.count+=1,e.total+=t,t>e.max&&(e.max=t)}time(d,t){if(!this.enabled)return t();let e=performance.now();try{return t()}finally{this.record(d,performance.now()-e)}}async timeAsync(d,t){if(!this.enabled)return t();let e=performance.now();try{return await t()}finally{this.record(d,performance.now()-e)}}reset(){this.buckets.clear()}hasData(){return this.buckets.size>0}report(){let d=[...this.buckets.entries()].map(([e,s])=>({label:e,...s,avg:s.total/s.count})).sort((e,s)=>s.total-e.total);if(d.length===0)return"Stashpad perf: no samples (enable profiling, then use the app).";let t=["**Stashpad performance profile**","","| label | count | total (ms) | avg (ms) | max (ms) |","| --- | ---: | ---: | ---: | ---: |"];for(let e of d)t.push(`| \`${e.label}\` | ${e.count} | ${e.total.toFixed(0)} | ${e.avg.toFixed(1)} | ${e.max.toFixed(0)} |`);return t.join(` +`)}},Et=new Bs;var yi=".stashpad-order.json",rs=class{constructor(d){this.app=d;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(d){if(this.cache.has(d))return this.cache.get(d);let t=`${d}/${yi}`,e=this.app.vault.adapter,s={};try{if(await e.exists(t)){let i=await e.read(t),n=JSON.parse(i);if(n&&typeof n=="object"&&!Array.isArray(n))for(let[r,a]of Object.entries(n))Array.isArray(a)&&a.every(o=>typeof o=="string")&&(s[r]=a)}}catch(i){console.warn("Stashpad: order load failed",i)}return this.cache.set(d,s),s}async save(d){this.scheduleWrite(d)}async flush(d){let t=this.pendingTimers.get(d);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(d)),await this.writeNow(d)}scheduleWrite(d){let t=this.pendingTimers.get(d);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(d),this.writeNow(d)},150);this.pendingTimers.set(d,e)}async writeNow(d){let e=(this.writeInFlight.get(d)??Promise.resolve()).then(()=>this.doWrite(d));this.writeInFlight.set(d,e);try{await e}finally{this.writeInFlight.get(d)===e&&this.writeInFlight.delete(d)}}async doWrite(d){let t=this.cache.get(d)??{},e={};for(let[n,r]of Object.entries(t))r.length>0&&(e[n]=r);this.cache.set(d,e);let s=`${d}/${yi}`,i=this.app.vault.adapter;try{if(Object.keys(e).length===0)try{await i.remove(s)}catch{}else await i.write(s,JSON.stringify(e,null,2))}catch(n){console.warn("Stashpad: order save failed",n)}}getOrder(d,t){return this.cache.get(d)?.[t]?.slice()??[]}setOrder(d,t,e){let s=this.cache.get(d)??{};s[t]=e.slice(),this.cache.set(d,s)}appendChild(d,t,e){let s=this.cache.get(d)??{},i=s[t]??[];i.includes(e)||i.push(e),s[t]=i,this.cache.set(d,s)}removeChild(d,t){let e=this.cache.get(d);if(e)for(let s of Object.values(e)){let i=s.indexOf(t);i>=0&&s.splice(i,1)}}invalidate(d){this.cache.delete(d)}};var _e={manual:"Manual","created-asc":"Created \u2014 oldest first","created-desc":"Created \u2014 newest first","modified-asc":"Modified \u2014 oldest first","modified-desc":"Modified \u2014 newest first","title-az":"Title \u2014 A\u2192Z","title-za":"Title \u2014 Z\u2192A"},Hs=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],Qi=new Set(Hs),wi=".stashpad-sort.json",as=class{constructor(d){this.app=d;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(d){if(this.cache.has(d))return this.cache.get(d);let t=`${d}/${wi}`,e=this.app.vault.adapter,s={};try{if(await e.exists(t)){let i=JSON.parse(await e.read(t));if(i&&typeof i=="object"&&!Array.isArray(i))for(let[n,r]of Object.entries(i))typeof r=="string"&&Qi.has(r)&&(s[n]=r)}}catch(i){console.warn("Stashpad: sort load failed",i)}return this.cache.set(d,s),s}async save(d){this.scheduleWrite(d)}async flush(d){let t=this.pendingTimers.get(d);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(d)),await this.writeNow(d)}scheduleWrite(d){let t=this.pendingTimers.get(d);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(d),this.writeNow(d)},150);this.pendingTimers.set(d,e)}async writeNow(d){let e=(this.writeInFlight.get(d)??Promise.resolve()).then(()=>this.doWrite(d));this.writeInFlight.set(d,e);try{await e}finally{this.writeInFlight.get(d)===e&&this.writeInFlight.delete(d)}}async doWrite(d){let t=this.cache.get(d)??{},e=`${d}/${wi}`,s=this.app.vault.adapter;try{if(Object.keys(t).length===0)try{await s.remove(e)}catch{}else await s.write(e,JSON.stringify(t,null,2))}catch(i){console.warn("Stashpad: sort save failed",i)}}getMode(d,t){return this.cache.get(d)?.[t]??"manual"}setMode(d,t,e){let s=this.cache.get(d)??{};e==="manual"?delete s[t]:s[t]=e,this.cache.set(d,s)}removeParent(d,t){let e=this.cache.get(d);e&&delete e[t]}invalidate(d){this.cache.delete(d)}};Tt();var jt="parentLink",de="children";var cs=class cs{constructor(d,t){this.app=d;this.getTree=t;this.pending=new Set;this.timer=null;this.activityListeners=new Set;this.errorListeners=new Set}onActivity(d){return this.activityListeners.add(d),()=>this.activityListeners.delete(d)}emitActivity(){let d=this.pending.size;for(let t of this.activityListeners)try{t(d)}catch(e){console.warn("[Stashpad] fmSync activity listener failed",e)}}schedule(d){if(!d)return;let t=this.pending.size;this.pending.add(d),this.pending.size!==t&&this.emitActivity(),this.kick()}scheduleParentChange(d,t,e){this.schedule(d),t&&this.schedule(t),this.schedule(e)}scheduleSubtree(d){let t=this.getTree(),e=s=>{this.schedule(s);for(let i of t.getChildren(s))e(i.id)};e(d)}scheduleParentOfDeleted(d){d&&this.schedule(d)}async flush(){for(this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null);this.pending.size>0;){let d=this.pending.values().next().value;if(d===void 0)break;this.pending.delete(d),this.emitActivity(),await this.syncOne(d)}}pendingCount(){return this.pending.size}onError(d){return this.errorListeners.add(d),()=>this.errorListeners.delete(d)}emitError(d,t){for(let e of this.errorListeners)try{e(d,t)}catch(s){console.warn("[Stashpad] fmSync error listener failed",s)}}reset(){this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null),this.pending.clear()}kick(){this.timer!=null||this.pending.size===0||(this.timer=window.setTimeout(()=>this.tick(),cs.PACING_MS))}async tick(){this.timer=null;let d=this.pending.values().next().value;if(d!==void 0){this.pending.delete(d),this.emitActivity();try{await this.syncOne(d)}catch(t){console.warn("[Stashpad] frontmatter sync tick failed",t)}this.pending.size>0&&this.kick()}}wouldWrite(d){let e=this.getTree().get(d);if(!e||!e.file)return!1;let s=this.computeParentLink(e),i=this.computeChildrenLinks(e),n=this.app.metadataCache.getFileCache(e.file)?.frontmatter,r=n&&typeof n[jt]=="string"?n[jt]:null,a=n?.[de],o=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];if((r??null)!==(s??null)||o.length!==i.length)return!0;for(let l=0;l<o.length;l++)if(o[l]!==i[l])return!0;return!1}async syncOne(d){let e=this.getTree().get(d);if(!e||!e.file||!this.wouldWrite(d))return;let s=this.computeParentLink(e),i=this.computeChildrenLinks(e);try{await Et.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{s?n[jt]=s:delete n[jt],i.length>0?n[de]=i:delete n[de]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(d){if(d.id===R)return null;let t=this.getTree();if(!d.parent||d.parent===R){let s=t.getRoot();return s&&s.id!==d.id&&s.file?os(s.file.path):null}let e=t.get(d.parent);return e?.file?os(e.file.path):null}computeChildrenLinks(d){return this.getTree().getChildren(d.id).filter(e=>!!e.file).map(e=>os(e.file.path))}};cs.PACING_MS=100;var ls=cs;async function bi(g,d){let t=d.endsWith("/")?d:d+"/",e=new Map,s=new Map;for(let l of g.vault.getMarkdownFiles()){if(l.path!==d&&!l.path.startsWith(t))continue;let c=g.metadataCache.getFileCache(l)?.frontmatter,p=typeof c?.id=="string"?c.id:null;if(!p)continue;let u=typeof c?.parent=="string"?c.parent:R;e.set(p,{file:l,id:p,parent:u});let h=s.get(u)??[];h.push(p),s.set(u,h)}let i=l=>os(l.file.path),n=l=>{if(l.id===R)return null;if(l.parent===R||!l.parent){let p=e.get(R);return p?i(p):null}let c=e.get(l.parent);return c?i(c):null},r=l=>{let c=s.get(l.id)??[],p=[];for(let u of c){let h=e.get(u);h&&p.push(i(h))}return p},a=0,o=0;for(let l of e.values()){a+=1;let c=n(l),p=r(l),u=g.metadataCache.getFileCache(l.file)?.frontmatter,h=u&&typeof u[jt]=="string"?u[jt]:null,f=u?.[de],m=Array.isArray(f)?f.filter(b=>typeof b=="string"):[],v=(h??null)===(c??null),y=m.length===p.length&&m.every((b,k)=>b===p[k]);if(!(v&&y))try{await g.fileManager.processFrontMatter(l.file,b=>{c?b[jt]=c:delete b[jt],p.length>0?b[de]=p:delete b[de]}),o+=1,await new Promise(b=>setTimeout(b,50))}catch(b){console.warn("[Stashpad] rebootstrap fm sync failed",l.file.path,b)}}return{checked:a,written:o}}function os(g){return`[[${g.replace(/\.md$/i,"")}]]`}Mt();ae();var ds=class{constructor(d,t){this.tree=d;this.log=t}async sweep(d){let t=await this.log.readState(),e=this.tree.snapshot(),s=n=>{if(!d)return!0;let r=d.replace(/\/+$/,"");return n===r||n.startsWith(r+"/")};for(let[n,r]of Object.entries(e)){let a=t[n];a?a.parent!==r.parent?await this.log.append({type:"parent_change",id:n,payload:{from:a.parent,to:r.parent}}):a.path!==r.path&&await this.log.append({type:"rename",id:n,payload:{from:a.path,to:r.path}}):await this.log.append({type:"create",id:n,payload:{path:r.path,parent:r.parent}})}for(let[n,r]of Object.entries(t))!e[n]&&s(r.path)&&await this.log.append({type:"missing",id:n,payload:{lastPath:r.path}});let i={};for(let[n,r]of Object.entries(t))s(r.path)||(i[n]=r);for(let[n,r]of Object.entries(e))i[n]=r;await this.log.writeState(i)}};var dt=require("obsidian");Tt();Es();function zs(g){let d=g.trim().toLowerCase();if(!d)return null;let t=Date.now(),e=f=>(0,dt.moment)(f).startOf("day").valueOf(),s=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,i=0,n=!1,r=d,a=s.exec(d);if(a&&(a[3]||a[2])){let f=parseInt(a[1],10),m=a[2]?parseInt(a[2],10):0,v=a[3];v==="pm"&&f<12&&(f+=12),v==="am"&&f===12&&(f=0),f>=0&&f<24&&m>=0&&m<60&&(i=(f*3600+m*60)*1e3,n=!0,r=d.replace(a[0]," ").replace(/\s+/g," ").trim())}let o=f=>n?f+i:f;if(r===""||r==="today")return o(e(t));if(r==="yesterday")return o(e(t)-864e5);if(r==="tomorrow")return o(e(t)+864e5);let l=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],c=["sun","mon","tue","wed","thu","fri","sat"],p=l.indexOf(r)>=0?l.indexOf(r):c.indexOf(r);if(p>=0){let f=(0,dt.moment)().startOf("day"),v=(f.day()-p+7)%7;return o(f.subtract(v,"days").valueOf())}let u=/^(\d+)\s*([dwmy])$/.exec(r);if(u){let f=parseInt(u[1],10),m={d:"days",w:"weeks",m:"months",y:"years"}[u[2]];return o((0,dt.moment)().subtract(f,m).startOf("day").valueOf())}let h=(0,dt.moment)(r,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return h.isValid()?o(h.startOf("day").valueOf()):null}function Si(g){let d={text:[],filters:{}},t=(g||"").trim();if(!t)return d;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,s=t,i;for(;(i=e.exec(t))!=null;){let n=i[1].toLowerCase(),r=(i[2]!==void 0?i[2]:i[3]??"").trim();if(r){if(n==="in")d.filters.in=r.toLowerCase();else if(n==="before"){let a=zs(r);a!=null&&(d.filters.before=a)}else if(n==="after"){let a=zs(r);a!=null&&(d.filters.after=a)}else if(n==="on"){let a=zs(r);if(a!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(r))d.filters.on={start:a-6e4,end:a+6e4};else{let l=(0,dt.moment)(a).startOf("day").valueOf();d.filters.on={start:l,end:l+864e5}}}s=s.replace(i[0]," ")}}for(let n of s.split(/\s+/))n&&d.text.push(n.toLowerCase());return d}var $t=class g extends dt.SuggestModal{constructor(t,e,s,i){super(t);this.tree=e;this.titleFn=s;this.opts=i;this.notes=[];this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(i.placeholder??(i.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}onClose(){for(;this.pendingCleanups.length>0;){let t=this.pendingCleanups.pop();try{t&&t()}catch{}}}loadAll(){let t=(s,i)=>{let n=this.tree.get(s);n?.file&&s!==R?this.notes.push({node:n,title:`${" ".repeat(i)}${this.titleFn(n)}`,body:""}):n?.file&&s===R&&this.notes.push({node:n,title:"Home",body:""});for(let r of this.tree.getChildren(s))t(r.id,i+1)},e=this.tree.getRoot();e.file&&this.notes.push({node:e,title:"Home",body:""});for(let s of this.tree.getChildren(R))t(s.id,1);for(let s of this.notes)s.node?.file&&this.app.vault.cachedRead(s.node.file).then(i=>{s.body=this.stripFm(i)});if(this.opts.crossFolderNotes){let s=this.opts.crossFolderNotes();for(let i of s)this.notes.push({node:null,title:i.title,body:i.body,cross:i});for(let i of this.notes)!i.cross||i.body||i.cross.file&&this.app.vault.cachedRead(i.cross.file).then(n=>{i.body=this.stripFm(n)})}}createdMsFor(t){if(t.node?.created){let e=Date.parse(t.node.created);if(!Number.isNaN(e))return e}return t.cross?.file?.stat?.ctime!=null?t.cross.file.stat.ctime:null}stripFm(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` +---`,3);return e===-1?t:t.slice(e+4).replace(/^\r?\n/,"")}getSuggestions(t){let e=t.trim().toLowerCase(),s=Si(t),i=s.text;console.log("[Stashpad] search query parsed",{query:t,text:s.text,filters:s.filters});let n=y=>{if(!i.length)return!0;for(let b of i)if(!y.includes(b))return!1;return!0},r=null,a=null;if(s.filters.in){let y=s.filters.in.split(/\s+/).filter(Boolean);r=new Set,a=new Map;let b=I=>y.every(E=>I.toLowerCase().includes(E)),k=I=>{if(!r.has(I)){r.add(I);for(let E of this.tree.getChildren(I))k(E.id)}};for(let I of this.notes)!I.node||I.cross||b(I.title)&&k(I.node.id);let T=new Map;for(let I of this.notes){if(!I.cross)continue;let E=T.get(I.cross.folder)??[];E.push(I),T.set(I.cross.folder,E)}for(let[I,E]of T){let D=new Map;for(let A of E){let S=A.cross?.parentId??null;if(!S)continue;let _=D.get(S)??[];_.push(A.cross.id),D.set(S,_)}let H=new Set;a.set(I,H);let C=A=>{if(!H.has(A)){H.add(A);for(let S of D.get(A)??[])C(S)}};for(let A of E)b(A.title)&&C(A.cross.id)}}let o=y=>{let b=s.filters;if(r||a)if(y.cross){let k=a?.get(y.cross.folder);if(!k||!k.has(y.cross.id))return!1}else if(y.node){if(!r||!r.has(y.node.id))return!1}else return!1;if(b.before||b.after||b.on){let k=this.createdMsFor(y);if(k==null||b.before!=null&&k>=b.before||b.after!=null&&k<=b.after||b.on&&(k<b.on.start||k>=b.on.end))return!1}return!0},l=y=>n(y.toLowerCase()),c=this.notes.filter(y=>!y.cross),p=this.notes.filter(y=>y.cross),u=(y,b)=>({id:y.cross?`cross:${y.cross.id}`:y.node.id,label:y.title,node:y.node,kind:"note",bodyPreview:this.previewFromBody(y.body,b),matchLine:b,crossFolder:y.cross?.folder,crossFile:y.cross?.file}),h=y=>{let b=[];for(let k of y)if(o(k))if(this.opts.mode==="search"){if(!e){b.push(u(k,-1));continue}let T=n(k.title.toLowerCase()),I=k.body.split(/\r?\n/),E=[];for(let H=0;H<I.length;H++)l(I[H])&&E.push(H);let D=E.length>0||n(k.body.toLowerCase());if(!T&&!D)continue;if(E.length===0)b.push(u(k,-1));else{let H=[],C=-100;for(let S of E)S-C>5&&H.push(S),C=S;let A=5;for(let S of H.slice(0,A))b.push(u(k,S))}}else{if(e&&!n(k.title.toLowerCase())&&!n(k.body.toLowerCase()))continue;b.push(u(k,-1))}return b},f=h(c),m=[...f];if(this.opts.mode==="search"?e?!0:f.length<10:!!e){let y=h(p);this.opts.mode==="search"&&!e&&(m.length=Math.min(m.length,50)),m.push(...y)}if(this.opts.folderResults){let y=this.opts.folderResults(),b=!e||y.some(k=>{let T=k.split("/").pop()??k;return n(`${k.toLowerCase()} ${T.toLowerCase()}`)});if(y.length>0&&b){let k={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};Object.keys(s.filters).length>0?m.push(k):m.unshift(k)}}return this.opts.allowCreate&&e&&!m.some(y=>y.label.trim().toLowerCase()===e)&&m.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),m}previewFromBody(t,e){let s=t.split(/\r?\n/);if(e<0)return s.filter(a=>a.trim().length>0).slice(0,3).join(` `);let i=Math.max(0,e-2),n=Math.min(s.length,e+3);return s.slice(i,n).filter(r=>r.trim().length>0).join(` -`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}if(t.kind==="folder-open"){e.addClass("is-folder-open"),e.createDiv({cls:"stashpad-suggest-title",text:t.label}),t.folder?e.createDiv({cls:"stashpad-suggest-preview",text:t.folder}):e.createDiv({cls:"stashpad-suggest-preview",text:"Click to choose a folder\u2026"});return}t.crossFolder&&e.addClass("is-cross-folder"),e.addClass("stashpad-suggest-row");let s=e.createDiv({cls:"stashpad-suggest-body"}),i=this.notes.find(d=>t.crossFolder?d.cross?.id===t.id.replace(/^cross:/,""):d.node?.id===t.id),n=gi(this.inputEl?.value??"").text,r=this.firstLineOfBody(i?.body??"")||t.label.trim(),o=s.createDiv({cls:"stashpad-suggest-title"});this.highlightInto(o,r,n);let a=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let d=s.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(d,t.bodyPreview,n)}let l="";if(t.crossFolder?l=i?.cross?.parentBlurb??"":l=this.parentBlurbFor(t.node),l){let d=s.createDiv({cls:"stashpad-suggest-preview"});d.appendText("Parent: "),this.highlightInto(d,l,n)}let c=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),p=t.crossFolder??this.opts.localFolder??null;if(p||c){let d=s.createDiv({cls:"stashpad-suggest-breadcrumb"}),m=[p?p.split("/").pop()||p:"",c].filter(v=>v&&v.length>0).join(" \u203A ");m&&d.setText(m)}let u=i?this.createdMsFor(i):null;if(u!=null||a){let d=e.createDiv({cls:"stashpad-suggest-rail"});if(u!=null){let f=d.createDiv({cls:"stashpad-suggest-time"});f.setText(this.formatRelativeTime(u)),f.title=(0,dt.moment)(u).format("YYYY-MM-DD HH:mm")}a&&d.createDiv({cls:"stashpad-suggest-folder-badge",text:a.split("/").pop()||a})}}formatRelativeTime(t){let e=(0,dt.moment)(t),s=(0,dt.moment)().startOf("day").diff((0,dt.moment)(t).startOf("day"),"days");return s===0?e.format("h:mm a"):s===1?"yesterday":s>1&&s<7?`${s}d ago`:s>=7&&s<30?`${Math.floor(s/7)}w ago`:s>=30&&s<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,s){if(!e)return;let i=s.filter(l=>l&&l.length>0);if(!i.length){t.appendText(e);return}let n=e.toLowerCase(),r=[];for(let l of i){let c=0;for(;(c=n.indexOf(l,c))!==-1;)r.push([c,c+l.length]),c+=l.length}if(!r.length){t.appendText(e);return}r.sort((l,c)=>l[0]-c[0]);let o=[];for(let l of r){let c=o[o.length-1];c&&l[0]<=c[1]?c[1]=Math.max(c[1],l[1]):o.push([l[0],l[1]])}let a=0;for(let[l,c]of o)l>a&&t.appendText(e.slice(a,l)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(l,c)}),a=c;a<e.length&&t.appendText(e.slice(a))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===R)return"";let e=[],s=new Set([t.id]),i=this.tree.get(t.parent);for(;i&&i.id!==R&&!s.has(i.id);)s.add(i.id),e.unshift(this.titleFn(i)),i=i.parent&&i.parent!==R?this.tree.get(i.parent):null;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let a of this.notes){if(!a.cross)continue;let l=this.crossFolderIndex.get(a.cross.folder);l||(l=new Map,this.crossFolderIndex.set(a.cross.folder,l)),l.set(a.cross.id,a.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let s=t.id.replace(/^cross:/,""),i=e.get(s);if(!i)return"";let n=[],r=new Set([i.id]),o=i.parentId?e.get(i.parentId):null;for(;o&&!r.has(o.id);)r.add(o.id),n.unshift(o.title),o=o.parentId?e.get(o.parentId):null;return n.join(" \u203A ")}firstLineOfBody(t){if(!t)return"";let e=t.split(/\r?\n/);for(let s of e){let i=s.trim();if(i)return i}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===R)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let s=this.notes.find(i=>i.node?.id===e.id);return s?this.firstLineOfBody(s.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!dt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(dt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",l=>{if(l.key==="["){l.preventDefault();let c=t.selectionStart??t.value.length,p=t.selectionEnd??c,u=t.value.slice(0,c),d=t.value.slice(c,p),f=t.value.slice(p);t.value=`${u}[${d}]${f}`;let m=c+1+d.length;t.setSelectionRange(m,m),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(l.key==="]"){let c=t.selectionStart??-1;c>=0&&t.value[c]==="]"&&(l.preventDefault(),t.setSelectionRange(c+1,c+1));return}if(l.key==="Backspace"&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&t.selectionStart===t.selectionEnd){let c=t.selectionStart??-1;if(c>0&&t.value[c-1]==="["&&t.value[c]==="]"){l.preventDefault();let p=t.value.slice(0,c-1),u=t.value.slice(c+1);t.value=`${p}${u}`,t.setSelectionRange(c-1,c-1),t.dispatchEvent(new Event("input",{bubbles:!0}))}}});let s=document.createElement("div");s.className="stashpad-search-filter-row";let i=document.createElement("span");i.className="stashpad-search-filter-label",i.textContent="Filters:",s.appendChild(i);let n=document.createElement("button");n.className="stashpad-search-filter-chip",n.type="button",n.textContent="in:[parent note]",n.title='Insert "in:" \u2014 filter by parent note.',n.addEventListener("mousedown",l=>{l.preventDefault()}),n.addEventListener("click",l=>{l.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),n.click())}),s.appendChild(n);let r=document.createElement("button");r.className="stashpad-search-filter-chip stashpad-search-filter-when",r.type="button",r.textContent="when:[date / day / timeframe]",r.title="Open the time-filter builder (Before / On / After / Between).",r.addEventListener("mousedown",l=>{l.preventDefault()}),r.addEventListener("click",l=>{l.preventDefault(),this.toggleWhenBuilder(t,s)}),r.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),r.click())}),s.appendChild(r),e.parentElement?.insertBefore(s,e);let o=new dt.Scope(this.scope),a=l=>{let c=document.activeElement;return c?.classList?.contains("stashpad-search-filter-chip")?(l.preventDefault(),c.click(),!1):l.key==="Enter"&&!l.isComposing?(l.preventDefault(),this.selectActiveSuggestion?.(l),!1):!0};o.register([],"Enter",a),o.register([]," ",a),o.register(["Mod"],"f",l=>{l.preventDefault();let c=this.inputEl;return c&&(c.focus(),c.select()),!1}),o.register([],"Tab",l=>{let c=this.modalEl,p=this.inputEl;if(!c)return!0;let u=Array.from(c.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(m=>!m.hasAttribute("disabled")&&m.tabIndex!==-1&&m.offsetParent!==null);if(u.length===0)return!0;let d=document.activeElement,f=d?u.indexOf(d):-1;if(l.shiftKey){if(f<=0)return l.preventDefault(),u[u.length-1].focus(),!1}else if(f===u.length-1)return l.preventDefault(),(p??u[0]).focus(),!1;return!0}),this.app.keymap?.pushScope(o),this.pendingCleanups.push(()=>{try{this.app.keymap?.popScope(o)}catch{}})}appendFilterToInput(t,e,s){let i=t.value,r=`${i.length>0&&!/\s$/.test(i)?" ":""}${e}: [`,o="]",a=s;t.value=`${i}${r}${a}${o}`;let l=i.length+r.length+a.length;if(t.setSelectionRange(l,l+0),!a){let c=i.length+r.length;t.setSelectionRange(c,c)}t.focus(),t.dispatchEvent(new Event("input",{bubbles:!0}))}toggleWhenBuilder(t,e){let s=this.modalEl;if(this.whenBuilderEl){this.whenBuilderEl.remove(),this.whenBuilderEl=null,s?.removeClass("is-when-builder-open");return}s?.addClass("is-when-builder-open");let i=document.createElement("div");i.className="stashpad-when-builder";let n=document.createElement("div");n.className="stashpad-when-tabs";let r=[{id:"before",label:"Before"},{id:"on",label:"On"},{id:"after",label:"After"},{id:"between",label:"Between"}],o={};for(let m of r){let v=document.createElement("button");v.type="button",v.className="stashpad-when-tab",v.textContent=m.label,this.whenMode===m.id&&v.addClass("is-active"),v.addEventListener("mousedown",y=>y.preventDefault()),v.addEventListener("click",y=>{if(y.preventDefault(),this.whenMode===m.id)return;let b=this.whenMode;b!=="between"&&m.id==="between"?(this.whenBetweenEndText="",this.whenBetweenEndDate="",this.whenBetweenEndTime=""):b==="between"&&m.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),!this.whenSingleDate&&this.whenBetweenEndDate&&(this.whenSingleDate=this.whenBetweenEndDate,this.whenSingleTime=this.whenBetweenEndTime),this.whenBetweenEndText="",this.whenBetweenEndDate="",this.whenBetweenEndTime=""),this.whenMode=m.id;for(let k in o)o[k].toggleClass("is-active",k===m.id);f()}),o[m.id]=v,n.appendChild(v)}i.appendChild(n);let a=document.createElement("div");a.className="stashpad-when-body",i.appendChild(a);let l=(m,v,y="single")=>{let b=(0,dt.moment)().format("YYYY-MM-DD"),k=!v||v===b;if(y==="betweenStart")return"00:00";if(y==="betweenEnd")return"23:59";switch(m){case"after":return"00:00";case"on":return k?(0,dt.moment)().format("HH:mm"):"23:59";case"before":return k?(0,dt.moment)().format("HH:mm"):"23:59";default:return"23:59"}},c=(m,v)=>{m.addEventListener("keydown",y=>{y.key==="Enter"?(y.preventDefault(),y.stopPropagation(),v()):y.key==="Escape"&&(y.preventDefault(),y.stopPropagation(),this.closeWhenBuilder())})},p=(m,v)=>{let y=m.selectionStart??m.value.length,b=m.selectionEnd??m.value.length,C=`${y>0&&!/\s$/.test(m.value.slice(0,y))?" ":""}${v}`,I=m.value.slice(0,y)+C+m.value.slice(b);m.value=I;let E=y+C.length;m.setSelectionRange(E,E),m.focus(),m.dispatchEvent(new Event("input",{bubbles:!0}))},u=(m,v)=>{let b=m.slice(0,v).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return b?b[1]:null},d=(m,v,y,b)=>{let k=a.createDiv({cls:"stashpad-when-input-wrap has-icons"}),C=k.createDiv({cls:"stashpad-when-icon-slot"}),I=C.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});I.type="button",I.title="Pick date",(0,dt.setIcon)(I,"calendar-days");let E=C.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});E.tabIndex=-1;let D=k.createDiv({cls:"stashpad-when-icon-slot"}),H=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});H.type="button",H.title="Pick time",(0,dt.setIcon)(H,"clock");let T=k.createDiv({cls:"stashpad-when-icon-slot"}),A=T.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});A.type="button",A.title="Pick day",(0,dt.setIcon)(A,"calendar");let S=k.createDiv({cls:"stashpad-when-icon-slot"}),_=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});_.type="button",_.title="Pick timeframe",(0,dt.setIcon)(_,"history");let J=k.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:m}});J.value=v(),J.addEventListener("input",()=>y(J.value));let U=k.createEl("button",{cls:"stashpad-when-clear"});U.type="button",U.textContent="\xD7",U.title="Clear";for(let P of[I,H,A,_,U])P.addEventListener("mousedown",X=>X.preventDefault());let z=null,W=(P,X)=>{z&&z();let q=P.createDiv({cls:"stashpad-when-popover"}),Y=new dt.Scope(this.scope),ct=null,pt=it=>{ct=it},nt=!1,rt=it=>{!q.contains(it.target)&&it.target!==P&&!P.contains(it.target)&&at()},at=()=>{if(!nt){nt=!0,q.remove(),document.removeEventListener("mousedown",rt,!0);try{this.app.keymap?.popScope(Y)}catch{}z===at&&(z=null)}};z=at,Y.register([],"Escape",it=>(it.preventDefault(),at(),!1)),Y.register([],"Enter",it=>(it.preventDefault(),ct&&ct(),!1));try{X(q,at,pt)}catch(it){console.error("[stashpad] popover fill threw:",it),q.remove(),z=null;return}this.app.keymap?.pushScope(Y),this.pendingCleanups.push(at),setTimeout(()=>document.addEventListener("mousedown",rt,!0),0)};_.addEventListener("click",P=>{P.preventDefault(),W(S,(X,q,Y)=>{let ct=this.whenMode==="on",pt=(B,$)=>{if(!ct)return`${B}${$}`;let x={d:"days",w:"weeks",m:"months",y:"years"}[$];return(0,dt.moment)().subtract(B,x).format("YYYY-MM-DD")},nt=X.createDiv({cls:"stashpad-when-pop-row"}),rt=[{label:"Last 7d",n:7,unit:"d"},{label:"Last 30d",n:30,unit:"d"},{label:"This week",n:1,unit:"w"},{label:"This month",n:1,unit:"m"}];for(let B of rt){let $=nt.createEl("button",{cls:"stashpad-when-pop-chip",text:B.label});$.type="button",$.addEventListener("mousedown",x=>x.preventDefault()),$.addEventListener("click",x=>{x.preventDefault(),p(J,pt(B.n,B.unit)),q()})}let at=X.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});at.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let it=at.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),gt=at.createEl("select",{cls:"stashpad-when-pop-unit"});for(let B of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let $=gt.createEl("option",{text:B.label});$.value=B.v}let ft=at.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ft.type="button";let w=()=>{let B=parseInt(it.value,10);!Number.isFinite(B)||B<1||(p(J,pt(B,gt.value)),q())};ft.addEventListener("mousedown",B=>B.preventDefault()),ft.addEventListener("click",B=>{B.preventDefault(),w()}),Y(w),it.focus(),it.select()})});let Q=(P,X,q,Y,ct)=>{W(X,(pt,nt,rt)=>{Le(pt,{seedH:q,seedM:Y,seedPeriod:ct,close:nt,setOnEnter:rt,onFinalize:at=>p(P,ti(at))})})};A.addEventListener("click",P=>{P.preventDefault(),W(T,(X,q,Y)=>{let ct=X.createDiv({cls:"stashpad-when-pop-row"});for(let it of["Today","Yesterday"]){let gt=ct.createEl("button",{cls:"stashpad-when-pop-chip",text:it});gt.type="button",gt.addEventListener("mousedown",ft=>ft.preventDefault()),gt.addEventListener("click",ft=>{ft.preventDefault(),p(J,it),q()})}let pt=X.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),nt=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],at=((0,dt.moment)().day()+6)%7;for(let it=0;it<nt.length;it++){let gt=nt[it],ft=pt.createEl("button",{cls:"stashpad-when-pop-chip",text:gt.slice(0,3)});ft.type="button",ft.title=gt,it===at&&ft.addClass("is-today"),ft.addEventListener("mousedown",w=>w.preventDefault()),ft.addEventListener("click",w=>{if(w.preventDefault(),b==="betweenEnd"){let B=it,$=(0,dt.moment)().startOf("day"),x=($.day()+6)%7,F=(B-x+7)%7;F===0&&(F=7);let M=$.clone().add(F,"days").format("YYYY-MM-DD");p(J,M)}else p(J,gt);q()})}})});let N=(P,X)=>{P.value||(P.value=X);let q=P;if(typeof q.showPicker=="function")try{q.showPicker();return}catch{}P.focus(),P.click()};return I.addEventListener("click",P=>{P.preventDefault(),N(E,(0,dt.moment)().format("YYYY-MM-DD"))}),E.addEventListener("change",()=>{E.value&&p(J,E.value)}),H.addEventListener("click",P=>{P.preventDefault();let X=J.selectionStart??J.value.length,q=u(J.value,X),Y=l(this.whenMode,q,b),[ct,pt]=Y.split(":"),nt=parseInt(ct,10),rt=parseInt(pt,10),at=nt%12;at===0&&(at=12);let it=nt>=12?"pm":"am";Q(J,D,at,rt,it)}),U.addEventListener("click",P=>{P.preventDefault(),J.value="",y(""),J.focus()}),J},f=()=>{if(a.empty(),this.whenMode==="between"){let m=d("start (date / day / timeframe)",()=>this.whenSingleText,I=>{this.whenSingleText=I},"betweenStart"),v=d("end (date / day / timeframe)",()=>this.whenBetweenEndText,I=>{this.whenBetweenEndText=I},"betweenEnd"),y=a.createDiv({cls:"stashpad-when-actions"}),b=y.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});b.type="button",b.addEventListener("mousedown",I=>I.preventDefault());let k=()=>{let I=m.value.trim(),E=v.value.trim();I&&this.appendFilterToInput(t,"after",I),E&&this.appendFilterToInput(t,"before",E),this.closeWhenBuilder()};b.addEventListener("click",I=>{I.preventDefault(),k()});let C=y.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});C.type="button",C.addEventListener("mousedown",I=>I.preventDefault()),C.addEventListener("click",I=>{I.preventDefault(),this.closeWhenBuilder()}),c(m,k),c(v,k),m.focus(),m.setSelectionRange(m.value.length,m.value.length)}else{let m=d("date / day / timeframe",()=>this.whenSingleText,C=>{this.whenSingleText=C},"single"),v=a.createDiv({cls:"stashpad-when-actions"}),y=v.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});y.type="button",y.addEventListener("mousedown",C=>C.preventDefault());let b=()=>{let C=m.value.trim();C&&this.appendFilterToInput(t,this.whenMode,C),this.closeWhenBuilder()};y.addEventListener("click",C=>{C.preventDefault(),b()});let k=v.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});k.type="button",k.addEventListener("mousedown",C=>C.preventDefault()),k.addEventListener("click",C=>{C.preventDefault(),this.closeWhenBuilder()}),c(m,b),m.focus(),m.setSelectionRange(m.value.length,m.value.length)}};f(),e.parentElement?.insertBefore(i,e.nextSibling),this.whenBuilderEl=i}closeWhenBuilder(){if(!this.whenBuilderEl)return;this.whenBuilderEl.remove(),this.whenBuilderEl=null,this.modalEl?.removeClass("is-when-builder-open")}onChooseSuggestion(t){if(t.kind==="create"&&this.opts.onCreate){this.opts.onCreate(this.inputEl?.value??"");return}if(t.kind==="folder-open"&&t.id==="__folder_picker__"){let e=this.opts.folderResults?.()??[];if(!e.length)return;let s=this.inputEl?.value??"",i=!1,n=u=>{i=!0;let d=u.split("/").pop()??u;this.opts.onPick({id:`folder:${u}`,label:`Open folder \u201C${d}\u201D in a new tab`,node:null,kind:"folder-open",folder:u})},r=new $s(this.app,e,n),o=r.onClose.bind(r),a=this.tree,l=this.titleFn,c=this.opts,p=this.app;r.onClose=()=>{if(o(),!i){let u=new g(p,a,l,c);u.open(),setTimeout(()=>{let d=u.inputEl;d&&(s&&(d.value=s,d.dispatchEvent(new Event("input",{bubbles:!0}))),d.focus(),d.setSelectionRange(d.value.length,d.value.length))},0)}},r.open();return}this.opts.onPick(t)}},$s=class extends dt.FuzzySuggestModal{constructor(t,e,s){super(t);this.folders=e;this.onChosen=s;this.setPlaceholder("Open which folder?")}getItems(){return this.folders}getItemText(t){let e=t.split("/").pop()??t;return e===t?t:`${e} \u2014 ${t}`}onChooseItem(t){this.onChosen(t)}};Bt();var Hs=Oi(yi()),os=require("obsidian");Pt();Tt();var Gt="stash",Si=1;function wi(g){let t=(g.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var Bs=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function ki(g,h){let t=new Hs.default,e=Ki([...h.rootNotes,...h.allDescendants]),s=new Map,i=[];for(let r of e){let o=await g.vault.read(r.file),a=o,l=Zi(o);for(let c of l){let p=g.metadataCache.getFirstLinkpathDest(c,r.file.path);if(!p){i.push(`Missing attachment "${c}" in ${r.file.path}`);continue}let u=p.name;s.has(u)||s.set(u,await g.vault.readBinary(p)),a=Gi(a,c,u)}a=Xi(a,g,r.file.path),t.file(`notes/${r.file.name}`,a)}for(let[r,o]of s)t.file(`attachments/${r}`,o);let n={stashSchema:Si,exportedAt:new Date().toISOString(),sourceFolder:h.sourceFolder,noteCount:e.length,rootIds:h.rootNotes.map(r=>r.id)};return t.file("manifest.json",JSON.stringify(n,null,2)),i.length&&t.file("warnings.txt",i.join(` -`)),t.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:6}})}async function ls(g,h,t,e){let s=await Hs.default.loadAsync(h),i=s.file("manifest.json");if(!i)throw new Error("Not a valid .stash package: missing manifest.json");let n=JSON.parse(await i.async("string"));if(typeof n.stashSchema!="number"||n.stashSchema>Si)throw new Error(`Unsupported .stash schema: v${n.stashSchema}`);await bi(g,t);let r=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("notes/")&&v.name.endsWith(".md")),o=[];for(let v of r){let y=await v.async("string"),{fm:b,body:k}=Ee(y),C=wi(v.name.slice(6))||`${b.id||"imported-"+yt(4)}.md`;o.push({originalName:C,fm:b,body:k})}let a=new Map,l=0;for(let v of o){let y=v.fm.id;y&&(e.has(y)||a.has(y)?(a.set(y,`${y}-${yt(4)}-Imported`),l++):a.set(y,y))}let c=new Date().toISOString(),p=[],u=`${t}/_attachments`,d=0,f=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("attachments/"));f.length>0&&await bi(g,u);for(let v of f){let y=wi(v.name.slice(12));if(!y)continue;let b=`${u}/${y}`;if(await g.vault.adapter.exists(b))continue;let k=await v.async("arraybuffer");await g.vault.createBinary(b,k),d++}let m=0;for(let v of o){let y=v.fm.id;if(!y){p.push(`Skipped ${v.originalName} \u2014 no id in frontmatter`);continue}let b=a.get(y),k=v.fm.parent??null,C=k;k&&k!==R&&a.has(k)?C=a.get(k):k&&k!==R&&!a.has(k)&&(C=R);let I=Ji(v.body,u),E={...v.fm,id:b,parent:C,import_date:c};Array.isArray(E.attachments)&&(E.attachments=E.attachments.map(A=>`${u}/${Ti(A)}`));let D=jt(E,I),H=b===y?v.originalName:tn(v.originalName,y,b),T=`${t}/${H}`;await g.vault.adapter.exists(T)&&(H=`${H.replace(/\.md$/,"")}-${yt(4)}.md`,T=`${t}/${H}`),await g.vault.create(T,D),m++}return{notesWritten:m,attachmentsWritten:d,collisionsRenamed:l,warnings:p}}function Ki(g){let h=new Set,t=[];for(let e of g)h.has(e.id)||(h.add(e.id),t.push(e));return t}function Zi(g){let h=new Set,t;for(Bs.lastIndex=0;(t=Bs.exec(g))!==null;)h.add(t[1]);return[...h]}function Gi(g,h,t){return g.replace(new RegExp(`!\\[\\[${Qi(h)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,s)=>`![[${t}${s??""}]]`)}function Ji(g,h){return g.replace(Bs,(t,e,s)=>e.includes("/")?t:t.replace(e,`${h}/${e}`))}function Xi(g,h,t){let e=Ee(g);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return g;let s=e.fm.attachments.map(n=>{let r=h.metadataCache.getFirstLinkpathDest(n,t);return r?r.name:Ti(n)}),i={...e.fm,attachments:s};return jt(i,e.body)}function Qi(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ti(g){let h=g.lastIndexOf("/");return h<0?g:g.slice(h+1)}function tn(g,h,t){return g.includes(h)?g.replace(h,t):g.replace(/\.md$/,`-${t}.md`)}function Ee(g){if(!g.startsWith("---"))return{fm:{},body:g};let h=g.indexOf(` ----`,3);if(h<0)return{fm:{},body:g};let t=g.slice(3,h).replace(/^\n/,""),e=g.slice(h+4),s={};try{s=(0,os.parseYaml)(t)??{}}catch{s={}}let i=e.startsWith(` -`)?e.slice(1):e;return{fm:s,body:i}}function jt(g,h){return`--- -${(0,os.stringifyYaml)(g).trimEnd()} +`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}if(t.kind==="folder-open"){e.addClass("is-folder-open"),e.createDiv({cls:"stashpad-suggest-title",text:t.label}),t.folder?e.createDiv({cls:"stashpad-suggest-preview",text:t.folder}):e.createDiv({cls:"stashpad-suggest-preview",text:"Click to choose a folder\u2026"});return}t.crossFolder&&e.addClass("is-cross-folder"),e.addClass("stashpad-suggest-row");let s=e.createDiv({cls:"stashpad-suggest-body"}),i=this.notes.find(h=>t.crossFolder?h.cross?.id===t.id.replace(/^cross:/,""):h.node?.id===t.id),n=Si(this.inputEl?.value??"").text,r=this.firstLineOfBody(i?.body??"")||t.label.trim(),a=s.createDiv({cls:"stashpad-suggest-title"});this.highlightInto(a,r,n);let o=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let h=s.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(h,t.bodyPreview,n)}let l="";if(t.crossFolder?l=i?.cross?.parentBlurb??"":l=this.parentBlurbFor(t.node),l){let h=s.createDiv({cls:"stashpad-suggest-preview"});h.appendText("Parent: "),this.highlightInto(h,l,n)}let c=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),p=t.crossFolder??this.opts.localFolder??null;if(p||c){let h=s.createDiv({cls:"stashpad-suggest-breadcrumb"}),m=[p?p.split("/").pop()||p:"",c].filter(v=>v&&v.length>0).join(" \u203A ");m&&h.setText(m)}let u=i?this.createdMsFor(i):null;if(u!=null||o){let h=e.createDiv({cls:"stashpad-suggest-rail"});if(u!=null){let f=h.createDiv({cls:"stashpad-suggest-time"});f.setText(this.formatRelativeTime(u)),f.title=(0,dt.moment)(u).format("YYYY-MM-DD HH:mm")}o&&h.createDiv({cls:"stashpad-suggest-folder-badge",text:o.split("/").pop()||o})}}formatRelativeTime(t){let e=(0,dt.moment)(t),s=(0,dt.moment)().startOf("day").diff((0,dt.moment)(t).startOf("day"),"days");return s===0?e.format("h:mm a"):s===1?"yesterday":s>1&&s<7?`${s}d ago`:s>=7&&s<30?`${Math.floor(s/7)}w ago`:s>=30&&s<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,s){if(!e)return;let i=s.filter(l=>l&&l.length>0);if(!i.length){t.appendText(e);return}let n=e.toLowerCase(),r=[];for(let l of i){let c=0;for(;(c=n.indexOf(l,c))!==-1;)r.push([c,c+l.length]),c+=l.length}if(!r.length){t.appendText(e);return}r.sort((l,c)=>l[0]-c[0]);let a=[];for(let l of r){let c=a[a.length-1];c&&l[0]<=c[1]?c[1]=Math.max(c[1],l[1]):a.push([l[0],l[1]])}let o=0;for(let[l,c]of a)l>o&&t.appendText(e.slice(o,l)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(l,c)}),o=c;o<e.length&&t.appendText(e.slice(o))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===R)return"";let e=[],s=new Set([t.id]),i=this.tree.get(t.parent);for(;i&&i.id!==R&&!s.has(i.id);)s.add(i.id),e.unshift(this.titleFn(i)),i=i.parent&&i.parent!==R?this.tree.get(i.parent):null;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let o of this.notes){if(!o.cross)continue;let l=this.crossFolderIndex.get(o.cross.folder);l||(l=new Map,this.crossFolderIndex.set(o.cross.folder,l)),l.set(o.cross.id,o.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let s=t.id.replace(/^cross:/,""),i=e.get(s);if(!i)return"";let n=[],r=new Set([i.id]),a=i.parentId?e.get(i.parentId):null;for(;a&&!r.has(a.id);)r.add(a.id),n.unshift(a.title),a=a.parentId?e.get(a.parentId):null;return n.join(" \u203A ")}firstLineOfBody(t){if(!t)return"";let e=t.split(/\r?\n/);for(let s of e){let i=s.trim();if(i)return i}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===R)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let s=this.notes.find(i=>i.node?.id===e.id);return s?this.firstLineOfBody(s.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!dt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(dt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",l=>{if(l.key==="["){l.preventDefault();let c=t.selectionStart??t.value.length,p=t.selectionEnd??c,u=t.value.slice(0,c),h=t.value.slice(c,p),f=t.value.slice(p);t.value=`${u}[${h}]${f}`;let m=c+1+h.length;t.setSelectionRange(m,m),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(l.key==="]"){let c=t.selectionStart??-1;c>=0&&t.value[c]==="]"&&(l.preventDefault(),t.setSelectionRange(c+1,c+1));return}if(l.key==="Backspace"&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&t.selectionStart===t.selectionEnd){let c=t.selectionStart??-1;if(c>0&&t.value[c-1]==="["&&t.value[c]==="]"){l.preventDefault();let p=t.value.slice(0,c-1),u=t.value.slice(c+1);t.value=`${p}${u}`,t.setSelectionRange(c-1,c-1),t.dispatchEvent(new Event("input",{bubbles:!0}))}}});let s=document.createElement("div");s.className="stashpad-search-filter-row";let i=document.createElement("span");i.className="stashpad-search-filter-label",i.textContent="Filters:",s.appendChild(i);let n=document.createElement("button");n.className="stashpad-search-filter-chip",n.type="button",n.textContent="in:[parent note]",n.title='Insert "in:" \u2014 filter by parent note.',n.addEventListener("mousedown",l=>{l.preventDefault()}),n.addEventListener("click",l=>{l.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),n.click())}),s.appendChild(n);let r=document.createElement("button");r.className="stashpad-search-filter-chip stashpad-search-filter-when",r.type="button",r.textContent="when:[date / day / timeframe]",r.title="Open the time-filter builder (Before / On / After / Between).",r.addEventListener("mousedown",l=>{l.preventDefault()}),r.addEventListener("click",l=>{l.preventDefault(),this.toggleWhenBuilder(t,s)}),r.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),r.click())}),s.appendChild(r),e.parentElement?.insertBefore(s,e);let a=new dt.Scope(this.scope),o=l=>{let c=document.activeElement;return c?.classList?.contains("stashpad-search-filter-chip")?(l.preventDefault(),c.click(),!1):l.key==="Enter"&&!l.isComposing?(l.preventDefault(),this.selectActiveSuggestion?.(l),!1):!0};a.register([],"Enter",o),a.register([]," ",o),a.register(["Mod"],"f",l=>{l.preventDefault();let c=this.inputEl;return c&&(c.focus(),c.select()),!1}),a.register([],"Tab",l=>{let c=this.modalEl,p=this.inputEl;if(!c)return!0;let u=Array.from(c.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(m=>!m.hasAttribute("disabled")&&m.tabIndex!==-1&&m.offsetParent!==null);if(u.length===0)return!0;let h=document.activeElement,f=h?u.indexOf(h):-1;if(l.shiftKey){if(f<=0)return l.preventDefault(),u[u.length-1].focus(),!1}else if(f===u.length-1)return l.preventDefault(),(p??u[0]).focus(),!1;return!0}),this.app.keymap?.pushScope(a),this.pendingCleanups.push(()=>{try{this.app.keymap?.popScope(a)}catch{}})}appendFilterToInput(t,e,s){let i=t.value,r=`${i.length>0&&!/\s$/.test(i)?" ":""}${e}: [`,a="]",o=s;t.value=`${i}${r}${o}${a}`;let l=i.length+r.length+o.length;if(t.setSelectionRange(l,l+0),!o){let c=i.length+r.length;t.setSelectionRange(c,c)}t.focus(),t.dispatchEvent(new Event("input",{bubbles:!0}))}toggleWhenBuilder(t,e){let s=this.modalEl;if(this.whenBuilderEl){this.whenBuilderEl.remove(),this.whenBuilderEl=null,s?.removeClass("is-when-builder-open");return}s?.addClass("is-when-builder-open");let i=document.createElement("div");i.className="stashpad-when-builder";let n=document.createElement("div");n.className="stashpad-when-tabs";let r=[{id:"before",label:"Before"},{id:"on",label:"On"},{id:"after",label:"After"},{id:"between",label:"Between"}],a={};for(let m of r){let v=document.createElement("button");v.type="button",v.className="stashpad-when-tab",v.textContent=m.label,this.whenMode===m.id&&v.addClass("is-active"),v.addEventListener("mousedown",y=>y.preventDefault()),v.addEventListener("click",y=>{if(y.preventDefault(),this.whenMode===m.id)return;let b=this.whenMode;b!=="between"&&m.id==="between"?(this.whenBetweenEndText="",this.whenBetweenEndDate="",this.whenBetweenEndTime=""):b==="between"&&m.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),!this.whenSingleDate&&this.whenBetweenEndDate&&(this.whenSingleDate=this.whenBetweenEndDate,this.whenSingleTime=this.whenBetweenEndTime),this.whenBetweenEndText="",this.whenBetweenEndDate="",this.whenBetweenEndTime=""),this.whenMode=m.id;for(let k in a)a[k].toggleClass("is-active",k===m.id);f()}),a[m.id]=v,n.appendChild(v)}i.appendChild(n);let o=document.createElement("div");o.className="stashpad-when-body",i.appendChild(o);let l=(m,v,y="single")=>{let b=(0,dt.moment)().format("YYYY-MM-DD"),k=!v||v===b;if(y==="betweenStart")return"00:00";if(y==="betweenEnd")return"23:59";switch(m){case"after":return"00:00";case"on":return k?(0,dt.moment)().format("HH:mm"):"23:59";case"before":return k?(0,dt.moment)().format("HH:mm"):"23:59";default:return"23:59"}},c=(m,v)=>{m.addEventListener("keydown",y=>{y.key==="Enter"?(y.preventDefault(),y.stopPropagation(),v()):y.key==="Escape"&&(y.preventDefault(),y.stopPropagation(),this.closeWhenBuilder())})},p=(m,v)=>{let y=m.selectionStart??m.value.length,b=m.selectionEnd??m.value.length,T=`${y>0&&!/\s$/.test(m.value.slice(0,y))?" ":""}${v}`,I=m.value.slice(0,y)+T+m.value.slice(b);m.value=I;let E=y+T.length;m.setSelectionRange(E,E),m.focus(),m.dispatchEvent(new Event("input",{bubbles:!0}))},u=(m,v)=>{let b=m.slice(0,v).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return b?b[1]:null},h=(m,v,y,b)=>{let k=o.createDiv({cls:"stashpad-when-input-wrap has-icons"}),T=k.createDiv({cls:"stashpad-when-icon-slot"}),I=T.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});I.type="button",I.title="Pick date",(0,dt.setIcon)(I,"calendar-days");let E=T.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});E.tabIndex=-1;let D=k.createDiv({cls:"stashpad-when-icon-slot"}),H=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});H.type="button",H.title="Pick time",(0,dt.setIcon)(H,"clock");let C=k.createDiv({cls:"stashpad-when-icon-slot"}),A=C.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});A.type="button",A.title="Pick day",(0,dt.setIcon)(A,"calendar");let S=k.createDiv({cls:"stashpad-when-icon-slot"}),_=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});_.type="button",_.title="Pick timeframe",(0,dt.setIcon)(_,"history");let J=k.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:m}});J.value=v(),J.addEventListener("input",()=>y(J.value));let U=k.createEl("button",{cls:"stashpad-when-clear"});U.type="button",U.textContent="\xD7",U.title="Clear";for(let P of[I,H,A,_,U])P.addEventListener("mousedown",X=>X.preventDefault());let z=null,W=(P,X)=>{z&&z();let q=P.createDiv({cls:"stashpad-when-popover"}),Y=new dt.Scope(this.scope),ct=null,pt=it=>{ct=it},nt=!1,rt=it=>{!q.contains(it.target)&&it.target!==P&&!P.contains(it.target)&&ot()},ot=()=>{if(!nt){nt=!0,q.remove(),document.removeEventListener("mousedown",rt,!0);try{this.app.keymap?.popScope(Y)}catch{}z===ot&&(z=null)}};z=ot,Y.register([],"Escape",it=>(it.preventDefault(),ot(),!1)),Y.register([],"Enter",it=>(it.preventDefault(),ct&&ct(),!1));try{X(q,ot,pt)}catch(it){console.error("[stashpad] popover fill threw:",it),q.remove(),z=null;return}this.app.keymap?.pushScope(Y),this.pendingCleanups.push(ot),setTimeout(()=>document.addEventListener("mousedown",rt,!0),0)};_.addEventListener("click",P=>{P.preventDefault(),W(S,(X,q,Y)=>{let ct=this.whenMode==="on",pt=(B,$)=>{if(!ct)return`${B}${$}`;let x={d:"days",w:"weeks",m:"months",y:"years"}[$];return(0,dt.moment)().subtract(B,x).format("YYYY-MM-DD")},nt=X.createDiv({cls:"stashpad-when-pop-row"}),rt=[{label:"Last 7d",n:7,unit:"d"},{label:"Last 30d",n:30,unit:"d"},{label:"This week",n:1,unit:"w"},{label:"This month",n:1,unit:"m"}];for(let B of rt){let $=nt.createEl("button",{cls:"stashpad-when-pop-chip",text:B.label});$.type="button",$.addEventListener("mousedown",x=>x.preventDefault()),$.addEventListener("click",x=>{x.preventDefault(),p(J,pt(B.n,B.unit)),q()})}let ot=X.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});ot.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let it=ot.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),gt=ot.createEl("select",{cls:"stashpad-when-pop-unit"});for(let B of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let $=gt.createEl("option",{text:B.label});$.value=B.v}let ft=ot.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ft.type="button";let w=()=>{let B=parseInt(it.value,10);!Number.isFinite(B)||B<1||(p(J,pt(B,gt.value)),q())};ft.addEventListener("mousedown",B=>B.preventDefault()),ft.addEventListener("click",B=>{B.preventDefault(),w()}),Y(w),it.focus(),it.select()})});let Q=(P,X,q,Y,ct)=>{W(X,(pt,nt,rt)=>{Be(pt,{seedH:q,seedM:Y,seedPeriod:ct,close:nt,setOnEnter:rt,onFinalize:ot=>p(P,ri(ot))})})};A.addEventListener("click",P=>{P.preventDefault(),W(C,(X,q,Y)=>{let ct=X.createDiv({cls:"stashpad-when-pop-row"});for(let it of["Today","Yesterday"]){let gt=ct.createEl("button",{cls:"stashpad-when-pop-chip",text:it});gt.type="button",gt.addEventListener("mousedown",ft=>ft.preventDefault()),gt.addEventListener("click",ft=>{ft.preventDefault(),p(J,it),q()})}let pt=X.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),nt=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],ot=((0,dt.moment)().day()+6)%7;for(let it=0;it<nt.length;it++){let gt=nt[it],ft=pt.createEl("button",{cls:"stashpad-when-pop-chip",text:gt.slice(0,3)});ft.type="button",ft.title=gt,it===ot&&ft.addClass("is-today"),ft.addEventListener("mousedown",w=>w.preventDefault()),ft.addEventListener("click",w=>{if(w.preventDefault(),b==="betweenEnd"){let B=it,$=(0,dt.moment)().startOf("day"),x=($.day()+6)%7,F=(B-x+7)%7;F===0&&(F=7);let M=$.clone().add(F,"days").format("YYYY-MM-DD");p(J,M)}else p(J,gt);q()})}})});let L=(P,X)=>{P.value||(P.value=X);let q=P;if(typeof q.showPicker=="function")try{q.showPicker();return}catch{}P.focus(),P.click()};return I.addEventListener("click",P=>{P.preventDefault(),L(E,(0,dt.moment)().format("YYYY-MM-DD"))}),E.addEventListener("change",()=>{E.value&&p(J,E.value)}),H.addEventListener("click",P=>{P.preventDefault();let X=J.selectionStart??J.value.length,q=u(J.value,X),Y=l(this.whenMode,q,b),[ct,pt]=Y.split(":"),nt=parseInt(ct,10),rt=parseInt(pt,10),ot=nt%12;ot===0&&(ot=12);let it=nt>=12?"pm":"am";Q(J,D,ot,rt,it)}),U.addEventListener("click",P=>{P.preventDefault(),J.value="",y(""),J.focus()}),J},f=()=>{if(o.empty(),this.whenMode==="between"){let m=h("start (date / day / timeframe)",()=>this.whenSingleText,I=>{this.whenSingleText=I},"betweenStart"),v=h("end (date / day / timeframe)",()=>this.whenBetweenEndText,I=>{this.whenBetweenEndText=I},"betweenEnd"),y=o.createDiv({cls:"stashpad-when-actions"}),b=y.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});b.type="button",b.addEventListener("mousedown",I=>I.preventDefault());let k=()=>{let I=m.value.trim(),E=v.value.trim();I&&this.appendFilterToInput(t,"after",I),E&&this.appendFilterToInput(t,"before",E),this.closeWhenBuilder()};b.addEventListener("click",I=>{I.preventDefault(),k()});let T=y.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});T.type="button",T.addEventListener("mousedown",I=>I.preventDefault()),T.addEventListener("click",I=>{I.preventDefault(),this.closeWhenBuilder()}),c(m,k),c(v,k),m.focus(),m.setSelectionRange(m.value.length,m.value.length)}else{let m=h("date / day / timeframe",()=>this.whenSingleText,T=>{this.whenSingleText=T},"single"),v=o.createDiv({cls:"stashpad-when-actions"}),y=v.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});y.type="button",y.addEventListener("mousedown",T=>T.preventDefault());let b=()=>{let T=m.value.trim();T&&this.appendFilterToInput(t,this.whenMode,T),this.closeWhenBuilder()};y.addEventListener("click",T=>{T.preventDefault(),b()});let k=v.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});k.type="button",k.addEventListener("mousedown",T=>T.preventDefault()),k.addEventListener("click",T=>{T.preventDefault(),this.closeWhenBuilder()}),c(m,b),m.focus(),m.setSelectionRange(m.value.length,m.value.length)}};f(),e.parentElement?.insertBefore(i,e.nextSibling),this.whenBuilderEl=i}closeWhenBuilder(){if(!this.whenBuilderEl)return;this.whenBuilderEl.remove(),this.whenBuilderEl=null,this.modalEl?.removeClass("is-when-builder-open")}onChooseSuggestion(t){if(t.kind==="create"&&this.opts.onCreate){this.opts.onCreate(this.inputEl?.value??"");return}if(t.kind==="folder-open"&&t.id==="__folder_picker__"){let e=this.opts.folderResults?.()??[];if(!e.length)return;let s=this.inputEl?.value??"",i=!1,n=u=>{i=!0;let h=u.split("/").pop()??u;this.opts.onPick({id:`folder:${u}`,label:`Open folder \u201C${h}\u201D in a new tab`,node:null,kind:"folder-open",folder:u})},r=new Ws(this.app,e,n),a=r.onClose.bind(r),o=this.tree,l=this.titleFn,c=this.opts,p=this.app;r.onClose=()=>{if(a(),!i){let u=new g(p,o,l,c);u.open(),setTimeout(()=>{let h=u.inputEl;h&&(s&&(h.value=s,h.dispatchEvent(new Event("input",{bubbles:!0}))),h.focus(),h.setSelectionRange(h.value.length,h.value.length))},0)}},r.open();return}this.opts.onPick(t)}},Ws=class extends dt.FuzzySuggestModal{constructor(t,e,s){super(t);this.folders=e;this.onChosen=s;this.setPlaceholder("Open which folder?")}getItems(){return this.folders}getItemText(t){let e=t.split("/").pop()??t;return e===t?t:`${e} \u2014 ${t}`}onChooseItem(t){this.onChosen(t)}};Ht();var Vs=zi(Ti()),hs=require("obsidian");Mt();Tt();var Qt="stash",xi=1;function Ci(g){let t=(g.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var Us=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Ei(g,d){let t=new Vs.default,e=tn([...d.rootNotes,...d.allDescendants]),s=new Map,i=[];for(let r of e){let a=await g.vault.read(r.file),o=a,l=en(a);for(let c of l){let p=g.metadataCache.getFirstLinkpathDest(c,r.file.path);if(!p){i.push(`Missing attachment "${c}" in ${r.file.path}`);continue}let u=p.name;s.has(u)||s.set(u,await g.vault.readBinary(p)),o=sn(o,c,u)}o=rn(o,g,r.file.path),t.file(`notes/${r.file.name}`,o)}for(let[r,a]of s)t.file(`attachments/${r}`,a);let n={stashSchema:xi,exportedAt:new Date().toISOString(),sourceFolder:d.sourceFolder,noteCount:e.length,rootIds:d.rootNotes.map(r=>r.id)};return t.file("manifest.json",JSON.stringify(n,null,2)),i.length&&t.file("warnings.txt",i.join(` +`)),t.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:6}})}async function ps(g,d,t,e){let s=await Vs.default.loadAsync(d),i=s.file("manifest.json");if(!i)throw new Error("Not a valid .stash package: missing manifest.json");let n=JSON.parse(await i.async("string"));if(typeof n.stashSchema!="number"||n.stashSchema>xi)throw new Error(`Unsupported .stash schema: v${n.stashSchema}`);await Fi(g,t);let r=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("notes/")&&v.name.endsWith(".md")),a=[];for(let v of r){let y=await v.async("string"),{fm:b,body:k}=he(y),T=Ci(v.name.slice(6))||`${b.id||"imported-"+yt(4)}.md`;a.push({originalName:T,fm:b,body:k})}let o=new Map,l=0;for(let v of a){let y=v.fm.id;y&&(e.has(y)||o.has(y)?(o.set(y,`${y}-${yt(4)}-Imported`),l++):o.set(y,y))}let c=new Date().toISOString(),p=[],u=`${t}/_attachments`,h=0,f=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("attachments/"));f.length>0&&await Fi(g,u);for(let v of f){let y=Ci(v.name.slice(12));if(!y)continue;let b=`${u}/${y}`;if(await g.vault.adapter.exists(b))continue;let k=await v.async("arraybuffer");await g.vault.createBinary(b,k),h++}let m=0;for(let v of a){let y=v.fm.id;if(!y){p.push(`Skipped ${v.originalName} \u2014 no id in frontmatter`);continue}let b=o.get(y),k=v.fm.parent??null,T=k;k&&k!==R&&o.has(k)?T=o.get(k):k&&k!==R&&!o.has(k)&&(T=R);let I=nn(v.body,u),E={...v.fm,id:b,parent:T,import_date:c};Array.isArray(E.attachments)&&(E.attachments=E.attachments.map(A=>qt(`${u}/${Ii(se(A))}`)));let D=Ut(E,I),H=b===y?v.originalName:on(v.originalName,y,b),C=`${t}/${H}`;await g.vault.adapter.exists(C)&&(H=`${H.replace(/\.md$/,"")}-${yt(4)}.md`,C=`${t}/${H}`),await g.vault.create(C,D),m++}return{notesWritten:m,attachmentsWritten:h,collisionsRenamed:l,warnings:p}}function tn(g){let d=new Set,t=[];for(let e of g)d.has(e.id)||(d.add(e.id),t.push(e));return t}function en(g){let d=new Set,t;for(Us.lastIndex=0;(t=Us.exec(g))!==null;)d.add(t[1]);return[...d]}function sn(g,d,t){return g.replace(new RegExp(`!\\[\\[${an(d)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,s)=>`![[${t}${s??""}]]`)}function nn(g,d){return g.replace(Us,(t,e,s)=>e.includes("/")?t:t.replace(e,`${d}/${e}`))}function rn(g,d,t){let e=he(g);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return g;let s=e.fm.attachments.map(n=>{let r=d.metadataCache.getFirstLinkpathDest(n,t);return r?r.name:Ii(n)}),i={...e.fm,attachments:s};return Ut(i,e.body)}function an(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ii(g){let d=g.lastIndexOf("/");return d<0?g:g.slice(d+1)}function on(g,d,t){return g.includes(d)?g.replace(d,t):g.replace(/\.md$/,`-${t}.md`)}function he(g){if(!g.startsWith("---"))return{fm:{},body:g};let d=g.indexOf(` +---`,3);if(d<0)return{fm:{},body:g};let t=g.slice(3,d).replace(/^\n/,""),e=g.slice(d+4),s={};try{s=(0,hs.parseYaml)(t)??{}}catch{s={}}let i=e.startsWith(` +`)?e.slice(1):e;return{fm:s,body:i}}function Ut(g,d){return`--- +${(0,hs.stringifyYaml)(g).trimEnd()} --- -${h}`}async function bi(g,h){if(!(!h||await g.vault.adapter.exists(h)))try{await g.vault.createFolder(h)}catch(e){let s=e?.message??"";if(!/already exists/i.test(s))throw e}}var en=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);function Jt(g,h,t){g.empty();try{(0,O.setIcon)(g,h)}catch{}let e=g.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(g.empty(),g.createSpan({cls:"stashpad-icon-fallback",text:t}))}var cs={nested:"Nested",flat:"Flat",everything:"Everything"};function sn(g){if(g instanceof Element&&g.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let h=new Set([document]);g instanceof Element&&g.ownerDocument&&h.add(g.ownerDocument);for(let t of h)if(t.body?.querySelector(".modal-bg")||t.body?.querySelector(".modal-container .modal")||t.body?.querySelector(".suggestion-container")||t.body?.querySelector(".menu.mod-active"))return!0;return!1}var ds=[{key:"day",calShort:"Today",rollShort:"24h",calLong:"Since midnight today",rollLong:"Last 24 hours"},{key:"week",calShort:"Week",rollShort:"7d",calLong:"Since Monday this week",rollLong:"Last 7 days"},{key:"month",calShort:"Month",rollShort:"30d",calLong:"Since the 1st of this month",rollLong:"Last 30 days"},{key:"year",calShort:"Year",rollShort:"365d",calLong:"Since January 1 this year",rollLong:"Last 365 days"},{key:"all",calShort:"All",rollShort:"ad infinitum",calLong:"All time",rollLong:"All time"}],At=class At extends O.ItemView{constructor(t,e){super(t);this.focusId=R;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.noteFolder="Stashpad";this.folderOverride=null;this.tinyMode=!1;this.tinyAlwaysOnTop=!1;this.tinyOpacity=1;this.compactMode=!1;this.detachTreeHook=null;this.detachSettings=null;this.slugDebouncers=new Map;this.attachmentDebouncers=new Map;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.currentChildren=[];this.modeSplit=null;this.modeEnterSubmits=!0;this.nextDestination=null;this.nextDestinationFolder=null;this.nextDestinationLabel=null;this.inListPicker=null;this.listEl=null;this.composerInputEl=null;this.composerDraft="";this.draftsLoadedFor=null;this.autoSelectNewest=!1;this.scrollToBottomOnNextRender=!1;this.scrollListenerSaveTimer=null;this.suppressScrollSave=!1;this.selectionGuardKey=0;this.pendingRenderPolicy=null;this.stickToListBottom=!1;this.keyboardTransitionUntil=0;this.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.expandedNotes=new Set;this.focusComposerOnNextRender=!1;this.suppressComposerFocusUntil=0;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navBackStack=[];this.navForwardSnapshots=[];this.treeReconcileTimer=null;this.stampLastCursorTimer=null;this.tinyOpacityPopover=null;this.renderCache=new Map;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||sn(t.target))return;let e=bt().bindings;if(ot(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(ot(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(ot(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(ot(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(ot(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(ot(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(ot(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(ot(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let s=t.target,i=!!s&&(s.tagName==="INPUT"||s.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!i){let a=this.composerInputEl;if(a){t.preventDefault(),t.stopPropagation(),a.focus();let l=a.value.length;a.setSelectionRange(l,l);return}}let n=!!s&&(s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.tagName==="BUTTON"||s.tagName==="SELECT");if(t.key==="Escape"&&s instanceof HTMLElement&&(s.tagName==="BUTTON"||s.tagName==="SELECT")&&this.viewRoot.contains(s)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null;let a=this.listEl,l=!!a&&a.scrollTop+a.clientHeight>=a.scrollHeight-2,c=a?.scrollTop??0;if(this.render(),a){let p=l?a.scrollHeight:c;a.scrollTop=p,requestAnimationFrame(()=>{a.scrollTop=l?a.scrollHeight:c}),setTimeout(()=>{a.scrollTop=l?a.scrollHeight:c},60),this.revealCursorRow()}return}if(this.inListPicker&&!n){if(t.key==="ArrowDown"){t.preventDefault(),this.inListPicker.activeIdx=Math.min(this.currentChildren.length-1,this.inListPicker.activeIdx+1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="ArrowUp"){t.preventDefault(),this.inListPicker.activeIdx=Math.max(0,this.inListPicker.activeIdx-1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="Enter"){t.preventDefault(),this.commitInListPicker();return}return}if(n)return;if(ot(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(ot(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(ot(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(ot(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(ot(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(ot(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(ot(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(ot(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(ot(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(ot(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(ot(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(ot(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let a=this.composerInputEl;if(a){a.focus();let l=a.value.length;a.setSelectionRange(l,l)}return}if(t.key==="ArrowDown"){t.preventDefault(),this.cursorIdx>=this.currentChildren.length-1?this.cursorIdx=0:this.cursorIdx++,this.selectCursor(t.shiftKey);return}if(t.key==="ArrowUp"){t.preventDefault(),this.cursorIdx<=0?this.cursorIdx=this.currentChildren.length-1:this.cursorIdx--,this.selectCursor(t.shiftKey);return}if(t.altKey&&t.key==="ArrowLeft"){t.preventDefault(),this.navigateBack();return}if(t.altKey&&t.key==="ArrowRight"){t.preventDefault(),this.navigateForward();return}if(t.key==="ArrowRight"){let a=this.currentChildren[this.cursorIdx];a&&(t.preventDefault(),this.navigateTo(a.id));return}if(t.key==="ArrowLeft"||t.key==="Backspace"){t.preventDefault(),this.navigateUp();return}if(t.key==="Escape"){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let a=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,a){let l=this.currentChildren.findIndex(c=>c.id===a);this.selection.add(a),this.lastSelected=a,l>=0&&(this.cursorIdx=l)}this.repaintSelectionClasses(),this.revealCursorRow();return}let r=bt().bindings;if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(ot(t,r.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(ot(t,r.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(ot(t,r.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(ot(t,r.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(ot(t,r.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(ot(t,r.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(ot(t,r.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(ot(t,r.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let a=this.tree.get(this.focusId);a?.file&&this.cmdOpenInEditor(a)}else this.cmdOpenInEditor();return}if(ot(t,r.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(ot(t,r.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(ot(t,r.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(ot(t,r.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(ot(t,r.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(ot(t,r.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(ot(t,r.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(ot(t,r.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}let o=this.tree.get(this.focusId);if(o?.file){if(ot(t,r.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(o);return}if(ot(t,r.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(o);return}}};this.openSearchInstance=null;this.fmSyncUnsubscribe=null;this.completedState=new Map;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0;this.pendingFocusIds=null;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map;this.onFileModify=t=>{if(!(t instanceof O.TFile)||t.extension!=="md"||!t.path.startsWith(this.noteFolder+"/"))return;let e=Date.now(),s=this.recentSelfWrites.get(t.path);s!==void 0&&e-s<At.EXTERNAL_WRITE_GRACE_MS||this.lastExternalModify.set(t.path,e),this.scheduleSlugRename(t),this.scheduleAttachmentSync(t),this.scheduleContribution(t),this.debouncedRender()};this.onFileCreate=t=>{!(t instanceof O.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new ts(this.app),this.log=e.newLog(),this.integrity=new as(this.tree,this.log),this.order=new es(this.app),this.sortStore=new ss(this.app),this.fmSync=new ns(this.app,()=>this.tree),this.tree.setOrderProvider(s=>{let i=this.noteFolder,n=this.sortStore.getMode(i,s);return n==="manual"?this.order.getOrder(i,s):this.computeSortedIds(s,n)}),this.debouncedRender=(0,O.debounce)(()=>this.render(),80)}getViewType(){return mt}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==R){let s=this.tree.get(this.focusId);if(s){let i=this.titleForNode(s).trim(),n=i.length>40?i.slice(0,40)+"\u2026":i;if(n)return`${e} \u2014 ${n}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let s=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;s&&s.textContent!==t&&s.setText(t)}getIcon(){return"list-tree"}async onOpen(){let t=this.contentEl;t.empty(),t.addClass("stashpad-scroll-host"),this.viewRoot=t.createDiv({cls:"stashpad-view"}),this.viewRoot.setAttribute("tabindex","0"),this.viewRoot.addEventListener("focusin",()=>Ke(this)),this.viewRoot.addEventListener("click",()=>Ke(this)),this.viewRoot.addEventListener("mouseup",o=>{o.button===3?(o.preventDefault(),this.navigateBack()):o.button===4&&(o.preventDefault(),this.navigateForward())}),this.viewRoot.addEventListener("auxclick",o=>{o.button===3?(o.preventDefault(),this.navigateBack()):o.button===4&&(o.preventDefault(),this.navigateForward())}),Ke(this),this.registerInterval(window.setInterval(()=>this.pruneContribMaps(),6e4));let e=null,s=()=>{e||(e=new O.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.selection.size>1){let o=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,o){let a=this.currentChildren.findIndex(l=>l.id===o);this.selection.add(o),this.lastSelected=o,a>=0&&(this.cursorIdx=a)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},i=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",s),this.viewRoot.addEventListener("focusout",o=>{let a=o.relatedTarget;a&&this.viewRoot&&this.viewRoot.contains(a)||i()}),this.register(()=>i()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",o=>{if(o.extension!=="md")return;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;this.completedState.set(o.path,!!a?.completed)})),this.registerEvent(this.app.vault.on("rename",(o,a)=>{this.completedState.has(a)&&(this.completedState.set(o.path,this.completedState.get(a)),this.completedState.delete(a))})),this.registerEvent(this.app.vault.on("delete",o=>{this.completedState.delete(o.path)})),this.detachSettings=hi(()=>{this.loadConfig();let o=this.plugin.settings.drafts?.[this.noteFolder]??"",a=this.composerInputEl?.value??"";o===""&&this.composerDraft!==""&&a===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):o===""&&a!==""&&(this.composerDraft=a),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(o){let a=o?.message??"";/already exists/i.test(a)||console.warn("[Stashpad] bootstrapFolder failed:",o)}this.tree.rebuild(this.noteFolder),this.installFmSyncActivityNotice(),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder();try{let o=this.plugin.loadLastCursor(this.noteFolder);for(let[a,l]of o)this.lastCursorByFocus.set(a,l)}catch{}let n=this.lastCursorByFocus.get(this.focusId),r;n&&this.tree.get(n)?(r={kind:"scroll-to-id",id:n,align:"start"},this.pendingFocusIds=[n]):(this.scrollToBottomOnNextRender=!0,r={kind:"pin-bottom",until:"next-user-input"}),this.render(r),this.tinyMode&&(setTimeout(()=>this.applyTinyWindow(),1e3),setTimeout(()=>this.applyTinyWindow(),1500)),this.registerDomEvent(window,"beforeunload",()=>{this.flushDrafts(),this.stampSelectedCursor(!0)}),this.registerDomEvent(window,"blur",()=>{this.flushDrafts(),this.stampSelectedCursor(!0)}),this.focusComposer(),this.registerEvent(this.app.workspace.on("active-leaf-change",o=>{o===this.leaf?this.focusComposer():this.stickToListBottom=!1}))}scheduleTreeReconcile(){this.treeReconcileTimer==null&&(this.treeReconcileTimer=window.setTimeout(()=>{if(this.treeReconcileTimer=null,!this.viewRoot?.isConnected)return;let t=this.noteFolder,e=t+"/",s=0;for(let i of this.app.vault.getMarkdownFiles()){let n=i.parent?.path?.replace(/\/+$/,"")??"";if(!(n===t||t!==""&&n.startsWith(e)))continue;let r=this.app.metadataCache.getFileCache(i)?.frontmatter?.id;typeof r=="string"&&r&&s++}s!==this.tree.fileBackedCount()&&(this.tree.rebuild(t),this.debouncedRender())},400))}focusView(){requestAnimationFrame(()=>{this.viewRoot?.isConnected&&(document.activeElement instanceof HTMLElement&&(document.activeElement.tagName==="INPUT"||document.activeElement.tagName==="TEXTAREA")||this.viewRoot.focus({preventScroll:!0}))})}focusComposer(){if(!bt().autofocusComposerAfterSend)return;let t=()=>{if(!this.viewRoot?.isConnected||Date.now()<this.suppressComposerFocusUntil)return;let e=document.activeElement;e&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA")&&e!==this.composerInputEl||(e&&e.tagName==="BUTTON"&&this.viewRoot.contains(e),this.composerInputEl?.focus({preventScroll:!0}))};requestAnimationFrame(t),setTimeout(t,50),setTimeout(t,200)}async onClose(){li(this),this.detachTreeHook?.(),this.detachSettings?.(),this.app.vault.off("modify",this.onFileModify),this.app.vault.off("create",this.onFileCreate),window.removeEventListener("keydown",this.onDocKeyDown,!0),this.listResizeObserver?.disconnect(),this.listResizeObserver=null,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null,this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();for(let t of this.contribTimers.values())clearTimeout(t);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}try{await this.fmSync.flush()}catch{}this.stampSelectedCursor(!0),this.fmSyncUnsubscribe?.(),this.fmSyncUnsubscribe=null}setEphemeralState(t){let e=t;e?.focusId&&(this.focusId=e.focusId),e?.timeFilter&&(this.timeFilter=e.timeFilter)}getEphemeralState(){return{focusId:this.focusId,timeFilter:this.timeFilter}}getState(){return{...super.getState()??{},folderOverride:this.folderOverride,timeFilter:this.timeFilter,focusId:this.focusId,tagFilter:this.tagFilter,colorFilter:this.colorFilter,timeFilterCalendar:this.timeFilterCalendar,tinyMode:this.tinyMode,tinyAlwaysOnTop:this.tinyAlwaysOnTop,tinyOpacity:this.tinyOpacity,compactMode:this.compactMode,navBackStack:this.navBackStack,navForwardSnapshots:this.navForwardSnapshots}}async setState(t,e){let s=t??null;if(s){"folderOverride"in s&&(this.folderOverride=s.folderOverride??null),s.timeFilter&&(this.timeFilter=s.timeFilter),s.focusId&&(this.focusId=s.focusId),"tagFilter"in s&&(this.tagFilter=s.tagFilter??null),"colorFilter"in s&&(this.colorFilter=s.colorFilter??null),"timeFilterCalendar"in s&&(this.timeFilterCalendar=!!s.timeFilterCalendar),"tinyMode"in s&&(this.tinyMode=!!s.tinyMode),"tinyAlwaysOnTop"in s&&(this.tinyAlwaysOnTop=!!s.tinyAlwaysOnTop),typeof s.tinyOpacity=="number"&&Number.isFinite(s.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,s.tinyOpacity))),"compactMode"in s&&(this.compactMode=!!s.compactMode);let r=o=>o&&typeof o.folder=="string"&&typeof o.focusId=="string";Array.isArray(s.navBackStack)&&(this.navBackStack=s.navBackStack.filter(r)),Array.isArray(s.navForwardSnapshots)&&(this.navForwardSnapshots=s.navForwardSnapshots.filter(r))}let i=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||i||"Stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot){this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.lastCursorByFocus.clear();try{let a=this.plugin.loadLastCursor(this.noteFolder);for(let[l,c]of a)this.lastCursorByFocus.set(l,c)}catch{}let r=this.lastCursorByFocus.get(this.focusId),o;r&&this.tree.get(r)?(this.pendingFocusIds=[r],o={kind:"scroll-to-id",id:r,align:"start"}):o={kind:"pin-bottom",until:"next-user-input"},this.render(o)}}focus(){this.viewRoot?.focus({preventScroll:!0})}loadConfig(){let t=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),s=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null||t||"Stashpad";s!==this.noteFolder?(this.noteFolder=s,this.tree.rebuild(this.noteFolder)):this.noteFolder=s}captureNavSnapshot(){return{folder:this.noteFolder,focusId:this.focusId}}recordNavState(t={}){let e=this.captureNavSnapshot(),s=this.navBackStack[this.navBackStack.length-1];s&&s.folder===e.folder&&s.focusId===e.focusId||(this.navBackStack.push(e),t.keepForward||(this.navForwardSnapshots=[]))}async setFolderOverride(t,e={}){let s=t?.trim().replace(/^\/+|\/+$/g,"")||null;if(s&&this.isReservedFolder(s)){new O.Notice(`"${s}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((s||null)!==(this.folderOverride||null)){e.skipHistory||this.recordNavState(),this.folderOverride=s,this.focusId=R,this.lastCursorByFocus.clear(),this.selection.clear(),this.cursorIdx=-1,this.lastSelected=null,this.composerDraft="",await this.flushDrafts(),this.draftsLoadedFor=null,this.loadConfig();try{await this.bootstrapFolder()}catch(i){let n=i?.message??"";/already exists/i.test(n)||console.warn("[Stashpad] bootstrapFolder failed:",i)}this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),await this.loadDraftsForFolder();try{let i=this.app.workspace;typeof i.saveLayout=="function"?await i.saveLayout():this.app.workspace.requestSaveLayout()}catch{this.app.workspace.requestSaveLayout()}this.refreshHeaderTitle(),this.render()}}cmdOpenFolderPicker(){this.openFolderPicker()}openFolderPicker(){this.plugin.openFolderPicker()}listVaultFolders(){let t=[];for(let e of this.app.vault.getAllLoadedFiles())if(e instanceof O.TFolder){if(e.path==="/"||e.path===""||e.path.startsWith(".")||this.isReservedFolder(e.path))continue;t.push(e.path)}return t.sort((e,s)=>e.localeCompare(s))}isReservedFolder(t){let e=t.split("/").filter(Boolean).pop()??"";return e?new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed","_authors"].map(i=>(i??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(e):!1}persistFocus(){try{this.app.workspace.requestSaveLayout()}catch{}}cmdUndo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canUndo()){new O.Notice("Nothing to undo.");return}let e=t.peekUndoLabel(),s=this.plugin.notifications.recent()[0]?.category??"system";t.undo().then(()=>this.plugin.notifications.show({message:`Undid: ${e}`,kind:"info",category:s,folder:this.noteFolder})).catch(i=>this.plugin.notifications.show({message:`Undo failed: ${i.message}`,kind:"error",category:"system",folder:this.noteFolder}))}cmdRedo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canRedo()){new O.Notice("Nothing to redo.");return}let e=t.peekRedoLabel(),s=this.plugin.notifications.recent()[0]?.category??"system";t.redo().then(()=>this.plugin.notifications.show({message:`Redid: ${e}`,kind:"info",category:s,folder:this.noteFolder})).catch(i=>this.plugin.notifications.show({message:`Redo failed: ${i.message}`,kind:"error",category:"system",folder:this.noteFolder}))}async snapshotNotes(t,e){let s=[],i=new Set;for(let a of t)!a.file||i.has(a.file.path)||(i.add(a.file.path),s.push(a.file));let n=await Promise.all(s.map(a=>this.app.vault.read(a))),r=s.map((a,l)=>({path:a.path,content:n[l]})),o=[];if(e){let a=new Set,l=[];for(let p of n)for(let u of this.extractAttachments(this.stripFrontmatter(p))){let d=this.app.metadataCache.getFirstLinkpathDest(u,"");d&&!a.has(d.path)&&(a.add(d.path),l.push(d))}let c=await Promise.all(l.map(p=>this.app.vault.readBinary(p)));for(let p=0;p<l.length;p++)o.push({path:l[p].path,data:c[p]})}return{notes:r,attachments:o}}async restoreSnapshots(t,e){for(let i of t.attachments)try{await this.app.vault.adapter.exists(i.path)||await this.app.vault.createBinary(i.path,i.data)}catch{}for(let i of t.notes)try{await this.app.vault.adapter.exists(i.path)||await this.app.vault.create(i.path,i.content)}catch{}let s=()=>{e&&e.some(n=>this.tree.get(n))&&(this.pendingFocusIds=e.slice())};s(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"}),setTimeout(()=>{s(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},100),setTimeout(()=>{s(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},400),setTimeout(()=>{for(let i of t.notes){let n=this.tree.idForPath(i.path);n&&this.fmSync.schedule(n)}},500)}async trashNotesAndAttachments(t){let e=new Set;for(let s of t.notes){let i=this.tree.idForPath(s.path);if(!i)continue;let n=this.tree.get(i);n?.parent&&e.add(n.parent)}for(let s of t.notes){let i=this.app.vault.getAbstractFileByPath(s.path);if(i)try{await this.app.fileManager.trashFile(i)}catch{}}for(let s of t.attachments){let i=this.app.vault.getAbstractFileByPath(s.path);if(i)try{await this.app.fileManager.trashFile(i)}catch{}}this.tree.rebuild(this.noteFolder),this.render();for(let s of e)this.fmSync.scheduleParentOfDeleted(s)}async loadDraftsForFolder(){if(this.draftsLoadedFor===this.noteFolder)return;this.draftsLoadedFor=this.noteFolder;let t=this.plugin.settings.drafts??{};this.composerDraft=t[this.noteFolder]??"",console.debug("[Stashpad] loadDrafts",{folder:this.noteFolder,has:!!t[this.noteFolder],available:Object.keys(t)})}async saveDraft(t){try{let e=this.noteFolder;if((this.plugin.settings.drafts?.[e]??"")===t)return;let i={...this.plugin.settings.drafts??{}};t.length===0?delete i[e]:i[e]=t,this.plugin.settings.drafts=i,t.length===0?await this.plugin.saveSettings():await this.plugin.persistSettingsQuiet()}catch(e){console.warn("Stashpad: drafts save failed",e)}}async recordLastSubmitted(t){try{let e={...this.plugin.settings.lastSubmitted??{}};e[this.noteFolder]=t,this.plugin.settings.lastSubmitted=e,await this.plugin.persistSettingsQuiet()}catch{}}hasRestorableDraft(){let t=this.plugin.settings.drafts?.[this.noteFolder];if(!t||!t.trim())return!1;let e=this.plugin.settings.lastSubmitted?.[this.noteFolder];return!(e&&e===t)}syncComposerDraftForFocus(){}async flushDrafts(){this.composerInputEl?await this.saveDraft(this.composerInputEl.value):await this.saveDraft(this.composerDraft)}timeFilterCutoff(){if(this.timeFilter==="all")return null;if(this.timeFilterCalendar){let e=(0,O.moment)();switch(this.timeFilter){case"day":return e.startOf("day").valueOf();case"week":return e.startOf("isoWeek").valueOf();case"month":return e.startOf("month").valueOf();case"year":return e.startOf("year").valueOf()}}let t=Date.now();switch(this.timeFilter){case"day":return t-864e5;case"week":return t-7*864e5;case"month":return t-30*864e5;case"year":return t-365*864e5}return null}allowedByBases(){return null}currentViewMode(){return this.plugin.settings.viewModes?.[this.noteFolder]??"nested"}currentIncludeAttachments(){return!!this.plugin.settings.includeAttachmentsInEverything?.[this.noteFolder]}async setIncludeAttachments(t){let e={...this.plugin.settings.includeAttachmentsInEverything??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.includeAttachmentsInEverything=e,await this.plugin.saveSettings()}currentHideChildless(){return!!this.plugin.settings.hideChildlessNotes?.[this.noteFolder]}async setHideChildless(t){let e={...this.plugin.settings.hideChildlessNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.hideChildlessNotes=e,await this.plugin.saveSettings()}currentHideCompleted(){return!!this.plugin.settings.hideCompletedNotes?.[this.noteFolder]}async setHideCompleted(t){let e={...this.plugin.settings.hideCompletedNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.hideCompletedNotes=e,await this.plugin.saveSettings()}currentAttachmentsOnly(){return!!this.plugin.settings.attachmentsOnlyNotes?.[this.noteFolder]}async setAttachmentsOnly(t){let e={...this.plugin.settings.attachmentsOnlyNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.attachmentsOnlyNotes=e,await this.plugin.saveSettings()}nodeHasAttachment(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.attachments;return Array.isArray(e)&&e.length>0}hasAttachmentInSubtree(t){if(this.nodeHasAttachment(t))return!0;for(let e of this.tree.getChildren(t.id))if(this.hasAttachmentInSubtree(e))return!0;return!1}hasIncompleteDescendant(t){for(let e of t.children){let s=this.tree.get(e);if(s&&(!this.isCompleted(s)||this.hasIncompleteDescendant(s)))return!0}return!1}collectEmbeddedAttachmentPaths(){let t=new Set,e=this.noteFolder,s=this.app.vault.getAbstractFileByPath(e);if(!(s instanceof O.TFolder))return t;let i=[s];for(;i.length;){let n=i.pop();for(let r of n.children){if(r instanceof O.TFolder){i.push(r);continue}if(!(r instanceof O.TFile)||r.extension!=="md")continue;let o=this.app.metadataCache.getFileCache(r)?.frontmatter;if(!(!o||!Array.isArray(o.attachments)))for(let a of o.attachments){if(typeof a!="string")continue;let l=this.app.metadataCache.getFirstLinkpathDest(a,r.path);l?t.add(l.path):t.add(a)}}}return t}collectFileItems(t){let e=this.noteFolder,s=this.app.vault.getAbstractFileByPath(e);if(!(s instanceof O.TFolder))return[];let i=this.currentIncludeAttachments(),n=i?new Set:this.collectEmbeddedAttachmentPaths(),r=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),o=[],a=[s];for(;a.length;){let l=a.pop();for(let c of l.children){if(c instanceof O.TFolder){let p=c.name;if(l===s&&r.has(p)||l===s&&p==="_attachments"&&!i)continue;a.push(c);continue}c instanceof O.TFile&&c.extension!=="md"&&(c.name===".stashpad-order.json"||c.name===".stashpad-sort.json"||!i&&n.has(c.path)||o.push(c))}}return o}populateListBody(t,e){this.lastListWidth=t.clientWidth||this.lastListWidth,e.file&&O.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode()==="everything"?this.collectFileItems(e.id):[];if(this.currentChildren.length===0&&i.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(i.length===0)for(let n=0;n<this.currentChildren.length;n++)this.renderNote(t,this.currentChildren[n],n);else{let r=[...this.currentChildren.map((o,a)=>({kind:"note",ts:Number.isFinite(Date.parse(o.created))?Date.parse(o.created):0,idx:a})),...i.map(o=>({kind:"file",ts:o.stat.ctime,file:o}))];r.sort((o,a)=>o.ts-a.ts);for(let o of r)o.kind==="note"?this.renderNote(t,this.currentChildren[o.idx],o.idx):this.renderFileRow(t,o.file)}e.file&&O.Platform.isMobile&&this.installFocusedMiniObserver(t)}refreshList(){if(!this.listEl){this.render();return}let t=this.tree.get(this.focusId)??this.tree.getRoot();this.currentChildren=this.filterChildren(this.collectViewItems(t.id)),this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let e=this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2,s=this.listEl.scrollTop;this.listEl.empty(),this.populateListBody(this.listEl,t),e?this.listEl.scrollTop=this.listEl.scrollHeight:this.listEl.scrollTop=s}renderFileRow(t,e){let s=t.createDiv({cls:"stashpad-file-row"});s.dataset.path=e.path,s.createDiv({cls:"stashpad-file-meta"}).createSpan({cls:"stashpad-file-time",text:this.formatTime(new Date(e.stat.ctime).toISOString())});let n=s.createDiv({cls:"stashpad-file-body"});n.createSpan({cls:"stashpad-file-name",text:e.name}),n.createSpan({cls:"stashpad-file-ext",text:e.extension.toUpperCase()}),s.title=`${e.path} \u2014 click to open`,s.onclick=r=>{r.preventDefault(),this.app.workspace.openLinkText(e.path,"",!1)}}async setViewMode(t){let e={...this.plugin.settings.viewModes??{}};t==="nested"?delete e[this.noteFolder]:e[this.noteFolder]=t,this.plugin.settings.viewModes=e,await this.plugin.saveSettings()}collectViewItems(t){let e=this.currentViewMode(),s=this.currentHideChildless(),i=this.tree.getChildren(t),n=s?i.filter(a=>a.children.length>0):i;if(e==="nested")return n;let r=[],o=a=>{r.push(a);for(let l of this.tree.getChildren(a.id))o(l)};for(let a of n)o(a);return r}filterChildren(t){let e=this.timeFilterCutoff(),s=this.tagFilter?.toLowerCase(),i=this.colorFilter?.toLowerCase()??null,n=this.currentHideCompleted(),r=this.currentAttachmentsOnly();return!e&&!s&&!i&&!n&&!r?t:t.filter(o=>{if(e&&o.created){let a=Date.parse(o.created);if(!Number.isNaN(a)&&a<e)return!1}return!(s&&(!o.file||!this.nodeHasTag(o,s))||i&&(this.colorForNode(o)?.toLowerCase()??null)!==i||n&&this.isCompleted(o)&&!this.hasIncompleteDescendant(o)||r&&!this.hasAttachmentInSubtree(o))})}nodeHasTag(t,e){if(!t.file)return!1;let s=this.app.metadataCache.getFileCache(t.file);if(!s)return!1;if(s.tags){for(let n of s.tags)if((n.tag||"").replace(/^#/,"").toLowerCase()===e)return!0}let i=s.frontmatter?.tags;if(i){let n=Array.isArray(i)?i:[i];for(let r of n)if(typeof r=="string"&&r.replace(/^#/,"").toLowerCase()===e)return!0}return!1}collectFolderTags(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let i of e){if(!i.file)continue;let n=this.app.metadataCache.getFileCache(i.file);if(n?.tags)for(let o of n.tags){let a=(o.tag||"").replace(/^#/,"");a&&t.set(a,(t.get(a)??0)+1)}let r=n?.frontmatter?.tags;if(r){let o=Array.isArray(r)?r:[r];for(let a of o){if(typeof a!="string")continue;let l=a.replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}}}let s=[...t.entries()].map(([i,n])=>({raw:i,count:n,label:this.formatTagLabel(i)}));return s.sort((i,n)=>n.count-i.count||i.label.localeCompare(n.label)),s}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let i of e){let n=this.colorForNode(i);if(!n)continue;let r=n.toLowerCase();t.set(r,(t.get(r)??0)+1)}let s=[...t.entries()].map(([i,n])=>({hex:i,count:n}));return s.sort((i,n)=>n.count-i.count||i.hex.localeCompare(n.hex)),s}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.collectViewItems(t.id));this.cursorIdx=e.length-1,this.selection.clear(),e.length>0&&(this.selection.add(e[e.length-1].id),this.lastSelected=e[e.length-1].id)}stampSelectedCursor(t=!1){let s=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!s)return;this.lastCursorByFocus.set(this.focusId,s);let i=()=>{let n=this.lastCursorByFocus.get(this.focusId);n&&this.plugin.saveLastCursor(this.noteFolder,this.focusId,n)};if(t){this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=null,i();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,i()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,s=Array.from(t.querySelectorAll(".stashpad-note"));if(s.length===0)return null;let i=null;for(let n of s){let r=n.dataset.id;if(!r)continue;let o=n.getBoundingClientRect().top-e;if(o>=0){i={id:r,offsetFromListTop:o};break}i={id:r,offsetFromListTop:o}}return i}restoreScrollAnchor(t,e){let s=this.listEl;if(s){if(t){let i=s.querySelector(`[data-id="${t.id}"]`);if(i){let n=s.getBoundingClientRect().top,r=i.getBoundingClientRect().top-n;s.scrollTop+=r-t.offsetFromListTop;return}}e>0&&(s.scrollTop=e)}}render(t){this.pendingRenderPolicy=t??{kind:"preserve"},this.loadConfig();let e=this.viewRoot,s=this.listEl?.scrollTop??0,n=(t??{kind:"preserve"}).kind==="preserve"?this.captureScrollAnchor():null;!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0,this.pendingComposerCaret=this.composerInputEl?.selectionStart??null);let o=!!this.listEl&&(this.stickToListBottom||this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2);e.empty(),e.toggleClass("is-mobile",O.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let a=this.containerEl.closest(".workspace-leaf");a&&(a.classList.toggle("stashpad-is-tiny",this.tinyMode),a.classList.toggle("stashpad-is-compact",this.compactMode));let l=this.containerEl.closest(".workspace-tabs");l&&l.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let c=this.tree.get(this.focusId)??this.tree.getRoot();c.file&&!O.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,c),this.currentChildren=this.filterChildren(this.collectViewItems(c.id));let p=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let f=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(f.id),this.lastSelected=f.id,this.autoSelectNewest=!1,p=!0}else if(this.pendingFocusIds){let f=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let m=-1;for(let v of f){let y=this.currentChildren.findIndex(b=>b.id===v);y>=0&&(this.selection.add(v),m<0&&(m=y))}this.cursorIdx=m,m>=0&&(this.lastSelected=f.find(v=>this.currentChildren.some(y=>y.id===v))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let u=e.createDiv({cls:"stashpad-list"});if(this.listEl=u,u.addEventListener("dragover",f=>{if(!this.dragSourceIds)return;let m=f.target;if(m&&m.closest&&m.closest(".stashpad-note"))return;f.preventDefault(),f.dataTransfer&&(f.dataTransfer.dropEffect="move");let v=Array.from(u.querySelectorAll(".stashpad-note"));if(v.length!==0){for(let y of v){let b=y.getBoundingClientRect();if(f.clientY<b.top+b.height/2){this.placePlaceholder(y,"before");return}}this.placePlaceholder(v[v.length-1],"after")}}),u.addEventListener("drop",f=>{if(!this.dragSourceIds)return;f.preventDefault();let m=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let v=this.dragPlaceholder.nextElementSibling,y=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),v&&v.classList.contains("stashpad-note")){let b=v.dataset.id;b&&this.reorderToTarget(m,b,"before")}else if(y&&y.classList.contains("stashpad-note")){let b=y.dataset.id;b&&this.reorderToTarget(m,b,"after")}}),this.populateListBody(u,c),this.renderComposer(e),O.Platform.isMobile&&this.renderMobileNav(e),this.plugin.notifyStashpadContentChanged(),p&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let f=this.pendingComposerCaret;this.pendingComposerCaret=null;let m=this.composerInputEl;if(m&&m.isConnected){if(m.focus({preventScroll:!0}),f!=null){let v=Math.min(f,m.value.length);try{m.setSelectionRange(v,v)}catch{}}}else requestAnimationFrame(()=>{let v=this.composerInputEl;if(v&&(v.focus({preventScroll:!0}),f!=null)){let y=Math.min(f,v.value.length);try{v.setSelectionRange(y,y)}catch{}}})}let d=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,d&&this.listEl){let f=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,d.kind){case"preserve":f?this.scrollListToBottom():o?this.scrollListToBottom():this.restoreScrollAnchor(n,s);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let m=d.scrollTop,v=this.listEl,y=()=>{this.suppressScrollSave=!0;let b=Math.max(0,v.scrollHeight-v.clientHeight);v.scrollTop=Math.min(m,b),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};y(),requestAnimationFrame(y),setTimeout(y,60),setTimeout(y,200),setTimeout(y,600);break}case"follow-cursor":s>0&&(this.listEl.scrollTop=s),this.revealCursorRow();break;case"scroll-to-id":{let m=d.id,v=d.align,y=this.listEl,b=()=>{this.suppressScrollSave=!0;let k=y.querySelector(`[data-id="${m}"]`);k&&k.scrollIntoView({block:v,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};b(),requestAnimationFrame(b),setTimeout(b,60),setTimeout(b,200),setTimeout(b,600),setTimeout(()=>{this.suppressScrollSave=!1},700);break}}}else this.scrollToBottomOnNextRender?(this.scrollToBottomOnNextRender=!1,this.scrollListToBottom()):this.listEl&&o?this.scrollListToBottom():this.listEl&&s>0&&(this.listEl.scrollTop=s);if(this.stampSelectedCursor(),this.listEl){this.listResizeObserver?.disconnect();let f=this.listEl,m=f.scrollTop,v=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){f.scrollTop=f.scrollHeight,m=f.scrollTop;return}let b=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop<m&&m<=b?f.scrollTop=m:m=f.scrollTop});v.observe(f),this.listResizeObserver=v,f.addEventListener("wheel",b=>{b.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let y=0;f.addEventListener("touchstart",b=>{y=b.touches[0]?.clientY??0},{passive:!0}),f.addEventListener("touchmove",b=>{let k=b.touches[0]?.clientY??y;k>y&&(this.stickToListBottom=!1),y=k},{passive:!0}),f.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),f.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),s=e.createEl("button",{cls:"stashpad-folder-btn"}),i=!!this.folderOverride,n=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,O.setIcon)(s.createSpan({cls:"stashpad-btn-icon"}),"folder"),s.createSpan({text:n,cls:"stashpad-btn-text"}),s.title=i?`Folder (override): ${this.noteFolder} +${d}`}async function Fi(g,d){if(!(!d||await g.vault.adapter.exists(d)))try{await g.vault.createFolder(d)}catch(e){let s=e?.message??"";if(!/already exists/i.test(s))throw e}}var ln=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);function te(g,d,t){g.empty();try{(0,O.setIcon)(g,d)}catch{}let e=g.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(g.empty(),g.createSpan({cls:"stashpad-icon-fallback",text:t}))}var us={nested:"Nested",flat:"Flat",everything:"Everything"};function cn(g){if(g instanceof Element&&g.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let d=new Set([document]);g instanceof Element&&g.ownerDocument&&d.add(g.ownerDocument);for(let t of d)if(t.body?.querySelector(".modal-bg")||t.body?.querySelector(".modal-container .modal")||t.body?.querySelector(".suggestion-container")||t.body?.querySelector(".menu.mod-active"))return!0;return!1}var fs=[{key:"day",calShort:"Today",rollShort:"24h",calLong:"Since midnight today",rollLong:"Last 24 hours"},{key:"week",calShort:"Week",rollShort:"7d",calLong:"Since Monday this week",rollLong:"Last 7 days"},{key:"month",calShort:"Month",rollShort:"30d",calLong:"Since the 1st of this month",rollLong:"Last 30 days"},{key:"year",calShort:"Year",rollShort:"365d",calLong:"Since January 1 this year",rollLong:"Last 365 days"},{key:"all",calShort:"All",rollShort:"ad infinitum",calLong:"All time",rollLong:"All time"}],Dt=class Dt extends O.ItemView{constructor(t,e){super(t);this.focusId=R;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.noteFolder="Stashpad";this.folderOverride=null;this.tinyMode=!1;this.tinyAlwaysOnTop=!1;this.tinyOpacity=1;this.compactMode=!1;this.detachTreeHook=null;this.detachSettings=null;this.slugDebouncers=new Map;this.attachmentDebouncers=new Map;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.currentChildren=[];this.modeSplit=null;this.modeEnterSubmits=!0;this.nextDestination=null;this.nextDestinationFolder=null;this.nextDestinationLabel=null;this.inListPicker=null;this.listEl=null;this.composerInputEl=null;this.composerDraft="";this.draftsLoadedFor=null;this.autoSelectNewest=!1;this.scrollToBottomOnNextRender=!1;this.scrollListenerSaveTimer=null;this.suppressScrollSave=!1;this.selectionGuardKey=0;this.pendingRenderPolicy=null;this.stickToListBottom=!1;this.keyboardTransitionUntil=0;this.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.expandedNotes=new Set;this.focusComposerOnNextRender=!1;this.suppressComposerFocusUntil=0;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navBackStack=[];this.navForwardSnapshots=[];this.treeReconcileTimer=null;this.stampLastCursorTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.renderCache=new Map;this.bodyObserver=null;this.lazyBodies=new WeakMap;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||cn(t.target))return;let e=St().bindings;if(at(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(at(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(at(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(at(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(at(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(at(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(at(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(at(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let s=t.target,i=!!s&&(s.tagName==="INPUT"||s.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!i){let o=this.composerInputEl;if(o){t.preventDefault(),t.stopPropagation(),o.focus();let l=o.value.length;o.setSelectionRange(l,l);return}}let n=!!s&&(s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.tagName==="BUTTON"||s.tagName==="SELECT");if(t.key==="Escape"&&s instanceof HTMLElement&&(s.tagName==="BUTTON"||s.tagName==="SELECT")&&this.viewRoot.contains(s)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null;let o=this.listEl,l=!!o&&o.scrollTop+o.clientHeight>=o.scrollHeight-2,c=o?.scrollTop??0;if(this.render(),o){let p=l?o.scrollHeight:c;o.scrollTop=p,requestAnimationFrame(()=>{o.scrollTop=l?o.scrollHeight:c}),setTimeout(()=>{o.scrollTop=l?o.scrollHeight:c},60),this.revealCursorRow()}return}if(this.inListPicker&&!n){if(t.key==="ArrowDown"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="ArrowUp"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,-1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="Enter"){t.preventDefault(),this.commitInListPicker();return}return}if(n)return;if(at(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(at(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(at(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(at(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(at(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(at(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(at(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(at(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(at(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(at(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(at(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(at(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let o=this.composerInputEl;if(o){o.focus();let l=o.value.length;o.setSelectionRange(l,l)}return}if(t.key==="ArrowDown"){t.preventDefault(),this.cursorIdx>=this.currentChildren.length-1?this.cursorIdx=0:this.cursorIdx++,this.selectCursor(t.shiftKey);return}if(t.key==="ArrowUp"){t.preventDefault(),this.cursorIdx<=0?this.cursorIdx=this.currentChildren.length-1:this.cursorIdx--,this.selectCursor(t.shiftKey);return}if(t.altKey&&t.key==="ArrowLeft"){t.preventDefault(),this.navigateBack();return}if(t.altKey&&t.key==="ArrowRight"){t.preventDefault(),this.navigateForward();return}if(t.key==="ArrowRight"){let o=this.currentChildren[this.cursorIdx];o&&(t.preventDefault(),this.navigateTo(o.id));return}if(t.key==="ArrowLeft"||t.key==="Backspace"){t.preventDefault(),this.navigateUp();return}if(t.key==="Escape"){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let o=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,o){let l=this.currentChildren.findIndex(c=>c.id===o);this.selection.add(o),this.lastSelected=o,l>=0&&(this.cursorIdx=l)}this.repaintSelectionClasses(),this.revealCursorRow();return}let r=St().bindings;if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(at(t,r.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(at(t,r.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(at(t,r.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(at(t,r.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(at(t,r.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(at(t,r.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(at(t,r.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(at(t,r.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let o=this.tree.get(this.focusId);o?.file&&this.cmdOpenInEditor(o)}else this.cmdOpenInEditor();return}if(at(t,r.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(at(t,r.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(at(t,r.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(at(t,r.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(at(t,r.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(at(t,r.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(at(t,r.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(at(t,r.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(at(t,r.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(at(t,r.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let a=this.tree.get(this.focusId);if(a?.file){if(at(t,r.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(at(t,r.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(a);return}}};this.openSearchInstance=null;this.fmSyncUnsubscribe=null;this.completedState=new Map;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0;this.pendingFocusIds=null;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map;this.onFileModify=t=>{if(!(t instanceof O.TFile)||t.extension!=="md"||!t.path.startsWith(this.noteFolder+"/"))return;let e=Date.now(),s=this.recentSelfWrites.get(t.path);s!==void 0&&e-s<Dt.EXTERNAL_WRITE_GRACE_MS||this.lastExternalModify.set(t.path,e),this.scheduleSlugRename(t),this.scheduleAttachmentSync(t),this.scheduleContribution(t),this.debouncedRender()};this.onFileCreate=t=>{!(t instanceof O.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new ns(this.app),this.log=e.newLog(),this.integrity=new ds(this.tree,this.log),this.order=new rs(this.app),this.sortStore=new as(this.app),this.fmSync=new ls(this.app,()=>this.tree),this.tree.setOrderProvider(s=>{let i=this.noteFolder,n=this.sortStore.getMode(i,s);return n==="manual"?this.order.getOrder(i,s):this.computeSortedIds(s,n)}),this.debouncedRender=(0,O.debounce)(()=>this.render(),80)}getViewType(){return mt}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==R){let s=this.tree.get(this.focusId);if(s){let i=this.titleForNode(s).trim(),n=i.length>40?i.slice(0,40)+"\u2026":i;if(n)return`${e} \u2014 ${n}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let s=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;s&&s.textContent!==t&&s.setText(t)}getIcon(){return"list-tree"}async onOpen(){let t=this.contentEl;t.empty(),t.addClass("stashpad-scroll-host"),this.viewRoot=t.createDiv({cls:"stashpad-view"}),this.viewRoot.setAttribute("tabindex","0"),this.viewRoot.addEventListener("focusin",()=>Xe(this)),this.viewRoot.addEventListener("click",()=>Xe(this)),this.viewRoot.addEventListener("mouseup",a=>{a.button===3?(a.preventDefault(),this.navigateBack()):a.button===4&&(a.preventDefault(),this.navigateForward())}),this.viewRoot.addEventListener("auxclick",a=>{a.button===3?(a.preventDefault(),this.navigateBack()):a.button===4&&(a.preventDefault(),this.navigateForward())}),Xe(this),this.registerInterval(window.setInterval(()=>this.pruneContribMaps(),6e4));let e=null,s=()=>{e||(e=new O.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.selection.size>1){let a=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,a){let o=this.currentChildren.findIndex(l=>l.id===a);this.selection.add(a),this.lastSelected=a,o>=0&&(this.cursorIdx=o)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},i=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",s),this.viewRoot.addEventListener("focusout",a=>{let o=a.relatedTarget;o&&this.viewRoot&&this.viewRoot.contains(o)||i()}),this.register(()=>i()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",a=>{if(a.extension!=="md")return;let o=this.app.metadataCache.getFileCache(a)?.frontmatter;this.completedState.set(a.path,!!o?.completed)})),this.registerEvent(this.app.vault.on("rename",(a,o)=>{this.completedState.has(o)&&(this.completedState.set(a.path,this.completedState.get(o)),this.completedState.delete(o))})),this.registerEvent(this.app.vault.on("delete",a=>{this.completedState.delete(a.path)})),this.detachSettings=gi(()=>{this.loadConfig();let a=this.plugin.settings.drafts?.[this.noteFolder]??"",o=this.composerInputEl?.value??"";a===""&&this.composerDraft!==""&&o===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):a===""&&o!==""&&(this.composerDraft=o),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(a){let o=a?.message??"";/already exists/i.test(o)||console.warn("[Stashpad] bootstrapFolder failed:",a)}this.tree.rebuild(this.noteFolder),this.installFmSyncActivityNotice(),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder();try{let a=this.plugin.loadLastCursor(this.noteFolder);for(let[o,l]of a)this.lastCursorByFocus.set(o,l)}catch{}let n=this.lastCursorByFocus.get(this.focusId),r;n&&this.tree.get(n)?(r={kind:"scroll-to-id",id:n,align:"start"},this.pendingFocusIds=[n]):(this.scrollToBottomOnNextRender=!0,r={kind:"pin-bottom",until:"next-user-input"}),this.render(r),this.tinyMode&&(setTimeout(()=>this.applyTinyWindow(),1e3),setTimeout(()=>this.applyTinyWindow(),1500)),this.registerDomEvent(window,"beforeunload",()=>{this.flushDrafts(),this.stampSelectedCursor(!0)}),this.registerDomEvent(window,"blur",()=>{this.flushDrafts(),this.stampSelectedCursor(!0)}),this.focusComposer(),this.registerEvent(this.app.workspace.on("active-leaf-change",a=>{a===this.leaf?this.focusComposer():this.stickToListBottom=!1}))}scheduleTreeReconcile(){this.treeReconcileTimer==null&&(this.treeReconcileTimer=window.setTimeout(()=>{if(this.treeReconcileTimer=null,!this.viewRoot?.isConnected)return;let t=this.noteFolder,e=t+"/",s=0;for(let i of this.app.vault.getMarkdownFiles()){let n=i.parent?.path?.replace(/\/+$/,"")??"";if(!(n===t||t!==""&&n.startsWith(e)))continue;let r=this.app.metadataCache.getFileCache(i)?.frontmatter?.id;typeof r=="string"&&r&&s++}s!==this.tree.fileBackedCount()&&(this.tree.rebuild(t),this.debouncedRender())},400))}focusView(){requestAnimationFrame(()=>{this.viewRoot?.isConnected&&(document.activeElement instanceof HTMLElement&&(document.activeElement.tagName==="INPUT"||document.activeElement.tagName==="TEXTAREA")||this.viewRoot.focus({preventScroll:!0}))})}focusComposer(){if(!St().autofocusComposerAfterSend)return;let t=()=>{if(!this.viewRoot?.isConnected||Date.now()<this.suppressComposerFocusUntil)return;let e=document.activeElement;e&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA")&&e!==this.composerInputEl||(e&&e.tagName==="BUTTON"&&this.viewRoot.contains(e),this.composerInputEl?.focus({preventScroll:!0}))};requestAnimationFrame(t),setTimeout(t,50),setTimeout(t,200)}async onClose(){ui(this),this.detachTreeHook?.(),this.detachSettings?.(),this.app.vault.off("modify",this.onFileModify),this.app.vault.off("create",this.onFileCreate),window.removeEventListener("keydown",this.onDocKeyDown,!0),this.listResizeObserver?.disconnect(),this.listResizeObserver=null,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null,this.bodyObserver?.disconnect(),this.bodyObserver=null,this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();for(let t of this.contribTimers.values())clearTimeout(t);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}try{await this.fmSync.flush()}catch{}this.stampSelectedCursor(!0),this.fmSyncUnsubscribe?.(),this.fmSyncUnsubscribe=null}setEphemeralState(t){let e=t;e?.focusId&&(this.focusId=e.focusId),e?.timeFilter&&(this.timeFilter=e.timeFilter)}getEphemeralState(){return{focusId:this.focusId,timeFilter:this.timeFilter}}getState(){return{...super.getState()??{},folderOverride:this.folderOverride,timeFilter:this.timeFilter,focusId:this.focusId,tagFilter:this.tagFilter,colorFilter:this.colorFilter,timeFilterCalendar:this.timeFilterCalendar,tinyMode:this.tinyMode,tinyAlwaysOnTop:this.tinyAlwaysOnTop,tinyOpacity:this.tinyOpacity,compactMode:this.compactMode,navBackStack:this.navBackStack,navForwardSnapshots:this.navForwardSnapshots}}async setState(t,e){let s=t??null;if(s){"folderOverride"in s&&(this.folderOverride=s.folderOverride??null),s.timeFilter&&(this.timeFilter=s.timeFilter),s.focusId&&(this.focusId=s.focusId),"tagFilter"in s&&(this.tagFilter=s.tagFilter??null),"colorFilter"in s&&(this.colorFilter=s.colorFilter??null),"timeFilterCalendar"in s&&(this.timeFilterCalendar=!!s.timeFilterCalendar),"tinyMode"in s&&(this.tinyMode=!!s.tinyMode),"tinyAlwaysOnTop"in s&&(this.tinyAlwaysOnTop=!!s.tinyAlwaysOnTop),typeof s.tinyOpacity=="number"&&Number.isFinite(s.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,s.tinyOpacity))),"compactMode"in s&&(this.compactMode=!!s.compactMode);let r=a=>a&&typeof a.folder=="string"&&typeof a.focusId=="string";Array.isArray(s.navBackStack)&&(this.navBackStack=s.navBackStack.filter(r)),Array.isArray(s.navForwardSnapshots)&&(this.navForwardSnapshots=s.navForwardSnapshots.filter(r))}let i=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||i||"Stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot){this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.lastCursorByFocus.clear();try{let o=this.plugin.loadLastCursor(this.noteFolder);for(let[l,c]of o)this.lastCursorByFocus.set(l,c)}catch{}let r=this.lastCursorByFocus.get(this.focusId),a;r&&this.tree.get(r)?(this.pendingFocusIds=[r],a={kind:"scroll-to-id",id:r,align:"start"}):a={kind:"pin-bottom",until:"next-user-input"},this.render(a)}}focus(){this.viewRoot?.focus({preventScroll:!0})}loadConfig(){let t=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),s=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null||t||"Stashpad";s!==this.noteFolder?(this.noteFolder=s,this.tree.rebuild(this.noteFolder)):this.noteFolder=s}captureNavSnapshot(){return{folder:this.noteFolder,focusId:this.focusId}}recordNavState(t={}){let e=this.captureNavSnapshot(),s=this.navBackStack[this.navBackStack.length-1];s&&s.folder===e.folder&&s.focusId===e.focusId||(this.navBackStack.push(e),t.keepForward||(this.navForwardSnapshots=[]))}async setFolderOverride(t,e={}){let s=t?.trim().replace(/^\/+|\/+$/g,"")||null;if(s&&this.isReservedFolder(s)){new O.Notice(`"${s}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((s||null)!==(this.folderOverride||null)){e.skipHistory||this.recordNavState(),this.folderOverride=s,this.focusId=R,this.lastCursorByFocus.clear(),this.selection.clear(),this.cursorIdx=-1,this.lastSelected=null,this.composerDraft="",await this.flushDrafts(),this.draftsLoadedFor=null,this.loadConfig();try{await this.bootstrapFolder()}catch(i){let n=i?.message??"";/already exists/i.test(n)||console.warn("[Stashpad] bootstrapFolder failed:",i)}this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),await this.loadDraftsForFolder();try{let i=this.app.workspace;typeof i.saveLayout=="function"?await i.saveLayout():this.app.workspace.requestSaveLayout()}catch{this.app.workspace.requestSaveLayout()}this.refreshHeaderTitle(),this.render()}}cmdOpenFolderPicker(){this.openFolderPicker()}openFolderPicker(){this.plugin.openFolderPicker()}listVaultFolders(){let t=[];for(let e of this.app.vault.getAllLoadedFiles())if(e instanceof O.TFolder){if(e.path==="/"||e.path===""||e.path.startsWith(".")||this.isReservedFolder(e.path))continue;t.push(e.path)}return t.sort((e,s)=>e.localeCompare(s))}isReservedFolder(t){let e=t.split("/").filter(Boolean).pop()??"";return e?new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed","_authors"].map(i=>(i??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(e):!1}persistFocus(){try{this.app.workspace.requestSaveLayout()}catch{}}cmdUndo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canUndo()){new O.Notice("Nothing to undo.");return}let e=t.peekUndoLabel(),s=this.plugin.notifications.recent()[0]?.category??"system";t.undo().then(()=>this.plugin.notifications.show({message:`Undid: ${e}`,kind:"info",category:s,folder:this.noteFolder})).catch(i=>this.plugin.notifications.show({message:`Undo failed: ${i.message}`,kind:"error",category:"system",folder:this.noteFolder}))}cmdRedo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canRedo()){new O.Notice("Nothing to redo.");return}let e=t.peekRedoLabel(),s=this.plugin.notifications.recent()[0]?.category??"system";t.redo().then(()=>this.plugin.notifications.show({message:`Redid: ${e}`,kind:"info",category:s,folder:this.noteFolder})).catch(i=>this.plugin.notifications.show({message:`Redo failed: ${i.message}`,kind:"error",category:"system",folder:this.noteFolder}))}async snapshotNotes(t,e){let s=[],i=new Set;for(let o of t)!o.file||i.has(o.file.path)||(i.add(o.file.path),s.push(o.file));let n=await Promise.all(s.map(o=>this.app.vault.read(o))),r=s.map((o,l)=>({path:o.path,content:n[l]})),a=[];if(e){let o=new Set,l=[];for(let p of n)for(let u of this.extractAttachments(this.stripFrontmatter(p))){let h=this.app.metadataCache.getFirstLinkpathDest(u,"");h&&!o.has(h.path)&&(o.add(h.path),l.push(h))}let c=await Promise.all(l.map(p=>this.app.vault.readBinary(p)));for(let p=0;p<l.length;p++)a.push({path:l[p].path,data:c[p]})}return{notes:r,attachments:a}}async restoreSnapshots(t,e){for(let i of t.attachments)try{await this.app.vault.adapter.exists(i.path)||await this.app.vault.createBinary(i.path,i.data)}catch{}for(let i of t.notes)try{await this.app.vault.adapter.exists(i.path)||await this.app.vault.create(i.path,i.content)}catch{}let s=()=>{e&&e.some(n=>this.tree.get(n))&&(this.pendingFocusIds=e.slice())};s(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"}),setTimeout(()=>{s(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},100),setTimeout(()=>{s(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},400),setTimeout(()=>{for(let i of t.notes){let n=this.tree.idForPath(i.path);n&&this.fmSync.schedule(n)}},500)}async trashNotesAndAttachments(t){let e=new Set;for(let s of t.notes){let i=this.tree.idForPath(s.path);if(!i)continue;let n=this.tree.get(i);n?.parent&&e.add(n.parent)}for(let s of t.notes){let i=this.app.vault.getAbstractFileByPath(s.path);if(i)try{await this.app.fileManager.trashFile(i)}catch{}}for(let s of t.attachments){let i=this.app.vault.getAbstractFileByPath(s.path);if(i)try{await this.app.fileManager.trashFile(i)}catch{}}this.tree.rebuild(this.noteFolder),this.render();for(let s of e)this.fmSync.scheduleParentOfDeleted(s)}async loadDraftsForFolder(){if(this.draftsLoadedFor===this.noteFolder)return;this.draftsLoadedFor=this.noteFolder;let t=this.plugin.settings.drafts??{};this.composerDraft=t[this.noteFolder]??"",console.debug("[Stashpad] loadDrafts",{folder:this.noteFolder,has:!!t[this.noteFolder],available:Object.keys(t)})}async saveDraft(t){try{let e=this.noteFolder;if((this.plugin.settings.drafts?.[e]??"")===t)return;let i={...this.plugin.settings.drafts??{}};t.length===0?delete i[e]:i[e]=t,this.plugin.settings.drafts=i,t.length===0?await this.plugin.saveSettings():await this.plugin.persistSettingsQuiet()}catch(e){console.warn("Stashpad: drafts save failed",e)}}async recordLastSubmitted(t){try{let e={...this.plugin.settings.lastSubmitted??{}};e[this.noteFolder]=t,this.plugin.settings.lastSubmitted=e,await this.plugin.persistSettingsQuiet()}catch{}}hasRestorableDraft(){let t=this.plugin.settings.drafts?.[this.noteFolder];if(!t||!t.trim())return!1;let e=this.plugin.settings.lastSubmitted?.[this.noteFolder];return!(e&&e===t)}syncComposerDraftForFocus(){}async flushDrafts(){this.composerInputEl?await this.saveDraft(this.composerInputEl.value):await this.saveDraft(this.composerDraft)}timeFilterCutoff(){if(this.timeFilter==="all")return null;if(this.timeFilterCalendar){let e=(0,O.moment)();switch(this.timeFilter){case"day":return e.startOf("day").valueOf();case"week":return e.startOf("isoWeek").valueOf();case"month":return e.startOf("month").valueOf();case"year":return e.startOf("year").valueOf()}}let t=Date.now();switch(this.timeFilter){case"day":return t-864e5;case"week":return t-7*864e5;case"month":return t-30*864e5;case"year":return t-365*864e5}return null}allowedByBases(){return null}currentViewMode(){return this.plugin.settings.viewModes?.[this.noteFolder]??"nested"}currentIncludeAttachments(){return!!this.plugin.settings.includeAttachmentsInEverything?.[this.noteFolder]}async setIncludeAttachments(t){let e={...this.plugin.settings.includeAttachmentsInEverything??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.includeAttachmentsInEverything=e,await this.plugin.saveSettings()}currentHideChildless(){return!!this.plugin.settings.hideChildlessNotes?.[this.noteFolder]}async setHideChildless(t){let e={...this.plugin.settings.hideChildlessNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.hideChildlessNotes=e,await this.plugin.saveSettings()}currentHideCompleted(){return!!this.plugin.settings.hideCompletedNotes?.[this.noteFolder]}async setHideCompleted(t){let e={...this.plugin.settings.hideCompletedNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.hideCompletedNotes=e,await this.plugin.saveSettings()}currentAttachmentsOnly(){return!!this.plugin.settings.attachmentsOnlyNotes?.[this.noteFolder]}async setAttachmentsOnly(t){let e={...this.plugin.settings.attachmentsOnlyNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.attachmentsOnlyNotes=e,await this.plugin.saveSettings()}nodeHasAttachment(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.attachments;return Array.isArray(e)&&e.length>0}hasAttachmentInSubtree(t){if(this.nodeHasAttachment(t))return!0;for(let e of this.tree.getChildren(t.id))if(this.hasAttachmentInSubtree(e))return!0;return!1}hasIncompleteDescendant(t){for(let e of t.children){let s=this.tree.get(e);if(s&&(!this.isCompleted(s)||this.hasIncompleteDescendant(s)))return!0}return!1}collectEmbeddedAttachmentPaths(){let t=new Set,e=this.noteFolder,s=this.app.vault.getAbstractFileByPath(e);if(!(s instanceof O.TFolder))return t;let i=[s];for(;i.length;){let n=i.pop();for(let r of n.children){if(r instanceof O.TFolder){i.push(r);continue}if(!(r instanceof O.TFile)||r.extension!=="md")continue;let a=this.app.metadataCache.getFileCache(r)?.frontmatter;if(!(!a||!Array.isArray(a.attachments)))for(let o of a.attachments){if(typeof o!="string")continue;let l=se(o),c=this.app.metadataCache.getFirstLinkpathDest(l,r.path);c?t.add(c.path):t.add(l)}}}return t}collectFileItems(t){let e=this.noteFolder,s=this.app.vault.getAbstractFileByPath(e);if(!(s instanceof O.TFolder))return[];let i=this.currentIncludeAttachments(),n=i?new Set:this.collectEmbeddedAttachmentPaths(),r=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),a=[],o=[s];for(;o.length;){let l=o.pop();for(let c of l.children){if(c instanceof O.TFolder){let p=c.name;if(l===s&&r.has(p)||l===s&&p==="_attachments"&&!i)continue;o.push(c);continue}c instanceof O.TFile&&c.extension!=="md"&&(c.name===".stashpad-order.json"||c.name===".stashpad-sort.json"||!i&&n.has(c.path)||a.push(c))}}return a}populateListBody(t,e){this.lastListWidth=t.clientWidth||this.lastListWidth,this.armBodyObserver(),e.file&&O.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode()==="everything"?this.collectFileItems(e.id):[];if(this.currentChildren.length===0&&i.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(i.length===0)for(let n=0;n<this.currentChildren.length;n++)this.renderNote(t,this.currentChildren[n],n);else{let r=[...this.currentChildren.map((a,o)=>({kind:"note",ts:Number.isFinite(Date.parse(a.created))?Date.parse(a.created):0,idx:o})),...i.map(a=>({kind:"file",ts:a.stat.ctime,file:a}))];r.sort((a,o)=>a.ts-o.ts);for(let a of r)a.kind==="note"?this.renderNote(t,this.currentChildren[a.idx],a.idx):this.renderFileRow(t,a.file)}e.file&&O.Platform.isMobile&&this.installFocusedMiniObserver(t)}refreshList(){if(!this.listEl){this.render();return}let t=this.tree.get(this.focusId)??this.tree.getRoot();this.currentChildren=this.filterChildren(this.collectViewItems(t.id)),this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let e=this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2,s=this.listEl.scrollTop;this.listEl.empty(),this.populateListBody(this.listEl,t),e?this.listEl.scrollTop=this.listEl.scrollHeight:this.listEl.scrollTop=s}renderFileRow(t,e){let s=t.createDiv({cls:"stashpad-file-row"});s.dataset.path=e.path,s.createDiv({cls:"stashpad-file-meta"}).createSpan({cls:"stashpad-file-time",text:this.formatTime(new Date(e.stat.ctime).toISOString())});let n=s.createDiv({cls:"stashpad-file-body"});n.createSpan({cls:"stashpad-file-name",text:e.name}),n.createSpan({cls:"stashpad-file-ext",text:e.extension.toUpperCase()}),s.title=`${e.path} \u2014 click to open`,s.onclick=r=>{r.preventDefault(),this.app.workspace.openLinkText(e.path,"",!1)}}async setViewMode(t){let e={...this.plugin.settings.viewModes??{}};t==="nested"?delete e[this.noteFolder]:e[this.noteFolder]=t,this.plugin.settings.viewModes=e,await this.plugin.saveSettings()}collectViewItems(t){let e=this.currentViewMode(),s=this.currentHideChildless(),i=this.tree.getChildren(t),n=s?i.filter(o=>o.children.length>0):i;if(e==="nested")return n;let r=[],a=o=>{r.push(o);for(let l of this.tree.getChildren(o.id))a(l)};for(let o of n)a(o);return r}filterChildren(t){let e=this.timeFilterCutoff(),s=this.tagFilter?.toLowerCase(),i=this.colorFilter?.toLowerCase()??null,n=this.currentHideCompleted(),r=this.currentAttachmentsOnly();return!e&&!s&&!i&&!n&&!r?t:t.filter(a=>{if(e&&a.created){let o=Date.parse(a.created);if(!Number.isNaN(o)&&o<e)return!1}return!(s&&(!a.file||!this.nodeHasTag(a,s))||i&&(this.colorForNode(a)?.toLowerCase()??null)!==i||n&&this.isCompleted(a)&&!this.hasIncompleteDescendant(a)||r&&!this.hasAttachmentInSubtree(a))})}nodeHasTag(t,e){if(!t.file)return!1;let s=this.app.metadataCache.getFileCache(t.file);if(!s)return!1;if(s.tags){for(let n of s.tags)if((n.tag||"").replace(/^#/,"").toLowerCase()===e)return!0}let i=s.frontmatter?.tags;if(i){let n=Array.isArray(i)?i:[i];for(let r of n)if(typeof r=="string"&&r.replace(/^#/,"").toLowerCase()===e)return!0}return!1}collectFolderTags(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let i of e){if(!i.file)continue;let n=this.app.metadataCache.getFileCache(i.file);if(n?.tags)for(let a of n.tags){let o=(a.tag||"").replace(/^#/,"");o&&t.set(o,(t.get(o)??0)+1)}let r=n?.frontmatter?.tags;if(r){let a=Array.isArray(r)?r:[r];for(let o of a){if(typeof o!="string")continue;let l=o.replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}}}let s=[...t.entries()].map(([i,n])=>({raw:i,count:n,label:this.formatTagLabel(i)}));return s.sort((i,n)=>n.count-i.count||i.label.localeCompare(n.label)),s}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let i of e){let n=this.colorForNode(i);if(!n)continue;let r=n.toLowerCase();t.set(r,(t.get(r)??0)+1)}let s=[...t.entries()].map(([i,n])=>({hex:i,count:n}));return s.sort((i,n)=>n.count-i.count||i.hex.localeCompare(n.hex)),s}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.collectViewItems(t.id));this.cursorIdx=e.length-1,this.selection.clear(),e.length>0&&(this.selection.add(e[e.length-1].id),this.lastSelected=e[e.length-1].id)}stampSelectedCursor(t=!1){let s=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!s)return;this.lastCursorByFocus.set(this.focusId,s);let i=()=>{let n=this.lastCursorByFocus.get(this.focusId);n&&this.plugin.saveLastCursor(this.noteFolder,this.focusId,n)};if(t){this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=null,i();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,i()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,s=Array.from(t.querySelectorAll(".stashpad-note"));if(s.length===0)return null;let i=null;for(let n of s){let r=n.dataset.id;if(!r)continue;let a=n.getBoundingClientRect().top-e;if(a>=0){i={id:r,offsetFromListTop:a};break}i={id:r,offsetFromListTop:a}}return i}restoreScrollAnchor(t,e){let s=this.listEl;if(s){if(t){let i=s.querySelector(`[data-id="${t.id}"]`);if(i){let n=s.getBoundingClientRect().top,r=i.getBoundingClientRect().top-n;s.scrollTop+=r-t.offsetFromListTop;return}}e>0&&(s.scrollTop=e)}}render(t){Et.enabled&&(this._renderT0=performance.now()),this.pendingRenderPolicy=t??{kind:"preserve"},this.loadConfig();let e=this.viewRoot,s=this.listEl?.scrollTop??0,n=(t??{kind:"preserve"}).kind==="preserve"?this.captureScrollAnchor():null;!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0,this.pendingComposerCaret=this.composerInputEl?.selectionStart??null);let a=!!this.listEl&&(this.stickToListBottom||this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2);e.empty(),e.toggleClass("is-mobile",O.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let o=this.containerEl.closest(".workspace-leaf");o&&(o.classList.toggle("stashpad-is-tiny",this.tinyMode),o.classList.toggle("stashpad-is-compact",this.compactMode));let l=this.containerEl.closest(".workspace-tabs");l&&l.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let c=this.tree.get(this.focusId)??this.tree.getRoot();c.file&&!O.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,c),this.currentChildren=this.filterChildren(this.collectViewItems(c.id));let p=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let f=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(f.id),this.lastSelected=f.id,this.autoSelectNewest=!1,p=!0}else if(this.pendingFocusIds){let f=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let m=-1;for(let v of f){let y=this.currentChildren.findIndex(b=>b.id===v);y>=0&&(this.selection.add(v),m<0&&(m=y))}this.cursorIdx=m,m>=0&&(this.lastSelected=f.find(v=>this.currentChildren.some(y=>y.id===v))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let u=e.createDiv({cls:"stashpad-list"});if(this.listEl=u,u.addEventListener("dragover",f=>{if(!this.dragSourceIds)return;let m=f.target;if(m&&m.closest&&m.closest(".stashpad-note"))return;f.preventDefault(),f.dataTransfer&&(f.dataTransfer.dropEffect="move");let v=Array.from(u.querySelectorAll(".stashpad-note"));if(v.length!==0){for(let y of v){let b=y.getBoundingClientRect();if(f.clientY<b.top+b.height/2){this.placePlaceholder(y,"before");return}}this.placePlaceholder(v[v.length-1],"after")}}),u.addEventListener("drop",f=>{if(!this.dragSourceIds)return;f.preventDefault();let m=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let v=this.dragPlaceholder.nextElementSibling,y=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),v&&v.classList.contains("stashpad-note")){let b=v.dataset.id;b&&this.reorderToTarget(m,b,"before")}else if(y&&y.classList.contains("stashpad-note")){let b=y.dataset.id;b&&this.reorderToTarget(m,b,"after")}}),this.populateListBody(u,c),this.renderComposer(e),O.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(Et.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),p&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let f=this.pendingComposerCaret;this.pendingComposerCaret=null;let m=this.composerInputEl;if(m&&m.isConnected){if(m.focus({preventScroll:!0}),f!=null){let v=Math.min(f,m.value.length);try{m.setSelectionRange(v,v)}catch{}}}else requestAnimationFrame(()=>{let v=this.composerInputEl;if(v&&(v.focus({preventScroll:!0}),f!=null)){let y=Math.min(f,v.value.length);try{v.setSelectionRange(y,y)}catch{}}})}let h=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,h&&this.listEl){let f=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,h.kind){case"preserve":f?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,s);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let m=h.scrollTop,v=this.listEl,y=()=>{this.suppressScrollSave=!0;let b=Math.max(0,v.scrollHeight-v.clientHeight);v.scrollTop=Math.min(m,b),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};y(),requestAnimationFrame(y),setTimeout(y,60),setTimeout(y,200),setTimeout(y,600);break}case"follow-cursor":s>0&&(this.listEl.scrollTop=s),this.revealCursorRow();break;case"scroll-to-id":{let m=h.id,v=h.align,y=this.listEl,b=()=>{this.suppressScrollSave=!0;let k=y.querySelector(`[data-id="${m}"]`);k&&k.scrollIntoView({block:v,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};b(),requestAnimationFrame(b),setTimeout(b,60),setTimeout(b,200),setTimeout(b,600),setTimeout(()=>{this.suppressScrollSave=!1},700);break}}}else this.scrollToBottomOnNextRender?(this.scrollToBottomOnNextRender=!1,this.scrollListToBottom()):this.listEl&&a?this.scrollListToBottom():this.listEl&&s>0&&(this.listEl.scrollTop=s);if(this.stampSelectedCursor(),this.listEl){this.listResizeObserver?.disconnect();let f=this.listEl,m=f.scrollTop,v=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){f.scrollTop=f.scrollHeight,m=f.scrollTop;return}let b=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop<m&&m<=b?f.scrollTop=m:m=f.scrollTop});v.observe(f),this.listResizeObserver=v,f.addEventListener("wheel",b=>{b.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let y=0;f.addEventListener("touchstart",b=>{y=b.touches[0]?.clientY??0},{passive:!0}),f.addEventListener("touchmove",b=>{let k=b.touches[0]?.clientY??y;k>y&&(this.stickToListBottom=!1),y=k},{passive:!0}),f.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),f.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),s=e.createEl("button",{cls:"stashpad-folder-btn"}),i=!!this.folderOverride,n=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,O.setIcon)(s.createSpan({cls:"stashpad-btn-icon"}),"folder"),s.createSpan({text:n,cls:"stashpad-btn-text"}),s.title=i?`Folder (override): ${this.noteFolder} Click to change or revert to default.`:`Folder: ${this.noteFolder} -Click to override for this tab.`,i&&s.addClass("is-override"),s.onclick=d=>{d.preventDefault(),this.openFolderPicker()};let r=e.createEl("button",{cls:"stashpad-search-btn"});Jt(r,"search","\u{1F50D}"),r.title="Search notes (Mod+F)",r.onclick=d=>{d.preventDefault(),this.openSearchModal()},O.Platform.isMobile?this.renderMobileFiltersButton(e):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let o=e.createDiv({cls:"stashpad-time-filter-btns"}),a=o.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,O.setIcon)(a,this.timeFilterCalendar?"calendar":"history"),a.title=this.timeFilterCalendar?"Calendar mode: filters use start-of-day/week/month/year. Click for rolling windows.":"Rolling mode: filters look back N days from now. Click for calendar boundaries.",this.timeFilterCalendar&&a.addClass("is-active"),a.onclick=d=>{d.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let d of ds){let f=this.timeFilterCalendar?d.calShort:d.rollShort,m=this.timeFilterCalendar?d.calLong:d.rollLong,v=o.createEl("button",{cls:"stashpad-time-filter-btn",text:f});v.title=m,this.timeFilter===d.key&&v.addClass("is-active"),v.onclick=y=>{y.preventDefault(),this.setTimeFilter(d.key)}}let l=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let d of ds){let f=this.timeFilterCalendar?d.calLong:d.rollLong,m=l.createEl("option",{text:f});m.value=d.key,this.timeFilter===d.key&&(m.selected=!0)}l.onchange=()=>this.setTimeFilter(l.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!O.Platform.isMobile){let d=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,O.setIcon)(d,"minimize-2"),d.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",d.onclick=f=>{f.preventDefault(),this.plugin.openTinyWindow()}}let p=c.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,O.setIcon)(p,this.compactMode?"panel-top":"rows-2"),p.title=this.compactMode?"Compact mode is ON \u2014 click to restore full chrome.":"Compact mode \u2014 hide the filter row + focused header; keep breadcrumb + list + composer.",this.compactMode&&p.addClass("is-active"),p.onclick=d=>{d.preventDefault(),this.toggleCompactMode()},O.Platform.isMobile)return;let u=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,O.setIcon)(u,"external-link"),u.title=bt().popoutDuplicates?"Duplicate this Stashpad tab into a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)":"Move this Stashpad tab to a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)",u.onclick=d=>{d.preventDefault();let f=bt().popoutDuplicates;try{let m=this.app.workspace;if(f){let v=this.leaf.getViewState(),y=m.openPopoutLeaf?.();y?y.setViewState({...v,active:!0}):new O.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else m.moveLeafToPopout?.(this.leaf)}catch(m){new O.Notice(`Stashpad: open-in-new-window failed (${m.message})`)}}}toggleCompactMode(){this.compactMode=!this.compactMode,this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),s=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Jt(s,"arrow-left","\u2039");let i=this.navBackStack.length>0||this.focusId!==R;s.title=this.navBackStack.length>0?"Back":this.focusId!==R?"Back (up to parent)":"No back history",i||s.addClass("is-disabled"),s.onclick=c=>{c.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Jt(n,"arrow-right","\u203A");let r=this.navForwardSnapshots.length>0;n.title=r?"Forward":"No forward history",r||n.addClass("is-disabled"),n.onclick=c=>{c.preventDefault(),this.navigateForward()};let o=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),a=this.mobileSelectMode;Jt(o,a?"check-square":"square",a?"\u2611":"\u2610"),o.title=a?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",a&&o.addClass("is-active"),o.onclick=c=>{if(c.preventDefault(),this.mobileSelectMode){let p=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),p){let u=this.currentChildren.findIndex(d=>d.id===p);this.selection.add(p),this.lastSelected=p,u>=0&&(this.cursorIdx=u)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let p=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),p&&(this.selection.add(p.id),this.lastSelected=p.id,this.firstSelectedId=p.id),this.render(),new O.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let l=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Jt(l,"zap","\u26A1"),l.title="Actions (move, delete, undo, \u2026)",l.onclick=c=>{c.preventDefault(),this.openMobileActionsMenu(l)}}openMobileActionsMenu(t){let e=new O.Menu,s=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],i=this.selection.size<=1;e.addItem(r=>r.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(r=>r.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(r=>r.setTitle("Notification history\u2026").setIcon("bell").onClick(()=>{this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")})),e.addSeparator(),e.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!s).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(r=>r.setTitle("Open in editor").setIcon("pencil").setDisabled(!s).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(r=>r.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!s).onClick(()=>this.cmdMovePicker())),e.addItem(r=>r.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!s).onClick(()=>this.cmdInListPicker())),e.addItem(r=>r.setTitle("Outdent").setIcon("outdent").setDisabled(!s).onClick(()=>void this.cmdOutdent())),e.addItem(r=>r.setTitle("Set color\u2026").setIcon("palette").setDisabled(!s).onClick(()=>this.cmdSetColor())),e.addItem(r=>r.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!s).onClick(()=>void this.cmdToggleComplete())),e.addItem(r=>r.setTitle("Toggle task (todo)").setIcon("check-square").setDisabled(!s).onClick(()=>void this.cmdToggleTask())),e.addItem(r=>r.setTitle("Set due date\u2026").setIcon("calendar-clock").setDisabled(!s).onClick(()=>this.cmdSetDue())),e.addItem(r=>r.setTitle("Assign to\u2026").setIcon("user-plus").setDisabled(!s).onClick(()=>this.cmdAssign())),e.addSeparator(),e.addItem(r=>r.setTitle("Copy").setIcon("copy").setDisabled(!s).onClick(()=>void this.cmdCopy())),e.addItem(r=>r.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!s).onClick(()=>void this.cmdCopyTree())),e.addItem(r=>r.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!s).onClick(()=>void this.cmdClone())),e.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(r=>r.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(r=>r.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!s||!i).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(r=>r.setTitle("Delete").setIcon("trash-2").setDisabled(!s).onClick(()=>void this.cmdDelete()));let n=t.getBoundingClientRect();e.showAtPosition({x:n.left,y:n.bottom+4})}renderTagFilterDropdown(t){let e=t.createEl("select",{cls:"stashpad-tag-filter-select"}),s=e.createEl("option",{text:"All tags"});s.value="",this.tagFilter||(s.selected=!0);let i=this.collectFolderTags();if(i.length===0)e.disabled=!0,s.text="No tags";else for(let n of i){let r=e.createEl("option",{text:`${n.label} (${n.count})`});r.value=n.raw,this.tagFilter&&this.tagFilter.toLowerCase()===n.raw.toLowerCase()&&(r.selected=!0)}e.onchange=()=>this.setTagFilter(e.value||null)}renderColorFilterDropdown(t){let e=this.collectFolderColors(),s=t.createDiv({cls:"stashpad-color-filter-btn"});s.setAttribute("role","button"),s.setAttribute("tabindex","0"),(()=>{s.empty();let r=s.createSpan({cls:"stashpad-color-filter-swatch"}),o=s.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let a=this.colorFilter.toLowerCase();r.style.background=a;let l=this.plugin.getColorAlias(this.noteFolder,a);o.setText(l??a)}else e.length===0?(r.addClass("is-empty"),o.setText("No colors"),s.addClass("is-disabled")):(r.addClass("is-empty"),o.setText("All colors"))})();let n=r=>{r.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(s,e)};s.onclick=n,s.onkeydown=r=>{(r.key==="Enter"||r.key===" ")&&n(r)}}openColorFilterMenu(t,e){let s=t.ownerDocument??document;s.querySelectorAll(".stashpad-color-filter-popover").forEach(l=>l.remove());let i=s.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();i.style.left=`${Math.max(8,n.left)}px`,i.style.top=`${n.bottom+4}px`,i.style.minWidth=`${n.width}px`,i.style.maxWidth="min(280px, calc(100vw - 16px))",i.style.width="max-content";let r=new O.Scope(this.app.scope),o=()=>{i.remove(),s.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(r)}catch{}},a=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&o()};r.register([],"Escape",l=>(l.preventDefault(),o(),!1)),this.app.keymap?.pushScope(r),this.populateColorMenuBody(i,e,o),setTimeout(()=>{s.addEventListener("mousedown",a,!0)},0)}renderSortDropdown(t){let e=this.noteFolder,s=this.focusId,i=this.sortStore.getMode(e,s),n=this.currentViewMode(),r=n!=="nested",o=t.createDiv({cls:"stashpad-sort-btn"});o.setAttribute("role","button"),o.setAttribute("tabindex",r?"-1":"0"),r&&o.addClass("is-disabled");let a=o.createSpan({cls:"stashpad-sort-icon"});(0,O.setIcon)(a,"arrow-up-down");let l=o.createSpan({cls:"stashpad-sort-label"});r?(l.setText("Sort: \u2014"),o.title=`Sort is per-parent and applies only to Nested view. The current view (${cs[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(l.setText(xe[i]),i!=="manual"&&o.addClass("is-active"),o.title=i==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${xe[i]}. Drag-reorder will revert this parent to Manual.`);let c=p=>{r||(p.preventDefault(),this.openSortMenu(o))};o.onclick=c,o.onkeydown=p=>{r||(p.key==="Enter"||p.key===" ")&&c(p)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(a=>a.remove());let s=e.body.createDiv({cls:"stashpad-sort-popover"}),i=t.getBoundingClientRect();s.style.left=`${Math.max(8,i.left)}px`,s.style.top=`${i.bottom+4}px`,s.style.minWidth=`${i.width}px`,s.style.maxWidth="min(280px, calc(100vw - 16px))",s.style.width="max-content";let n=()=>{s.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(o)}catch{}},r=a=>{!s.contains(a.target)&&a.target!==t&&!t.contains(a.target)&&n()};this.populateSortMenuBody(s,n);let o=new O.Scope(this.app.scope);o.register([],"Escape",a=>(a.preventDefault(),n(),!1)),this.app.keymap?.pushScope(o),setTimeout(()=>{e.addEventListener("mousedown",r,!0)},0)}renderMobileFiltersButton(t){let e=t.createDiv({cls:"stashpad-mobile-filters-btn"});e.setAttribute("role","button"),e.setAttribute("tabindex","0");let s=e.createSpan({cls:"stashpad-mobile-filters-icon"});(0,O.setIcon)(s,"sliders-horizontal"),e.title="Filters / view options";let i=!!this.tagFilter,n=!!this.colorFilter,r=this.timeFilter!=="all",o=this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual",a=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(i||n||r||o||a)&&e.addClass("is-active");let l=c=>{c.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=l,e.onkeydown=c=>{(c.key==="Enter"||c.key===" ")&&l(c)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(u=>u.remove());let s=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),i=t.getBoundingClientRect(),n=e.defaultView??window;s.style.right=`${Math.max(8,n.innerWidth-i.right)}px`,s.style.left="auto",s.style.top=`${i.bottom+4}px`,s.style.maxWidth="min(360px, calc(100vw - 16px))",s.style.width="max-content",s.style.minWidth="260px";let r=()=>{s.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(p)}catch{}},o=u=>{!s.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&r()},a=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:u=>this.populateTagMenuBody(u,r)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:u=>this.populateColorMenuBody(u,this.collectFolderColors(),r)},{key:"time",title:"Time filter",summary:()=>{let u=ds.find(d=>d.key===this.timeFilter);return u?this.timeFilterCalendar?u.calShort:u.rollShort:"All"},populate:u=>this.populateTimeMenuBody(u,r)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":xe[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:u=>{if(this.currentViewMode()!=="nested"){u.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(u,r)}},{key:"view",title:"View",summary:()=>cs[this.currentViewMode()],populate:u=>this.populateViewMenuBody(u,r)}],l="",c=()=>{s.empty();for(let u of a){let d=s.createDiv({cls:"stashpad-mobile-filters-section"}),f=d.createDiv({cls:"stashpad-mobile-filters-header"}),m=f.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,O.setIcon)(m,l===u.key?"chevron-down":"chevron-right"),f.createSpan({cls:"stashpad-mobile-filters-title",text:u.title}),f.createSpan({cls:"stashpad-mobile-filters-summary",text:u.summary()}),f.onclick=v=>{v.preventDefault(),v.stopPropagation(),l=l===u.key?"":u.key,c()},l===u.key){let v=d.createDiv({cls:"stashpad-mobile-filters-body"});u.populate(v)}}};c();let p=new O.Scope(this.app.scope);p.register([],"Escape",u=>(u.preventDefault(),r(),!1)),this.app.keymap?.pushScope(p),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),s=t.createDiv({cls:"stashpad-view-btn"});s.setAttribute("role","button"),s.setAttribute("tabindex","0");let i=s.createSpan({cls:"stashpad-view-icon"});(0,O.setIcon)(i,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),s.createSpan({cls:"stashpad-view-label"}).setText(cs[e]),e!=="nested"&&s.addClass("is-active"),s.title=e==="nested"?"View: Nested (the default). Click to switch to Flat or Everything.":e==="flat"?"View: Flat \u2014 all descendants of the current focus, flat by sort order. Drag-reorder is disabled in this mode. Click to change.":"View: Everything \u2014 all descendants of the current focus PLUS non-Stashpad files in the folder, flat by created/ctime. Click to change.";let r=o=>{o.preventDefault(),this.openViewMenu(s)};s.onclick=r,s.onkeydown=o=>{(o.key==="Enter"||o.key===" ")&&r(o)}}openViewMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-view-popover").forEach(a=>a.remove());let s=e.body.createDiv({cls:"stashpad-view-popover"});O.Platform.isMobile&&s.addClass("is-mobile");let i=t.getBoundingClientRect();s.style.left=`${Math.max(8,i.left)}px`,s.style.top=`${i.bottom+4}px`,s.style.minWidth=`${i.width}px`,s.style.maxWidth="min(320px, calc(100vw - 16px))",s.style.width="max-content";let n=()=>{s.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(o)}catch{}},r=a=>{!s.contains(a.target)&&a.target!==t&&!t.contains(a.target)&&n()};this.populateViewMenuBody(s,n);let o=new O.Scope(this.app.scope);o.register([],"Escape",a=>(a.preventDefault(),n(),!1)),this.app.keymap?.pushScope(o),setTimeout(()=>{e.addEventListener("mousedown",r,!0)},0)}populateViewMenuBody(t,e){let s=this.currentViewMode(),i=(d,f)=>{let m=t.createDiv({cls:"stashpad-view-popover-row"});d===s&&m.addClass("is-active"),m.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:cs[d]}),m.createDiv({cls:"stashpad-view-popover-desc",text:f}),m.onclick=async y=>{y.preventDefault(),y.stopPropagation(),e(),d!==s&&(await this.setViewMode(d),this.render())}};i("nested","Tree of immediate children (default)."),i("flat","All descendants of the current focus, flat by sort."),i("everything","All descendants PLUS non-Stashpad files in the folder."),t.createDiv({cls:"stashpad-view-popover-divider"});let n=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),r=n.createEl("input",{type:"checkbox"});r.checked=this.currentHideChildless(),n.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide childless notes"}),n.createDiv({cls:"stashpad-view-popover-desc",text:s==="nested"?"Show only notes that have children. Applied at this level.":"Hide top-level notes without children; keep every parent's full subtree so no task is overlooked."}),n.onclick=async d=>{d.target!==r&&(d.preventDefault(),r.checked=!r.checked),await this.setHideChildless(r.checked),this.refreshList()};let o=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),a=o.createEl("input",{type:"checkbox"});a.checked=this.currentHideCompleted(),o.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide completed notes"}),o.createDiv({cls:"stashpad-view-popover-desc",text:"Hide notes marked complete. A completed parent stays visible while any descendant is still incomplete."}),o.onclick=async d=>{d.target!==a&&(d.preventDefault(),a.checked=!a.checked),await this.setHideCompleted(a.checked),this.refreshList()};let l=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),c=l.createEl("input",{type:"checkbox"});c.checked=this.currentAttachmentsOnly(),l.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),l.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),l.onclick=async d=>{d.target!==c&&(d.preventDefault(),c.checked=!c.checked),await this.setAttachmentsOnly(c.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let p=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});s!=="everything"&&p.addClass("is-disabled");let u=p.createEl("input",{type:"checkbox"});u.checked=this.currentIncludeAttachments(),u.disabled=s!=="everything",p.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),p.createDiv({cls:"stashpad-view-popover-desc",text:s==="everything"?"Show attachments referenced by notes as their own rows in the file list. Off by default \u2014 they already appear inline on the notes that embed them.":"Only applies in Everything mode."}),p.onclick=async d=>{s==="everything"&&(d.target!==u&&(d.preventDefault(),u.checked=!u.checked),await this.setIncludeAttachments(u.checked),this.refreshList())}}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}populateSortMenuBody(t,e){let s=this.noteFolder,i=this.focusId,n=this.sortStore.getMode(s,i);for(let r of Ns){let o=t.createDiv({cls:"stashpad-sort-popover-row"});r===n&&o.addClass("is-active"),o.createSpan({cls:"stashpad-sort-popover-label",text:xe[r]}),o.onclick=async a=>{a.preventDefault(),a.stopPropagation(),e(),r!==n&&(this.sortStore.setMode(s,i,r),await this.sortStore.save(s),this.tree.rebuild(s),this.render())}}}populateTimeMenuBody(t,e){let s=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),i=s.createEl("input",{type:"checkbox"});i.checked=this.timeFilterCalendar,s.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Calendar mode"}),s.createDiv({cls:"stashpad-view-popover-desc",text:"Use calendar boundaries (start of today/week/month/year). Off = rolling windows back from now."}),s.onclick=n=>{n.target!==i&&(n.preventDefault(),i.checked=!i.checked),this.timeFilterCalendar=i.checked,this.persistFocus(),this.refreshList()};for(let n of ds){let r=t.createDiv({cls:"stashpad-sort-popover-row"});this.timeFilter===n.key&&r.addClass("is-active");let o=this.timeFilterCalendar?n.calLong:n.rollLong;r.createSpan({cls:"stashpad-sort-popover-label",text:o}),r.onclick=a=>{a.preventDefault(),a.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,s){let i=(n,r,o)=>{let a=t.createDiv({cls:"stashpad-color-filter-popover-row"}),l=a.createSpan({cls:"stashpad-color-filter-swatch"});r?l.style.background=r:l.addClass("is-empty");let c=a.createSpan({cls:"stashpad-color-filter-popover-label"});c.setText(n),r&&(c.style.color=r),a.onclick=p=>{p.preventDefault(),p.stopPropagation(),o(),s()}};i("All colors",null,()=>this.setColorFilter(null));for(let n of e){let r=this.plugin.getColorAlias(this.noteFolder,n.hex),o=r?`${r} (${n.count})`:`${n.hex} (${n.count})`;i(o,n.hex,()=>this.setColorFilter(n.hex))}}populateTagMenuBody(t,e){let s=this.collectFolderTags(),i=(n,r)=>{let o=t.createDiv({cls:"stashpad-color-filter-popover-row"});o.createSpan({cls:"stashpad-color-filter-swatch is-empty"}),o.createSpan({cls:"stashpad-color-filter-popover-label"}).setText(n),(this.tagFilter??"")===(r??"")&&o.addClass("is-active"),o.onclick=c=>{c.preventDefault(),c.stopPropagation(),this.setTagFilter(r),e()}};i(s.length===0?"No tags":"All tags",null);for(let n of s)i(`${n.label} (${n.count})`,n.raw)}setColorFilter(t){let e=t?t.toLowerCase():null;(this.colorFilter??null)!==e&&(this.colorFilter=e,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}setTimeFilter(t){this.timeFilter!==t&&(this.timeFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}reconcileSelectionAfterFilter(){let t=this.filterChildren(this.collectViewItems(this.focusId)),e=new Set(t.map(s=>s.id));for(let s of[...this.selection])e.has(s)||this.selection.delete(s);if(this.firstSelectedId&&!e.has(this.firstSelectedId)&&(this.firstSelectedId=null),this.lastSelected&&!e.has(this.lastSelected)&&(this.lastSelected=null),this.selection.size>0){let s=t.findIndex(i=>this.selection.has(i.id));this.cursorIdx=s>=0?s:Math.min(this.cursorIdx,t.length-1)}else this.cursorIdx>=t.length&&(this.cursorIdx=t.length-1)}renderTinyHeader(t){let e=t.createDiv({cls:"stashpad-tiny-header"}),s=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});Jt(s,"arrow-left","\u2039"),s.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==R||s.addClass("is-disabled"),s.title=this.navBackStack.length>0?"Back":this.focusId!==R?"Back (up to parent)":"No back history",s.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});Jt(n,"arrow-right","\u203A"),n.title=this.navForwardSnapshots.length>0?"Forward":"No forward history",this.navForwardSnapshots.length===0&&n.addClass("is-disabled"),n.onclick=()=>this.navigateForward();let r=this.tree.get(this.focusId)??this.tree.getRoot(),o=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),a=this.focusId===R?o:`${o} / ${this.titleForNode(r).trim()}`,l=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),c=l.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,O.setIcon)(c,"folder"),l.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:a}),l.title=`${this.noteFolder}${this.focusId!==R?` / ${this.titleForNode(r).trim()}`:""} -Click to switch / create folder.`,l.onclick=m=>{m.preventDefault(),this.plugin.openFolderPicker()};let p=e.createDiv({cls:"stashpad-tiny-sticky"}),u=p.createEl("input",{type:"checkbox"});if(u.checked=this.tinyAlwaysOnTop,p.createSpan({text:"Sticky"}),u.onchange=()=>{this.tinyAlwaysOnTop=u.checked,this.applyTinyAlwaysOnTop()},!O.Platform.isMobile){let m=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,O.setIcon)(m,"contrast"),m.title="Window transparency",this.tinyOpacity<1&&m.addClass("is-active"),m.onclick=v=>{v.stopPropagation(),this.toggleTinyOpacityPopover(m)}}let d=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,O.setIcon)(d,this.compactMode?"panel-top":"rows-2"),d.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&d.addClass("is-active"),d.onclick=()=>{this.toggleCompactMode()};let f=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,O.setIcon)(f,"maximize-2"),f.title="Exit tiny mode",f.onclick=()=>{this.exitTinyMode()}}toggleTinyOpacityPopover(t){if(this.tinyOpacityPopover){this.tinyOpacityPopover.remove(),this.tinyOpacityPopover=null;return}let e=document.createElement("div");e.className="stashpad-tiny-opacity-popover",e.createSpan({cls:"stashpad-tiny-opacity-label",text:"Transparency"});let s=e.createEl("input",{type:"range"});s.min="30",s.max="100",s.step="1",s.value=String(Math.round(this.tinyOpacity*100));let i=e.createSpan({cls:"stashpad-tiny-opacity-pct",text:`${s.value}%`});s.addEventListener("input",()=>{let c=Math.min(100,Math.max(30,parseInt(s.value,10)||100));this.tinyOpacity=c/100,i.setText(`${c}%`),this.applyTinyOpacity(),t.toggleClass("is-active",this.tinyOpacity<1)}),s.addEventListener("change",()=>{this.app.workspace.requestSaveLayout()}),this.viewRoot.appendChild(e);let n=t.getBoundingClientRect(),r=this.viewRoot.getBoundingClientRect();e.style.top=`${n.bottom-r.top+4}px`,e.style.left=`${Math.max(4,Math.min(n.left-r.left,r.width-180))}px`;let o=c=>{e.contains(c.target)||c.target===t||t.contains(c.target)||l()},a=c=>{c.key==="Escape"&&l()},l=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",o,!0),document.removeEventListener("keydown",a,!0)};setTimeout(()=>{document.addEventListener("mousedown",o,!0),document.addEventListener("keydown",a,!0)},0),this.tinyOpacityPopover=e,s.focus()}getOwnElectronWindow(){try{let t=this.containerEl?.ownerDocument?.defaultView??window,i=((t?.require?.("electron")??window.require?.("electron"))?.remote??t?.electron?.remote??t?.["@electron/remote"])?.getCurrentWindow?.()??t?.electronWindow??null;if(!i)try{let n=window.require?.("electron"),r=n?.remote??n?.["@electron/remote"],a=(r?.BrowserWindow??n?.BrowserWindow)?.getAllWindows?.()??[];a.length===1?i=a[0]:a.length>1&&(i=r?.getFocusedWindow?.()??null??a[a.length-1])}catch(n){console.debug("[Stashpad] BrowserWindow.getAllWindows fallback failed",n)}return i||console.debug("[Stashpad] couldn't resolve own electron window"),i??null}catch(t){return console.debug("[Stashpad] resolve own electron window failed",t),null}}applyTinyAlwaysOnTop(){let t=this.getOwnElectronWindow();if(t)try{t.setAlwaysOnTop?.(!!this.tinyAlwaysOnTop)}catch(e){console.debug("[Stashpad] setAlwaysOnTop failed",e)}}applyTinyOpacity(){let t=this.getOwnElectronWindow();if(!t)return;let e=Math.min(1,Math.max(.3,this.tinyOpacity));try{t.setOpacity?.(e)}catch(s){console.debug("[Stashpad] setOpacity failed",s)}}applyTinyWindow(){let t=this.getOwnElectronWindow();if(t)try{if(this.tinyMode){t.setMinimumSize?.(220,260);let i=100,n=100;try{let r=t.getBounds?.();r&&typeof r.x=="number"&&(i=r.x,n=r.y)}catch{}try{t.setBounds?.({x:i,y:n,width:280,height:360})}catch{}try{t.setSize?.(280,360)}catch{}t.setAlwaysOnTop?.(!!this.tinyAlwaysOnTop);try{t.setOpacity?.(Math.min(1,Math.max(.3,this.tinyOpacity)))}catch{}}else t.setAlwaysOnTop?.(!1)}catch(e){console.debug("[Stashpad] tiny window apply failed",e)}}async exitTinyMode(){this.tinyMode=!1,this.tinyAlwaysOnTop=!1,this.tinyOpacity=1;try{this.getOwnElectronWindow()?.setOpacity?.(1)}catch{}this.compactMode=!1,this.applyTinyWindow();let t=this.getOwnElectronWindow();try{if(t?.setMinimumSize?.(400,300),O.Platform.isMacOS??!1){let s=this.containerEl?.ownerDocument?.defaultView?.require?.("electron")??window.require?.("electron"),n=(s?.remote?.screen??s?.screen)?.getPrimaryDisplay?.().workArea;n?t?.setBounds?.({x:n.x,y:n.y,width:n.width,height:n.height}):t?.maximize?.()}else t?.maximize?.()}catch{}this.render();try{await this.app.workspace.requestSaveLayout?.()}catch{}}enterTinyMode(){this.tinyMode=!0,this.applyTinyWindow(),this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderBreadcrumb(t){let e=t.createDiv({cls:"stashpad-breadcrumb"});this.renderActionsCluster(e);let s=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(O.Platform.isMobile?((0,O.setIcon)(s,"home"),s.title="Home"):s.setText("Home"),s.onclick=()=>this.navigateTo(R),this.focusId===R){let c=this.tree.getChildren(this.focusId).length;if(c>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${c}`}).title=`${c} direct child${c===1?"":"ren"}`),this.compactMode){let p=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,O.setIcon)(p,"panel-top"),p.title="Exit compact mode",p.onclick=u=>{u.preventDefault(),this.toggleCompactMode()}}return}let i=28,n=100,r=this.tree.pathTo(this.focusId),o=r.map(c=>{let p=this.titleForNode(c),u=p.length>i?p.slice(0,i-1)+"\u2026":p;return{id:c.id,label:u}}),a=c=>c.reduce((p,u)=>p+u.label.length+3,0);if(a(o)>n&&o.length>2){let c=!1;for(;a(o)>n&&o.length>2;)o.splice(1,1),c||(o.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),c=!0)}for(let c of o)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),c.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:c.label}).title=r.map(p=>this.titleForNode(p)).join(" / ");else{let p=c.id,u=e.createSpan({cls:"stashpad-crumb",text:c.label});u.title=c.label,u.onclick=()=>this.navigateTo(p),u.oncontextmenu=d=>{d.preventDefault(),this.openCrumbMenu(d,p)},O.Platform.isMobile&&this.attachLongPress(u,()=>this.openCrumbMenu(null,p))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",c=>{c.preventDefault(),this.openCrumbMenu(c,R)}),O.Platform.isMobile){let c=e.querySelector(".stashpad-crumb-home");c&&this.attachLongPress(c,()=>this.openCrumbMenu(null,R))}let l=this.tree.getChildren(this.focusId).length;if(l>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${l}`}).title=`${l} direct child${l===1?"":"ren"}`),this.compactMode){let c=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,O.setIcon)(c,"panel-top"),c.title="Exit compact mode",c.onclick=p=>{p.preventDefault(),this.toggleCompactMode()}}}attachLongPress(t,e){let s=null,i=0,n=0,r=()=>{s!=null&&(window.clearTimeout(s),s=null)};t.addEventListener("touchstart",o=>{let a=o.touches[0];i=a?.clientX??0,n=a?.clientY??0,r(),s=window.setTimeout(()=>{s=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",o=>{let a=o.touches[0];a&&(Math.abs(a.clientX-i)>10||Math.abs(a.clientY-n)>10)&&r()},{passive:!0}),t.addEventListener("touchend",r),t.addEventListener("touchcancel",r)}openCrumbMenu(t,e){let s=this.tree.get(e);if(!s)return;let i=new O.Menu;if(i.addItem(n=>n.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>this.navigateTo(e))),i.addItem(n=>n.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>this.cmdOpenInNewStashpadTab(s))),s.file&&i.addItem(n=>n.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>this.cmdOpenInEditor(s))),t&&(t.clientX>0||t.clientY>0))i.showAtMouseEvent(t);else{let r=(t?.target??null)?.getBoundingClientRect();i.showAtPosition({x:r?.left??8,y:(r?.bottom??60)+4})}}renderFocusedHeaderMini(t,e){if(!e.file)return;let s=e.file,i=t.createDiv({cls:"stashpad-focused-mini"});i.dataset.id=e.id,i.createDiv({cls:"stashpad-focused-mini-text"}).setText(this.titleForNode(e).trim());let r=i.createEl("button",{cls:"stashpad-pencil stashpad-focused-mini-pencil"});(0,O.setIcon)(r,"pencil"),r.title="Edit in new tab",r.onclick=o=>{o.stopPropagation(),this.openFileAtEnd(s)}}installFocusedMiniObserver(t){let e=t.querySelector(".stashpad-focused"),s=t.querySelector(".stashpad-focused-mini");!e||!s||(this.focusedMiniObserver&&this.focusedMiniObserver.disconnect(),this.focusedMiniObserver=new IntersectionObserver(i=>{for(let n of i)s.toggleClass("is-visible",!n.isIntersecting)},{root:t,threshold:.05}),this.focusedMiniObserver.observe(e))}renderFocusedHeader(t,e){if(!e.file)return;let s=e.file,i=t.createDiv({cls:"stashpad-focused"}),r=i.createDiv({cls:"stashpad-focused-meta"}).createDiv({cls:"stashpad-focused-meta-top"});r.createSpan({cls:"stashpad-focused-time stashpad-note-time",text:this.formatTime(e.created)}),r.createDiv({cls:"stashpad-focused-grip-spacer"});let o=i.createDiv({cls:"stashpad-focused-body"});o.addEventListener("click",p=>this.handleRenderedClick(p,e));let a=i.createDiv({cls:"stashpad-focused-actions"}),l=a.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,O.setIcon)(l,"pencil"),l.title="Edit in new tab",l.onclick=()=>void this.openFileAtEnd(s);let c=a.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,O.setIcon)(c,"copy"),c.title="Open this Stashpad in a new tab (clone)",c.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(o,e,{clamp:O.Platform.isMobile,toggleHost:a,toggleAnchor:l})}renderRowBreadcrumb(t,e){let s=this.tree.pathTo(e.id),i=s.findIndex(o=>o.id===this.focusId),n=s.slice(i+1,s.length-1);if(n.length===0)return;let r=t.createDiv({cls:"stashpad-row-breadcrumb"});n.forEach((o,a)=>{let l=r.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(o)});l.title=`Focus into "${this.titleForNode(o)}"`,l.onclick=c=>{c.stopPropagation(),this.navigateTo(o.id)},a<n.length-1&&r.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return Ye(this.app,t,O.Platform.isMobile)}collectAuthorIds(t){let e=new Set,s=i=>{if(typeof i!="string")return null;let n=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let i of t){if(!i.file)continue;let n=this.app.metadataCache.getFileCache(i.file)?.frontmatter;if(!n)continue;let r=s(n.author);if(r&&e.add(r),Array.isArray(n.contributors))for(let o of n.contributors){let a=s(o);a&&e.add(a)}}return Array.from(e)}bulkActionMessage(t){let e=t.nodes.map(o=>`"${this.titleForNode(o).trim()||"(untitled)"}"`),s=t.suffix?` ${t.suffix}`:"",i=t.destination?` ${t.destination}`:"";if(e.length===0)return`${t.verb}${s}${i}`;if(e.length===1)return`${t.verb} ${e[0]}${s}${i}`;let n=t.bulletMax??10,r=e.length<=n?e.map(o=>`\u2022 ${o}`).join(` -`):e.slice(0,n).map(o=>`\u2022 ${o}`).join(` +Click to override for this tab.`,i&&s.addClass("is-override"),s.onclick=h=>{h.preventDefault(),this.openFolderPicker()};let r=e.createEl("button",{cls:"stashpad-search-btn"});te(r,"search","\u{1F50D}"),r.title="Search notes (Mod+F)",r.onclick=h=>{h.preventDefault(),this.openSearchModal()},O.Platform.isMobile?this.renderMobileFiltersButton(e):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let a=e.createDiv({cls:"stashpad-time-filter-btns"}),o=a.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,O.setIcon)(o,this.timeFilterCalendar?"calendar":"history"),o.title=this.timeFilterCalendar?"Calendar mode: filters use start-of-day/week/month/year. Click for rolling windows.":"Rolling mode: filters look back N days from now. Click for calendar boundaries.",this.timeFilterCalendar&&o.addClass("is-active"),o.onclick=h=>{h.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let h of fs){let f=this.timeFilterCalendar?h.calShort:h.rollShort,m=this.timeFilterCalendar?h.calLong:h.rollLong,v=a.createEl("button",{cls:"stashpad-time-filter-btn",text:f});v.title=m,this.timeFilter===h.key&&v.addClass("is-active"),v.onclick=y=>{y.preventDefault(),this.setTimeFilter(h.key)}}let l=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let h of fs){let f=this.timeFilterCalendar?h.calLong:h.rollLong,m=l.createEl("option",{text:f});m.value=h.key,this.timeFilter===h.key&&(m.selected=!0)}l.onchange=()=>this.setTimeFilter(l.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!O.Platform.isMobile){let h=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,O.setIcon)(h,"minimize-2"),h.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",h.onclick=f=>{f.preventDefault(),this.plugin.openTinyWindow()}}let p=c.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,O.setIcon)(p,this.compactMode?"panel-top":"rows-2"),p.title=this.compactMode?"Compact mode is ON \u2014 click to restore full chrome.":"Compact mode \u2014 hide the filter row + focused header; keep breadcrumb + list + composer.",this.compactMode&&p.addClass("is-active"),p.onclick=h=>{h.preventDefault(),this.toggleCompactMode()},O.Platform.isMobile)return;let u=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,O.setIcon)(u,"external-link"),u.title=St().popoutDuplicates?"Duplicate this Stashpad tab into a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)":"Move this Stashpad tab to a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)",u.onclick=h=>{h.preventDefault();let f=St().popoutDuplicates;try{let m=this.app.workspace;if(f){let v=this.leaf.getViewState(),y=m.openPopoutLeaf?.();y?y.setViewState({...v,active:!0}):new O.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else m.moveLeafToPopout?.(this.leaf)}catch(m){new O.Notice(`Stashpad: open-in-new-window failed (${m.message})`)}}}toggleCompactMode(){this.compactMode=!this.compactMode,this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),s=e.createEl("button",{cls:"stashpad-mobile-action-btn"});te(s,"arrow-left","\u2039");let i=this.navBackStack.length>0||this.focusId!==R;s.title=this.navBackStack.length>0?"Back":this.focusId!==R?"Back (up to parent)":"No back history",i||s.addClass("is-disabled"),s.onclick=c=>{c.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});te(n,"arrow-right","\u203A");let r=this.navForwardSnapshots.length>0;n.title=r?"Forward":"No forward history",r||n.addClass("is-disabled"),n.onclick=c=>{c.preventDefault(),this.navigateForward()};let a=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),o=this.mobileSelectMode;te(a,o?"check-square":"square",o?"\u2611":"\u2610"),a.title=o?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",o&&a.addClass("is-active"),a.onclick=c=>{if(c.preventDefault(),this.mobileSelectMode){let p=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),p){let u=this.currentChildren.findIndex(h=>h.id===p);this.selection.add(p),this.lastSelected=p,u>=0&&(this.cursorIdx=u)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let p=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),p&&(this.selection.add(p.id),this.lastSelected=p.id,this.firstSelectedId=p.id),this.render(),new O.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let l=e.createEl("button",{cls:"stashpad-mobile-action-btn"});te(l,"zap","\u26A1"),l.title="Actions (move, delete, undo, \u2026)",l.onclick=c=>{c.preventDefault(),this.openMobileActionsMenu(l)}}openMobileActionsMenu(t){let e=new O.Menu,s=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],i=this.selection.size<=1;e.addItem(r=>r.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(r=>r.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(r=>r.setTitle("Notification history\u2026").setIcon("bell").onClick(()=>{this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")})),e.addSeparator(),e.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!s).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(r=>r.setTitle("Open in editor").setIcon("pencil").setDisabled(!s).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(r=>r.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!s).onClick(()=>this.cmdMovePicker())),e.addItem(r=>r.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!s).onClick(()=>this.cmdInListPicker())),e.addItem(r=>r.setTitle("Outdent").setIcon("outdent").setDisabled(!s).onClick(()=>void this.cmdOutdent())),e.addItem(r=>r.setTitle("Set color\u2026").setIcon("palette").setDisabled(!s).onClick(()=>this.cmdSetColor())),e.addItem(r=>r.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!s).onClick(()=>void this.cmdToggleComplete())),e.addItem(r=>r.setTitle("Toggle task (todo)").setIcon("check-square").setDisabled(!s).onClick(()=>void this.cmdToggleTask())),e.addItem(r=>r.setTitle("Set due date\u2026").setIcon("calendar-clock").setDisabled(!s).onClick(()=>this.cmdSetDue())),e.addItem(r=>r.setTitle("Assign to\u2026").setIcon("user-plus").setDisabled(!s).onClick(()=>this.cmdAssign())),e.addSeparator(),e.addItem(r=>r.setTitle("Copy").setIcon("copy").setDisabled(!s).onClick(()=>void this.cmdCopy())),e.addItem(r=>r.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!s).onClick(()=>void this.cmdCopyTree())),e.addItem(r=>r.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!s).onClick(()=>void this.cmdClone())),e.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(r=>r.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(r=>r.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!s||!i).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(r=>r.setTitle("Delete").setIcon("trash-2").setDisabled(!s).onClick(()=>void this.cmdDelete()));let n=t.getBoundingClientRect();e.showAtPosition({x:n.left,y:n.bottom+4})}renderTagFilterDropdown(t){let e=t.createEl("select",{cls:"stashpad-tag-filter-select"}),s=e.createEl("option",{text:"All tags"});s.value="",this.tagFilter||(s.selected=!0);let i=this.collectFolderTags();if(i.length===0)e.disabled=!0,s.text="No tags";else for(let n of i){let r=e.createEl("option",{text:`${n.label} (${n.count})`});r.value=n.raw,this.tagFilter&&this.tagFilter.toLowerCase()===n.raw.toLowerCase()&&(r.selected=!0)}e.onchange=()=>this.setTagFilter(e.value||null)}renderColorFilterDropdown(t){let e=this.collectFolderColors(),s=t.createDiv({cls:"stashpad-color-filter-btn"});s.setAttribute("role","button"),s.setAttribute("tabindex","0"),(()=>{s.empty();let r=s.createSpan({cls:"stashpad-color-filter-swatch"}),a=s.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let o=this.colorFilter.toLowerCase();r.style.background=o;let l=this.plugin.getColorAlias(this.noteFolder,o);a.setText(l??o)}else e.length===0?(r.addClass("is-empty"),a.setText("No colors"),s.addClass("is-disabled")):(r.addClass("is-empty"),a.setText("All colors"))})();let n=r=>{r.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(s,e)};s.onclick=n,s.onkeydown=r=>{(r.key==="Enter"||r.key===" ")&&n(r)}}openColorFilterMenu(t,e){let s=t.ownerDocument??document;s.querySelectorAll(".stashpad-color-filter-popover").forEach(l=>l.remove());let i=s.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();i.style.left=`${Math.max(8,n.left)}px`,i.style.top=`${n.bottom+4}px`,i.style.minWidth=`${n.width}px`,i.style.maxWidth="min(280px, calc(100vw - 16px))",i.style.width="max-content";let r=new O.Scope(this.app.scope),a=()=>{i.remove(),s.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(r)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&a()};r.register([],"Escape",l=>(l.preventDefault(),a(),!1)),this.app.keymap?.pushScope(r),this.populateColorMenuBody(i,e,a),setTimeout(()=>{s.addEventListener("mousedown",o,!0)},0)}renderSortDropdown(t){let e=this.noteFolder,s=this.focusId,i=this.sortStore.getMode(e,s),n=this.currentViewMode(),r=n!=="nested",a=t.createDiv({cls:"stashpad-sort-btn"});a.setAttribute("role","button"),a.setAttribute("tabindex",r?"-1":"0"),r&&a.addClass("is-disabled");let o=a.createSpan({cls:"stashpad-sort-icon"});(0,O.setIcon)(o,"arrow-up-down");let l=a.createSpan({cls:"stashpad-sort-label"});r?(l.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${us[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(l.setText(_e[i]),i!=="manual"&&a.addClass("is-active"),a.title=i==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${_e[i]}. Drag-reorder will revert this parent to Manual.`);let c=p=>{r||(p.preventDefault(),this.openSortMenu(a))};a.onclick=c,a.onkeydown=p=>{r||(p.key==="Enter"||p.key===" ")&&c(p)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(o=>o.remove());let s=e.body.createDiv({cls:"stashpad-sort-popover"}),i=t.getBoundingClientRect();s.style.left=`${Math.max(8,i.left)}px`,s.style.top=`${i.bottom+4}px`,s.style.minWidth=`${i.width}px`,s.style.maxWidth="min(280px, calc(100vw - 16px))",s.style.width="max-content";let n=()=>{s.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(a)}catch{}},r=o=>{!s.contains(o.target)&&o.target!==t&&!t.contains(o.target)&&n()};this.populateSortMenuBody(s,n);let a=new O.Scope(this.app.scope);a.register([],"Escape",o=>(o.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",r,!0)},0)}renderMobileFiltersButton(t){let e=t.createDiv({cls:"stashpad-mobile-filters-btn"});e.setAttribute("role","button"),e.setAttribute("tabindex","0");let s=e.createSpan({cls:"stashpad-mobile-filters-icon"});(0,O.setIcon)(s,"sliders-horizontal"),e.title="Filters / view options";let i=!!this.tagFilter,n=!!this.colorFilter,r=this.timeFilter!=="all",a=this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual",o=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(i||n||r||a||o)&&e.addClass("is-active");let l=c=>{c.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=l,e.onkeydown=c=>{(c.key==="Enter"||c.key===" ")&&l(c)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(u=>u.remove());let s=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),i=t.getBoundingClientRect(),n=e.defaultView??window;s.style.right=`${Math.max(8,n.innerWidth-i.right)}px`,s.style.left="auto",s.style.top=`${i.bottom+4}px`,s.style.maxWidth="min(360px, calc(100vw - 16px))",s.style.width="max-content",s.style.minWidth="260px";let r=()=>{s.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(p)}catch{}},a=u=>{!s.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&r()},o=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:u=>this.populateTagMenuBody(u,r)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:u=>this.populateColorMenuBody(u,this.collectFolderColors(),r)},{key:"time",title:"Time filter",summary:()=>{let u=fs.find(h=>h.key===this.timeFilter);return u?this.timeFilterCalendar?u.calShort:u.rollShort:"All"},populate:u=>this.populateTimeMenuBody(u,r)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":_e[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:u=>{if(this.currentViewMode()!=="nested"){u.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(u,r)}},{key:"view",title:"View",summary:()=>us[this.currentViewMode()],populate:u=>this.populateViewMenuBody(u,r)}],l="",c=()=>{s.empty();for(let u of o){let h=s.createDiv({cls:"stashpad-mobile-filters-section"}),f=h.createDiv({cls:"stashpad-mobile-filters-header"}),m=f.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,O.setIcon)(m,l===u.key?"chevron-down":"chevron-right"),f.createSpan({cls:"stashpad-mobile-filters-title",text:u.title}),f.createSpan({cls:"stashpad-mobile-filters-summary",text:u.summary()}),f.onclick=v=>{v.preventDefault(),v.stopPropagation(),l=l===u.key?"":u.key,c()},l===u.key){let v=h.createDiv({cls:"stashpad-mobile-filters-body"});u.populate(v)}}};c();let p=new O.Scope(this.app.scope);p.register([],"Escape",u=>(u.preventDefault(),r(),!1)),this.app.keymap?.pushScope(p),setTimeout(()=>{e.addEventListener("mousedown",a,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),s=t.createDiv({cls:"stashpad-view-btn"});s.setAttribute("role","button"),s.setAttribute("tabindex","0");let i=s.createSpan({cls:"stashpad-view-icon"});(0,O.setIcon)(i,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),s.createSpan({cls:"stashpad-view-label"}).setText(us[e]),e!=="nested"&&s.addClass("is-active"),s.title=e==="nested"?"View: Nested (the default). Click to switch to Flat or Everything.":e==="flat"?"View: Flat \u2014 all descendants of the current focus, flat by sort order. Drag-reorder is disabled in this mode. Click to change.":"View: Everything \u2014 all descendants of the current focus PLUS non-Stashpad files in the folder, flat by created/ctime. Click to change.";let r=a=>{a.preventDefault(),this.openViewMenu(s)};s.onclick=r,s.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&r(a)}}openViewMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-view-popover").forEach(o=>o.remove());let s=e.body.createDiv({cls:"stashpad-view-popover"});O.Platform.isMobile&&s.addClass("is-mobile");let i=t.getBoundingClientRect();s.style.left=`${Math.max(8,i.left)}px`,s.style.top=`${i.bottom+4}px`,s.style.minWidth=`${i.width}px`,s.style.maxWidth="min(320px, calc(100vw - 16px))",s.style.width="max-content";let n=()=>{s.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(a)}catch{}},r=o=>{!s.contains(o.target)&&o.target!==t&&!t.contains(o.target)&&n()};this.populateViewMenuBody(s,n);let a=new O.Scope(this.app.scope);a.register([],"Escape",o=>(o.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",r,!0)},0)}populateViewMenuBody(t,e){let s=this.currentViewMode(),i=(h,f)=>{let m=t.createDiv({cls:"stashpad-view-popover-row"});h===s&&m.addClass("is-active"),m.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:us[h]}),m.createDiv({cls:"stashpad-view-popover-desc",text:f}),m.onclick=async y=>{y.preventDefault(),y.stopPropagation(),e(),h!==s&&(await this.setViewMode(h),this.render())}};i("nested","Tree of immediate children (default)."),i("flat","All descendants of the current focus, flat by sort."),i("everything","All descendants PLUS non-Stashpad files in the folder."),t.createDiv({cls:"stashpad-view-popover-divider"});let n=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),r=n.createEl("input",{type:"checkbox"});r.checked=this.currentHideChildless(),n.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide childless notes"}),n.createDiv({cls:"stashpad-view-popover-desc",text:s==="nested"?"Show only notes that have children. Applied at this level.":"Hide top-level notes without children; keep every parent's full subtree so no task is overlooked."}),n.onclick=async h=>{h.target!==r&&(h.preventDefault(),r.checked=!r.checked),await this.setHideChildless(r.checked),this.refreshList()};let a=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),o=a.createEl("input",{type:"checkbox"});o.checked=this.currentHideCompleted(),a.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide completed notes"}),a.createDiv({cls:"stashpad-view-popover-desc",text:"Hide notes marked complete. A completed parent stays visible while any descendant is still incomplete."}),a.onclick=async h=>{h.target!==o&&(h.preventDefault(),o.checked=!o.checked),await this.setHideCompleted(o.checked),this.refreshList()};let l=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),c=l.createEl("input",{type:"checkbox"});c.checked=this.currentAttachmentsOnly(),l.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),l.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),l.onclick=async h=>{h.target!==c&&(h.preventDefault(),c.checked=!c.checked),await this.setAttachmentsOnly(c.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let p=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});s!=="everything"&&p.addClass("is-disabled");let u=p.createEl("input",{type:"checkbox"});u.checked=this.currentIncludeAttachments(),u.disabled=s!=="everything",p.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),p.createDiv({cls:"stashpad-view-popover-desc",text:s==="everything"?"Show attachments referenced by notes as their own rows in the file list. Off by default \u2014 they already appear inline on the notes that embed them.":"Only applies in Everything mode."}),p.onclick=async h=>{s==="everything"&&(h.target!==u&&(h.preventDefault(),u.checked=!u.checked),await this.setIncludeAttachments(u.checked),this.refreshList())}}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}populateSortMenuBody(t,e){let s=this.noteFolder,i=this.focusId,n=this.sortStore.getMode(s,i);for(let r of Hs){let a=t.createDiv({cls:"stashpad-sort-popover-row"});r===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:_e[r]}),a.onclick=async o=>{o.preventDefault(),o.stopPropagation(),e(),r!==n&&(this.sortStore.setMode(s,i,r),await this.sortStore.save(s),this.tree.rebuild(s),this.render())}}}populateTimeMenuBody(t,e){let s=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),i=s.createEl("input",{type:"checkbox"});i.checked=this.timeFilterCalendar,s.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Calendar mode"}),s.createDiv({cls:"stashpad-view-popover-desc",text:"Use calendar boundaries (start of today/week/month/year). Off = rolling windows back from now."}),s.onclick=n=>{n.target!==i&&(n.preventDefault(),i.checked=!i.checked),this.timeFilterCalendar=i.checked,this.persistFocus(),this.refreshList()};for(let n of fs){let r=t.createDiv({cls:"stashpad-sort-popover-row"});this.timeFilter===n.key&&r.addClass("is-active");let a=this.timeFilterCalendar?n.calLong:n.rollLong;r.createSpan({cls:"stashpad-sort-popover-label",text:a}),r.onclick=o=>{o.preventDefault(),o.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,s){let i=(n,r,a)=>{let o=t.createDiv({cls:"stashpad-color-filter-popover-row"}),l=o.createSpan({cls:"stashpad-color-filter-swatch"});r?l.style.background=r:l.addClass("is-empty");let c=o.createSpan({cls:"stashpad-color-filter-popover-label"});c.setText(n),r&&(c.style.color=r),o.onclick=p=>{p.preventDefault(),p.stopPropagation(),a(),s()}};i("All colors",null,()=>this.setColorFilter(null));for(let n of e){let r=this.plugin.getColorAlias(this.noteFolder,n.hex),a=r?`${r} (${n.count})`:`${n.hex} (${n.count})`;i(a,n.hex,()=>this.setColorFilter(n.hex))}}populateTagMenuBody(t,e){let s=this.collectFolderTags(),i=(n,r)=>{let a=t.createDiv({cls:"stashpad-color-filter-popover-row"});a.createSpan({cls:"stashpad-color-filter-swatch is-empty"}),a.createSpan({cls:"stashpad-color-filter-popover-label"}).setText(n),(this.tagFilter??"")===(r??"")&&a.addClass("is-active"),a.onclick=c=>{c.preventDefault(),c.stopPropagation(),this.setTagFilter(r),e()}};i(s.length===0?"No tags":"All tags",null);for(let n of s)i(`${n.label} (${n.count})`,n.raw)}setColorFilter(t){let e=t?t.toLowerCase():null;(this.colorFilter??null)!==e&&(this.colorFilter=e,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}setTimeFilter(t){this.timeFilter!==t&&(this.timeFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}reconcileSelectionAfterFilter(){let t=this.filterChildren(this.collectViewItems(this.focusId)),e=new Set(t.map(s=>s.id));for(let s of[...this.selection])e.has(s)||this.selection.delete(s);if(this.firstSelectedId&&!e.has(this.firstSelectedId)&&(this.firstSelectedId=null),this.lastSelected&&!e.has(this.lastSelected)&&(this.lastSelected=null),this.selection.size>0){let s=t.findIndex(i=>this.selection.has(i.id));this.cursorIdx=s>=0?s:Math.min(this.cursorIdx,t.length-1)}else this.cursorIdx>=t.length&&(this.cursorIdx=t.length-1)}renderTinyHeader(t){let e=t.createDiv({cls:"stashpad-tiny-header"}),s=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});te(s,"arrow-left","\u2039"),s.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==R||s.addClass("is-disabled"),s.title=this.navBackStack.length>0?"Back":this.focusId!==R?"Back (up to parent)":"No back history",s.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});te(n,"arrow-right","\u203A"),n.title=this.navForwardSnapshots.length>0?"Forward":"No forward history",this.navForwardSnapshots.length===0&&n.addClass("is-disabled"),n.onclick=()=>this.navigateForward();let r=this.tree.get(this.focusId)??this.tree.getRoot(),a=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),o=this.focusId===R?a:`${a} / ${this.titleForNode(r).trim()}`,l=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),c=l.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,O.setIcon)(c,"folder"),l.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:o}),l.title=`${this.noteFolder}${this.focusId!==R?` / ${this.titleForNode(r).trim()}`:""} +Click to switch / create folder.`,l.onclick=m=>{m.preventDefault(),this.plugin.openFolderPicker()};let p=e.createDiv({cls:"stashpad-tiny-sticky"}),u=p.createEl("input",{type:"checkbox"});if(u.checked=this.tinyAlwaysOnTop,p.createSpan({text:"Sticky"}),u.onchange=()=>{this.tinyAlwaysOnTop=u.checked,this.applyTinyAlwaysOnTop()},!O.Platform.isMobile){let m=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,O.setIcon)(m,"contrast"),m.title="Window transparency",this.tinyOpacity<1&&m.addClass("is-active"),m.onclick=v=>{v.stopPropagation(),this.toggleTinyOpacityPopover(m)}}let h=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,O.setIcon)(h,this.compactMode?"panel-top":"rows-2"),h.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&h.addClass("is-active"),h.onclick=()=>{this.toggleCompactMode()};let f=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,O.setIcon)(f,"maximize-2"),f.title="Exit tiny mode",f.onclick=()=>{this.exitTinyMode()}}toggleTinyOpacityPopover(t){if(this.tinyOpacityPopover){this.tinyOpacityPopover.remove(),this.tinyOpacityPopover=null;return}let e=document.createElement("div");e.className="stashpad-tiny-opacity-popover",e.createSpan({cls:"stashpad-tiny-opacity-label",text:"Transparency"});let s=e.createEl("input",{type:"range"});s.min="30",s.max="100",s.step="1",s.value=String(Math.round(this.tinyOpacity*100));let i=e.createSpan({cls:"stashpad-tiny-opacity-pct",text:`${s.value}%`});s.addEventListener("input",()=>{let c=Math.min(100,Math.max(30,parseInt(s.value,10)||100));this.tinyOpacity=c/100,i.setText(`${c}%`),this.applyTinyOpacity(),t.toggleClass("is-active",this.tinyOpacity<1)}),s.addEventListener("change",()=>{this.app.workspace.requestSaveLayout()}),this.viewRoot.appendChild(e);let n=t.getBoundingClientRect(),r=this.viewRoot.getBoundingClientRect();e.style.top=`${n.bottom-r.top+4}px`,e.style.left=`${Math.max(4,Math.min(n.left-r.left,r.width-180))}px`;let a=c=>{e.contains(c.target)||c.target===t||t.contains(c.target)||l()},o=c=>{c.key==="Escape"&&l()},l=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",o,!0)};setTimeout(()=>{document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",o,!0)},0),this.tinyOpacityPopover=e,s.focus()}getOwnElectronWindow(){try{let t=this.containerEl?.ownerDocument?.defaultView??window,i=((t?.require?.("electron")??window.require?.("electron"))?.remote??t?.electron?.remote??t?.["@electron/remote"])?.getCurrentWindow?.()??t?.electronWindow??null;if(!i)try{let n=window.require?.("electron"),r=n?.remote??n?.["@electron/remote"],o=(r?.BrowserWindow??n?.BrowserWindow)?.getAllWindows?.()??[];o.length===1?i=o[0]:o.length>1&&(i=r?.getFocusedWindow?.()??null??o[o.length-1])}catch(n){console.debug("[Stashpad] BrowserWindow.getAllWindows fallback failed",n)}return i||console.debug("[Stashpad] couldn't resolve own electron window"),i??null}catch(t){return console.debug("[Stashpad] resolve own electron window failed",t),null}}applyTinyAlwaysOnTop(){let t=this.getOwnElectronWindow();if(t)try{t.setAlwaysOnTop?.(!!this.tinyAlwaysOnTop)}catch(e){console.debug("[Stashpad] setAlwaysOnTop failed",e)}}applyTinyOpacity(){let t=this.getOwnElectronWindow();if(!t)return;let e=Math.min(1,Math.max(.3,this.tinyOpacity));try{t.setOpacity?.(e)}catch(s){console.debug("[Stashpad] setOpacity failed",s)}}applyTinyWindow(){let t=this.getOwnElectronWindow();if(t)try{if(this.tinyMode){t.setMinimumSize?.(220,260);let i=100,n=100;try{let r=t.getBounds?.();r&&typeof r.x=="number"&&(i=r.x,n=r.y)}catch{}try{t.setBounds?.({x:i,y:n,width:280,height:360})}catch{}try{t.setSize?.(280,360)}catch{}t.setAlwaysOnTop?.(!!this.tinyAlwaysOnTop);try{t.setOpacity?.(Math.min(1,Math.max(.3,this.tinyOpacity)))}catch{}}else t.setAlwaysOnTop?.(!1)}catch(e){console.debug("[Stashpad] tiny window apply failed",e)}}async exitTinyMode(){this.tinyMode=!1,this.tinyAlwaysOnTop=!1,this.tinyOpacity=1;try{this.getOwnElectronWindow()?.setOpacity?.(1)}catch{}this.compactMode=!1,this.applyTinyWindow();let t=this.getOwnElectronWindow();try{if(t?.setMinimumSize?.(400,300),O.Platform.isMacOS??!1){let s=this.containerEl?.ownerDocument?.defaultView?.require?.("electron")??window.require?.("electron"),n=(s?.remote?.screen??s?.screen)?.getPrimaryDisplay?.().workArea;n?t?.setBounds?.({x:n.x,y:n.y,width:n.width,height:n.height}):t?.maximize?.()}else t?.maximize?.()}catch{}this.render();try{await this.app.workspace.requestSaveLayout?.()}catch{}}enterTinyMode(){this.tinyMode=!0,this.applyTinyWindow(),this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderBreadcrumb(t){let e=t.createDiv({cls:"stashpad-breadcrumb"});this.renderActionsCluster(e);let s=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(O.Platform.isMobile?((0,O.setIcon)(s,"home"),s.title="Home"):s.setText("Home"),s.onclick=()=>this.navigateTo(R),this.focusId===R){let c=this.tree.getChildren(this.focusId).length;if(c>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${c}`}).title=`${c} direct child${c===1?"":"ren"}`),this.compactMode){let p=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,O.setIcon)(p,"panel-top"),p.title="Exit compact mode",p.onclick=u=>{u.preventDefault(),this.toggleCompactMode()}}return}let i=28,n=100,r=this.tree.pathTo(this.focusId),a=r.map(c=>{let p=this.titleForNode(c),u=p.length>i?p.slice(0,i-1)+"\u2026":p;return{id:c.id,label:u}}),o=c=>c.reduce((p,u)=>p+u.label.length+3,0);if(o(a)>n&&a.length>2){let c=!1;for(;o(a)>n&&a.length>2;)a.splice(1,1),c||(a.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),c=!0)}for(let c of a)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),c.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:c.label}).title=r.map(p=>this.titleForNode(p)).join(" / ");else{let p=c.id,u=e.createSpan({cls:"stashpad-crumb",text:c.label});u.title=c.label,u.onclick=()=>this.navigateTo(p),u.oncontextmenu=h=>{h.preventDefault(),this.openCrumbMenu(h,p)},O.Platform.isMobile&&this.attachLongPress(u,()=>this.openCrumbMenu(null,p))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",c=>{c.preventDefault(),this.openCrumbMenu(c,R)}),O.Platform.isMobile){let c=e.querySelector(".stashpad-crumb-home");c&&this.attachLongPress(c,()=>this.openCrumbMenu(null,R))}let l=this.tree.getChildren(this.focusId).length;if(l>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${l}`}).title=`${l} direct child${l===1?"":"ren"}`),this.compactMode){let c=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,O.setIcon)(c,"panel-top"),c.title="Exit compact mode",c.onclick=p=>{p.preventDefault(),this.toggleCompactMode()}}}attachLongPress(t,e){let s=null,i=0,n=0,r=()=>{s!=null&&(window.clearTimeout(s),s=null)};t.addEventListener("touchstart",a=>{let o=a.touches[0];i=o?.clientX??0,n=o?.clientY??0,r(),s=window.setTimeout(()=>{s=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let o=a.touches[0];o&&(Math.abs(o.clientX-i)>10||Math.abs(o.clientY-n)>10)&&r()},{passive:!0}),t.addEventListener("touchend",r),t.addEventListener("touchcancel",r)}openCrumbMenu(t,e){let s=this.tree.get(e);if(!s)return;let i=new O.Menu;if(i.addItem(n=>n.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>this.navigateTo(e))),i.addItem(n=>n.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>this.cmdOpenInNewStashpadTab(s))),s.file&&i.addItem(n=>n.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>this.cmdOpenInEditor(s))),t&&(t.clientX>0||t.clientY>0))i.showAtMouseEvent(t);else{let r=(t?.target??null)?.getBoundingClientRect();i.showAtPosition({x:r?.left??8,y:(r?.bottom??60)+4})}}renderFocusedHeaderMini(t,e){if(!e.file)return;let s=e.file,i=t.createDiv({cls:"stashpad-focused-mini"});i.dataset.id=e.id,i.createDiv({cls:"stashpad-focused-mini-text"}).setText(this.titleForNode(e).trim());let r=i.createEl("button",{cls:"stashpad-pencil stashpad-focused-mini-pencil"});(0,O.setIcon)(r,"pencil"),r.title="Edit in new tab",r.onclick=a=>{a.stopPropagation(),this.openFileAtEnd(s)}}installFocusedMiniObserver(t){let e=t.querySelector(".stashpad-focused"),s=t.querySelector(".stashpad-focused-mini");!e||!s||(this.focusedMiniObserver&&this.focusedMiniObserver.disconnect(),this.focusedMiniObserver=new IntersectionObserver(i=>{for(let n of i)s.toggleClass("is-visible",!n.isIntersecting)},{root:t,threshold:.05}),this.focusedMiniObserver.observe(e))}renderFocusedHeader(t,e){if(!e.file)return;let s=e.file,i=t.createDiv({cls:"stashpad-focused"}),r=i.createDiv({cls:"stashpad-focused-meta"}).createDiv({cls:"stashpad-focused-meta-top"});r.createSpan({cls:"stashpad-focused-time stashpad-note-time",text:this.formatTime(e.created)}),r.createDiv({cls:"stashpad-focused-grip-spacer"});let a=i.createDiv({cls:"stashpad-focused-body"});a.addEventListener("click",p=>this.handleRenderedClick(p,e));let o=i.createDiv({cls:"stashpad-focused-actions"}),l=o.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,O.setIcon)(l,"pencil"),l.title="Edit in new tab",l.onclick=()=>void this.openFileAtEnd(s);let c=o.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,O.setIcon)(c,"copy"),c.title="Open this Stashpad in a new tab (clone)",c.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:O.Platform.isMobile,toggleHost:o,toggleAnchor:l})}renderRowBreadcrumb(t,e){let s=this.tree.pathTo(e.id),i=s.findIndex(a=>a.id===this.focusId),n=s.slice(i+1,s.length-1);if(n.length===0)return;let r=t.createDiv({cls:"stashpad-row-breadcrumb"});n.forEach((a,o)=>{let l=r.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(a)});l.title=`Focus into "${this.titleForNode(a)}"`,l.onclick=c=>{c.stopPropagation(),this.navigateTo(a.id)},o<n.length-1&&r.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return Ge(this.app,t,O.Platform.isMobile)}collectAuthorIds(t){let e=new Set,s=i=>{if(typeof i!="string")return null;let n=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let i of t){if(!i.file)continue;let n=this.app.metadataCache.getFileCache(i.file)?.frontmatter;if(!n)continue;let r=s(n.author);if(r&&e.add(r),Array.isArray(n.contributors))for(let a of n.contributors){let o=s(a);o&&e.add(o)}}return Array.from(e)}bulkActionMessage(t){let e=t.nodes.map(a=>`"${this.titleForNode(a).trim()||"(untitled)"}"`),s=t.suffix?` ${t.suffix}`:"",i=t.destination?` ${t.destination}`:"";if(e.length===0)return`${t.verb}${s}${i}`;if(e.length===1)return`${t.verb} ${e[0]}${s}${i}`;let n=t.bulletMax??10,r=e.length<=n?e.map(a=>`\u2022 ${a}`).join(` +`):e.slice(0,n).map(a=>`\u2022 ${a}`).join(` `)+` \u2026+ ${e.length-n} more`;return`${t.verb} ${e.length} notes${s}${i}: -${r}`}titleList(t,e=3){if(!t.length)return"";let s=t.map(n=>this.titleForNode(n).trim()||"(untitled)");return s.length<=e?s.map(n=>`"${n}"`).join(", "):`${s.slice(0,e).map(n=>`"${n}"`).join(", ")}, +${s.length-e} more`}titleForNode(t){if(!t.file)return"Untitled";let s=this.app.metadataCache.getFileCache(t.file)?.headings?.[0]?.heading;return s||t.file.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")||"Untitled"}computeSortedIds(t,e){return this.tree.getChildren(t).slice().sort((i,n)=>this.compareForSort(i,n,e)).map(i=>i.id)}compareForSort(t,e,s){switch(s){case"created-asc":return(t.created||"").localeCompare(e.created||"");case"created-desc":return(e.created||"").localeCompare(t.created||"");case"modified-asc":case"modified-desc":{let i=this.modifiedFor(t)||t.created||"",n=this.modifiedFor(e)||e.created||"";return s==="modified-asc"?i.localeCompare(n):n.localeCompare(i)}case"title-az":case"title-za":{let i=this.titleForNode(t),n=this.titleForNode(e),r={numeric:!0,sensitivity:"base"};return s==="title-az"?i.localeCompare(n,void 0,r):n.localeCompare(i,void 0,r)}default:return 0}}modifiedFor(t){if(!t.file)return"";let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return(typeof e?.modified=="string"?e.modified:"")||""}async forceManualMode(t){let e=this.noteFolder;this.sortStore.getMode(e,t)!=="manual"&&(this.sortStore.setMode(e,t,"manual"),await this.sortStore.save(e))}renderNote(t,e,s){if(!e.file)return;let i=e.file,n=this.tree.getChildren(e.id).length,r=this.selection.has(e.id),o=s===this.cursorIdx,a=this.inListPicker?.activeIdx===s,l=t.createDiv({cls:"stashpad-note"});r&&l.addClass("is-selected"),o&&l.addClass("is-cursor"),o&&this.plugin.settings.autoExpandCursorRow&&l.addClass("is-cursor-expanded"),a&&l.addClass("is-pick-target"),this.isCompleted(e)&&l.addClass("is-completed"),l.dataset.idx=String(s),l.dataset.id=e.id;let c=this.currentViewMode()==="nested";if(l.draggable=c,c&&this.attachRowDnD(l,e,s),l.addEventListener("click",C=>this.handleRowClick(C,s,e)),l.addEventListener("dblclick",C=>{!this.plugin.settings.doubleClickToFocus||C.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(C.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))}),this.isTask(e)){l.addClass("is-task");let C=l.createSpan({cls:"stashpad-note-task-checkbox"}),I=this.isCompleted(e);(0,O.setIcon)(C,I?"check-square":"square"),C.title=I?"Mark not done":"Mark done",C.addEventListener("mousedown",E=>E.stopPropagation()),C.addEventListener("dblclick",E=>{E.preventDefault(),E.stopPropagation()}),C.onclick=E=>{E.preventDefault(),E.stopPropagation(),this.toggleCompletedForNode(e)}}let p=l.createDiv({cls:"stashpad-note-meta"}),u=p.createDiv({cls:"stashpad-note-meta-top"});u.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let d=this.colorForNode(e),f=u.createDiv({cls:"stashpad-note-grip"});if(d&&f.addClass("has-color"),(0,O.setIcon)(f,"grip-vertical"),f.title=d?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",f.draggable=c,c||(f.title=d?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),d&&f.style.setProperty("--stashpad-note-color",d),n>0){let C=p.createSpan({cls:"stashpad-note-enter"});d&&(C.style.color=d),(0,O.setIcon)(C.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),C.createSpan({text:` ${n}`}),C.onclick=I=>{I.stopPropagation(),this.navigateTo(e.id)}}if(d)l.addClass("has-color"),l.style.setProperty("--stashpad-note-color",d);else{let C=this.inheritedColorForNode(e);C&&C.depth>0&&(l.addClass("has-inherited-color"),l.style.setProperty("--stashpad-inherited-color",C.hex),l.style.setProperty("--stashpad-inherited-depth",String(C.depth)))}let m=l.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(m,e);let v=m.createDiv({cls:"stashpad-note-body-content"}),y=l.createDiv({cls:"stashpad-note-actions"}),b=y.createEl("button",{cls:"stashpad-pencil"});(0,O.setIcon)(b,"pencil"),b.title="Edit in new tab",b.onclick=C=>{C.stopPropagation(),this.openFileAtEnd(i)};let k=y.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,O.setIcon)(k,"arrow-right"),k.title="Open in Stashpad view",k.onclick=C=>{C.stopPropagation(),this.navigateTo(e.id)},this.renderNoteBody(v,e,{clamp:!0,toggleHost:y,toggleAnchor:b}),l.oncontextmenu=C=>{C.preventDefault(),this.openNoteMenu(C,e)}}async getOrComputeRender(t){let e=this.renderCache.get(t.path);if(e&&e.mtime===t.stat.mtime)return e;let s=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(s),{text:n,attachments:r}=this.splitAttachments(i),o=createDiv({cls:"stashpad-note-text"});await O.MarkdownRenderer.render(this.app,n,o,t.path,this);let a=o.innerHTML,l={mtime:t.stat.mtime,text:n,attachments:r,html:a};return this.renderCache.set(t.path,l),l}renderNoteBody(t,e,s={clamp:!0}){if(!e.file)return;let i=e.file,n=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=n,this.getOrComputeRender(i).then(r=>{if(t.__stashpadRenderToken!==n)return;let{text:o,attachments:a,html:l}=r;t.empty();let c=t.createDiv({cls:"stashpad-note-text"}),p=this.expandedNotes.has(e.id);if(s.clamp&&!p&&c.addClass("is-clamped"),this.compactMode||this.tinyMode?(c.addClass("is-plain"),c.textContent=o):c.innerHTML=l,a.length>0&&this.renderAttachmentRail(t,a),this.renderAuthorshipFooter(t,e),!s.clamp)return;let u=this.lastListWidth;if(r.ovW===u&&r.ovV!==void 0&&!p){r.ovV?this.attachExpandToggle(s,t,e,p):c.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let d=c.scrollHeight>c.clientHeight+4;if(r.ovW=u,r.ovV=d,!d&&!p){c.removeClass("is-clamped");return}this.attachExpandToggle(s,t,e,p)})})}attachExpandToggle(t,e,s,i){let n=!!t.toggleHost,r=t.toggleHost??e;r.querySelector(".stashpad-expand-toggle")?.remove();let o=r.createEl("button",{cls:"stashpad-expand-toggle"});o.title=i?"Show less":"Show more",n||O.Platform.isMobile?((0,O.setIcon)(o,i?"chevron-up":"chevron-down"),o.addClass("is-icon"),n&&o.addClass("is-inline")):o.setText(i?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===r&&r.insertBefore(o,t.toggleAnchor),o.onclick=a=>{a.stopPropagation(),this.expandedNotes.has(s.id)?this.expandedNotes.delete(s.id):this.expandedNotes.add(s.id),e.empty(),this.renderNoteBody(e,s,t)}}splitAttachments(t){let e=[];return{text:t.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,n)=>(e.push(n),"")).replace(/\n{3,}/g,` +${r}`}titleList(t,e=3){if(!t.length)return"";let s=t.map(n=>this.titleForNode(n).trim()||"(untitled)");return s.length<=e?s.map(n=>`"${n}"`).join(", "):`${s.slice(0,e).map(n=>`"${n}"`).join(", ")}, +${s.length-e} more`}titleForNode(t){if(!t.file)return"Untitled";let s=this.app.metadataCache.getFileCache(t.file)?.headings?.[0]?.heading;return s||t.file.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")||"Untitled"}computeSortedIds(t,e){return this.tree.getChildren(t).slice().sort((i,n)=>this.compareForSort(i,n,e)).map(i=>i.id)}compareForSort(t,e,s){switch(s){case"created-asc":return(t.created||"").localeCompare(e.created||"");case"created-desc":return(e.created||"").localeCompare(t.created||"");case"modified-asc":case"modified-desc":{let i=this.modifiedFor(t)||t.created||"",n=this.modifiedFor(e)||e.created||"";return s==="modified-asc"?i.localeCompare(n):n.localeCompare(i)}case"title-az":case"title-za":{let i=this.titleForNode(t),n=this.titleForNode(e),r={numeric:!0,sensitivity:"base"};return s==="title-az"?i.localeCompare(n,void 0,r):n.localeCompare(i,void 0,r)}default:return 0}}modifiedFor(t){if(!t.file)return"";let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return(typeof e?.modified=="string"?e.modified:"")||""}async forceManualMode(t){let e=this.noteFolder;this.sortStore.getMode(e,t)!=="manual"&&(this.sortStore.setMode(e,t,"manual"),await this.sortStore.save(e))}renderNote(t,e,s){if(!e.file)return;let i=e.file,n=this.tree.getChildren(e.id).length,r=this.selection.has(e.id),a=s===this.cursorIdx,o=this.inListPicker?.activeIdx===s,l=t.createDiv({cls:"stashpad-note"});r&&l.addClass("is-selected"),a&&l.addClass("is-cursor"),a&&this.plugin.settings.autoExpandCursorRow&&l.addClass("is-cursor-expanded"),o&&l.addClass("is-pick-target"),this.isCompleted(e)&&l.addClass("is-completed"),l.dataset.idx=String(s),l.dataset.id=e.id;let c=this.currentViewMode()==="nested";if(l.draggable=c,c&&this.attachRowDnD(l,e,s),l.addEventListener("click",T=>this.handleRowClick(T,s,e)),l.addEventListener("dblclick",T=>{!this.plugin.settings.doubleClickToFocus||T.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(T.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))}),this.isTask(e)){l.addClass("is-task");let T=l.createSpan({cls:"stashpad-note-task-checkbox"}),I=this.isCompleted(e);(0,O.setIcon)(T,I?"check-square":"square"),T.title=I?"Mark not done":"Mark done",T.addEventListener("mousedown",E=>E.stopPropagation()),T.addEventListener("dblclick",E=>{E.preventDefault(),E.stopPropagation()}),T.onclick=E=>{E.preventDefault(),E.stopPropagation(),this.toggleCompletedForNode(e)}}let p=l.createDiv({cls:"stashpad-note-meta"}),u=p.createDiv({cls:"stashpad-note-meta-top"});u.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let h=this.colorForNode(e),f=u.createDiv({cls:"stashpad-note-grip"});if(h&&f.addClass("has-color"),(0,O.setIcon)(f,"grip-vertical"),f.title=h?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",f.draggable=c,c||(f.title=h?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),h&&f.style.setProperty("--stashpad-note-color",h),n>0){let T=p.createSpan({cls:"stashpad-note-enter"});h&&(T.style.color=h),(0,O.setIcon)(T.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),T.createSpan({text:` ${n}`}),T.onclick=I=>{I.stopPropagation(),this.navigateTo(e.id)}}if(h)l.addClass("has-color"),l.style.setProperty("--stashpad-note-color",h);else{let T=this.inheritedColorForNode(e);T&&T.depth>0&&(l.addClass("has-inherited-color"),l.style.setProperty("--stashpad-inherited-color",T.hex),l.style.setProperty("--stashpad-inherited-depth",String(T.depth)))}let m=l.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(m,e);let v=m.createDiv({cls:"stashpad-note-body-content"}),y=l.createDiv({cls:"stashpad-note-actions"}),b=y.createEl("button",{cls:"stashpad-pencil"});(0,O.setIcon)(b,"pencil"),b.title="Edit in new tab",b.onclick=T=>{T.stopPropagation(),this.openFileAtEnd(i)};let k=y.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,O.setIcon)(k,"arrow-right"),k.title="Open in Stashpad view",k.onclick=T=>{T.stopPropagation(),this.navigateTo(e.id)},this.renderNoteBody(v,e,{clamp:!0,toggleHost:y,toggleAnchor:b}),l.oncontextmenu=T=>{T.preventDefault(),this.openNoteMenu(T,e)}}async getOrComputeRender(t){let e=this.renderCache.get(t.path);if(e&&e.mtime===t.stat.mtime)return Et.record("render.row.cacheHit",0),e;let s=await Et.timeAsync("render.row.read",()=>this.app.vault.cachedRead(t)),i=this.stripFrontmatter(s),{text:n,attachments:r}=this.splitAttachments(i),a=createDiv({cls:"stashpad-note-text"});await Et.timeAsync("render.row.markdown",()=>O.MarkdownRenderer.render(this.app,n,a,t.path,this));let o=a.innerHTML,l={mtime:t.stat.mtime,text:n,attachments:r,html:o};return this.renderCache.set(t.path,l),l}armBodyObserver(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(t=>{for(let e of t){if(!e.isIntersecting)continue;let s=e.target,i=this.lazyBodies.get(s);this.bodyObserver?.unobserve(s),this.lazyBodies.delete(s),i&&i()}},{root:this.contentEl,rootMargin:"1400px 0px"})}hasFreshRenderCache(t){let e=this.renderCache.get(t.path);return!!e&&e.mtime===t.stat.mtime}renderNoteBody(t,e,s={clamp:!0}){if(!e.file)return;if(this.hasFreshRenderCache(e.file)||!this.bodyObserver){this.renderNoteBodyNow(t,e,s);return}t.empty();let i=t.createDiv({cls:"stashpad-note-text is-plain is-lazy-placeholder"});i.textContent=this.titleForNode(e),this.lazyBodies.set(t,()=>this.renderNoteBodyNow(t,e,s)),this.bodyObserver.observe(t)}renderNoteBodyNow(t,e,s={clamp:!0}){if(!e.file)return;let i=e.file,n=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=n,this.getOrComputeRender(i).then(r=>{if(t.__stashpadRenderToken!==n)return;let{text:a,attachments:o,html:l}=r;t.empty();let c=t.createDiv({cls:"stashpad-note-text"}),p=this.expandedNotes.has(e.id);if(s.clamp&&!p&&c.addClass("is-clamped"),this.compactMode||this.tinyMode?(c.addClass("is-plain"),c.textContent=a):c.innerHTML=l,o.length>0&&this.renderAttachmentRail(t,o),this.renderAuthorshipFooter(t,e),!s.clamp)return;let u=this.lastListWidth;if(r.ovW===u&&r.ovV!==void 0&&!p){r.ovV?this.attachExpandToggle(s,t,e,p):c.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let h=c.scrollHeight>c.clientHeight+4;if(r.ovW=u,r.ovV=h,!h&&!p){c.removeClass("is-clamped");return}this.attachExpandToggle(s,t,e,p)})})}attachExpandToggle(t,e,s,i){let n=!!t.toggleHost,r=t.toggleHost??e;r.querySelector(".stashpad-expand-toggle")?.remove();let a=r.createEl("button",{cls:"stashpad-expand-toggle"});a.title=i?"Show less":"Show more",n||O.Platform.isMobile?((0,O.setIcon)(a,i?"chevron-up":"chevron-down"),a.addClass("is-icon"),n&&a.addClass("is-inline")):a.setText(i?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===r&&r.insertBefore(a,t.toggleAnchor),a.onclick=o=>{o.stopPropagation(),this.expandedNotes.has(s.id)?this.expandedNotes.delete(s.id):this.expandedNotes.add(s.id),e.empty(),this.renderNoteBody(e,s,t)}}splitAttachments(t){let e=[];return{text:t.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,n)=>(e.push(n),"")).replace(/\n{3,}/g,` -`).trim(),attachments:e}}renderAttachmentRail(t,e){let s=t.createDiv({cls:"stashpad-rail"});for(let i of e){let n=this.app.metadataCache.getFirstLinkpathDest(i,""),r=(i.split(".").pop()??"").toLowerCase(),o=s.createDiv({cls:"stashpad-att"});if(o.title=i,n&&en.has(r)){let a=o.createEl("img",{cls:"stashpad-att-img"});a.src=this.app.vault.getResourcePath(n),a.alt=i}else{o.createDiv({cls:"stashpad-att-ext",text:r.toUpperCase()||"?"});let a=(i.split("/").pop()??i).replace(/\.[^.]+$/,"");o.createDiv({cls:"stashpad-att-name",text:a})}o.onclick=a=>{a.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposer(t){let e=bt(),s=this.modeEnterSubmits,i=this.modeSplit??e.splitOnLines,n=null,r=t.createDiv({cls:"stashpad-composer"}),o=r.createDiv({cls:"stashpad-composer-input-wrap"}),a=o.createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(s,i)}});a.value=this.composerDraft;let l=null,c=()=>{l&&(l.remove(),l=null)};n!==null&&n.length>0&&(l=o.createEl("button",{cls:"stashpad-composer-clear"}),(0,O.setIcon)(l,"x"),l.title="Clear restored draft",l.onmousedown=z=>z.preventDefault(),l.onclick=z=>{z.preventDefault(),a.value="",this.composerDraft="",this.saveDraft(""),c(),a.focus()},requestAnimationFrame(()=>{a.focus(),a.setSelectionRange(0,a.value.length)})),this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,O.debounce)(z=>{this.saveDraft(z)},250)),a.addEventListener("input",()=>{this.composerDraft=a.value,this.debouncedSaveDraft(a.value),c()}),a.addEventListener("blur",()=>{this.saveDraft(a.value)});let p=null,u=()=>{p||(p=new O.Scope(this.app.scope),p.register([],"Escape",()=>(a.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),p.register(["Mod"],"z",()=>!0),p.register(["Mod","Shift"],"z",()=>!0),this.app.keymap?.pushScope(p))},d=()=>{if(p){try{this.app.keymap?.popScope(p)}catch{}p=null}};if(a.addEventListener("focus",u),a.addEventListener("blur",d),document.activeElement===a&&u(),O.Platform.isMobile){let z=()=>{this.keyboardTransitionUntil=Date.now()+600};a.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),z()}),a.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),z()})}this.composerInputEl=a,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new re(this.app,a),this.composerAutocomplete.attach();let f=async z=>{let W="";for(let Q of z){let N=await this.importAttachment(Q);if(!N)continue;let P=a.value+W,X=P&&!P.endsWith(` +`).trim(),attachments:e}}renderAttachmentRail(t,e){let s=t.createDiv({cls:"stashpad-rail"});for(let i of e){let n=this.app.metadataCache.getFirstLinkpathDest(i,""),r=(i.split(".").pop()??"").toLowerCase(),a=s.createDiv({cls:"stashpad-att"});if(a.title=i,n&&ln.has(r)){let o=a.createEl("img",{cls:"stashpad-att-img"});o.src=this.app.vault.getResourcePath(n),o.alt=i}else{a.createDiv({cls:"stashpad-att-ext",text:r.toUpperCase()||"?"});let o=(i.split("/").pop()??i).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:o})}a.onclick=o=>{o.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposer(t){let e=St(),s=this.modeEnterSubmits,i=this.modeSplit??e.splitOnLines,n=null,r=t.createDiv({cls:"stashpad-composer"}),a=r.createDiv({cls:"stashpad-composer-input-wrap"}),o=a.createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(s,i)}});o.value=this.composerDraft;let l=null,c=()=>{l&&(l.remove(),l=null)};n!==null&&n.length>0&&(l=a.createEl("button",{cls:"stashpad-composer-clear"}),(0,O.setIcon)(l,"x"),l.title="Clear restored draft",l.onmousedown=z=>z.preventDefault(),l.onclick=z=>{z.preventDefault(),o.value="",this.composerDraft="",this.saveDraft(""),c(),o.focus()},requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(0,o.value.length)})),this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,O.debounce)(z=>{this.saveDraft(z)},250)),o.addEventListener("input",()=>{this.composerDraft=o.value,this.debouncedSaveDraft(o.value),c()}),o.addEventListener("blur",()=>{this.saveDraft(o.value)});let p=null,u=()=>{p||(p=new O.Scope(this.app.scope),p.register([],"Escape",()=>(o.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),p.register(["Mod"],"z",()=>!0),p.register(["Mod","Shift"],"z",()=>!0),this.app.keymap?.pushScope(p))},h=()=>{if(p){try{this.app.keymap?.popScope(p)}catch{}p=null}};if(o.addEventListener("focus",u),o.addEventListener("blur",h),document.activeElement===o&&u(),O.Platform.isMobile){let z=()=>{this.keyboardTransitionUntil=Date.now()+600};o.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),z()}),o.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),z()})}this.composerInputEl=o,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new ce(this.app,o),this.composerAutocomplete.attach();let f=async z=>{let W="";for(let Q of z){let L=await this.importAttachment(Q);if(!L)continue;let P=o.value+W,X=P&&!P.endsWith(` `)?` -`:"";W+=`${X}${N} -`}W&&(a.value=a.value+W,this.composerDraft=a.value,this.saveDraft(a.value),a.focus(),a.setSelectionRange(a.value.length,a.value.length))};a.addEventListener("dragover",z=>{if(!(!z.dataTransfer||!Array.from(z.dataTransfer.types).includes("Files"))){z.preventDefault(),z.stopPropagation();try{z.dataTransfer.dropEffect="copy"}catch{}}}),a.addEventListener("drop",z=>{let W=Array.from(z.dataTransfer?.files??[]);W.length!==0&&(z.preventDefault(),z.stopPropagation(),f(W))}),a.addEventListener("paste",z=>{let W=[],Q=z.clipboardData;if(Q){for(let N of Array.from(Q.files??[]))W.push(N);if(W.length===0){for(let N of Array.from(Q.items??[]))if(N.kind==="file"){let P=N.getAsFile();P&&W.push(P)}}W.length!==0&&(z.preventDefault(),z.stopPropagation(),f(W))}});let m=r.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});m.style.display="none";let v=r.createDiv({cls:"stashpad-composer-btn-rail"}),y=v.createDiv({cls:"stashpad-composer-btn-group"}),b=y.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(b,"list-end"),b.title=i?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",i&&b.addClass("is-active"),b.onmousedown=z=>z.preventDefault(),b.onclick=z=>{z.preventDefault(),this.toggleSplit()};let k=y.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(k,"map-pin"),this.nextDestination&&k.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),k.title="Set destination (Mod+D)",this.nextDestination&&k.addClass("is-active"),k.onmousedown=z=>z.preventDefault(),k.onclick=z=>{z.preventDefault();let W=document.activeElement===a;if(this.openDestinationPicker(),W){let Q=()=>{a.focus()};setTimeout(Q,50),setTimeout(Q,250)}};let C=y.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(C,s?"corner-down-left":"arrow-big-down-dash"),C.title=s?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",C.onmousedown=z=>z.preventDefault(),C.onclick=z=>{z.preventDefault(),this.modeEnterSubmits=!s,this.render(),this.composerInputEl?.focus()};let I=z=>{let W=a.value&&!a.value.endsWith(` +`:"";W+=`${X}${L} +`}W&&(o.value=o.value+W,this.composerDraft=o.value,this.saveDraft(o.value),o.focus(),o.setSelectionRange(o.value.length,o.value.length))};o.addEventListener("dragover",z=>{if(!(!z.dataTransfer||!Array.from(z.dataTransfer.types).includes("Files"))){z.preventDefault(),z.stopPropagation();try{z.dataTransfer.dropEffect="copy"}catch{}}}),o.addEventListener("drop",z=>{let W=Array.from(z.dataTransfer?.files??[]);W.length!==0&&(z.preventDefault(),z.stopPropagation(),f(W))}),o.addEventListener("paste",z=>{let W=[],Q=z.clipboardData;if(Q){for(let L of Array.from(Q.files??[]))W.push(L);if(W.length===0){for(let L of Array.from(Q.items??[]))if(L.kind==="file"){let P=L.getAsFile();P&&W.push(P)}}W.length!==0&&(z.preventDefault(),z.stopPropagation(),f(W))}});let m=r.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});m.style.display="none";let v=r.createDiv({cls:"stashpad-composer-btn-rail"}),y=v.createDiv({cls:"stashpad-composer-btn-group"}),b=y.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(b,"list-end"),b.title=i?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",i&&b.addClass("is-active"),b.onmousedown=z=>z.preventDefault(),b.onclick=z=>{z.preventDefault(),this.toggleSplit()};let k=y.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(k,"map-pin"),this.nextDestination&&k.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),k.title="Set destination (Mod+D)",this.nextDestination&&k.addClass("is-active"),k.onmousedown=z=>z.preventDefault(),k.onclick=z=>{z.preventDefault();let W=document.activeElement===o;if(this.openDestinationPicker(),W){let Q=()=>{o.focus()};setTimeout(Q,50),setTimeout(Q,250)}};let T=y.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(T,s?"corner-down-left":"arrow-big-down-dash"),T.title=s?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",T.onmousedown=z=>z.preventDefault(),T.onclick=z=>{z.preventDefault(),this.modeEnterSubmits=!s,this.render(),this.composerInputEl?.focus()};let I=z=>{let W=o.value&&!o.value.endsWith(` `)?` -`:"";a.value+=`${W}${z} -`,this.composerDraft=a.value},E=y.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(E,"paperclip"),E.title="Attach files",E.onmousedown=z=>z.preventDefault(),E.onclick=z=>{z.preventDefault();let W=document.activeElement===a;if(m.click(),W){let Q=()=>{a.focus()};setTimeout(Q,100),setTimeout(Q,500)}},m.addEventListener("change",async()=>{let z=Array.from(m.files??[]);m.value="";for(let W of z){let Q=await this.importAttachment(W);Q&&I(Q)}a.focus()});let D=v.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,O.setIcon)(D,"chevron-left"),D.title="Show more composer options",v.insertBefore(D,y);let H=z=>{v.toggleClass("is-expanded",z),D.title=z?"Hide options":"Show more composer options",(0,O.setIcon)(D,z?"chevron-right":"chevron-left")};D.onmousedown=z=>z.preventDefault(),D.onclick=z=>{z.preventDefault(),H(!v.hasClass("is-expanded"))},H(!1);let T=()=>r.clientWidth<700,A=()=>{let z=T();r.toggleClass("is-narrow",z),H(!z)};A(),requestAnimationFrame(A);let S=new ResizeObserver(A);S.observe(r),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=S;let _=v.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});_.title="Send (Enter)",(0,O.setIcon)(_,"arrow-up");let J=async()=>{let z=a.value.trim();if(!z)return;a.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(z)}catch{}let W=this.modeSplit??bt().splitOnLines,Q=this.nextDestination,N=this.nextDestinationFolder,P=!!N&&N!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!P,this.scrollToBottomOnNextRender=!P;let X=P?{targetFolder:N}:void 0;if(W)for(let q of z.split(/\r?\n/)){let Y=q.trim();Y&&await this.createNoteUnder(Y,Q,X)}else await this.createNoteUnder(z,Q,X);bt().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,P&&this.composerInputEl?.focus())};_.onclick=()=>void J(),a.addEventListener("keydown",z=>{let W=this.modeEnterSubmits;if(z.key==="Escape"){z.preventDefault(),z.stopPropagation(),a.blur(),this.viewRoot.focus({preventScroll:!0});return}if(z.key==="ArrowUp"&&a.selectionStart===0&&a.selectionEnd===0){z.preventDefault(),a.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0&&(this.cursorIdx=this.currentChildren.length-1,this.selectCursor(!1));return}z.key==="Enter"&&!z.isComposing&&(W?!z.shiftKey:z.shiftKey)&&(z.preventDefault(),z.stopPropagation(),z.stopImmediatePropagation(),J())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(s,i))}composerPlaceholder(t,e){return O.Platform.isMobile?e?"New notes (split on newlines)":"New note":`Type a note. ${t?"Enter":"Shift+Enter"} = send, ${t?"Shift+Enter":"Enter"} = newline${e?" (each line \u2192 a note)":""}\u2026`}composerHelperText(t,e){let s=t?"Enter":"Shift+Enter",i=t?"Shift+Enter":"Enter",n=bt().bindings,r=p=>{let u=n[p];return u.primary&&u.secondary?u.preferRight?u.secondary:u.primary:u.primary||u.secondary},o=zs(r("toggleSplit")),a=zs(r("pickDestination")),l=zs(r("search")),c=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${s} sends \xB7 ${i} newline \xB7 ${o} split: ${e?"ON":"off"} \xB7 ${a} destination \xB7 ${l} search${c}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===R)return"Home";let t=this.tree.get(this.nextDestination);return t?this.titleForNode(t).trim():"?"}renderMobileNav(t){let e=t.createDiv({cls:"stashpad-mobile-nav"});e.createEl("button",{text:"Home"}).onclick=()=>this.navigateTo(R),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let s=t.target,i=s?.closest?.(".tag");if(i){t.preventDefault(),t.stopPropagation();let o=(i.getAttribute("href")||i.textContent||"").replace(/^#/,"").trim();if(o){let a=this.app.internalPlugins?.plugins?.["global-search"],l=a?.instance?.openGlobalSearch?.bind(a.instance);l&&l(`tag:#${o}`)}return}let n=s?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let r=n.getAttribute("data-href")||n.getAttribute("href");if(r){let o=e.file?.path||"";this.app.workspace.openLinkText(r,o,!0)}}}handleRowClick(t,e,s){let i=t.target,n=i?.closest?.(".tag");if(n){t.preventDefault(),t.stopPropagation();let l=(n.getAttribute("href")||n.textContent||"").replace(/^#/,"").trim();if(l){let c=this.app.internalPlugins?.plugins?.["global-search"],p=c?.instance?.openGlobalSearch?.bind(c.instance);p&&p(`tag:#${l}`)}return}let r=i?.closest?.(".internal-link");if(r){t.preventDefault(),t.stopPropagation();let a=r.getAttribute("data-href")||r.getAttribute("href");if(a){let l=s.file?.path||"";this.app.workspace.openLinkText(a,l,!0)}return}if(i?.tagName==="A"&&i.href)return;if(t.stopPropagation(),this.inListPicker){this.inListPicker.activeIdx=e,this.commitInListPicker();return}let o=this.selection.size===0;if(t.shiftKey&&this.lastSelected){this.cursorIdx=e;let a=this.currentChildren.findIndex(l=>l.id===this.lastSelected);if(o&&(this.firstSelectedId=this.lastSelected),a!==-1){let[l,c]=a<e?[a,e]:[e,a];for(let p=l;p<=c;p++)this.selection.add(this.currentChildren[p].id)}else this.selection.add(s.id)}else if(t.metaKey||t.ctrlKey)if(this.selection.has(s.id))if(this.selection.delete(s.id),this.firstSelectedId===s.id&&(this.firstSelectedId=null),this.lastSelected===s.id&&(this.lastSelected=this.selection.size>0?[...this.selection][this.selection.size-1]:null),this.selection.size===0)this.cursorIdx=-1;else{let a=this.lastSelected??[...this.selection][this.selection.size-1],l=a?this.currentChildren.findIndex(c=>c.id===a):-1;l>=0&&(this.cursorIdx=l)}else this.cursorIdx=e,o&&(this.firstSelectedId=s.id),this.selection.add(s.id);else this.mobileSelectMode?(this.cursorIdx=e,this.selection.has(s.id)?(this.selection.delete(s.id),this.firstSelectedId===s.id&&(this.firstSelectedId=null)):this.selection.add(s.id)):(this.cursorIdx=e,this.selection.clear(),this.selection.add(s.id),this.firstSelectedId=s.id,this.lastSelected=s.id);this.selection.size===0&&(this.firstSelectedId=null),this.selection.has(s.id)&&(this.lastSelected=s.id),this.viewRoot.focus({preventScroll:!0}),this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}revealCursorRow(){let t=()=>{let e=this.listEl?.querySelector(`[data-idx="${this.cursorIdx}"]`);if(!e||!this.listEl)return;let s=this.listEl,i=s.getBoundingClientRect(),n=e.getBoundingClientRect(),r=4;n.top<i.top+r?s.scrollTop+=n.top-i.top-r:n.bottom>i.bottom-r&&(s.scrollTop+=n.bottom-i.bottom+r)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}selectCursor(t){let e=this.currentChildren[this.cursorIdx];if(e){if(!t)this.selection.clear(),this.selection.add(e.id),this.firstSelectedId=e.id,this.lastSelected=e.id;else{let s=this.firstSelectedId??e.id,i=this.currentChildren.findIndex(n=>n.id===s);if(i===-1)this.selection.add(e.id),this.firstSelectedId=e.id;else{let[n,r]=i<this.cursorIdx?[i,this.cursorIdx]:[this.cursorIdx,i];this.selection.clear();for(let o=n;o<=r;o++)this.selection.add(this.currentChildren[o].id);this.firstSelectedId=s}this.lastSelected=e.id}this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}}repaintSelectionClasses(){if(!this.listEl)return;let t=!!this.plugin.settings.autoExpandCursorRow,e=this.inListPicker?.activeIdx??-1;this.listEl.querySelectorAll(".stashpad-note").forEach(i=>{let n=Number(i.dataset.idx),r=i.dataset.id??"",o=n===this.cursorIdx;i.classList.toggle("is-cursor",o),i.classList.toggle("is-selected",this.selection.has(r)),i.classList.toggle("is-cursor-expanded",t&&o),i.classList.toggle("is-pick-target",n===e)})}revealRowAt(t){if(!this.listEl)return;let e=this.listEl.querySelector(`.stashpad-note[data-idx="${t}"]`);if(!e)return;let s=e.getBoundingClientRect(),i=this.listEl.getBoundingClientRect();(s.top<i.top||s.bottom>i.bottom)&&e.scrollIntoView({block:"nearest",behavior:"auto"})}getActionTargets(){if(this.selection.size>0)return[...this.selection].map(e=>this.tree.get(e)).filter(e=>!!e&&!!e.file);let t=this.currentChildren[this.cursorIdx];return t?[t]:[]}toggleSplit(){let t=this.modeSplit??bt().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(){new Ot(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:async t=>{if(t.crossFolder){let e=t.id.replace(/^cross:/,"");this.nextDestination=e,this.nextDestinationFolder=t.crossFolder;let s=t.crossFolder.split("/").pop()||t.crossFolder,i=e===R?"Home":(t.crossFile?.basename??"note").replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ");this.nextDestinationLabel=`${s} \u25B8 ${i}`,this.render(),this.composerInputEl?.focus();return}this.nextDestination=t.id,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus()},onCreate:async t=>{let e=await this.createNoteUnder(t,this.focusId);e&&(this.nextDestination=e,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus())},crossFolderNotes:()=>this.collectCrossFolderDestinations()}).open()}collectCrossFolderDestinations(){let t=this.collectCrossFolderNotes(),e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder),s=new Map;for(let n of this.app.vault.getMarkdownFiles()){let r=n.parent?.path?.replace(/\/+$/,"")??"";if(!e.includes(r))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===R&&s.set(r,n)}return[...e.map(n=>({file:s.get(n),folder:n,id:R,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...t]}openSearchInParentModal(){let t=this.focusId,e=i=>{if(i===t)return!0;let n=new Set,r=this.tree.get(i);for(;r&&r.id!==R&&!n.has(r.id);){if(n.add(r.id),r.parent===t||r.id===t)return!0;if(!r.parent)return!1;r=this.tree.get(r.parent)}return t===R},s=new Proxy(this.tree,{get:(i,n)=>n==="getRoot"?()=>i.get(t)??i.getRoot():n==="getChildren"?r=>i.getChildren(r):i[n]});new Ot(this.app,s,i=>this.titleForNode(i),{mode:"search",placeholder:`Search in "${this.titleForNode(this.tree.get(t)??this.tree.getRoot()).trim()}"\u2026`,allowCreate:!1,onPick:i=>{i.node&&e(i.node.id)?this.navigateTo(i.node.id):i.node&&this.navigateTo(i.node.id)}}).open()}openSearchModal(){if(this.openSearchInstance){let s=this.openSearchInstance.inputEl;s&&(s.focus(),s.select());return}let t=new Ot(this.app,this.tree,s=>this.titleForNode(s),{mode:"search",placeholder:"Search Stashpad notes\u2026",allowCreate:!0,onCreate:async s=>{let i=s.trim();i&&new Ot(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",placeholder:`Create "${i}" under which note?`,allowCreate:!1,crossFolderNotes:()=>this.collectCrossFolderDestinations(),folderResults:()=>this.plugin.discoverStashpadFolders().filter(n=>n!==this.noteFolder),localFolder:this.noteFolder,onPick:async n=>{let r=n.crossFolder?n.id.replace(/^cross:/,""):n.node?.id,o=n.crossFolder??this.noteFolder;if(!r)return;let a=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",l=this.app.workspace,c=l.getLeaf("tab");await c.setViewState({type:mt,active:!0,state:{focusId:r,folderOverride:o===a?null:o}}),l.revealLeaf(c);let p=c.view;if(p&&typeof p.createNoteUnder=="function"){let u=await p.createNoteUnder(i,r);u&&typeof p.navigateTo=="function"&&p.navigateTo(u)}}}).open()},onPick:s=>{if(s.kind==="folder-open"&&s.folder){this.openFolderInNewTab(s.folder);return}if(s.crossFolder&&s.crossFile){let i=s.id.replace(/^cross:/,"");this.switchToFolderAndFocus(s.crossFolder,i);return}s.node&&this.navigateTo(s.node.id)},crossFolderNotes:()=>this.collectCrossFolderDestinations(),folderResults:()=>this.plugin.discoverStashpadFolders().filter(s=>s!==this.noteFolder),showFilterChips:!0,localFolder:this.noteFolder});this.openSearchInstance=t;let e=t.onClose.bind(t);t.onClose=()=>{e(),this.openSearchInstance===t&&(this.openSearchInstance=null)},t.open()}collectCrossFolderNotes(){let t=[],e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder);if(!e.length)return t;let s=new Set(e),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let r=n.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(r))continue;let o=i.get(r);o||(o=[],i.set(r,o)),o.push(n)}for(let n of e){let r=i.get(n)??[],o=new Map;for(let a of r){let l=this.app.metadataCache.getFileCache(a)?.frontmatter;typeof l?.id=="string"&&o.set(l.id,a)}for(let a of r){let l=this.app.metadataCache.getFileCache(a)?.frontmatter,c=typeof l?.id=="string"?l.id:"";if(!c||c===R)continue;let p=a.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),u,d=l?.parent??null;if(d&&d!==R){let f=o.get(d);f&&(u=f.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}t.push({file:a,folder:n,id:c,title:p,body:"",parentBlurb:u,parentId:d??null})}}return t}async switchToFolderAndFocus(t,e){await this.setFolderOverride(t),this.tree.get(e)&&this.navigateTo(e)}async cmdOutdent(){let t=this.getActionTargets();if(!t.length)return;let e=[],s=[];for(let i of t){let n=i.parent?this.tree.get(i.parent):null;if(!n||n.id===R){s.push(i.id);continue}let r=n.parent??R;await this.changeParent(i,r),e.push(i)}if(e.length===0){new O.Notice(s.length?"Already at the top level.":"Nothing to outdent.");return}if(this.render(),s.length){let i=e.map(n=>this.tree.get(n)).filter(n=>!!n);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Outdented",nodes:i,suffix:s.length?`(${s.length} already at root)`:void 0}),kind:"success",category:"move",affectedIds:e,folder:this.noteFolder})}if(this.plugin.settings.autoNavOnMoveOut&&e.length>0){let i=e[0].parent;i!=null&&e.every(r=>r.parent===i)&&i!==this.focusId&&this.navigateTo(i)}}cmdSetColor(){let t=this.getActionTargets();if(!t.length)return;let e=new Set(t.map(n=>this.colorForNode(n)??"")),s=e.size===1&&Array.from(e)[0]||null,i=this.plugin.settings.customPalette??[];new Zt(this.app,s,i,async(n,r)=>{let o=[];for(let p of t)if(p.file){o.push({id:p.id,path:p.file.path,was:this.colorForNode(p)??null});try{await this.app.fileManager.processFrontMatter(p.file,u=>{n?u.color=n:delete u.color})}catch(u){new O.Notice(`Couldn't set color for ${p.id}: ${u.message}`)}}if(r.addToPalette&&typeof n=="string"){let p=[...this.plugin.settings.customPalette??[]],u=n.toLowerCase();p.some(d=>d.toLowerCase()===u)||(p.push(n),this.plugin.settings.customPalette=p,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:R,payload:{color:n}}))}this.render();let a=this.noteFolder,l=n,c=async p=>{for(let u of p){let d=this.app.vault.getAbstractFileByPath(u.path);if(d)try{await this.app.fileManager.processFrontMatter(d,f=>{u.col?f.color=u.col:delete f.color})}catch{}}this.tree.rebuild(a),this.render()};this.plugin.getUndoStack(a).push({label:o.length===1?"Color change":`Color change (${o.length})`,undo:()=>c(o.map(p=>({path:p.path,col:p.was}))),redo:()=>c(o.map(p=>({path:p.path,col:l})))})},async n=>{let r=(this.plugin.settings.customPalette??[]).filter(o=>o.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=r,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:R,payload:{color:n}}),r}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new Ot(this.app,this.tree,e=>this.titleForNode(e),{mode:"pick",placeholder:"Move to which note?",allowCreate:!0,onPick:async e=>{if(e.crossFolder){let i=e.id.replace(/^cross:/,"");await this.moveAcrossFolders(t,e.crossFolder,i),this.selection.clear(),this.render();return}let s=e.id;for(let i of t)await this.changeParent(i,s);this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&s!==this.focusId&&this.navigateTo(s)},onCreate:async e=>{let s=await this.createNoteUnder(e,this.focusId);if(s){for(let i of t)await this.changeParent(i,s);this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&this.navigateTo(s)}},crossFolderNotes:()=>this.collectCrossFolderDestinations(),showFilterChips:!0}).open()}async moveAcrossFolders(t,e,s){if(!t.length)return;let i=(e||"").replace(/\/+$/,"");if(!i){new O.Notice("Target folder is empty");return}let n=[],r=new Set;for(let p of this.app.vault.getMarkdownFiles())(p.parent?.path?.replace(/\/+$/,"")??"")===i&&r.add(p.path);let o=(p,u)=>{if(!p.file)return;let d=p.file,f=`${i}/${d.name}`;if(r.has(f)){let m=d.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),v=m?m[1]:d.basename,y=m?m[2]:"";for(let b=1;b<1e3;b++){let k=`${v}-${b}${y}.md`,C=`${i}/${k}`;if(!r.has(C)){f=C;break}}}r.add(f),n.push({id:p.id,file:d,oldPath:d.path,newPath:f,oldParent:p.parent,isRoot:u});for(let m of this.tree.getChildren(p.id))o(m,!1)};for(let p of t)o(p,!0);if(!n.length)return;await this.ensureFolder(i);for(let p of n)try{await this.app.fileManager.renameFile(p.file,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(p.file,u=>{u.parent=s}),await this.log.append({type:"parent_change",id:p.id,payload:{from:p.oldParent,to:p.isRoot?s:p.oldParent,crossFolder:{from:this.noteFolder,to:i}}})}catch(u){new O.Notice(`Move failed for ${p.id}: ${u.message}`)}this.tree.rebuild(this.noteFolder);let a=t.map(p=>this.tree.get(p.id)).filter(p=>!!p),l=a.length>0?this.titleList(a):`${t.length} note${t.length===1?"":"s"}`,c=s===R?"Open home":"Open parent";this.plugin.notifications.show({message:`Moved ${l} \u2192 \`${i}\``,kind:"success",category:"move",affectedIds:t.map(p=>p.id),folder:this.noteFolder,actions:[{label:c,onClick:()=>{this.switchToFolderAndFocus(i,s)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let p of n){let u=this.app.vault.getAbstractFileByPath(p.newPath);if(u)try{await this.app.fileManager.renameFile(u,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(u,d=>{d.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let u=this.app.vault.getAbstractFileByPath(p.oldPath);if(u)try{await this.app.fileManager.renameFile(u,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(u,d=>{d.parent=s})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}cmdInListPicker(){if(this.currentChildren.length===0)return;let t=this.cursorIdx>0?this.cursorIdx-1:0;this.inListPicker={activeIdx:t},new O.Notice("Arrows to pick parent, Enter confirms, Esc cancels.");let e=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let s=this.listEl;s.scrollTop=e,requestAnimationFrame(()=>{s.scrollTop=e}),setTimeout(()=>{s.scrollTop=e},60)}}async commitInListPicker(){if(!this.inListPicker)return;let t=this.currentChildren[this.inListPicker.activeIdx];if(this.inListPicker=null,!t){this.render();return}let e=this.getActionTargets().filter(n=>n.id!==t.id);for(let n of e)await this.changeParent(n,t.id);if(this.plugin.settings.autoNavOnMoveIn){this.navigateTo(t.id);return}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"});let s=this.selectionGuardKey,i=()=>{if(this.selectionGuardKey!==s||this.selection.has(t.id))return;let n=this.currentChildren.findIndex(r=>r.id===t.id);n<0||(this.selection.add(t.id),this.cursorIdx=n,this.render({kind:"follow-cursor"}))};setTimeout(i,120),setTimeout(i,400)}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new O.Notice("Select 2+ notes to merge.");return}t.sort((m,v)=>(m.created||"").localeCompare(v.created||""));let e=t[0];if(!e.file)return;let s=e.file.path,i=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),r=[],o=[];for(let m of t){if(!m.file)continue;let v=await this.app.vault.cachedRead(m.file);o.push(this.stripFrontmatter(v).trim())}let a=o.map(m=>m.trim()).filter(Boolean).join(` +`:"";o.value+=`${W}${z} +`,this.composerDraft=o.value},E=y.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(E,"paperclip"),E.title="Attach files",E.onmousedown=z=>z.preventDefault(),E.onclick=z=>{z.preventDefault();let W=document.activeElement===o;if(m.click(),W){let Q=()=>{o.focus()};setTimeout(Q,100),setTimeout(Q,500)}},m.addEventListener("change",async()=>{let z=Array.from(m.files??[]);m.value="";for(let W of z){let Q=await this.importAttachment(W);Q&&I(Q)}o.focus()});let D=v.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,O.setIcon)(D,"chevron-left"),D.title="Show more composer options",v.insertBefore(D,y);let H=z=>{v.toggleClass("is-expanded",z),D.title=z?"Hide options":"Show more composer options",(0,O.setIcon)(D,z?"chevron-right":"chevron-left")};D.onmousedown=z=>z.preventDefault(),D.onclick=z=>{z.preventDefault(),H(!v.hasClass("is-expanded"))},H(!1);let C=()=>r.clientWidth<700,A=()=>{let z=C();r.toggleClass("is-narrow",z),H(!z)};A(),requestAnimationFrame(A);let S=new ResizeObserver(A);S.observe(r),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=S;let _=v.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});_.title="Send (Enter)",(0,O.setIcon)(_,"arrow-up");let J=async()=>{let z=o.value.trim();if(!z)return;o.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(z)}catch{}let W=this.modeSplit??St().splitOnLines,Q=this.nextDestination,L=this.nextDestinationFolder,P=!!L&&L!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!P,this.scrollToBottomOnNextRender=!P;let X=P?{targetFolder:L}:void 0;if(W)for(let q of z.split(/\r?\n/)){let Y=q.trim();Y&&await this.createNoteUnder(Y,Q,X)}else await this.createNoteUnder(z,Q,X);St().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,P&&this.composerInputEl?.focus())};_.onclick=()=>void J(),o.addEventListener("keydown",z=>{let W=this.modeEnterSubmits;if(z.key==="Escape"){z.preventDefault(),z.stopPropagation(),o.blur(),this.viewRoot.focus({preventScroll:!0});return}if(z.key==="ArrowUp"&&o.selectionStart===0&&o.selectionEnd===0){if(z.preventDefault(),o.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let Q=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,L=Q?this.currentChildren.findIndex(P=>P.id===Q):-1;this.cursorIdx=L>=0?L:this.currentChildren.length-1,this.selectCursor(!1)}return}z.key==="Enter"&&!z.isComposing&&(W?!z.shiftKey:z.shiftKey)&&(z.preventDefault(),z.stopPropagation(),z.stopImmediatePropagation(),J())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(s,i))}composerPlaceholder(t,e){return O.Platform.isMobile?e?"New notes (split on newlines)":"New note":`Type a note. ${t?"Enter":"Shift+Enter"} = send, ${t?"Shift+Enter":"Enter"} = newline${e?" (each line \u2192 a note)":""}\u2026`}composerHelperText(t,e){let s=t?"Enter":"Shift+Enter",i=t?"Shift+Enter":"Enter",n=St().bindings,r=p=>{let u=n[p];return u.primary&&u.secondary?u.preferRight?u.secondary:u.primary:u.primary||u.secondary},a=Ys(r("toggleSplit")),o=Ys(r("pickDestination")),l=Ys(r("search")),c=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${s} sends \xB7 ${i} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${o} destination \xB7 ${l} search${c}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===R)return"Home";let t=this.tree.get(this.nextDestination);return t?this.titleForNode(t).trim():"?"}renderMobileNav(t){let e=t.createDiv({cls:"stashpad-mobile-nav"});e.createEl("button",{text:"Home"}).onclick=()=>this.navigateTo(R),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let s=t.target,i=s?.closest?.(".tag");if(i){t.preventDefault(),t.stopPropagation();let a=(i.getAttribute("href")||i.textContent||"").replace(/^#/,"").trim();if(a){let o=this.app.internalPlugins?.plugins?.["global-search"],l=o?.instance?.openGlobalSearch?.bind(o.instance);l&&l(`tag:#${a}`)}return}let n=s?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let r=n.getAttribute("data-href")||n.getAttribute("href");if(r){let a=e.file?.path||"";this.app.workspace.openLinkText(r,a,!0)}}}handleRowClick(t,e,s){let i=t.target,n=i?.closest?.(".tag");if(n){t.preventDefault(),t.stopPropagation();let l=(n.getAttribute("href")||n.textContent||"").replace(/^#/,"").trim();if(l){let c=this.app.internalPlugins?.plugins?.["global-search"],p=c?.instance?.openGlobalSearch?.bind(c.instance);p&&p(`tag:#${l}`)}return}let r=i?.closest?.(".internal-link");if(r){t.preventDefault(),t.stopPropagation();let o=r.getAttribute("data-href")||r.getAttribute("href");if(o){let l=s.file?.path||"";this.app.workspace.openLinkText(o,l,!0)}return}if(i?.tagName==="A"&&i.href)return;if(t.stopPropagation(),this.inListPicker){this.inListPicker.activeIdx=e,this.commitInListPicker();return}let a=this.selection.size===0;if(t.shiftKey&&this.lastSelected){this.cursorIdx=e;let o=this.currentChildren.findIndex(l=>l.id===this.lastSelected);if(a&&(this.firstSelectedId=this.lastSelected),o!==-1){let[l,c]=o<e?[o,e]:[e,o];for(let p=l;p<=c;p++)this.selection.add(this.currentChildren[p].id)}else this.selection.add(s.id)}else if(t.metaKey||t.ctrlKey)if(this.selection.has(s.id))if(this.selection.delete(s.id),this.firstSelectedId===s.id&&(this.firstSelectedId=null),this.lastSelected===s.id&&(this.lastSelected=this.selection.size>0?[...this.selection][this.selection.size-1]:null),this.selection.size===0)this.cursorIdx=-1;else{let o=this.lastSelected??[...this.selection][this.selection.size-1],l=o?this.currentChildren.findIndex(c=>c.id===o):-1;l>=0&&(this.cursorIdx=l)}else this.cursorIdx=e,a&&(this.firstSelectedId=s.id),this.selection.add(s.id);else this.mobileSelectMode?(this.cursorIdx=e,this.selection.has(s.id)?(this.selection.delete(s.id),this.firstSelectedId===s.id&&(this.firstSelectedId=null)):this.selection.add(s.id)):(this.cursorIdx=e,this.selection.clear(),this.selection.add(s.id),this.firstSelectedId=s.id,this.lastSelected=s.id);this.selection.size===0&&(this.firstSelectedId=null),this.selection.has(s.id)&&(this.lastSelected=s.id),this.viewRoot.focus({preventScroll:!0}),this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}revealCursorRow(){let t=()=>{let e=this.listEl?.querySelector(`[data-idx="${this.cursorIdx}"]`);if(!e||!this.listEl)return;let s=this.listEl,i=s.getBoundingClientRect(),n=e.getBoundingClientRect(),r=4;n.top<i.top+r?s.scrollTop+=n.top-i.top-r:n.bottom>i.bottom-r&&(s.scrollTop+=n.bottom-i.bottom+r)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}jumpToTop(){this.currentChildren.length!==0&&(this.cursorIdx=0,this.selectCursor(!1))}jumpToBottom(){this.currentChildren.length!==0&&(this.cursorIdx=this.currentChildren.length-1,this.selectCursor(!1))}selectCursor(t){let e=this.currentChildren[this.cursorIdx];if(e){if(!t)this.selection.clear(),this.selection.add(e.id),this.firstSelectedId=e.id,this.lastSelected=e.id;else{let s=this.firstSelectedId??e.id,i=this.currentChildren.findIndex(n=>n.id===s);if(i===-1)this.selection.add(e.id),this.firstSelectedId=e.id;else{let[n,r]=i<this.cursorIdx?[i,this.cursorIdx]:[this.cursorIdx,i];this.selection.clear();for(let a=n;a<=r;a++)this.selection.add(this.currentChildren[a].id);this.firstSelectedId=s}this.lastSelected=e.id}this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}}repaintSelectionClasses(){if(!this.listEl)return;let t=!!this.plugin.settings.autoExpandCursorRow,e=this.inListPicker?.activeIdx??-1;this.listEl.querySelectorAll(".stashpad-note").forEach(i=>{let n=Number(i.dataset.idx),r=i.dataset.id??"",a=n===this.cursorIdx;i.classList.toggle("is-cursor",a),i.classList.toggle("is-selected",this.selection.has(r)),i.classList.toggle("is-cursor-expanded",t&&a),i.classList.toggle("is-pick-target",n===e)})}revealRowAt(t){if(!this.listEl)return;let e=this.listEl.querySelector(`.stashpad-note[data-idx="${t}"]`);if(!e)return;let s=e.getBoundingClientRect(),i=this.listEl.getBoundingClientRect();(s.top<i.top||s.bottom>i.bottom)&&e.scrollIntoView({block:"nearest",behavior:"auto"})}getActionTargets(){if(this.selection.size>0)return[...this.selection].map(e=>this.tree.get(e)).filter(e=>!!e&&!!e.file);let t=this.currentChildren[this.cursorIdx];return t?[t]:[]}toggleSplit(){let t=this.modeSplit??St().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(){new $t(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:async t=>{if(t.crossFolder){let e=t.id.replace(/^cross:/,"");this.nextDestination=e,this.nextDestinationFolder=t.crossFolder;let s=t.crossFolder.split("/").pop()||t.crossFolder,i=e===R?"Home":(t.crossFile?.basename??"note").replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ");this.nextDestinationLabel=`${s} \u25B8 ${i}`,this.render(),this.composerInputEl?.focus();return}this.nextDestination=t.id,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus()},onCreate:async t=>{let e=await this.createNoteUnder(t,this.focusId);e&&(this.nextDestination=e,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus())},crossFolderNotes:()=>this.collectCrossFolderDestinations()}).open()}collectCrossFolderDestinations(){let t=this.collectCrossFolderNotes(),e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder),s=new Map;for(let n of this.app.vault.getMarkdownFiles()){let r=n.parent?.path?.replace(/\/+$/,"")??"";if(!e.includes(r))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===R&&s.set(r,n)}return[...e.map(n=>({file:s.get(n),folder:n,id:R,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...t]}openSearchInParentModal(){let t=this.focusId,e=i=>{if(i===t)return!0;let n=new Set,r=this.tree.get(i);for(;r&&r.id!==R&&!n.has(r.id);){if(n.add(r.id),r.parent===t||r.id===t)return!0;if(!r.parent)return!1;r=this.tree.get(r.parent)}return t===R},s=new Proxy(this.tree,{get:(i,n)=>n==="getRoot"?()=>i.get(t)??i.getRoot():n==="getChildren"?r=>i.getChildren(r):i[n]});new $t(this.app,s,i=>this.titleForNode(i),{mode:"search",placeholder:`Search in "${this.titleForNode(this.tree.get(t)??this.tree.getRoot()).trim()}"\u2026`,allowCreate:!1,onPick:i=>{i.node&&e(i.node.id)?this.navigateTo(i.node.id):i.node&&this.navigateTo(i.node.id)}}).open()}openSearchModal(){if(this.openSearchInstance){let s=this.openSearchInstance.inputEl;s&&(s.focus(),s.select());return}let t=new $t(this.app,this.tree,s=>this.titleForNode(s),{mode:"search",placeholder:"Search Stashpad notes\u2026",allowCreate:!0,onCreate:async s=>{let i=s.trim();i&&new $t(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",placeholder:`Create "${i}" under which note?`,allowCreate:!1,crossFolderNotes:()=>this.collectCrossFolderDestinations(),folderResults:()=>this.plugin.discoverStashpadFolders().filter(n=>n!==this.noteFolder),localFolder:this.noteFolder,onPick:async n=>{let r=n.crossFolder?n.id.replace(/^cross:/,""):n.node?.id,a=n.crossFolder??this.noteFolder;if(!r)return;let o=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",l=this.app.workspace,c=l.getLeaf("tab");await c.setViewState({type:mt,active:!0,state:{focusId:r,folderOverride:a===o?null:a}}),l.revealLeaf(c);let p=c.view;if(p&&typeof p.createNoteUnder=="function"){let u=await p.createNoteUnder(i,r);u&&typeof p.navigateTo=="function"&&p.navigateTo(u)}}}).open()},onPick:s=>{if(s.kind==="folder-open"&&s.folder){this.openFolderInNewTab(s.folder);return}if(s.crossFolder&&s.crossFile){let i=s.id.replace(/^cross:/,"");this.switchToFolderAndFocus(s.crossFolder,i);return}s.node&&this.navigateTo(s.node.id)},crossFolderNotes:()=>this.collectCrossFolderDestinations(),folderResults:()=>this.plugin.discoverStashpadFolders().filter(s=>s!==this.noteFolder),showFilterChips:!0,localFolder:this.noteFolder});this.openSearchInstance=t;let e=t.onClose.bind(t);t.onClose=()=>{e(),this.openSearchInstance===t&&(this.openSearchInstance=null)},t.open()}collectCrossFolderNotes(){let t=[],e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder);if(!e.length)return t;let s=new Set(e),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let r=n.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(r))continue;let a=i.get(r);a||(a=[],i.set(r,a)),a.push(n)}for(let n of e){let r=i.get(n)??[],a=new Map;for(let o of r){let l=this.app.metadataCache.getFileCache(o)?.frontmatter;typeof l?.id=="string"&&a.set(l.id,o)}for(let o of r){let l=this.app.metadataCache.getFileCache(o)?.frontmatter,c=typeof l?.id=="string"?l.id:"";if(!c||c===R)continue;let p=o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),u,h=l?.parent??null;if(h&&h!==R){let f=a.get(h);f&&(u=f.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}t.push({file:o,folder:n,id:c,title:p,body:"",parentBlurb:u,parentId:h??null})}}return t}async switchToFolderAndFocus(t,e){await this.setFolderOverride(t),this.tree.get(e)&&this.navigateTo(e)}async cmdOutdent(){let t=this.getActionTargets();if(!t.length)return;let e=[],s=[];for(let i of t){let n=i.parent?this.tree.get(i.parent):null;if(!n||n.id===R){s.push(i.id);continue}let r=n.parent??R;await this.changeParent(i,r),e.push(i)}if(e.length===0){new O.Notice(s.length?"Already at the top level.":"Nothing to outdent.");return}if(this.render(),s.length){let i=e.map(n=>this.tree.get(n)).filter(n=>!!n);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Outdented",nodes:i,suffix:s.length?`(${s.length} already at root)`:void 0}),kind:"success",category:"move",affectedIds:e,folder:this.noteFolder})}if(this.plugin.settings.autoNavOnMoveOut&&e.length>0){let i=e[0].parent;i!=null&&e.every(r=>r.parent===i)&&i!==this.focusId&&this.navigateTo(i)}}cmdSetColor(){let t=this.getActionTargets();if(!t.length)return;let e=new Set(t.map(n=>this.colorForNode(n)??"")),s=e.size===1&&Array.from(e)[0]||null,i=this.plugin.settings.customPalette??[];new Jt(this.app,s,i,async(n,r)=>{let a=[];for(let p of t)if(p.file){a.push({id:p.id,path:p.file.path,was:this.colorForNode(p)??null});try{await this.app.fileManager.processFrontMatter(p.file,u=>{n?u.color=n:delete u.color})}catch(u){new O.Notice(`Couldn't set color for ${p.id}: ${u.message}`)}}if(r.addToPalette&&typeof n=="string"){let p=[...this.plugin.settings.customPalette??[]],u=n.toLowerCase();p.some(h=>h.toLowerCase()===u)||(p.push(n),this.plugin.settings.customPalette=p,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:R,payload:{color:n}}))}this.render();let o=this.noteFolder,l=n,c=async p=>{for(let u of p){let h=this.app.vault.getAbstractFileByPath(u.path);if(h)try{await this.app.fileManager.processFrontMatter(h,f=>{u.col?f.color=u.col:delete f.color})}catch{}}this.tree.rebuild(o),this.render()};this.plugin.getUndoStack(o).push({label:a.length===1?"Color change":`Color change (${a.length})`,undo:()=>c(a.map(p=>({path:p.path,col:p.was}))),redo:()=>c(a.map(p=>({path:p.path,col:l})))})},async n=>{let r=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=r,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:R,payload:{color:n}}),r}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new $t(this.app,this.tree,e=>this.titleForNode(e),{mode:"pick",placeholder:"Move to which note?",allowCreate:!0,onPick:async e=>{if(e.crossFolder){let i=e.id.replace(/^cross:/,"");await this.moveAcrossFolders(t,e.crossFolder,i),this.selection.clear(),this.render();return}let s=e.id;for(let i of t)await this.changeParent(i,s);this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&s!==this.focusId&&this.navigateTo(s)},onCreate:async e=>{let s=await this.createNoteUnder(e,this.focusId);if(s){for(let i of t)await this.changeParent(i,s);this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&this.navigateTo(s)}},crossFolderNotes:()=>this.collectCrossFolderDestinations(),showFilterChips:!0}).open()}async moveAcrossFolders(t,e,s){if(!t.length)return;let i=(e||"").replace(/\/+$/,"");if(!i){new O.Notice("Target folder is empty");return}let n=[],r=new Set;for(let p of this.app.vault.getMarkdownFiles())(p.parent?.path?.replace(/\/+$/,"")??"")===i&&r.add(p.path);let a=(p,u)=>{if(!p.file)return;let h=p.file,f=`${i}/${h.name}`;if(r.has(f)){let m=h.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),v=m?m[1]:h.basename,y=m?m[2]:"";for(let b=1;b<1e3;b++){let k=`${v}-${b}${y}.md`,T=`${i}/${k}`;if(!r.has(T)){f=T;break}}}r.add(f),n.push({id:p.id,file:h,oldPath:h.path,newPath:f,oldParent:p.parent,isRoot:u});for(let m of this.tree.getChildren(p.id))a(m,!1)};for(let p of t)a(p,!0);if(!n.length)return;await this.ensureFolder(i);for(let p of n)try{await this.app.fileManager.renameFile(p.file,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(p.file,u=>{u.parent=s}),await this.log.append({type:"parent_change",id:p.id,payload:{from:p.oldParent,to:p.isRoot?s:p.oldParent,crossFolder:{from:this.noteFolder,to:i}}})}catch(u){new O.Notice(`Move failed for ${p.id}: ${u.message}`)}this.tree.rebuild(this.noteFolder);let o=t.map(p=>this.tree.get(p.id)).filter(p=>!!p),l=o.length>0?this.titleList(o):`${t.length} note${t.length===1?"":"s"}`,c=s===R?"Open home":"Open parent";this.plugin.notifications.show({message:`Moved ${l} \u2192 \`${i}\``,kind:"success",category:"move",affectedIds:t.map(p=>p.id),folder:this.noteFolder,actions:[{label:c,onClick:()=>{this.switchToFolderAndFocus(i,s)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let p of n){let u=this.app.vault.getAbstractFileByPath(p.newPath);if(u)try{await this.app.fileManager.renameFile(u,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(u,h=>{h.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let u=this.app.vault.getAbstractFileByPath(p.oldPath);if(u)try{await this.app.fileManager.renameFile(u,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(u,h=>{h.parent=s})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}nextPickableIdx(t,e){for(let s=t+e;s>=0&&s<this.currentChildren.length;s+=e){let i=this.currentChildren[s];if(i&&!this.selection.has(i.id))return s}return t}cmdInListPicker(){if(this.currentChildren.length===0)return;let t=this.cursorIdx>0?this.cursorIdx-1:0;if(this.currentChildren[t]&&this.selection.has(this.currentChildren[t].id)){let s=this.nextPickableIdx(t,-1);t=s!==t?s:this.nextPickableIdx(t,1)}this.inListPicker={activeIdx:t},new O.Notice("Arrows to pick parent, Enter confirms, Esc cancels.");let e=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let s=this.listEl;s.scrollTop=e,requestAnimationFrame(()=>{s.scrollTop=e}),setTimeout(()=>{s.scrollTop=e},60)}}async commitInListPicker(){if(!this.inListPicker)return;let t=this.currentChildren[this.inListPicker.activeIdx];if(this.inListPicker=null,!t){this.render();return}let e=this.getActionTargets().filter(n=>n.id!==t.id);for(let n of e)await this.changeParent(n,t.id);if(this.plugin.settings.autoNavOnMoveIn){this.navigateTo(t.id);return}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"});let s=this.selectionGuardKey,i=()=>{if(this.selectionGuardKey!==s||this.selection.has(t.id))return;let n=this.currentChildren.findIndex(r=>r.id===t.id);n<0||(this.selection.add(t.id),this.cursorIdx=n,this.render({kind:"follow-cursor"}))};setTimeout(i,120),setTimeout(i,400)}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new O.Notice("Select 2+ notes to merge.");return}t.sort((m,v)=>(m.created||"").localeCompare(v.created||""));let e=t[0];if(!e.file)return;let s=e.file.path,i=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),r=[],a=[];for(let m of t){if(!m.file)continue;let v=await this.app.vault.cachedRead(m.file);a.push(this.stripFrontmatter(v).trim())}let o=a.map(m=>m.trim()).filter(Boolean).join(` `),l=await this.app.vault.read(e.file),c=l.startsWith("---")?l.indexOf(` ---`,3)+4:0,u=`${l.slice(0,c)} -${a} -`;await this.app.vault.modify(e.file,u);for(let m=1;m<t.length;m++){let v=t[m];if(v.file){for(let y of this.tree.getChildren(v.id))y.file&&r.push({childId:y.id,childPath:y.file.path,oldParent:y.parent}),await this.changeParent(y,e.id,{record:!1});await this.app.fileManager.trashFile(v.file),await this.log.append({type:"delete",id:v.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let d=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${d}"`}),kind:"success",category:"merge",affectedIds:t.map(m=>m.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let m=e.id,v=this.selectionGuardKey,y=()=>{if(this.selectionGuardKey!==v||this.selection.has(m))return;let b=this.currentChildren.findIndex(k=>k.id===m);b<0||(this.selection.add(m),this.cursorIdx=b,this.render({kind:"follow-cursor"}))};setTimeout(y,120),setTimeout(y,400)}let f=this.noteFolder;this.plugin.getUndoStack(f).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(v=>v.id));let m=this.app.vault.getAbstractFileByPath(s);m&&await this.app.vault.modify(m,i);for(let v of r){let y=this.app.vault.getAbstractFileByPath(v.childPath);y&&await this.app.fileManager.processFrontMatter(y,b=>{b.parent=v.oldParent})}this.pendingFocusIds=t.map(v=>v.id),this.tree.rebuild(f),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let m=this.app.vault.getAbstractFileByPath(s);m&&await this.app.vault.modify(m,u);for(let v of r){let y=this.app.vault.getAbstractFileByPath(v.childPath);y&&await this.app.fileManager.processFrontMatter(y,b=>{b.parent=e.id})}this.tree.rebuild(f),this.render()}})}async cmdCopy(){let t=this.getActionTargets();if(!t.length)return;let e=bt().prefixTimestampsOnCopy,s=[];for(let i of t){if(!i.file)continue;let n=await this.app.vault.cachedRead(i.file),r=this.stripFrontmatter(n).trim();s.push(e?`${this.formatTimeInline(i.created)} ${r}`:r)}await navigator.clipboard.writeText(s.join(` +${o} +`;await this.app.vault.modify(e.file,u);for(let m=1;m<t.length;m++){let v=t[m];if(v.file){for(let y of this.tree.getChildren(v.id))y.file&&r.push({childId:y.id,childPath:y.file.path,oldParent:y.parent}),await this.changeParent(y,e.id,{record:!1});await this.app.fileManager.trashFile(v.file),await this.log.append({type:"delete",id:v.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let h=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${h}"`}),kind:"success",category:"merge",affectedIds:t.map(m=>m.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let m=e.id,v=this.selectionGuardKey,y=()=>{if(this.selectionGuardKey!==v||this.selection.has(m))return;let b=this.currentChildren.findIndex(k=>k.id===m);b<0||(this.selection.add(m),this.cursorIdx=b,this.render({kind:"follow-cursor"}))};setTimeout(y,120),setTimeout(y,400)}let f=this.noteFolder;this.plugin.getUndoStack(f).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(v=>v.id));let m=this.app.vault.getAbstractFileByPath(s);m&&await this.app.vault.modify(m,i);for(let v of r){let y=this.app.vault.getAbstractFileByPath(v.childPath);y&&await this.app.fileManager.processFrontMatter(y,b=>{b.parent=v.oldParent})}this.pendingFocusIds=t.map(v=>v.id),this.tree.rebuild(f),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let m=this.app.vault.getAbstractFileByPath(s);m&&await this.app.vault.modify(m,u);for(let v of r){let y=this.app.vault.getAbstractFileByPath(v.childPath);y&&await this.app.fileManager.processFrontMatter(y,b=>{b.parent=e.id})}this.tree.rebuild(f),this.render()}})}async cmdCopy(){let t=this.getActionTargets();if(!t.length)return;let e=St().prefixTimestampsOnCopy,s=[];for(let i of t){if(!i.file)continue;let n=await this.app.vault.cachedRead(i.file),r=this.stripFrontmatter(n).trim();s.push(e?`${this.formatTimeInline(i.created)} ${r}`:r)}await navigator.clipboard.writeText(s.join(` -`)),this.plugin.notifications.show({message:`Copied ${this.titleList(t)} to clipboard`,kind:"success",category:"system",affectedIds:t.map(i=>i.id),folder:this.noteFolder})}async cmdCopyCodeBlock(){let t=this.getActionTargets();if(!t.length||!t[0].file){new O.Notice("Nothing to copy from.");return}let e=t[0],s=await this.app.vault.cachedRead(e.file),i=this.stripFrontmatter(s),n=an(i);if(n.length===0){this.plugin.notifications.show({message:`No codeblock found in "${this.titleForNode(e)}".`,kind:"info",category:"system",affectedIds:[e.id],folder:this.noteFolder});return}if(n.length===1){await navigator.clipboard.writeText(n[0].code),this.plugin.notifications.show({message:`Copied codeblock${n[0].lang?` (${n[0].lang})`:""} from "${this.titleForNode(e)}".`,kind:"success",category:"system",affectedIds:[e.id],folder:this.noteFolder});return}let r=n.map((l,c)=>({kind:"one",idx:c,label:`${c+1}. ${l.lang||"(no language)"} \u2014 ${l.code.split(` +`)),this.plugin.notifications.show({message:`Copied ${this.titleList(t)} to clipboard`,kind:"success",category:"system",affectedIds:t.map(i=>i.id),folder:this.noteFolder})}async cmdCopyCodeBlock(){let t=this.getActionTargets();if(!t.length||!t[0].file){new O.Notice("Nothing to copy from.");return}let e=t[0],s=await this.app.vault.cachedRead(e.file),i=this.stripFrontmatter(s),n=pn(i);if(n.length===0){this.plugin.notifications.show({message:`No codeblock found in "${this.titleForNode(e)}".`,kind:"info",category:"system",affectedIds:[e.id],folder:this.noteFolder});return}if(n.length===1){await navigator.clipboard.writeText(n[0].code),this.plugin.notifications.show({message:`Copied codeblock${n[0].lang?` (${n[0].lang})`:""} from "${this.titleForNode(e)}".`,kind:"success",category:"system",affectedIds:[e.id],folder:this.noteFolder});return}let r=n.map((l,c)=>({kind:"one",idx:c,label:`${c+1}. ${l.lang||"(no language)"} \u2014 ${l.code.split(` `)[0].slice(0,60)}${l.code.includes(` -`)?"\u2026":""}`}));r.push({kind:"all",idx:-1,label:`Copy all ${n.length} blocks (joined with blank lines)`});let o=this,a=new class extends O.SuggestModal{getSuggestions(l){let c=l.trim().toLowerCase();if(!c)return r;let p=c.split(/\s+/).filter(Boolean);return r.filter(u=>{let d=u.label.toLowerCase();return p.every(f=>d.includes(f))})}renderSuggestion(l,c){c.createDiv({cls:"stashpad-suggest-title",text:l.label})}async onChooseSuggestion(l){let c=l.kind==="all"?n.map(p=>p.code).join(` +`)?"\u2026":""}`}));r.push({kind:"all",idx:-1,label:`Copy all ${n.length} blocks (joined with blank lines)`});let a=this,o=new class extends O.SuggestModal{getSuggestions(l){let c=l.trim().toLowerCase();if(!c)return r;let p=c.split(/\s+/).filter(Boolean);return r.filter(u=>{let h=u.label.toLowerCase();return p.every(f=>h.includes(f))})}renderSuggestion(l,c){c.createDiv({cls:"stashpad-suggest-title",text:l.label})}async onChooseSuggestion(l){let c=l.kind==="all"?n.map(p=>p.code).join(` -`):n[l.idx].code;await navigator.clipboard.writeText(c),o.plugin.notifications.show({message:l.kind==="all"?`Copied all ${n.length} codeblocks from "${o.titleForNode(e)}".`:`Copied codeblock${n[l.idx].lang?` (${n[l.idx].lang})`:""} from "${o.titleForNode(e)}".`,kind:"success",category:"system",affectedIds:[e.id],folder:o.noteFolder})}}(this.app);a.setPlaceholder(`${n.length} codeblocks in "${this.titleForNode(e)}" \u2014 pick one to copy.`),a.open()}async cmdCopyTree(){let t=this.getActionTargets();if(t.length===0){let n=this.tree.get(this.focusId);n?.file&&(t=[n])}if(t.length===0){new O.Notice("Nothing to copy.");return}let e=bt().prefixTimestampsOnCopy,s=[],i=async(n,r)=>{if(n.file){let o=await this.app.vault.cachedRead(n.file),a=this.stripFrontmatter(o).trim().split(/\r?\n/).join(" "),l=e?`${this.formatTimeInline(n.created)} `:"";s.push(`${" ".repeat(r)}- ${l}${a}`)}for(let o of this.tree.getChildren(n.id))await i(o,r+1)};for(let n of t)await i(n,0);await navigator.clipboard.writeText(s.join(` -`)),this.plugin.notifications.show({message:`Copied tree of ${this.titleList(t)} (${s.length} entries)`,kind:"success",category:"system",affectedIds:t.map(n=>n.id),folder:this.noteFolder})}async cmdCopyOutline(){let t=this.getActionTargets();if(t.length===0){let i=this.tree.get(this.focusId);i?.file&&(t=[i])}if(t.length===0){new O.Notice("Nothing to copy.");return}let e=[],s=(i,n)=>{if(!i.file)return;let r=" ".repeat(n);e.push(`${r}- ![[${i.file.basename}]]`);for(let o of this.tree.getChildren(i.id))s(o,n+1)};for(let i of t)s(i,0);await navigator.clipboard.writeText(e.join(` -`)),this.plugin.notifications.show({message:`Copied outline of ${this.titleList(t)} (${e.length} entr${e.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:t.map(i=>i.id),folder:this.noteFolder})}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(s=>!this.expandedNotes.has(s.id));for(let s of t)e?this.expandedNotes.add(s.id):this.expandedNotes.delete(s.id);this.render()}async cloneSubtree(t,e,s){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new O.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let i=this.tree.getChildren(t.id).slice(),n=t.file,r=await this.app.vault.read(n),o=this.stripFrontmatter(r),a=this.app.metadataCache.getFileCache(n)?.frontmatter??{},l=yt(),c=Ft(o,this.activeStopwords()),p=xt(c,l),u=`${this.noteFolder}/${p}`,d=new Date().toISOString(),f=this.extractAttachments(o),m=["---",`id: ${l}`,`parent: ${e}`,`created: ${d}`];if(f.length>0){m.push("attachments:");for(let y of f)m.push(` - "${y.replace(/"/g,'\\"')}"`)}else m.push("attachments: []");m.push("---",o),await this.ensureFolder(this.noteFolder),await this.app.vault.create(u,m.join(` -`)),s.push(u);let v=this.app.vault.getAbstractFileByPath(u);if(v){try{await this.app.fileManager.processFrontMatter(v,y=>{for(let[b,k]of Object.entries(a))Rt.includes(b)||(y[b]=k)})}catch(y){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",y)}try{this.tree.insertSynthetic({id:l,parent:e,children:[],file:v,created:d})}catch{}this.fmSync.scheduleParentChange(l,null,e)}for(let y of i)await this.cloneSubtree(y,l,s);return l}async cmdClone(){let t=this.getActionTargets();if(!t.length){new O.Notice("Nothing to clone.");return}let e=this.noteFolder,s=[],i=[];for(let a of t){if(!a.file)continue;let l=a.parent??this.focusId,c=await this.cloneSubtree(a,l,s);c&&i.push(c)}if(!i.length)return;this.tree.rebuild(e),this.pendingFocusIds=i.slice(),this.render();let n=s.map(a=>this.app.vault.getAbstractFileByPath(a)).filter(a=>!!a&&a.extension==="md").map(a=>({id:ee(a.basename)??a.basename,parent:null,children:[],file:a,created:new Date().toISOString()})),r=await this.snapshotNotes(n,!1);this.plugin.getUndoStack(e).push({label:`Clone ${i.length} note${i.length===1?"":"s"}`,undo:async()=>{for(let a of[...s].reverse()){let l=this.app.vault.getAbstractFileByPath(a);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(r,i)}});let o=i.map(a=>this.tree.get(a)).filter(a=>!!a);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Cloned",nodes:o,suffix:`(${s.length} file${s.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:i,folder:this.noteFolder})}cmdInsertTemplate(){new Ot(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Insert which note as a template?",allowCreate:!1,onPick:async t=>{if(t.crossFolder){new O.Notice("Cross-Stashpad templates aren't supported yet \u2014 pick a note from this Stashpad.");return}let e=this.tree.get(t.id);if(!e?.file)return;let s=this.noteFolder,i=[],n=await this.cloneSubtree(e,this.focusId,i);if(!n)return;this.tree.rebuild(s),this.pendingFocusIds=[n],this.render();let r=i.map(a=>this.app.vault.getAbstractFileByPath(a)).filter(a=>!!a&&a.extension==="md").map(a=>({id:ee(a.basename)??a.basename,parent:null,children:[],file:a,created:new Date().toISOString()})),o=await this.snapshotNotes(r,!1);this.plugin.getUndoStack(s).push({label:"Insert template",undo:async()=>{for(let a of[...i].reverse()){let l=this.app.vault.getAbstractFileByPath(a);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(s),this.render()},redo:async()=>{await this.restoreSnapshots(o,[n])}}),this.plugin.notifications.show({message:`Inserted template (${i.length} file${i.length===1?"":"s"})`,kind:"success",category:"clone",folder:this.noteFolder})}}).open()}navigateTo(t,e={}){if(e.keepForwardStack||this.recordNavState(),this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.tagFilter){let n=this.tagFilter.toLowerCase();this.collectFolderTags().some(o=>o.raw.toLowerCase()===n)||(this.tagFilter=null)}if(this.colorFilter){let n=this.colorFilter.toLowerCase();this.collectFolderColors().some(o=>o.hex===n)||(this.colorFilter=null)}let s=this.lastCursorByFocus.get(t),i;s&&this.tree.get(s)?(this.pendingFocusIds=[s],i={kind:"scroll-to-id",id:s,align:"start"}):i={kind:"preserve"},this.render(i),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0}),this.plugin.notifyStashpadSelectionChanged()}navigateBack(){let t=this.navBackStack.pop();if(!t){this.focusId!==R&&this.navigateUp();return}this.navForwardSnapshots.push(this.captureNavSnapshot()),this.applyNavSnapshot(t)}navigateForward(){let t=this.navForwardSnapshots.pop();t&&(this.navBackStack.push(this.captureNavSnapshot()),this.applyNavSnapshot(t))}async applyNavSnapshot(t){if(this.tagFilter=null,this.colorFilter=null,t.folder!==this.noteFolder){await this.setFolderOverride(t.folder,{skipHistory:!0}),t.focusId!==this.focusId&&this.tree.get(t.focusId)&&(this.focusId=t.focusId,this.render({kind:"preserve"}));return}if(!this.tree.get(t.focusId))return;this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t.focusId,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus();let e=this.lastCursorByFocus.get(t.focusId),s;e&&this.tree.get(e)?(this.pendingFocusIds=[e],s={kind:"scroll-to-id",id:e,align:"start"}):s={kind:"preserve"},this.render(s),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0})}navigateUp(){this.selectionGuardKey++,this.tagFilter=null,this.colorFilter=null;let t=this.tree.get(this.focusId);if(!t||t.parent==null){if(this.navBackStack.length>0){this.navigateBack();return}return this.navigateTo(R)}let e=this.focusId;if(this.recordNavState(),this.listEl){let r=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;r&&this.plugin.saveLastCursor(this.noteFolder,e,r)}this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus();let s=this.filterChildren(this.tree.getChildren(this.focusId)),i=s.findIndex(n=>n.id===e);this.selection.clear(),i>=0?(this.cursorIdx=i,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=s.length-1,s.length>0&&(this.selection.add(s[s.length-1].id),this.lastSelected=s[s.length-1].id)),this.render({kind:"follow-cursor"}),this.refreshHeaderTitle(),this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),s=new O.Menu,i=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let r=this.tree.idForPath(n.path);r&&(s.addItem(o=>o.setTitle(n.title||n.path).onClick(()=>this.navigateTo(r))),i++)}i||s.addItem(n=>n.setTitle("(no bookmarks in scope)").setDisabled(!0)),s.showAtMouseEvent(new MouseEvent("click",{clientX:200,clientY:400}))}async bootstrapFolder(){if(this.bootstrappedFolders.has(this.noteFolder))return;await this.ensureFolder(this.noteFolder),await this.ensureHomeNote(),await this.migrateNullParents();let t=(this.plugin.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),e=(this.plugin.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");t&&await this.ensureFolder(`${this.noteFolder}/${t}`),e&&await this.ensureFolder(`${this.noteFolder}/${e}`),await this.order.load(this.noteFolder),await this.sortStore.load(this.noteFolder),this.bootstrappedFolders.add(this.noteFolder)}backfillFrontmatterSync(){let t=[R],e=this.tree.getRoot(),s=i=>{for(let n of this.tree.getChildren(i))t.push(n.id),s(n.id)};for(let i of e.children)s(i);for(let i of t)this.fmSync.wouldWrite(i)&&this.fmSync.schedule(i)}installFmSyncActivityNotice(){this.fmSyncUnsubscribe||(this.fmSyncUnsubscribe=this.fmSync.onError((t,e)=>{this.plugin.notifications.show({message:`Stashpad: couldn't update recovery metadata +`):n[l.idx].code;await navigator.clipboard.writeText(c),a.plugin.notifications.show({message:l.kind==="all"?`Copied all ${n.length} codeblocks from "${a.titleForNode(e)}".`:`Copied codeblock${n[l.idx].lang?` (${n[l.idx].lang})`:""} from "${a.titleForNode(e)}".`,kind:"success",category:"system",affectedIds:[e.id],folder:a.noteFolder})}}(this.app);o.setPlaceholder(`${n.length} codeblocks in "${this.titleForNode(e)}" \u2014 pick one to copy.`),o.open()}async cmdCopyTree(){let t=this.getActionTargets();if(t.length===0){let n=this.tree.get(this.focusId);n?.file&&(t=[n])}if(t.length===0){new O.Notice("Nothing to copy.");return}let e=St().prefixTimestampsOnCopy,s=[],i=async(n,r)=>{if(n.file){let a=await this.app.vault.cachedRead(n.file),o=this.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),l=e?`${this.formatTimeInline(n.created)} `:"";s.push(`${" ".repeat(r)}- ${l}${o}`)}for(let a of this.tree.getChildren(n.id))await i(a,r+1)};for(let n of t)await i(n,0);await navigator.clipboard.writeText(s.join(` +`)),this.plugin.notifications.show({message:`Copied tree of ${this.titleList(t)} (${s.length} entries)`,kind:"success",category:"system",affectedIds:t.map(n=>n.id),folder:this.noteFolder})}async cmdCopyOutline(){let t=this.getActionTargets();if(t.length===0){let i=this.tree.get(this.focusId);i?.file&&(t=[i])}if(t.length===0){new O.Notice("Nothing to copy.");return}let e=[],s=(i,n)=>{if(!i.file)return;let r=" ".repeat(n);e.push(`${r}- ![[${i.file.basename}]]`);for(let a of this.tree.getChildren(i.id))s(a,n+1)};for(let i of t)s(i,0);await navigator.clipboard.writeText(e.join(` +`)),this.plugin.notifications.show({message:`Copied outline of ${this.titleList(t)} (${e.length} entr${e.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:t.map(i=>i.id),folder:this.noteFolder})}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(s=>!this.expandedNotes.has(s.id));for(let s of t)e?this.expandedNotes.add(s.id):this.expandedNotes.delete(s.id);this.render()}async cloneSubtree(t,e,s){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new O.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let i=this.tree.getChildren(t.id).slice(),n=t.file,r=await this.app.vault.read(n),a=this.stripFrontmatter(r),o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},l=yt(),c=Ft(a,this.activeStopwords()),p=xt(c,l),u=`${this.noteFolder}/${p}`,h=new Date().toISOString(),f=this.extractAttachments(a),m=["---",`id: ${l}`,`parent: ${e}`,`created: ${h}`];if(f.length>0){m.push("attachments:");for(let y of f)m.push(` - "${y.replace(/"/g,'\\"')}"`)}else m.push("attachments: []");m.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(u,m.join(` +`)),s.push(u);let v=this.app.vault.getAbstractFileByPath(u);if(v){try{await this.app.fileManager.processFrontMatter(v,y=>{for(let[b,k]of Object.entries(o))Bt.includes(b)||(y[b]=k)})}catch(y){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",y)}try{this.tree.insertSynthetic({id:l,parent:e,children:[],file:v,created:h})}catch{}this.fmSync.scheduleParentChange(l,null,e)}for(let y of i)await this.cloneSubtree(y,l,s);return l}async cmdClone(){let t=this.getActionTargets();if(!t.length){new O.Notice("Nothing to clone.");return}let e=this.noteFolder,s=[],i=[];for(let o of t){if(!o.file)continue;let l=o.parent??this.focusId,c=await this.cloneSubtree(o,l,s);c&&i.push(c)}if(!i.length)return;this.tree.rebuild(e),this.pendingFocusIds=i.slice(),this.render();let n=s.map(o=>this.app.vault.getAbstractFileByPath(o)).filter(o=>!!o&&o.extension==="md").map(o=>({id:re(o.basename)??o.basename,parent:null,children:[],file:o,created:new Date().toISOString()})),r=await this.snapshotNotes(n,!1);this.plugin.getUndoStack(e).push({label:`Clone ${i.length} note${i.length===1?"":"s"}`,undo:async()=>{for(let o of[...s].reverse()){let l=this.app.vault.getAbstractFileByPath(o);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(r,i)}});let a=i.map(o=>this.tree.get(o)).filter(o=>!!o);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Cloned",nodes:a,suffix:`(${s.length} file${s.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:i,folder:this.noteFolder})}cmdInsertTemplate(){new $t(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Insert which note as a template?",allowCreate:!1,onPick:async t=>{if(t.crossFolder){new O.Notice("Cross-Stashpad templates aren't supported yet \u2014 pick a note from this Stashpad.");return}let e=this.tree.get(t.id);if(!e?.file)return;let s=this.noteFolder,i=[],n=await this.cloneSubtree(e,this.focusId,i);if(!n)return;this.tree.rebuild(s),this.pendingFocusIds=[n],this.render();let r=i.map(o=>this.app.vault.getAbstractFileByPath(o)).filter(o=>!!o&&o.extension==="md").map(o=>({id:re(o.basename)??o.basename,parent:null,children:[],file:o,created:new Date().toISOString()})),a=await this.snapshotNotes(r,!1);this.plugin.getUndoStack(s).push({label:"Insert template",undo:async()=>{for(let o of[...i].reverse()){let l=this.app.vault.getAbstractFileByPath(o);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(s),this.render()},redo:async()=>{await this.restoreSnapshots(a,[n])}}),this.plugin.notifications.show({message:`Inserted template (${i.length} file${i.length===1?"":"s"})`,kind:"success",category:"clone",folder:this.noteFolder})}}).open()}navigateTo(t,e={}){if(e.keepForwardStack||this.recordNavState(),this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.tagFilter){let n=this.tagFilter.toLowerCase();this.collectFolderTags().some(a=>a.raw.toLowerCase()===n)||(this.tagFilter=null)}if(this.colorFilter){let n=this.colorFilter.toLowerCase();this.collectFolderColors().some(a=>a.hex===n)||(this.colorFilter=null)}let s=this.lastCursorByFocus.get(t),i;s&&this.tree.get(s)?(this.pendingFocusIds=[s],i={kind:"scroll-to-id",id:s,align:"start"}):i={kind:"preserve"},this.render(i),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0}),this.plugin.notifyStashpadSelectionChanged()}navigateBack(){let t=this.navBackStack.pop();if(!t){this.focusId!==R&&this.navigateUp();return}this.navForwardSnapshots.push(this.captureNavSnapshot()),this.applyNavSnapshot(t)}navigateForward(){let t=this.navForwardSnapshots.pop();t&&(this.navBackStack.push(this.captureNavSnapshot()),this.applyNavSnapshot(t))}async applyNavSnapshot(t){if(this.tagFilter=null,this.colorFilter=null,t.folder!==this.noteFolder){await this.setFolderOverride(t.folder,{skipHistory:!0}),t.focusId!==this.focusId&&this.tree.get(t.focusId)&&(this.focusId=t.focusId,this.render({kind:"preserve"}));return}if(!this.tree.get(t.focusId))return;this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t.focusId,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus();let e=this.lastCursorByFocus.get(t.focusId),s;e&&this.tree.get(e)?(this.pendingFocusIds=[e],s={kind:"scroll-to-id",id:e,align:"start"}):s={kind:"preserve"},this.render(s),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0})}navigateUp(){this.selectionGuardKey++,this.tagFilter=null,this.colorFilter=null;let t=this.tree.get(this.focusId);if(!t||t.parent==null){if(this.navBackStack.length>0){this.navigateBack();return}return this.navigateTo(R)}let e=this.focusId;if(this.recordNavState(),this.listEl){let r=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;r&&this.plugin.saveLastCursor(this.noteFolder,e,r)}this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus();let s=this.filterChildren(this.tree.getChildren(this.focusId)),i=s.findIndex(n=>n.id===e);this.selection.clear(),i>=0?(this.cursorIdx=i,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=s.length-1,s.length>0&&(this.selection.add(s[s.length-1].id),this.lastSelected=s[s.length-1].id)),i>=0?this.render({kind:"scroll-to-id",id:e,align:"start"}):this.render({kind:"follow-cursor"}),this.refreshHeaderTitle(),i<0&&this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),s=new O.Menu,i=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let r=this.tree.idForPath(n.path);r&&(s.addItem(a=>a.setTitle(n.title||n.path).onClick(()=>this.navigateTo(r))),i++)}i||s.addItem(n=>n.setTitle("(no bookmarks in scope)").setDisabled(!0)),s.showAtMouseEvent(new MouseEvent("click",{clientX:200,clientY:400}))}async bootstrapFolder(){if(this.bootstrappedFolders.has(this.noteFolder))return;await this.ensureFolder(this.noteFolder),await this.ensureHomeNote(),await this.migrateNullParents();let t=(this.plugin.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),e=(this.plugin.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");t&&await this.ensureFolder(`${this.noteFolder}/${t}`),e&&await this.ensureFolder(`${this.noteFolder}/${e}`),await this.order.load(this.noteFolder),await this.sortStore.load(this.noteFolder),this.bootstrappedFolders.add(this.noteFolder)}backfillFrontmatterSync(){let t=[R],e=this.tree.getRoot(),s=i=>{for(let n of this.tree.getChildren(i))t.push(n.id),s(n.id)};for(let i of e.children)s(i);for(let i of t)this.fmSync.wouldWrite(i)&&this.fmSync.schedule(i)}installFmSyncActivityNotice(){this.fmSyncUnsubscribe||(this.fmSyncUnsubscribe=this.fmSync.onError((t,e)=>{this.plugin.notifications.show({message:`Stashpad: couldn't update recovery metadata File: \`${t}\` Error: ${e.message}`,kind:"error",category:"system",duration:0,affectedPaths:[t],folder:this.noteFolder})}))}async ensureHomeNote(){let t=this.noteFolder,e=`${t}/${this.buildHomeFilename(t)}`,s=this.app.vault.getMarkdownFiles().filter(r=>r.path.startsWith(t+"/"));for(let r of s){if(this.app.metadataCache.getFileCache(r)?.frontmatter?.id!==R)continue;if(r.path===e||this.app.vault.getAbstractFileByPath(e))return r;try{await this.app.fileManager.renameFile(r,e);let l=this.app.vault.getAbstractFileByPath(e);if(l instanceof O.TFile)return l}catch(l){console.warn("[Stashpad] home note rename failed; keeping legacy path",l)}return r}let i=new Date().toISOString(),n=["---",`id: ${R}`,"parent: null",`created: ${i}`,"attachments: []","---","","# Home","","This is your Stashpad home note. Edit me freely \u2014 everything else nests below.",""].join(` -`);return this.app.vault.create(e,n)}buildHomeFilename(t){return`Home-${(t.split("/").filter(Boolean).pop()??"Stashpad").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"Stashpad"}.md`}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(s=>s.path.startsWith(t+"/"));for(let s of e){let i=this.app.metadataCache.getFileCache(s)?.frontmatter,n=i?.id;if(!n||n===R)continue;let r=i?.parent;(r==null||r===""||r==="null")&&(await this.app.fileManager.processFrontMatter(s,o=>{o.parent=R}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:R,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,s=this.leaf,i=e.getLeaf("tab");await i.setViewState({type:mt,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i);let n=e.on("active-leaf-change",()=>{if((()=>{let a=!1;return e.iterateAllLeaves(l=>{l===i&&(a=!0)}),a})())return;e.offref(n),(()=>{let a=!1;return e.iterateAllLeaves(l=>{l===s&&(a=!0)}),a})()&&(e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s))})}async openFolderInNewTab(t){let e=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!e)return;let s=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",i=this.app.workspace,n=this.leaf,r=i.getLeaf("tab");await r.setViewState({type:mt,active:!0,state:{focusId:R,folderOverride:e===s?null:e}}),i.setActiveLeaf(r,{focus:!0}),i.revealLeaf(r);let o=i.on("active-leaf-change",()=>{if((()=>{let c=!1;return i.iterateAllLeaves(p=>{p===r&&(c=!0)}),c})())return;i.offref(o),(()=>{let c=!1;return i.iterateAllLeaves(p=>{p===n&&(c=!0)}),c})()&&(i.setActiveLeaf(n,{focus:!0}),i.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let s of e)s.file&&this.openFileAtEnd(s.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new O.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,s=this.leaf,i=e.getLeaf("tab");await i.openFile(t,{active:!0}),e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i);let n=e.on("active-leaf-change",()=>{if((()=>{let c=!1;return e.iterateAllLeaves(p=>{p===i&&(c=!0)}),c})())return;e.offref(n),(()=>{let c=!1;return e.iterateAllLeaves(p=>{p===s&&(c=!0)}),c})()&&(e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s))}),o=i.view?.editor;o&&requestAnimationFrame(()=>{try{let a=o.lastLine(),l=o.getLine(a)?.length??0;o.setCursor({line:a,ch:l}),o.scrollIntoView({from:{line:a,ch:l},to:{line:a,ch:l}},!0),o.focus()}catch{}})}cmdSelectAll(){if(this.currentChildren.length!==0){this.selection.clear();for(let t of this.currentChildren)this.selection.add(t.id);this.firstSelectedId=this.currentChildren[0].id,this.lastSelected=this.currentChildren[this.currentChildren.length-1].id,this.cursorIdx=this.currentChildren.length-1,this.render()}}async cmdTogglePin(){let t=this.getActionTargets();if(t.length===0){let n=this.tree.get(this.focusId);n?.file&&(t=[n])}if(t.length===0){new O.Notice("Nothing to pin.");return}let e=t.some(n=>!this.plugin.isPinned({folder:this.noteFolder,id:n.id})),s=0,i=0;for(let n of t){let r={folder:this.noteFolder,id:n.id};e?this.plugin.isPinned(r)||(await this.plugin.pinNote(r),s++):this.plugin.isPinned(r)&&(await this.plugin.unpinNote(r),i++)}s>0?new O.Notice(`Pinned ${s} note${s===1?"":"s"} to sidebar.`):i>0&&new O.Notice(`Unpinned ${i} note${i===1?"":"s"} from sidebar.`)}async cmdToggleComplete(){let t=this.getActionTargets();if(t.length===0){let o=this.tree.get(this.focusId);o?.file&&(t=[o])}if(t.length===0){new O.Notice("Nothing to toggle.");return}let s=t.some(o=>!this.isCompleted(o)),i=[],n=[];for(let o of t){if(!o.file)continue;let a=this.isCompleted(o);i.push({id:o.id,path:o.file.path,was:a}),a!==s&&(await this.app.fileManager.processFrontMatter(o.file,l=>{s?l.completed=!0:delete l.completed}),this.completedState.set(o.file.path,s),n.push(o.id))}if(this.render(),n.length>0){await this.log.append({type:s?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length}});let o=n.map(a=>this.tree.get(a)).filter(a=>!!a);this.plugin.notifications.show({message:this.bulkActionMessage({verb:s?"Marked complete":"Unmarked",nodes:o}),kind:"success",category:s?"complete":"uncomplete",affectedIds:n,folder:this.noteFolder})}let r=this.noteFolder;this.plugin.getUndoStack(r).push({label:`${s?"Mark complete":"Unmark complete"} (${t.length})`,undo:async()=>{let o=[];for(let a of i){let l=this.app.vault.getAbstractFileByPath(a.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{a.was?c.completed=!0:delete c.completed}),n.includes(a.id)&&o.push(a.id))}o.length>0&&await this.log.append({type:s?"uncomplete":"complete",id:o[0],payload:{ids:o,count:o.length,undo:!0}}),this.tree.rebuild(r),this.render()},redo:async()=>{for(let o of i){let a=this.app.vault.getAbstractFileByPath(o.path);a&&await this.app.fileManager.processFrontMatter(a,l=>{s?l.completed=!0:delete l.completed})}n.length>0&&await this.log.append({type:s?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(r),this.render()}})}isCompleted(t){if(!t.file)return!1;let e=this.completedState.get(t.file.path);return e!==void 0?e:!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed}cmdSetDue(){let t=this.getActionTargets();if(t.length===0){let o=this.tree.get(this.focusId);o?.file&&(t=[o])}if(t.length===0){new O.Notice("Nothing to schedule.");return}let e=t[0],s=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,i=s&&(typeof s.due=="string"||typeof s.due=="number")?String(s.due):null,n=this.plugin.authorRegistry.all().map(o=>({id:o.id,name:o.name})),r=ue(s??{});new ve(this.app,i,o=>{this.applyDue(t,o.iso,o.assignees)},{knownAuthors:n,currentAssignees:r}).open()}async applyDue(t,e,s=[]){let i=[],n=[],r=this.currentAuthorLink();for(let l of s)await this.plugin.ensureAuthorStubFor(this.noteFolder,l.id,l.name);let o=s.map(l=>this.plugin.authorRefFor(this.noteFolder,l.id,l.name));for(let l of t){if(!l.file)continue;let c=this.app.metadataCache.getFileCache(l.file)?.frontmatter;i.push({id:l.id,path:l.file.path,due:c?.due,task:c?.task,assignedTo:c?.assignedTo,assignedBy:c?.assignedBy}),await this.app.fileManager.processFrontMatter(l.file,p=>{e===null?delete p.due:(p.due=e,p.task=!0),o.length>0?(p.assignedTo=o,r&&(p.assignedBy=r.link),p.task=!0):(delete p.assignedTo,delete p.assignedBy)}),n.push(l.id)}if(this.render(),n.length>0){let l=n.map(c=>this.tree.get(c)).filter(c=>!!c);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${Yt(Date.parse(e),this.plugin.settings)}`,nodes:l}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let a=this.noteFolder;this.plugin.getUndoStack(a).push({label:e===null?`Clear due date (${t.length})`:`Set due date (${t.length})`,undo:async()=>{for(let l of i){let c=this.app.vault.getAbstractFileByPath(l.path);c&&await this.app.fileManager.processFrontMatter(c,p=>{l.due===void 0?delete p.due:p.due=l.due,l.task===void 0?delete p.task:p.task=l.task,l.assignedTo===void 0?delete p.assignedTo:p.assignedTo=l.assignedTo,l.assignedBy===void 0?delete p.assignedBy:p.assignedBy=l.assignedBy})}this.tree.rebuild(a),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new O.Notice("Nothing to assign.");return}let e=t[0],s=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,i=this.plugin.authorRegistry.all().map(r=>({id:r.id,name:r.name})),n=ue(s??{});new ge(this.app,{knownAuthors:i,currentAssignees:n},r=>{this.applyAssignees(t,r)}).open()}async applyAssignees(t,e){let s=this.currentAuthorLink();for(let a of e)await this.plugin.ensureAuthorStubFor(this.noteFolder,a.id,a.name);let i=e.map(a=>this.plugin.authorRefFor(this.noteFolder,a.id,a.name)),n=[],r=[];for(let a of t){if(!a.file)continue;let l=this.app.metadataCache.getFileCache(a.file)?.frontmatter;n.push({path:a.file.path,assignedTo:l?.assignedTo,assignedBy:l?.assignedBy,task:l?.task}),await this.app.fileManager.processFrontMatter(a.file,c=>{i.length>0?(c.assignedTo=i,s&&(c.assignedBy=s.link),c.task=!0):(delete c.assignedTo,delete c.assignedBy)}),r.push(a.id)}if(this.render(),r.length>0){let a=r.map(c=>this.tree.get(c)).filter(c=>!!c),l=e.map(c=>c.name).join(", ");this.plugin.notifications.show({message:this.bulkActionMessage({verb:i.length>0?`Assigned to ${l}`:"Cleared assignment",nodes:a}),kind:"success",category:"edit",affectedIds:r,folder:this.noteFolder})}let o=this.noteFolder;this.plugin.getUndoStack(o).push({label:i.length>0?`Assign (${t.length})`:`Clear assignment (${t.length})`,undo:async()=>{for(let a of n){let l=this.app.vault.getAbstractFileByPath(a.path);l&&await this.app.fileManager.processFrontMatter(l,c=>{a.assignedTo===void 0?delete c.assignedTo:c.assignedTo=a.assignedTo,a.assignedBy===void 0?delete c.assignedBy:c.assignedBy=a.assignedBy,a.task===void 0?delete c.task:c.task=a.task})}this.tree.rebuild(o),this.render()}})}isTask(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return e?Vt(e,"task")||e.task===!0||e.completed!==void 0:!1}async cmdToggleTask(){let t=this.getActionTargets();if(t.length===0){let o=this.tree.get(this.focusId);o?.file&&(t=[o])}if(t.length===0){new O.Notice("Nothing to toggle.");return}let e=t.some(o=>!this.isTaskTagged(o)),s=[],i=[];for(let o of t){if(!o.file)continue;let a=this.isTaskTagged(o),l=this.app.metadataCache.getFileCache(o.file)?.frontmatter;if(s.push({id:o.id,path:o.file.path,tags:l?.tags,completed:l?.completed,task:l?.task}),a===e)continue;let c=!1;await this.app.fileManager.processFrontMatter(o.file,p=>{e?(Ss(p,"task"),p.completed===void 0&&(p.completed=!1),c=p.completed===!0,delete p.task):(ks(p,"task"),delete p.completed,delete p.task,c=!1)}),this.completedState.set(o.file.path,c),i.push(o.id)}if(this.render(),i.length>0){let o=e?"marked as task":"unmarked as task",a;if(i.length===1){let l=this.tree.get(i[0]);a=`"${l&&this.titleForNode(l).trim()||"(untitled)"}" ${o}`}else a=`${i.length} notes ${o}`;this.plugin.notifications.show({message:a,kind:"success",category:"edit",affectedIds:i,folder:this.noteFolder})}let n=this.noteFolder,r=async()=>{for(let o of s){let a=this.app.vault.getAbstractFileByPath(o.path);a&&await this.app.fileManager.processFrontMatter(a,l=>{o.tags===void 0?delete l.tags:l.tags=o.tags,o.completed===void 0?delete l.completed:l.completed=o.completed,o.task===void 0?delete l.task:l.task=o.task})}this.tree.rebuild(n),this.render()};this.plugin.getUndoStack(n).push({label:`${e?"Mark task":"Unmark task"} (${t.length})`,undo:r,redo:async()=>{for(let o of s){let a=this.app.vault.getAbstractFileByPath(o.path);a&&await this.app.fileManager.processFrontMatter(a,l=>{e?(Ss(l,"task"),l.completed===void 0&&(l.completed=!1),delete l.task):(ks(l,"task"),delete l.completed,delete l.task)})}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,s=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!s}),this.completedState.set(e,!s),await this.log.append({type:s?"uncomplete":"complete",id:t.id}),this.render();let i=this.noteFolder;this.plugin.getUndoStack(i).push({label:s?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,r=>{r.completed=s}),this.tree.rebuild(i),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return e?Vt(e,"task")||e.task===!0:!1}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let s=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s)?s:null}inheritedColorForNode(t){let e=t,s=0,i=new Set;for(;e&&e.id!==R&&!i.has(e.id);){i.add(e.id);let n=this.colorForNode(e);if(n)return{hex:n,depth:s};e=e.parent?this.tree.get(e.parent):void 0,s+=1}return null}attachRowDnD(t,e,s){t.addEventListener("dragstart",i=>{let n=this.selection.has(e.id)&&this.selection.size>1?[...this.selection]:[e.id];if(this.dragSourceIds=n,this.dragRowHeight=t.offsetHeight,t.addClass("is-dragging"),this.listEl&&(this.dragPlaceholder=this.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.style.height="0px",this.dragPlaceholder.addEventListener("dragover",r=>{this.dragSourceIds&&(r.preventDefault(),r.dataTransfer&&(r.dataTransfer.dropEffect="move"))}),this.dragPlaceholder.addEventListener("drop",r=>{if(!this.dragSourceIds||!this.dragPlaceholder)return;r.preventDefault(),r.stopPropagation();let o=this.dragSourceIds.slice();this.dragSourceIds=null;let a=this.dragPlaceholder.nextElementSibling,l=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let c,p="before";a&&a.classList.contains("stashpad-note")?(c=a.dataset.id,p="before"):l&&l.classList.contains("stashpad-note")&&(c=l.dataset.id,p="after"),c&&this.reorderToTarget(o,c,p)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",n.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(t,12,12)}catch{}}}),t.addEventListener("dragend",()=>{t.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),t.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let n=this.dropZone(i,t);this.clearDropIndicators(),n==="drop-into"?(this.removeDragPlaceholder(),t.addClass("drop-into")):(t.removeClass("drop-into"),this.placePlaceholder(t,n==="drop-above"?"before":"after"))}),t.addEventListener("dragleave",i=>{let n=t.getBoundingClientRect();(i.clientX<n.left||i.clientX>n.right||i.clientY<n.top||i.clientY>n.bottom)&&t.removeClass("drop-into")}),t.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let n=this.dragSourceIds.slice();this.dragSourceIds=null;let r=this.dropZone(i,t);this.clearDropIndicators(),this.removeDragPlaceholder(),t.removeClass("is-dragging"),r==="drop-into"?this.reorderToTarget(n,e.id,"into"):this.reorderToTarget(n,e.id,r==="drop-above"?"before":"after")})}placePlaceholder(t,e){if(!this.dragPlaceholder||!this.listEl)return;let s=e==="before"?t:t.nextSibling;if(e==="before"&&this.dragPlaceholder.nextSibling===t||e==="after"&&this.dragPlaceholder.previousSibling===t)return;let i=!!this.dragPlaceholder.parentElement;this.listEl.insertBefore(this.dragPlaceholder,s),this.dragPlaceholder.style.opacity="1",i?this.dragPlaceholder.style.height=`${this.dragRowHeight}px`:(this.dragPlaceholder.style.height="0px",this.dragPlaceholder.offsetHeight,this.dragPlaceholder.style.height=`${this.dragRowHeight}px`)}removeDragPlaceholder(){if(!this.dragPlaceholder?.parentElement)return;let t=this.dragPlaceholder;t.style.height="0px",t.style.opacity="0",setTimeout(()=>{t.parentElement&&t.remove()},150)}dropZone(t,e){let s=e.getBoundingClientRect(),i=t.clientY-s.top;return i<s.height*.3?"drop-above":i>s.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.listEl)for(let t of Array.from(this.listEl.querySelectorAll(".drop-into")))t.removeClass("drop-into")}isDescendant(t,e){let s=this.tree.get(t),i=new Set;for(;s&&s.parent&&!i.has(s.id);){if(s.parent===e)return!0;i.add(s.id),s=this.tree.get(s.parent)}return!1}async moveAcrossThenReorder(t,e,s,i){let n=[],r=new Set;for(let D of t){let H=this.tree.get(D);H?.file&&(n.push({id:D,path:H.file.path,oldParent:H.parent}),r.add(H.parent??R))}r.add(e);let o=this.collectAuthorIds(t.map(D=>this.tree.get(D)).filter(D=>!!D)),a=this.noteFolder,l={};for(let D of r)l[D]=this.order.getOrder(a,D).slice();for(let D of n){let H=this.app.vault.getAbstractFileByPath(D.path);H&&(await this.app.fileManager.processFrontMatter(H,T=>{T.parent=e}),this.fmSync.scheduleParentChange(D.id,D.oldParent,e),await this.log.append({type:"parent_change",id:D.id,payload:{from:D.oldParent,to:e,reason:"drag"}}),this.order.removeChild(a,D.id))}this.tree.rebuild(a);let c=this.tree.getChildren(e).map(D=>D.id),p=new Set(t),u=c.filter(D=>!p.has(D)),d=u.indexOf(s);d<0&&(d=u.length),i==="after"&&(d+=1);let f=[...u.slice(0,d),...t.filter(D=>!!this.tree.get(D)),...u.slice(d)];this.order.setOrder(a,e,f),await this.order.save(a),await this.forceManualMode(e),await this.log.append({type:"reorder",id:e,payload:{dir:"drag-cross",parent:e,ids:t,count:t.length}});let m=this.focusId===e,v=m?t[0]:e,y=m?t.slice():[e];m?this.pendingFocusIds=y:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=y),this.tree.rebuild(a),this.render({kind:"follow-cursor"});let b=this.selectionGuardKey,k=()=>{if(this.selectionGuardKey!==b||this.selection.has(v))return;let D=this.currentChildren.findIndex(H=>H.id===v);D<0||(this.selection.add(v),this.cursorIdx=D,this.render({kind:"follow-cursor"}))};setTimeout(k,120),setTimeout(k,400);let C=t.map(D=>this.tree.get(D)).filter(D=>!!D),I=this.tree.get(e),E=I?this.titleForNode(I):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:C,destination:`\u2192 "${E}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:o,folder:a,actions:e===R?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(a).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let D of n){let H=this.app.vault.getAbstractFileByPath(D.path);H&&(await this.app.fileManager.processFrontMatter(H,T=>{D.oldParent===null||D.oldParent===void 0?T.parent=R:T.parent=D.oldParent}),await this.log.append({type:"parent_change",id:D.id,payload:{from:e,to:D.oldParent,reason:"drag-undo"}}))}for(let[D,H]of Object.entries(l))if(H.length===0){let T=this.order.cache.get(a)??{};delete T[D],this.order.cache.set(a,T)}else this.order.setOrder(a,D,H);await this.order.save(a),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(a),this.render()},redo:async()=>{for(let D of n){let H=this.app.vault.getAbstractFileByPath(D.path);H&&(await this.app.fileManager.processFrontMatter(H,T=>{T.parent=e}),this.order.removeChild(a,D.id))}this.order.setOrder(a,e,f),await this.order.save(a),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(a),this.render()}})}async reorderToTarget(t,e,s){let i=this.tree.get(e);if(!i)return;let n=t.map(b=>this.tree.get(b)).filter(b=>!!b&&!!b.file);if(n.length===0)return;if(n.some(b=>b.id===e)){this.plugin.notifications.show({message:"Can't move a note into itself.",kind:"warning",category:"move",folder:this.noteFolder});return}if(s==="into"){for(let b of n)if(this.isDescendant(e,b.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(b)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",folder:this.noteFolder});return}}let r=s==="into"?e:i.parent??R;if(n.some(b=>(b.parent??R)!==r)){let b=bt(),k=async()=>{s==="into"?await this.moveAcrossThenReorder(n.map(C=>C.id),r,"","after"):await this.moveAcrossThenReorder(n.map(C=>C.id),r,e,s)};if(b.confirmCrossParentDrag){let C=this.titleForNode(i),I=n.length,E=s==="into"?"Nest":"Move",D=s==="into"?"as children of":"under";new It(this.app,s==="into"?"Nest under target?":"Move under different parent?",`${E} ${I} note${I===1?"":"s"} ${D} "${C}"? Their parent will change.`,E,H=>{H&&k()}).open()}else await k();return}let a=r,l=n.map(b=>b.id),c=this.tree.getChildren(a).map(b=>b.id),p=new Set(l),u=c.filter(b=>!p.has(b)),d=u.indexOf(e);if(d<0)return;s==="after"&&(d+=1);let f=[...u.slice(0,d),...l,...u.slice(d)];if(Ci(f,c))return;let m=this.noteFolder,v=this.order.getOrder(m,a).slice();this.order.setOrder(m,a,f),await this.order.save(m),await this.forceManualMode(a),await this.log.append({type:"reorder",id:a,payload:{dir:"drag",parent:a,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(m),this.render();let y=l.map(b=>this.tree.get(b)).filter(b=>!!b);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:y}),kind:"success",category:"reorder",affectedIds:l,folder:m}),this.plugin.getUndoStack(m).push({label:`Reorder (drag, ${l.length})`,undo:async()=>{if(v.length===0){let b=this.order.cache.get(m)??{};delete b[a],this.order.cache.set(m,b)}else this.order.setOrder(m,a,v);await this.order.save(m),await this.log.append({type:"reorder",id:a,payload:{dir:"undo",parent:a,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(m),this.render()},redo:async()=>{this.order.setOrder(m,a,f),await this.order.save(m),await this.log.append({type:"reorder",id:a,payload:{dir:"redo:drag",parent:a,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(m),this.render()}})}cmdMoveUp(){this.reorderSelection("up")}cmdMoveDown(){this.reorderSelection("down")}cmdMoveToTop(){this.reorderSelection("top")}cmdMoveToBottom(){this.reorderSelection("bottom")}async reorderSelection(t){let e=[];if(this.selection.size>0){let p=[...this.selection].map(d=>this.tree.get(d)).filter(d=>!!d&&!!d.file);if(p.length===0)return;if(new Set(p.map(d=>d.parent)).size>1){new O.Notice("Reorder requires a single-parent selection.");return}e=p}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new O.Notice("Nothing to reorder.");return}let s=e[0].parent??R,i=this.tree.getChildren(s).map(p=>p.id);if(i.length===0)return;let n=new Set(e.map(p=>p.id)),r=i.filter(p=>n.has(p));if(r.length===0)return;let o=on(i,r,t);if(Ci(o,i))return;let a=this.noteFolder,l=this.order.getOrder(a,s).slice();this.order.setOrder(a,s,o),await this.order.save(a),await this.forceManualMode(s),await this.log.append({type:"reorder",id:s,payload:{dir:t,parent:s,ids:r,count:r.length}}),this.pendingFocusIds=r.slice(),this.tree.rebuild(a),this.render({kind:"follow-cursor"});let c=r.map(p=>this.tree.get(p)).filter(p=>!!p);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:c,destination:t}),kind:"success",category:"reorder",affectedIds:r,folder:a}),this.plugin.getUndoStack(a).push({label:`Reorder (${t})`,undo:async()=>{if(l.length===0){let p=this.order.cache.get(a)??{};delete p[s],this.order.cache.set(a,p)}else this.order.setOrder(a,s,l);await this.order.save(a),await this.log.append({type:"reorder",id:s,payload:{dir:"undo",parent:s,ids:r,count:r.length}}),this.pendingFocusIds=r.slice(),this.tree.rebuild(a),this.render()},redo:async()=>{this.order.setOrder(a,s,o),await this.order.save(a),await this.log.append({type:"reorder",id:s,payload:{dir:`redo:${t}`,parent:s,ids:r,count:r.length}}),this.pendingFocusIds=r.slice(),this.tree.rebuild(a),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let f=this.tree.get(this.focusId);f?.file&&(t=[f])}if(t.length===0){new O.Notice("Nothing selected to delete.");return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],s=new Set,i=f=>{if(!s.has(f.id)){s.add(f.id);for(let m of this.tree.getChildren(f.id))i(m);e.push(f)}};for(let f of t)i(f);let n=e.filter(f=>!!f.file),r=await Promise.all(n.map(f=>this.app.vault.read(f.file))),o=[];for(let f=0;f<n.length;f++){let m=n[f];o.push(...this.extractAttachments(this.stripFrontmatter(r[f])));let v=this.app.metadataCache.getFileCache(m.file)?.frontmatter;if(Array.isArray(v?.attachments))for(let y of v.attachments)typeof y=="string"&&y.trim()&&o.push(y)}let a=[...new Set(o)],l=e.length-t.length,c=async f=>{let m=await this.snapshotNotes(e,f),v=0;if(f)for(let _ of a){let J=this.app.metadataCache.getFirstLinkpathDest(_,"");if(J)try{await this.app.fileManager.trashFile(J),await this.log.append({type:"attachment_remove",id:R,payload:{path:J.path}}),this.plugin.notifications.show({message:`Deleted attachment "${J.name}"`,kind:"warning",category:"attachment",affectedPaths:[J.path],folder:this.noteFolder}),v+=1}catch{}}let y=new Set;for(let _ of e)_.parent&&y.add(_.parent);let b=this.collectAuthorIds(e),k=new Set(t.map(_=>_.id)),C=this.currentChildren.map((_,J)=>k.has(_.id)?J:-1).filter(_=>_>=0),I=C.length>0?C[0]:-1,E=null;if(I>=0){for(let _=I+1;_<this.currentChildren.length;_++)if(!k.has(this.currentChildren[_].id)){E=this.currentChildren[_].id;break}if(!E){for(let _=I-1;_>=0;_--)if(!k.has(this.currentChildren[_].id)){E=this.currentChildren[_].id;break}}}for(let _ of e)if(_.file){try{await this.app.fileManager.trashFile(_.file)}catch{}await this.log.append({type:"delete",id:_.id,payload:{path:_.file.path,attachmentsRemoved:f?a:[]}})}this.selection.clear(),this.cursorIdx=-1,E&&(this.pendingFocusIds=[E]),this.tree.rebuild(this.noteFolder);for(let _ of y)e.some(J=>J.id===_)||this.fmSync.scheduleParentOfDeleted(_);this.render({kind:"follow-cursor"});let D=v>0?` with ${v} attachment${v===1?"":"s"}`:"",H=this.noteFolder,T=t.map(_=>_.id),A=!1,S=async()=>{A||(A=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(m,T.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:D.trim()||void 0}),kind:"warning",category:"delete",duration:0,affectedIds:t.map(_=>_.id),affectedAuthorIds:b,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void S()}]}),this.plugin.getUndoStack(H).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await S()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,A=!1,await this.trashNotesAndAttachments(m)}}),this.focusView()},p=bt(),u=p.confirmBulkDelete,d=a.length>0&&p.confirmAttachmentDelete;if(!u&&!d){await c(!1);return}new te(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,a.length,d,c).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new O.Notice("Pick a note to split.");return}let s=e.file,i=await this.app.vault.read(s),n=this.stripFrontmatter(i).replace(/\s+$/,""),r=n.split(/\r?\n/);if(n.trim().length<2){new O.Notice("Note is too short to split.");return}let o=i,a=s.path,l=async(c,p,u)=>{if(!c.trim()||!p.trim()){new O.Notice("Split would leave one part empty.");return}try{let d=i.startsWith("---")?i.slice(0,i.indexOf(` ----`,3)+4):"",f=d+(d?` +`);return this.app.vault.create(e,n)}buildHomeFilename(t){return`Home-${(t.split("/").filter(Boolean).pop()??"Stashpad").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"Stashpad"}.md`}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(s=>s.path.startsWith(t+"/"));for(let s of e){let i=this.app.metadataCache.getFileCache(s)?.frontmatter,n=i?.id;if(!n||n===R)continue;let r=i?.parent;(r==null||r===""||r==="null")&&(await this.app.fileManager.processFrontMatter(s,a=>{a.parent=R}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:R,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,s=this.leaf,i=e.getLeaf("tab");await i.setViewState({type:mt,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i);let n=e.on("active-leaf-change",()=>{if((()=>{let o=!1;return e.iterateAllLeaves(l=>{l===i&&(o=!0)}),o})())return;e.offref(n),(()=>{let o=!1;return e.iterateAllLeaves(l=>{l===s&&(o=!0)}),o})()&&(e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s))})}async openFolderInNewTab(t){let e=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!e)return;let s=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",i=this.app.workspace,n=this.leaf,r=i.getLeaf("tab");await r.setViewState({type:mt,active:!0,state:{focusId:R,folderOverride:e===s?null:e}}),i.setActiveLeaf(r,{focus:!0}),i.revealLeaf(r);let a=i.on("active-leaf-change",()=>{if((()=>{let c=!1;return i.iterateAllLeaves(p=>{p===r&&(c=!0)}),c})())return;i.offref(a),(()=>{let c=!1;return i.iterateAllLeaves(p=>{p===n&&(c=!0)}),c})()&&(i.setActiveLeaf(n,{focus:!0}),i.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let s of e)s.file&&this.openFileAtEnd(s.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new O.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,s=this.leaf,i=e.getLeaf("tab");await i.openFile(t,{active:!0}),e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i);let n=e.on("active-leaf-change",()=>{if((()=>{let c=!1;return e.iterateAllLeaves(p=>{p===i&&(c=!0)}),c})())return;e.offref(n),(()=>{let c=!1;return e.iterateAllLeaves(p=>{p===s&&(c=!0)}),c})()&&(e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s))}),a=i.view?.editor;a&&requestAnimationFrame(()=>{try{let o=a.lastLine(),l=a.getLine(o)?.length??0;a.setCursor({line:o,ch:l}),a.scrollIntoView({from:{line:o,ch:l},to:{line:o,ch:l}},!0),a.focus()}catch{}})}cmdSelectAll(){if(this.currentChildren.length!==0){this.selection.clear();for(let t of this.currentChildren)this.selection.add(t.id);this.firstSelectedId=this.currentChildren[0].id,this.lastSelected=this.currentChildren[this.currentChildren.length-1].id,this.cursorIdx=this.currentChildren.length-1,this.render()}}async cmdTogglePin(){let t=this.getActionTargets();if(t.length===0){let n=this.tree.get(this.focusId);n?.file&&(t=[n])}if(t.length===0){new O.Notice("Nothing to pin.");return}let e=t.some(n=>!this.plugin.isPinned({folder:this.noteFolder,id:n.id})),s=0,i=0;for(let n of t){let r={folder:this.noteFolder,id:n.id};e?this.plugin.isPinned(r)||(await this.plugin.pinNote(r),s++):this.plugin.isPinned(r)&&(await this.plugin.unpinNote(r),i++)}s>0?new O.Notice(`Pinned ${s} note${s===1?"":"s"} to sidebar.`):i>0&&new O.Notice(`Unpinned ${i} note${i===1?"":"s"} from sidebar.`)}async cmdToggleComplete(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new O.Notice("Nothing to toggle.");return}let s=t.some(a=>!this.isCompleted(a)),i=[],n=[];for(let a of t){if(!a.file)continue;let o=this.isCompleted(a);i.push({id:a.id,path:a.file.path,was:o}),o!==s&&(await this.app.fileManager.processFrontMatter(a.file,l=>{s?l.completed=!0:delete l.completed}),this.completedState.set(a.file.path,s),n.push(a.id))}if(this.render(),n.length>0){await this.log.append({type:s?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length}});let a=n.map(o=>this.tree.get(o)).filter(o=>!!o);this.plugin.notifications.show({message:this.bulkActionMessage({verb:s?"Marked complete":"Unmarked",nodes:a}),kind:"success",category:s?"complete":"uncomplete",affectedIds:n,folder:this.noteFolder})}let r=this.noteFolder;this.plugin.getUndoStack(r).push({label:`${s?"Mark complete":"Unmark complete"} (${t.length})`,undo:async()=>{let a=[];for(let o of i){let l=this.app.vault.getAbstractFileByPath(o.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{o.was?c.completed=!0:delete c.completed}),n.includes(o.id)&&a.push(o.id))}a.length>0&&await this.log.append({type:s?"uncomplete":"complete",id:a[0],payload:{ids:a,count:a.length,undo:!0}}),this.tree.rebuild(r),this.render()},redo:async()=>{for(let a of i){let o=this.app.vault.getAbstractFileByPath(a.path);o&&await this.app.fileManager.processFrontMatter(o,l=>{s?l.completed=!0:delete l.completed})}n.length>0&&await this.log.append({type:s?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(r),this.render()}})}isCompleted(t){if(!t.file)return!1;let e=this.completedState.get(t.file.path);return e!==void 0?e:!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed}cmdSetDue(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new O.Notice("Nothing to schedule.");return}let e=t[0],s=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,i=s&&(typeof s.due=="string"||typeof s.due=="number")?String(s.due):null,n=this.plugin.authorRegistry.all().map(a=>({id:a.id,name:a.name})),r=be(s??{});new Ce(this.app,i,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:r}).open()}async applyDue(t,e,s=[]){let i=[],n=[],r=this.currentAuthorLink();for(let l of s)await this.plugin.ensureAuthorStubFor(this.noteFolder,l.id,l.name);let a=s.map(l=>this.plugin.authorRefFor(this.noteFolder,l.id,l.name));for(let l of t){if(!l.file)continue;let c=this.app.metadataCache.getFileCache(l.file)?.frontmatter;i.push({id:l.id,path:l.file.path,due:c?.due,task:c?.task,assignedTo:c?.assignedTo,assignedBy:c?.assignedBy}),await this.app.fileManager.processFrontMatter(l.file,p=>{e===null?delete p.due:(p.due=e,p.task=!0),a.length>0?(p.assignedTo=a,r&&(p.assignedBy=r.link),p.task=!0):(delete p.assignedTo,delete p.assignedBy)}),n.push(l.id)}if(this.render(),n.length>0){let l=n.map(c=>this.tree.get(c)).filter(c=>!!c);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${Kt(Date.parse(e),this.plugin.settings)}`,nodes:l}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let o=this.noteFolder;this.plugin.getUndoStack(o).push({label:e===null?`Clear due date (${t.length})`:`Set due date (${t.length})`,undo:async()=>{for(let l of i){let c=this.app.vault.getAbstractFileByPath(l.path);c&&await this.app.fileManager.processFrontMatter(c,p=>{l.due===void 0?delete p.due:p.due=l.due,l.task===void 0?delete p.task:p.task=l.task,l.assignedTo===void 0?delete p.assignedTo:p.assignedTo=l.assignedTo,l.assignedBy===void 0?delete p.assignedBy:p.assignedBy=l.assignedBy})}this.tree.rebuild(o),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new O.Notice("Nothing to assign.");return}let e=t[0],s=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,i=this.plugin.authorRegistry.all().map(r=>({id:r.id,name:r.name})),n=be(s??{});new Te(this.app,{knownAuthors:i,currentAssignees:n},r=>{this.applyAssignees(t,r)}).open()}async applyAssignees(t,e){let s=this.currentAuthorLink();for(let o of e)await this.plugin.ensureAuthorStubFor(this.noteFolder,o.id,o.name);let i=e.map(o=>this.plugin.authorRefFor(this.noteFolder,o.id,o.name)),n=[],r=[];for(let o of t){if(!o.file)continue;let l=this.app.metadataCache.getFileCache(o.file)?.frontmatter;n.push({path:o.file.path,assignedTo:l?.assignedTo,assignedBy:l?.assignedBy,task:l?.task}),await this.app.fileManager.processFrontMatter(o.file,c=>{i.length>0?(c.assignedTo=i,s&&(c.assignedBy=s.link),c.task=!0):(delete c.assignedTo,delete c.assignedBy)}),r.push(o.id)}if(this.render(),r.length>0){let o=r.map(c=>this.tree.get(c)).filter(c=>!!c),l=e.map(c=>c.name).join(", ");this.plugin.notifications.show({message:this.bulkActionMessage({verb:i.length>0?`Assigned to ${l}`:"Cleared assignment",nodes:o}),kind:"success",category:"edit",affectedIds:r,folder:this.noteFolder})}let a=this.noteFolder;this.plugin.getUndoStack(a).push({label:i.length>0?`Assign (${t.length})`:`Clear assignment (${t.length})`,undo:async()=>{for(let o of n){let l=this.app.vault.getAbstractFileByPath(o.path);l&&await this.app.fileManager.processFrontMatter(l,c=>{o.assignedTo===void 0?delete c.assignedTo:c.assignedTo=o.assignedTo,o.assignedBy===void 0?delete c.assignedBy:c.assignedBy=o.assignedBy,o.task===void 0?delete c.task:c.task=o.task})}this.tree.rebuild(a),this.render()}})}isTask(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return e?Yt(e,"task")||e.task===!0||e.completed!==void 0:!1}async cmdToggleTask(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new O.Notice("Nothing to toggle.");return}let e=t.some(a=>!this.isTaskTagged(a)),s=[],i=[];for(let a of t){if(!a.file)continue;let o=this.isTaskTagged(a),l=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(s.push({id:a.id,path:a.file.path,tags:l?.tags,completed:l?.completed,task:l?.task}),o===e)continue;let c=!1;await this.app.fileManager.processFrontMatter(a.file,p=>{e?(Fs(p,"task"),p.completed===void 0&&(p.completed=!1),c=p.completed===!0,delete p.task):(xs(p,"task"),delete p.completed,delete p.task,c=!1)}),this.completedState.set(a.file.path,c),i.push(a.id)}if(this.render(),i.length>0){let a=e?"marked as task":"unmarked as task",o;if(i.length===1){let l=this.tree.get(i[0]);o=`"${l&&this.titleForNode(l).trim()||"(untitled)"}" ${a}`}else o=`${i.length} notes ${a}`;this.plugin.notifications.show({message:o,kind:"success",category:"edit",affectedIds:i,folder:this.noteFolder})}let n=this.noteFolder,r=async()=>{for(let a of s){let o=this.app.vault.getAbstractFileByPath(a.path);o&&await this.app.fileManager.processFrontMatter(o,l=>{a.tags===void 0?delete l.tags:l.tags=a.tags,a.completed===void 0?delete l.completed:l.completed=a.completed,a.task===void 0?delete l.task:l.task=a.task})}this.tree.rebuild(n),this.render()};this.plugin.getUndoStack(n).push({label:`${e?"Mark task":"Unmark task"} (${t.length})`,undo:r,redo:async()=>{for(let a of s){let o=this.app.vault.getAbstractFileByPath(a.path);o&&await this.app.fileManager.processFrontMatter(o,l=>{e?(Fs(l,"task"),l.completed===void 0&&(l.completed=!1),delete l.task):(xs(l,"task"),delete l.completed,delete l.task)})}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,s=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!s}),this.completedState.set(e,!s),await this.log.append({type:s?"uncomplete":"complete",id:t.id}),this.render();let i=this.noteFolder;this.plugin.getUndoStack(i).push({label:s?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,r=>{r.completed=s}),this.tree.rebuild(i),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return e?Yt(e,"task")||e.task===!0:!1}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let s=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s)?s:null}inheritedColorForNode(t){let e=t,s=0,i=new Set;for(;e&&e.id!==R&&!i.has(e.id);){i.add(e.id);let n=this.colorForNode(e);if(n)return{hex:n,depth:s};e=e.parent?this.tree.get(e.parent):void 0,s+=1}return null}attachRowDnD(t,e,s){t.addEventListener("dragstart",i=>{let n=this.selection.has(e.id)&&this.selection.size>1?[...this.selection]:[e.id];if(this.dragSourceIds=n,this.dragRowHeight=t.offsetHeight,t.addClass("is-dragging"),this.listEl&&(this.dragPlaceholder=this.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.style.height="0px",this.dragPlaceholder.addEventListener("dragover",r=>{this.dragSourceIds&&(r.preventDefault(),r.dataTransfer&&(r.dataTransfer.dropEffect="move"))}),this.dragPlaceholder.addEventListener("drop",r=>{if(!this.dragSourceIds||!this.dragPlaceholder)return;r.preventDefault(),r.stopPropagation();let a=this.dragSourceIds.slice();this.dragSourceIds=null;let o=this.dragPlaceholder.nextElementSibling,l=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let c,p="before";o&&o.classList.contains("stashpad-note")?(c=o.dataset.id,p="before"):l&&l.classList.contains("stashpad-note")&&(c=l.dataset.id,p="after"),c&&this.reorderToTarget(a,c,p)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",n.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(t,12,12)}catch{}}}),t.addEventListener("dragend",()=>{t.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),t.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let n=this.dropZone(i,t);this.clearDropIndicators(),n==="drop-into"?(this.removeDragPlaceholder(),t.addClass("drop-into")):(t.removeClass("drop-into"),this.placePlaceholder(t,n==="drop-above"?"before":"after"))}),t.addEventListener("dragleave",i=>{let n=t.getBoundingClientRect();(i.clientX<n.left||i.clientX>n.right||i.clientY<n.top||i.clientY>n.bottom)&&t.removeClass("drop-into")}),t.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let n=this.dragSourceIds.slice();this.dragSourceIds=null;let r=this.dropZone(i,t);this.clearDropIndicators(),this.removeDragPlaceholder(),t.removeClass("is-dragging"),r==="drop-into"?this.reorderToTarget(n,e.id,"into"):this.reorderToTarget(n,e.id,r==="drop-above"?"before":"after")})}placePlaceholder(t,e){if(!this.dragPlaceholder||!this.listEl)return;let s=e==="before"?t:t.nextSibling;if(e==="before"&&this.dragPlaceholder.nextSibling===t||e==="after"&&this.dragPlaceholder.previousSibling===t)return;let i=!!this.dragPlaceholder.parentElement;this.listEl.insertBefore(this.dragPlaceholder,s),this.dragPlaceholder.style.opacity="1",i?this.dragPlaceholder.style.height=`${this.dragRowHeight}px`:(this.dragPlaceholder.style.height="0px",this.dragPlaceholder.offsetHeight,this.dragPlaceholder.style.height=`${this.dragRowHeight}px`)}removeDragPlaceholder(){if(!this.dragPlaceholder?.parentElement)return;let t=this.dragPlaceholder;t.style.height="0px",t.style.opacity="0",setTimeout(()=>{t.parentElement&&t.remove()},150)}dropZone(t,e){let s=e.getBoundingClientRect(),i=t.clientY-s.top;return i<s.height*.3?"drop-above":i>s.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.listEl)for(let t of Array.from(this.listEl.querySelectorAll(".drop-into")))t.removeClass("drop-into")}isDescendant(t,e){let s=this.tree.get(t),i=new Set;for(;s&&s.parent&&!i.has(s.id);){if(s.parent===e)return!0;i.add(s.id),s=this.tree.get(s.parent)}return!1}async moveAcrossThenReorder(t,e,s,i){let n=[],r=new Set;for(let D of t){let H=this.tree.get(D);H?.file&&(n.push({id:D,path:H.file.path,oldParent:H.parent}),r.add(H.parent??R))}r.add(e);let a=this.collectAuthorIds(t.map(D=>this.tree.get(D)).filter(D=>!!D)),o=this.noteFolder,l={};for(let D of r)l[D]=this.order.getOrder(o,D).slice();for(let D of n){let H=this.app.vault.getAbstractFileByPath(D.path);H&&(await this.app.fileManager.processFrontMatter(H,C=>{C.parent=e}),this.fmSync.scheduleParentChange(D.id,D.oldParent,e),await this.log.append({type:"parent_change",id:D.id,payload:{from:D.oldParent,to:e,reason:"drag"}}),this.order.removeChild(o,D.id))}this.tree.rebuild(o);let c=this.tree.getChildren(e).map(D=>D.id),p=new Set(t),u=c.filter(D=>!p.has(D)),h=u.indexOf(s);h<0&&(h=u.length),i==="after"&&(h+=1);let f=[...u.slice(0,h),...t.filter(D=>!!this.tree.get(D)),...u.slice(h)];this.order.setOrder(o,e,f),await this.order.save(o),await this.forceManualMode(e),await this.log.append({type:"reorder",id:e,payload:{dir:"drag-cross",parent:e,ids:t,count:t.length}});let m=this.focusId===e,v=m?t[0]:e,y=m?t.slice():[e];m?this.pendingFocusIds=y:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=y),this.tree.rebuild(o),this.render({kind:"follow-cursor"});let b=this.selectionGuardKey,k=()=>{if(this.selectionGuardKey!==b||this.selection.has(v))return;let D=this.currentChildren.findIndex(H=>H.id===v);D<0||(this.selection.add(v),this.cursorIdx=D,this.render({kind:"follow-cursor"}))};setTimeout(k,120),setTimeout(k,400);let T=t.map(D=>this.tree.get(D)).filter(D=>!!D),I=this.tree.get(e),E=I?this.titleForNode(I):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:T,destination:`\u2192 "${E}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:o,actions:e===R?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(o).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let D of n){let H=this.app.vault.getAbstractFileByPath(D.path);H&&(await this.app.fileManager.processFrontMatter(H,C=>{D.oldParent===null||D.oldParent===void 0?C.parent=R:C.parent=D.oldParent}),await this.log.append({type:"parent_change",id:D.id,payload:{from:e,to:D.oldParent,reason:"drag-undo"}}))}for(let[D,H]of Object.entries(l))if(H.length===0){let C=this.order.cache.get(o)??{};delete C[D],this.order.cache.set(o,C)}else this.order.setOrder(o,D,H);await this.order.save(o),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(o),this.render()},redo:async()=>{for(let D of n){let H=this.app.vault.getAbstractFileByPath(D.path);H&&(await this.app.fileManager.processFrontMatter(H,C=>{C.parent=e}),this.order.removeChild(o,D.id))}this.order.setOrder(o,e,f),await this.order.save(o),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(o),this.render()}})}async reorderToTarget(t,e,s){let i=this.tree.get(e);if(!i)return;let n=t.map(b=>this.tree.get(b)).filter(b=>!!b&&!!b.file);if(n.length===0)return;if(n.some(b=>b.id===e)){this.plugin.notifications.show({message:"Can't move a note into itself.",kind:"warning",category:"move",folder:this.noteFolder});return}if(s==="into"){for(let b of n)if(this.isDescendant(e,b.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(b)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",folder:this.noteFolder});return}}let r=s==="into"?e:i.parent??R;if(n.some(b=>(b.parent??R)!==r)){let b=St(),k=async()=>{s==="into"?await this.moveAcrossThenReorder(n.map(T=>T.id),r,"","after"):await this.moveAcrossThenReorder(n.map(T=>T.id),r,e,s)};if(b.confirmCrossParentDrag){let T=this.titleForNode(i),I=n.length,E=s==="into"?"Nest":"Move",D=s==="into"?"as children of":"under";new At(this.app,s==="into"?"Nest under target?":"Move under different parent?",`${E} ${I} note${I===1?"":"s"} ${D} "${T}"? Their parent will change.`,E,H=>{H&&k()}).open()}else await k();return}let o=r,l=n.map(b=>b.id),c=this.tree.getChildren(o).map(b=>b.id),p=new Set(l),u=c.filter(b=>!p.has(b)),h=u.indexOf(e);if(h<0)return;s==="after"&&(h+=1);let f=[...u.slice(0,h),...l,...u.slice(h)];if(Ai(f,c))return;let m=this.noteFolder,v=this.order.getOrder(m,o).slice();this.order.setOrder(m,o,f),await this.order.save(m),await this.forceManualMode(o),await this.log.append({type:"reorder",id:o,payload:{dir:"drag",parent:o,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(m),this.render();let y=l.map(b=>this.tree.get(b)).filter(b=>!!b);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:y}),kind:"success",category:"reorder",affectedIds:l,folder:m}),this.plugin.getUndoStack(m).push({label:`Reorder (drag, ${l.length})`,undo:async()=>{if(v.length===0){let b=this.order.cache.get(m)??{};delete b[o],this.order.cache.set(m,b)}else this.order.setOrder(m,o,v);await this.order.save(m),await this.log.append({type:"reorder",id:o,payload:{dir:"undo",parent:o,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(m),this.render()},redo:async()=>{this.order.setOrder(m,o,f),await this.order.save(m),await this.log.append({type:"reorder",id:o,payload:{dir:"redo:drag",parent:o,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(m),this.render()}})}cmdMoveUp(){this.reorderSelection("up")}cmdMoveDown(){this.reorderSelection("down")}cmdMoveToTop(){this.reorderSelection("top")}cmdMoveToBottom(){this.reorderSelection("bottom")}async reorderSelection(t){let e=[];if(this.selection.size>0){let p=[...this.selection].map(h=>this.tree.get(h)).filter(h=>!!h&&!!h.file);if(p.length===0)return;if(new Set(p.map(h=>h.parent)).size>1){new O.Notice("Reorder requires a single-parent selection.");return}e=p}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new O.Notice("Nothing to reorder.");return}let s=e[0].parent??R,i=this.tree.getChildren(s).map(p=>p.id);if(i.length===0)return;let n=new Set(e.map(p=>p.id)),r=i.filter(p=>n.has(p));if(r.length===0)return;let a=un(i,r,t);if(Ai(a,i))return;let o=this.noteFolder,l=this.order.getOrder(o,s).slice();this.order.setOrder(o,s,a),await this.order.save(o),await this.forceManualMode(s),await this.log.append({type:"reorder",id:s,payload:{dir:t,parent:s,ids:r,count:r.length}}),this.pendingFocusIds=r.slice(),this.tree.rebuild(o),this.render({kind:"follow-cursor"});let c=r.map(p=>this.tree.get(p)).filter(p=>!!p);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:c,destination:t}),kind:"success",category:"reorder",affectedIds:r,folder:o}),this.plugin.getUndoStack(o).push({label:`Reorder (${t})`,undo:async()=>{if(l.length===0){let p=this.order.cache.get(o)??{};delete p[s],this.order.cache.set(o,p)}else this.order.setOrder(o,s,l);await this.order.save(o),await this.log.append({type:"reorder",id:s,payload:{dir:"undo",parent:s,ids:r,count:r.length}}),this.pendingFocusIds=r.slice(),this.tree.rebuild(o),this.render()},redo:async()=>{this.order.setOrder(o,s,a),await this.order.save(o),await this.log.append({type:"reorder",id:s,payload:{dir:`redo:${t}`,parent:s,ids:r,count:r.length}}),this.pendingFocusIds=r.slice(),this.tree.rebuild(o),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let f=this.tree.get(this.focusId);f?.file&&(t=[f])}if(t.length===0){new O.Notice("Nothing selected to delete.");return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],s=new Set,i=f=>{if(!s.has(f.id)){s.add(f.id);for(let m of this.tree.getChildren(f.id))i(m);e.push(f)}};for(let f of t)i(f);let n=e.filter(f=>!!f.file),r=await Promise.all(n.map(f=>this.app.vault.read(f.file))),a=[];for(let f=0;f<n.length;f++){let m=n[f];a.push(...this.extractAttachments(this.stripFrontmatter(r[f])));let v=this.app.metadataCache.getFileCache(m.file)?.frontmatter;if(Array.isArray(v?.attachments))for(let y of v.attachments)typeof y=="string"&&y.trim()&&a.push(se(y))}let o=[...new Set(a)],l=e.length-t.length,c=async f=>{let m=await this.snapshotNotes(e,f),v=0;if(f)for(let _ of o){let J=this.app.metadataCache.getFirstLinkpathDest(_,"");if(J)try{await this.app.fileManager.trashFile(J),await this.log.append({type:"attachment_remove",id:R,payload:{path:J.path}}),this.plugin.notifications.show({message:`Deleted attachment "${J.name}"`,kind:"warning",category:"attachment",affectedPaths:[J.path],folder:this.noteFolder}),v+=1}catch{}}let y=new Set;for(let _ of e)_.parent&&y.add(_.parent);let b=this.collectAuthorIds(e),k=new Set(t.map(_=>_.id)),T=this.currentChildren.map((_,J)=>k.has(_.id)?J:-1).filter(_=>_>=0),I=T.length>0?T[0]:-1,E=null;if(I>=0){for(let _=I+1;_<this.currentChildren.length;_++)if(!k.has(this.currentChildren[_].id)){E=this.currentChildren[_].id;break}if(!E){for(let _=I-1;_>=0;_--)if(!k.has(this.currentChildren[_].id)){E=this.currentChildren[_].id;break}}}for(let _ of e)if(_.file){try{await this.app.fileManager.trashFile(_.file)}catch{}await this.log.append({type:"delete",id:_.id,payload:{path:_.file.path,attachmentsRemoved:f?o:[]}})}this.selection.clear(),this.cursorIdx=-1,E&&(this.pendingFocusIds=[E]),this.tree.rebuild(this.noteFolder);for(let _ of y)e.some(J=>J.id===_)||this.fmSync.scheduleParentOfDeleted(_);this.render({kind:"follow-cursor"});let D=v>0?` with ${v} attachment${v===1?"":"s"}`:"",H=this.noteFolder,C=t.map(_=>_.id),A=!1,S=async()=>{A||(A=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(m,C.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:D.trim()||void 0}),kind:"warning",category:"delete",duration:0,affectedIds:t.map(_=>_.id),affectedAuthorIds:b,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void S()}]}),this.plugin.getUndoStack(H).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await S()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,A=!1,await this.trashNotesAndAttachments(m)}}),this.focusView()},p=St(),u=p.confirmBulkDelete,h=o.length>0&&p.confirmAttachmentDelete;if(!u&&!h){await c(!1);return}new ne(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,o.length,h,c).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new O.Notice("Pick a note to split.");return}let s=e.file,i=await this.app.vault.read(s),n=this.stripFrontmatter(i).replace(/\s+$/,""),r=n.split(/\r?\n/);if(n.trim().length<2){new O.Notice("Note is too short to split.");return}let a=i,o=s.path,l=async(c,p,u)=>{if(!c.trim()||!p.trim()){new O.Notice("Split would leave one part empty.");return}try{let h=i.startsWith("---")?i.slice(0,i.indexOf(` +---`,3)+4):"",f=h+(h?` `:"")+c+` -`;await this.app.vault.modify(s,f);let m=e.parent??R,v=Date.parse(e.created||""),y=Number.isFinite(v)?new Date(v+1).toISOString():new Date().toISOString(),b=await this.createNoteUnder(p,m,{record:!1,createdOverride:y});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:b,...u}}),this.tree.rebuild(this.noteFolder),this.render(),this.suppressComposerFocusUntil=Date.now()+500,this.viewRoot?.focus({preventScroll:!0}),this.plugin.notifications.show({message:`Split "${this.titleForNode(e)}" into two`,kind:"success",category:"split",affectedIds:[e.id],folder:this.noteFolder});let k=b?this.tree.get(b):void 0,C=k?.file?.path,I=C?await this.app.vault.read(k.file):null,E=this.noteFolder;this.plugin.getUndoStack(E).push({label:"Split note",undo:async()=>{if(C){let H=this.app.vault.getAbstractFileByPath(C);if(H)try{await this.app.fileManager.trashFile(H)}catch{}}let D=this.app.vault.getAbstractFileByPath(a);D&&await this.app.vault.modify(D,o),this.tree.rebuild(E),this.render()},redo:async()=>{let D=this.app.vault.getAbstractFileByPath(a);D&&await this.app.vault.modify(D,f),C&&I&&!await this.app.vault.adapter.exists(C)&&await this.app.vault.create(C,I),this.tree.rebuild(E),this.render()}})}catch(d){new O.Notice(`Stashpad: split failed (${d.message})`),console.error(d)}};new me(this.app,n,async c=>{let p=r.slice(0,c).join(` +`;await this.app.vault.modify(s,f);let m=e.parent??R,v=Date.parse(e.created||""),y=Number.isFinite(v)?new Date(v+1).toISOString():new Date().toISOString(),b=await this.createNoteUnder(p,m,{record:!1,createdOverride:y});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:b,...u}}),this.tree.rebuild(this.noteFolder),this.render(),this.suppressComposerFocusUntil=Date.now()+500,this.viewRoot?.focus({preventScroll:!0}),this.plugin.notifications.show({message:`Split "${this.titleForNode(e)}" into two`,kind:"success",category:"split",affectedIds:[e.id],folder:this.noteFolder});let k=b?this.tree.get(b):void 0,T=k?.file?.path,I=T?await this.app.vault.read(k.file):null,E=this.noteFolder;this.plugin.getUndoStack(E).push({label:"Split note",undo:async()=>{if(T){let H=this.app.vault.getAbstractFileByPath(T);if(H)try{await this.app.fileManager.trashFile(H)}catch{}}let D=this.app.vault.getAbstractFileByPath(o);D&&await this.app.vault.modify(D,a),this.tree.rebuild(E),this.render()},redo:async()=>{let D=this.app.vault.getAbstractFileByPath(o);D&&await this.app.vault.modify(D,f),T&&I&&!await this.app.vault.adapter.exists(T)&&await this.app.vault.create(T,I),this.tree.rebuild(E),this.render()}})}catch(h){new O.Notice(`Stashpad: split failed (${h.message})`),console.error(h)}};new ke(this.app,n,async c=>{let p=r.slice(0,c).join(` `).replace(/\s+$/,""),u=r.slice(c).join(` -`).replace(/^\s+|\s+$/g,"");await l(p,u,{mode:"line",splitAtLine:c})},async c=>{let p=n.slice(0,c).replace(/\s+$/,""),u=n.slice(c).replace(/^\s+|\s+$/g,"");await l(p,u,{mode:"cursor",splitAtChar:c})}).open()}cmdOpenInNewStashpadTab(t){let e=t??this.resolveActionTarget();e?.file&&this.openInNewStashpadTab(e.id)}cmdCloneStashpadTab(){let t=this.tree.get(this.focusId);t?.file?this.cmdOpenInNewStashpadTab(t):this.openInNewStashpadTab(this.focusId)}resolveActionTarget(){if(this.cursorIdx>=0&&this.currentChildren[this.cursorIdx])return this.currentChildren[this.cursorIdx];let t=this.tree.get(this.focusId);return t?.file?t:void 0}async cmdExportStash(t){let e=this.collectExportRoots(t);if(e.length===0){new O.Notice("Nothing to export.");return}let s=this.collectExportSubtree(e);if(s.length===0){new O.Notice("No exportable notes (no files attached).");return}try{let i=await ki(this.app,{rootNotes:e.filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),allDescendants:s.filter(u=>!e.some(d=>d.id===u.id)).filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),sourceFolder:this.noteFolder}),n=(0,O.moment)().format("YYYYMMDD-HHmmss"),r=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),a=(e.length===1?this.titleForNode(e[0]):`${r}-${e.length}notes`).replace(/[^\w.\-]+/g,"_").slice(0,60)||"stash-export",l=(this.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${this.noteFolder}/${l}`;await this.ensureFolder(c);let p=`${c}/${a}-${n}.${Gt}`;await this.app.vault.createBinary(p,i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)),await this.log.append({type:"stash_export",id:e[0].id,payload:{path:p,noteCount:s.length,rootIds:e.map(u=>u.id)}}),this.plugin.notifications.show({message:`Exported ${s.length} note${s.length===1?"":"s"} \u2192 \`${p}\``,kind:"success",category:"export",affectedPaths:[p],folder:this.noteFolder,actions:this.actionsForFile(p),duration:0})}catch(i){this.plugin.notifications.show({message:`Stashpad: export failed +`).replace(/^\s+|\s+$/g,"");await l(p,u,{mode:"line",splitAtLine:c})},async c=>{let p=n.slice(0,c).replace(/\s+$/,""),u=n.slice(c).replace(/^\s+|\s+$/g,"");await l(p,u,{mode:"cursor",splitAtChar:c})}).open()}cmdOpenInNewStashpadTab(t){let e=t??this.resolveActionTarget();e?.file&&this.openInNewStashpadTab(e.id)}cmdCloneStashpadTab(){let t=this.tree.get(this.focusId);t?.file?this.cmdOpenInNewStashpadTab(t):this.openInNewStashpadTab(this.focusId)}resolveActionTarget(){if(this.cursorIdx>=0&&this.currentChildren[this.cursorIdx])return this.currentChildren[this.cursorIdx];let t=this.tree.get(this.focusId);return t?.file?t:void 0}async cmdExportStash(t){let e=this.collectExportRoots(t);if(e.length===0){new O.Notice("Nothing to export.");return}let s=this.collectExportSubtree(e);if(s.length===0){new O.Notice("No exportable notes (no files attached).");return}try{let i=await Ei(this.app,{rootNotes:e.filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),allDescendants:s.filter(u=>!e.some(h=>h.id===u.id)).filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),sourceFolder:this.noteFolder}),n=(0,O.moment)().format("YYYYMMDD-HHmmss"),r=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),o=(e.length===1?this.titleForNode(e[0]):`${r}-${e.length}notes`).replace(/[^\w.\-]+/g,"_").slice(0,60)||"stash-export",l=(this.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${this.noteFolder}/${l}`;await this.ensureFolder(c);let p=`${c}/${o}-${n}.${Qt}`;await this.app.vault.createBinary(p,i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)),await this.log.append({type:"stash_export",id:e[0].id,payload:{path:p,noteCount:s.length,rootIds:e.map(u=>u.id)}}),this.plugin.notifications.show({message:`Exported ${s.length} note${s.length===1?"":"s"} \u2192 \`${p}\``,kind:"success",category:"export",affectedPaths:[p],folder:this.noteFolder,actions:this.actionsForFile(p),duration:0})}catch(i){this.plugin.notifications.show({message:`Stashpad: export failed Error: ${i.message} -Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(i)}}collectExportRoots(t){if(t?.file)return[t];if(this.selection.size>0)return[...this.selection].map(s=>this.tree.get(s)).filter(s=>!!s?.file);if(this.cursorIdx>=0&&this.currentChildren[this.cursorIdx])return[this.currentChildren[this.cursorIdx]];let e=this.tree.get(this.focusId);return e?.file?[e]:[]}collectExportSubtree(t){let e=new Set,s=[],i=n=>{if(!e.has(n.id)){e.add(n.id),n.file&&s.push(n);for(let r of this.tree.getChildren(n.id))i(r)}};for(let n of t)i(n);return s}async cmdImportStash(){let t=this.app.vault.getFiles().filter(i=>i.extension===Gt);if(t.length===0){new O.Notice("No .stash files found in this vault.");return}let e=this,s=new class extends O.FuzzySuggestModal{getItems(){return t}getItemText(i){return i.path}onChooseItem(i){e.processStashFile(i)}}(this.app);s.setPlaceholder("Pick a .stash file to import\u2026"),s.open()}async processStashFile(t){try{let e=await this.app.vault.readBinary(t),s=await ls(this.app,new Uint8Array(e),this.noteFolder,this.collectExistingIds());this.tree.rebuild(this.noteFolder),this.render(),await this.log.append({type:"stash_import",id:R,payload:{from:t.path,into:this.noteFolder,noteCount:s.notesWritten,attachmentsWritten:s.attachmentsWritten,collisionsRenamed:s.collisionsRenamed}});try{await this.app.fileManager.trashFile(t)}catch{}let i=[`Imported ${s.notesWritten} note${s.notesWritten===1?"":"s"}`];s.attachmentsWritten&&i.push(`+ ${s.attachmentsWritten} attachment${s.attachmentsWritten===1?"":"s"}`),s.collisionsRenamed&&i.push(`(${s.collisionsRenamed} id collision${s.collisionsRenamed===1?"":"s"} renamed)`),this.plugin.notifications.show({message:i.join(" "),kind:"success",category:"import",folder:this.noteFolder})}catch(e){this.plugin.notifications.show({message:`Stashpad: import failed +Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(i)}}collectExportRoots(t){if(t?.file)return[t];if(this.selection.size>0)return[...this.selection].map(s=>this.tree.get(s)).filter(s=>!!s?.file);if(this.cursorIdx>=0&&this.currentChildren[this.cursorIdx])return[this.currentChildren[this.cursorIdx]];let e=this.tree.get(this.focusId);return e?.file?[e]:[]}collectExportSubtree(t){let e=new Set,s=[],i=n=>{if(!e.has(n.id)){e.add(n.id),n.file&&s.push(n);for(let r of this.tree.getChildren(n.id))i(r)}};for(let n of t)i(n);return s}async cmdImportStash(){let t=this.app.vault.getFiles().filter(i=>i.extension===Qt);if(t.length===0){new O.Notice("No .stash files found in this vault.");return}let e=this,s=new class extends O.FuzzySuggestModal{getItems(){return t}getItemText(i){return i.path}onChooseItem(i){e.processStashFile(i)}}(this.app);s.setPlaceholder("Pick a .stash file to import\u2026"),s.open()}async processStashFile(t){try{let e=await this.app.vault.readBinary(t),s=await ps(this.app,new Uint8Array(e),this.noteFolder,this.collectExistingIds());this.tree.rebuild(this.noteFolder),this.render(),await this.log.append({type:"stash_import",id:R,payload:{from:t.path,into:this.noteFolder,noteCount:s.notesWritten,attachmentsWritten:s.attachmentsWritten,collisionsRenamed:s.collisionsRenamed}});try{await this.app.fileManager.trashFile(t)}catch{}let i=[`Imported ${s.notesWritten} note${s.notesWritten===1?"":"s"}`];s.attachmentsWritten&&i.push(`+ ${s.attachmentsWritten} attachment${s.attachmentsWritten===1?"":"s"}`),s.collisionsRenamed&&i.push(`(${s.collisionsRenamed} id collision${s.collisionsRenamed===1?"":"s"} renamed)`),this.plugin.notifications.show({message:i.join(" "),kind:"success",category:"import",folder:this.noteFolder})}catch(e){this.plugin.notifications.show({message:`Stashpad: import failed File: \`${t.name}\` Error: ${e.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[t.path],actions:this.actionsForFile(t.path)}),console.error(e)}}collectExistingIds(){let t=new Set,e=s=>{if(t.add(s),!!this.tree.get(s))for(let n of this.tree.getChildren(s))e(n.id)};return e(R),t}async createNoteUnder(t,e,s={record:!0}){let i=(s.targetFolder??this.noteFolder).replace(/\/+$/,""),n=i!==this.noteFolder;await this.ensureFolder(i);let r=yt(),o=null;{let v=(this.plugin.settings.noteTemplates??{})[i];if(v){let y=this.app.vault.getAbstractFileByPath(v);if(y&&y.extension==="md")try{let b=await this.app.vault.cachedRead(y),k=this.stripFrontmatter(b);o=this.app.metadataCache.getFileCache(y)?.frontmatter??{},k.includes("{{body}}")?t=k.replace(/\{\{body\}\}/g,t):t.trim()?k.trim()&&(t=`${t} +Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[t.path],actions:this.actionsForFile(t.path)}),console.error(e)}}collectExistingIds(){let t=new Set,e=s=>{if(t.add(s),!!this.tree.get(s))for(let n of this.tree.getChildren(s))e(n.id)};return e(R),t}async createNoteUnder(t,e,s={record:!0}){let i=(s.targetFolder??this.noteFolder).replace(/\/+$/,""),n=i!==this.noteFolder;await this.ensureFolder(i);let r=yt(),a=null;{let v=(this.plugin.settings.noteTemplates??{})[i];if(v){let y=this.app.vault.getAbstractFileByPath(v);if(y&&y.extension==="md")try{let b=await this.app.vault.cachedRead(y),k=this.stripFrontmatter(b);a=this.app.metadataCache.getFileCache(y)?.frontmatter??{},k.includes("{{body}}")?t=k.replace(/\{\{body\}\}/g,t):t.trim()?k.trim()&&(t=`${t} -${k}`):t=k}catch(b){console.warn("[Stashpad] template read failed",b)}}}let a=Ft(t,this.activeStopwords()),l=xt(a,r),c=`${i}/${l}`,p=e??this.focusId,u=s.createdOverride??new Date().toISOString(),d=this.extractAttachments(t),f=this.currentAuthorLink();f&&this.ensureAuthorFile(f);let m=["---",`id: ${r}`,`parent: ${p}`,`created: ${u}`,`modified: ${u}`];if(f&&m.push(`author: "${f.link.replace(/"/g,'\\"')}"`),d.length>0){m.push("attachments:");for(let v of d)m.push(` - "${v.replace(/"/g,'\\"')}"`)}else m.push("attachments: []");m.push("---",t);try{let v=m.join(` -`);await this.app.vault.create(c,v);try{let y=this.app.vault.getAbstractFileByPath(c);if(y&&y.extension==="md"){if(!n)this.tree.insertSynthetic({id:r,parent:p,children:[],file:y,created:u}),this.render(),this.fmSync.scheduleParentChange(r,null,p);else{this.render();let b=i.split("/").pop()||i,k=(t.split(` -`).find(C=>C.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${k}" landed in \`${b}\``,kind:"success",category:"create",duration:0,folder:i,affectedIds:[r],actions:[{label:"Jump to note",onClick:()=>{this.switchToFolderAndFocus(i,r)}}]})}if(o)try{await this.app.fileManager.processFrontMatter(y,b=>{for(let[k,C]of Object.entries(o))Rt.includes(k)||b[k]===void 0&&(b[k]=C)})}catch(b){console.warn("[Stashpad] template fm overlay failed",b)}}}catch{}if(await this.log.append({type:"create",id:r,payload:{path:c,parent:p}}),s.record!==!1){let y=t;this.plugin.getUndoStack(i).push({label:n?"Send note":"Create note",undo:async()=>{let b=this.app.vault.getAbstractFileByPath(c);if(b)try{await this.app.fileManager.trashFile(b)}catch{}if(this.composerDraft=y,this.saveDraft(y),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=y;let k=y.length;this.composerInputEl.setSelectionRange(k,k),this.composerInputEl.focus()}n||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{await this.app.vault.adapter.exists(c)||await this.app.vault.create(c,v),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(y),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return r}catch(v){return new O.Notice(`Stashpad: failed to create note (${v.message})`),null}}extractAttachments(t){let e=[],s=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,i;for(;(i=s.exec(t))!==null;)e.push(i[1]);return e}async ensureFolder(t){if(await this.app.vault.adapter.exists(t)){let e=this.app.vault.getAbstractFileByPath(t);if(e&&!(e instanceof O.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let s=e?.message??"";if(!/already exists/i.test(s))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),s=`${this.noteFolder}/_attachments`;await this.ensureFolder(s);let i=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),r=`${s}/${n}-${i}`;return await this.app.vault.createBinary(r,e),await this.log.append({type:"attachment_add",id:R,payload:{path:r,name:t.name,size:t.size}}),this.plugin.notifications.show({message:`Attached ${t.name}`,kind:"success",category:"attachment",affectedPaths:[r],folder:this.noteFolder}),`![[${r}]]`}catch(e){return new O.Notice(`Stashpad: attachment failed (${e.message})`),null}}currentAuthorLink(){let t=(this.plugin.settings.authorName??"").trim(),e=(this.plugin.settings.authorId??"").trim();if(!t||!e)return null;let s=t.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.noteFolder}/_authors/${s}-${e}.md`,n=t.replace(/[\[\]|]/g,"").trim()||s;return{link:`[[${i}|${n}]]`,path:i,name:t,id:e}}claimSelectedAsAuthor(){this.claimAuthorship({scope:"selection",contributorMode:!1})}claimFolderAsAuthor(){this.claimAuthorship({scope:"folder",contributorMode:!1})}claimSelectedWithContributor(){this.claimAuthorship({scope:"selection",contributorMode:!0})}claimFolderWithContributor(){this.claimAuthorship({scope:"folder",contributorMode:!0})}fileBackedNotesInFolder(){let t=this.noteFolder.replace(/\/+$/,"");return this.app.vault.getMarkdownFiles().filter(e=>{let s=e.parent?.path?.replace(/\/+$/,"")??"";if(s!==t&&!s.startsWith(t+"/")||e.path.includes("/_authors/"))return!1;let i=this.app.metadataCache.getFileCache(e)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(t,e){for(let n=0;n<t.length;n++){let r=this.app.vault.getAbstractFileByPath(t[n]);if(r instanceof O.TFile){this.recentSelfWrites.set(r.path,Date.now());try{await this.app.fileManager.processFrontMatter(r,o=>e(o,t[n]))}catch(o){console.warn("[Stashpad] claim: frontmatter write failed",t[n],o)}}(n+1)%25===0&&await new Promise(o=>setTimeout(o,30))}}async claimAuthorship(t){let e=this.currentAuthorLink();if(!e){new O.Notice("Set your author name in Stashpad settings first.");return}let s=`-${e.id}`,i=t.scope==="selection"?this.getActionTargets().map(d=>d.file).filter(d=>!!d):this.fileBackedNotesInFolder();if(i.length===0){new O.Notice(t.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let n=[],r=[];for(let d of i){let f=this.app.metadataCache.getFileCache(d)?.frontmatter,m=typeof f?.author=="string"?f.author:"";if(!m.trim()){n.push(d.path);continue}if(m.includes(s)||!t.contributorMode)continue;(Array.isArray(f?.contributors)?f.contributors.filter(y=>typeof y=="string"):[]).some(y=>y.includes(s))||r.push(d.path)}let o=n.length+r.length;if(o===0){new O.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(t.scope==="folder"){let d=[`Stamp yourself as author on ${n.length} unauthored note(s)`];if(r.length&&d.push(`and as a contributor on ${r.length} already-authored note(s)`),!await new Promise(m=>{new It(this.app,"Claim authorship",`${d.join(" ")}? -Existing authors are never overwritten. This can be undone.`,"Claim",m).open()}))return}let a=this.noteFolder,l=e.link,c=new Set,p=async()=>{await this.pacedFrontmatter(n,(d,f)=>{typeof d.author=="string"&&d.author.trim()||(d.author=l),Array.isArray(d.contributors)&&d.contributors.some(m=>typeof m=="string"&&m.includes(s))&&(d.contributors=d.contributors.filter(m=>!(typeof m=="string"&&m.includes(s))),c.add(f))}),await this.pacedFrontmatter(r,d=>{let f=Array.isArray(d.contributors)?d.contributors.filter(m=>typeof m=="string"):[];f.some(m=>m.includes(s))||f.push(l),d.contributors=f})};this.ensureAuthorFile(e),await p(),this.plugin.getUndoStack(a).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(n,(d,f)=>{if(typeof d.author=="string"&&d.author.includes(s)&&delete d.author,c.has(f)){let m=Array.isArray(d.contributors)?d.contributors.filter(v=>typeof v=="string"):[];m.some(v=>v.includes(s))||m.push(l),d.contributors=m}}),await this.pacedFrontmatter(r,d=>{Array.isArray(d.contributors)&&(d.contributors=d.contributors.filter(f=>!(typeof f=="string"&&f.includes(s))))}),this.debouncedRender()},redo:async()=>{c.clear(),await p(),this.debouncedRender()}});let u=[];n.length&&u.push(`authored ${n.length}`),r.length&&u.push(`contributing to ${r.length}`),new O.Notice(`Claimed authorship: ${u.join(", ")}. Undo available.`),this.debouncedRender()}async ensureAuthorFile(t){try{t.id&&this.plugin.authorRegistry.record({id:t.id,name:t.name});let e=`${this.noteFolder}/_authors`;if(await this.ensureFolder(e),await this.app.vault.adapter.exists(t.path))return;let s=t.id===(this.plugin.settings.authorId??"").trim(),i=this.plugin.buildAuthorStub({id:t.id,name:t.name,role:s?this.plugin.settings.authorRole:void 0,department:s?this.plugin.settings.authorDepartment:void 0},new Date().toISOString());await this.app.vault.create(t.path,i)}catch(e){console.warn("[Stashpad] ensureAuthorFile failed",e)}}renderAuthorshipFooter(t,e){if(!e.file)return;let s=this.plugin.settings;if(!s.showAuthor&&!s.showContributors&&!s.showLastEdit)return;let i=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},n=typeof i.author=="string"?i.author:"",r=Array.isArray(i.contributors)?i.contributors.filter(f=>typeof f=="string"&&f.trim()!==""):[],o=typeof i.modified=="string"?i.modified:typeof i.created=="string"?i.created:"",a=s.showAuthor&&!!n,l=s.showContributors&&r.length>0,c=s.showLastEdit&&!!o;if(!a&&!l&&!c)return;let p=t.createDiv({cls:"stashpad-note-authorship"}),u=(f,m)=>{let v=m.replace(/^\[\[/,"").replace(/\]\]$/,""),y=v.indexOf("|"),b=y>=0?v.slice(0,y):v,k=y>=0?v.slice(y+1):v.split("/").pop()??v,C=f.createEl("a",{cls:"internal-link",text:k});C.setAttribute("data-href",b),C.setAttribute("href",b)},d=[];a&&d.push(f=>{f.createSpan({cls:"stashpad-authorship-label",text:"by "}),u(f,n)}),l&&d.push(f=>{f.createSpan({cls:"stashpad-authorship-label",text:"with "}),r.forEach((m,v)=>{v>0&&f.createSpan({text:", "}),u(f,m)})}),c&&d.push(f=>{f.createSpan({cls:"stashpad-authorship-label",text:"edited "}),f.createSpan({text:this.formatTimeInline(o)})}),d.forEach((f,m)=>{m>0&&p.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let v=p.createSpan({cls:"stashpad-authorship-piece"});f(v)}),p.addEventListener("click",f=>this.handleRenderedClick(f,e))}pruneContribMaps(){let t=Date.now(),e=At.EXTERNAL_WRITE_GRACE_MS*20,s=At.EXTERNAL_QUIESCENCE_MS*12;for(let[i,n]of this.recentSelfWrites)t-n>e&&this.recentSelfWrites.delete(i);for(let[i,n]of this.lastExternalModify)t-n>s&&this.lastExternalModify.delete(i);if(this.knownBodies.size>64)for(let i of this.knownBodies.keys())this.tree.idForPath(i)||this.knownBodies.delete(i)}scheduleContribution(t){let e=this.contribTimers.get(t.path);e&&clearTimeout(e);let s=this.isFileActivelyEdited(t),i=At.CONTRIB_DEBOUNCE_MS+(s?At.CONTRIB_ACTIVE_EDITOR_BONUS_MS:0),n=setTimeout(()=>{if(this.contribTimers.delete(t.path),this.isFileActivelyEdited(t)){this.scheduleContribution(t);return}let r=this.lastExternalModify.get(t.path);if(r!==void 0&&Date.now()-r<At.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(t);return}this.maybeRecordContribution(t)},i);this.contribTimers.set(t.path,n)}isFileActivelyEdited(t){try{let e=this.app.workspace.activeLeaf;if(!e)return!1;let s=e.view;if(!s||s.getViewType?.()!=="markdown"||s.file?.path!==t.path)return!1;let i=s.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(t){let e="";try{e=await this.app.vault.cachedRead(t)}catch{return}let s=this.stripFrontmatter(e),i=this.knownBodies.get(t.path);if(this.knownBodies.set(t.path,s),i===void 0||i===s)return;let n=this.currentAuthorLink();if(!n)return;this.ensureAuthorFile(n);let r=new Date().toISOString();this.recentSelfWrites.set(t.path,Date.now());try{await this.app.fileManager.processFrontMatter(t,o=>{o.modified=r;let a=typeof o.author=="string"?o.author:"",l=Array.isArray(o.contributors)?o.contributors.filter(d=>typeof d=="string"):[],c=`-${n.id}`,p=a.includes(c),u=l.some(d=>d.includes(c));!p&&!u&&l.push(n.link),o.contributors=l})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}activeStopwords(){return this.plugin.settings.slugStopWords??Mt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,O.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=ee(t.basename);if(!e||e===R)return;let s=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(s),n=Ft(i,this.activeStopwords()),r=xt(n,e);if(t.name===r)return;let o=t.parent?`${t.parent.path}/${r}`:r;if(this.app.vault.getAbstractFileByPath(o))return;let a=t.path;try{await this.app.fileManager.renameFile(t,o),await this.log.append({type:"rename",id:e,payload:{from:a,to:o}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,O.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(e),i=this.extractAttachments(s),n=this.app.metadataCache.getFileCache(t)?.frontmatter,r=Array.isArray(n?.attachments)?n.attachments:[];r.length===i.length&&r.every((a,l)=>a===i[l])||await this.app.fileManager.processFrontMatter(t,a=>{a.attachments=i})}stripFrontmatter(t){let e=t.replace(/^/,""),s=e.match(/^\s*---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/);return s?e.slice(s[0].length):e}formatTime(t){if(!t)return"";let e=(0,O.moment)(t);if(!e.isValid())return"";if(bt().useTemplatesFormat){let i=Je(this.app);if(i)return`${e.format(i.dateFormat)} +${k}`):t=k}catch(b){console.warn("[Stashpad] template read failed",b)}}}let o=Ft(t,this.activeStopwords()),l=xt(o,r),c=`${i}/${l}`,p=e??this.focusId,u=s.createdOverride??new Date().toISOString(),h=this.extractAttachments(t),f=this.currentAuthorLink();f&&this.ensureAuthorFile(f);let m=["---",`id: ${r}`,`parent: ${p}`,`created: ${u}`,`modified: ${u}`];if(f&&m.push(`author: "${f.link.replace(/"/g,'\\"')}"`),h.length>0){m.push("attachments:");for(let v of h)m.push(` - "${v.replace(/"/g,'\\"')}"`)}else m.push("attachments: []");m.push("---",t);try{let v=m.join(` +`);this.plugin.importService.suppress(c,6e4),await Et.timeAsync("write.createNote.file",()=>this.app.vault.create(c,v));try{let y=this.app.vault.getAbstractFileByPath(c);if(y&&y.extension==="md"){if(!n)this.tree.insertSynthetic({id:r,parent:p,children:[],file:y,created:u}),this.render(),this.fmSync.scheduleParentChange(r,null,p);else{this.render();let b=i.split("/").pop()||i,k=(t.split(` +`).find(T=>T.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${k}" landed in \`${b}\``,kind:"success",category:"create",duration:0,folder:i,affectedIds:[r],actions:[{label:"Jump to note",onClick:()=>{this.switchToFolderAndFocus(i,r)}}]})}if(a)try{await this.app.fileManager.processFrontMatter(y,b=>{for(let[k,T]of Object.entries(a))Bt.includes(k)||b[k]===void 0&&(b[k]=T)})}catch(b){console.warn("[Stashpad] template fm overlay failed",b)}}}catch{}if(await this.log.append({type:"create",id:r,payload:{path:c,parent:p}}),s.record!==!1){let y=t;this.plugin.getUndoStack(i).push({label:n?"Send note":"Create note",undo:async()=>{let b=this.app.vault.getAbstractFileByPath(c);if(b)try{await this.app.fileManager.trashFile(b)}catch{}if(this.composerDraft=y,this.saveDraft(y),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=y;let k=y.length;this.composerInputEl.setSelectionRange(k,k),this.composerInputEl.focus()}n||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{await this.app.vault.adapter.exists(c)||await this.app.vault.create(c,v),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(y),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return r}catch(v){return new O.Notice(`Stashpad: failed to create note (${v.message})`),null}}extractAttachments(t){let e=[],s=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,i;for(;(i=s.exec(t))!==null;)e.push(i[1]);return e}async ensureFolder(t){if(await this.app.vault.adapter.exists(t)){let e=this.app.vault.getAbstractFileByPath(t);if(e&&!(e instanceof O.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let s=e?.message??"";if(!/already exists/i.test(s))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),s=`${this.noteFolder}/_attachments`;await this.ensureFolder(s);let i=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),r=`${s}/${n}-${i}`;return await this.app.vault.createBinary(r,e),await this.log.append({type:"attachment_add",id:R,payload:{path:r,name:t.name,size:t.size}}),this.plugin.notifications.show({message:`Attached ${t.name}`,kind:"success",category:"attachment",affectedPaths:[r],folder:this.noteFolder}),`![[${r}]]`}catch(e){return new O.Notice(`Stashpad: attachment failed (${e.message})`),null}}currentAuthorLink(){let t=(this.plugin.settings.authorName??"").trim(),e=(this.plugin.settings.authorId??"").trim();if(!t||!e)return null;let s=t.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.noteFolder}/_authors/${s}-${e}.md`,n=t.replace(/[\[\]|]/g,"").trim()||s;return{link:`[[${i}|${n}]]`,path:i,name:t,id:e}}claimSelectedAsAuthor(){this.claimAuthorship({scope:"selection",contributorMode:!1})}claimFolderAsAuthor(){this.claimAuthorship({scope:"folder",contributorMode:!1})}claimSelectedWithContributor(){this.claimAuthorship({scope:"selection",contributorMode:!0})}claimFolderWithContributor(){this.claimAuthorship({scope:"folder",contributorMode:!0})}fileBackedNotesInFolder(){let t=this.noteFolder.replace(/\/+$/,"");return this.app.vault.getMarkdownFiles().filter(e=>{let s=e.parent?.path?.replace(/\/+$/,"")??"";if(s!==t&&!s.startsWith(t+"/")||e.path.includes("/_authors/"))return!1;let i=this.app.metadataCache.getFileCache(e)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(t,e){for(let n=0;n<t.length;n++){let r=this.app.vault.getAbstractFileByPath(t[n]);if(r instanceof O.TFile){this.recentSelfWrites.set(r.path,Date.now());try{await this.app.fileManager.processFrontMatter(r,a=>e(a,t[n]))}catch(a){console.warn("[Stashpad] claim: frontmatter write failed",t[n],a)}}(n+1)%25===0&&await new Promise(a=>setTimeout(a,30))}}async claimAuthorship(t){let e=this.currentAuthorLink();if(!e){new O.Notice("Set your author name in Stashpad settings first.");return}let s=`-${e.id}`,i=t.scope==="selection"?this.getActionTargets().map(h=>h.file).filter(h=>!!h):this.fileBackedNotesInFolder();if(i.length===0){new O.Notice(t.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let n=[],r=[];for(let h of i){let f=this.app.metadataCache.getFileCache(h)?.frontmatter,m=typeof f?.author=="string"?f.author:"";if(!m.trim()){n.push(h.path);continue}if(m.includes(s)||!t.contributorMode)continue;(Array.isArray(f?.contributors)?f.contributors.filter(y=>typeof y=="string"):[]).some(y=>y.includes(s))||r.push(h.path)}let a=n.length+r.length;if(a===0){new O.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(t.scope==="folder"){let h=[`Stamp yourself as author on ${n.length} unauthored note(s)`];if(r.length&&h.push(`and as a contributor on ${r.length} already-authored note(s)`),!await new Promise(m=>{new At(this.app,"Claim authorship",`${h.join(" ")}? +Existing authors are never overwritten. This can be undone.`,"Claim",m).open()}))return}let o=this.noteFolder,l=e.link,c=new Set,p=async()=>{await this.pacedFrontmatter(n,(h,f)=>{typeof h.author=="string"&&h.author.trim()||(h.author=l),Array.isArray(h.contributors)&&h.contributors.some(m=>typeof m=="string"&&m.includes(s))&&(h.contributors=h.contributors.filter(m=>!(typeof m=="string"&&m.includes(s))),c.add(f))}),await this.pacedFrontmatter(r,h=>{let f=Array.isArray(h.contributors)?h.contributors.filter(m=>typeof m=="string"):[];f.some(m=>m.includes(s))||f.push(l),h.contributors=f})};this.ensureAuthorFile(e),await p(),this.plugin.getUndoStack(o).push({label:`Claim authorship (${a} note${a===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(n,(h,f)=>{if(typeof h.author=="string"&&h.author.includes(s)&&delete h.author,c.has(f)){let m=Array.isArray(h.contributors)?h.contributors.filter(v=>typeof v=="string"):[];m.some(v=>v.includes(s))||m.push(l),h.contributors=m}}),await this.pacedFrontmatter(r,h=>{Array.isArray(h.contributors)&&(h.contributors=h.contributors.filter(f=>!(typeof f=="string"&&f.includes(s))))}),this.debouncedRender()},redo:async()=>{c.clear(),await p(),this.debouncedRender()}});let u=[];n.length&&u.push(`authored ${n.length}`),r.length&&u.push(`contributing to ${r.length}`),new O.Notice(`Claimed authorship: ${u.join(", ")}. Undo available.`),this.debouncedRender()}async ensureAuthorFile(t){try{t.id&&this.plugin.authorRegistry.record({id:t.id,name:t.name});let e=`${this.noteFolder}/_authors`;if(await this.ensureFolder(e),await this.app.vault.adapter.exists(t.path))return;let s=t.id===(this.plugin.settings.authorId??"").trim(),i=this.plugin.buildAuthorStub({id:t.id,name:t.name,role:s?this.plugin.settings.authorRole:void 0,department:s?this.plugin.settings.authorDepartment:void 0},new Date().toISOString());await this.app.vault.create(t.path,i)}catch(e){console.warn("[Stashpad] ensureAuthorFile failed",e)}}renderAuthorshipFooter(t,e){if(!e.file)return;let s=this.plugin.settings;if(!s.showAuthor&&!s.showContributors&&!s.showLastEdit)return;let i=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},n=typeof i.author=="string"?i.author:"",r=Array.isArray(i.contributors)?i.contributors.filter(f=>typeof f=="string"&&f.trim()!==""):[],a=typeof i.modified=="string"?i.modified:typeof i.created=="string"?i.created:"",o=s.showAuthor&&!!n,l=s.showContributors&&r.length>0,c=s.showLastEdit&&!!a;if(!o&&!l&&!c)return;let p=t.createDiv({cls:"stashpad-note-authorship"}),u=(f,m)=>{let v=m.replace(/^\[\[/,"").replace(/\]\]$/,""),y=v.indexOf("|"),b=y>=0?v.slice(0,y):v,k=y>=0?v.slice(y+1):v.split("/").pop()??v,T=f.createEl("a",{cls:"internal-link",text:k});T.setAttribute("data-href",b),T.setAttribute("href",b)},h=[];o&&h.push(f=>{f.createSpan({cls:"stashpad-authorship-label",text:"by "}),u(f,n)}),l&&h.push(f=>{f.createSpan({cls:"stashpad-authorship-label",text:"with "}),r.forEach((m,v)=>{v>0&&f.createSpan({text:", "}),u(f,m)})}),c&&h.push(f=>{f.createSpan({cls:"stashpad-authorship-label",text:"edited "}),f.createSpan({text:this.formatTimeInline(a)})}),h.forEach((f,m)=>{m>0&&p.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let v=p.createSpan({cls:"stashpad-authorship-piece"});f(v)}),p.addEventListener("click",f=>this.handleRenderedClick(f,e))}pruneContribMaps(){let t=Date.now(),e=Dt.EXTERNAL_WRITE_GRACE_MS*20,s=Dt.EXTERNAL_QUIESCENCE_MS*12;for(let[i,n]of this.recentSelfWrites)t-n>e&&this.recentSelfWrites.delete(i);for(let[i,n]of this.lastExternalModify)t-n>s&&this.lastExternalModify.delete(i);if(this.knownBodies.size>64)for(let i of this.knownBodies.keys())this.tree.idForPath(i)||this.knownBodies.delete(i)}scheduleContribution(t){let e=this.contribTimers.get(t.path);e&&clearTimeout(e);let s=this.isFileActivelyEdited(t),i=Dt.CONTRIB_DEBOUNCE_MS+(s?Dt.CONTRIB_ACTIVE_EDITOR_BONUS_MS:0),n=setTimeout(()=>{if(this.contribTimers.delete(t.path),this.isFileActivelyEdited(t)){this.scheduleContribution(t);return}let r=this.lastExternalModify.get(t.path);if(r!==void 0&&Date.now()-r<Dt.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(t);return}this.maybeRecordContribution(t)},i);this.contribTimers.set(t.path,n)}isFileActivelyEdited(t){try{let e=this.app.workspace.activeLeaf;if(!e)return!1;let s=e.view;if(!s||s.getViewType?.()!=="markdown"||s.file?.path!==t.path)return!1;let i=s.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(t){let e="";try{e=await this.app.vault.cachedRead(t)}catch{return}let s=this.stripFrontmatter(e),i=this.knownBodies.get(t.path);if(this.knownBodies.set(t.path,s),i===void 0||i===s||this.plugin.rebootstrapInProgress)return;let n=this.currentAuthorLink();if(!n)return;this.ensureAuthorFile(n);let r=new Date().toISOString();this.recentSelfWrites.set(t.path,Date.now());try{await this.app.fileManager.processFrontMatter(t,a=>{a.modified=r;let o=typeof a.author=="string"?a.author:"",l=Array.isArray(a.contributors)?a.contributors.filter(h=>typeof h=="string"):[],c=`-${n.id}`,p=o.includes(c),u=l.some(h=>h.includes(c));!p&&!u&&l.push(n.link),a.contributors=l})}catch(a){console.warn("[Stashpad] maybeRecordContribution failed",a)}}activeStopwords(){return this.plugin.settings.slugStopWords??_t}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,O.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=re(t.basename);if(!e||e===R)return;let s=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(s),n=Ft(i,this.activeStopwords()),r=xt(n,e);if(t.name===r)return;let a=t.parent?`${t.parent.path}/${r}`:r;if(this.app.vault.getAbstractFileByPath(a))return;let o=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:o,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,O.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(e),i=this.extractAttachments(s),n=this.app.metadataCache.getFileCache(t)?.frontmatter,r=Array.isArray(n?.attachments)?n.attachments:[];r.length===i.length&&r.every((o,l)=>o===i[l])||await this.app.fileManager.processFrontMatter(t,o=>{o.attachments=i})}stripFrontmatter(t){let e=t.replace(/^/,""),s=e.match(/^\s*---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/);return s?e.slice(s[0].length):e}formatTime(t){if(!t)return"";let e=(0,O.moment)(t);if(!e.isValid())return"";if(St().useTemplatesFormat){let i=es(this.app);if(i)return`${e.format(i.dateFormat)} ${e.format(i.timeFormat)}`}return`${e.format("YYYY.MM.DD")} -${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,O.moment)(t);if(!e.isValid())return"";if(bt().useTemplatesFormat){let i=Je(this.app);if(i){let n=/:ss/.test(i.timeFormat)?i.timeFormat:i.timeFormat.replace(/(:mm)/,"$1:ss");return`${e.format(i.dateFormat)} ${e.format(n)}`}}return`${e.format("YYYY.MM.DD")} ${e.format("HH:mm:ss A")}`}scrollListToBottom(){let t=this.listEl;if(!t)return;if(this.stickToListBottom=!0,t.scrollTop=t.scrollHeight,O.Platform.isMobile){let o=0,a=()=>{!this.stickToListBottom||o>=8||(o++,Date.now()>=this.keyboardTransitionUntil&&(t.scrollTop=t.scrollHeight),window.setTimeout(a,120))};window.setTimeout(a,60);return}this.stickyRowObserver?.disconnect();let e=()=>{if(!this.stickToListBottom){this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null;return}t.scrollTop=t.scrollHeight},s=new ResizeObserver(e);for(let o of Array.from(t.children))o instanceof HTMLElement&&s.observe(o);this.stickyRowObserver=s;let i=performance.now(),n=t.scrollHeight,r=()=>{if(!this.stickToListBottom)return;let o=t.scrollHeight;o!==n&&(t.scrollTop=o,n=o),performance.now()-i<3e4?requestAnimationFrame(r):(this.stickToListBottom=!1,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null)};requestAnimationFrame(r)}openNoteMenu(t,e){if(!e.file)return;let s=e.file,i=new O.Menu;i.addItem(a=>a.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),i.addItem(a=>a.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(s)})),i.addItem(a=>a.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),i.addSeparator(),i.addItem(a=>a.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),i.addItem(a=>a.setTitle("Clone (duplicate / copy)").setIcon("files").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdClone()})),i.addItem(a=>a.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),i.addItem(a=>a.setTitle("Export to .stash").setIcon("package").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportStash()})),i.addSeparator(),i.addItem(a=>a.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),i.addItem(a=>a.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,R),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==R&&this.navigateTo(R)}));let n={folder:this.noteFolder,id:e.id},r=this.plugin.isPinned(n);i.addItem(a=>a.setTitle(r?"Unpin from sidebar":"Pin to sidebar").setIcon(r?"pin-off":"pin").onClick(async()=>{r?await this.plugin.unpinNote(n):await this.plugin.pinNote(n)})),i.addItem(a=>a.setTitle("Set color\u2026").setIcon("palette").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdSetColor()}));let o=this.isCompleted(e);i.addItem(a=>a.setTitle(o?"Mark incomplete":"Mark complete").setIcon(o?"circle":"check-circle").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdToggleComplete()})),i.addSeparator(),i.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(async()=>{await this.deleteNote(e)})),i.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],s=f=>{for(let m of this.tree.getChildren(f.id))s(m),e.push(m)};s(t);let i=[...e,t],n=i.filter(f=>!!f.file),r=await Promise.all(n.map(f=>this.app.vault.cachedRead(f.file))),o=[];for(let f=0;f<n.length;f++){let m=n[f];o.push(...this.extractAttachments(this.stripFrontmatter(r[f])));let v=this.app.metadataCache.getFileCache(m.file)?.frontmatter;if(Array.isArray(v?.attachments))for(let y of v.attachments)typeof y=="string"&&y.trim()&&o.push(y)}let a=[...new Set(o)],l=this.collectAuthorIds(i),c=async f=>{let m=await this.snapshotNotes(i,f),v=0;if(f)for(let A of a){let S=this.app.metadataCache.getFirstLinkpathDest(A,"");if(S)try{await this.app.fileManager.trashFile(S),await this.log.append({type:"attachment_remove",id:R,payload:{path:S.path}}),this.plugin.notifications.show({message:`Deleted attachment "${S.name}"`,kind:"warning",category:"attachment",affectedPaths:[S.path],folder:this.noteFolder}),v+=1}catch{}}let y=new Set;for(let A of i)A.parent&&y.add(A.parent);let b=this.currentChildren.findIndex(A=>A.id===t.id),k=null;if(b>=0){for(let A=b+1;A<this.currentChildren.length;A++)if(this.currentChildren[A].id!==t.id){k=this.currentChildren[A].id;break}if(!k){for(let A=b-1;A>=0;A--)if(this.currentChildren[A].id!==t.id){k=this.currentChildren[A].id;break}}}for(let A of i)if(A.file){try{await this.app.fileManager.trashFile(A.file)}catch{}await this.log.append({type:"delete",id:A.id,payload:{path:A.file.path,attachmentsRemoved:f?a:[]}})}this.selection.clear(),this.cursorIdx=-1,k&&(this.pendingFocusIds=[k]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let A of y)i.some(S=>S.id===A)||this.fmSync.scheduleParentOfDeleted(A);let C=this.noteFolder,I=`Delete "${this.titleForNode(t)}"`,E=t.id,D=v>0?` with ${v} attachment${v===1?"":"s"}`:"",H=!1,T=async()=>{H||(H=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(m,[E]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${D}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:l,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void T()}]}),this.plugin.getUndoStack(C).push({label:I,undo:async()=>{await T()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,H=!1,await this.trashNotesAndAttachments(m)}})},p=bt(),u=e.length>0&&p.confirmBulkDelete,d=a.length>0&&p.confirmAttachmentDelete;if(!u&&!d){await c(!1),this.focusView();return}new te(this.app,this.titleForNode(t),e.length,a.length,d,async f=>{await c(f),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new O.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===R){new O.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new O.Notice("Couldn't find the parent note.");return}let s=e.parent??R,i=this.titleForNode(t),n=this.titleForNode(e),r=this.tree.getChildren(e.id).filter(a=>a.id!==t.id).length,o=[`"${n}" becomes a child of "${i}".`];r>0&&o.push(`${r} sibling${r===1?"":"s"} move with it.`),new It(this.app,"Swap notes?",o.join(` -`),"Swap",async a=>{a&&await this.swapParentChild(e,t,s)}).open()}offerSwapForDescendantMove(t,e){let s=this.tree.get(e);if(!s?.file){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder});return}if(s.parent!==t.id){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under "${this.titleForNode(s)}" \u2014 it's a deeper descendant. Only direct parent \u2194 child swaps are supported (try moving "${this.titleForNode(s)}" up first, then swap).`,kind:"warning",category:"move",affectedIds:[t.id,s.id],folder:this.noteFolder});return}let i=this.titleForNode(t),n=this.titleForNode(s),r=this.tree.getChildren(t.id).filter(a=>a.id!==s.id).length,o=[`"${i}" becomes a child of "${n}".`];r>0&&o.push(`${r} sibling${r===1?"":"s"} move with it.`),new It(this.app,"Confirm Note Swap",o.join(` -`),"Swap",async a=>{if(!a)return;let l=t.parent??R;await this.swapParentChild(t,s,l)}).open()}async swapParentChild(t,e,s){if(!t.file||!e.file)return;if(e.parent!==t.id){new O.Notice("Swap aborted: parent/child relationship changed.");return}let i=this.noteFolder,n=t.parent,r=this.tree.getChildren(t.id).filter(d=>d.id!==e.id).filter(d=>!!d.file),o=r.map(d=>({id:d.id,path:d.file.path,was:d.parent})),a=this.order.getOrder(i,s).slice(),l=this.order.getOrder(i,e.id).slice(),c=this.order.getOrder(i,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,d=>{d.parent=s}),this.fmSync.scheduleParentChange(e.id,t.id,s),await this.app.fileManager.processFrontMatter(t.file,d=>{d.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let d of r)await this.app.fileManager.processFrontMatter(d.file,f=>{f.parent=e.id}),this.fmSync.scheduleParentChange(d.id,t.id,e.id);if(a.length>0){let d=a.includes(t.id)?a.map(f=>f===t.id?e.id:f):[...a.filter(f=>f!==e.id),e.id];this.order.setOrder(i,s,d)}let p=r.map(d=>d.id),u=[t.id,...l.filter(d=>d!==t.id&&!p.includes(d)),...p];this.order.setOrder(i,e.id,u),this.order.setOrder(i,t.id,[]),await this.order.save(i),await this.log.append({type:"parent_change",id:e.id,payload:{from:t.id,to:s,reason:"swap"}}),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e.id,reason:"swap"}});for(let d of o)await this.log.append({type:"parent_change",id:d.id,payload:{from:d.was,to:e.id,reason:"swap"}});this.tree.rebuild(i),this.pendingFocusIds=[e.id],this.render({kind:"follow-cursor"}),this.plugin.notifications.show({message:`Swapped "${this.titleForNode(e)}" \u2194 "${this.titleForNode(t)}".`,kind:"success",category:"move",affectedIds:[e.id,t.id,...p],folder:i}),this.plugin.getUndoStack(i).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let d=this.tree.get(t.id),f=this.tree.get(e.id);d?.file&&await this.app.fileManager.processFrontMatter(d.file,m=>{n==null||n===R?(delete m.parent,m.parent=R):m.parent=n}),f?.file&&await this.app.fileManager.processFrontMatter(f.file,m=>{m.parent=t.id});for(let m of o){let v=this.app.vault.getAbstractFileByPath(m.path);v&&await this.app.fileManager.processFrontMatter(v,y=>{m.was==null?y.parent=R:y.parent=m.was})}this.order.setOrder(i,s,a),this.order.setOrder(i,e.id,l),this.order.setOrder(i,t.id,c),await this.order.save(i),this.tree.rebuild(i),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,s)}})}async changeParent(t,e,s={record:!0}){if(!t.file)return;let i=t.file,n=t.parent,r=a=>a??R;if(r(n)===r(e)){if(!s.quiet){let a=this.titleForNode(t),l=e===R?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${a}" is already under ${l}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return}if(e===t.id){s.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder});return}if(e!==R&&this.isDescendant(e,t.id)){s.quiet||this.offerSwapForDescendantMove(t,e);return}let o=this.collectAuthorIds([t]);if(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=e}),this.fmSync.scheduleParentChange(t.id,n,e),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e}}),this.pendingFocusIds=[t.id],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),!s.quiet){let a=this.tree.get(e),l=a?this.titleForNode(a):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${l}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:o,folder:this.noteFolder,actions:e===R?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(s.record!==!1){let a=this.noteFolder,l=i.path,c=t.id;this.plugin.getUndoStack(a).push({label:"Move note",undo:async()=>{let p=this.app.vault.getAbstractFileByPath(l);if(p){await this.app.fileManager.processFrontMatter(p,u=>{u.parent=n}),this.pendingFocusIds=[c],this.focusId!==n&&this.focusId!==e?(this.selection.clear(),this.cursorIdx=-1):this.focusId===e&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(a),this.render({kind:"follow-cursor"});{let u=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==u||this.selection.has(c))return;let f=this.currentChildren.findIndex(m=>m.id===c);f<0||(this.selection.add(c),this.cursorIdx=f,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}},redo:async()=>{let p=this.app.vault.getAbstractFileByPath(l);if(p){await this.app.fileManager.processFrontMatter(p,u=>{u.parent=e}),this.pendingFocusIds=[c],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(a),this.render({kind:"follow-cursor"});{let u=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==u||this.selection.has(c))return;let f=this.currentChildren.findIndex(m=>m.id===c);f<0||(this.selection.add(c),this.cursorIdx=f,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}}})}}};At.CONTRIB_DEBOUNCE_MS=4e3,At.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,At.EXTERNAL_WRITE_GRACE_MS=1500,At.EXTERNAL_QUIESCENCE_MS=5e3;var hs=At;function nn(g,h){return!h||g.metaKey||g.ctrlKey||g.altKey?!1:g.key.toLowerCase()===h.toLowerCase()}function oe(g,h){return h?h.includes("+")?rn(g,h):nn(g,h):!1}function ot(g,h){if(!h)return!1;let{primary:t,secondary:e,preferRight:s,useBoth:i}=h;return t&&e?i?oe(g,t)||oe(g,e):s?oe(g,e):oe(g,t):oe(g,t)||oe(g,e)}function zs(g){if(!g)return"";let h=O.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return g.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?h?"Cmd":"Ctrl":e.toLowerCase()==="alt"?h?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function rn(g,h){if(!h)return!1;let t=h.split("+").map(p=>p.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),s=new Set(t.slice(0,-1).map(p=>p.toLowerCase())),i=s.has("mod"),n=s.has("ctrl")||s.has("control"),r=s.has("cmd")||s.has("meta")||s.has("command"),o=s.has("alt")||s.has("option"),a=s.has("shift"),c=O.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?g.metaKey:g.ctrlKey;return i&&!c||n&&!g.ctrlKey||r&&!g.metaKey||o!==g.altKey||a!==g.shiftKey||!i&&(!n&&g.ctrlKey||!r&&g.metaKey)?!1:g.key.toLowerCase()===e}function an(g){let h=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(g))!=null;)h.push({lang:e[3].trim(),code:e[4]});return h}function ps(g){return g.split("/").map(h=>h.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function on(g,h,t){let e=new Set(h),s=g.filter(n=>!e.has(n)),i=g.findIndex(n=>e.has(n));if(i<0)return g.slice();switch(t){case"top":return[...h,...s];case"bottom":return[...s,...h];case"up":{let n=Math.max(0,i-1),r=s.slice();return r.splice(n,0,...h),r}case"down":{let n=(()=>{let l=-1;return g.forEach((c,p)=>{e.has(c)&&(l=p)}),l})(),r=0;for(let l=0;l<Math.min(g.length,n+2);l++)e.has(g[l])||r++;let o=Math.min(s.length,r),a=s.slice();return a.splice(o,0,...h),a}}}function Ci(g,h){if(g.length!==h.length)return!1;for(let t=0;t<g.length;t++)if(g[t]!==h[t])return!1;return!0}se();var us=class{constructor(h,t,e){this.app=h;this.dirOk=!1;this.writeChain=Promise.resolve();this.baseDir=t.replace(/\/+$/,""),this.logPath=`${this.baseDir}/log.jsonl`,this.statePath=`${this.baseDir}/state.json`,this.getAuthor=e??(()=>"")}getLogPath(){return this.logPath}getDir(){return this.baseDir}async ensureDir(){if(this.dirOk)return;let h=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let s of t)e=e?`${e}/${s}`:s,await h.exists(e)||await h.mkdir(e);this.dirOk=!0}append(h){let t=h.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...h};t?e.author=t:delete e.author;let s=JSON.stringify(e)+` -`;return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let i=this.app.vault.adapter;if(typeof i.append=="function")await i.append(this.logPath,s);else{let n=await i.exists(this.logPath)?await i.read(this.logPath):"";await i.write(this.logPath,n+s)}}catch(i){console.warn("Stashpad: log append failed",i)}}),Promise.resolve()}async readState(){let h=this.app.vault.adapter;if(!await h.exists(this.statePath))return{};try{return JSON.parse(await h.read(this.statePath))}catch{return{}}}async writeState(h){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(h,null,2))}};Tt();var fs=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(h){for(this.undoStack.push(h),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let h=this.undoStack.pop();if(!h)return null;try{await h.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(h),h}async redo(){let h=this.redoStack.pop();if(!h)return null;try{await h.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(h),h}peekUndoLabel(){return this.undoStack[this.undoStack.length-1]?.label??null}peekRedoLabel(){return this.redoStack[this.redoStack.length-1]?.label??null}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[]}};var ms=class{constructor(h,t){this.app=h;this.data={version:1,authors:{}};this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/authors.json`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let h=this.app.vault.adapter;if(await h.exists(this.path)){let t=JSON.parse(await h.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(h){console.warn("[Stashpad] author registry load failed; starting empty",h),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((h,t)=>(t.lastSeen??"").localeCompare(h.lastSeen??""))}get(h){return this.data.authors[h]??null}record(h){let t=(h.id??"").trim();if(!t)return!1;let e=h.at??new Date().toISOString(),s=(h.name??"").trim(),i=this.data.authors[t],n=!1;if(!i)this.data.authors[t]={id:t,name:s,role:h.role?.trim()||void 0,department:h.department?.trim()||void 0,firstSeen:e,lastSeen:e,renames:[]},n=!0;else{if(s&&s!==i.name&&(i.renames.push({from:i.name,to:s,at:e}),i.name=s,n=!0),h.role!==void 0){let r=h.role.trim()||void 0;r!==i.role&&(i.role=r,n=!0)}if(h.department!==void 0){let r=h.department.trim()||void 0;r!==i.department&&(i.department=r,n=!0)}i.lastSeen=e}return n&&this.save(),n}replaceAll(h,t){let e=t??new Date().toISOString(),s={};for(let i of h){let n=(i.id??"").trim();if(!n)continue;let r=this.data.authors[n],o=(i.name??"").trim()||r?.name||"",a=r?.renames?[...r.renames]:[];r&&o&&o!==r.name&&a.push({from:r.name,to:o,at:e}),s[n]={id:n,name:o,role:i.role?.trim()||r?.role||void 0,department:i.department?.trim()||r?.department||void 0,firstSeen:r?.firstSeen??e,lastSeen:e,renames:a}}this.data={version:1,authors:s},this.save()}async ensureDir(){if(this.dirOk)return;let h=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),s="";for(let i of e)s=s?`${s}/${i}`:i,await h.exists(s)||await h.mkdir(s);this.dirOk=!0}save(){return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.write(this.path,JSON.stringify(this.data,null,2))}catch(h){console.warn("[Stashpad] author registry save failed",h)}}),this.writeChain}};var St=require("obsidian");Tt();Pt();se();Bt();var Fi=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),xi="_archive",le=class le{constructor(h){this.plugin=h;this.pending=new Map;this.pendingFolders=new Map;this.suppressed=new Set;this.armed=!1;this.drainTimer=null;this.draining=!1}setArmed(h){this.armed=h}get app(){return this.plugin.app}enqueue(h){this.armed&&this.plugin.settings.autoImport&&this.isEligiblePath(h)&&(this.pending.set(h.path,Date.now()),this.arm())}enqueueFolder(h){if(!this.armed||!this.plugin.settings.autoImport||this.suppressed.has(h.path))return;let t=h.parent?.path?.replace(/\/+$/,"")??"";this.plugin.discoverStashpadFolders().includes(t)&&(Fi.has(h.name)||(this.pendingFolders.set(h.path,Date.now()),this.arm()))}arm(){this.drainTimer!=null&&window.clearTimeout(this.drainTimer),this.drainTimer=window.setTimeout(()=>void this.drain(),le.DEBOUNCE_MS)}suppress(h){this.suppressed.add(h),window.setTimeout(()=>this.suppressed.delete(h),4e3)}isEligiblePath(h){if(this.suppressed.has(h.path)||h.extension===Gt||h.extension==="edtz")return!1;let t=h.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return Fi.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}isStillImportable(h){if(!this.isEligiblePath(h))return!1;if(h.extension==="md"){let t=this.app.metadataCache.getFileCache(h)?.frontmatter;if(t&&typeof t.id=="string"&&t.id)return!1}return!0}async drain(){if(this.drainTimer=null,!this.draining){this.draining=!0;try{let h=[...this.pending.keys()];this.pending.clear();let t=h.map(c=>this.app.vault.getAbstractFileByPath(c)).filter(c=>c instanceof St.TFile).filter(c=>this.isStillImportable(c)),e=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=e.map(c=>this.app.vault.getAbstractFileByPath(c)).filter(c=>c instanceof St.TFolder).map(c=>({folder:c,files:this.filesUnder(c.path)})).filter(c=>c.files.length>0),i=s.reduce((c,p)=>c+p.files.length,0),n=t.length+i;if(n===0)return;await this.plugin.importLog.load();let r=t,o=[],a=t.filter(c=>this.plugin.importLog.findDuplicate(c.name,c.stat?.size??null));if(a.length>0){let c=a.slice(0,5).map(d=>`\u2022 ${d.name}`).join(` -`),p=a.length>5?` -\u2026and ${a.length-5} more`:"",u=await this.dupChoice(`${a.length} of these look like files you've imported before: -${c}${p} +${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,O.moment)(t);if(!e.isValid())return"";if(St().useTemplatesFormat){let i=es(this.app);if(i){let n=/:ss/.test(i.timeFormat)?i.timeFormat:i.timeFormat.replace(/(:mm)/,"$1:ss");return`${e.format(i.dateFormat)} ${e.format(n)}`}}return`${e.format("YYYY.MM.DD")} ${e.format("HH:mm:ss A")}`}scrollListToBottom(){let t=this.listEl;if(!t)return;if(this.stickToListBottom=!0,t.scrollTop=t.scrollHeight,O.Platform.isMobile){let a=0,o=()=>{!this.stickToListBottom||a>=8||(a++,Date.now()>=this.keyboardTransitionUntil&&(t.scrollTop=t.scrollHeight),window.setTimeout(o,120))};window.setTimeout(o,60);return}this.stickyRowObserver?.disconnect();let e=()=>{if(!this.stickToListBottom){this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null;return}t.scrollTop=t.scrollHeight},s=new ResizeObserver(e);for(let a of Array.from(t.children))a instanceof HTMLElement&&s.observe(a);this.stickyRowObserver=s;let i=performance.now(),n=t.scrollHeight,r=()=>{if(!this.stickToListBottom)return;let a=t.scrollHeight;a!==n&&(t.scrollTop=a,n=a),performance.now()-i<3e4?requestAnimationFrame(r):(this.stickToListBottom=!1,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null)};requestAnimationFrame(r)}openNoteMenu(t,e){if(!e.file)return;let s=e.file,i=new O.Menu;i.addItem(o=>o.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),i.addItem(o=>o.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(s)})),i.addItem(o=>o.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),i.addSeparator(),i.addItem(o=>o.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),i.addItem(o=>o.setTitle("Clone (duplicate / copy)").setIcon("files").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdClone()})),i.addItem(o=>o.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),i.addItem(o=>o.setTitle("Export to .stash").setIcon("package").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportStash()})),i.addSeparator(),i.addItem(o=>o.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),i.addItem(o=>o.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,R),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==R&&this.navigateTo(R)}));let n={folder:this.noteFolder,id:e.id},r=this.plugin.isPinned(n);i.addItem(o=>o.setTitle(r?"Unpin from sidebar":"Pin to sidebar").setIcon(r?"pin-off":"pin").onClick(async()=>{r?await this.plugin.unpinNote(n):await this.plugin.pinNote(n)})),i.addItem(o=>o.setTitle("Set color\u2026").setIcon("palette").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdSetColor()}));let a=this.isCompleted(e);i.addItem(o=>o.setTitle(a?"Mark incomplete":"Mark complete").setIcon(a?"circle":"check-circle").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdToggleComplete()})),i.addSeparator(),i.addItem(o=>o.setTitle("Delete").setIcon("trash").onClick(async()=>{await this.deleteNote(e)})),i.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],s=f=>{for(let m of this.tree.getChildren(f.id))s(m),e.push(m)};s(t);let i=[...e,t],n=i.filter(f=>!!f.file),r=await Promise.all(n.map(f=>this.app.vault.cachedRead(f.file))),a=[];for(let f=0;f<n.length;f++){let m=n[f];a.push(...this.extractAttachments(this.stripFrontmatter(r[f])));let v=this.app.metadataCache.getFileCache(m.file)?.frontmatter;if(Array.isArray(v?.attachments))for(let y of v.attachments)typeof y=="string"&&y.trim()&&a.push(se(y))}let o=[...new Set(a)],l=this.collectAuthorIds(i),c=async f=>{let m=await this.snapshotNotes(i,f),v=0;if(f)for(let A of o){let S=this.app.metadataCache.getFirstLinkpathDest(A,"");if(S)try{await this.app.fileManager.trashFile(S),await this.log.append({type:"attachment_remove",id:R,payload:{path:S.path}}),this.plugin.notifications.show({message:`Deleted attachment "${S.name}"`,kind:"warning",category:"attachment",affectedPaths:[S.path],folder:this.noteFolder}),v+=1}catch{}}let y=new Set;for(let A of i)A.parent&&y.add(A.parent);let b=this.currentChildren.findIndex(A=>A.id===t.id),k=null;if(b>=0){for(let A=b+1;A<this.currentChildren.length;A++)if(this.currentChildren[A].id!==t.id){k=this.currentChildren[A].id;break}if(!k){for(let A=b-1;A>=0;A--)if(this.currentChildren[A].id!==t.id){k=this.currentChildren[A].id;break}}}for(let A of i)if(A.file){try{await this.app.fileManager.trashFile(A.file)}catch{}await this.log.append({type:"delete",id:A.id,payload:{path:A.file.path,attachmentsRemoved:f?o:[]}})}this.selection.clear(),this.cursorIdx=-1,k&&(this.pendingFocusIds=[k]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let A of y)i.some(S=>S.id===A)||this.fmSync.scheduleParentOfDeleted(A);let T=this.noteFolder,I=`Delete "${this.titleForNode(t)}"`,E=t.id,D=v>0?` with ${v} attachment${v===1?"":"s"}`:"",H=!1,C=async()=>{H||(H=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(m,[E]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${D}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:l,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void C()}]}),this.plugin.getUndoStack(T).push({label:I,undo:async()=>{await C()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,H=!1,await this.trashNotesAndAttachments(m)}})},p=St(),u=e.length>0&&p.confirmBulkDelete,h=o.length>0&&p.confirmAttachmentDelete;if(!u&&!h){await c(!1),this.focusView();return}new ne(this.app,this.titleForNode(t),e.length,o.length,h,async f=>{await c(f),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new O.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===R){new O.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new O.Notice("Couldn't find the parent note.");return}let s=e.parent??R,i=this.titleForNode(t),n=this.titleForNode(e),r=this.tree.getChildren(e.id).filter(o=>o.id!==t.id).length,a=[`"${n}" becomes a child of "${i}".`];r>0&&a.push(`${r} sibling${r===1?"":"s"} move with it.`),new At(this.app,"Swap notes?",a.join(` +`),"Swap",async o=>{o&&await this.swapParentChild(e,t,s)}).open()}offerSwapForDescendantMove(t,e){let s=this.tree.get(e);if(!s?.file){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder});return}if(s.parent!==t.id){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under "${this.titleForNode(s)}" \u2014 it's a deeper descendant. Only direct parent \u2194 child swaps are supported (try moving "${this.titleForNode(s)}" up first, then swap).`,kind:"warning",category:"move",affectedIds:[t.id,s.id],folder:this.noteFolder});return}let i=this.titleForNode(t),n=this.titleForNode(s),r=this.tree.getChildren(t.id).filter(o=>o.id!==s.id).length,a=[`"${i}" becomes a child of "${n}".`];r>0&&a.push(`${r} sibling${r===1?"":"s"} move with it.`),new At(this.app,"Confirm Note Swap",a.join(` +`),"Swap",async o=>{if(!o)return;let l=t.parent??R;await this.swapParentChild(t,s,l)}).open()}async swapParentChild(t,e,s){if(!t.file||!e.file)return;if(e.parent!==t.id){new O.Notice("Swap aborted: parent/child relationship changed.");return}let i=this.noteFolder,n=t.parent,r=this.tree.getChildren(t.id).filter(h=>h.id!==e.id).filter(h=>!!h.file),a=r.map(h=>({id:h.id,path:h.file.path,was:h.parent})),o=this.order.getOrder(i,s).slice(),l=this.order.getOrder(i,e.id).slice(),c=this.order.getOrder(i,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,h=>{h.parent=s}),this.fmSync.scheduleParentChange(e.id,t.id,s),await this.app.fileManager.processFrontMatter(t.file,h=>{h.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let h of r)await this.app.fileManager.processFrontMatter(h.file,f=>{f.parent=e.id}),this.fmSync.scheduleParentChange(h.id,t.id,e.id);if(o.length>0){let h=o.includes(t.id)?o.map(f=>f===t.id?e.id:f):[...o.filter(f=>f!==e.id),e.id];this.order.setOrder(i,s,h)}let p=r.map(h=>h.id),u=[t.id,...l.filter(h=>h!==t.id&&!p.includes(h)),...p];this.order.setOrder(i,e.id,u),this.order.setOrder(i,t.id,[]),await this.order.save(i),await this.log.append({type:"parent_change",id:e.id,payload:{from:t.id,to:s,reason:"swap"}}),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e.id,reason:"swap"}});for(let h of a)await this.log.append({type:"parent_change",id:h.id,payload:{from:h.was,to:e.id,reason:"swap"}});this.tree.rebuild(i),this.pendingFocusIds=[e.id],this.render({kind:"follow-cursor"}),this.plugin.notifications.show({message:`Swapped "${this.titleForNode(e)}" \u2194 "${this.titleForNode(t)}".`,kind:"success",category:"move",affectedIds:[e.id,t.id,...p],folder:i}),this.plugin.getUndoStack(i).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let h=this.tree.get(t.id),f=this.tree.get(e.id);h?.file&&await this.app.fileManager.processFrontMatter(h.file,m=>{n==null||n===R?(delete m.parent,m.parent=R):m.parent=n}),f?.file&&await this.app.fileManager.processFrontMatter(f.file,m=>{m.parent=t.id});for(let m of a){let v=this.app.vault.getAbstractFileByPath(m.path);v&&await this.app.fileManager.processFrontMatter(v,y=>{m.was==null?y.parent=R:y.parent=m.was})}this.order.setOrder(i,s,o),this.order.setOrder(i,e.id,l),this.order.setOrder(i,t.id,c),await this.order.save(i),this.tree.rebuild(i),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,s)}})}async changeParent(t,e,s={record:!0}){if(!t.file)return;let i=t.file,n=t.parent,r=o=>o??R;if(r(n)===r(e)){if(!s.quiet){let o=this.titleForNode(t),l=e===R?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${o}" is already under ${l}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return}if(e===t.id){s.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder});return}if(e!==R&&this.isDescendant(e,t.id)){s.quiet||this.offerSwapForDescendantMove(t,e);return}let a=this.collectAuthorIds([t]);if(await this.app.fileManager.processFrontMatter(i,o=>{o.parent=e}),this.fmSync.scheduleParentChange(t.id,n,e),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e}}),this.pendingFocusIds=[t.id],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),!s.quiet){let o=this.tree.get(e),l=o?this.titleForNode(o):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${l}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===R?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(s.record!==!1){let o=this.noteFolder,l=i.path,c=t.id;this.plugin.getUndoStack(o).push({label:"Move note",undo:async()=>{let p=this.app.vault.getAbstractFileByPath(l);if(p){await this.app.fileManager.processFrontMatter(p,u=>{u.parent=n}),this.pendingFocusIds=[c],this.focusId!==n&&this.focusId!==e?(this.selection.clear(),this.cursorIdx=-1):this.focusId===e&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(o),this.render({kind:"follow-cursor"});{let u=this.selectionGuardKey,h=()=>{if(this.selectionGuardKey!==u||this.selection.has(c))return;let f=this.currentChildren.findIndex(m=>m.id===c);f<0||(this.selection.add(c),this.cursorIdx=f,this.render({kind:"follow-cursor"}))};setTimeout(h,120),setTimeout(h,400)}}},redo:async()=>{let p=this.app.vault.getAbstractFileByPath(l);if(p){await this.app.fileManager.processFrontMatter(p,u=>{u.parent=e}),this.pendingFocusIds=[c],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(o),this.render({kind:"follow-cursor"});{let u=this.selectionGuardKey,h=()=>{if(this.selectionGuardKey!==u||this.selection.has(c))return;let f=this.currentChildren.findIndex(m=>m.id===c);f<0||(this.selection.add(c),this.cursorIdx=f,this.render({kind:"follow-cursor"}))};setTimeout(h,120),setTimeout(h,400)}}}})}}};Dt.CONTRIB_DEBOUNCE_MS=4e3,Dt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Dt.EXTERNAL_WRITE_GRACE_MS=1500,Dt.EXTERNAL_QUIESCENCE_MS=5e3;var ms=Dt;function dn(g,d){return!d||g.metaKey||g.ctrlKey||g.altKey?!1:g.key.toLowerCase()===d.toLowerCase()}function pe(g,d){return d?d.includes("+")?hn(g,d):dn(g,d):!1}function at(g,d){if(!d)return!1;let{primary:t,secondary:e,preferRight:s,useBoth:i}=d;return t&&e?i?pe(g,t)||pe(g,e):s?pe(g,e):pe(g,t):pe(g,t)||pe(g,e)}function Ys(g){if(!g)return"";let d=O.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return g.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?d?"Cmd":"Ctrl":e.toLowerCase()==="alt"?d?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function hn(g,d){if(!d)return!1;let t=d.split("+").map(p=>p.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),s=new Set(t.slice(0,-1).map(p=>p.toLowerCase())),i=s.has("mod"),n=s.has("ctrl")||s.has("control"),r=s.has("cmd")||s.has("meta")||s.has("command"),a=s.has("alt")||s.has("option"),o=s.has("shift"),c=O.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?g.metaKey:g.ctrlKey;return i&&!c||n&&!g.ctrlKey||r&&!g.metaKey||a!==g.altKey||o!==g.shiftKey||!i&&(!n&&g.ctrlKey||!r&&g.metaKey)?!1:g.key.toLowerCase()===e}function pn(g){let d=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(g))!=null;)d.push({lang:e[3].trim(),code:e[4]});return d}function gs(g){return g.split("/").map(d=>d.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function un(g,d,t){let e=new Set(d),s=g.filter(n=>!e.has(n)),i=g.findIndex(n=>e.has(n));if(i<0)return g.slice();switch(t){case"top":return[...d,...s];case"bottom":return[...s,...d];case"up":{let n=Math.max(0,i-1),r=s.slice();return r.splice(n,0,...d),r}case"down":{let n=(()=>{let l=-1;return g.forEach((c,p)=>{e.has(c)&&(l=p)}),l})(),r=0;for(let l=0;l<Math.min(g.length,n+2);l++)e.has(g[l])||r++;let a=Math.min(s.length,r),o=s.slice();return o.splice(a,0,...d),o}}}function Ai(g,d){if(g.length!==d.length)return!1;for(let t=0;t<g.length;t++)if(g[t]!==d[t])return!1;return!0}ae();var vs=class{constructor(d,t,e){this.app=d;this.dirOk=!1;this.writeChain=Promise.resolve();this.baseDir=t.replace(/\/+$/,""),this.logPath=`${this.baseDir}/log.jsonl`,this.statePath=`${this.baseDir}/state.json`,this.getAuthor=e??(()=>"")}getLogPath(){return this.logPath}getDir(){return this.baseDir}async ensureDir(){if(this.dirOk)return;let d=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let s of t)e=e?`${e}/${s}`:s,await d.exists(e)||await d.mkdir(e);this.dirOk=!0}append(d){let t=d.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...d};t?e.author=t:delete e.author;let s=JSON.stringify(e)+` +`;return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let i=this.app.vault.adapter;if(typeof i.append=="function")await i.append(this.logPath,s);else{let n=await i.exists(this.logPath)?await i.read(this.logPath):"";await i.write(this.logPath,n+s)}}catch(i){console.warn("Stashpad: log append failed",i)}}),Promise.resolve()}async readState(){let d=this.app.vault.adapter;if(!await d.exists(this.statePath))return{};try{return JSON.parse(await d.read(this.statePath))}catch{return{}}}async writeState(d){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(d,null,2))}};Tt();var ys=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(d){for(this.undoStack.push(d),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let d=this.undoStack.pop();if(!d)return null;try{await d.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(d),d}async redo(){let d=this.redoStack.pop();if(!d)return null;try{await d.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(d),d}peekUndoLabel(){return this.undoStack[this.undoStack.length-1]?.label??null}peekRedoLabel(){return this.redoStack[this.redoStack.length-1]?.label??null}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[]}};var ws=class{constructor(d,t){this.app=d;this.data={version:1,authors:{}};this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/authors.json`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let d=this.app.vault.adapter;if(await d.exists(this.path)){let t=JSON.parse(await d.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(d){console.warn("[Stashpad] author registry load failed; starting empty",d),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((d,t)=>(t.lastSeen??"").localeCompare(d.lastSeen??""))}get(d){return this.data.authors[d]??null}record(d){let t=(d.id??"").trim();if(!t)return!1;let e=d.at??new Date().toISOString(),s=(d.name??"").trim(),i=this.data.authors[t],n=!1;if(!i)this.data.authors[t]={id:t,name:s,role:d.role?.trim()||void 0,department:d.department?.trim()||void 0,firstSeen:e,lastSeen:e,renames:[]},n=!0;else{if(s&&s!==i.name&&(i.renames.push({from:i.name,to:s,at:e}),i.name=s,n=!0),d.role!==void 0){let r=d.role.trim()||void 0;r!==i.role&&(i.role=r,n=!0)}if(d.department!==void 0){let r=d.department.trim()||void 0;r!==i.department&&(i.department=r,n=!0)}i.lastSeen=e}return n&&this.save(),n}replaceAll(d,t){let e=t??new Date().toISOString(),s={};for(let i of d){let n=(i.id??"").trim();if(!n)continue;let r=this.data.authors[n],a=(i.name??"").trim()||r?.name||"",o=r?.renames?[...r.renames]:[];r&&a&&a!==r.name&&o.push({from:r.name,to:a,at:e}),s[n]={id:n,name:a,role:i.role?.trim()||r?.role||void 0,department:i.department?.trim()||r?.department||void 0,firstSeen:r?.firstSeen??e,lastSeen:e,renames:o}}this.data={version:1,authors:s},this.save()}async ensureDir(){if(this.dirOk)return;let d=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),s="";for(let i of e)s=s?`${s}/${i}`:i,await d.exists(s)||await d.mkdir(s);this.dirOk=!0}save(){return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.write(this.path,JSON.stringify(this.data,null,2))}catch(d){console.warn("[Stashpad] author registry save failed",d)}}),this.writeChain}};var bt=require("obsidian");Tt();Mt();ae();Ht();var Di=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),Pi="_archive",ue=class ue{constructor(d){this.plugin=d;this.pending=new Map;this.pendingFolders=new Map;this.suppressed=new Set;this.armed=!1;this.drainTimer=null;this.draining=!1}setArmed(d){this.armed=d}get app(){return this.plugin.app}enqueue(d){this.armed&&this.plugin.settings.autoImport&&this.isEligiblePath(d)&&(this.pending.set(d.path,Date.now()),this.arm())}enqueueFolder(d){if(!this.armed||!this.plugin.settings.autoImport||this.suppressed.has(d.path))return;let t=d.parent?.path?.replace(/\/+$/,"")??"";this.plugin.discoverStashpadFolders().includes(t)&&(Di.has(d.name)||(this.pendingFolders.set(d.path,Date.now()),this.arm()))}arm(){this.drainTimer!=null&&window.clearTimeout(this.drainTimer),this.drainTimer=window.setTimeout(()=>void this.drain(),ue.DEBOUNCE_MS)}suppress(d,t=4e3){this.suppressed.add(d),window.setTimeout(()=>this.suppressed.delete(d),t)}async createNote(d,t){this.suppress(d,6e4),await this.app.vault.create(d,t)}isEligiblePath(d){if(this.suppressed.has(d.path)||d.extension===Qt||d.extension==="edtz")return!1;let t=d.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return Di.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}async isStillImportable(d){if(!this.isEligiblePath(d))return!1;if(d.extension==="md")try{let{fm:t}=he(await this.app.vault.read(d));if(t&&typeof t.id=="string"&&t.id)return!1}catch{}return!0}async drain(){if(this.drainTimer=null,!this.draining){this.draining=!0;try{let d=[...this.pending.keys()];this.pending.clear();let t=d.map(p=>this.app.vault.getAbstractFileByPath(p)).filter(p=>p instanceof bt.TFile),e=[];for(let p of t)await this.isStillImportable(p)&&e.push(p);let s=[...this.pendingFolders.keys()];this.pendingFolders.clear();let i=s.map(p=>this.app.vault.getAbstractFileByPath(p)).filter(p=>p instanceof bt.TFolder).map(p=>({folder:p,files:this.filesUnder(p.path)})).filter(p=>p.files.length>0),n=i.reduce((p,u)=>p+u.files.length,0),r=e.length+n;if(r===0)return;await this.plugin.importLog.load();let a=e,o=[],l=e.filter(p=>this.plugin.importLog.findDuplicate(p.name,p.stat?.size??null));if(l.length>0){let p=l.slice(0,5).map(f=>`\u2022 ${f.name}`).join(` +`),u=l.length>5?` +\u2026and ${l.length-5} more`:"",h=await this.dupChoice(`${l.length} of these look like files you've imported before: +${p}${u} -Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(u==="skip"){let d=new Set(a.map(f=>f.path));if(r=t.filter(f=>!d.has(f.path)),r.length===0&&s.length===0){new St.Notice(`Skipped ${a.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(u==="replace")for(let d of a){let f=this.plugin.importLog.findDuplicate(d.name,d.stat?.size??null);for(let m of f?.notePaths??[]){let v=this.app.vault.getAbstractFileByPath(m);if(v instanceof St.TFile)try{o.push({path:m,content:await this.app.vault.read(v)}),await this.app.fileManager.trashFile(v)}catch(y){console.warn("[Stashpad] replace: couldn't remove prior note",m,y)}}}}if(n=r.length+i,n>=le.BATCH_CONFIRM_AT){let c=s.length?` (incl. ${s.length} folder${s.length===1?"":"s"})`:"";if(!await this.confirm("Import many files?",`You're about to auto-import ${n} files into Stashpad${c}. Proceed? -Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new St.Notice(`Import cancelled \u2014 ${n} file(s) left as-is.`);return}}let l=[];for(let c of r)try{let p=c.stat?.size??null,u=c.extension==="md"?await this.importMarkdown(c):await this.importOtherFile(c);u&&(l.push(u),this.plugin.importLog.append({ts:new Date().toISOString(),folder:u.folder,kind:u.kind,originalName:c.name,size:p,sourcePath:c.path,notePaths:u.kind==="folder"?u.notePaths:[u.notePath]}))}catch(p){console.warn("[Stashpad] import failed",c.path,p)}for(let{folder:c}of s)try{let p=await this.importFolder(c);p&&p.kind==="folder"&&(l.push(p),this.plugin.importLog.append({ts:new Date().toISOString(),folder:p.folder,kind:"folder",originalName:p.originalName,size:null,sourcePath:c.path,notePaths:p.notePaths}))}catch(p){console.warn("[Stashpad] folder import failed",c.path,p)}(l.length>0||o.length>0)&&this.announce(l,o)}finally{this.draining=!1}}}async importMarkdown(h){let t=h.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(h),{fm:s,body:i}=Ee(e),n=`${t}/${xi}`;await this.ensureFolder(n);let r=await this.uniquePath(n,h.name);await this.app.fileManager.renameFile(h,r);let o={};for(let[c,p]of Object.entries(s))Rt.includes(c)||(o[c]=p);o.id=yt(),o.parent=R,o.created=new Date().toISOString(),o.attachments=Array.isArray(s.attachments)?s.attachments:[];let a=Ft(i)||h.basename,l=await this.uniquePath(t,xt(a,o.id));return await this.app.vault.create(l,jt(o,i)),{kind:"md",folder:t,archivePath:r,notePath:l,originalName:h.name}}async importOtherFile(h){let t=h.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let s=await this.uniquePath(e,h.name);await this.app.fileManager.renameFile(h,s);let i=h.basename,n=yt(),r={id:n,parent:R,created:new Date().toISOString(),attachments:[s]},o=`${i} +Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(h==="skip"){let f=new Set(l.map(m=>m.path));if(a=e.filter(m=>!f.has(m.path)),a.length===0&&i.length===0){new bt.Notice(`Skipped ${l.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(h==="replace")for(let f of l){let m=this.plugin.importLog.findDuplicate(f.name,f.stat?.size??null);for(let v of m?.notePaths??[]){let y=this.app.vault.getAbstractFileByPath(v);if(y instanceof bt.TFile)try{o.push({path:v,content:await this.app.vault.read(y)}),await this.app.fileManager.trashFile(y)}catch(b){console.warn("[Stashpad] replace: couldn't remove prior note",v,b)}}}}if(r=a.length+n,r>=ue.BATCH_CONFIRM_AT){let p=i.length?` (incl. ${i.length} folder${i.length===1?"":"s"})`:"";if(!await this.confirm("Import many files?",`You're about to auto-import ${r} files into Stashpad${p}. Proceed? +Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new bt.Notice(`Import cancelled \u2014 ${r} file(s) left as-is.`);return}}let c=[];for(let p of a)try{let u=p.stat?.size??null,h=p.extension==="md"?await this.importMarkdown(p):await this.importOtherFile(p);h&&(c.push(h),this.plugin.importLog.append({ts:new Date().toISOString(),folder:h.folder,kind:h.kind,originalName:p.name,size:u,sourcePath:p.path,notePaths:h.kind==="folder"?h.notePaths:[h.notePath]}))}catch(u){console.warn("[Stashpad] import failed",p.path,u)}for(let{folder:p}of i)try{let u=await this.importFolder(p);u&&u.kind==="folder"&&(c.push(u),this.plugin.importLog.append({ts:new Date().toISOString(),folder:u.folder,kind:"folder",originalName:u.originalName,size:null,sourcePath:p.path,notePaths:u.notePaths}))}catch(u){console.warn("[Stashpad] folder import failed",p.path,u)}(c.length>0||o.length>0)&&this.announce(c,o)}finally{this.draining=!1}}}async importMarkdown(d){let t=d.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(d),{fm:s,body:i}=he(e),n=`${t}/${Pi}`;await this.ensureFolder(n);let r=await this.uniquePath(n,d.name);if(await this.app.fileManager.renameFile(d,r),!(this.app.vault.getAbstractFileByPath(r)instanceof bt.TFile))throw new Error(`archive move failed for ${d.path} \u2014 import aborted to avoid data loss`);let a={};for(let[p,u]of Object.entries(s))Bt.includes(p)||(a[p]=u);a.id=yt(),a.parent=R;let o=this.preservedTimes(s,d);a.created=o.created,o.modified&&(a.modified=o.modified),a.attachments=Array.isArray(s.attachments)?s.attachments:[];let l=Ft(i)||d.basename,c=await this.uniquePath(t,xt(l,a.id));return await this.createNote(c,Ut(a,i)),{kind:"md",folder:t,archivePath:r,notePath:c,originalName:d.name}}async importOtherFile(d){let t=d.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let s=await this.uniquePath(e,d.name);await this.app.fileManager.renameFile(d,s);let i=d.basename,n=yt(),r={id:n,parent:R,created:new Date().toISOString(),attachments:[qt(s)]},a=`${i} -[[${s}]] -`,a=Ft(i)||i,l=await this.uniquePath(t,xt(a,n));return await this.app.vault.create(l,jt(r,o)),{kind:"file",folder:t,attachmentPath:s,notePath:l,originalName:h.name}}filesUnder(h){let t=h.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(h){let t=h.parent.path.replace(/\/+$/,""),e=h.name,s=`${t}/${xi}`;await this.ensureFolder(s);let i=await this.uniquePath(s,e);await this.app.fileManager.renameFile(h,i);let n=this.app.vault.getAbstractFileByPath(i),r=[],o=await this.createFolderNote(t,e,R,r);return n instanceof St.TFolder&&await this.buildNotesFromArchive(n,t,o,r),{kind:"folder",folder:t,archivePath:i,notePaths:r,attachmentPaths:[],originalName:e}}async createFolderNote(h,t,e,s){let i=yt(),n={id:i,parent:e,created:new Date().toISOString(),attachments:[]},r=Ft(t)||t,o=await this.uniquePath(h,xt(r,i));return await this.app.vault.create(o,jt(n,`${t} -`)),s.push(o),i}async buildNotesFromArchive(h,t,e,s){for(let i of h.children)if(i instanceof St.TFolder){let n=await this.createFolderNote(t,i.name,e,s);await this.buildNotesFromArchive(i,t,n,s)}else if(i instanceof St.TFile)if(i.extension==="md"){let n=await this.app.vault.read(i),{fm:r,body:o}=Ee(n),a={};for(let[p,u]of Object.entries(r))Rt.includes(p)||(a[p]=u);a.id=yt(),a.parent=e,a.created=new Date().toISOString(),a.attachments=Array.isArray(r.attachments)?r.attachments:[];let l=Ft(o)||i.basename,c=await this.uniquePath(t,xt(l,a.id));await this.app.vault.create(c,jt(a,o)),s.push(c)}else{let n=yt(),r={id:n,parent:e,created:new Date().toISOString(),attachments:[i.path]},o=`${i.basename} +![[${s}]] +`,o=Ft(i)||i,l=await this.uniquePath(t,xt(o,n));return await this.createNote(l,Ut(r,a)),{kind:"file",folder:t,attachmentPath:s,notePath:l,originalName:d.name}}preservedTimes(d,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),s=e(d.created)?d.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),i=e(d.modified)?d.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:s,modified:i}}filesUnder(d){let t=d.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(d){let t=d.parent.path.replace(/\/+$/,""),e=d.name,s=`${t}/${Pi}`;await this.ensureFolder(s);let i=await this.uniquePath(s,e);await this.app.fileManager.renameFile(d,i);let n=this.app.vault.getAbstractFileByPath(i),r=[],a=await this.createFolderNote(t,e,R,r);return n instanceof bt.TFolder&&await this.buildNotesFromArchive(n,t,a,r),{kind:"folder",folder:t,archivePath:i,notePaths:r,attachmentPaths:[],originalName:e}}async createFolderNote(d,t,e,s){let i=yt(),n={id:i,parent:e,created:new Date().toISOString(),attachments:[]},r=Ft(t)||t,a=await this.uniquePath(d,xt(r,i));return await this.createNote(a,Ut(n,`${t} +`)),s.push(a),i}async buildNotesFromArchive(d,t,e,s){for(let i of d.children)if(i instanceof bt.TFolder){let n=await this.createFolderNote(t,i.name,e,s);await this.buildNotesFromArchive(i,t,n,s)}else if(i instanceof bt.TFile)if(i.extension==="md"){let n=await this.app.vault.read(i),{fm:r,body:a}=he(n),o={};for(let[u,h]of Object.entries(r))Bt.includes(u)||(o[u]=h);o.id=yt(),o.parent=e;let l=this.preservedTimes(r,i);o.created=l.created,l.modified&&(o.modified=l.modified),o.attachments=Array.isArray(r.attachments)?r.attachments:[];let c=Ft(a)||i.basename,p=await this.uniquePath(t,xt(c,o.id));await this.createNote(p,Ut(o,a)),s.push(p)}else{let n=yt(),r={id:n,parent:e,created:new Date().toISOString(),attachments:[qt(i.path)]},a=`${i.basename} -[[${i.path}]] -`,a=Ft(i.basename)||i.basename,l=await this.uniquePath(t,xt(a,n));await this.app.vault.create(l,jt(r,o)),s.push(l)}}recordNotePaths(h){return h.kind==="folder"?h.notePaths:[h.notePath]}announce(h,t=[]){let e=h[0]?.folder??"",s=h.length,i=t.length?`, replaced ${t.length}`:"",n=!1,r=async()=>{n||(n=!0,await this.undo(h,t))};this.plugin.notifications.show({message:`Imported ${s} file${s===1?"":"s"}${i} into \`${e.split("/").pop()}\`.`,kind:"success",category:"import",duration:0,folder:e,affectedPaths:h.flatMap(o=>this.recordNotePaths(o)),actions:[{label:"Undo import",onClick:()=>void r()}]}),e&&this.plugin.getUndoStack(e).push({label:`Import ${s} file${s===1?"":"s"}`,undo:async()=>{await r()},redo:async()=>{}})}async undo(h,t=[]){for(let e of h)try{if(e.kind==="md"){let s=this.app.vault.getAbstractFileByPath(e.notePath);s instanceof St.TFile&&await this.app.fileManager.trashFile(s);let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof St.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(i,n)}}else if(e.kind==="file"){let s=this.app.vault.getAbstractFileByPath(e.notePath);s instanceof St.TFile&&await this.app.fileManager.trashFile(s);let i=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(i instanceof St.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(i,n)}}else{for(let i of e.notePaths){let n=this.app.vault.getAbstractFileByPath(i);n instanceof St.TFile&&await this.app.fileManager.trashFile(n)}for(let i of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(i);n instanceof St.TFile&&await this.app.fileManager.trashFile(n)}let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof St.TFolder){let i=await this.uniquePath(e.folder,e.originalName);this.suppress(i),await this.app.fileManager.renameFile(s,i)}}}catch(s){console.warn("[Stashpad] import undo failed",e,s)}for(let e of t)try{await this.app.vault.adapter.exists(e.path)||await this.app.vault.create(e.path,e.content)}catch(s){console.warn("[Stashpad] import undo: couldn't restore replaced note",e.path,s)}new St.Notice(`Undid import of ${h.length} file(s).`)}pickFilesInto(h){let t=document.createElement("input");t.type="file",t.multiple=!0,t.style.display="none",t.onchange=async()=>{let e=Array.from(t.files??[]);if(t.remove(),e.length===0)return;let s=0;for(let i of e)try{let n=await i.arrayBuffer(),r=await this.uniquePath(h,i.name);await this.app.vault.createBinary(r,n),s++}catch(n){console.warn("[Stashpad] file-picker import failed",i.name,n)}s>0&&new St.Notice(`Added ${s} file(s) to "${h.split("/").pop()}" \u2014 importing\u2026`)},document.body.appendChild(t),t.click()}async importLooseFilesIn(h){let t=h.replace(/\/+$/,""),e=this.app.vault.getFiles().filter(i=>(i.parent?.path?.replace(/\/+$/,"")??"")===t).filter(i=>this.isStillImportable(i));if(e.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let i of e)try{let n=i.stat?.size??null,r=i.extension==="md"?await this.importMarkdown(i):await this.importOtherFile(i);r&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:r.folder,kind:r.kind,originalName:i.name,size:n,sourcePath:i.path,notePaths:r.kind==="folder"?r.notePaths:[r.notePath]}))}catch(n){console.warn("[Stashpad] loose-file import failed",i.path,n)}return s}defaultDestination(){let t=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder;return t&&this.plugin.discoverStashpadFolders().includes(t)?t:this.plugin.discoverStashpadFolders()[0]??null}confirm(h,t,e){return new Promise(s=>{new It(this.app,h,t,e,s).open()})}dupChoice(h){return new Promise(t=>{new we(this.app,h,t).open()})}async ensureFolder(h){let t=this.app.vault.adapter,e=h.split("/").filter(Boolean),s="";for(let i of e){s=s?`${s}/${i}`:i;try{await t.exists(s)||await t.mkdir(s)}catch(n){if(!/already exists/i.test(n.message))throw n}}}async uniquePath(h,t){let e=this.app.vault.adapter,s=t.lastIndexOf("."),i=s>0?t.slice(0,s):t,n=s>0?t.slice(s):"",r=`${h}/${t}`,o=0;for(;await e.exists(r);)o+=1,r=`${h}/${i}-${o}${n}`;return r}};le.DEBOUNCE_MS=900,le.BATCH_CONFIRM_AT=8;var gs=le;var vs=class{constructor(h,t){this.app=h;this.entries=[];this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/import-log.jsonl`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let h=this.app.vault.adapter;if(await h.exists(this.path)){let t=await h.read(this.path);for(let e of t.split(/\r?\n/))if(e.trim())try{this.entries.push(JSON.parse(e))}catch{}}}catch(h){console.warn("[Stashpad] import log load failed",h)}}}recent(){return[...this.entries].reverse()}findDuplicate(h,t){for(let e=this.entries.length-1;e>=0;e--){let s=this.entries[e];if(s.originalName===h&&(t==null||s.size==null||s.size===t))return s}return null}append(h){this.entries.push(h),this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.append(this.path,JSON.stringify(h)+` -`)}catch(t){console.warn("[Stashpad] import log append failed",t)}})}async ensureDir(){if(this.dirOk)return;let h=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),s="";for(let i of e)s=s?`${s}/${i}`:i,await h.exists(s)||await h.mkdir(s);this.dirOk=!0}};var ys=class extends et.Plugin{constructor(){super(...arguments);this.settings={...Ht};this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.settingTab=null;this.stashpadSelectionListeners=new Set;this.stashpadContentListeners=new Set;this._notifications=null;this._authorRegistry=null;this._importService=null;this._importLog=null;this.sweptFolders=new Set;this.notifiedBuildVersion=null;this.authorRenameInFlight=new Set;this.notifPersistenceWired=!1;this.notifSaveTimer=null;this.LAST_CURSOR_LS_KEY="stashpad:last-cursor";this.writeChain=Promise.resolve()}get notifications(){return this._notifications||(this._notifications=new Ue(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new ms(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new gs(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new vs(this.app,this.pluginPrivatePath())),this._importLog}pluginPrivatePath(t=""){let s=`${this.manifest.dir.replace(/\/+$/,"")}/.stashpad`;return t?`${s}/${t.replace(/^\/+/,"")}`:s}newLog(){return new us(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),s=async()=>{let o=e.split("/").filter(Boolean),a="";for(let l of o)a=a?`${a}/${l}`:l,await t.exists(a)||await t.mkdir(a)},i=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,n=this.pluginPrivatePath("data.json");if(await t.exists(i)&&!await t.exists(n))try{await s();let o=await t.read(i);await t.write(n,o),console.debug("[Stashpad] migrated data.json \u2192",n)}catch(o){console.warn("Stashpad: data.json migration failed",o)}let r=".stashpad";if(await t.exists(r))try{await s();let o=await t.list(r);for(let a of o.files){let l=a.replace(/^.*\//,""),c=this.pluginPrivatePath(l);if(!await t.exists(c))try{let p=await t.read(a);await t.write(c,p),console.debug("[Stashpad] migrated",a,"\u2192",c)}catch(p){console.warn(`Stashpad: failed to migrate ${a}`,p)}}}catch(o){console.warn("Stashpad: .stashpad migration scan failed",o)}}async loadData(){let t=this.app.vault.adapter,e=this.pluginPrivatePath("data.json");if(!await t.exists(e))return null;try{return JSON.parse(await t.read(e))}catch(s){return console.warn("Stashpad: data.json parse failed",s),null}}async saveData(t){let e=this.app.vault.adapter,s=this.pluginPrivatePath();if(!await e.exists(s)){let i=s.split("/").filter(Boolean),n="";for(let r of i)n=n?`${n}/${r}`:r,await e.exists(n)||await e.mkdir(n)}await e.write(this.pluginPrivatePath("data.json"),JSON.stringify(t,null,2))}async createNewStashpad(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!e)throw new Error("Folder name is empty");let s=this.app.vault.adapter,i=e.split("/").filter(Boolean),n="";for(let l of i)n=n?`${n}/${l}`:l,await s.exists(n)||await s.mkdir(n);let r=`${e}/Home.md`;if(await s.exists(r)){let l=this.app.vault.getAbstractFileByPath(r);l&&await this.app.fileManager.processFrontMatter(l,c=>{(typeof c.id!="string"||!c.id)&&(c.id=R),"parent"in c||(c.parent=null),(typeof c.created!="string"||!c.created)&&(c.created=new Date().toISOString())});return}let o=new Date().toISOString(),a=["---",`id: ${R}`,"parent: null",`created: ${o}`,"---","Home"].join(` -`);await this.app.vault.create(r,a);try{await this.seedLocalAuthorStub(e)}catch{}}collectColorsInFolder(t){let e=new Map,s=t.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let r=n.parent?.path?.replace(/\/+$/,"")??"";if(r!==s&&!r.startsWith(s+"/"))continue;let o=this.app.metadataCache.getFileCache(n)?.frontmatter,a=typeof o?.color=="string"?o.color.trim():"";if(!a||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(a))continue;let l=a.toLowerCase();e.set(l,(e.get(l)??0)+1)}let i=[...e.entries()].map(([n,r])=>({hex:n,count:r}));return i.sort((n,r)=>r.count-n.count||n.hex.localeCompare(r.hex)),i}async recolorAllInFolder(t,e,s){let i=t.replace(/\/+$/,""),n=e.toLowerCase(),r=0;for(let a of this.app.vault.getMarkdownFiles()){let l=a.parent?.path?.replace(/\/+$/,"")??"";if(l!==i&&!l.startsWith(i+"/"))continue;let c=this.app.metadataCache.getFileCache(a)?.frontmatter;if((typeof c?.color=="string"?c.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(a,u=>{s?u.color=s:delete u.color}),r++}catch(u){console.warn(`Stashpad: recolor failed for ${a.path}`,u)}}let o=this.settings.colorAliases?.[i];if(o){let a=o[n];a&&(delete o[n],s&&(o[s.toLowerCase()]=a),Object.keys(o).length===0&&delete this.settings.colorAliases[i],await this.saveSettings())}return r}getColorAlias(t,e){let s=t.replace(/\/+$/,""),i=this.settings.colorAliases?.[s];if(!i)return;let n=i[e.toLowerCase()];return n&&n.trim()?n:void 0}async setColorAlias(t,e,s){let i=t.replace(/\/+$/,""),n=e.toLowerCase();this.settings.colorAliases||(this.settings.colorAliases={}),this.settings.colorAliases[i]||(this.settings.colorAliases[i]={});let r=this.settings.colorAliases[i],o=s.trim();o?r[n]=o:delete r[n],Object.keys(r).length===0&&delete this.settings.colorAliases[i],await this.saveSettings()}async waitForStashpadFolder(t,e=2e3){let s=t.trim().replace(/^\/+|\/+$/g,"");if(!s)return;let i=Date.now();for(;Date.now()-i<e;){if(this.discoverStashpadFolders().includes(s))return;await new Promise(n=>setTimeout(n,80))}}discoverStashpadFolders(){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(e)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let i=e.parent?.path?.replace(/\/+$/,"")??"";i&&t.add(i)}return[...t].sort()}searchableFolders(t){let e=new Set(this.settings.searchIncludedFolders),s=new Set(this.settings.searchExcludedFolders),n=this.discoverStashpadFolders().filter(a=>e.size>0?e.has(a):!s.has(a)),r=(t||"").trim().replace(/\/+$/,""),o=n.filter(a=>a!==r);return r&&o.unshift(r),o}async maybeSweepFolder(t){let e=(t||"").trim().replace(/\/+$/,"");!e||this.sweptFolders.has(e)||(this.sweptFolders.add(e),setTimeout(()=>{this.runSweep(e,{silent:!0})},3e3))}async runIntegrityCheckOnFolder(t){let e=(t||"").trim().replace(/\/+$/,"");e&&await this.runSweep(e,{silent:!1})}async runSweep(t,e){try{let s=this.newLog(),i={},n=this.app.vault.getMarkdownFiles().filter(l=>l.path===t||l.path.startsWith(t+"/"));for(let l of n){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,p=typeof c?.id=="string"?c.id.trim():"";if(!p)continue;let u=c&&"parent"in c?c.parent??null:null;i[p]={parent:u,path:l.path}}let r=await s.readState(),o=l=>l===t||l.startsWith(t+"/");if(!e.silent){for(let[l,c]of Object.entries(i)){let p=r[l];p?p.parent!==c.parent?await s.append({type:"parent_change",id:l,payload:{from:p.parent,to:c.parent}}):p.path!==c.path&&await s.append({type:"rename",id:l,payload:{from:p.path,to:c.path}}):await s.append({type:"create",id:l,payload:{path:c.path,parent:c.parent}})}for(let[l,c]of Object.entries(r))!i[l]&&o(c.path)&&await s.append({type:"missing",id:l,payload:{lastPath:c.path}})}let a={};for(let[l,c]of Object.entries(r))o(c.path)||(a[l]=c);for(let[l,c]of Object.entries(i))a[l]=c;await s.writeState(a)}catch(s){console.warn("Stashpad: integrity sweep failed",s)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new fs,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),this.settingTab=new Ge(this.app,this),this.addSettingTab(this.settingTab),await this.authorRegistry.load();{let d=(this.settings.authorId??"").trim();d&&this.authorRegistry.record({id:d,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.app.workspace.onLayoutReady(()=>{window.setTimeout(()=>{this.seedLocalAuthorStubsEverywhere()},4e3),window.setTimeout(()=>this.syncObsidianExcludedArchives(),4500),window.setTimeout(()=>this.importService.setArmed(!0),2500)}),this.registerView(mt,d=>new hs(d,this)),this.registerView(Ut,d=>new Xe(d,this)),this.registerView($t,d=>new Re(d,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",d=>{d&&d.view.getViewType()===mt&&(this.lastActiveStashpadLeaf=d,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(Ut).length===0&&setTimeout(()=>{Qe(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let d=Nt(),f=!!d&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===d,m=!!f&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",m),document.body.classList.toggle("stashpad-active",!!f)};this.register(ci(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t));let e=d=>{try{let f=Array.from(document.querySelectorAll("style")).filter(m=>(m.textContent??"").includes(".stashpad-"));for(let m of f){let v=m.id||"",y=v?`style[data-stashpad-source="${v}"]`:null;if(y&&d.head.querySelector(y))continue;let b=d.createElement("style");v?b.setAttribute("data-stashpad-source",v):b.setAttribute("data-stashpad-source","anon"),b.textContent=m.textContent??"",d.head.appendChild(b)}}catch(f){console.warn("[Stashpad] inject popout styles failed",f)}};this.registerEvent(this.app.workspace.on("window-open",d=>{let f=d?.doc??d?.win?.document??null;f&&e(f)})),setTimeout(()=>{try{let d=this.app.workspace;typeof d.iterateAllLeaves=="function"&&d.iterateAllLeaves(f=>{let m=f?.view?.containerEl?.ownerDocument;m&&m!==document&&e(m)})}catch{}},200),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let s=window.visualViewport,i=()=>{let d=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),f=d&&d.isConnected?d.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${f}px`);let m=0;s&&(m=Math.max(0,window.innerHeight-s.height-s.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${m}px`),document.body.classList.toggle("stashpad-keyboard-open",m>100)};i(),s&&(s.addEventListener("resize",i),s.addEventListener("scroll",i),this.register(()=>{s.removeEventListener("resize",i),s.removeEventListener("scroll",i)})),window.addEventListener("resize",i),this.register(()=>window.removeEventListener("resize",i)),requestAnimationFrame(i),setTimeout(i,250),setTimeout(i,1e3),this.addRibbonIcon("list-tree","Open Stashpad",()=>{if(this.discoverStashpadFolders().length===0){this.activateView({reveal:!0});return}this.openFolderPicker()}).addEventListener("contextmenu",d=>{d.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{Be(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{Qe(this.app)}),this.addCommand({id:"stashpad-open",name:"Open Stashpad in new tab",callback:()=>{if(this.discoverStashpadFolders().length>=2){this.openFolderPicker();return}this.activateView({reveal:!1})}}),this.addCommand({id:"stashpad-reveal",name:"Reveal or open Stashpad",callback:()=>void this.activateView({reveal:!0})});let r=d=>{let f=Nt();f&&typeof f[d]=="function"&&f[d]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>r("toggleSplit")}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>r("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>r("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>r("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>r("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>r("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>r("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>r("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>r("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>r("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>r("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>r("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>r("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>r("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>r("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>r("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>r("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>r("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>r("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>r("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>r("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>r("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>r("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>r("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>r("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>r("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>r("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>r("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>r("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>r("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>r("cmdSetDue")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>r("cmdAssign")}),this.addCommand({id:"stashpad-open-import-log",name:"Open import log",callback:async()=>{await this.importLog.load();let{ImportLogModal:d}=await Promise.resolve().then(()=>(Bt(),be));new d(this.app,this.importLog.recent()).open()}}),this.addCommand({id:"stashpad-import-files",name:"Import file(s) into Stashpad\u2026",callback:()=>this.openImportPicker()}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>r("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>r("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void Be(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void Qe(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:d=>{let f=this.app.workspace.getActiveFile(),m=!!f&&f.extension==="md"&&this.isStashpadNoteFile(f);return d||m&&f&&this.revealNoteInStashpad(f),m}});let o=Object.keys(Se);for(let d of o){let f=Se[d];this.addCommand({id:`stashpad-open-panels-${d}`,name:`Open Stashpad panel: ${f.label}`,callback:async()=>{await Be(this.app),this.app.workspace.getLeavesOfType($t)[0]?.view?.setActivePanel?.(d)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>r("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>r("cmdTogglePin")}),this.addCommand({id:"stashpad-open-tiny",name:"Open Stashpad in tiny window",callback:()=>void this.openTinyWindow()}),this.addCommand({id:"stashpad-clone-tab",name:"Clone (duplicate / copy) this Stashpad tab",callback:()=>r("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>r("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>r("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>r("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>r("cmdImportStash")}),this.addCommand({id:"stashpad-pick-folder",name:"Stashpad: open / switch / create folder\u2026",callback:()=>this.openFolderPicker()}),this.addCommand({id:"stashpad-run-integrity-check",name:"Run integrity check on active Stashpad folder",checkCallback:d=>{let f=Nt(),m=f&&f.noteFolder;return m?(d||(new et.Notice(`Running integrity check on "${m}"\u2026`),this.runIntegrityCheckOnFolder(m).then(()=>{new et.Notice("Integrity check complete \u2014 see Stashpad log.")})),!0):!1}}),this.addCommand({id:"stashpad-fix-orphans",name:"Set missing parents to Home (orphan fix)",callback:()=>void this.fixOrphanParents()}),this.addCommand({id:"stashpad-rebuild-author-registry",name:"Rebuild author registry (scan authors + note frontmatter)",callback:async()=>{new et.Notice("Stashpad: rebuilding author registry\u2026");try{let d=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${d.total} author(s) \u2014 ${d.fromStubs} from stubs, ${d.fromNotes} from note links.`,kind:"success",category:"system"})}catch(d){new et.Notice(`Author registry rebuild failed: ${d.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new et.Notice("Stashpad: restoring author stubs\u2026");try{let d=await this.restoreMissingAuthorStubs();this.notifications.show({message:d.created>0?`Restored ${d.created} author stub(s) across ${d.folders} folder(s).`:`No missing author stubs \u2014 all present across ${d.folders} folder(s).`,kind:"success",category:"system"})}catch(d){new et.Notice(`Restore author stubs failed: ${d.message}`)}}}),this.addCommand({id:"stashpad-rebootstrap-all",name:"Rebootstrap all Stashpad folders (backfill metadata + rename stale titles)",callback:async()=>{new et.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:d,fmChecked:f,fmWritten:m,slugsRenamed:v,authors:y,imported:b}=await this.rebootstrapAllFolders(),k=[];k.push(`rebootstrapped ${d.length} folder${d.length===1?"":"s"}`),b>0&&k.push(`imported ${b} loose file${b===1?"":"s"}`),m>0&&k.push(`updated ${m} note${m===1?"":"s"}' metadata`),v>0&&k.push(`renamed ${v} note${v===1?"":"s"}`),y>0&&k.push(`${y} author${y===1?"":"s"} in registry`),k.push(`(checked ${f} total)`),new et.Notice(`Stashpad: ${k.join(" \xB7 ")}`)}catch(d){new et.Notice(`Stashpad: rebootstrap failed (${d.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:d=>{let f=this.app.workspace.getActiveFile();return!f||f.extension!=="md"?!1:(d||this.adoptNote(f),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Bt(),be)).then(({NotificationHistoryModal:d,LogModal:f})=>{new d(this.app,this.notifications,async()=>{let m=this.app.vault.adapter,v=this.pluginPrivatePath("log.jsonl");if(!await m.exists(v)){new et.Notice("No log yet \u2014 make some changes first.");return}let y=await m.read(v);new f(this.app,y,v).open()},this.settings.authorId||null,m=>this.lookupNoteAuthorIds(m)).open()})}});let a=[{key:"prefixTimestampsOnCopy",label:"Prefix timestamps when copying"},{key:"useTemplatesFormat",label:"Use Templates plugin date/time formats"},{key:"autoNavOnMoveIn",label:"Auto-navigate into parent on move IN"},{key:"autoNavOnMoveOut",label:"Auto-navigate to destination on move OUT"},{key:"confirmCrossParentDrag",label:"Confirm cross-parent drag-and-drop"},{key:"confirmBulkDelete",label:"Confirm bulk deletes"},{key:"confirmAttachmentDelete",label:"Offer to delete attachments with note"},{key:"autofocusComposerAfterSend",label:"Autofocus composer after sending"},{key:"popoutDuplicates",label:"Open in new window \u2014 duplicate tab"},{key:"autoExpandCursorRow",label:"Expand the cursor row's body automatically"},{key:"autoOpenDetailPanel",label:"Auto-open the detail panel"},{key:"doubleClickToFocus",label:"Double-click a note to open it"}];for(let d of a){let f=`stashpad-toggle-${String(d.key).replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`)}`;this.addCommand({id:f,name:`Toggle: ${d.label}`,callback:async()=>{let m=!this.settings[d.key];this.settings[d.key]=m,await this.saveSettings(),new et.Notice(`${d.label}: ${m?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id),setTimeout(()=>this.settingTab?.focusSearchInput?.(),0))}});for(let d of Ze)this.addCommand({id:`stashpad-open-settings-${d.id}`,name:`Open Stashpad settings: ${d.label}`,callback:()=>{let f=this.app.setting;!f?.open||!f?.openTabById||(this.settingTab?.openToTab(d.id),f.open(),f.openTabById(this.manifest.id))}});let l=()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id),setTimeout(()=>{document.getElementById("stashpad-jd-index-section")?.scrollIntoView({behavior:"smooth",block:"start"})},100))};this.addCommand({id:"stashpad-preview-jd-index",name:"Preview JD index (overwrites home note body)",callback:async()=>{try{let{buildJdIndexPreview:d}=await Promise.resolve().then(()=>(Te(),We)),f=await d(this.app,this,this.settings);if(f.error==="no-dest"){new et.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(f.error==="no-home"){new et.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:m}=await Promise.resolve().then(()=>(Te(),We));m(this.app,f)}catch(d){console.error("[stashpad] preview failed",d),new et.Notice(`Preview failed: ${d?.message??d}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:d,scanForJdNotes:f,JdBuildConfirmModal:m}=await Promise.resolve().then(()=>(Te(),We));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new et.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}let y=f(this.app,this,this.settings);new m(this.app,this,this.settings,y.indexed.length,async()=>{try{let k=await d(this.app,this,this.settings);if(k.error==="no-dest"){new et.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(k.error==="dest-not-stashpad"){new et.Notice(`"${k.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),l();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new et.Notice(`Index built: ${k.created} created, ${k.updated} updated, ${k.skipped} skipped \u2192 ${k.destFolder}`,6e3)}catch(k){console.error("[stashpad] build failed",k),new et.Notice(`Build failed: ${k?.message??k}`,8e3)}}).open()}catch(d){console.error("[stashpad] build failed",d),new et.Notice(`Build failed: ${d?.message??d}`,8e3)}}});let c=d=>{if(d.extension!==Gt)return;let f=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),m=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!f)return;let v=d.parent?.path||"";if((v.split("/").pop()??"")!==f||m&&v.endsWith(`/${m}`))return;let b=v.slice(0,v.length-f.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(d,b)};this.registerEvent(this.app.vault.on("create",d=>{d instanceof et.TFile&&c(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof et.TFile&&c(d)}));let p=d=>{if(d.extension!=="md")return;let f=d.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(f)&&setTimeout(()=>{this.fixOrphanParentForFile(d)},800)},u=d=>{if(d.extension!=="md")return;let f=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!f)return;let m=d.parent?.path?.replace(/\/+$/,"")??"";if((m.split("/").pop()??"")!==f)return;let y=m.slice(0,m.length-f.length).replace(/\/+$/,"");!y||!this.discoverStashpadFolders().includes(y)||setTimeout(()=>{this.adoptMarkdownDrop(d,y)},200)};this.registerEvent(this.app.vault.on("create",d=>{d instanceof et.TFile&&(p(d),u(d))})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof et.TFile&&(p(d),u(d))})),this.registerEvent(this.app.vault.on("create",d=>{d instanceof et.TFile?this.importService.enqueue(d):d instanceof et.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof et.TFile?this.importService.enqueue(d):d instanceof et.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",(d,f)=>{d instanceof et.TFile&&this.maybeAdoptAuthorRename(d,f)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3)}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,s=this.app.vault.adapter;if(!await s.exists(e))return;let i=JSON.parse(await s.read(e))?.version,n=this.manifest.version;if(typeof i!="string"||!i||i===n||!this.isSemverGreater(i,n)||this.notifiedBuildVersion===i)return;this.notifiedBuildVersion=i,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${i}\`). Reload to apply.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload Stashpad",onClick:async()=>{let r=this.app.plugins;try{await r?.disablePlugin?.(this.manifest.id),await r?.enablePlugin?.(this.manifest.id)}catch(o){new et.Notice(`Couldn't reload \u2014 toggle Stashpad off/on in settings. (${o.message})`)}}}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}isSemverGreater(t,e){let s=t.split(".").map(r=>parseInt(r,10)||0),i=e.split(".").map(r=>parseInt(r,10)||0),n=Math.max(s.length,i.length);for(let r=0;r<n;r++){let o=s[r]??0,a=i[r]??0;if(o!==a)return o>a}return!1}parseAuthorFilePath(t){let e=t.match(/\/_authors\/([^/]+?)-([a-z0-9]{4,12})\.md$/i);return e?{name:e[1].replace(/-/g," "),id:e[2]}:null}authorNameToSafe(t){return t.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author"}async syncAuthorFilesToName(){let t=(this.settings.authorId??"").trim(),e=(this.settings.authorName??"").trim();if(!t||!e)return;let s=this.authorNameToSafe(e);for(let i of this.discoverStashpadFolders()){let n=`${i}/_authors`;if(await this.app.vault.adapter.exists(n))for(let r of this.app.vault.getMarkdownFiles()){if(!r.path.startsWith(n+"/"))continue;let o=this.parseAuthorFilePath(r.path);if(!o||o.id!==t)continue;let a=`${n}/${s}-${t}.md`,l=r;if(r.path!==a)try{this.authorRenameInFlight.add(r.path),this.authorRenameInFlight.add(a),await this.app.fileManager.renameFile(r,a);let c=this.app.vault.getAbstractFileByPath(a);c&&(l=c)}catch(c){console.warn("[Stashpad] author file rename failed",c);continue}try{await this.refreshAuthorStub(l)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),s=(this.settings.authorRole??"").trim(),i=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),r=n.replace(/^# .*$/m,`# ${e}`);r!==n&&await this.app.vault.modify(t,r),await this.app.fileManager.processFrontMatter(t,o=>{o.aliases=[e],delete o.name,s?o.role=s:delete o.role,i?o.department=i:delete o.department})}catch(n){console.warn("[Stashpad] refreshAuthorStub failed",n)}}async maybeAdoptAuthorRename(t,e){if(this.authorRenameInFlight.delete(t.path)||this.authorRenameInFlight.delete(e))return;let s=this.parseAuthorFilePath(t.path);if(!s)return;let i=(this.settings.authorId??"").trim();if(!i||s.id!==i)return;let n=s.name.trim();!n||n===(this.settings.authorName??"").trim()||(this.settings.authorName=n,await this.saveSettings(),await this.syncAuthorFilesToName())}async adoptMarkdownDrop(t,e){try{let s=this.app.vault.adapter,i=t.name,n=i.lastIndexOf("."),r=n>0?i.slice(0,n):i,o=n>0?i.slice(n):"",a=0;for(;await s.exists(`${e}/${i}`);)a+=1,i=`${r}-${a}${o}`;let l=`${e}/${i}`;await this.app.fileManager.renameFile(t,l);let c=this.app.vault.getAbstractFileByPath(l);c instanceof et.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(c)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[l]})}catch(s){console.warn("Stashpad: markdown drop adoption failed",s),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${s.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,s=typeof e?.id=="string"?e.id.trim():"",i=e?.parent,n=typeof i=="string"?i.trim()!=="":i!=null,r=typeof e?.created=="string"&&e.created.trim()!=="",o=!s,a=!n,l=!r;if(!o&&!a&&!l)return;let{newId:c}=await Promise.resolve().then(()=>(Pt(),Ne)),p,u=!1,d=!1;if(await this.app.fileManager.processFrontMatter(t,v=>{if(o&&(typeof v.id=="string"&&v.id.trim()||(p=c(),v.id=p)),a){let y=v.parent;(typeof y=="string"?y.trim()!=="":y!=null)||(v.parent=R,u=!0)}l&&(typeof v.created=="string"&&v.created.trim()||(v.created=new Date(t.stat.ctime).toISOString(),d=!0))}),!p&&!u&&!d)return;let f=this.newLog(),m=p||s;m&&await f.append({type:"parent_change",id:m,payload:{from:null,to:R,reason:"orphan_auto_fix",path:t.path,addedId:!!p,addedParent:u,addedCreated:d}}),new et.Notice(`Adopted ${t.basename} \u2192 Home`)}catch(e){console.warn("Stashpad: orphan auto-fix failed",e)}}async autoImportStash(t,e){try{let s=new Uint8Array(await this.app.vault.readBinary(t)),i=Nt(),n=new Set;if(i&&typeof i.collectExistingIds=="function"&&i.noteFolder===e)for(let a of i.collectExistingIds())n.add(a);else for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(e+"/"))continue;let l=this.app.metadataCache.getFileCache(a)?.frontmatter?.id;typeof l=="string"&&n.add(l)}let r=await ls(this.app,s,e,n);try{await this.newLog().append({type:"stash_import",id:R,payload:{from:t.path,into:e,noteCount:r.notesWritten,attachmentsWritten:r.attachmentsWritten,collisionsRenamed:r.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let o=[`Auto-imported ${r.notesWritten} note${r.notesWritten===1?"":"s"} from ${t.name}`];r.attachmentsWritten&&o.push(`+ ${r.attachmentsWritten} attachment${r.attachmentsWritten===1?"":"s"}`),r.collisionsRenamed&&o.push(`(${r.collisionsRenamed} renamed)`),this.notifications.show({message:o.join(" "),kind:"success",category:"import",folder:e}),i&&typeof i.debouncedRender=="function"&&i.debouncedRender()}catch(s){this.notifications.show({message:`Stashpad: auto-import failed +![[${i.path}]] +`,o=Ft(i.basename)||i.basename,l=await this.uniquePath(t,xt(o,n));await this.createNote(l,Ut(r,a)),s.push(l)}}recordNotePaths(d){return d.kind==="folder"?d.notePaths:[d.notePath]}announce(d,t=[]){let e=d[0]?.folder??"",s=d.length,i=t.length?`, replaced ${t.length}`:"",n=!1,r=async()=>{n||(n=!0,await this.undo(d,t))};this.plugin.notifications.show({message:`Imported ${s} file${s===1?"":"s"}${i} into \`${e.split("/").pop()}\`.`,kind:"success",category:"import",duration:0,folder:e,affectedPaths:d.flatMap(a=>this.recordNotePaths(a)),actions:[{label:"Undo import",onClick:()=>void r()}]}),e&&this.plugin.getUndoStack(e).push({label:`Import ${s} file${s===1?"":"s"}`,undo:async()=>{await r()},redo:async()=>{}})}async undo(d,t=[]){for(let e of d)try{if(e.kind==="md"){let s=this.app.vault.getAbstractFileByPath(e.notePath);s instanceof bt.TFile&&await this.app.fileManager.trashFile(s);let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof bt.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(i,n)}}else if(e.kind==="file"){let s=this.app.vault.getAbstractFileByPath(e.notePath);s instanceof bt.TFile&&await this.app.fileManager.trashFile(s);let i=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(i instanceof bt.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(i,n)}}else{for(let i of e.notePaths){let n=this.app.vault.getAbstractFileByPath(i);n instanceof bt.TFile&&await this.app.fileManager.trashFile(n)}for(let i of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(i);n instanceof bt.TFile&&await this.app.fileManager.trashFile(n)}let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof bt.TFolder){let i=await this.uniquePath(e.folder,e.originalName);this.suppress(i),await this.app.fileManager.renameFile(s,i)}}}catch(s){console.warn("[Stashpad] import undo failed",e,s)}for(let e of t)try{await this.app.vault.adapter.exists(e.path)||await this.app.vault.create(e.path,e.content)}catch(s){console.warn("[Stashpad] import undo: couldn't restore replaced note",e.path,s)}new bt.Notice(`Undid import of ${d.length} file(s).`)}pickFilesInto(d){let t=document.createElement("input");t.type="file",t.multiple=!0,t.style.display="none",t.onchange=async()=>{let e=Array.from(t.files??[]);if(t.remove(),e.length===0)return;let s=[];for(let n of e)try{let r=await n.arrayBuffer(),a=await this.uniquePath(d,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,r);let o=this.app.vault.getAbstractFileByPath(a);o instanceof bt.TFile&&s.push(o)}catch(r){console.warn("[Stashpad] file-picker write failed",n.name,r)}if(s.length===0)return;await this.plugin.importLog.load();let i=[];for(let n of s)try{let r=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(i.push(a),this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:r,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(r){console.warn("[Stashpad] file-picker import failed",n.path,r)}i.length>0&&this.announce(i,[])},document.body.appendChild(t),t.click()}async importLooseFilesIn(d){let t=d.replace(/\/+$/,""),e=this.app.vault.getFiles().filter(n=>(n.parent?.path?.replace(/\/+$/,"")??"")===t),s=[];for(let n of e)await this.isStillImportable(n)&&s.push(n);if(s.length===0)return 0;await this.plugin.importLog.load();let i=0;for(let n of s)try{let r=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(i++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:r,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(r){console.warn("[Stashpad] loose-file import failed",n.path,r)}return i}defaultDestination(){let t=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder;return t&&this.plugin.discoverStashpadFolders().includes(t)?t:this.plugin.discoverStashpadFolders()[0]??null}confirm(d,t,e){return new Promise(s=>{new At(this.app,d,t,e,s).open()})}dupChoice(d){return new Promise(t=>{new xe(this.app,d,t).open()})}async ensureFolder(d){let t=this.app.vault.adapter,e=d.split("/").filter(Boolean),s="";for(let i of e){s=s?`${s}/${i}`:i;try{await t.exists(s)||await t.mkdir(s)}catch(n){if(!/already exists/i.test(n.message))throw n}}}async uniquePath(d,t){let e=this.app.vault.adapter,s=t.lastIndexOf("."),i=s>0?t.slice(0,s):t,n=s>0?t.slice(s):"",r=`${d}/${t}`,a=0;for(;await e.exists(r);)a+=1,r=`${d}/${i}-${a}${n}`;return r}};ue.DEBOUNCE_MS=900,ue.BATCH_CONFIRM_AT=8;var bs=ue;var Ss=class{constructor(d,t){this.app=d;this.entries=[];this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/import-log.jsonl`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let d=this.app.vault.adapter;if(await d.exists(this.path)){let t=await d.read(this.path);for(let e of t.split(/\r?\n/))if(e.trim())try{this.entries.push(JSON.parse(e))}catch{}}}catch(d){console.warn("[Stashpad] import log load failed",d)}}}recent(){return[...this.entries].reverse()}findDuplicate(d,t){for(let e=this.entries.length-1;e>=0;e--){let s=this.entries[e];if(s.originalName===d&&(t==null||s.size==null||s.size===t))return s}return null}append(d){this.entries.push(d),this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.append(this.path,JSON.stringify(d)+` +`)}catch(t){console.warn("[Stashpad] import log append failed",t)}})}async ensureDir(){if(this.dirOk)return;let d=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),s="";for(let i of e)s=s?`${s}/${i}`:i,await d.exists(s)||await d.mkdir(s);this.dirOk=!0}};var ks=class extends et.Plugin{constructor(){super(...arguments);this.settings={...zt};this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.rebootstrapInProgress=!1;this.settingTab=null;this.stashpadSelectionListeners=new Set;this.stashpadContentListeners=new Set;this._notifications=null;this._authorRegistry=null;this._importService=null;this._importLog=null;this.sweptFolders=new Set;this.notifiedBuildVersion=null;this.authorRenameInFlight=new Set;this.notifPersistenceWired=!1;this.notifSaveTimer=null;this.LAST_CURSOR_LS_KEY="stashpad:last-cursor";this.writeChain=Promise.resolve()}get notifications(){return this._notifications||(this._notifications=new Ze(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new ws(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new bs(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new Ss(this.app,this.pluginPrivatePath())),this._importLog}pluginPrivatePath(t=""){let s=`${this.manifest.dir.replace(/\/+$/,"")}/.stashpad`;return t?`${s}/${t.replace(/^\/+/,"")}`:s}newLog(){return new vs(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),s=async()=>{let a=e.split("/").filter(Boolean),o="";for(let l of a)o=o?`${o}/${l}`:l,await t.exists(o)||await t.mkdir(o)},i=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,n=this.pluginPrivatePath("data.json");if(await t.exists(i)&&!await t.exists(n))try{await s();let a=await t.read(i);await t.write(n,a),console.debug("[Stashpad] migrated data.json \u2192",n)}catch(a){console.warn("Stashpad: data.json migration failed",a)}let r=".stashpad";if(await t.exists(r))try{await s();let a=await t.list(r);for(let o of a.files){let l=o.replace(/^.*\//,""),c=this.pluginPrivatePath(l);if(!await t.exists(c))try{let p=await t.read(o);await t.write(c,p),console.debug("[Stashpad] migrated",o,"\u2192",c)}catch(p){console.warn(`Stashpad: failed to migrate ${o}`,p)}}}catch(a){console.warn("Stashpad: .stashpad migration scan failed",a)}}async loadData(){let t=this.app.vault.adapter,e=this.pluginPrivatePath("data.json");if(!await t.exists(e))return null;try{return JSON.parse(await t.read(e))}catch(s){return console.warn("Stashpad: data.json parse failed",s),null}}async saveData(t){let e=this.app.vault.adapter,s=this.pluginPrivatePath();if(!await e.exists(s)){let i=s.split("/").filter(Boolean),n="";for(let r of i)n=n?`${n}/${r}`:r,await e.exists(n)||await e.mkdir(n)}await e.write(this.pluginPrivatePath("data.json"),JSON.stringify(t,null,2))}async createNewStashpad(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!e)throw new Error("Folder name is empty");let s=this.app.vault.adapter,i=e.split("/").filter(Boolean),n="";for(let l of i)n=n?`${n}/${l}`:l,await s.exists(n)||await s.mkdir(n);let r=`${e}/Home.md`;if(await s.exists(r)){let l=this.app.vault.getAbstractFileByPath(r);l&&await this.app.fileManager.processFrontMatter(l,c=>{(typeof c.id!="string"||!c.id)&&(c.id=R),"parent"in c||(c.parent=null),(typeof c.created!="string"||!c.created)&&(c.created=new Date().toISOString())});return}let a=new Date().toISOString(),o=["---",`id: ${R}`,"parent: null",`created: ${a}`,"---","Home"].join(` +`);await this.app.vault.create(r,o);try{await this.seedLocalAuthorStub(e)}catch{}}collectColorsInFolder(t){let e=new Map,s=t.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let r=n.parent?.path?.replace(/\/+$/,"")??"";if(r!==s&&!r.startsWith(s+"/"))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter,o=typeof a?.color=="string"?a.color.trim():"";if(!o||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(o))continue;let l=o.toLowerCase();e.set(l,(e.get(l)??0)+1)}let i=[...e.entries()].map(([n,r])=>({hex:n,count:r}));return i.sort((n,r)=>r.count-n.count||n.hex.localeCompare(r.hex)),i}async recolorAllInFolder(t,e,s){let i=t.replace(/\/+$/,""),n=e.toLowerCase(),r=0;for(let o of this.app.vault.getMarkdownFiles()){let l=o.parent?.path?.replace(/\/+$/,"")??"";if(l!==i&&!l.startsWith(i+"/"))continue;let c=this.app.metadataCache.getFileCache(o)?.frontmatter;if((typeof c?.color=="string"?c.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(o,u=>{s?u.color=s:delete u.color}),r++}catch(u){console.warn(`Stashpad: recolor failed for ${o.path}`,u)}}let a=this.settings.colorAliases?.[i];if(a){let o=a[n];o&&(delete a[n],s&&(a[s.toLowerCase()]=o),Object.keys(a).length===0&&delete this.settings.colorAliases[i],await this.saveSettings())}return r}getColorAlias(t,e){let s=t.replace(/\/+$/,""),i=this.settings.colorAliases?.[s];if(!i)return;let n=i[e.toLowerCase()];return n&&n.trim()?n:void 0}async setColorAlias(t,e,s){let i=t.replace(/\/+$/,""),n=e.toLowerCase();this.settings.colorAliases||(this.settings.colorAliases={}),this.settings.colorAliases[i]||(this.settings.colorAliases[i]={});let r=this.settings.colorAliases[i],a=s.trim();a?r[n]=a:delete r[n],Object.keys(r).length===0&&delete this.settings.colorAliases[i],await this.saveSettings()}async waitForStashpadFolder(t,e=2e3){let s=t.trim().replace(/^\/+|\/+$/g,"");if(!s)return;let i=Date.now();for(;Date.now()-i<e;){if(this.discoverStashpadFolders().includes(s))return;await new Promise(n=>setTimeout(n,80))}}discoverStashpadFolders(){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(e)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let i=e.parent?.path?.replace(/\/+$/,"")??"";i&&t.add(i)}return[...t].sort()}searchableFolders(t){let e=new Set(this.settings.searchIncludedFolders),s=new Set(this.settings.searchExcludedFolders),n=this.discoverStashpadFolders().filter(o=>e.size>0?e.has(o):!s.has(o)),r=(t||"").trim().replace(/\/+$/,""),a=n.filter(o=>o!==r);return r&&a.unshift(r),a}async maybeSweepFolder(t){let e=(t||"").trim().replace(/\/+$/,"");!e||this.sweptFolders.has(e)||(this.sweptFolders.add(e),setTimeout(()=>{this.runSweep(e,{silent:!0})},3e3))}async runIntegrityCheckOnFolder(t){let e=(t||"").trim().replace(/\/+$/,"");e&&await this.runSweep(e,{silent:!1})}async runSweep(t,e){try{let s=this.newLog(),i={},n=this.app.vault.getMarkdownFiles().filter(l=>l.path===t||l.path.startsWith(t+"/"));for(let l of n){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,p=typeof c?.id=="string"?c.id.trim():"";if(!p)continue;let u=c&&"parent"in c?c.parent??null:null;i[p]={parent:u,path:l.path}}let r=await s.readState(),a=l=>l===t||l.startsWith(t+"/");if(!e.silent){for(let[l,c]of Object.entries(i)){let p=r[l];p?p.parent!==c.parent?await s.append({type:"parent_change",id:l,payload:{from:p.parent,to:c.parent}}):p.path!==c.path&&await s.append({type:"rename",id:l,payload:{from:p.path,to:c.path}}):await s.append({type:"create",id:l,payload:{path:c.path,parent:c.parent}})}for(let[l,c]of Object.entries(r))!i[l]&&a(c.path)&&await s.append({type:"missing",id:l,payload:{lastPath:c.path}})}let o={};for(let[l,c]of Object.entries(r))a(c.path)||(o[l]=c);for(let[l,c]of Object.entries(i))o[l]=c;await s.writeState(o)}catch(s){console.warn("Stashpad: integrity sweep failed",s)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new ys,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),Et.enabled=!!this.settings.enablePerfProfiling,this.settingTab=new ts(this.app,this),this.addSettingTab(this.settingTab),await this.authorRegistry.load();{let h=(this.settings.authorId??"").trim();h&&this.authorRegistry.record({id:h,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.app.workspace.onLayoutReady(()=>{window.setTimeout(()=>{this.seedLocalAuthorStubsEverywhere()},4e3),window.setTimeout(()=>this.syncObsidianExcludedArchives(),4500),window.setTimeout(()=>this.importService.setArmed(!0),2500)}),this.registerView(mt,h=>new ms(h,this)),this.registerView(Vt,h=>new ss(h,this)),this.registerView(Rt,h=>new je(h,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",h=>{h&&h.view.getViewType()===mt&&(this.lastActiveStashpadLeaf=h,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(Vt).length===0&&setTimeout(()=>{is(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let h=Ot(),f=!!h&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===h,m=!!f&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",m),document.body.classList.toggle("stashpad-active",!!f)};this.register(fi(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t));let e=h=>{try{let f=Array.from(document.querySelectorAll("style")).filter(m=>(m.textContent??"").includes(".stashpad-"));for(let m of f){let v=m.id||"",y=v?`style[data-stashpad-source="${v}"]`:null;if(y&&h.head.querySelector(y))continue;let b=h.createElement("style");v?b.setAttribute("data-stashpad-source",v):b.setAttribute("data-stashpad-source","anon"),b.textContent=m.textContent??"",h.head.appendChild(b)}}catch(f){console.warn("[Stashpad] inject popout styles failed",f)}};this.registerEvent(this.app.workspace.on("window-open",h=>{let f=h?.doc??h?.win?.document??null;f&&e(f)})),setTimeout(()=>{try{let h=this.app.workspace;typeof h.iterateAllLeaves=="function"&&h.iterateAllLeaves(f=>{let m=f?.view?.containerEl?.ownerDocument;m&&m!==document&&e(m)})}catch{}},200),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let s=window.visualViewport,i=()=>{let h=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),f=h&&h.isConnected?h.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${f}px`);let m=0;s&&(m=Math.max(0,window.innerHeight-s.height-s.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${m}px`),document.body.classList.toggle("stashpad-keyboard-open",m>100)};i(),s&&(s.addEventListener("resize",i),s.addEventListener("scroll",i),this.register(()=>{s.removeEventListener("resize",i),s.removeEventListener("scroll",i)})),window.addEventListener("resize",i),this.register(()=>window.removeEventListener("resize",i)),requestAnimationFrame(i),setTimeout(i,250),setTimeout(i,1e3),this.addRibbonIcon("list-tree","Open Stashpad",()=>{if(this.discoverStashpadFolders().length===0){this.activateView({reveal:!0});return}this.openFolderPicker()}).addEventListener("contextmenu",h=>{h.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{Ue(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{is(this.app)}),this.addCommand({id:"stashpad-open",name:"Open Stashpad in new tab",callback:()=>{if(this.discoverStashpadFolders().length>=2){this.openFolderPicker();return}this.activateView({reveal:!1})}}),this.addCommand({id:"stashpad-reveal",name:"Reveal or open Stashpad",callback:()=>void this.activateView({reveal:!0})});let r=h=>{let f=Ot();f&&typeof f[h]=="function"&&f[h]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>r("toggleSplit")}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>r("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>r("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>r("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>r("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>r("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>r("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>r("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>r("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>r("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>r("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>r("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>r("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>r("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>r("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>r("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>r("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>r("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>r("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>r("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>r("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>r("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>r("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>r("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>r("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>r("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>r("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>r("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>r("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>r("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>r("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new et.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let h=Et.report();console.log(h);try{await navigator.clipboard.writeText(h)}catch{}new et.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{Et.reset(),new et.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>r("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>r("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>r("cmdAssign")}),this.addCommand({id:"stashpad-open-import-log",name:"Open import log",callback:async()=>{await this.importLog.load();let{ImportLogModal:h}=await Promise.resolve().then(()=>(Ht(),Ee));new h(this.app,this.importLog.recent()).open()}}),this.addCommand({id:"stashpad-import-files",name:"Import file(s) into Stashpad\u2026",callback:()=>this.openImportPicker()}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>r("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>r("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void Ue(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void is(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:h=>{let f=this.app.workspace.getActiveFile(),m=!!f&&f.extension==="md"&&this.isStashpadNoteFile(f);return h||m&&f&&this.revealNoteInStashpad(f),m}});let a=Object.keys(Ie);for(let h of a){let f=Ie[h];this.addCommand({id:`stashpad-open-panels-${h}`,name:`Open Stashpad panel: ${f.label}`,callback:async()=>{await Ue(this.app),this.app.workspace.getLeavesOfType(Rt)[0]?.view?.setActivePanel?.(h)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>r("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>r("cmdTogglePin")}),this.addCommand({id:"stashpad-open-tiny",name:"Open Stashpad in tiny window",callback:()=>void this.openTinyWindow()}),this.addCommand({id:"stashpad-clone-tab",name:"Clone (duplicate / copy) this Stashpad tab",callback:()=>r("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>r("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>r("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>r("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>r("cmdImportStash")}),this.addCommand({id:"stashpad-pick-folder",name:"Stashpad: open / switch / create folder\u2026",callback:()=>this.openFolderPicker()}),this.addCommand({id:"stashpad-run-integrity-check",name:"Run integrity check on active Stashpad folder",checkCallback:h=>{let f=Ot(),m=f&&f.noteFolder;return m?(h||(new et.Notice(`Running integrity check on "${m}"\u2026`),this.runIntegrityCheckOnFolder(m).then(()=>{new et.Notice("Integrity check complete \u2014 see Stashpad log.")})),!0):!1}}),this.addCommand({id:"stashpad-fix-orphans",name:"Set missing parents to Home (orphan fix)",callback:()=>void this.fixOrphanParents()}),this.addCommand({id:"stashpad-rebuild-author-registry",name:"Rebuild author registry (scan authors + note frontmatter)",callback:async()=>{new et.Notice("Stashpad: rebuilding author registry\u2026");try{let h=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${h.total} author(s) \u2014 ${h.fromStubs} from stubs, ${h.fromNotes} from note links.`,kind:"success",category:"system"})}catch(h){new et.Notice(`Author registry rebuild failed: ${h.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new et.Notice("Stashpad: restoring author stubs\u2026");try{let h=await this.restoreMissingAuthorStubs();this.notifications.show({message:h.created>0?`Restored ${h.created} author stub(s) across ${h.folders} folder(s).`:`No missing author stubs \u2014 all present across ${h.folders} folder(s).`,kind:"success",category:"system"})}catch(h){new et.Notice(`Restore author stubs failed: ${h.message}`)}}}),this.addCommand({id:"stashpad-rebootstrap-all",name:"Rebootstrap all Stashpad folders (backfill metadata + rename stale titles)",callback:async()=>{new et.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:h,fmChecked:f,fmWritten:m,slugsRenamed:v,authors:y,imported:b,attachmentsLinked:k}=await this.rebootstrapAllFolders(),T=[];T.push(`rebootstrapped ${h.length} folder${h.length===1?"":"s"}`),b>0&&T.push(`imported ${b} loose file${b===1?"":"s"}`),k>0&&T.push(`linked attachments on ${k} note${k===1?"":"s"}`),m>0&&T.push(`updated ${m} note${m===1?"":"s"}' metadata`),v>0&&T.push(`renamed ${v} note${v===1?"":"s"}`),y>0&&T.push(`${y} author${y===1?"":"s"} in registry`),T.push(`(checked ${f} total)`),new et.Notice(`Stashpad: ${T.join(" \xB7 ")}`)}catch(h){new et.Notice(`Stashpad: rebootstrap failed (${h.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:h=>{let f=this.app.workspace.getActiveFile();return!f||f.extension!=="md"?!1:(h||this.adoptNote(f),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Ht(),Ee)).then(({NotificationHistoryModal:h,LogModal:f})=>{new h(this.app,this.notifications,async()=>{let m=this.app.vault.adapter,v=this.pluginPrivatePath("log.jsonl");if(!await m.exists(v)){new et.Notice("No log yet \u2014 make some changes first.");return}let y=await m.read(v);new f(this.app,y,v).open()},this.settings.authorId||null,m=>this.lookupNoteAuthorIds(m)).open()})}});let o=[{key:"prefixTimestampsOnCopy",label:"Prefix timestamps when copying"},{key:"useTemplatesFormat",label:"Use Templates plugin date/time formats"},{key:"autoNavOnMoveIn",label:"Auto-navigate into parent on move IN"},{key:"autoNavOnMoveOut",label:"Auto-navigate to destination on move OUT"},{key:"confirmCrossParentDrag",label:"Confirm cross-parent drag-and-drop"},{key:"confirmBulkDelete",label:"Confirm bulk deletes"},{key:"confirmAttachmentDelete",label:"Offer to delete attachments with note"},{key:"autofocusComposerAfterSend",label:"Autofocus composer after sending"},{key:"popoutDuplicates",label:"Open in new window \u2014 duplicate tab"},{key:"autoExpandCursorRow",label:"Expand the cursor row's body automatically"},{key:"autoOpenDetailPanel",label:"Auto-open the detail panel"},{key:"doubleClickToFocus",label:"Double-click a note to open it"}];for(let h of o){let f=`stashpad-toggle-${String(h.key).replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`)}`;this.addCommand({id:f,name:`Toggle: ${h.label}`,callback:async()=>{let m=!this.settings[h.key];this.settings[h.key]=m,await this.saveSettings(),new et.Notice(`${h.label}: ${m?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.openTabById(this.manifest.id),setTimeout(()=>this.settingTab?.focusSearchInput?.(),0))}});for(let h of Qe)this.addCommand({id:`stashpad-open-settings-${h.id}`,name:`Open Stashpad settings: ${h.label}`,callback:()=>{let f=this.app.setting;!f?.open||!f?.openTabById||(this.settingTab?.openToTab(h.id),f.open(),f.openTabById(this.manifest.id))}});let l=()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.openTabById(this.manifest.id),setTimeout(()=>{document.getElementById("stashpad-jd-index-section")?.scrollIntoView({behavior:"smooth",block:"start"})},100))};this.addCommand({id:"stashpad-preview-jd-index",name:"Preview JD index (overwrites home note body)",callback:async()=>{try{let{buildJdIndexPreview:h}=await Promise.resolve().then(()=>(De(),qe)),f=await h(this.app,this,this.settings);if(f.error==="no-dest"){new et.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(f.error==="no-home"){new et.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:m}=await Promise.resolve().then(()=>(De(),qe));m(this.app,f)}catch(h){console.error("[stashpad] preview failed",h),new et.Notice(`Preview failed: ${h?.message??h}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:h,scanForJdNotes:f,JdBuildConfirmModal:m}=await Promise.resolve().then(()=>(De(),qe));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new et.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}let y=f(this.app,this,this.settings);new m(this.app,this,this.settings,y.indexed.length,async()=>{try{let k=await h(this.app,this,this.settings);if(k.error==="no-dest"){new et.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(k.error==="dest-not-stashpad"){new et.Notice(`"${k.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),l();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new et.Notice(`Index built: ${k.created} created, ${k.updated} updated, ${k.skipped} skipped \u2192 ${k.destFolder}`,6e3)}catch(k){console.error("[stashpad] build failed",k),new et.Notice(`Build failed: ${k?.message??k}`,8e3)}}).open()}catch(h){console.error("[stashpad] build failed",h),new et.Notice(`Build failed: ${h?.message??h}`,8e3)}}});let c=h=>{if(h.extension!==Qt)return;let f=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),m=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!f)return;let v=h.parent?.path||"";if((v.split("/").pop()??"")!==f||m&&v.endsWith(`/${m}`))return;let b=v.slice(0,v.length-f.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(h,b)};this.registerEvent(this.app.vault.on("create",h=>{h instanceof et.TFile&&c(h)})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof et.TFile&&c(h)}));let p=h=>{if(h.extension!=="md")return;let f=h.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(f)&&setTimeout(()=>{this.fixOrphanParentForFile(h)},800)},u=h=>{if(h.extension!=="md")return;let f=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!f)return;let m=h.parent?.path?.replace(/\/+$/,"")??"";if((m.split("/").pop()??"")!==f)return;let y=m.slice(0,m.length-f.length).replace(/\/+$/,"");!y||!this.discoverStashpadFolders().includes(y)||setTimeout(()=>{this.adoptMarkdownDrop(h,y)},200)};this.registerEvent(this.app.vault.on("create",h=>{h instanceof et.TFile&&(p(h),u(h))})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof et.TFile&&(p(h),u(h))})),this.registerEvent(this.app.vault.on("create",h=>{h instanceof et.TFile?this.importService.enqueue(h):h instanceof et.TFolder&&this.importService.enqueueFolder(h)})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof et.TFile?this.importService.enqueue(h):h instanceof et.TFolder&&this.importService.enqueueFolder(h)})),this.registerEvent(this.app.vault.on("rename",(h,f)=>{h instanceof et.TFile&&this.maybeAdoptAuthorRename(h,f)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3)}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,s=this.app.vault.adapter;if(!await s.exists(e))return;let i=JSON.parse(await s.read(e))?.version,n=this.manifest.version;if(typeof i!="string"||!i||i===n||!this.isSemverGreater(i,n)||this.notifiedBuildVersion===i)return;this.notifiedBuildVersion=i,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${i}\`). Reload to apply.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload Stashpad",onClick:async()=>{let r=this.app.plugins;try{await r?.disablePlugin?.(this.manifest.id),await r?.enablePlugin?.(this.manifest.id)}catch(a){new et.Notice(`Couldn't reload \u2014 toggle Stashpad off/on in settings. (${a.message})`)}}}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}isSemverGreater(t,e){let s=t.split(".").map(r=>parseInt(r,10)||0),i=e.split(".").map(r=>parseInt(r,10)||0),n=Math.max(s.length,i.length);for(let r=0;r<n;r++){let a=s[r]??0,o=i[r]??0;if(a!==o)return a>o}return!1}parseAuthorFilePath(t){let e=t.match(/\/_authors\/([^/]+?)-([a-z0-9]{4,12})\.md$/i);return e?{name:e[1].replace(/-/g," "),id:e[2]}:null}authorNameToSafe(t){return t.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author"}async syncAuthorFilesToName(){let t=(this.settings.authorId??"").trim(),e=(this.settings.authorName??"").trim();if(!t||!e)return;let s=this.authorNameToSafe(e);for(let i of this.discoverStashpadFolders()){let n=`${i}/_authors`;if(await this.app.vault.adapter.exists(n))for(let r of this.app.vault.getMarkdownFiles()){if(!r.path.startsWith(n+"/"))continue;let a=this.parseAuthorFilePath(r.path);if(!a||a.id!==t)continue;let o=`${n}/${s}-${t}.md`,l=r;if(r.path!==o)try{this.authorRenameInFlight.add(r.path),this.authorRenameInFlight.add(o),await this.app.fileManager.renameFile(r,o);let c=this.app.vault.getAbstractFileByPath(o);c&&(l=c)}catch(c){console.warn("[Stashpad] author file rename failed",c);continue}try{await this.refreshAuthorStub(l)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),s=(this.settings.authorRole??"").trim(),i=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),r=n.replace(/^# .*$/m,`# ${e}`);r!==n&&await this.app.vault.modify(t,r),await this.app.fileManager.processFrontMatter(t,a=>{a.aliases=[e],delete a.name,s?a.role=s:delete a.role,i?a.department=i:delete a.department})}catch(n){console.warn("[Stashpad] refreshAuthorStub failed",n)}}async maybeAdoptAuthorRename(t,e){if(this.authorRenameInFlight.delete(t.path)||this.authorRenameInFlight.delete(e))return;let s=this.parseAuthorFilePath(t.path);if(!s)return;let i=(this.settings.authorId??"").trim();if(!i||s.id!==i)return;let n=s.name.trim();!n||n===(this.settings.authorName??"").trim()||(this.settings.authorName=n,await this.saveSettings(),await this.syncAuthorFilesToName())}async adoptMarkdownDrop(t,e){try{let s=this.app.vault.adapter,i=t.name,n=i.lastIndexOf("."),r=n>0?i.slice(0,n):i,a=n>0?i.slice(n):"",o=0;for(;await s.exists(`${e}/${i}`);)o+=1,i=`${r}-${o}${a}`;let l=`${e}/${i}`;await this.app.fileManager.renameFile(t,l);let c=this.app.vault.getAbstractFileByPath(l);c instanceof et.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(c)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[l]})}catch(s){console.warn("Stashpad: markdown drop adoption failed",s),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${s.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,s=typeof e?.id=="string"?e.id.trim():"",i=e?.parent,n=typeof i=="string"?i.trim()!=="":i!=null,r=typeof e?.created=="string"&&e.created.trim()!=="",a=!s,o=!n,l=!r;if(!a&&!o&&!l)return;let{newId:c}=await Promise.resolve().then(()=>(Mt(),He)),p,u=!1,h=!1;if(await this.app.fileManager.processFrontMatter(t,v=>{if(a&&(typeof v.id=="string"&&v.id.trim()||(p=c(),v.id=p)),o){let y=v.parent;(typeof y=="string"?y.trim()!=="":y!=null)||(v.parent=R,u=!0)}l&&(typeof v.created=="string"&&v.created.trim()||(v.created=new Date(t.stat.ctime).toISOString(),h=!0))}),!p&&!u&&!h)return;let f=this.newLog(),m=p||s;m&&await f.append({type:"parent_change",id:m,payload:{from:null,to:R,reason:"orphan_auto_fix",path:t.path,addedId:!!p,addedParent:u,addedCreated:h}}),new et.Notice(`Adopted ${t.basename} \u2192 Home`)}catch(e){console.warn("Stashpad: orphan auto-fix failed",e)}}async autoImportStash(t,e){try{let s=new Uint8Array(await this.app.vault.readBinary(t)),i=Ot(),n=new Set;if(i&&typeof i.collectExistingIds=="function"&&i.noteFolder===e)for(let o of i.collectExistingIds())n.add(o);else for(let o of this.app.vault.getMarkdownFiles()){if(!o.path.startsWith(e+"/"))continue;let l=this.app.metadataCache.getFileCache(o)?.frontmatter?.id;typeof l=="string"&&n.add(l)}let r=await ps(this.app,s,e,n);try{await this.newLog().append({type:"stash_import",id:R,payload:{from:t.path,into:e,noteCount:r.notesWritten,attachmentsWritten:r.attachmentsWritten,collisionsRenamed:r.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let a=[`Auto-imported ${r.notesWritten} note${r.notesWritten===1?"":"s"} from ${t.name}`];r.attachmentsWritten&&a.push(`+ ${r.attachmentsWritten} attachment${r.attachmentsWritten===1?"":"s"}`),r.collisionsRenamed&&a.push(`(${r.collisionsRenamed} renamed)`),this.notifications.show({message:a.join(" "),kind:"success",category:"import",folder:e}),i&&typeof i.debouncedRender=="function"&&i.debouncedRender()}catch(s){this.notifications.show({message:`Stashpad: auto-import failed File: \`${t.name}\` Error: ${s.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[t.path],actions:Ye(this.app,t.path,et.Platform.isMobile)}),console.error(s)}}lookupNoteAuthorIds(t){let e=new Set,s=i=>{if(typeof i!="string")return null;let n=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let i of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(i)?.frontmatter;if(n?.id!==t)continue;let r=s(n?.author);r&&e.add(r);let o=n?.contributors;if(Array.isArray(o))for(let a of o){let l=s(a);l&&e.add(l)}break}return Array.from(e)}lookupNoteAuthorId(t){return this.lookupNoteAuthorIds(t)[0]??null}async rebootstrapAllFolders(){let t="__root__",e=new Set;for(let u of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(u)?.frontmatter?.id!==t)continue;let f=u.parent?.path;f&&e.add(f)}let s=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),i=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],r=async u=>{if(u&&!await this.app.vault.adapter.exists(u))try{await this.app.vault.createFolder(u)}catch(d){let f=d?.message??"";if(!/already exists/i.test(f))throw d}},o=0,a=0,l=0,c=0;for(let u of e)try{if(s&&await r(`${u}/${s}`),i&&await r(`${u}/${i}`),this.settings.autoImport)try{c+=await this.importService.importLooseFilesIn(u)}catch(f){console.warn("Stashpad: loose-file sweep failed",u,f)}let d=await mi(this.app,u);o+=d.checked,a+=d.written,l+=await this.rebootstrapFolderSlugs(u),n.push(u)}catch(d){console.warn(`Stashpad: rebootstrap skipped ${u}`,d)}let p=0;try{p=(await this.rebuildAuthorRegistry()).total}catch(u){console.warn("Stashpad: rebootstrap author-registry rebuild failed",u)}return{touched:n,fmChecked:o,fmWritten:a,slugsRenamed:l,authors:p,imported:c}}async rebootstrapFolderSlugs(t){let e="__root__",s=t.replace(/\/+$/,""),i=this.settings.slugStopWords??Mt,n=0,r=this.app.vault.getMarkdownFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===s);for(let o of r){let a=ee(o.basename);if(!(!a||a===e||this.app.metadataCache.getFileCache(o)?.frontmatter?.id!==a))try{let c=await this.app.vault.cachedRead(o),p=c.startsWith("---")?c.slice(c.indexOf(` ----`,3)+4).replace(/^\r?\n/,""):c,u=Ft(p,i),d=xt(u,a);if(o.name===d)continue;let f=o.parent?`${o.parent.path}/${d}`:d;if(this.app.vault.getAbstractFileByPath(f))continue;await this.app.fileManager.renameFile(o,f),n+=1}catch(c){console.warn(`Stashpad: slug rebootstrap skipped ${o.path}`,c)}}return n}onStashpadSelectionChange(t){return this.stashpadSelectionListeners.add(t),()=>this.stashpadSelectionListeners.delete(t)}notifyStashpadSelectionChanged(){for(let t of this.stashpadSelectionListeners)try{t()}catch(e){console.warn("[Stashpad] selection listener failed",e)}}onStashpadContentChange(t){return this.stashpadContentListeners.add(t),()=>this.stashpadContentListeners.delete(t)}notifyStashpadContentChanged(){for(let t of this.stashpadContentListeners)try{t()}catch(e){console.warn("[Stashpad] content listener failed",e)}}getActiveStashpadSelection(){let e=this.lastActiveStashpadLeaf?.view;if(!e||e.getViewType?.()!==mt)return null;let s=e.noteFolder??"";if(!s)return null;let i=e.currentChildren??[],n;if(typeof e.cursorIdx=="number"&&e.cursorIdx>=0&&(n=i[e.cursorIdx]),!n&&e.selection?.size>0){let r=e.firstSelectedId??[...e.selection][0];n=i.find(o=>o.id===r)}return n?.file?{folder:s,id:n.id,file:n.file}:null}async pinNote(t){let e=this.settings.pinnedNotes??[];e.some(s=>s.folder===t.folder&&s.id===t.id)||(this.settings.pinnedNotes=[...e,t],await this.saveSettings(),this.refreshPanelsView())}async unpinNote(t){let e=this.settings.pinnedNotes??[],s=e.filter(i=>!(i.folder===t.folder&&i.id===t.id));s.length!==e.length&&(this.settings.pinnedNotes=s,await this.saveSettings(),this.refreshPanelsView())}isPinned(t){return(this.settings.pinnedNotes??[]).some(e=>e.folder===t.folder&&e.id===t.id)}refreshPanelsView(){let t=this.app.workspace.getLeavesOfType($t);for(let e of t){let s=e.view;s&&typeof s.render=="function"&&s.render()}}openFolderPicker(){let t=f=>{let v=f.getViewState().state?.folderOverride;return typeof v=="string"&&v.trim()?v.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(mt),s=this.discoverStashpadFolders(),i=Nt(),n=i?(i.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",r=new Set;for(let f of this.app.vault.getAllLoadedFiles())if(f.children){let m=f.path;m&&m!=="/"&&!m.startsWith(".")&&r.add(m)}let o=f=>{let m=f.split("/").filter(Boolean).pop()??"";return m?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive"].map(y=>(y??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(m):!1},a=new Set,l=[],c=[],p=new Set;for(let f of e){let m=t(f);if(p.has(m))continue;p.add(m),a.add(m);let v=m.split("/").pop()||m;l.push({kind:"reveal",folder:m,label:`Reveal "${v}" tab`,leaf:f,icon:"layout-grid"}),c.push({kind:"open-anyway",folder:m,label:`Open "${v}" in another new tab`,icon:"layout-template"})}for(let f of s.filter(m=>!a.has(m))){let m=f.split("/").pop()||f;l.push({kind:"open",folder:f,label:`Open "${m}" in new tab`,icon:"layout-template"})}let u=this,d=new class extends et.SuggestModal{getSuggestions(f){let m=f.trim().toLowerCase(),v=m?m.split(/\s+/).filter(Boolean):[],y=I=>{if(!v.length)return!0;let E=I.toLowerCase();for(let D of v)if(!E.includes(D))return!1;return!0},b=m?l.filter(I=>{let E="folder"in I?I.folder:"";return y(I.label)||y(E)}):l.slice();if(m&&i&&n)for(let I of s){if(I.toLowerCase()===n.toLowerCase())continue;let E=I.split("/").pop()??I,D=`${I} ${E}`;y(D)&&b.push({kind:"switch-current",folder:I,label:`Switch this tab to "${E}"`,icon:"folder-input"})}let k=f.trim().replace(/^\/+|\/+$/g,"");if(k&&!o(k)){let I=Array.from(r).find(D=>D.toLowerCase()===k.toLowerCase()),E=s.some(D=>D.toLowerCase()===k.toLowerCase());if(I&&!E)b.push({kind:"convert",folder:I,label:`Convert \u201C${ps(I)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!I){let D=ps(k);b.push({kind:"create",folder:k,label:`+ Create new Stashpad \u201C${D}\u201D`,icon:"folder-plus"})}}let C=c.filter(I=>y(I.label)||y(I.folder));return b.push(...C),b}renderSuggestion(f,m){m.addClass("stashpad-suggest-item"),m.addClass("stashpad-ribbon-suggest-item"),f.kind==="create"&&m.addClass("stashpad-suggest-create");let v=m.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,et.setIcon)(v,f.icon);let y=m.createDiv({cls:"stashpad-ribbon-suggest-body"});y.createDiv({cls:"stashpad-suggest-title",text:f.label}),"folder"in f&&f.folder&&f.label!==f.folder&&y.createDiv({cls:"stashpad-suggest-preview",text:f.folder})}async onChooseSuggestion(f){if(f.kind==="reveal"){u.app.workspace.revealLeaf(f.leaf);return}if(f.kind==="open"||f.kind==="open-anyway"){await u.activateViewForFolder(f.folder);return}if(f.kind==="switch-current"){let m=i;m&&typeof m.setFolderOverride=="function"&&(await m.setFolderOverride(f.folder),u.app.workspace.revealLeaf(m.leaf));return}if(f.kind==="create"){try{let m=ps(f.folder);await u.app.vault.adapter.exists(m)||await u.app.vault.createFolder(m),await u.activateViewForFolder(m)}catch(m){new et.Notice(`Stashpad: couldn't create folder (${m.message})`)}return}if(f.kind==="convert"){let{ConfirmModal:m}=await Promise.resolve().then(()=>(Bt(),be)),v=f.folder,y=[`\u201C${v}\u201D already exists as a regular vault folder.`,"Converting will add a Home note + _imports / _exports subfolders inside it.","Existing files are NOT touched."];new m(u.app,"Convert into a Stashpad?",y.join(` -`),"Convert",async b=>{if(b)try{await u.activateViewForFolder(v)}catch(k){new et.Notice(`Stashpad: couldn't convert folder (${k.message})`)}}).open();return}}}(this.app);d.setPlaceholder(i?"Open, switch this tab, or create a Stashpad folder \u2014 type to filter\u2026":"Open or create a Stashpad folder \u2014 type to filter\u2026"),d.open()}async openTinyWindow(){let t=Nt(),e=t?.folderOverride??null,s=t?.focusId??"__root__",i=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new et.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:mt,active:!0,state:{folderOverride:e,focusId:s,tinyMode:!0,tinyAlwaysOnTop:!1,compactMode:i}});try{this.app.workspace.revealLeaf(n)}catch{}}async activateView(t={reveal:!0}){let{workspace:e}=this.app;if(t.reveal){let i=e.getLeavesOfType(mt);if(i.length>0){e.revealLeaf(i[0]);return}}let s=e.getLeaf("tab");await s.setViewState({type:mt,active:!0}),e.revealLeaf(s)}async activateViewForFolder(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let s=this.app.workspace.getLeaf("tab");await s.setViewState({type:mt,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(s)}isStashpadNoteFile(t){let e=t.parent?.path?.replace(/\/+$/,"")??"";if(!this.discoverStashpadFolders().includes(e))return!1;let s=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;return typeof s=="string"&&s.length>0}async revealNoteInStashpad(t){let e=t.parent?.path?.replace(/\/+$/,"")??"",s=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;if(!e||typeof s!="string"||!s){new et.Notice("That note isn't a Stashpad note.");return}let i=this.app.workspace.getLeavesOfType(mt).find(r=>(r.view?.noteFolder??"")===e);if(i){this.app.workspace.revealLeaf(i);let r=i.view;typeof r?.navigateTo=="function"&&r.navigateTo(s);return}await this.activateViewForFolder(e);let n=this.lastActiveStashpadLeaf?.view;typeof n?.navigateTo=="function"&&n.navigateTo(s)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,s=this.discoverStashpadFolders(),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let r=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!r)continue;let o=typeof r.author=="string"?r.author:"",a=Array.isArray(r.contributors)?r.contributors.filter(f=>typeof f=="string"):[],l=o.includes(e),c=a.some(f=>f.includes(e));if(!l&&!c)continue;let p=n.parent?.path??"",u=s.find(f=>p===f||p.startsWith(f+"/"));if(!u)continue;i.has(u)||i.set(u,{authored:0,contributed:0});let d=i.get(u);l&&d.authored++,c&&d.contributed++}return[...i.entries()].map(([n,r])=>({folder:n,...r})).sort((n,r)=>r.authored+r.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return pe(t)}authorRefFor(t,e,s){let i=s.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",n=`${t.replace(/\/+$/,"")}/_authors/${i}-${e}.md`,r=s.replace(/[\[\]|]/g,"").trim()||i;return`[[${n}|${r}]]`}async ensureAuthorStubFor(t,e,s){if(!e||!s)return;this.authorRegistry.record({id:e,name:s});let i=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(l=>l.path.startsWith(i+"/")&&this.parseAuthorFilePath(l.path)?.id===e))return;let r=this.authorRegistry.get(e),o=this.authorNameToSafe(s),a=`${i}/${o}-${e}.md`;try{if(await this.ensureFolderPath(i),await this.app.vault.adapter.exists(a))return;await this.app.vault.create(a,this.buildAuthorStub({id:e,name:s,role:r?.role,department:r?.department},new Date().toISOString()))}catch(l){console.warn("[Stashpad] ensureAuthorStubFor failed",a,l)}}async rebuildAuthorRegistry(){let t=this.discoverStashpadFolders(),e=new Map,s=0;for(let n of this.app.vault.getMarkdownFiles()){let r=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!r)continue;let o=[];if(typeof r.author=="string"&&o.push(r.author),Array.isArray(r.contributors))for(let a of r.contributors)typeof a=="string"&&o.push(a);for(let a of o){let l=this.parseAuthorRef(a);if(l)if(!e.has(l.id))e.set(l.id,{id:l.id,name:l.name,fromStub:!1}),s++;else{let c=e.get(l.id);!c.name&&l.name&&(c.name=l.name)}}}let i=0;for(let n of t){let r=`${n}/_authors`;for(let o of this.app.vault.getMarkdownFiles()){if(!o.path.startsWith(r+"/"))continue;let a=this.parseAuthorFilePath(o.path);if(!a)continue;let l=this.app.metadataCache.getFileCache(o)?.frontmatter,p=((Array.isArray(l?.aliases)?l.aliases.find(m=>typeof m=="string")??"":typeof l?.aliases=="string"?l.aliases:"")||(typeof l?.name=="string"?l.name:"")||a.name).trim(),u=typeof l?.role=="string"?l.role:void 0,d=typeof l?.department=="string"?l.department:void 0,f=e.get(a.id);f||i++,e.set(a.id,{id:a.id,name:p||f?.name,role:u??f?.role,department:d??f?.department,fromStub:!0})}}return await this.authorRegistry.load(),this.authorRegistry.replaceAll([...e.values()]),await this.authorRegistry.save(),{total:e.size,fromStubs:i,fromNotes:s}}buildAuthorStub(t,e){let s=o=>o.replace(/[\r\n]+/g," ").trim(),i=o=>s(o).replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=s(t.name),r=["---",`authorId: ${t.id}`,"aliases:",` - "${i(t.name)}"`];return t.role&&r.push(`role: "${i(t.role)}"`),t.department&&r.push(`department: "${i(t.department)}"`),r.push(`created: ${e}`,"---",`# ${n}`),r.join(` -`)}async restoreMissingAuthorStubs(){await this.authorRegistry.load();let t=this.authorRegistry.all().filter(n=>n.id&&n.name),e=this.discoverStashpadFolders(),s=this.app.vault.getMarkdownFiles(),i=0;for(let n of e){let r=`${n}/_authors`,o=new Set;for(let a of s){if(!a.path.startsWith(r+"/"))continue;let l=this.parseAuthorFilePath(a.path)?.id;l&&o.add(l)}for(let a of t){if(o.has(a.id))continue;let l=this.authorNameToSafe(a.name),c=`${r}/${l}-${a.id}.md`;try{if(await this.ensureFolderPath(r),await this.app.vault.adapter.exists(c))continue;await this.app.vault.create(c,this.buildAuthorStub(a,a.firstSeen??new Date().toISOString())),i++}catch(p){console.warn("[Stashpad] restore author stub failed",c,p)}}}return{created:i,folders:e.length}}syncObsidianExcludedArchives(){try{let t=this.app.vault;if(typeof t.getConfig!="function"||typeof t.setConfig!="function")return;let e=Array.isArray(t.getConfig("userIgnoreFilters"))?t.getConfig("userIgnoreFilters"):[],s=new Set(e),i=!1;for(let n of this.discoverStashpadFolders()){let r=`${n.replace(/\/+$/,"")}/_archive/`;s.has(r)||(s.add(r),i=!0)}i&&t.setConfig("userIgnoreFilters",[...s])}catch(t){console.warn("[Stashpad] couldn't update Obsidian excluded files",t)}}openImportPicker(){let t=this.discoverStashpadFolders();if(t.length===0){new et.Notice("No Stashpad folders to import into.");return}if(t.length===1){this.importService.pickFilesInto(t[0]);return}let e=this.importService.defaultDestination()??t[0];new Ws(this.app,e,t,s=>this.importService.pickFilesInto(s)).open()}async seedLocalAuthorStub(t){let e=(this.settings.authorId??"").trim(),s=(this.settings.authorName??"").trim();if(!e||!s)return!1;let i=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(a=>a.path.startsWith(i+"/")&&this.parseAuthorFilePath(a.path)?.id===e))return!1;let r=this.authorNameToSafe(s),o=`${i}/${r}-${e}.md`;try{return await this.ensureFolderPath(i),await this.app.vault.adapter.exists(o)?!1:(await this.app.vault.create(o,this.buildAuthorStub({id:e,name:s,role:this.settings.authorRole,department:this.settings.authorDepartment},new Date().toISOString())),this.authorRegistry.record({id:e,name:s,role:this.settings.authorRole,department:this.settings.authorDepartment}),!0)}catch(a){return console.warn("[Stashpad] seedLocalAuthorStub failed",o,a),!1}}async seedLocalAuthorStubsEverywhere(){if(!(this.settings.authorName??"").trim())return 0;let e=0;for(let s of this.discoverStashpadFolders())await this.seedLocalAuthorStub(s)&&e++;return e}async ensureFolderPath(t){let e=this.app.vault.adapter,s=t.split("/").filter(Boolean),i="";for(let n of s){i=i?`${i}/${n}`:n;try{await e.exists(i)||await e.mkdir(i)}catch(r){if(!/already exists/i.test(r.message))throw r}}}async loadSettings(){let t=await this.loadData()??{};typeof t?.confirmMultiDelete=="boolean"&&(typeof t.confirmBulkDelete!="boolean"&&(t.confirmBulkDelete=t.confirmMultiDelete),typeof t.confirmAttachmentDelete!="boolean"&&(t.confirmAttachmentDelete=t.confirmMultiDelete),delete t.confirmMultiDelete),typeof t?.jdIndexDestFolder=="string"&&typeof t?.jdIndexStashpadFolder!="string"&&(t.jdIndexStashpadFolder=t.jdIndexDestFolder),this.settings={...Ht,...t,shortcuts:{...Ht.shortcuts,...t?.shortcuts??{}},mod:{...Ht.mod,...t?.mod??{}},bindings:ln(t?.bindings,t?.shortcuts,t?.mod),customPalette:Array.isArray(t?.customPalette)?t.customPalette.filter(e=>typeof e=="string"&&/^#[0-9a-f]{6}$/i.test(e)):[],colorAliases:t?.colorAliases&&typeof t.colorAliases=="object"?t.colorAliases:{},noteTemplates:t?.noteTemplates&&typeof t.noteTemplates=="object"?t.noteTemplates:{},authorName:typeof t?.authorName=="string"?t.authorName:"",authorId:typeof t?.authorId=="string"?t.authorId:"",authorRole:typeof t?.authorRole=="string"?t.authorRole:"",authorDepartment:typeof t?.authorDepartment=="string"?t.authorDepartment:"",showAuthor:typeof t?.showAuthor=="boolean"?t.showAuthor:!0,showContributors:typeof t?.showContributors=="boolean"?t.showContributors:!0,showLastEdit:typeof t?.showLastEdit=="boolean"?t.showLastEdit:!0,viewModes:t?.viewModes&&typeof t.viewModes=="object"&&!Array.isArray(t.viewModes)?t.viewModes:{},includeAttachmentsInEverything:t?.includeAttachmentsInEverything&&typeof t.includeAttachmentsInEverything=="object"&&!Array.isArray(t.includeAttachmentsInEverything)?t.includeAttachmentsInEverything:{},hideChildlessNotes:t?.hideChildlessNotes&&typeof t.hideChildlessNotes=="object"&&!Array.isArray(t.hideChildlessNotes)?t.hideChildlessNotes:{},hideCompletedNotes:t?.hideCompletedNotes&&typeof t.hideCompletedNotes=="object"&&!Array.isArray(t.hideCompletedNotes)?t.hideCompletedNotes:{},mutedNotificationCategories:Array.isArray(t?.mutedNotificationCategories)?t.mutedNotificationCategories.filter(e=>typeof e=="string"):[],notificationHistoryLimit:typeof t?.notificationHistoryLimit=="number"&&Number.isFinite(t.notificationHistoryLimit)?t.notificationHistoryLimit:5e3,drafts:cn(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Mt]},Ls(this.settings),this.notifications.loadMutedFromList(this.settings.mutedNotificationCategories),this.notifications.setHistoryLimit(this.settings.notificationHistoryLimit),this.notifications.setDefaultAuthorId(this.settings.authorId),this.attachNotificationPersistence()}notificationsPath(){return this.pluginPrivatePath("notifications.json")}async attachNotificationPersistence(){if(this.notifPersistenceWired)return;this.notifPersistenceWired=!0;let t=this.app.vault.adapter,e=this.notificationsPath();try{if(await t.exists(e)){let s=await t.read(e),i=JSON.parse(s);Array.isArray(i)&&this.notifications.loadHistory(i)}}catch(s){console.warn("[Stashpad] failed to load notification history",s)}this.notifications.onChange(()=>{this.notifSaveTimer!=null&&window.clearTimeout(this.notifSaveTimer),this.notifSaveTimer=window.setTimeout(()=>{this.notifSaveTimer=null,this.persistNotificationHistory()},1e3)})}async persistNotificationHistory(){try{let t=this.notifications.recent().slice().reverse(),e=this.notificationsPath(),s=e.replace(/\/[^/]+$/,""),i=this.app.vault.adapter;s&&!await i.exists(s)&&await i.mkdir(s),await i.write(e,JSON.stringify(t))}catch(t){console.warn("[Stashpad] failed to save notification history",t)}}readLastCursorFile(){try{let t=window.localStorage.getItem(this.LAST_CURSOR_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadLastCursor(t){let s=this.readLastCursorFile()[t]??{};return new Map(Object.entries(s))}saveLastCursor(t,e,s){try{let i=this.readLastCursorFile();i[t]||(i[t]={}),i[t][e]=s,window.localStorage.setItem(this.LAST_CURSOR_LS_KEY,JSON.stringify(i))}catch(i){console.warn("[Stashpad] failed to save last-cursor",i)}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),Ls(this.settings);let t=(this.settings.authorId??"").trim();t&&this.authorRegistry.record({id:t,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment}),console.debug("[Stashpad] saveSettings",{shortcuts:this.settings.shortcuts,mod:this.settings.mod})}async persistSettingsQuiet(){await this.queueWrite()}async fixOrphanParents(){let t=new Set(this.discoverStashpadFolders());if(t.size===0){new et.Notice("No Stashpad folders found.");return}let e=new Set,s=this.app.vault.getMarkdownFiles();for(let p of s){let u=this.app.metadataCache.getFileCache(p)?.frontmatter,d=typeof u?.id=="string"?u.id.trim():"";d&&e.add(d)}let{newId:i}=await Promise.resolve().then(()=>(Pt(),Ne)),n=()=>{for(let p=0;p<100;p++){let u=i();if(!e.has(u))return e.add(u),u}for(let p=8;p<=16;p+=2){let u=i(p);if(!e.has(u))return e.add(u),u}throw new Error("Could not generate a unique id")},r=[];for(let p of s){let u=p.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(u))continue;let d=this.app.metadataCache.getFileCache(p)?.frontmatter,f=typeof d?.id=="string"?d.id.trim():"",m=d?.parent,v=typeof m=="string"?m.trim()!=="":m!=null,y=typeof d?.created=="string"&&d.created.trim()!=="",b=!f,k=!v,C=!y;!b&&!k&&!C||r.push({file:p,addId:b,addParent:k,addCreated:C})}if(r.length===0){new et.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let o=0,a=0,l=this.newLog();for(let p of r)try{let u;await this.app.fileManager.processFrontMatter(p.file,m=>{if(p.addId&&(typeof m.id=="string"&&m.id.trim()||(u=n(),m.id=u)),p.addParent){let v=m.parent;(typeof v=="string"?v.trim()!=="":v!=null)||(m.parent=R)}p.addCreated&&(typeof m.created=="string"&&m.created.trim()||(m.created=new Date(p.file.stat.ctime).toISOString()))});let d=this.app.metadataCache.getFileCache(p.file)?.frontmatter,f=u??d?.id??"";f&&await l.append({type:"parent_change",id:f,payload:{from:null,to:R,reason:"orphan_fix",path:p.file.path,addedId:p.addId,addedParent:p.addParent,addedCreated:p.addCreated}}),o++}catch(u){console.warn("Stashpad: orphan fix failed for",p.file.path,u),a++}let c=a?` (${a} failed \u2014 see console)`:"";new et.Notice(`Fixed ${o} note${o===1?"":"s"} in Stashpad folders${c}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Pt(),Ne)),s=new Set;for(let l of this.app.vault.getMarkdownFiles()){if(l.path===t.path)continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter,p=typeof c?.id=="string"?c.id.trim():"";p&&s.add(p)}let i=()=>{for(let l=0;l<50;l++){let c=e();if(!s.has(c))return c}for(let l=8;l<=16;l+=2){let c=e(l);if(!s.has(c))return c}throw new Error("Could not generate a unique id")},n=[],r=[];try{await this.app.fileManager.processFrontMatter(t,l=>{let c=typeof l.id=="string"?l.id.trim():"";!c||/\s/.test(c)||s.has(c)?(l.id=i(),n.push("id")):r.push("id"),l.parent!==void 0&&l.parent!==null&&String(l.parent).trim()!==""?r.push("parent"):(l.parent=R,n.push("parent")),typeof l.created=="string"&&l.created.trim()!==""?r.push("created"):(l.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(l){new et.Notice(`Adopt failed: ${l.message}`);return}let o=!1;try{let l=this.app.metadataCache.getFileCache(t)?.frontmatter,c=typeof l?.id=="string"?l.id.trim():"";if(c&&t.basename&&!t.basename.endsWith(`-${c}`)){let p=`${t.parent?t.parent.path+"/":""}${t.basename}-${c}.md`;await this.app.vault.adapter.exists(p)||(await this.app.fileManager.renameFile(t,p),o=!0)}}catch(l){console.warn("Stashpad: adopt rename failed",l)}if(n.length===0&&!o){new et.Notice(`Already a Stashpad note (${r.join(", ")} present).`);return}let a=[];n.length&&a.push(`added: ${n.join(", ")}`),o&&a.push("renamed with id"),new et.Notice(`Adopted into Stashpad \u2014 ${a.join("; ")}.`);try{let l=this.newLog(),c=this.app.metadataCache.getFileCache(t)?.frontmatter,p=c?.id??"";p&&await l.append({type:"create",id:p,payload:{path:t.path,parent:c?.parent??R,source:"adopt",added:n}})}catch{}}};function ln(g,h,t){let e=_s();for(let s of Fe){let i=h&&typeof h[s.id]=="string"?h[s.id]:t&&typeof t[s.id]=="string"?t[s.id]:null;i!=null&&i!==""&&(e[s.id].primary=i)}if(g&&typeof g=="object")for(let s of Fe){let i=g[s.id];!i||typeof i!="object"||(e[s.id]={primary:typeof i.primary=="string"?i.primary:e[s.id].primary,secondary:typeof i.secondary=="string"?i.secondary:"",preferRight:!!i.preferRight,useBoth:!!i.useBoth})}return e}function cn(g){let h={};if(!g||typeof g!="object")return h;for(let[t,e]of Object.entries(g))if(typeof e=="string")h[t]=e;else if(e&&typeof e=="object"){for(let s of Object.values(e))if(typeof s=="string"&&s.length>0){h[t]=s;break}}return h}var Ws=class extends et.SuggestModal{constructor(t,e,s,i){super(t);this.def=e;this.folders=s;this.onPick=i;this.setPlaceholder("Open the file picker, or choose a destination folder\u2026")}getSuggestions(t){let e=t.toLowerCase(),i={label:`\u{1F4C2} Open file picker \u2192 ${this.def.split("/").pop()||this.def}`,folder:this.def,pinned:!0},n=this.folders.filter(r=>r.toLowerCase().includes(e)).map(r=>({label:`Import into ${r}`,folder:r}));return[i,...n]}renderSuggestion(t,e){e.createDiv({text:t.label}),t.pinned&&e.addClass("is-pinned-import-target")}onChooseSuggestion(t){this.onPick(t.folder)}}; +Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[t.path],actions:Ge(this.app,t.path,et.Platform.isMobile)}),console.error(s)}}lookupNoteAuthorIds(t){let e=new Set,s=i=>{if(typeof i!="string")return null;let n=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let i of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(i)?.frontmatter;if(n?.id!==t)continue;let r=s(n?.author);r&&e.add(r);let a=n?.contributors;if(Array.isArray(a))for(let o of a){let l=s(o);l&&e.add(l)}break}return Array.from(e)}lookupNoteAuthorId(t){return this.lookupNoteAuthorIds(t)[0]??null}async rebootstrapAllFolders(){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner()}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let h of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(h)?.frontmatter?.id!==t)continue;let m=h.parent?.path;m&&e.add(m)}let s=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),i=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],r=async h=>{if(h&&!await this.app.vault.adapter.exists(h))try{await this.app.vault.createFolder(h)}catch(f){let m=f?.message??"";if(!/already exists/i.test(m))throw f}},a=0,o=0,l=0,c=0;for(let h of e)try{if(s&&await r(`${h}/${s}`),i&&await r(`${h}/${i}`),this.settings.autoImport)try{c+=await this.importService.importLooseFilesIn(h)}catch(m){console.warn("Stashpad: loose-file sweep failed",h,m)}let f=await bi(this.app,h);a+=f.checked,o+=f.written,l+=await this.rebootstrapFolderSlugs(h),n.push(h)}catch(f){console.warn(`Stashpad: rebootstrap skipped ${h}`,f)}let p=0;try{p=(await this.rebuildAuthorRegistry()).total}catch(h){console.warn("Stashpad: rebootstrap author-registry rebuild failed",h)}let u=0;try{u=await this.convertAttachmentsToLinks()}catch(h){console.warn("Stashpad: attachment-link conversion failed",h)}return{touched:n,fmChecked:a,fmWritten:o,slugsRenamed:l,authors:p,imported:c,attachmentsLinked:u}}async rebootstrapFolderSlugs(t){let e="__root__",s=t.replace(/\/+$/,""),i=this.settings.slugStopWords??_t,n=0,r=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===s);for(let a of r){let o=re(a.basename);if(!(!o||o===e||this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==o))try{let c=await this.app.vault.cachedRead(a),p=c.startsWith("---")?c.slice(c.indexOf(` +---`,3)+4).replace(/^\r?\n/,""):c,u=Ft(p,i),h=xt(u,o);if(a.name===h)continue;let f=a.parent?`${a.parent.path}/${h}`:h;if(this.app.vault.getAbstractFileByPath(f))continue;await this.app.fileManager.renameFile(a,f),n+=1}catch(c){console.warn(`Stashpad: slug rebootstrap skipped ${a.path}`,c)}}return n}onStashpadSelectionChange(t){return this.stashpadSelectionListeners.add(t),()=>this.stashpadSelectionListeners.delete(t)}notifyStashpadSelectionChanged(){for(let t of this.stashpadSelectionListeners)try{t()}catch(e){console.warn("[Stashpad] selection listener failed",e)}}onStashpadContentChange(t){return this.stashpadContentListeners.add(t),()=>this.stashpadContentListeners.delete(t)}notifyStashpadContentChanged(){for(let t of this.stashpadContentListeners)try{t()}catch(e){console.warn("[Stashpad] content listener failed",e)}}getActiveStashpadSelection(){let e=this.lastActiveStashpadLeaf?.view;if(!e||e.getViewType?.()!==mt)return null;let s=e.noteFolder??"";if(!s)return null;let i=e.currentChildren??[],n;if(typeof e.cursorIdx=="number"&&e.cursorIdx>=0&&(n=i[e.cursorIdx]),!n&&e.selection?.size>0){let r=e.firstSelectedId??[...e.selection][0];n=i.find(a=>a.id===r)}return n?.file?{folder:s,id:n.id,file:n.file}:null}async pinNote(t){let e=this.settings.pinnedNotes??[];e.some(s=>s.folder===t.folder&&s.id===t.id)||(this.settings.pinnedNotes=[...e,t],await this.saveSettings(),this.refreshPanelsView())}async unpinNote(t){let e=this.settings.pinnedNotes??[],s=e.filter(i=>!(i.folder===t.folder&&i.id===t.id));s.length!==e.length&&(this.settings.pinnedNotes=s,await this.saveSettings(),this.refreshPanelsView())}isPinned(t){return(this.settings.pinnedNotes??[]).some(e=>e.folder===t.folder&&e.id===t.id)}refreshPanelsView(){let t=this.app.workspace.getLeavesOfType(Rt);for(let e of t){let s=e.view;s&&typeof s.render=="function"&&s.render()}}openFolderPicker(){let t=f=>{let v=f.getViewState().state?.folderOverride;return typeof v=="string"&&v.trim()?v.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(mt),s=this.discoverStashpadFolders(),i=Ot(),n=i?(i.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",r=new Set;for(let f of this.app.vault.getAllLoadedFiles())if(f.children){let m=f.path;m&&m!=="/"&&!m.startsWith(".")&&r.add(m)}let a=f=>{let m=f.split("/").filter(Boolean).pop()??"";return m?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive"].map(y=>(y??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(m):!1},o=new Set,l=[],c=[],p=new Set;for(let f of e){let m=t(f);if(p.has(m))continue;p.add(m),o.add(m);let v=m.split("/").pop()||m;l.push({kind:"reveal",folder:m,label:`Reveal "${v}" tab`,leaf:f,icon:"layout-grid"}),c.push({kind:"open-anyway",folder:m,label:`Open "${v}" in another new tab`,icon:"layout-template"})}for(let f of s.filter(m=>!o.has(m))){let m=f.split("/").pop()||f;l.push({kind:"open",folder:f,label:`Open "${m}" in new tab`,icon:"layout-template"})}let u=this,h=new class extends et.SuggestModal{getSuggestions(f){let m=f.trim().toLowerCase(),v=m?m.split(/\s+/).filter(Boolean):[],y=I=>{if(!v.length)return!0;let E=I.toLowerCase();for(let D of v)if(!E.includes(D))return!1;return!0},b=m?l.filter(I=>{let E="folder"in I?I.folder:"";return y(I.label)||y(E)}):l.slice();if(m&&i&&n)for(let I of s){if(I.toLowerCase()===n.toLowerCase())continue;let E=I.split("/").pop()??I,D=`${I} ${E}`;y(D)&&b.push({kind:"switch-current",folder:I,label:`Switch this tab to "${E}"`,icon:"folder-input"})}let k=f.trim().replace(/^\/+|\/+$/g,"");if(k&&!a(k)){let I=Array.from(r).find(D=>D.toLowerCase()===k.toLowerCase()),E=s.some(D=>D.toLowerCase()===k.toLowerCase());if(I&&!E)b.push({kind:"convert",folder:I,label:`Convert \u201C${gs(I)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!I){let D=gs(k);b.push({kind:"create",folder:k,label:`+ Create new Stashpad \u201C${D}\u201D`,icon:"folder-plus"})}}let T=c.filter(I=>y(I.label)||y(I.folder));return b.push(...T),b}renderSuggestion(f,m){m.addClass("stashpad-suggest-item"),m.addClass("stashpad-ribbon-suggest-item"),f.kind==="create"&&m.addClass("stashpad-suggest-create");let v=m.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,et.setIcon)(v,f.icon);let y=m.createDiv({cls:"stashpad-ribbon-suggest-body"});y.createDiv({cls:"stashpad-suggest-title",text:f.label}),"folder"in f&&f.folder&&f.label!==f.folder&&y.createDiv({cls:"stashpad-suggest-preview",text:f.folder})}async onChooseSuggestion(f){if(f.kind==="reveal"){u.app.workspace.revealLeaf(f.leaf);return}if(f.kind==="open"||f.kind==="open-anyway"){await u.activateViewForFolder(f.folder);return}if(f.kind==="switch-current"){let m=i;m&&typeof m.setFolderOverride=="function"&&(await m.setFolderOverride(f.folder),u.app.workspace.revealLeaf(m.leaf));return}if(f.kind==="create"){try{let m=gs(f.folder);await u.app.vault.adapter.exists(m)||await u.app.vault.createFolder(m),await u.activateViewForFolder(m)}catch(m){new et.Notice(`Stashpad: couldn't create folder (${m.message})`)}return}if(f.kind==="convert"){let{ConfirmModal:m}=await Promise.resolve().then(()=>(Ht(),Ee)),v=f.folder,y=[`\u201C${v}\u201D already exists as a regular vault folder.`,"Converting will add a Home note + _imports / _exports subfolders inside it.","Existing files are NOT touched."];new m(u.app,"Convert into a Stashpad?",y.join(` +`),"Convert",async b=>{if(b)try{await u.activateViewForFolder(v)}catch(k){new et.Notice(`Stashpad: couldn't convert folder (${k.message})`)}}).open();return}}}(this.app);h.setPlaceholder(i?"Open, switch this tab, or create a Stashpad folder \u2014 type to filter\u2026":"Open or create a Stashpad folder \u2014 type to filter\u2026"),h.open()}async openTinyWindow(){let t=Ot(),e=t?.folderOverride??null,s=t?.focusId??"__root__",i=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new et.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:mt,active:!0,state:{folderOverride:e,focusId:s,tinyMode:!0,tinyAlwaysOnTop:!1,compactMode:i}});try{this.app.workspace.revealLeaf(n)}catch{}}async activateView(t={reveal:!0}){let{workspace:e}=this.app;if(t.reveal){let i=e.getLeavesOfType(mt);if(i.length>0){e.revealLeaf(i[0]);return}}let s=e.getLeaf("tab");await s.setViewState({type:mt,active:!0}),e.revealLeaf(s)}async activateViewForFolder(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let s=this.app.workspace.getLeaf("tab");await s.setViewState({type:mt,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(s)}isStashpadNoteFile(t){let e=t.parent?.path?.replace(/\/+$/,"")??"";if(!this.discoverStashpadFolders().includes(e))return!1;let s=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;return typeof s=="string"&&s.length>0}async revealNoteInStashpad(t){let e=t.parent?.path?.replace(/\/+$/,"")??"",s=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;if(!e||typeof s!="string"||!s){new et.Notice("That note isn't a Stashpad note.");return}let i=this.app.workspace.getLeavesOfType(mt).find(r=>(r.view?.noteFolder??"")===e);if(i){this.app.workspace.revealLeaf(i);let r=i.view;typeof r?.navigateTo=="function"&&r.navigateTo(s);return}await this.activateViewForFolder(e);let n=this.lastActiveStashpadLeaf?.view;typeof n?.navigateTo=="function"&&n.navigateTo(s)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,s=this.discoverStashpadFolders(),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let r=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!r)continue;let a=typeof r.author=="string"?r.author:"",o=Array.isArray(r.contributors)?r.contributors.filter(f=>typeof f=="string"):[],l=a.includes(e),c=o.some(f=>f.includes(e));if(!l&&!c)continue;let p=n.parent?.path??"",u=s.find(f=>p===f||p.startsWith(f+"/"));if(!u)continue;i.has(u)||i.set(u,{authored:0,contributed:0});let h=i.get(u);l&&h.authored++,c&&h.contributed++}return[...i.entries()].map(([n,r])=>({folder:n,...r})).sort((n,r)=>r.authored+r.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return we(t)}authorRefFor(t,e,s){let i=s.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",n=`${t.replace(/\/+$/,"")}/_authors/${i}-${e}.md`,r=s.replace(/[\[\]|]/g,"").trim()||i;return`[[${n}|${r}]]`}async ensureAuthorStubFor(t,e,s){if(!e||!s)return;this.authorRegistry.record({id:e,name:s});let i=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(l=>l.path.startsWith(i+"/")&&this.parseAuthorFilePath(l.path)?.id===e))return;let r=this.authorRegistry.get(e),a=this.authorNameToSafe(s),o=`${i}/${a}-${e}.md`;try{if(await this.ensureFolderPath(i),await this.app.vault.adapter.exists(o))return;await this.app.vault.create(o,this.buildAuthorStub({id:e,name:s,role:r?.role,department:r?.department},new Date().toISOString()))}catch(l){console.warn("[Stashpad] ensureAuthorStubFor failed",o,l)}}async rebuildAuthorRegistry(){let t=this.discoverStashpadFolders(),e=new Map,s=0;for(let n of this.app.vault.getMarkdownFiles()){let r=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!r)continue;let a=[];if(typeof r.author=="string"&&a.push(r.author),Array.isArray(r.contributors))for(let o of r.contributors)typeof o=="string"&&a.push(o);for(let o of a){let l=this.parseAuthorRef(o);if(l)if(!e.has(l.id))e.set(l.id,{id:l.id,name:l.name,fromStub:!1}),s++;else{let c=e.get(l.id);!c.name&&l.name&&(c.name=l.name)}}}let i=0;for(let n of t){let r=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(r+"/"))continue;let o=this.parseAuthorFilePath(a.path);if(!o)continue;let l=this.app.metadataCache.getFileCache(a)?.frontmatter,p=((Array.isArray(l?.aliases)?l.aliases.find(m=>typeof m=="string")??"":typeof l?.aliases=="string"?l.aliases:"")||(typeof l?.name=="string"?l.name:"")||o.name).trim(),u=typeof l?.role=="string"?l.role:void 0,h=typeof l?.department=="string"?l.department:void 0,f=e.get(o.id);f||i++,e.set(o.id,{id:o.id,name:p||f?.name,role:u??f?.role,department:h??f?.department,fromStub:!0})}}return await this.authorRegistry.load(),this.authorRegistry.replaceAll([...e.values()]),await this.authorRegistry.save(),{total:e.size,fromStubs:i,fromNotes:s}}buildAuthorStub(t,e){let s=a=>a.replace(/[\r\n]+/g," ").trim(),i=a=>s(a).replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=s(t.name),r=["---",`authorId: ${t.id}`,"aliases:",` - "${i(t.name)}"`];return t.role&&r.push(`role: "${i(t.role)}"`),t.department&&r.push(`department: "${i(t.department)}"`),r.push(`created: ${e}`,"---",`# ${n}`),r.join(` +`)}async restoreMissingAuthorStubs(){await this.authorRegistry.load();let t=this.authorRegistry.all().filter(n=>n.id&&n.name),e=this.discoverStashpadFolders(),s=this.app.vault.getMarkdownFiles(),i=0;for(let n of e){let r=`${n}/_authors`,a=new Set;for(let o of s){if(!o.path.startsWith(r+"/"))continue;let l=this.parseAuthorFilePath(o.path)?.id;l&&a.add(l)}for(let o of t){if(a.has(o.id))continue;let l=this.authorNameToSafe(o.name),c=`${r}/${l}-${o.id}.md`;try{if(await this.ensureFolderPath(r),await this.app.vault.adapter.exists(c))continue;await this.app.vault.create(c,this.buildAuthorStub(o,o.firstSeen??new Date().toISOString())),i++}catch(p){console.warn("[Stashpad] restore author stub failed",c,p)}}}return{created:i,folders:e.length}}async convertAttachmentsToLinks(){let t=0,e=s=>/^\[\[.*\]\]$/.test(s.trim());for(let s of this.discoverStashpadFolders()){let i=s.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let r=n.parent?.path?.replace(/\/+$/,"")??"";if(r!==i&&!r.startsWith(i+"/")||ye(n.path))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!(!a||typeof a.id!="string"||!a.id||!Array.isArray(a.attachments)||!a.attachments.some(l=>typeof l=="string"&&l.trim()&&!e(l))))try{await this.app.fileManager.processFrontMatter(n,l=>{Array.isArray(l.attachments)&&(l.attachments=l.attachments.map(c=>typeof c=="string"&&c.trim()?qt(c):c))}),t++}catch(l){console.warn("[Stashpad] attachment-link conversion failed",n.path,l)}}}return t}syncObsidianExcludedArchives(){try{let t=this.app.vault;if(typeof t.getConfig!="function"||typeof t.setConfig!="function")return;let e=Array.isArray(t.getConfig("userIgnoreFilters"))?t.getConfig("userIgnoreFilters"):[],s=new Set(e),i=!1;for(let n of this.discoverStashpadFolders()){let r=`${n.replace(/\/+$/,"")}/_archive/`;s.has(r)||(s.add(r),i=!0)}i&&t.setConfig("userIgnoreFilters",[...s])}catch(t){console.warn("[Stashpad] couldn't update Obsidian excluded files",t)}}openImportPicker(){let t=this.discoverStashpadFolders();if(t.length===0){new et.Notice("No Stashpad folders to import into.");return}if(t.length===1){this.importService.pickFilesInto(t[0]);return}let e=this.importService.defaultDestination()??t[0];new qs(this.app,e,t,s=>this.importService.pickFilesInto(s)).open()}async seedLocalAuthorStub(t){let e=(this.settings.authorId??"").trim(),s=(this.settings.authorName??"").trim();if(!e||!s)return!1;let i=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(o=>o.path.startsWith(i+"/")&&this.parseAuthorFilePath(o.path)?.id===e))return!1;let r=this.authorNameToSafe(s),a=`${i}/${r}-${e}.md`;try{return await this.ensureFolderPath(i),await this.app.vault.adapter.exists(a)?!1:(await this.app.vault.create(a,this.buildAuthorStub({id:e,name:s,role:this.settings.authorRole,department:this.settings.authorDepartment},new Date().toISOString())),this.authorRegistry.record({id:e,name:s,role:this.settings.authorRole,department:this.settings.authorDepartment}),!0)}catch(o){return console.warn("[Stashpad] seedLocalAuthorStub failed",a,o),!1}}async seedLocalAuthorStubsEverywhere(){if(!(this.settings.authorName??"").trim())return 0;let e=0;for(let s of this.discoverStashpadFolders())await this.seedLocalAuthorStub(s)&&e++;return e}async ensureFolderPath(t){let e=this.app.vault.adapter,s=t.split("/").filter(Boolean),i="";for(let n of s){i=i?`${i}/${n}`:n;try{await e.exists(i)||await e.mkdir(i)}catch(r){if(!/already exists/i.test(r.message))throw r}}}async loadSettings(){let t=await this.loadData()??{};typeof t?.confirmMultiDelete=="boolean"&&(typeof t.confirmBulkDelete!="boolean"&&(t.confirmBulkDelete=t.confirmMultiDelete),typeof t.confirmAttachmentDelete!="boolean"&&(t.confirmAttachmentDelete=t.confirmMultiDelete),delete t.confirmMultiDelete),typeof t?.jdIndexDestFolder=="string"&&typeof t?.jdIndexStashpadFolder!="string"&&(t.jdIndexStashpadFolder=t.jdIndexDestFolder),this.settings={...zt,...t,shortcuts:{...zt.shortcuts,...t?.shortcuts??{}},mod:{...zt.mod,...t?.mod??{}},bindings:fn(t?.bindings,t?.shortcuts,t?.mod),customPalette:Array.isArray(t?.customPalette)?t.customPalette.filter(e=>typeof e=="string"&&/^#[0-9a-f]{6}$/i.test(e)):[],colorAliases:t?.colorAliases&&typeof t.colorAliases=="object"?t.colorAliases:{},noteTemplates:t?.noteTemplates&&typeof t.noteTemplates=="object"?t.noteTemplates:{},authorName:typeof t?.authorName=="string"?t.authorName:"",authorId:typeof t?.authorId=="string"?t.authorId:"",authorRole:typeof t?.authorRole=="string"?t.authorRole:"",authorDepartment:typeof t?.authorDepartment=="string"?t.authorDepartment:"",showAuthor:typeof t?.showAuthor=="boolean"?t.showAuthor:!0,showContributors:typeof t?.showContributors=="boolean"?t.showContributors:!0,showLastEdit:typeof t?.showLastEdit=="boolean"?t.showLastEdit:!0,viewModes:t?.viewModes&&typeof t.viewModes=="object"&&!Array.isArray(t.viewModes)?t.viewModes:{},includeAttachmentsInEverything:t?.includeAttachmentsInEverything&&typeof t.includeAttachmentsInEverything=="object"&&!Array.isArray(t.includeAttachmentsInEverything)?t.includeAttachmentsInEverything:{},hideChildlessNotes:t?.hideChildlessNotes&&typeof t.hideChildlessNotes=="object"&&!Array.isArray(t.hideChildlessNotes)?t.hideChildlessNotes:{},hideCompletedNotes:t?.hideCompletedNotes&&typeof t.hideCompletedNotes=="object"&&!Array.isArray(t.hideCompletedNotes)?t.hideCompletedNotes:{},mutedNotificationCategories:Array.isArray(t?.mutedNotificationCategories)?t.mutedNotificationCategories.filter(e=>typeof e=="string"):[],notificationHistoryLimit:typeof t?.notificationHistoryLimit=="number"&&Number.isFinite(t.notificationHistoryLimit)?t.notificationHistoryLimit:5e3,drafts:mn(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[..._t]},Rs(this.settings),this.notifications.loadMutedFromList(this.settings.mutedNotificationCategories),this.notifications.setHistoryLimit(this.settings.notificationHistoryLimit),this.notifications.setDefaultAuthorId(this.settings.authorId),this.attachNotificationPersistence()}notificationsPath(){return this.pluginPrivatePath("notifications.json")}async attachNotificationPersistence(){if(this.notifPersistenceWired)return;this.notifPersistenceWired=!0;let t=this.app.vault.adapter,e=this.notificationsPath();try{if(await t.exists(e)){let s=await t.read(e),i=JSON.parse(s);Array.isArray(i)&&this.notifications.loadHistory(i)}}catch(s){console.warn("[Stashpad] failed to load notification history",s)}this.notifications.onChange(()=>{this.notifSaveTimer!=null&&window.clearTimeout(this.notifSaveTimer),this.notifSaveTimer=window.setTimeout(()=>{this.notifSaveTimer=null,this.persistNotificationHistory()},1e3)})}async persistNotificationHistory(){try{let t=this.notifications.recent().slice().reverse(),e=this.notificationsPath(),s=e.replace(/\/[^/]+$/,""),i=this.app.vault.adapter;s&&!await i.exists(s)&&await i.mkdir(s),await i.write(e,JSON.stringify(t))}catch(t){console.warn("[Stashpad] failed to save notification history",t)}}readLastCursorFile(){try{let t=window.localStorage.getItem(this.LAST_CURSOR_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadLastCursor(t){let s=this.readLastCursorFile()[t]??{};return new Map(Object.entries(s))}saveLastCursor(t,e,s){try{let i=this.readLastCursorFile();i[t]||(i[t]={}),i[t][e]=s,window.localStorage.setItem(this.LAST_CURSOR_LS_KEY,JSON.stringify(i))}catch(i){console.warn("[Stashpad] failed to save last-cursor",i)}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),Rs(this.settings),Et.enabled=!!this.settings.enablePerfProfiling;let t=(this.settings.authorId??"").trim();t&&this.authorRegistry.record({id:t,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment}),console.debug("[Stashpad] saveSettings",{shortcuts:this.settings.shortcuts,mod:this.settings.mod})}async persistSettingsQuiet(){await this.queueWrite()}async fixOrphanParents(){let t=new Set(this.discoverStashpadFolders());if(t.size===0){new et.Notice("No Stashpad folders found.");return}let e=new Set,s=this.app.vault.getMarkdownFiles();for(let p of s){let u=this.app.metadataCache.getFileCache(p)?.frontmatter,h=typeof u?.id=="string"?u.id.trim():"";h&&e.add(h)}let{newId:i}=await Promise.resolve().then(()=>(Mt(),He)),n=()=>{for(let p=0;p<100;p++){let u=i();if(!e.has(u))return e.add(u),u}for(let p=8;p<=16;p+=2){let u=i(p);if(!e.has(u))return e.add(u),u}throw new Error("Could not generate a unique id")},r=[];for(let p of s){let u=p.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(u))continue;let h=this.app.metadataCache.getFileCache(p)?.frontmatter,f=typeof h?.id=="string"?h.id.trim():"",m=h?.parent,v=typeof m=="string"?m.trim()!=="":m!=null,y=typeof h?.created=="string"&&h.created.trim()!=="",b=!f,k=!v,T=!y;!b&&!k&&!T||r.push({file:p,addId:b,addParent:k,addCreated:T})}if(r.length===0){new et.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,o=0,l=this.newLog();for(let p of r)try{let u;await this.app.fileManager.processFrontMatter(p.file,m=>{if(p.addId&&(typeof m.id=="string"&&m.id.trim()||(u=n(),m.id=u)),p.addParent){let v=m.parent;(typeof v=="string"?v.trim()!=="":v!=null)||(m.parent=R)}p.addCreated&&(typeof m.created=="string"&&m.created.trim()||(m.created=new Date(p.file.stat.ctime).toISOString()))});let h=this.app.metadataCache.getFileCache(p.file)?.frontmatter,f=u??h?.id??"";f&&await l.append({type:"parent_change",id:f,payload:{from:null,to:R,reason:"orphan_fix",path:p.file.path,addedId:p.addId,addedParent:p.addParent,addedCreated:p.addCreated}}),a++}catch(u){console.warn("Stashpad: orphan fix failed for",p.file.path,u),o++}let c=o?` (${o} failed \u2014 see console)`:"";new et.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${c}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Mt(),He)),s=new Set;for(let l of this.app.vault.getMarkdownFiles()){if(l.path===t.path)continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter,p=typeof c?.id=="string"?c.id.trim():"";p&&s.add(p)}let i=()=>{for(let l=0;l<50;l++){let c=e();if(!s.has(c))return c}for(let l=8;l<=16;l+=2){let c=e(l);if(!s.has(c))return c}throw new Error("Could not generate a unique id")},n=[],r=[];try{await this.app.fileManager.processFrontMatter(t,l=>{let c=typeof l.id=="string"?l.id.trim():"";!c||/\s/.test(c)||s.has(c)?(l.id=i(),n.push("id")):r.push("id"),l.parent!==void 0&&l.parent!==null&&String(l.parent).trim()!==""?r.push("parent"):(l.parent=R,n.push("parent")),typeof l.created=="string"&&l.created.trim()!==""?r.push("created"):(l.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(l){new et.Notice(`Adopt failed: ${l.message}`);return}let a=!1;try{let l=this.app.metadataCache.getFileCache(t)?.frontmatter,c=typeof l?.id=="string"?l.id.trim():"";if(c&&t.basename&&!t.basename.endsWith(`-${c}`)){let p=`${t.parent?t.parent.path+"/":""}${t.basename}-${c}.md`;await this.app.vault.adapter.exists(p)||(await this.app.fileManager.renameFile(t,p),a=!0)}}catch(l){console.warn("Stashpad: adopt rename failed",l)}if(n.length===0&&!a){new et.Notice(`Already a Stashpad note (${r.join(", ")} present).`);return}let o=[];n.length&&o.push(`added: ${n.join(", ")}`),a&&o.push("renamed with id"),new et.Notice(`Adopted into Stashpad \u2014 ${o.join("; ")}.`);try{let l=this.newLog(),c=this.app.metadataCache.getFileCache(t)?.frontmatter,p=c?.id??"";p&&await l.append({type:"create",id:p,payload:{path:t.path,parent:c?.parent??R,source:"adopt",added:n}})}catch{}}};function fn(g,d,t){let e=$s();for(let s of Me){let i=d&&typeof d[s.id]=="string"?d[s.id]:t&&typeof t[s.id]=="string"?t[s.id]:null;i!=null&&i!==""&&(e[s.id].primary=i)}if(g&&typeof g=="object")for(let s of Me){let i=g[s.id];!i||typeof i!="object"||(e[s.id]={primary:typeof i.primary=="string"?i.primary:e[s.id].primary,secondary:typeof i.secondary=="string"?i.secondary:"",preferRight:!!i.preferRight,useBoth:!!i.useBoth})}return e}function mn(g){let d={};if(!g||typeof g!="object")return d;for(let[t,e]of Object.entries(g))if(typeof e=="string")d[t]=e;else if(e&&typeof e=="object"){for(let s of Object.values(e))if(typeof s=="string"&&s.length>0){d[t]=s;break}}return d}var qs=class extends et.SuggestModal{constructor(t,e,s,i){super(t);this.def=e;this.folders=s;this.onPick=i;this.setPlaceholder("Choose a Stashpad folder to import into\u2026")}getSuggestions(t){let e=t.toLowerCase();return[this.def,...this.folders.filter(i=>i!==this.def)].filter(i=>i.toLowerCase().includes(e)).map(i=>({label:i,folder:i,current:i===this.def}))}renderSuggestion(t,e){e.createDiv({text:t.label}),t.current&&(e.createDiv({cls:"stashpad-suggest-note",text:"current"}),e.addClass("is-pinned-import-target"))}onChooseSuggestion(t){this.onPick(t.folder)}}; /*! Bundled license information: jszip/dist/jszip.min.js: diff --git a/manifest.json b/manifest.json index 449bd10..eb1e545 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.79.15", + "version": "0.82.4", "minAppVersion": "1.7.0", "description": "Chat-style nested-notes view: rapid capture, outliner navigation, in-place editing.", "author": "Human", diff --git a/package.json b/package.json index 0b9c563..4d96055 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad-obsidian", - "version": "0.79.15", + "version": "0.82.4", "private": true, "scripts": { "dev": "node esbuild.config.mjs", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..17757df --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,443 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + jszip: + specifier: ^3.10.1 + version: 3.10.1 + devDependencies: + '@types/node': + specifier: ^20.10.0 + version: 20.19.41 + esbuild: + specifier: ^0.21.0 + version: 0.21.5 + obsidian: + specifier: latest + version: 1.12.3(@codemirror/state@6.5.0)(@codemirror/view@6.38.6) + typescript: + specifier: ^5.4.0 + version: 5.9.3 + +packages: + + '@codemirror/state@6.5.0': + resolution: {integrity: sha512-MwBHVK60IiIHDcoMet78lxt6iw5gJOGSbNbOIVBHWVXIH4/Nq1+GQgLLGgI1KlnN86WDXsPudVaqYHKBIx7Eyw==} + + '@codemirror/view@6.38.6': + resolution: {integrity: sha512-qiS0z1bKs5WOvHIAC0Cybmv4AJSkAXgX5aD6Mqd2epSLlVJsQl8NG23jCVouIgkh4All/mrbdsf2UOLFnJw0tw==} + + '@esbuild/aix-ppc64@0.21.5': + resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.21.5': + resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.21.5': + resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.21.5': + resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.21.5': + resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.21.5': + resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.21.5': + resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.21.5': + resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.21.5': + resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.21.5': + resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.21.5': + resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.21.5': + resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.21.5': + resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.21.5': + resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.21.5': + resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.21.5': + resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.21.5': + resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-x64@0.21.5': + resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-x64@0.21.5': + resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/sunos-x64@0.21.5': + resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.21.5': + resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.21.5': + resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.21.5': + resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@marijn/find-cluster-break@1.0.2': + resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==} + + '@types/codemirror@5.60.8': + resolution: {integrity: sha512-VjFgDF/eB+Aklcy15TtOTLQeMjTo07k7KAjql8OK5Dirr7a6sJY4T1uVBDuTVG9VEmn1uUsohOpYnVfgC6/jyw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/node@20.19.41': + resolution: {integrity: sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==} + + '@types/tern@0.23.9': + resolution: {integrity: sha512-ypzHFE/wBzh+BlH6rrBgS5I/Z7RD21pGhZ2rltb/+ZrVM1awdZwjx7hE5XfuYgHWk9uvV5HLZN3SloevCAp3Bw==} + + core-util-is@1.0.3: + resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==} + + crelt@1.0.6: + resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==} + + esbuild@0.21.5: + resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==} + engines: {node: '>=12'} + hasBin: true + + immediate@3.0.6: + resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==} + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + isarray@1.0.0: + resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} + + jszip@3.10.1: + resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==} + + lie@3.3.0: + resolution: {integrity: sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==} + + moment@2.29.4: + resolution: {integrity: sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==} + + obsidian@1.12.3: + resolution: {integrity: sha512-HxWqe763dOqzXjnNiHmAJTRERN8KILBSqxDSEqbeSr7W8R8Jxezzbca+nz1LiiqXnMpM8lV2jzAezw3CZ4xNUw==} + peerDependencies: + '@codemirror/state': 6.5.0 + '@codemirror/view': 6.38.6 + + pako@1.0.11: + resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} + + process-nextick-args@2.0.1: + resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==} + + readable-stream@2.3.8: + resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==} + + safe-buffer@5.1.2: + resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} + + setimmediate@1.0.5: + resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} + + string_decoder@1.1.1: + resolution: {integrity: sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==} + + style-mod@4.1.3: + resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + w3c-keyname@2.2.8: + resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==} + +snapshots: + + '@codemirror/state@6.5.0': + dependencies: + '@marijn/find-cluster-break': 1.0.2 + + '@codemirror/view@6.38.6': + dependencies: + '@codemirror/state': 6.5.0 + crelt: 1.0.6 + style-mod: 4.1.3 + w3c-keyname: 2.2.8 + + '@esbuild/aix-ppc64@0.21.5': + optional: true + + '@esbuild/android-arm64@0.21.5': + optional: true + + '@esbuild/android-arm@0.21.5': + optional: true + + '@esbuild/android-x64@0.21.5': + optional: true + + '@esbuild/darwin-arm64@0.21.5': + optional: true + + '@esbuild/darwin-x64@0.21.5': + optional: true + + '@esbuild/freebsd-arm64@0.21.5': + optional: true + + '@esbuild/freebsd-x64@0.21.5': + optional: true + + '@esbuild/linux-arm64@0.21.5': + optional: true + + '@esbuild/linux-arm@0.21.5': + optional: true + + '@esbuild/linux-ia32@0.21.5': + optional: true + + '@esbuild/linux-loong64@0.21.5': + optional: true + + '@esbuild/linux-mips64el@0.21.5': + optional: true + + '@esbuild/linux-ppc64@0.21.5': + optional: true + + '@esbuild/linux-riscv64@0.21.5': + optional: true + + '@esbuild/linux-s390x@0.21.5': + optional: true + + '@esbuild/linux-x64@0.21.5': + optional: true + + '@esbuild/netbsd-x64@0.21.5': + optional: true + + '@esbuild/openbsd-x64@0.21.5': + optional: true + + '@esbuild/sunos-x64@0.21.5': + optional: true + + '@esbuild/win32-arm64@0.21.5': + optional: true + + '@esbuild/win32-ia32@0.21.5': + optional: true + + '@esbuild/win32-x64@0.21.5': + optional: true + + '@marijn/find-cluster-break@1.0.2': {} + + '@types/codemirror@5.60.8': + dependencies: + '@types/tern': 0.23.9 + + '@types/estree@1.0.9': {} + + '@types/node@20.19.41': + dependencies: + undici-types: 6.21.0 + + '@types/tern@0.23.9': + dependencies: + '@types/estree': 1.0.9 + + core-util-is@1.0.3: {} + + crelt@1.0.6: {} + + esbuild@0.21.5: + optionalDependencies: + '@esbuild/aix-ppc64': 0.21.5 + '@esbuild/android-arm': 0.21.5 + '@esbuild/android-arm64': 0.21.5 + '@esbuild/android-x64': 0.21.5 + '@esbuild/darwin-arm64': 0.21.5 + '@esbuild/darwin-x64': 0.21.5 + '@esbuild/freebsd-arm64': 0.21.5 + '@esbuild/freebsd-x64': 0.21.5 + '@esbuild/linux-arm': 0.21.5 + '@esbuild/linux-arm64': 0.21.5 + '@esbuild/linux-ia32': 0.21.5 + '@esbuild/linux-loong64': 0.21.5 + '@esbuild/linux-mips64el': 0.21.5 + '@esbuild/linux-ppc64': 0.21.5 + '@esbuild/linux-riscv64': 0.21.5 + '@esbuild/linux-s390x': 0.21.5 + '@esbuild/linux-x64': 0.21.5 + '@esbuild/netbsd-x64': 0.21.5 + '@esbuild/openbsd-x64': 0.21.5 + '@esbuild/sunos-x64': 0.21.5 + '@esbuild/win32-arm64': 0.21.5 + '@esbuild/win32-ia32': 0.21.5 + '@esbuild/win32-x64': 0.21.5 + + immediate@3.0.6: {} + + inherits@2.0.4: {} + + isarray@1.0.0: {} + + jszip@3.10.1: + dependencies: + lie: 3.3.0 + pako: 1.0.11 + readable-stream: 2.3.8 + setimmediate: 1.0.5 + + lie@3.3.0: + dependencies: + immediate: 3.0.6 + + moment@2.29.4: {} + + obsidian@1.12.3(@codemirror/state@6.5.0)(@codemirror/view@6.38.6): + dependencies: + '@codemirror/state': 6.5.0 + '@codemirror/view': 6.38.6 + '@types/codemirror': 5.60.8 + moment: 2.29.4 + + pako@1.0.11: {} + + process-nextick-args@2.0.1: {} + + readable-stream@2.3.8: + dependencies: + core-util-is: 1.0.3 + inherits: 2.0.4 + isarray: 1.0.0 + process-nextick-args: 2.0.1 + safe-buffer: 5.1.2 + string_decoder: 1.1.1 + util-deprecate: 1.0.2 + + safe-buffer@5.1.2: {} + + setimmediate@1.0.5: {} + + string_decoder@1.1.1: + dependencies: + safe-buffer: 5.1.2 + + style-mod@4.1.3: {} + + typescript@5.9.3: {} + + undici-types@6.21.0: {} + + util-deprecate@1.0.2: {} + + w3c-keyname@2.2.8: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..afbf582 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,6 @@ +# Allow esbuild's postinstall script (downloads its native binary). pnpm 11+ +# blocks all install scripts by default as a security policy; this opts +# esbuild in. Without it, `pnpm run build` fails before invoking the build +# command because pnpm's deps-status preamble sees the blocked script. +allowBuilds: + esbuild: true diff --git a/release-notes/0.82.4.md b/release-notes/0.82.4.md new file mode 100644 index 0000000..1594dd1 --- /dev/null +++ b/release-notes/0.82.4.md @@ -0,0 +1,51 @@ +# 0.82.4 — Faster big lists, import refinements, navigation polish + +## Performance: big lists load far faster (0.81–0.82) + +The headline change. Opening a folder used to read and render *every* +note's body up front; on a large folder (or a network drive) that was the +dominant cost. + +- **Lazy body rendering.** Rows now render their body only when they + scroll near the viewport. A cheap title placeholder shows instantly + (the title comes from the filename — no file read), and the full body + fills in on demand. Already-rendered rows still paint instantly from + cache. In practice this cut per-row read time ~40× and reads-per-open + from "every note" to "roughly what's on screen." +- **Look-ahead margin** pre-renders a screenful above/below so scrolling + and arrow-navigation rarely catch a placeholder mid-fill. +- **Opt-in performance profiler.** A Diagnostics toggle records render / + read / write timing; the *Dump performance profile* command copies a + Markdown table you can inspect. Zero overhead when off. + +## Imports: safer defaults + fixes (0.79.16–0.79.21, 0.80.1, 0.80.5) + +- **Auto-import is now off by default.** Dropping files only imports + automatically once you enable it in settings. The *Import file(s) into + Stashpad…* command works either way — it writes the chosen files and + imports them directly, listing the current folder first. +- **Attachments are embedded**, not just linked (`![[file]]`), so they + preview inline; the `attachments` frontmatter is stored as proper + internal links. +- **Created/modified times are preserved** on import (falling back to the + file's own timestamps) instead of being stamped to the import time. +- **Slow-drive + mobile fixes.** Stashpad no longer re-imports notes it + just created (a network-drive race that could re-home a note to Home), + and an editing/rename loop that could endlessly re-import a note on + mobile is fixed. Rebootstrap never bumps `created`/`modified` or adds + contributors. An archive-move conflict guard prevents losing an original. +- `_archive` is excluded from the find / move / destination pickers (and + Obsidian's own search), so archived originals don't clutter results. +- File-manager labels are platform-correct ("Show in File Explorer" on + Windows, "Finder" on macOS). + +## Navigation polish (0.80.2–0.80.4, 0.82.4) + +- **Jump to top / bottom** of the list — new commands with default + `Home` / `End` hotkeys (rebindable). +- **Escaping the composer with ↑** returns to the last-focused note for + that level, not the bottommost. +- **Going up a level (←/Backspace)** pins the note you came from to the + top of the parent list, so the next up/down moves relative to it. +- The in-list **"Nest under…"** picker skips over the notes being moved + when you arrow through candidates. diff --git a/src/frontmatter-sync.ts b/src/frontmatter-sync.ts index 504fdef..21051d5 100644 --- a/src/frontmatter-sync.ts +++ b/src/frontmatter-sync.ts @@ -1,6 +1,7 @@ import { TFile, type App } from "obsidian"; import { ROOT_ID, type StashpadId, type TreeNode } from "./types"; import type { TreeIndex } from "./tree-index"; +import { perf } from "./perf"; const PARENT_LINK_FIELD = "parentLink"; const CHILDREN_FIELD = "children"; @@ -213,12 +214,12 @@ export class FrontmatterSyncQueue { const parentLink = this.computeParentLink(node); const childrenLinks = this.computeChildrenLinks(node); try { - await this.app.fileManager.processFrontMatter(node.file, (fm) => { + await perf.timeAsync("write.fmSync", () => this.app.fileManager.processFrontMatter(node.file!, (fm) => { if (parentLink) fm[PARENT_LINK_FIELD] = parentLink; else delete fm[PARENT_LINK_FIELD]; if (childrenLinks.length > 0) fm[CHILDREN_FIELD] = childrenLinks; else delete fm[CHILDREN_FIELD]; - }); + })); } catch (e) { console.warn("[Stashpad] frontmatter sync failed", node.file?.path, e); // Surface to subscribers (the view turns this into a persistent diff --git a/src/import-service.ts b/src/import-service.ts index 873c79e..96f60c2 100644 --- a/src/import-service.ts +++ b/src/import-service.ts @@ -1,6 +1,6 @@ import { Notice, TFile, TFolder } from "obsidian"; import type StashpadPlugin from "./main"; -import { ROOT_ID, RESERVED_FRONTMATTER } from "./types"; +import { ROOT_ID, RESERVED_FRONTMATTER, toAttachmentLink } from "./types"; import { newId } from "./id-service"; import { bodyToSlug, buildFilename } from "./slug-service"; import { splitFrontmatter, serializeNote, STASH_EXT } from "./stash-package"; @@ -89,11 +89,23 @@ export class ImportService { /** Path-level eligibility (no content read): the file sits directly in a * discovered Stashpad folder ROOT (not a reserved subfolder), and isn't * a .stash archive (those have their own importer) or our own .edtz. */ - /** Suppress auto-import for `path` for a few seconds — used around our - * own moves so the resulting vault event doesn't re-import the file. */ - private suppress(path: string): void { + /** Suppress auto-import for `path` for `ttl` ms — used around our own + * moves (undo restores) and for Stashpad-created notes so the resulting + * vault event doesn't re-import the file. 0.79.20: public + tunable TTL; + * createNoteUnder uses a long window because on a slow network drive the + * create event (and the frontmatter flush its id-check needs) can lag + * well past a few seconds. */ + suppress(path: string, ttl = 4000): void { this.suppressed.add(path); - window.setTimeout(() => this.suppressed.delete(path), 4000); + window.setTimeout(() => this.suppressed.delete(path), ttl); + } + + /** Create a note file, suppressing auto-import for it first — the notes + * the importer itself creates must never be re-imported (same slow-drive + * frontmatter-flush race as composer-created notes). */ + private async createNote(path: string, content: string): Promise<void> { + this.suppress(path, 60000); + await this.app.vault.create(path, content); } private isEligiblePath(file: TFile): boolean { @@ -105,15 +117,20 @@ export class ImportService { return this.plugin.discoverStashpadFolders().includes(dir); } - /** Re-validate at drain time (after the debounce, when the metadata - * cache has had a chance to parse). A markdown file that already has a - * Stashpad `id` is an existing note (or one we just created) — skip it. - * Reads frontmatter from the cache; that's settled by now. */ - private isStillImportable(file: TFile): boolean { + /** Re-validate at drain time. A markdown file that already has a Stashpad + * `id` is an existing note (or one we just created) — skip it. 0.79.18: + * read the frontmatter FROM DISK rather than the metadata cache. The + * cache lags badly on mobile, so an existing note (re)appearing via a + * rename event — e.g. Stashpad's own slug-rename after an edit — looked + * id-less and got "imported" again, archiving + cloning it in an endless + * loop. Reading the file is authoritative and breaks that. */ + private async isStillImportable(file: TFile): Promise<boolean> { if (!this.isEligiblePath(file)) return false; if (file.extension === "md") { - const fm = this.app.metadataCache.getFileCache(file)?.frontmatter as any; - if (fm && typeof fm.id === "string" && fm.id) return false; + try { + const { fm } = splitFrontmatter(await this.app.vault.read(file)); + if (fm && typeof fm.id === "string" && fm.id) return false; + } catch { /* unreadable — fall through and let the import try */ } } return true; } @@ -125,10 +142,13 @@ export class ImportService { try { const paths = [...this.pending.keys()]; this.pending.clear(); - const files = paths + const candidates = paths .map((p) => this.app.vault.getAbstractFileByPath(p)) - .filter((f): f is TFile => f instanceof TFile) - .filter((f) => this.isStillImportable(f)); + .filter((f): f is TFile => f instanceof TFile); + const files: TFile[] = []; + for (const f of candidates) { + if (await this.isStillImportable(f)) files.push(f); + } // Eligible dropped folders, with their (non-empty) file lists. const folderPaths = [...this.pendingFolders.keys()]; @@ -253,6 +273,12 @@ export class ImportService { await this.ensureFolder(archiveDir); const archivePath = await this.uniquePath(archiveDir, file.name); await this.app.fileManager.renameFile(file, archivePath); + // 0.79.21: conflict guard — if the archive move didn't actually land, + // ABORT before creating the clone. Otherwise we'd produce a clone while + // the original is lost (the pre-0.79.10 .archive dot-folder failure). + if (!(this.app.vault.getAbstractFileByPath(archivePath) instanceof TFile)) { + throw new Error(`archive move failed for ${file.path} — import aborted to avoid data loss`); + } // Build the clone's frontmatter: keep the user's non-reserved keys, // then stamp Stashpad's structural fields. @@ -262,12 +288,16 @@ export class ImportService { } cloneFm.id = newId(); cloneFm.parent = ROOT_ID; - cloneFm.created = new Date().toISOString(); + // 0.79.21: preserve the original timestamps — don't stamp "now" over a + // note that already has a created/modified (e.g. re-imported export). + const t = this.preservedTimes(fm, file); + cloneFm.created = t.created; + if (t.modified) cloneFm.modified = t.modified; cloneFm.attachments = Array.isArray(fm.attachments) ? fm.attachments : []; const slug = bodyToSlug(body) || file.basename; const notePath = await this.uniquePath(folder, buildFilename(slug, cloneFm.id)); - await this.app.vault.create(notePath, serializeNote(cloneFm, body)); + await this.createNote(notePath, serializeNote(cloneFm, body)); return { kind: "md", folder, archivePath, notePath, originalName: file.name }; } @@ -287,16 +317,30 @@ export class ImportService { id, parent: ROOT_ID, created: new Date().toISOString(), - attachments: [attachmentPath], + // 0.79.18: attachments stored as internal links (not plain text). + attachments: [toAttachmentLink(attachmentPath)], }; - // Body: a wikilink to the attachment (link, not embed). - const body = `${title}\n\n[[${attachmentPath}]]\n`; + // 0.79.18: embed the attachment (! prefix) so it previews inline. + const body = `${title}\n\n![[${attachmentPath}]]\n`; const slug = bodyToSlug(title) || title; const notePath = await this.uniquePath(folder, buildFilename(slug, id)); - await this.app.vault.create(notePath, serializeNote(fm, body)); + await this.createNote(notePath, serializeNote(fm, body)); return { kind: "file", folder, attachmentPath, notePath, originalName: file.name }; } + /** Choose the created/modified to stamp on an imported note: prefer the + * source frontmatter's own values; else fall back to the file's + * filesystem ctime/mtime (usually survives a rename, far better than + * "now"); else, only as a last resort, now. */ + private preservedTimes(fm: Record<string, any>, file: TFile): { created: string; modified: string | null } { + const valid = (v: unknown): v is string => typeof v === "string" && v.trim().length > 0 && !Number.isNaN(Date.parse(v)); + const created = valid(fm.created) ? fm.created + : (file.stat?.ctime ? new Date(file.stat.ctime).toISOString() : new Date().toISOString()); + const modified = valid(fm.modified) ? fm.modified + : (file.stat?.mtime ? new Date(file.stat.mtime).toISOString() : null); + return { created, modified }; + } + /** All files anywhere under `folderPath` (recursive). */ private filesUnder(folderPath: string): TFile[] { const prefix = folderPath.replace(/\/+$/, "") + "/"; @@ -340,7 +384,7 @@ export class ImportService { }; const slug = bodyToSlug(title) || title; const notePath = await this.uniquePath(root, buildFilename(slug, id)); - await this.app.vault.create(notePath, serializeNote(fm, `${title}\n`)); + await this.createNote(notePath, serializeNote(fm, `${title}\n`)); notePaths.push(notePath); return id; } @@ -363,22 +407,25 @@ export class ImportService { } cloneFm.id = newId(); cloneFm.parent = parentId; - cloneFm.created = new Date().toISOString(); + const t = this.preservedTimes(fm, child); + cloneFm.created = t.created; + if (t.modified) cloneFm.modified = t.modified; cloneFm.attachments = Array.isArray(fm.attachments) ? fm.attachments : []; const slug = bodyToSlug(body) || child.basename; const notePath = await this.uniquePath(root, buildFilename(slug, cloneFm.id)); - await this.app.vault.create(notePath, serializeNote(cloneFm, body)); + await this.createNote(notePath, serializeNote(cloneFm, body)); notePaths.push(notePath); } else { // Link the archived file (no _attachments copy). const id = newId(); const fm: Record<string, any> = { - id, parent: parentId, created: new Date().toISOString(), attachments: [child.path], + id, parent: parentId, created: new Date().toISOString(), + attachments: [toAttachmentLink(child.path)], }; - const body = `${child.basename}\n\n[[${child.path}]]\n`; + const body = `${child.basename}\n\n![[${child.path}]]\n`; const slug = bodyToSlug(child.basename) || child.basename; const notePath = await this.uniquePath(root, buildFilename(slug, id)); - await this.app.vault.create(notePath, serializeNote(fm, body)); + await this.createNote(notePath, serializeNote(fm, body)); notePaths.push(notePath); } } @@ -482,33 +529,55 @@ export class ImportService { new Notice(`Undid import of ${records.length} file(s).`); } - /** 0.79.4: open the OS file picker and copy the chosen files into - * `folder`'s root; the auto-import watcher then turns them into notes. - * Uses an <input type=file> so it works on desktop AND mobile (native - * file/photo picker) without Electron-version juggling. */ + /** 0.79.4 / 0.80.1: open the OS file picker, copy the chosen files into + * `folder`, then import them DIRECTLY (not via the watcher) so this works + * regardless of the auto-import toggle. Uses an <input type=file> so it + * works on desktop AND mobile (native file/photo picker). */ pickFilesInto(folder: string): void { const input = document.createElement("input"); input.type = "file"; input.multiple = true; input.style.display = "none"; input.onchange = async () => { - const files = Array.from(input.files ?? []); + const picked = Array.from(input.files ?? []); input.remove(); - if (files.length === 0) return; - let written = 0; - for (const file of files) { + if (picked.length === 0) return; + // 1) write each picked file into the folder root (suppressed so the + // watcher, if armed, doesn't ALSO process it — we import below). + const written: TFile[] = []; + for (const file of picked) { try { const buf = await file.arrayBuffer(); const dest = await this.uniquePath(folder, file.name); + this.suppress(dest, 60000); await this.app.vault.createBinary(dest, buf); - written++; + const tf = this.app.vault.getAbstractFileByPath(dest); + if (tf instanceof TFile) written.push(tf); } catch (e) { - console.warn("[Stashpad] file-picker import failed", file.name, e); + console.warn("[Stashpad] file-picker write failed", file.name, e); } } - if (written > 0) { - new Notice(`Added ${written} file(s) to "${folder.split("/").pop()}" — importing…`); + if (written.length === 0) return; + // 2) import the written files directly. + await this.plugin.importLog.load(); + const records: ImportRecord[] = []; + for (const f of written) { + try { + const size = f.stat?.size ?? null; + const rec = f.extension === "md" ? await this.importMarkdown(f) : await this.importOtherFile(f); + if (rec) { + records.push(rec); + this.plugin.importLog.append({ + ts: new Date().toISOString(), folder: rec.folder, kind: rec.kind, + originalName: f.name, size, sourcePath: f.path, + notePaths: rec.kind === "folder" ? rec.notePaths : [rec.notePath], + }); + } + } catch (e) { + console.warn("[Stashpad] file-picker import failed", f.path, e); + } } + if (records.length > 0) this.announce(records, []); }; document.body.appendChild(input); input.click(); @@ -524,9 +593,12 @@ export class ImportService { * mode to surface. */ async importLooseFilesIn(folder: string): Promise<number> { const root = folder.replace(/\/+$/, ""); - const files = this.app.vault.getFiles() - .filter((f) => (f.parent?.path?.replace(/\/+$/, "") ?? "") === root) - .filter((f) => this.isStillImportable(f)); + const candidates = this.app.vault.getFiles() + .filter((f) => (f.parent?.path?.replace(/\/+$/, "") ?? "") === root); + const files: TFile[] = []; + for (const f of candidates) { + if (await this.isStillImportable(f)) files.push(f); + } if (files.length === 0) return 0; await this.plugin.importLog.load(); let n = 0; diff --git a/src/main.ts b/src/main.ts index b40303e..032de40 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,5 @@ import { Notice, Platform, Plugin, SuggestModal, TFile, TFolder, WorkspaceLeaf, setIcon } from "obsidian"; -import { STASHPAD_DETAIL_VIEW_TYPE, STASHPAD_PANELS_VIEW_TYPE, STASHPAD_VIEW_TYPE, parseAuthorRef, type PinnedNoteRef, type StashpadId } from "./types"; +import { STASHPAD_DETAIL_VIEW_TYPE, STASHPAD_PANELS_VIEW_TYPE, STASHPAD_VIEW_TYPE, parseAuthorRef, toAttachmentLink, isInReservedSubfolder, type PinnedNoteRef, type StashpadId } from "./types"; import { StashpadDetailView, openStashpadDetailView } from "./detail-view"; import { StashpadView, properCaseFolderPath } from "./view"; import { StashpadPanelsView, openStashpadPanelsView, PANEL_REGISTRY, type PanelId } from "./panels-view"; @@ -18,6 +18,7 @@ import { NotificationService, buildFileActions } from "./notifications"; import { AuthorRegistry } from "./author-registry"; import { ImportService } from "./import-service"; import { ImportLog } from "./import-log"; +import { perf } from "./perf"; export default class StashpadPlugin extends Plugin { settings: StashpadSettings = { ...DEFAULT_SETTINGS }; @@ -26,6 +27,11 @@ export default class StashpadPlugin extends Plugin { * Used by sidebar panel actions (Search, Home) so they target the * user's actual current tab rather than getLeavesOfType()[0]. */ lastActiveStashpadLeaf: WorkspaceLeaf | null = null; + /** 0.79.19: true while rebootstrap is running. Suppresses the + * contribution stamp so rebootstrap's own frontmatter writes — and the + * wikilink rewrites Obsidian does when slug-renames move files — never + * bump `modified` (or add the local user as a contributor). */ + rebootstrapInProgress = false; /** 0.73.10: keep a handle on the settings tab so command-palette * entries can pre-select a specific tab when opening Settings. */ settingTab: StashpadSettingTab | null = null; @@ -470,6 +476,7 @@ export default class StashpadPlugin extends Plugin { // loadSettings so the data.json move is in place when we read. await this.migrateLegacyPaths(); await this.loadSettings(); + perf.enabled = !!this.settings.enablePerfProfiling; this.settingTab = new StashpadSettingTab(this.app, this); this.addSettingTab(this.settingTab); @@ -825,6 +832,28 @@ export default class StashpadPlugin extends Plugin { this.addCommand({ id: "stashpad-toggle-complete", name: "Toggle complete (strikethrough)", callback: () => call("cmdToggleComplete") }); this.addCommand({ id: "stashpad-toggle-task", name: "Toggle task (todo)", callback: () => call("cmdToggleTask") }); this.addCommand({ id: "stashpad-set-due", name: "Set due date…", callback: () => call("cmdSetDue") }); + // 0.81.1: performance profiling — dump / reset the timing report. + this.addCommand({ + id: "stashpad-dump-perf", + name: "Dump performance profile (copy to clipboard)", + callback: async () => { + if (!this.settings.enablePerfProfiling) { + new Notice("Enable “Performance profiling” in Stashpad settings first, then use the app and run this again."); + return; + } + const report = perf.report(); + console.log(report); + try { await navigator.clipboard.writeText(report); } catch {} + new Notice("Performance profile copied to clipboard (also in the console)."); + }, + }); + this.addCommand({ + id: "stashpad-reset-perf", + name: "Reset performance profile", + callback: () => { perf.reset(); new Notice("Performance profile reset."); }, + }); + this.addCommand({ id: "stashpad-jump-to-top", name: "Jump to top of list", callback: () => call("jumpToTop") }); + this.addCommand({ id: "stashpad-jump-to-bottom", name: "Jump to bottom of list", callback: () => call("jumpToBottom") }); this.addCommand({ id: "stashpad-assign", name: "Assign task to…", callback: () => call("cmdAssign") }); // 0.79.3: view what's been auto-imported. this.addCommand({ @@ -1001,10 +1030,11 @@ export default class StashpadPlugin extends Plugin { callback: async () => { new Notice("Stashpad: rebootstrapping…"); try { - const { touched, fmChecked, fmWritten, slugsRenamed, authors, imported } = await this.rebootstrapAllFolders(); + const { touched, fmChecked, fmWritten, slugsRenamed, authors, imported, attachmentsLinked } = await this.rebootstrapAllFolders(); const parts: string[] = []; parts.push(`rebootstrapped ${touched.length} folder${touched.length === 1 ? "" : "s"}`); if (imported > 0) parts.push(`imported ${imported} loose file${imported === 1 ? "" : "s"}`); + if (attachmentsLinked > 0) parts.push(`linked attachments on ${attachmentsLinked} note${attachmentsLinked === 1 ? "" : "s"}`); if (fmWritten > 0) parts.push(`updated ${fmWritten} note${fmWritten === 1 ? "" : "s"}' metadata`); if (slugsRenamed > 0) parts.push(`renamed ${slugsRenamed} note${slugsRenamed === 1 ? "" : "s"}`); if (authors > 0) parts.push(`${authors} author${authors === 1 ? "" : "s"} in registry`); @@ -1697,7 +1727,19 @@ export default class StashpadPlugin extends Plugin { * ensure it has the import/export subfolders, and run the redundant-frontmatter * backfill (parentLink + children) so older notes pick up the recovery fields. * Used by the "Rebootstrap" button in settings to retrofit older folders. */ - async rebootstrapAllFolders(): Promise<{ touched: string[]; fmChecked: number; fmWritten: number; slugsRenamed: number; authors: number; imported: number }> { + async rebootstrapAllFolders(): Promise<{ touched: string[]; fmChecked: number; fmWritten: number; slugsRenamed: number; authors: number; imported: number; attachmentsLinked: number }> { + // 0.79.19: suppress contribution stamping for the duration (+ a short + // tail to catch async link-rewrite modify events) so rebootstrap never + // bumps `modified`/`created` or adds contributors. + this.rebootstrapInProgress = true; + try { + return await this.rebootstrapAllFoldersInner(); + } finally { + window.setTimeout(() => { this.rebootstrapInProgress = false; }, 2500); + } + } + + private async rebootstrapAllFoldersInner(): Promise<{ touched: string[]; fmChecked: number; fmWritten: number; slugsRenamed: number; authors: number; imported: number; attachmentsLinked: number }> { const ROOT_ID = "__root__"; const seen = new Set<string>(); for (const f of this.app.vault.getMarkdownFiles()) { @@ -1762,7 +1804,11 @@ export default class StashpadPlugin extends Plugin { let authors = 0; try { authors = (await this.rebuildAuthorRegistry()).total; } catch (e) { console.warn("Stashpad: rebootstrap author-registry rebuild failed", e); } - return { touched, fmChecked, fmWritten, slugsRenamed, authors, imported }; + // 0.79.18: convert any plain-text attachment frontmatter to links. + let attachmentsLinked = 0; + try { attachmentsLinked = await this.convertAttachmentsToLinks(); } + catch (e) { console.warn("Stashpad: attachment-link conversion failed", e); } + return { touched, fmChecked, fmWritten, slugsRenamed, authors, imported, attachmentsLinked }; } /** Walk every Stashpad note in `folder`. For each one whose filename @@ -2440,6 +2486,38 @@ export default class StashpadPlugin extends Plugin { return { created, folders: folders.length }; } + /** 0.79.18: convert plain-text `attachments` frontmatter entries to + * internal links (`[[path]]`) across all notes. Idempotent — only + * rewrites notes that have at least one non-link entry, and + * `toAttachmentLink` never re-brackets an existing link, so re-running + * can't double-wrap or loop. Returns the count of notes changed. */ + async convertAttachmentsToLinks(): Promise<number> { + let converted = 0; + const isLink = (s: string) => /^\[\[.*\]\]$/.test(s.trim()); + for (const folder of this.discoverStashpadFolders()) { + const dir = folder.replace(/\/+$/, ""); + for (const f of this.app.vault.getMarkdownFiles()) { + const fdir = f.parent?.path?.replace(/\/+$/, "") ?? ""; + if (fdir !== dir && !fdir.startsWith(dir + "/")) continue; + if (isInReservedSubfolder(f.path)) continue; // skip _archive/_attachments/… + const fm = this.app.metadataCache.getFileCache(f)?.frontmatter as any; + if (!fm || typeof fm.id !== "string" || !fm.id) continue; + if (!Array.isArray(fm.attachments)) continue; + const needs = fm.attachments.some((a: any) => typeof a === "string" && a.trim() && !isLink(a)); + if (!needs) continue; + try { + await this.app.fileManager.processFrontMatter(f, (m: any) => { + if (Array.isArray(m.attachments)) { + m.attachments = m.attachments.map((a: any) => (typeof a === "string" && a.trim()) ? toAttachmentLink(a) : a); + } + }); + converted++; + } catch (e) { console.warn("[Stashpad] attachment-link conversion failed", f.path, e); } + } + } + return converted; + } + /** 0.79.12: add each discovered Stashpad folder's `_archive` to * Obsidian's "Excluded files" list (`userIgnoreFilters`) so native * search, quick switcher, graph, and link suggestions skip the @@ -2720,6 +2798,7 @@ export default class StashpadPlugin extends Plugin { async saveSettings(): Promise<void> { await this.queueWrite(); setSettings(this.settings); + perf.enabled = !!this.settings.enablePerfProfiling; // 0.77.1: keep the registry's record of the local user current. The // registry is a recovery cache — recording here means a name/role/ // department change is remembered (with rename history) even if the @@ -3030,10 +3109,10 @@ function normalizeDrafts(raw: any): Record<string, string> { return out; } -/** 0.79.4: destination chooser for the Import command. The pinned top - * entry opens the OS file picker into the default folder; the rest target - * a specific Stashpad folder. */ -interface ImportTarget { label: string; folder: string; pinned?: boolean } +/** 0.79.4 / 0.80.1: destination chooser for the Import command. Lists the + * Stashpad folders with the current/active one first; picking one opens + * the OS file picker into that folder and imports the chosen files. */ +interface ImportTarget { label: string; folder: string; current?: boolean } class ImportTargetModal extends SuggestModal<ImportTarget> { constructor( app: import("obsidian").App, @@ -3042,20 +3121,22 @@ class ImportTargetModal extends SuggestModal<ImportTarget> { private onPick: (folder: string) => void, ) { super(app); - this.setPlaceholder("Open the file picker, or choose a destination folder…"); + this.setPlaceholder("Choose a Stashpad folder to import into…"); } getSuggestions(query: string): ImportTarget[] { const q = query.toLowerCase(); - const defName = this.def.split("/").pop() || this.def; - const pinned: ImportTarget = { label: `📂 Open file picker → ${defName}`, folder: this.def, pinned: true }; - const rest = this.folders + // Current folder first, then the rest (deduped), filtered by query. + const ordered = [this.def, ...this.folders.filter((f) => f !== this.def)]; + return ordered .filter((f) => f.toLowerCase().includes(q)) - .map((f) => ({ label: `Import into ${f}`, folder: f })); - return [pinned, ...rest]; + .map((f) => ({ label: f, folder: f, current: f === this.def })); } renderSuggestion(item: ImportTarget, el: HTMLElement): void { el.createDiv({ text: item.label }); - if (item.pinned) el.addClass("is-pinned-import-target"); + if (item.current) { + el.createDiv({ cls: "stashpad-suggest-note", text: "current" }); + el.addClass("is-pinned-import-target"); + } } onChooseSuggestion(item: ImportTarget): void { this.onPick(item.folder); } } diff --git a/src/notifications.ts b/src/notifications.ts index c2a6b33..18bd3fb 100644 --- a/src/notifications.ts +++ b/src/notifications.ts @@ -1,4 +1,4 @@ -import { Notice, TFile, type App } from "obsidian"; +import { Notice, Platform, TFile, type App } from "obsidian"; import type { StashpadId } from "./types"; /** Visual severity. Drives the toast's color + the history panel's @@ -353,8 +353,13 @@ export function buildFileActions( }, }]; if (!isMobile) { + // Platform-correct OS file-manager name (Windows: "File Explorer", + // capitalised; macOS: "Finder"; otherwise generic). + const osManager = Platform.isMacOS ? "Finder" + : Platform.isWin ? "File Explorer" + : "file manager"; actions.push({ - label: "Show in Finder", + label: `Show in ${osManager}`, keepOpen: true, onClick: () => { try { diff --git a/src/perf.ts b/src/perf.ts new file mode 100644 index 0000000..3d4bd68 --- /dev/null +++ b/src/perf.ts @@ -0,0 +1,60 @@ +/** 0.81.1: tiny opt-in profiler. Accumulates per-label timing buckets so we + * can see where Stashpad spends its time on a slow (e.g. network-drive) + * vault — split across the three suspects: rendering markdown, reading + * bodies, and writing files. Zero overhead when disabled (the time/record + * calls early-return). Toggle via the `enablePerfProfiling` setting; dump + * a report with the "Dump performance profile" command. */ +interface Bucket { count: number; total: number; max: number; } + +class Profiler { + enabled = false; + private buckets = new Map<string, Bucket>(); + + record(label: string, ms: number): void { + if (!this.enabled) return; + let b = this.buckets.get(label); + if (!b) { b = { count: 0, total: 0, max: 0 }; this.buckets.set(label, b); } + b.count += 1; + b.total += ms; + if (ms > b.max) b.max = ms; + } + + /** Time a synchronous block. Returns its result. */ + time<T>(label: string, fn: () => T): T { + if (!this.enabled) return fn(); + const t0 = performance.now(); + try { return fn(); } finally { this.record(label, performance.now() - t0); } + } + + /** Time an async block. */ + async timeAsync<T>(label: string, fn: () => Promise<T>): Promise<T> { + if (!this.enabled) return fn(); + const t0 = performance.now(); + try { return await fn(); } finally { this.record(label, performance.now() - t0); } + } + + reset(): void { this.buckets.clear(); } + + hasData(): boolean { return this.buckets.size > 0; } + + /** A sorted Markdown table (by total time desc) — renders as a table in + * a note and stays readable as raw text. */ + report(): string { + const rows = [...this.buckets.entries()] + .map(([label, b]) => ({ label, ...b, avg: b.total / b.count })) + .sort((a, b) => b.total - a.total); + if (rows.length === 0) return "Stashpad perf: no samples (enable profiling, then use the app)."; + const lines = [ + "**Stashpad performance profile**", + "", + "| label | count | total (ms) | avg (ms) | max (ms) |", + "| --- | ---: | ---: | ---: | ---: |", + ]; + for (const r of rows) { + lines.push(`| \`${r.label}\` | ${r.count} | ${r.total.toFixed(0)} | ${r.avg.toFixed(1)} | ${r.max.toFixed(0)} |`); + } + return lines.join("\n"); + } +} + +export const perf = new Profiler(); diff --git a/src/settings.ts b/src/settings.ts index 943762d..24114c5 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -1,4 +1,9 @@ -import { App, Notice, PluginSettingTab, Setting, TFile } from "obsidian"; +import { App, Notice, Platform, PluginSettingTab, Setting, TFile } from "obsidian"; + +/** Platform-correct OS file-manager name for button/notice labels. */ +function osFileManagerName(): string { + return Platform.isMacOS ? "Finder" : Platform.isWin ? "File Explorer" : "file manager"; +} import { buildJdIndexPreview, buildJdIndexNotes, scanForJdNotes, JdBuildConfirmModal, buildJdPreviewNotice } from "./index-builder"; import { FolderSuggest } from "./folder-suggest"; import type StashpadPlugin from "./main"; @@ -53,7 +58,8 @@ export type CommandId = | "cloneStashpadTab" | "selectAll" | "copyCodeBlock" | "swapWithParent" | "togglePin" - | "toggleTask" | "setDue"; + | "toggleTask" | "setDue" + | "jumpToTop" | "jumpToBottom"; /** Per-command bindings: up to two chord strings ("S" or "Mod+Enter"). * When BOTH are set, `preferRight` decides which actually fires. */ @@ -114,6 +120,8 @@ export const COMMAND_META: CommandMeta[] = [ { id: "togglePin", label: "Pin / unpin selected note", desc: "Default: P — toggle the sidebar pin state of the cursor row (or focused note).", defaultPrimary: "P" }, { id: "toggleTask", label: "Toggle task (todo)", desc: "Default: H — mark the selection (or cursor row) as a task / todo, or clear it. Tasks appear in the Tasks panel.", defaultPrimary: "H" }, { id: "setDue", label: "Set due date…", desc: "Default: D — open a date+time picker to set (or clear) the due date on the selection. Setting a due date also marks the note as a task.", defaultPrimary: "D" }, + { id: "jumpToTop", label: "Jump to top of list", desc: "Default: Home — move the cursor to the first note in the current list.", defaultPrimary: "Home" }, + { id: "jumpToBottom", label: "Jump to bottom of list", desc: "Default: End — move the cursor to the last note in the current list.", defaultPrimary: "End" }, ]; export function buildDefaultBindings(): CommandBindingMap { @@ -136,6 +144,10 @@ export interface StashpadSettings { * honor Obsidian's "Excluded files" (userIgnoreFilters), so exclusions * are managed in one place. `.edtz` is always excluded regardless. */ inheritObsidianExclusions: boolean; + /** 0.81.1: opt-in performance profiling — accumulates render/read/write + * timing so the "Dump performance profile" command reports where the + * time goes on a slow vault. Off by default. */ + enablePerfProfiling: boolean; useTemplatesFormat: boolean; prefixTimestampsOnCopy: boolean; splitOnLines: boolean; @@ -344,8 +356,9 @@ export const DEFAULT_SETTINGS: StashpadSettings = { folder: "Stashpad", importDropFolder: "", exportFolder: "_exports", - autoImport: true, + autoImport: false, inheritObsidianExclusions: true, + enablePerfProfiling: false, useTemplatesFormat: false, prefixTimestampsOnCopy: true, splitOnLines: false, @@ -594,6 +607,13 @@ export class StashpadSettingTab extends PluginSettingTab { /** Diagnostics tab: log + notification controls. Lifted verbatim * from the pre-0.73.1 Log section. Inventory items A1–A4. */ private renderDiagnosticsTab(parent: HTMLElement): void { + new Setting(parent) + .setName("Performance profiling") + .setDesc("Record timing for list rendering, body reads, and file writes. Turn on, use Stashpad normally (especially the slow operations), then run “Dump performance profile” from the command palette and share the result. Off = zero overhead.") + .addToggle((t) => t.setValue(this.plugin.settings.enablePerfProfiling).onChange(async (v) => { + this.plugin.settings.enablePerfProfiling = v; await this.plugin.saveSettings(); + })); + new Setting(parent) .setName("Open log file") .setDesc("Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.") @@ -743,10 +763,11 @@ export class StashpadSettingTab extends PluginSettingTab { b.setButtonText("Rebootstrap now").onClick(async () => { b.setDisabled(true).setButtonText("Working…"); try { - const { touched, fmChecked, fmWritten, slugsRenamed, authors, imported } = await this.plugin.rebootstrapAllFolders(); + const { touched, fmChecked, fmWritten, slugsRenamed, authors, imported, attachmentsLinked } = await this.plugin.rebootstrapAllFolders(); const parts: string[] = []; parts.push(`rebootstrapped ${touched.length} folder${touched.length === 1 ? "" : "s"}`); if (imported > 0) parts.push(`imported ${imported} loose file${imported === 1 ? "" : "s"}`); + if (attachmentsLinked > 0) parts.push(`linked attachments on ${attachmentsLinked} note${attachmentsLinked === 1 ? "" : "s"}`); if (fmWritten > 0) parts.push(`updated frontmatter on ${fmWritten} of ${fmChecked} notes`); else if (fmChecked > 0) parts.push(`frontmatter already in sync (${fmChecked} notes checked)`); if (slugsRenamed > 0) parts.push(`renamed ${slugsRenamed} note${slugsRenamed === 1 ? "" : "s"} to match body`); @@ -1186,7 +1207,7 @@ export class StashpadSettingTab extends PluginSettingTab { }); }) .addButton((b) => { - b.setButtonText("Reveal in Finder"); + b.setButtonText(`Reveal in ${osFileManagerName()}`); b.setTooltip("Open the designated Stashpad folder in your OS file browser."); b.onClick(async () => { const dest = (this.plugin.settings.jdIndexStashpadFolder ?? "").trim().replace(/^\/+|\/+$/g, ""); diff --git a/src/stash-package.ts b/src/stash-package.ts index 16bdede..80f2849 100644 --- a/src/stash-package.ts +++ b/src/stash-package.ts @@ -1,7 +1,7 @@ import JSZip from "jszip"; import { App, TFile, parseYaml, stringifyYaml } from "obsidian"; import { newId } from "./id-service"; -import { ROOT_ID, type StashpadId } from "./types"; +import { ROOT_ID, attachmentLinkPath, toAttachmentLink, type StashpadId } from "./types"; export const STASH_EXT = "stash"; export const SCHEMA_VERSION = 1; @@ -198,8 +198,10 @@ export async function importStashZip( import_date: importDate, }; if (Array.isArray(newFm.attachments)) { + // 0.79.18: attachments may be wikilinks now — normalize to a path, + // re-root into the export's attachments folder, re-wrap as a link. newFm.attachments = (newFm.attachments as string[]).map((a) => - `${attachmentsFolder}/${baseFileName(a)}`, + toAttachmentLink(`${attachmentsFolder}/${baseFileName(attachmentLinkPath(a))}`), ); } diff --git a/src/tree-index.ts b/src/tree-index.ts index 32da611..bf4c75d 100644 --- a/src/tree-index.ts +++ b/src/tree-index.ts @@ -1,5 +1,5 @@ import { TFile, TFolder, type App, type CachedMetadata } from "obsidian"; -import { ROOT_ID, RESERVED_SUBFOLDER_NAMES, type StashpadId, type TreeNode } from "./types"; +import { ROOT_ID, RESERVED_SUBFOLDER_NAMES, isInReservedSubfolder, type StashpadId, type TreeNode } from "./types"; /** Walk a Stashpad folder's TFolder subtree and return every .md file under * it. Iterative DFS rather than recursive to avoid a deep-recursion blow-up @@ -317,6 +317,15 @@ export class TreeIndex { /** Apply a single file create/modify event. Returns true if the tree * changed (caller should schedule onUpdate). */ private applyChange(file: TFile): boolean { + // 0.80.5: never index files in reserved subfolders (_archive, + // _attachments, …). The full rebuild already skips them, but this + // incremental hook didn't — so an archived note (which keeps its + // Stashpad id) got re-inserted when its metadata cache fired, and then + // showed up in every tree-backed picker (find / move / destination). + // Clean up any node that slipped in before this guard existed. + if (isInReservedSubfolder(file.path)) { + return this.byPath.has(file.path) ? this.applyDelete(file.path) : false; + } const fm = this.app.metadataCache.getFileCache(file)?.frontmatter; const id = fm?.id as string | undefined; const oldId = this.byPath.get(file.path); @@ -447,6 +456,14 @@ export class TreeIndex { if (!wasIn && !isIn) return false; if (wasIn && !isIn) return this.applyDelete(oldPath); if (!wasIn && isIn) return this.applyChange(file); + // 0.80.5: a within-folder move INTO a reserved subfolder (e.g. import + // archiving root/Note.md → _archive/Note.md) must drop the node, not + // just remap its path — otherwise the archived note lingers in the + // tree. (Moving back OUT falls through to applyChange below, since the + // archived path was never indexed, and re-adds it.) + if (isInReservedSubfolder(file.path)) { + return this.byPath.has(oldPath) ? this.applyDelete(oldPath) : false; + } // Rename within folder. const id = this.byPath.get(oldPath); if (!id) { diff --git a/src/types.ts b/src/types.ts index ac24f78..85a8592 100644 --- a/src/types.ts +++ b/src/types.ts @@ -117,6 +117,25 @@ export function isArchivedPath(path: string): boolean { return path.split("/").some((seg) => seg === "_archive" || seg === ".archive"); } +/** 0.79.18: an `attachments` frontmatter entry as a wikilink. Idempotent — + * returns an existing `[[...]]` unchanged (never double-brackets), so it's + * safe to run repeatedly (e.g. in rebootstrap) without looping. */ +export function toAttachmentLink(entry: string): string { + const s = (entry ?? "").trim(); + if (!s) return s; + if (/^\[\[.*\]\]$/.test(s)) return s; + return `[[${s}]]`; +} +/** The resolvable vault path/linktext inside an attachment entry — strips + * `[[ ]]`, a trailing `|alias`, and `#heading`/`^block` refs. Accepts both + * the new wikilink form and the legacy plain-path form. */ +export function attachmentLinkPath(entry: string): string { + let s = (entry ?? "").trim(); + const m = s.match(/^\[\[(.*)\]\]$/); + if (m) s = m[1]; + return s.split("|")[0].split("#")[0].split("^")[0].trim(); +} + /** File extensions Stashpad never surfaces in link/search (plugin-internal * formats users don't link to). `.edtz` = Encrypted Templater. */ export const IGNORED_FILE_EXTENSIONS: ReadonlySet<string> = new Set(["edtz"]); @@ -202,7 +221,10 @@ export type ScrollPolicy = | { kind: "pin-bottom"; until: "settle" | "next-user-input" } | { kind: "restore"; scrollTop: number } | { kind: "follow-cursor" } - | { kind: "scroll-to-id"; id: StashpadId; align: "center" | "nearest" | "top" }; + // `align` is passed straight to scrollIntoView({ block }), so it must be + // one of its valid values — "start" means top. ("top" was a long-standing + // typo that silently no-op'd; esbuild doesn't typecheck so it slipped by.) + | { kind: "scroll-to-id"; id: StashpadId; align: "start" | "center" | "end" | "nearest" }; export interface ViewConfigState { focusId: StashpadId; diff --git a/src/view.ts b/src/view.ts index 435b914..6865589 100644 --- a/src/view.ts +++ b/src/view.ts @@ -4,10 +4,11 @@ import { moment, setIcon, } from "obsidian"; import { - ROOT_ID, STASHPAD_VIEW_TYPE, RESERVED_FRONTMATTER, fmHasTag, fmAddTag, fmRemoveTag, parseAssignees, + ROOT_ID, STASHPAD_VIEW_TYPE, RESERVED_FRONTMATTER, fmHasTag, fmAddTag, fmRemoveTag, parseAssignees, attachmentLinkPath, type StashpadId, type TimeFilter, type TreeNode, type ViewConfigState, type ViewMode, type ScrollPolicy, } from "./types"; import { TreeIndex } from "./tree-index"; +import { perf } from "./perf"; import { formatDateTime } from "./format"; import { OrderStore } from "./order-store"; import { SortStore, type SortMode, SORT_MODE_LABELS, SORT_MODES_ORDER } from "./sort-store"; @@ -653,6 +654,8 @@ export class StashpadView extends ItemView { this.listResizeObserver = null; this.stickyRowObserver?.disconnect(); this.stickyRowObserver = null; + this.bodyObserver?.disconnect(); + this.bodyObserver = null; this.composerNarrowObserver?.disconnect(); this.composerNarrowObserver = null; this.focusedMiniObserver?.disconnect(); @@ -1299,12 +1302,13 @@ export class StashpadView extends ItemView { if (!fm || !Array.isArray(fm.attachments)) continue; for (const a of fm.attachments) { if (typeof a !== "string") continue; - // attachments may be stored as bare path or with a leading slash; - // resolve via Obsidian's linkpath resolver when possible, fall - // back to literal path. - const resolved = this.app.metadataCache.getFirstLinkpathDest(a, child.path); + // attachments may be a wikilink ([[path]]), a bare path, or have a + // leading slash; normalize to the linktext then resolve via + // Obsidian, falling back to the literal path. + const linktext = attachmentLinkPath(a); + const resolved = this.app.metadataCache.getFirstLinkpathDest(linktext, child.path); if (resolved) out.add(resolved.path); - else out.add(a); + else out.add(linktext); } } } @@ -1371,6 +1375,12 @@ export class StashpadView extends ItemView { // per-row overflow memo (see getOrComputeRender). One layout read // instead of one per row. this.lastListWidth = list.clientWidth || this.lastListWidth; + // 0.82.1: (re)arm the lazy-body observer for this paint. Cold rows + // (no cached render) get a cheap title placeholder and only do the + // expensive cachedRead + MarkdownRenderer once they scroll near the + // viewport — the profile showed body reads at full-list scale were + // ~97% of the time. + this.armBodyObserver(); if (focused.file && Platform.isMobile) { this.renderFocusedHeaderMini(list, focused); this.renderFocusedHeader(list, focused); @@ -1714,7 +1724,9 @@ export class StashpadView extends ItemView { if (fallbackScrollTop > 0) list.scrollTop = fallbackScrollTop; } + private _renderT0: number | null = null; private render(policy?: ScrollPolicy): void { + if (perf.enabled) this._renderT0 = performance.now(); // 0.56.3: unannotated render() calls default to "preserve". That kills // the bouncing class of regressions where metadataCache-driven // re-renders (color change, frontmatter mod, fmSync rewrites) would @@ -1914,6 +1926,7 @@ export class StashpadView extends ItemView { // reordered. Content-changed lets the panel refresh in place // while staying pinned to its displayed note. Genuine selection // changes fire from selectCursor / handleRowClick / navigateTo. + if (this._renderT0 != null) { perf.record("render.total", performance.now() - this._renderT0); this._renderT0 = null; } this.plugin.notifyStashpadContentChanged(); // 0.79.9: when this render auto-selected a newly-created note, that's // a real selection change — notify so the detail panel unlocks and @@ -3992,6 +4005,11 @@ export class StashpadView extends ItemView { * per-row reflow thrash was the dominant cost of the "couple * seconds to render" lag. */ private renderCache = new Map<string, { mtime: number; text: string; attachments: string[]; html: string; ovW?: number; ovV?: boolean }>(); + /** 0.82.1: lazy-body machinery. `bodyObserver` watches cold rows; when + * one nears the viewport its deferred render closure (stored in + * `lazyBodies`, keyed by the body container) runs once. */ + private bodyObserver: IntersectionObserver | null = null; + private lazyBodies = new WeakMap<HTMLElement, () => void>(); /** Width the list was last laid out at — the key for the overflow * memo above. Captured once per populateListBody (one read), not * per row. */ @@ -3999,24 +4017,71 @@ export class StashpadView extends ItemView { private async getOrComputeRender(file: TFile): Promise<{ mtime: number; text: string; attachments: string[]; html: string; ovW?: number; ovV?: boolean }> { const cached = this.renderCache.get(file.path); - if (cached && cached.mtime === file.stat.mtime) return cached; + if (cached && cached.mtime === file.stat.mtime) { perf.record("render.row.cacheHit", 0); return cached; } // Cache miss / stale entry. Read + parse + render into a detached div - // and stash the result before returning. - const md = await this.app.vault.cachedRead(file); + // and stash the result before returning. 0.81.1: split the body READ + // (network I/O on a share) from the markdown RENDER (CPU) so the + // profile shows which dominates. + const md = await perf.timeAsync("render.row.read", () => this.app.vault.cachedRead(file)); const raw = this.stripFrontmatter(md); const { text, attachments } = this.splitAttachments(raw); const detached = createDiv({ cls: "stashpad-note-text" }); - await MarkdownRenderer.render(this.app, text, detached, file.path, this as any); + await perf.timeAsync("render.row.markdown", () => MarkdownRenderer.render(this.app, text, detached, file.path, this as any)); const html = detached.innerHTML; const entry = { mtime: file.stat.mtime, text, attachments, html }; this.renderCache.set(file.path, entry); return entry; } + /** (Re)create the lazy-body IntersectionObserver for the current paint. + * Root is the view's scroll host; rootMargin pre-renders a screenful + * above/below so scrolling rarely catches a placeholder. */ + private armBodyObserver(): void { + this.bodyObserver?.disconnect(); + this.lazyBodies = new WeakMap(); + this.bodyObserver = new IntersectionObserver((entries) => { + for (const e of entries) { + if (!e.isIntersecting) continue; + const el = e.target as HTMLElement; + const fn = this.lazyBodies.get(el); + this.bodyObserver?.unobserve(el); + this.lazyBodies.delete(el); + if (fn) fn(); + } + }, { root: this.contentEl, rootMargin: "1400px 0px" }); + } + + private hasFreshRenderCache(file: TFile): boolean { + const c = this.renderCache.get(file.path); + return !!c && c.mtime === file.stat.mtime; + } + + /** Public entry: render the body NOW if it's already cached (cheap), or + * show a title placeholder and defer the expensive read+render until the + * row scrolls into view. 0.82.1. */ private renderNoteBody( container: HTMLElement, node: TreeNode, opts: { clamp?: boolean; toggleHost?: HTMLElement; toggleAnchor?: HTMLElement } = { clamp: true }, + ): void { + if (!node.file) return; + // Warm rows (cached HTML) render instantly — no deferral needed. Cold + // rows (the expensive cachedRead misses) get a placeholder + observer. + if (this.hasFreshRenderCache(node.file) || !this.bodyObserver) { + this.renderNoteBodyNow(container, node, opts); + return; + } + container.empty(); + const ph = container.createDiv({ cls: "stashpad-note-text is-plain is-lazy-placeholder" }); + ph.textContent = this.titleForNode(node); + this.lazyBodies.set(container, () => this.renderNoteBodyNow(container, node, opts)); + this.bodyObserver.observe(container); + } + + private renderNoteBodyNow( + container: HTMLElement, + node: TreeNode, + opts: { clamp?: boolean; toggleHost?: HTMLElement; toggleAnchor?: HTMLElement } = { clamp: true }, ): void { if (!node.file) return; const file = node.file; @@ -4554,15 +4619,19 @@ export class StashpadView extends ItemView { this.viewRoot.focus({ preventScroll: true }); return; } - // ↑ at the very start of the textarea → jump out into the list, landing on - // the LAST note (closest to composer) regardless of any prior cursor state. - // Subsequent arrow ups within the list decrement normally. + // ↑ at the very start of the textarea → jump out into the list. + // 0.80.2: land on the LAST-FOCUSED note for this level (the one that + // still has the ring), not always the bottommost — so escaping the + // composer returns you to where you were. Falls back to the last + // note when there's no remembered cursor. if (e.key === "ArrowUp" && ta.selectionStart === 0 && ta.selectionEnd === 0) { e.preventDefault(); ta.blur(); this.viewRoot.focus({ preventScroll: true }); if (this.currentChildren.length > 0) { - this.cursorIdx = this.currentChildren.length - 1; + const lastId = this.lastCursorByFocus.get(this.focusId) ?? this.lastSelected; + const idx = lastId ? this.currentChildren.findIndex((n) => n.id === lastId) : -1; + this.cursorIdx = idx >= 0 ? idx : this.currentChildren.length - 1; this.selectCursor(false); } return; @@ -4887,16 +4956,20 @@ export class StashpadView extends ItemView { // same 100–300ms regression we fixed for normal cursor nav in // 0.73.4. Now we just repaint the .is-pick-target class on // existing rows and scroll the new target into view. + // 0.80.4: skip the notes being moved (the current selection) — you + // can't nest them under themselves, so stepping onto them is wasted + // motion. Both directions skip, so reversing also hops over the + // selected run. if (e.key === "ArrowDown") { e.preventDefault(); - this.inListPicker.activeIdx = Math.min(this.currentChildren.length - 1, this.inListPicker.activeIdx + 1); + this.inListPicker.activeIdx = this.nextPickableIdx(this.inListPicker.activeIdx, 1); this.repaintSelectionClasses(); this.revealRowAt(this.inListPicker.activeIdx); return; } if (e.key === "ArrowUp") { e.preventDefault(); - this.inListPicker.activeIdx = Math.max(0, this.inListPicker.activeIdx - 1); + this.inListPicker.activeIdx = this.nextPickableIdx(this.inListPicker.activeIdx, -1); this.repaintSelectionClasses(); this.revealRowAt(this.inListPicker.activeIdx); return; @@ -5018,6 +5091,11 @@ export class StashpadView extends ItemView { if (matchBinding(e, sb.toggleTask)) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); void this.cmdToggleTask(); return; } if (matchBinding(e, sb.setDue)) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); this.cmdSetDue(); return; } } + // Jump to top/bottom: no selection required — only a non-empty list. + if (this.currentChildren.length > 0) { + if (matchBinding(e, sb.jumpToTop)) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); this.jumpToTop(); return; } + if (matchBinding(e, sb.jumpToBottom)) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); this.jumpToBottom(); return; } + } // Allow E / T from focused-header context too (no selection / cursor required). const focused = this.tree.get(this.focusId); if (focused?.file) { @@ -5031,6 +5109,19 @@ export class StashpadView extends ItemView { } }; + /** 0.80.3: move the cursor to the first / last note in the current list + * and reveal it. Single-select (no shift-range). */ + jumpToTop(): void { + if (this.currentChildren.length === 0) return; + this.cursorIdx = 0; + this.selectCursor(false); + } + jumpToBottom(): void { + if (this.currentChildren.length === 0) return; + this.cursorIdx = this.currentChildren.length - 1; + this.selectCursor(false); + } + private selectCursor(shift: boolean): void { const node = this.currentChildren[this.cursorIdx]; if (!node) return; @@ -5750,11 +5841,28 @@ export class StashpadView extends ItemView { }); } + /** 0.80.4: next index from `from` in `dir` whose note isn't part of the + * current selection (the notes being moved — invalid as their own + * parent). Stays put if there's no unselected note that way. */ + private nextPickableIdx(from: number, dir: 1 | -1): number { + for (let i = from + dir; i >= 0 && i < this.currentChildren.length; i += dir) { + const node = this.currentChildren[i]; + if (node && !this.selection.has(node.id)) return i; + } + return from; + } + private cmdInListPicker(): void { if (this.currentChildren.length === 0) return; // Pre-select the note above the cursor (the most common nest target). // Falls back to index 0 when the cursor is already at the top. - const start = this.cursorIdx > 0 ? this.cursorIdx - 1 : 0; + let start = this.cursorIdx > 0 ? this.cursorIdx - 1 : 0; + // 0.80.4: if that lands on a note being moved, hop to the nearest + // unselected one (look up first, then down). + if (this.currentChildren[start] && this.selection.has(this.currentChildren[start].id)) { + const up = this.nextPickableIdx(start, -1); + start = up !== start ? up : this.nextPickableIdx(start, 1); + } this.inListPicker = { activeIdx: start }; new Notice("Arrows to pick parent, Enter confirms, Esc cancels."); // Preserve scroll position across the activation render — the highlight is @@ -6454,15 +6562,16 @@ export class StashpadView extends ItemView { this.lastSelected = kids[kids.length - 1].id; } } - // 0.56.22: follow-cursor — we just set cursor to `cameFrom` (the - // child we came from). It IS the right thing to scroll to. - this.render({ kind: "follow-cursor" }); + // 0.80.3 / 0.82.4: pin the note we came from to the TOP of the view + // (when it's still present in the parent list). NOTE: the align value + // is passed to scrollIntoView({ block }), which only accepts + // start/center/end/nearest — "top" was invalid and silently did + // nothing (cursor set, but scroll stayed at 0). "start" = top. + if (idx >= 0) this.render({ kind: "scroll-to-id", id: cameFrom, align: "start" }); + else this.render({ kind: "follow-cursor" }); this.refreshHeaderTitle(); - // Always reveal — the cached scroll restore puts us approximately back, - // but the cursor row (often the child we just left) can still hide - // behind the composer when it sits at the bottom of a long list. - // revealCursorRow is a no-op if the row is already comfortably visible. - this.revealCursorRow(); + // Belt-and-suspenders reveal in the fallback case. + if (idx < 0) this.revealCursorRow(); } private openBookmarks(): void { const bookmarks = (this.app as any).internalPlugins?.plugins?.bookmarks?.instance?.items ?? []; @@ -7947,7 +8056,8 @@ export class StashpadView extends ItemView { const fm = this.app.metadataCache.getFileCache(n.file)?.frontmatter; if (Array.isArray(fm?.attachments)) { for (const a of fm.attachments) { - if (typeof a === "string" && a.trim()) attachments.push(a); + // 0.79.18: entries may be wikilinks now — normalize to linktext. + if (typeof a === "string" && a.trim()) attachments.push(attachmentLinkPath(a)); } } } @@ -8462,7 +8572,12 @@ export class StashpadView extends ItemView { fmLines.push("---", body); try { const fullContent = fmLines.join("\n"); - await this.app.vault.create(path, fullContent); + // 0.79.20: exempt our own new note from auto-import. On a slow + // network drive the file's frontmatter may not have flushed when the + // importer's create event fires, so its disk id-check would miss the + // id and "import" the note into Home. Long TTL covers a laggy create. + this.plugin.importService.suppress(path, 60000); + await perf.timeAsync("write.createNote.file", () => this.app.vault.create(path, fullContent)); try { const f = this.app.vault.getAbstractFileByPath(path); if (f && (f as any).extension === "md") { @@ -9056,6 +9171,11 @@ export class StashpadView extends ItemView { this.knownBodies.set(file.path, body); if (prev === undefined) return; // first sighting — no contribution if (prev === body) return; // frontmatter-only write — skip + // 0.79.19: never stamp during rebootstrap — its frontmatter writes and + // the wikilink rewrites from slug-renames must not bump `modified` or + // add contributors. knownBodies is already updated above, so the next + // genuine edit is still detected correctly. + if (this.plugin.rebootstrapInProgress) return; const author = this.currentAuthorLink(); if (!author) return; // user opted out of stamping void this.ensureAuthorFile(author); @@ -9361,7 +9481,8 @@ export class StashpadView extends ItemView { const fm = this.app.metadataCache.getFileCache(n.file)?.frontmatter; if (Array.isArray(fm?.attachments)) { for (const a of fm.attachments) { - if (typeof a === "string" && a.trim()) attachments.push(a); + // 0.79.18: entries may be wikilinks now — normalize to linktext. + if (typeof a === "string" && a.trim()) attachments.push(attachmentLinkPath(a)); } } }